feat: migrate to system cache with changing core logic

This commit is contained in:
2025-04-15 21:41:21 +03:00
parent 5ca34a572a
commit efa4f59403
62 changed files with 4002 additions and 1889 deletions

View File

@ -0,0 +1,176 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package appbuilder
import (
"context"
"errors"
"log/slog"
"github.com/leonelquinteros/gotext"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
)
type AppDeps struct {
Cfg *config.ALRConfig
DB *db.Database
Repos *repos.Repos
Info *distro.OSRelease
Manager manager.Manager
}
func (d *AppDeps) Defer() {
if d.DB != nil {
if err := d.DB.Close(); err != nil {
slog.Warn("failed to close db", "err", err)
}
}
}
type AppBuilder struct {
deps AppDeps
err error
ctx context.Context
}
func New(ctx context.Context) *AppBuilder {
return &AppBuilder{ctx: ctx}
}
func (b *AppBuilder) UseConfig(cfg *config.ALRConfig) *AppBuilder {
if b.err != nil {
return b
}
b.deps.Cfg = cfg
return b
}
func (b *AppBuilder) WithConfig() *AppBuilder {
if b.err != nil {
return b
}
cfg := config.New()
if err := cfg.Load(); err != nil {
b.err = cliutils.FormatCliExit(gotext.Get("Error loading config"), err)
return b
}
b.deps.Cfg = cfg
return b
}
func (b *AppBuilder) WithDB() *AppBuilder {
if b.err != nil {
return b
}
cfg := b.deps.Cfg
if cfg == nil {
b.err = errors.New("config is required before initializing DB")
return b
}
db := db.New(cfg)
if err := db.Init(b.ctx); err != nil {
b.err = cliutils.FormatCliExit(gotext.Get("Error initialization database"), err)
return b
}
b.deps.DB = db
return b
}
func (b *AppBuilder) WithRepos() *AppBuilder {
b.withRepos(true, false)
return b
}
func (b *AppBuilder) WithReposForcePull() *AppBuilder {
b.withRepos(true, true)
return b
}
func (b *AppBuilder) WithReposNoPull() *AppBuilder {
b.withRepos(false, false)
return b
}
func (b *AppBuilder) withRepos(enablePull, forcePull bool) *AppBuilder {
if b.err != nil {
return b
}
cfg := b.deps.Cfg
db := b.deps.DB
if cfg == nil || db == nil {
b.err = errors.New("config and db are required before initializing repos")
return b
}
rs := repos.New(cfg, db)
if enablePull && (forcePull || cfg.AutoPull()) {
if err := rs.Pull(b.ctx, cfg.Repos()); err != nil {
b.err = cliutils.FormatCliExit(gotext.Get("Error pulling repositories"), err)
return b
}
}
b.deps.Repos = rs
return b
}
func (b *AppBuilder) WithDistroInfo() *AppBuilder {
if b.err != nil {
return b
}
b.deps.Info, b.err = distro.ParseOSRelease(b.ctx)
if b.err != nil {
b.err = cliutils.FormatCliExit(gotext.Get("Error parsing os release"), b.err)
}
return b
}
func (b *AppBuilder) WithManager() *AppBuilder {
if b.err != nil {
return b
}
b.deps.Manager = manager.Detect()
if b.deps.Manager == nil {
b.err = cliutils.FormatCliExit(gotext.Get("Unable to detect a supported package manager on the system"), nil)
}
return b
}
func (b *AppBuilder) Build() (*AppDeps, error) {
if b.err != nil {
return nil, b.err
}
return &b.deps, nil
}

View File

@ -0,0 +1,60 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cliutils
import (
"errors"
"fmt"
"log/slog"
"github.com/urfave/cli/v2"
)
type BashCompleteWithErrorFunc func(c *cli.Context) error
func BashCompleteWithError(f BashCompleteWithErrorFunc) cli.BashCompleteFunc {
return func(c *cli.Context) { HandleExitCoder(f(c)) }
}
func HandleExitCoder(err error) {
if err == nil {
return
}
if exitErr, ok := err.(cli.ExitCoder); ok {
if err.Error() != "" {
if _, ok := exitErr.(cli.ErrorFormatter); ok {
slog.Error(fmt.Sprintf("%+v\n", err))
} else {
slog.Error(err.Error())
}
}
cli.OsExiter(exitErr.ExitCode())
return
}
}
func FormatCliExit(msg string, err error) cli.ExitCoder {
return FormatCliExitWithCode(msg, err, 1)
}
func FormatCliExitWithCode(msg string, err error, exitCode int) cli.ExitCoder {
if err == nil {
return cli.Exit(errors.New(msg), exitCode)
}
return cli.Exit(fmt.Errorf("%s: %w", msg, err), exitCode)
}

View File

@ -26,9 +26,9 @@ import (
"reflect"
"github.com/caarlos0/env"
"github.com/leonelquinteros/gotext"
"github.com/pelletier/go-toml/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/constants"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
)
@ -84,34 +84,18 @@ func mergeStructs(dst, src interface{}) {
}
}
const systemConfigPath = "/etc/alr/alr.toml"
func (c *ALRConfig) Load() error {
systemConfig, err := readConfig(
systemConfigPath,
constants.SystemConfigPath,
)
if err != nil {
slog.Debug("Cannot read system config", "err", err)
}
cfgDir, err := os.UserConfigDir()
if err != nil {
slog.Debug("Cannot read user config directory")
}
userConfigPath := filepath.Join(cfgDir, "alr", "alr.toml")
userConfig, err := readConfig(
userConfigPath,
)
if err != nil {
slog.Debug("Cannot read user config")
}
config := &types.Config{}
mergeStructs(config, defaultConfig)
mergeStructs(config, systemConfig)
mergeStructs(config, userConfig)
err = env.Parse(config)
if err != nil {
return err
@ -119,17 +103,13 @@ func (c *ALRConfig) Load() error {
c.cfg = config
cacheDir, err := os.UserCacheDir()
if err != nil {
return err
}
c.paths = &Paths{}
c.paths.UserConfigPath = userConfigPath
c.paths.CacheDir = filepath.Join(cacheDir, "alr")
c.paths.UserConfigPath = constants.SystemConfigPath
c.paths.CacheDir = constants.SystemCachePath
c.paths.RepoDir = filepath.Join(c.paths.CacheDir, "repo")
c.paths.PkgsDir = filepath.Join(c.paths.CacheDir, "pkgs")
c.paths.DBPath = filepath.Join(c.paths.CacheDir, "db")
c.initPaths()
// c.initPaths()
return nil
}
@ -146,10 +126,6 @@ func (c *ALRConfig) AutoPull() bool {
return c.cfg.AutoPull
}
func (c *ALRConfig) AllowRunAsRoot() bool {
return c.cfg.Unsafe.AllowRunAsRoot
}
func (c *ALRConfig) Repos() []types.Repo {
return c.cfg.Repos
}
@ -170,26 +146,6 @@ func (c *ALRConfig) GetPaths() *Paths {
return c.paths
}
func (c *ALRConfig) initPaths() {
err := os.MkdirAll(filepath.Dir(c.paths.UserConfigPath), 0o755)
if err != nil {
slog.Error(gotext.Get("Unable to create config directory"), "err", err)
os.Exit(1)
}
err = os.MkdirAll(c.paths.RepoDir, 0o755)
if err != nil {
slog.Error(gotext.Get("Unable to create repo cache directory"), "err", err)
os.Exit(1)
}
err = os.MkdirAll(c.paths.PkgsDir, 0o755)
if err != nil {
slog.Error(gotext.Get("Unable to create package cache directory"), "err", err)
os.Exit(1)
}
}
func (c *ALRConfig) SaveUserConfig() error {
f, err := os.Create(c.paths.UserConfigPath)
if err != nil {

View File

@ -0,0 +1,24 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package constants
const (
SystemConfigPath = "/etc/alr/alr.toml"
SystemCachePath = "/var/cache/alr"
AlrRunDir = "/var/run/alr"
PrivilegedGroup = "wheel"
)

152
internal/logger/hclog.go Normal file
View File

@ -0,0 +1,152 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package logger
import (
"io"
"log"
"strings"
chLog "github.com/charmbracelet/log"
"github.com/hashicorp/go-hclog"
)
type HCLoggerAdapter struct {
logger *Logger
}
func hclogLevelTochLog(level hclog.Level) chLog.Level {
switch level {
case hclog.Debug:
return chLog.DebugLevel
case hclog.Info:
return chLog.InfoLevel
case hclog.Warn:
return chLog.WarnLevel
case hclog.Error:
return chLog.ErrorLevel
}
return chLog.FatalLevel
}
func (a *HCLoggerAdapter) Log(level hclog.Level, msg string, args ...interface{}) {
filteredArgs := make([]interface{}, 0, len(args))
for i := 0; i < len(args); i += 2 {
if i+1 >= len(args) {
filteredArgs = append(filteredArgs, args[i])
continue
}
key, ok := args[i].(string)
if !ok || key != "timestamp" {
filteredArgs = append(filteredArgs, args[i], args[i+1])
}
}
// Start ugly hacks
// Ignore exit messages
// - https://github.com/hashicorp/go-plugin/issues/331
// - https://github.com/hashicorp/go-plugin/issues/203
// - https://github.com/hashicorp/go-plugin/issues/192
var chLogLevel chLog.Level
if msg == "plugin process exited" ||
strings.HasPrefix(msg, "[ERR] plugin: stream copy 'stderr' error") ||
strings.HasPrefix(msg, "[DEBUG] plugin") {
chLogLevel = chLog.DebugLevel
} else {
chLogLevel = hclogLevelTochLog(level)
}
a.logger.l.Log(chLogLevel, msg, filteredArgs...)
}
func (a *HCLoggerAdapter) Trace(msg string, args ...interface{}) {
a.Log(hclog.Trace, msg, args...)
}
func (a *HCLoggerAdapter) Debug(msg string, args ...interface{}) {
a.Log(hclog.Debug, msg, args...)
}
func (a *HCLoggerAdapter) Info(msg string, args ...interface{}) {
a.Log(hclog.Info, msg, args...)
}
func (a *HCLoggerAdapter) Warn(msg string, args ...interface{}) {
a.Log(hclog.Warn, msg, args...)
}
func (a *HCLoggerAdapter) Error(msg string, args ...interface{}) {
a.Log(hclog.Error, msg, args...)
}
func (a *HCLoggerAdapter) IsTrace() bool {
return a.logger.l.GetLevel() <= chLog.DebugLevel
}
func (a *HCLoggerAdapter) IsDebug() bool {
return a.logger.l.GetLevel() <= chLog.DebugLevel
}
func (a *HCLoggerAdapter) IsInfo() bool {
return a.logger.l.GetLevel() <= chLog.InfoLevel
}
func (a *HCLoggerAdapter) IsWarn() bool {
return a.logger.l.GetLevel() <= chLog.WarnLevel
}
func (a *HCLoggerAdapter) IsError() bool {
return a.logger.l.GetLevel() <= chLog.ErrorLevel
}
func (a *HCLoggerAdapter) ImpliedArgs() []interface{} {
return nil
}
func (a *HCLoggerAdapter) With(args ...interface{}) hclog.Logger {
return a
}
func (a *HCLoggerAdapter) Name() string {
return ""
}
func (a *HCLoggerAdapter) Named(name string) hclog.Logger {
return a
}
func (a *HCLoggerAdapter) ResetNamed(name string) hclog.Logger {
return a
}
func (a *HCLoggerAdapter) SetLevel(level hclog.Level) {
}
func (a *HCLoggerAdapter) StandardLogger(opts *hclog.StandardLoggerOptions) *log.Logger {
return nil
}
func (a *HCLoggerAdapter) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writer {
return nil
}
func GetHCLoggerAdapter() *HCLoggerAdapter {
return &HCLoggerAdapter{
logger: logger,
}
}

View File

@ -22,96 +22,90 @@ import (
"os"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
chLog "github.com/charmbracelet/log"
"github.com/leonelquinteros/gotext"
)
type Logger struct {
lOut slog.Handler
lErr slog.Handler
l *chLog.Logger
}
func setupOutLogger() *log.Logger {
styles := log.DefaultStyles()
logger := log.New(os.Stdout)
styles.Levels[log.InfoLevel] = lipgloss.NewStyle().
func setupLogger() *chLog.Logger {
styles := chLog.DefaultStyles()
logger := chLog.New(os.Stderr)
styles.Levels[chLog.InfoLevel] = lipgloss.NewStyle().
SetString("-->").
Foreground(lipgloss.Color("35"))
logger.SetStyles(styles)
return logger
}
func setupErrorLogger() *log.Logger {
styles := log.DefaultStyles()
styles.Levels[log.ErrorLevel] = lipgloss.NewStyle().
styles.Levels[chLog.ErrorLevel] = lipgloss.NewStyle().
SetString(gotext.Get("ERROR")).
Padding(0, 1, 0, 1).
Background(lipgloss.Color("204")).
Foreground(lipgloss.Color("0"))
logger := log.New(os.Stderr)
logger.SetStyles(styles)
return logger
}
func New() *Logger {
standardLogger := setupOutLogger()
errLogger := setupErrorLogger()
return &Logger{
lOut: standardLogger,
lErr: errLogger,
l: setupLogger(),
}
}
func slogLevelToLog(level slog.Level) log.Level {
func slogLevelToLog(level slog.Level) chLog.Level {
switch level {
case slog.LevelDebug:
return log.DebugLevel
return chLog.DebugLevel
case slog.LevelInfo:
return log.InfoLevel
return chLog.InfoLevel
case slog.LevelWarn:
return log.WarnLevel
return chLog.WarnLevel
case slog.LevelError:
return log.ErrorLevel
return chLog.ErrorLevel
}
return log.FatalLevel
return chLog.FatalLevel
}
func (l *Logger) SetLevel(level slog.Level) {
l.lOut.(*log.Logger).SetLevel(slogLevelToLog(level))
l.lErr.(*log.Logger).SetLevel(slogLevelToLog(level))
l.l.SetLevel(slogLevelToLog(level))
}
func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool {
if level <= slog.LevelInfo {
return l.lOut.Enabled(ctx, level)
}
return l.lErr.Enabled(ctx, level)
return l.l.Enabled(ctx, level)
}
func (l *Logger) Handle(ctx context.Context, rec slog.Record) error {
if rec.Level <= slog.LevelInfo {
return l.lOut.Handle(ctx, rec)
}
return l.lErr.Handle(ctx, rec)
return l.l.Handle(ctx, rec)
}
func (l *Logger) WithAttrs(attrs []slog.Attr) slog.Handler {
sl := *l
sl.lOut = l.lOut.WithAttrs(attrs)
sl.lErr = l.lErr.WithAttrs(attrs)
sl.l = l.l.WithAttrs(attrs).(*chLog.Logger)
return &sl
}
func (l *Logger) WithGroup(name string) slog.Handler {
sl := *l
sl.lOut = l.lOut.WithGroup(name)
sl.lErr = l.lErr.WithGroup(name)
sl.l = l.l.WithGroup(name).(*chLog.Logger)
return &sl
}
var logger *Logger
func SetupDefault() *Logger {
l := New()
logger := slog.New(l)
slog.SetDefault(logger)
return l
logger = New()
slogLogger := slog.New(logger)
slog.SetDefault(slogLogger)
return logger
}
func SetupForGoPlugin() {
logger.l.SetFormatter(chLog.JSONFormatter)
chLog.TimestampKey = "@timestamp"
chLog.MessageKey = "@message"
chLog.LevelKey = "@level"
}
func GetLogger() *Logger {
return logger
}

View File

@ -25,11 +25,11 @@ import (
"os"
"os/exec"
"runtime"
"slices"
"strings"
"syscall"
"time"
"gitea.plemya-x.ru/Plemya-x/fakeroot"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
)
@ -54,7 +54,7 @@ func FakerootExecHandler(killTimeout time.Duration) interp.ExecHandlerFunc {
Stderr: hc.Stderr,
}
err = fakeroot.Apply(cmd)
err = Apply(cmd)
if err != nil {
return err
}
@ -108,6 +108,52 @@ func FakerootExecHandler(killTimeout time.Duration) interp.ExecHandlerFunc {
}
}
func rootMap(m syscall.SysProcIDMap) bool {
return m.ContainerID == 0
}
func Apply(cmd *exec.Cmd) error {
uid := os.Getuid()
gid := os.Getgid()
// If the user is already root, there's no need for fakeroot
if uid == 0 {
return nil
}
// Ensure SysProcAttr isn't nil
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
// Create a new user namespace
cmd.SysProcAttr.Cloneflags |= syscall.CLONE_NEWUSER
// If the command already contains a mapping for the root user, return an error
if slices.ContainsFunc(cmd.SysProcAttr.UidMappings, rootMap) {
return nil
}
// If the command already contains a mapping for the root group, return an error
if slices.ContainsFunc(cmd.SysProcAttr.GidMappings, rootMap) {
return nil
}
cmd.SysProcAttr.UidMappings = append(cmd.SysProcAttr.UidMappings, syscall.SysProcIDMap{
ContainerID: 0,
HostID: uid,
Size: 1,
})
cmd.SysProcAttr.GidMappings = append(cmd.SysProcAttr.GidMappings, syscall.SysProcIDMap{
ContainerID: 0,
HostID: gid,
Size: 1,
})
return nil
}
// execEnv was extracted from github.com/mvdan/sh/interp/vars.go
func execEnv(env expand.Environ) []string {
list := make([]string, 0, 64)

View File

@ -9,91 +9,83 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: build.go:44
#: build.go:42
msgid "Build a local package"
msgstr ""
#: build.go:50
#: build.go:48
msgid "Path to the build script"
msgstr ""
#: build.go:55
#: build.go:53
msgid "Specify subpackage in script (for multi package script only)"
msgstr ""
#: build.go:60
#: build.go:58
msgid "Name of the package to build and its repo (example: default/go-bin)"
msgstr ""
#: build.go:65
#: build.go:63
msgid ""
"Build package from scratch even if there's an already built package available"
msgstr ""
#: build.go:73
msgid "Error loading config"
msgstr ""
#: build.go:81
msgid "Error initialization database"
msgstr ""
#: build.go:110
msgid "Package not found"
msgstr ""
#: build.go:130
msgid "Error pulling repositories"
msgstr ""
#: build.go:138
msgid "Unable to detect a supported package manager on the system"
msgstr ""
#: build.go:144
msgid "Error parsing os release"
msgstr ""
#: build.go:166
msgid "Error building package"
msgstr ""
#: build.go:173
msgid "Error getting working directory"
msgstr ""
#: build.go:182
#: build.go:118
msgid "Cannot get absolute script path"
msgstr ""
#: build.go:148
msgid "Package not found"
msgstr ""
#: build.go:161
msgid "Nothing to build"
msgstr ""
#: build.go:218
msgid "Error building package"
msgstr ""
#: build.go:225
msgid "Error moving the package"
msgstr ""
#: fix.go:37
#: build.go:229
msgid "Done"
msgstr ""
#: fix.go:38
msgid "Attempt to fix problems with ALR"
msgstr ""
#: fix.go:49
msgid "Removing cache directory"
#: fix.go:59
msgid "Clearing cache directory"
msgstr ""
#: fix.go:53
msgid "Unable to remove cache directory"
#: fix.go:64
msgid "Unable to open cache directory"
msgstr ""
#: fix.go:57
#: fix.go:70
msgid "Unable to read cache directory contents"
msgstr ""
#: fix.go:76
msgid "Unable to remove cache item (%s)"
msgstr ""
#: fix.go:80
msgid "Rebuilding cache"
msgstr ""
#: fix.go:61
#: fix.go:84
msgid "Unable to create new cache directory"
msgstr ""
#: fix.go:81
msgid "Error pulling repos"
msgstr ""
#: fix.go:85
msgid "Done"
msgstr ""
#: gen.go:34
msgid "Generate a ALR script from a template"
msgstr ""
@ -102,82 +94,106 @@ msgstr ""
msgid "Generate a ALR script for a pip module"
msgstr ""
#: helper.go:41
#: helper.go:42
msgid "List all the available helper commands"
msgstr ""
#: helper.go:53
#: helper.go:54
msgid "Run a ALR helper command"
msgstr ""
#: helper.go:60
#: helper.go:61
msgid "The directory that the install commands will install to"
msgstr ""
#: helper.go:73
#: helper.go:74 helper.go:75
msgid "No such helper command"
msgstr ""
#: info.go:43
msgid "Print information about a package"
msgstr ""
#: info.go:48
msgid "Show all information, not just for the current distro"
msgstr ""
#: info.go:69
msgid "Error getting packages"
msgstr ""
#: info.go:78
msgid "Error iterating over packages"
msgstr ""
#: info.go:105
msgid "Command info expected at least 1 argument, got %d"
msgstr ""
#: info.go:119
msgid "Error finding packages"
msgstr ""
#: info.go:144
#: helper.go:85
msgid "Error parsing os-release file"
msgstr ""
#: info.go:153
#: info.go:42
msgid "Print information about a package"
msgstr ""
#: info.go:47
msgid "Show all information, not just for the current distro"
msgstr ""
#: info.go:68
msgid "Error getting packages"
msgstr ""
#: info.go:76
msgid "Error iterating over packages"
msgstr ""
#: info.go:90
msgid "Command info expected at least 1 argument, got %d"
msgstr ""
#: info.go:110
msgid "Error finding packages"
msgstr ""
#: info.go:124
msgid "Can't detect system language"
msgstr ""
#: info.go:141
msgid "Error resolving overrides"
msgstr ""
#: info.go:162 info.go:168
#: info.go:149 info.go:154
msgid "Error encoding script variables"
msgstr ""
#: install.go:43
#: install.go:40
msgid "Install a new package"
msgstr ""
#: install.go:57
#: install.go:56
msgid "Command install expected at least 1 argument, got %d"
msgstr ""
#: install.go:118
msgid "Error parsing os release"
msgstr ""
#: install.go:163
msgid "Remove an installed package"
msgstr ""
#: install.go:188
#: install.go:182
msgid "Error listing installed packages"
msgstr ""
#: install.go:226
#: install.go:223
msgid "Command remove expected at least 1 argument, got %d"
msgstr ""
#: install.go:241
#: install.go:238
msgid "Error removing packages"
msgstr ""
#: internal/cliutils/app_builder/builder.go:75
msgid "Error loading config"
msgstr ""
#: internal/cliutils/app_builder/builder.go:96
msgid "Error initialization database"
msgstr ""
#: internal/cliutils/app_builder/builder.go:135
msgid "Error pulling repositories"
msgstr ""
#: internal/cliutils/app_builder/builder.go:165
msgid "Unable to detect a supported package manager on the system"
msgstr ""
#: internal/cliutils/prompt.go:60
msgid "Would you like to view the build script for %s"
msgstr ""
@ -258,18 +274,6 @@ msgstr ""
msgid "OPTIONS"
msgstr ""
#: internal/config/config.go:176
msgid "Unable to create config directory"
msgstr ""
#: internal/config/config.go:182
msgid "Unable to create repo cache directory"
msgstr ""
#: internal/config/config.go:188
msgid "Unable to create package cache directory"
msgstr ""
#: internal/db/db.go:133
msgid "Database version mismatch; resetting"
msgstr ""
@ -303,10 +307,22 @@ msgstr ""
msgid "%s %s downloading at %s/s\n"
msgstr ""
#: internal/logger/log.go:47
#: internal/logger/log.go:41
msgid "ERROR"
msgstr ""
#: internal/utils/cmd.go:95
msgid "Error dropping capabilities"
msgstr ""
#: internal/utils/cmd.go:123
msgid "You need to be root to perform this action"
msgstr ""
#: internal/utils/cmd.go:165
msgid "You need to be a %s member to perform this action"
msgstr ""
#: list.go:41
msgid "List ALR repo packages"
msgstr ""
@ -323,86 +339,40 @@ msgstr ""
msgid "Enable interactive questions and prompts"
msgstr ""
#: main.go:96
msgid ""
"Running ALR as root is forbidden as it may cause catastrophic damage to your "
"system"
msgstr ""
#: main.go:154
#: main.go:145
msgid "Show help"
msgstr ""
#: main.go:158
#: main.go:149
msgid "Error while running app"
msgstr ""
#: pkg/build/build.go:157
msgid "Failed to prompt user to view build script"
msgstr ""
#: pkg/build/build.go:161
#: pkg/build/build.go:394
msgid "Building package"
msgstr ""
#: pkg/build/build.go:209
#: pkg/build/build.go:423
msgid "The checksums array must be the same length as sources"
msgstr ""
#: pkg/build/build.go:238
#: pkg/build/build.go:454
msgid "Downloading sources"
msgstr ""
#: pkg/build/build.go:260
msgid "Building package metadata"
#: pkg/build/build.go:543
msgid "Installing dependencies"
msgstr ""
#: pkg/build/build.go:282
msgid "Compressing package"
msgstr ""
#: pkg/build/build.go:441
#: pkg/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
#: pkg/build/build.go:455
#: pkg/build/checker.go:67
msgid "This package is already installed"
msgstr ""
#: pkg/build/build.go:479
msgid "Installing build dependencies"
msgstr ""
#: pkg/build/build.go:524
msgid "Installing dependencies"
msgstr ""
#: pkg/build/build.go:605
msgid "Would you like to remove the build dependencies?"
msgstr ""
#: pkg/build/build.go:668
msgid "Executing prepare()"
msgstr ""
#: pkg/build/build.go:678
msgid "Executing build()"
msgstr ""
#: pkg/build/build.go:708 pkg/build/build.go:728
msgid "Executing %s()"
msgstr ""
#: pkg/build/build.go:787
msgid "Error installing native packages"
msgstr ""
#: pkg/build/build.go:811
msgid "Error installing package"
msgstr ""
#: pkg/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr ""
@ -423,6 +393,22 @@ msgstr ""
msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
#: pkg/build/script_executor.go:237
msgid "Building package metadata"
msgstr ""
#: pkg/build/script_executor.go:356
msgid "Executing prepare()"
msgstr ""
#: pkg/build/script_executor.go:365
msgid "Executing build()"
msgstr ""
#: pkg/build/script_executor.go:394 pkg/build/script_executor.go:414
msgid "Executing %s()"
msgstr ""
#: pkg/repos/pull.go:79
msgid "Pulling repository"
msgstr ""
@ -441,43 +427,47 @@ msgid ""
"updating ALR if something doesn't work."
msgstr ""
#: repo.go:40
#: repo.go:39
msgid "Add a new repository"
msgstr ""
#: repo.go:47
#: repo.go:46
msgid "Name of the new repo"
msgstr ""
#: repo.go:53
#: repo.go:52
msgid "URL of the new repo"
msgstr ""
#: repo.go:86 repo.go:156
#: repo.go:79
msgid "Repo %s already exists"
msgstr ""
#: repo.go:90 repo.go:167
msgid "Error saving config"
msgstr ""
#: repo.go:111
#: repo.go:116
msgid "Remove an existing repository"
msgstr ""
#: repo.go:118
#: repo.go:123
msgid "Name of the repo to be deleted"
msgstr ""
#: repo.go:142
msgid "Repo does not exist"
#: repo.go:156
msgid "Repo \"%s\" does not exist"
msgstr ""
#: repo.go:150
#: repo.go:163
msgid "Error removing repo directory"
msgstr ""
#: repo.go:167
#: repo.go:186
msgid "Error removing packages from database"
msgstr ""
#: repo.go:179
#: repo.go:197
msgid "Pull all repositories that have changed"
msgstr ""
@ -505,11 +495,15 @@ msgstr ""
msgid "Format output using a Go template"
msgstr ""
#: search.go:88 search.go:105
#: search.go:96
msgid "Error while executing search"
msgstr ""
#: search.go:104
msgid "Error parsing format template"
msgstr ""
#: search.go:113
#: search.go:112
msgid "Error executing template"
msgstr ""
@ -517,10 +511,10 @@ msgstr ""
msgid "Upgrade all installed packages"
msgstr ""
#: upgrade.go:96
#: upgrade.go:109 upgrade.go:126
msgid "Error checking for updates"
msgstr ""
#: upgrade.go:118
#: upgrade.go:129
msgid "There is nothing to do."
msgstr ""

View File

@ -16,92 +16,88 @@ msgstr ""
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Generator: Gtranslator 47.1\n"
#: build.go:44
#: build.go:42
msgid "Build a local package"
msgstr "Сборка локального пакета"
#: build.go:50
#: build.go:48
msgid "Path to the build script"
msgstr "Путь к скрипту сборки"
#: build.go:55
#: build.go:53
msgid "Specify subpackage in script (for multi package script only)"
msgstr "Укажите подпакет в скрипте (только для многопакетного скрипта)"
#: build.go:60
#: build.go:58
msgid "Name of the package to build and its repo (example: default/go-bin)"
msgstr "Имя пакета для сборки и его репозиторий (пример: default/go-bin)"
#: build.go:65
#: build.go:63
msgid ""
"Build package from scratch even if there's an already built package available"
msgstr "Создайте пакет с нуля, даже если уже имеется готовый пакет"
#: build.go:73
#, fuzzy
msgid "Error loading config"
msgstr "Ошибка при кодировании конфигурации"
#: build.go:81
msgid "Error initialization database"
msgstr "Ошибка инициализации базы данных"
#: build.go:110
msgid "Package not found"
msgstr "Пакет не найден"
#: build.go:130
msgid "Error pulling repositories"
msgstr "Ошибка при извлечении репозиториев"
#: build.go:138
msgid "Unable to detect a supported package manager on the system"
msgstr "Не удалось обнаружить поддерживаемый менеджер пакетов в системе"
#: build.go:144
msgid "Error parsing os release"
msgstr "Ошибка при разборе файла выпуска операционной системы"
#: build.go:166
msgid "Error building package"
msgstr "Ошибка при сборке пакета"
#: build.go:173
msgid "Error getting working directory"
msgstr "Ошибка при получении рабочего каталога"
#: build.go:182
#: build.go:118
msgid "Cannot get absolute script path"
msgstr ""
#: build.go:148
msgid "Package not found"
msgstr "Пакет не найден"
#: build.go:161
#, fuzzy
msgid "Nothing to build"
msgstr "Исполнение build()"
#: build.go:218
msgid "Error building package"
msgstr "Ошибка при сборке пакета"
#: build.go:225
msgid "Error moving the package"
msgstr "Ошибка при перемещении пакета"
#: fix.go:37
#: build.go:229
msgid "Done"
msgstr "Сделано"
#: fix.go:38
msgid "Attempt to fix problems with ALR"
msgstr "Попытка устранить проблемы с ALR"
#: fix.go:49
msgid "Removing cache directory"
#: fix.go:59
#, fuzzy
msgid "Clearing cache directory"
msgstr "Удаление каталога кэша"
#: fix.go:53
msgid "Unable to remove cache directory"
#: fix.go:64
#, fuzzy
msgid "Unable to open cache directory"
msgstr "Не удалось удалить каталог кэша"
#: fix.go:57
#: fix.go:70
#, fuzzy
msgid "Unable to read cache directory contents"
msgstr "Не удалось удалить каталог кэша"
#: fix.go:76
#, fuzzy
msgid "Unable to remove cache item (%s)"
msgstr "Не удалось удалить каталог кэша"
#: fix.go:80
msgid "Rebuilding cache"
msgstr "Восстановление кэша"
#: fix.go:61
#: fix.go:84
msgid "Unable to create new cache directory"
msgstr "Не удалось создать новый каталог кэша"
#: fix.go:81
msgid "Error pulling repos"
msgstr "Ошибка при извлечении репозиториев"
#: fix.go:85
msgid "Done"
msgstr "Сделано"
#: gen.go:34
msgid "Generate a ALR script from a template"
msgstr "Генерация скрипта ALR из шаблона"
@ -110,82 +106,108 @@ msgstr "Генерация скрипта ALR из шаблона"
msgid "Generate a ALR script for a pip module"
msgstr "Генерация скрипта ALR для модуля pip"
#: helper.go:41
#: helper.go:42
msgid "List all the available helper commands"
msgstr "Список всех доступных вспомогательных команды"
#: helper.go:53
#: helper.go:54
msgid "Run a ALR helper command"
msgstr "Запустить вспомогательную команду ALR"
#: helper.go:60
#: helper.go:61
msgid "The directory that the install commands will install to"
msgstr "Каталог, в который будут устанавливать команды установки"
#: helper.go:73
#: helper.go:74 helper.go:75
msgid "No such helper command"
msgstr "Такой вспомогательной команды нет"
#: info.go:43
msgid "Print information about a package"
msgstr "Отобразить информацию о пакете"
#: info.go:48
msgid "Show all information, not just for the current distro"
msgstr "Показывать всю информацию, не только для текущего дистрибутива"
#: info.go:69
msgid "Error getting packages"
msgstr "Ошибка при получении пакетов"
#: info.go:78
msgid "Error iterating over packages"
msgstr "Ошибка при переборе пакетов"
#: info.go:105
msgid "Command info expected at least 1 argument, got %d"
msgstr "Для команды info ожидался хотя бы 1 аргумент, получено %d"
#: info.go:119
msgid "Error finding packages"
msgstr "Ошибка при поиске пакетов"
#: info.go:144
#: helper.go:85
msgid "Error parsing os-release file"
msgstr "Ошибка при разборе файла выпуска операционной системы"
#: info.go:153
#: info.go:42
msgid "Print information about a package"
msgstr "Отобразить информацию о пакете"
#: info.go:47
msgid "Show all information, not just for the current distro"
msgstr "Показывать всю информацию, не только для текущего дистрибутива"
#: info.go:68
msgid "Error getting packages"
msgstr "Ошибка при получении пакетов"
#: info.go:76
msgid "Error iterating over packages"
msgstr "Ошибка при переборе пакетов"
#: info.go:90
msgid "Command info expected at least 1 argument, got %d"
msgstr "Для команды info ожидался хотя бы 1 аргумент, получено %d"
#: info.go:110
msgid "Error finding packages"
msgstr "Ошибка при поиске пакетов"
#: info.go:124
#, fuzzy
msgid "Can't detect system language"
msgstr "Ошибка при парсинге языка системы"
#: info.go:141
msgid "Error resolving overrides"
msgstr "Ошибка устранения переорпеделений"
#: info.go:162 info.go:168
#: info.go:149 info.go:154
msgid "Error encoding script variables"
msgstr "Ошибка кодирования переменных скрита"
#: install.go:43
#: install.go:40
msgid "Install a new package"
msgstr "Установить новый пакет"
#: install.go:57
#: install.go:56
msgid "Command install expected at least 1 argument, got %d"
msgstr "Для команды install ожидался хотя бы 1 аргумент, получено %d"
#: install.go:118
msgid "Error parsing os release"
msgstr "Ошибка при разборе файла выпуска операционной системы"
#: install.go:163
msgid "Remove an installed package"
msgstr "Удалить установленный пакет"
#: install.go:188
#: install.go:182
msgid "Error listing installed packages"
msgstr "Ошибка при составлении списка установленных пакетов"
#: install.go:226
#: install.go:223
msgid "Command remove expected at least 1 argument, got %d"
msgstr "Для команды remove ожидался хотя бы 1 аргумент, получено %d"
#: install.go:241
#: install.go:238
msgid "Error removing packages"
msgstr "Ошибка при удалении пакетов"
#: internal/cliutils/app_builder/builder.go:75
#, fuzzy
msgid "Error loading config"
msgstr "Ошибка при кодировании конфигурации"
#: internal/cliutils/app_builder/builder.go:96
msgid "Error initialization database"
msgstr "Ошибка инициализации базы данных"
#: internal/cliutils/app_builder/builder.go:135
msgid "Error pulling repositories"
msgstr "Ошибка при извлечении репозиториев"
#: internal/cliutils/app_builder/builder.go:165
msgid "Unable to detect a supported package manager on the system"
msgstr "Не удалось обнаружить поддерживаемый менеджер пакетов в системе"
#: internal/cliutils/prompt.go:60
msgid "Would you like to view the build script for %s"
msgstr "Показать скрипт для пакета %s"
@ -266,19 +288,6 @@ msgstr "КАТЕГОРИЯ"
msgid "OPTIONS"
msgstr "ПАРАМЕТРЫ"
#: internal/config/config.go:176
#, fuzzy
msgid "Unable to create config directory"
msgstr "Не удалось создать каталог конфигурации ALR"
#: internal/config/config.go:182
msgid "Unable to create repo cache directory"
msgstr "Не удалось создать каталог кэша репозитория"
#: internal/config/config.go:188
msgid "Unable to create package cache directory"
msgstr "Не удалось создать каталог кэша пакетов"
#: internal/db/db.go:133
msgid "Database version mismatch; resetting"
msgstr "Несоответствие версий базы данных; сброс настроек"
@ -313,10 +322,23 @@ msgstr "%s: выполнено!\n"
msgid "%s %s downloading at %s/s\n"
msgstr "%s %s загружается — %s/с\n"
#: internal/logger/log.go:47
#: internal/logger/log.go:41
msgid "ERROR"
msgstr "ОШИБКА"
#: internal/utils/cmd.go:95
#, fuzzy
msgid "Error dropping capabilities"
msgstr "Ошибка при открытии базы данных"
#: internal/utils/cmd.go:123
msgid "You need to be root to perform this action"
msgstr ""
#: internal/utils/cmd.go:165
msgid "You need to be a %s member to perform this action"
msgstr ""
#: list.go:41
msgid "List ALR repo packages"
msgstr "Список пакетов репозитория ALR"
@ -333,47 +355,31 @@ msgstr "Аргументы, которые будут переданы мене
msgid "Enable interactive questions and prompts"
msgstr "Включение интерактивных вопросов и запросов"
#: main.go:96
msgid ""
"Running ALR as root is forbidden as it may cause catastrophic damage to your "
"system"
msgstr ""
"Запуск ALR от имени root запрещён, так как это может привести к "
"катастрофическому повреждению вашей системы"
#: main.go:154
#: main.go:145
msgid "Show help"
msgstr "Показать справку"
#: main.go:158
#: main.go:149
msgid "Error while running app"
msgstr "Ошибка при запуске приложения"
#: pkg/build/build.go:157
msgid "Failed to prompt user to view build script"
msgstr "Не удалось предложить пользователю просмотреть скрипт сборки"
#: pkg/build/build.go:161
#: pkg/build/build.go:394
msgid "Building package"
msgstr "Сборка пакета"
#: pkg/build/build.go:209
#: pkg/build/build.go:423
msgid "The checksums array must be the same length as sources"
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
#: pkg/build/build.go:238
#: pkg/build/build.go:454
msgid "Downloading sources"
msgstr "Скачивание источников"
#: pkg/build/build.go:260
msgid "Building package metadata"
msgstr "Сборка метаданных пакета"
#: pkg/build/build.go:543
msgid "Installing dependencies"
msgstr "Установка зависимостей"
#: pkg/build/build.go:282
msgid "Compressing package"
msgstr "Сжатие пакета"
#: pkg/build/build.go:441
#: pkg/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
@ -381,42 +387,10 @@ msgstr ""
"Архитектура процессора вашей системы не соответствует этому пакету. Вы все "
"равно хотите выполнить сборку?"
#: pkg/build/build.go:455
#: pkg/build/checker.go:67
msgid "This package is already installed"
msgstr "Этот пакет уже установлен"
#: pkg/build/build.go:479
msgid "Installing build dependencies"
msgstr "Установка зависимостей сборки"
#: pkg/build/build.go:524
msgid "Installing dependencies"
msgstr "Установка зависимостей"
#: pkg/build/build.go:605
msgid "Would you like to remove the build dependencies?"
msgstr "Хотели бы вы удалить зависимости сборки?"
#: pkg/build/build.go:668
msgid "Executing prepare()"
msgstr "Исполнение prepare()"
#: pkg/build/build.go:678
msgid "Executing build()"
msgstr "Исполнение build()"
#: pkg/build/build.go:708 pkg/build/build.go:728
msgid "Executing %s()"
msgstr "Исполнение %s()"
#: pkg/build/build.go:787
msgid "Error installing native packages"
msgstr "Ошибка при установке нативных пакетов"
#: pkg/build/build.go:811
msgid "Error installing package"
msgstr "Ошибка при установке пакета"
#: pkg/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr "Команда не найдена в системе"
@ -439,6 +413,22 @@ msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
"AutoReq не реализовано для этого формата пакета, поэтому будет пропущено"
#: pkg/build/script_executor.go:237
msgid "Building package metadata"
msgstr "Сборка метаданных пакета"
#: pkg/build/script_executor.go:356
msgid "Executing prepare()"
msgstr "Исполнение prepare()"
#: pkg/build/script_executor.go:365
msgid "Executing build()"
msgstr "Исполнение build()"
#: pkg/build/script_executor.go:394 pkg/build/script_executor.go:414
msgid "Executing %s()"
msgstr "Исполнение %s()"
#: pkg/repos/pull.go:79
msgid "Pulling repository"
msgstr "Скачивание репозитория"
@ -459,44 +449,50 @@ msgstr ""
"Минимальная версия ALR для ALR-репозитория выше текущей версии. Попробуйте "
"обновить ALR, если что-то не работает."
#: repo.go:40
#: repo.go:39
msgid "Add a new repository"
msgstr "Добавить новый репозиторий"
#: repo.go:47
#: repo.go:46
msgid "Name of the new repo"
msgstr "Название нового репозитория"
#: repo.go:53
#: repo.go:52
msgid "URL of the new repo"
msgstr "URL-адрес нового репозитория"
#: repo.go:86 repo.go:156
#: repo.go:79
#, fuzzy
msgid "Repo %s already exists"
msgstr "Репозитория не существует"
#: repo.go:90 repo.go:167
#, fuzzy
msgid "Error saving config"
msgstr "Ошибка при кодировании конфигурации"
#: repo.go:111
#: repo.go:116
msgid "Remove an existing repository"
msgstr "Удалить существующий репозиторий"
#: repo.go:118
#: repo.go:123
msgid "Name of the repo to be deleted"
msgstr "Название репозитория удалён"
#: repo.go:142
msgid "Repo does not exist"
#: repo.go:156
#, fuzzy
msgid "Repo \"%s\" does not exist"
msgstr "Репозитория не существует"
#: repo.go:150
#: repo.go:163
msgid "Error removing repo directory"
msgstr "Ошибка при удалении каталога репозитория"
#: repo.go:167
#: repo.go:186
msgid "Error removing packages from database"
msgstr "Ошибка при удалении пакетов из базы данных"
#: repo.go:179
#: repo.go:197
msgid "Pull all repositories that have changed"
msgstr "Скачать все изменённые репозитории"
@ -524,11 +520,16 @@ msgstr "Иcкать по provides"
msgid "Format output using a Go template"
msgstr "Формат выходных данных с использованием шаблона Go"
#: search.go:88 search.go:105
#: search.go:96
#, fuzzy
msgid "Error while executing search"
msgstr "Ошибка при запуске приложения"
#: search.go:104
msgid "Error parsing format template"
msgstr "Ошибка при разборе шаблона"
#: search.go:113
#: search.go:112
msgid "Error executing template"
msgstr "Ошибка при выполнении шаблона"
@ -536,14 +537,60 @@ msgstr "Ошибка при выполнении шаблона"
msgid "Upgrade all installed packages"
msgstr "Обновить все установленные пакеты"
#: upgrade.go:96
#: upgrade.go:109 upgrade.go:126
msgid "Error checking for updates"
msgstr "Ошибка при проверке обновлений"
#: upgrade.go:118
#: upgrade.go:129
msgid "There is nothing to do."
msgstr "Здесь нечего делать."
#~ msgid "Error pulling repos"
#~ msgstr "Ошибка при извлечении репозиториев"
#, fuzzy
#~ msgid "Error getting current executable"
#~ msgstr "Ошибка при получении рабочего каталога"
#, fuzzy
#~ msgid "Error mounting"
#~ msgstr "Ошибка при кодировании конфигурации"
#, fuzzy
#~ msgid "Unable to create config directory"
#~ msgstr "Не удалось создать каталог конфигурации ALR"
#~ msgid "Unable to create repo cache directory"
#~ msgstr "Не удалось создать каталог кэша репозитория"
#~ msgid "Unable to create package cache directory"
#~ msgstr "Не удалось создать каталог кэша пакетов"
#~ msgid ""
#~ "Running ALR as root is forbidden as it may cause catastrophic damage to "
#~ "your system"
#~ msgstr ""
#~ "Запуск ALR от имени root запрещён, так как это может привести к "
#~ "катастрофическому повреждению вашей системы"
#~ msgid "Failed to prompt user to view build script"
#~ msgstr "Не удалось предложить пользователю просмотреть скрипт сборки"
#~ msgid "Compressing package"
#~ msgstr "Сжатие пакета"
#~ msgid "Installing build dependencies"
#~ msgstr "Установка зависимостей сборки"
#~ msgid "Would you like to remove the build dependencies?"
#~ msgstr "Хотели бы вы удалить зависимости сборки?"
#~ msgid "Error installing native packages"
#~ msgstr "Ошибка при установке нативных пакетов"
#~ msgid "Error installing package"
#~ msgstr "Ошибка при установке пакета"
#~ msgid "Error opening config file, using defaults"
#~ msgstr ""
#~ "Ошибка при открытии конфигурационного файла, используются значения по "
@ -569,12 +616,6 @@ msgstr "Здесь нечего делать."
#~ msgid "Error opening config file"
#~ msgstr "Ошибка при открытии конфигурационного файла"
#~ msgid "Error parsing system language"
#~ msgstr "Ошибка при парсинге языка системы"
#~ msgid "Error opening database"
#~ msgstr "Ошибка при открытии базы данных"
#~ msgid "Executing version()"
#~ msgstr "Исполнение версия()"

View File

@ -19,13 +19,11 @@
package types
import "gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
type BuildOpts struct {
Script string
Repository string
Packages []string
Manager manager.Manager
// Script string
// Repository string
// Packages []string
// Manager manager.Manager
Clean bool
Interactive bool
}

View File

@ -25,7 +25,6 @@ type Config struct {
PagerStyle string `toml:"pagerStyle" env:"ALR_PAGER_STYLE"`
IgnorePkgUpdates []string `toml:"ignorePkgUpdates"`
Repos []Repo `toml:"repo"`
Unsafe Unsafe `toml:"unsafe"`
AutoPull bool `toml:"autoPull" env:"ALR_AUTOPULL"`
LogLevel string `toml:"logLevel" env:"ALR_LOG_LEVEL"`
}
@ -35,7 +34,3 @@ type Repo struct {
Name string `toml:"name"`
URL string `toml:"url"`
}
type Unsafe struct {
AllowRunAsRoot bool `toml:"allowRunAsRoot" env:"ALR_UNSAFE_ALLOW_RUN_AS_ROOT"`
}

186
internal/utils/cmd.go Normal file
View File

@ -0,0 +1,186 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package utils
import (
"errors"
"os"
"os/user"
"strconv"
"syscall"
"github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/constants"
)
func GetUidGidAlrUserString() (string, string, error) {
u, err := user.Lookup("alr")
if err != nil {
return "", "", err
}
return u.Uid, u.Gid, nil
}
func GetUidGidAlrUser() (int, int, error) {
strUid, strGid, err := GetUidGidAlrUserString()
if err != nil {
return 0, 0, err
}
uid, err := strconv.Atoi(strUid)
if err != nil {
return 0, 0, err
}
gid, err := strconv.Atoi(strGid)
if err != nil {
return 0, 0, err
}
return uid, gid, nil
}
func DropCapsToAlrUser() error {
uid, gid, err := GetUidGidAlrUser()
if err != nil {
return err
}
err = syscall.Setgid(gid)
if err != nil {
return err
}
err = syscall.Setuid(uid)
if err != nil {
return err
}
return EnsureIsAlrUser()
}
func ExitIfCantDropGidToAlr() cli.ExitCoder {
_, gid, err := GetUidGidAlrUser()
if err != nil {
return cliutils.FormatCliExit("cannot get gid alr", err)
}
err = syscall.Setgid(gid)
if err != nil {
return cliutils.FormatCliExit("cannot get setgid alr", err)
}
return nil
}
// ExitIfCantDropCapsToAlrUser attempts to drop capabilities to the already
// running user. Returns a cli.ExitCoder with an error if the operation fails.
// See also [ExitIfCantDropCapsToAlrUserNoPrivs] for a version that also applies
// no-new-privs.
func ExitIfCantDropCapsToAlrUser() cli.ExitCoder {
err := DropCapsToAlrUser()
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error dropping capabilities"), err)
}
return nil
}
func ExitIfCantSetNoNewPrivs() cli.ExitCoder {
if err := NoNewPrivs(); err != nil {
return cliutils.FormatCliExit("error no new privs", err)
}
return nil
}
// ExitIfCantDropCapsToAlrUserNoPrivs combines [ExitIfCantDropCapsToAlrUser] with [ExitIfCantSetNoNewPrivs]
func ExitIfCantDropCapsToAlrUserNoPrivs() cli.ExitCoder {
if err := ExitIfCantDropCapsToAlrUser(); err != nil {
return err
}
if err := ExitIfCantSetNoNewPrivs(); err != nil {
return err
}
return nil
}
func ExitIfNotRoot() error {
if os.Getuid() != 0 {
return cli.Exit(gotext.Get("You need to be root to perform this action"), 1)
}
return nil
}
func EnsureIsAlrUser() error {
uid, gid, err := GetUidGidAlrUser()
if err != nil {
return err
}
newUid := syscall.Getuid()
if newUid != uid {
return errors.New("new uid don't matches requested")
}
newGid := syscall.Getgid()
if newGid != gid {
return errors.New("new gid don't matches requested")
}
return nil
}
func EnuseIsPrivilegedGroupMember() error {
currentUser, err := user.Current()
if err != nil {
return err
}
group, err := user.LookupGroup(constants.PrivilegedGroup)
if err != nil {
return err
}
groups, err := currentUser.GroupIds()
if err != nil {
return err
}
for _, gid := range groups {
if gid == group.Gid {
return nil
}
}
return cliutils.FormatCliExit(gotext.Get("You need to be a %s member to perform this action", constants.PrivilegedGroup), nil)
}
func EscalateToRootGid() error {
return syscall.Setgid(0)
}
func EscalateToRootUid() error {
return syscall.Setuid(0)
}
func EscalateToRoot() error {
err := EscalateToRootUid()
if err != nil {
return err
}
err = EscalateToRootGid()
if err != nil {
return err
}
return nil
}

23
internal/utils/utils.go Normal file
View File

@ -0,0 +1,23 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package utils
import "golang.org/x/sys/unix"
func NoNewPrivs() error {
return unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
}