Compare commits
4 Commits
v0.0.9
...
083df3c7aa
| Author | SHA1 | Date | |
|---|---|---|---|
| 083df3c7aa | |||
| 100739c419 | |||
| 17bbb2f4c5 | |||
| 8978cc2855 |
@@ -47,4 +47,4 @@ issues:
|
||||
# TODO: remove
|
||||
- linters:
|
||||
- staticcheck
|
||||
text: "SA1019: interp.ExecHandler"
|
||||
text: "SA1019:"
|
||||
3
Makefile
3
Makefile
@@ -21,7 +21,7 @@ build: check-no-root $(BIN)
|
||||
|
||||
export CGO_ENABLED := 0
|
||||
$(BIN):
|
||||
go build -ldflags="-X 'gitea.plemya-x.ru/Plemya-x/ALR/internal/config.Version=$(GIT_VERSION)'" -o $@
|
||||
go build -ldflags="-X 'gitea.plemya-x.ru/xpamych/ALR/internal/config.Version=$(GIT_VERSION)'" -o $@
|
||||
|
||||
check-no-root:
|
||||
@if [[ "$$(whoami)" == 'root' ]]; then \
|
||||
@@ -66,7 +66,6 @@ i18n:
|
||||
$(XGOTEXT_BIN) --output ./internal/translations/default.pot
|
||||
msguniq --use-first -o ./internal/translations/default.pot ./internal/translations/default.pot
|
||||
msgmerge --backup=off -U ./internal/translations/po/ru/default.po ./internal/translations/default.pot
|
||||
bash scripts/i18n-badge.sh
|
||||
|
||||
test-coverage:
|
||||
go test ./... -v -coverpkg=./... -coverprofile=coverage.out
|
||||
|
||||
24
README.md
24
README.md
@@ -3,13 +3,13 @@
|
||||
</p>
|
||||
<b></b>
|
||||
|
||||
[](https://goreportcard.com/report/gitea.plemya-x.ru/Plemya-x/ALR)  
|
||||
[](https://goreportcard.com/report/gitea.plemya-x.ru/Plemya-x/ALR) 
|
||||
|
||||
# ALR (Any Linux Repository)
|
||||
|
||||
ALR - это независимая от дистрибутива система сборки для Linux (форк [LURE](https://github.com/lure-sh/lure), аналогичная [AUR](https://wiki.archlinux.org/title/Arch_User_Repository). В настоящее время она находится в стадии бета-тестирования. Исправлено большинство основных ошибок и добавлено большинство важных функций. ALR готов к общему использованию, но все еще может время от времени ломаться или изменяться.
|
||||
ALR - это независимая от дистрибутива система сборки для Linux, аналогичная [AUR](https://wiki.archlinux.org/title/Arch_User_Repository). В настоящее время она находится в стадии бета-тестирования. Исправлено большинство основных ошибок и добавлено большинство важных функций. alr готов к общему использованию, но все еще может время от времени ломаться или заменяться.
|
||||
|
||||
ALR написан на чистом Go и после сборки не имеет зависимостей. Для повышения привилегий ALR требуется команда, такая как `sudo`, `doas` и т.д., а также поддерживаемый менеджер пакетов. В настоящее время ALR поддерживает `apt`, `apt-get` `pacman`, `apk`, `dnf`, `yum`, and `zypper`. Если в вашей системе используется поддерживаемый менеджер пакетов, то он будет обнаружен и использован автоматически.
|
||||
ALR написан на чистом Go и после сборки не имеет зависимостей. Единственное, для повышения привилегий ALR требуется команда, такая как `sudo`, `doas` и т.д., а также поддерживаемый менеджер пакетов. В настоящее время ALR поддерживает `apt`, `pacman`, `apk`, `dnf`, `yum`, and `zypper`. Если в вашей системе существует поддерживаемый менеджер пакетов, он будет обнаружен и использован автоматически.
|
||||
|
||||
---
|
||||
|
||||
@@ -23,14 +23,14 @@ ALR написан на чистом Go и после сборки не имее
|
||||
curl -fsSL plemya-x.ru/alr/install.sh | bash
|
||||
```
|
||||
|
||||
**ВАЖНО**: При этом скрипт будет загружен и запущен с <https://plemya-x.ru/alr/install.sh>. Пожалуйста, просматривайте любые скрипты, которые вы скачиваете из Интернета (включая этот), прежде чем запускать их.
|
||||
**ВАЖНО**: При этом скрипт будет загружен и запущен с <https://gitea.plemya-x.ru/Plemya-x/ALR/src/branch/master/scripts/install.sh>. Пожалуйста, просматривайте любые скрипты, которые вы скачиваете из Интернета (включая этот), прежде чем запускать их.
|
||||
|
||||
### Сборка из исходного кода
|
||||
|
||||
Чтобы собрать ALR из исходного кода, вам понадобится версия Go 1.18 или новее. Как только Go будет установлен, клонируйте это репозиторий и запустите:
|
||||
|
||||
```shell
|
||||
make build -B
|
||||
make build
|
||||
sudo make install
|
||||
```
|
||||
|
||||
@@ -44,23 +44,20 @@ ALR был создан потому, что упаковка программн
|
||||
|
||||
## Документация
|
||||
|
||||
Документация находится в [Wiki](https://disc.plemya-x.ru/c/alr/wiki-alr).
|
||||
Документация по всем этим вопросам находится в [Wiki](https://gitea.plemya-x.ru/xpamych/ALR/wiki/Home).
|
||||
|
||||
---
|
||||
|
||||
## Репозитории
|
||||
|
||||
Репозитории alr - это git-хранилища, которые содержат каталог для каждого пакета с файлом `alr.sh` внутри. Файл `alr.sh` содержит все инструкции по сборке пакета и информацию о нем. Скрипты `alr.sh` аналогичны скриптам Aur PKGBUILD.
|
||||
|
||||
Например, репозиторий [Plemya-x/alr-repo](https://gitea.plemya-x.ru/Plemya-x/alr-repo.git) можно подключить так:
|
||||
```
|
||||
alr addrepo --name alr-repo --url https://gitea.plemya-x.ru/Plemya-x/alr-repo.git
|
||||
```
|
||||
Репозитории alr - это git-хранилища, которые содержат каталог для каждого пакета с файлом `alr.sh` внутри. Файл `alr.sh` содержит все инструкции по сборке пакета и информацию о нем. Скрипты `alr.sh` аналогичны скриптам Aur PKGBUILD. Репозиторий [по-умолчанию](https://gitea.plemya-x.ru/xpamych/xpamych-alr-repo.git).
|
||||
|
||||
---
|
||||
## Соцсети
|
||||
VK - https://vk.com/plemya_kh
|
||||
|
||||
Discord - https://discord.com/channels/817759634105827358/1261631565084233749
|
||||
|
||||
Telegram - https://t.me/plemyakh
|
||||
|
||||
## Спасибы
|
||||
@@ -73,6 +70,3 @@ Telegram - https://t.me/plemyakh
|
||||
- <https://github.com/goreleaser/nfpm>
|
||||
- <https://github.com/charmbracelet/bubbletea>
|
||||
- <https://gitlab.com/cznic/sqlite>
|
||||
|
||||
Благодарим за активное участие в развитии проекта:
|
||||
- Maks1mS <maxim@slipenko.com>
|
||||
@@ -1,18 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="129" height="20">
|
||||
<linearGradient id="smooth" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<mask id="round">
|
||||
<rect width="129" height="20" rx="3" fill="#fff"/>
|
||||
</mask>
|
||||
<g mask="url(#round)">
|
||||
<rect width="75" height="20" fill="#555"/>
|
||||
<rect x="75" width="64" height="20" fill="#4c1"/>
|
||||
<rect width="129" height="20" fill="url(#smooth)"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
|
||||
<text x="37" y="15" fill="#010101" fill-opacity=".3">ru translate</text>
|
||||
<text x="37" y="14">ru translate</text>
|
||||
<text x="100" y="15" fill="#010101" fill-opacity=".3">100.00%</text>
|
||||
<text x="100" y="14">100.00%</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 942 B |
27
build.go
27
build.go
@@ -50,9 +50,9 @@ func BuildCmd() *cli.Command {
|
||||
Usage: gotext.Get("Path to the build script"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "subpackage",
|
||||
Aliases: []string{"sb"},
|
||||
Usage: gotext.Get("Specify subpackage in script (for multi package script only)"),
|
||||
Name: "script-package",
|
||||
Aliases: []string{"sp"},
|
||||
Usage: gotext.Get("Specify package in script (for multi package script only)"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "package",
|
||||
@@ -72,20 +72,20 @@ func BuildCmd() *cli.Command {
|
||||
rs := repos.New(cfg, db)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
slog.Error(gotext.Get("Error db init"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var script string
|
||||
var packages []string
|
||||
repository := "default"
|
||||
var script, packageName string
|
||||
|
||||
// Проверяем, установлен ли флаг script (-s)
|
||||
|
||||
repoDir := cfg.GetPaths(ctx).RepoDir
|
||||
|
||||
switch {
|
||||
case c.IsSet("script"):
|
||||
script = c.String("script")
|
||||
packages = append(packages, c.String("script-package"))
|
||||
packageName = c.String("script-package")
|
||||
case c.IsSet("package"):
|
||||
// TODO: handle multiple packages
|
||||
packageInput := c.String("package")
|
||||
@@ -105,13 +105,11 @@ func BuildCmd() *cli.Command {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
repository = pkg[0].Repository
|
||||
|
||||
if pkg[0].BasePkgName != "" {
|
||||
script = filepath.Join(repoDir, repository, pkg[0].BasePkgName, "alr.sh")
|
||||
packages = append(packages, pkg[0].Name)
|
||||
script = filepath.Join(repoDir, pkg[0].Repository, pkg[0].BasePkgName, "alr.sh")
|
||||
packageName = pkg[0].Name
|
||||
} else {
|
||||
script = filepath.Join(repoDir, repository, pkg[0].Name, "alr.sh")
|
||||
script = filepath.Join(repoDir, pkg[0].Repository, pkg[0].Name, "alr.sh")
|
||||
}
|
||||
default:
|
||||
script = filepath.Join(repoDir, "alr.sh")
|
||||
@@ -142,8 +140,7 @@ func BuildCmd() *cli.Command {
|
||||
builder := build.NewBuilder(
|
||||
ctx,
|
||||
types.BuildOpts{
|
||||
Packages: packages,
|
||||
Repository: repository,
|
||||
Package: packageName,
|
||||
Script: script,
|
||||
Manager: mgr,
|
||||
Clean: c.Bool("clean"),
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
|
||||
<text x="33.5" y="15" fill="#010101" fill-opacity=".3">coverage</text>
|
||||
<text x="33.5" y="14">coverage</text>
|
||||
<text x="86" y="15" fill="#010101" fill-opacity=".3">19.8%</text>
|
||||
<text x="86" y="14">19.8%</text>
|
||||
<text x="86" y="15" fill="#010101" fill-opacity=".3">20.8%</text>
|
||||
<text x="86" y="14">20.8%</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 926 B After Width: | Height: | Size: 926 B |
17
fix.go
17
fix.go
@@ -27,7 +27,7 @@ import (
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
|
||||
)
|
||||
|
||||
@@ -37,8 +37,9 @@ func FixCmd() *cli.Command {
|
||||
Usage: gotext.Get("Attempt to fix problems with ALR"),
|
||||
Action: func(c *cli.Context) error {
|
||||
ctx := c.Context
|
||||
cfg := config.New()
|
||||
paths := cfg.GetPaths(ctx)
|
||||
|
||||
db.Close()
|
||||
paths := config.GetPaths(ctx)
|
||||
|
||||
slog.Info(gotext.Get("Removing cache directory"))
|
||||
|
||||
@@ -56,15 +57,7 @@ func FixCmd() *cli.Command {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg = config.New()
|
||||
db := database.New(cfg)
|
||||
err = db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
rs := repos.New(cfg, db)
|
||||
err = rs.Pull(ctx, cfg.Repos(ctx))
|
||||
err = repos.Pull(ctx, config.Config(ctx).Repos)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error pulling repos"), "err", err)
|
||||
os.Exit(1)
|
||||
|
||||
41
info.go
41
info.go
@@ -24,14 +24,13 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/jeandeaual/go-locale"
|
||||
"github.com/leonelquinteros/gotext"
|
||||
"github.com/urfave/cli/v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
|
||||
@@ -48,39 +47,11 @@ func InfoCmd() *cli.Command {
|
||||
Usage: gotext.Get("Show all information, not just for the current distro"),
|
||||
},
|
||||
},
|
||||
BashComplete: func(c *cli.Context) {
|
||||
ctx := c.Context
|
||||
cfg := config.New()
|
||||
db := database.New(cfg)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
result, err := db.GetPkgs(c.Context, "true")
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error getting packages"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer result.Close()
|
||||
|
||||
for result.Next() {
|
||||
var pkg database.Package
|
||||
err = result.StructScan(&pkg)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error iterating over packages"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println(pkg.Name)
|
||||
}
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
ctx := c.Context
|
||||
|
||||
cfg := config.New()
|
||||
db := database.New(cfg)
|
||||
db := db.New(cfg)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
@@ -117,12 +88,6 @@ func InfoCmd() *cli.Command {
|
||||
var names []string
|
||||
all := c.Bool("all")
|
||||
|
||||
systemLang, err := locale.GetLanguage()
|
||||
if err != nil {
|
||||
slog.Error("Can't detect system language", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if !all {
|
||||
info, err := distro.ParseOSRelease(ctx)
|
||||
if err != nil {
|
||||
@@ -132,7 +97,7 @@ func InfoCmd() *cli.Command {
|
||||
names, err = overrides.Resolve(
|
||||
info,
|
||||
overrides.DefaultOpts.
|
||||
WithLanguages([]string{systemLang}),
|
||||
WithLanguages([]string{config.SystemLang()}),
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error resolving overrides"), "err", err)
|
||||
|
||||
@@ -46,7 +46,7 @@ func InstallCmd() *cli.Command {
|
||||
&cli.BoolFlag{
|
||||
Name: "clean",
|
||||
Aliases: []string{"c"},
|
||||
Usage: gotext.Get("Build package from scratch even if there's an already built package available"),
|
||||
Usage: "Build package from scratch even if there's an already built package available",
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
@@ -69,7 +69,7 @@ func InstallCmd() *cli.Command {
|
||||
rs := repos.New(cfg, db)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
slog.Error(gotext.Get("Error db init"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -119,11 +119,6 @@ func InstallCmd() *cli.Command {
|
||||
BashComplete: func(c *cli.Context) {
|
||||
cfg := config.New()
|
||||
db := database.New(cfg)
|
||||
err := db.Init(c.Context)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
result, err := db.GetPkgs(c.Context, "true")
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error getting packages"), "err", err)
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
// 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 (
|
||||
"fmt"
|
||||
|
||||
"github.com/leonelquinteros/gotext"
|
||||
)
|
||||
|
||||
// Templates are based on https://github.com/urfave/cli/blob/3b17080d70a630feadadd23dd036cad121dd9a50/template.go
|
||||
|
||||
//nolint:unused
|
||||
var (
|
||||
helpNameTemplate = `{{$v := offset .HelpName 6}}{{wrap .HelpName 3}}{{if .Usage}} - {{wrap .Usage $v}}{{end}}`
|
||||
descriptionTemplate = `{{wrap .Description 3}}`
|
||||
authorsTemplate = `{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
|
||||
{{range $index, $author := .Authors}}{{if $index}}
|
||||
{{end}}{{$author}}{{end}}`
|
||||
visibleCommandTemplate = `{{ $cv := offsetCommands .VisibleCommands 5}}{{range .VisibleCommands}}
|
||||
{{$s := join .Names ", "}}{{$s}}{{ $sp := subtract $cv (offset $s 3) }}{{ indent $sp ""}}{{wrap .Usage $cv}}{{end}}`
|
||||
visibleCommandCategoryTemplate = `{{range .VisibleCategories}}{{if .Name}}
|
||||
{{.Name}}:{{range .VisibleCommands}}
|
||||
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{template "visibleCommandTemplate" .}}{{end}}{{end}}`
|
||||
visibleFlagCategoryTemplate = `{{range .VisibleFlagCategories}}
|
||||
{{if .Name}}{{.Name}}
|
||||
|
||||
{{end}}{{$flglen := len .Flags}}{{range $i, $e := .Flags}}{{if eq (subtract $flglen $i) 1}}{{$e}}
|
||||
{{else}}{{$e}}
|
||||
{{end}}{{end}}{{end}}`
|
||||
visibleFlagTemplate = `{{range $i, $e := .VisibleFlags}}
|
||||
{{wrap $e.String 6}}{{end}}`
|
||||
copyrightTemplate = `{{wrap .Copyright 3}}`
|
||||
)
|
||||
|
||||
func GetAppCliTemplate() string {
|
||||
return fmt.Sprintf(`%s:
|
||||
{{template "helpNameTemplate" .}}
|
||||
|
||||
%s:
|
||||
{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[%s]{{end}}{{if .Commands}} %s [%s]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[%s...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
|
||||
|
||||
%s:
|
||||
{{.Version}}{{end}}{{end}}{{if .Description}}
|
||||
|
||||
%s:
|
||||
{{template "descriptionTemplate" .}}{{end}}
|
||||
{{- if len .Authors}}
|
||||
|
||||
%s{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}}
|
||||
|
||||
%s:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}}
|
||||
|
||||
%s:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}
|
||||
|
||||
%s:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}}
|
||||
|
||||
%s:
|
||||
{{template "copyrightTemplate" .}}{{end}}
|
||||
`, gotext.Get("NAME"), gotext.Get("USAGE"), gotext.Get("global options"), gotext.Get("command"), gotext.Get("command options"), gotext.Get("arguments"), gotext.Get("VERSION"), gotext.Get("DESCRIPTION"), gotext.Get("AUTHOR"), gotext.Get("COMMANDS"), gotext.Get("GLOBAL OPTIONS"), gotext.Get("GLOBAL OPTIONS"), gotext.Get("COPYRIGHT"))
|
||||
}
|
||||
|
||||
func GetCommandHelpTemplate() string {
|
||||
return fmt.Sprintf(`%s:
|
||||
{{template "helpNameTemplate" .}}
|
||||
|
||||
%s:
|
||||
{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}}{{if .VisibleFlags}} [%s]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[%s...]{{end}}{{end}}{{if .Category}}
|
||||
|
||||
%s:
|
||||
{{.Category}}{{end}}{{if .Description}}
|
||||
|
||||
%s:
|
||||
{{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}}
|
||||
|
||||
%s:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}
|
||||
|
||||
%s:{{template "visibleFlagTemplate" .}}{{end}}
|
||||
`, gotext.Get("NAME"),
|
||||
gotext.Get("USAGE"),
|
||||
gotext.Get("command options"),
|
||||
gotext.Get("arguments"),
|
||||
gotext.Get("CATEGORY"),
|
||||
gotext.Get("DESCRIPTION"),
|
||||
gotext.Get("OPTIONS"),
|
||||
gotext.Get("OPTIONS"),
|
||||
)
|
||||
}
|
||||
@@ -45,8 +45,13 @@ var defaultConfig = &types.Config{
|
||||
RootCmd: "sudo",
|
||||
PagerStyle: "native",
|
||||
IgnorePkgUpdates: []string{},
|
||||
AutoPull: false,
|
||||
Repos: []types.Repo{},
|
||||
AutoPull: true,
|
||||
Repos: []types.Repo{
|
||||
{
|
||||
Name: "default",
|
||||
URL: "https://gitea.plemya-x.ru/xpamych/xpamych-alr-repo.git",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func New() *ALRConfig {
|
||||
@@ -152,13 +157,6 @@ func (c *ALRConfig) Repos(ctx context.Context) []types.Repo {
|
||||
return c.cfg.Repos
|
||||
}
|
||||
|
||||
func (c *ALRConfig) SetRepos(ctx context.Context, repos []types.Repo) {
|
||||
c.cfgOnce.Do(func() {
|
||||
c.Load(ctx)
|
||||
})
|
||||
c.cfg.Repos = repos
|
||||
}
|
||||
|
||||
func (c *ALRConfig) IgnorePkgUpdates(ctx context.Context) []string {
|
||||
c.cfgOnce.Do(func() {
|
||||
c.Load(ctx)
|
||||
@@ -179,21 +177,3 @@ func (c *ALRConfig) PagerStyle(ctx context.Context) string {
|
||||
})
|
||||
return c.cfg.PagerStyle
|
||||
}
|
||||
|
||||
func (c *ALRConfig) AllowRunAsRoot(ctx context.Context) bool {
|
||||
c.cfgOnce.Do(func() {
|
||||
c.Load(ctx)
|
||||
})
|
||||
return c.cfg.Unsafe.AllowRunAsRoot
|
||||
}
|
||||
|
||||
func (c *ALRConfig) RootCmd(ctx context.Context) string {
|
||||
c.cfgOnce.Do(func() {
|
||||
c.Load(ctx)
|
||||
})
|
||||
return c.cfg.RootCmd
|
||||
}
|
||||
|
||||
func (c *ALRConfig) Save(f *os.File) error {
|
||||
return toml.NewEncoder(f).Encode(c.cfg)
|
||||
}
|
||||
|
||||
@@ -14,34 +14,39 @@
|
||||
// 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 build
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
|
||||
)
|
||||
|
||||
func TestRemoveDuplicatesSources(t *testing.T) {
|
||||
type testCase struct {
|
||||
Name string
|
||||
Sources []string
|
||||
Checksums []string
|
||||
NewSources []string
|
||||
NewChecksums []string
|
||||
}
|
||||
|
||||
for _, tc := range []testCase{{
|
||||
Name: "prefer non-skip values",
|
||||
Sources: []string{"a", "b", "c", "a"},
|
||||
Checksums: []string{"skip", "skip", "skip", "1"},
|
||||
NewSources: []string{"a", "b", "c"},
|
||||
NewChecksums: []string{"1", "skip", "skip"},
|
||||
}} {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
s, c := removeDuplicatesSources(tc.Sources, tc.Checksums)
|
||||
assert.Equal(t, s, tc.NewSources)
|
||||
assert.Equal(t, c, tc.NewChecksums)
|
||||
})
|
||||
}
|
||||
// Config returns a ALR configuration struct.
|
||||
// The first time it's called, it'll load the config from a file.
|
||||
// Subsequent calls will just return the same value.
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func Config(ctx context.Context) *types.Config {
|
||||
return GetInstance(ctx).cfg
|
||||
}
|
||||
|
||||
// =======================
|
||||
// FOR LEGACY ONLY
|
||||
// =======================
|
||||
|
||||
var (
|
||||
alrConfig *ALRConfig
|
||||
alrConfigOnce sync.Once
|
||||
)
|
||||
|
||||
// Deprecated: For legacy only
|
||||
func GetInstance(ctx context.Context) *ALRConfig {
|
||||
alrConfigOnce.Do(func() {
|
||||
alrConfig = New()
|
||||
alrConfig.Load(ctx)
|
||||
})
|
||||
|
||||
return alrConfig
|
||||
}
|
||||
70
internal/config/lang.go
Normal file
70
internal/config/lang.go
Normal file
@@ -0,0 +1,70 @@
|
||||
// This file was originally part of the project "LURE - Linux User REpository", created by Elara Musayelyan.
|
||||
// It has been modified as part of "ALR - Any Linux Repository" by Евгений Храмов.
|
||||
//
|
||||
// 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 config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/leonelquinteros/gotext"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
var (
|
||||
langMtx sync.Mutex
|
||||
lang language.Tag
|
||||
langSet bool
|
||||
)
|
||||
|
||||
// Language returns the system language.
|
||||
// The first time it's called, it'll detect the langauge based on
|
||||
// the $LANG environment variable.
|
||||
// Subsequent calls will just return the same value.
|
||||
func Language(ctx context.Context) language.Tag {
|
||||
langMtx.Lock()
|
||||
if !langSet {
|
||||
syslang := SystemLang()
|
||||
tag, err := language.Parse(syslang)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error parsing system language"), "err", err)
|
||||
langMtx.Unlock()
|
||||
os.Exit(1)
|
||||
}
|
||||
base, _ := tag.Base()
|
||||
lang = language.Make(base.String())
|
||||
langSet = true
|
||||
}
|
||||
langMtx.Unlock()
|
||||
return lang
|
||||
}
|
||||
|
||||
// SystemLang returns the system language based on
|
||||
// the $LANG environment variable.
|
||||
func SystemLang() string {
|
||||
lang := os.Getenv("LANG")
|
||||
lang, _, _ = strings.Cut(lang, ".")
|
||||
if lang == "" || lang == "C" {
|
||||
lang = "en"
|
||||
}
|
||||
return lang
|
||||
}
|
||||
@@ -19,6 +19,10 @@
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Paths contains various paths used by ALR
|
||||
type Paths struct {
|
||||
ConfigDir string
|
||||
@@ -28,3 +32,14 @@ type Paths struct {
|
||||
PkgsDir string
|
||||
DBPath string
|
||||
}
|
||||
|
||||
// GetPaths returns a Paths struct.
|
||||
// The first time it's called, it'll generate the struct
|
||||
// using information from the system.
|
||||
// Subsequent calls will return the same value.
|
||||
//
|
||||
// Deprecated: use struct API
|
||||
func GetPaths(ctx context.Context) *Paths {
|
||||
alrConfig := GetInstance(ctx)
|
||||
return alrConfig.GetPaths(ctx)
|
||||
}
|
||||
|
||||
106
internal/db/db_legacy.go
Normal file
106
internal/db/db_legacy.go
Normal file
@@ -0,0 +1,106 @@
|
||||
// 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 db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/leonelquinteros/gotext"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
)
|
||||
|
||||
// DB returns the ALR database.
|
||||
// The first time it's called, it opens the SQLite database file.
|
||||
// Subsequent calls return the same connection.
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func DB(ctx context.Context) *sqlx.DB {
|
||||
return GetInstance(ctx).GetConn()
|
||||
}
|
||||
|
||||
// Close closes the database
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func Close() error {
|
||||
if database != nil {
|
||||
return database.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsEmpty returns true if the database has no packages in it, otherwise it returns false.
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func IsEmpty(ctx context.Context) bool {
|
||||
return GetInstance(ctx).IsEmpty(ctx)
|
||||
}
|
||||
|
||||
// InsertPackage adds a package to the database
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func InsertPackage(ctx context.Context, pkg Package) error {
|
||||
return GetInstance(ctx).InsertPackage(ctx, pkg)
|
||||
}
|
||||
|
||||
// GetPkgs returns a result containing packages that match the where conditions
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func GetPkgs(ctx context.Context, where string, args ...any) (*sqlx.Rows, error) {
|
||||
return GetInstance(ctx).GetPkgs(ctx, where, args...)
|
||||
}
|
||||
|
||||
// GetPkg returns a single package that matches the where conditions
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func GetPkg(ctx context.Context, where string, args ...any) (*Package, error) {
|
||||
return GetInstance(ctx).GetPkg(ctx, where, args...)
|
||||
}
|
||||
|
||||
// DeletePkgs deletes all packages matching the where conditions
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func DeletePkgs(ctx context.Context, where string, args ...any) error {
|
||||
return GetInstance(ctx).DeletePkgs(ctx, where, args...)
|
||||
}
|
||||
|
||||
// =======================
|
||||
// FOR LEGACY ONLY
|
||||
// =======================
|
||||
|
||||
var (
|
||||
dbOnce sync.Once
|
||||
database *Database
|
||||
)
|
||||
|
||||
// Deprecated: For legacy only
|
||||
func GetInstance(ctx context.Context) *Database {
|
||||
dbOnce.Do(func() {
|
||||
cfg := config.GetInstance(ctx)
|
||||
database = New(cfg)
|
||||
err := database.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error opening database"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
})
|
||||
return database
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func TestDownloadWithoutCache(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "git download",
|
||||
path: "git+%s/git-downloader/git/Plemya-x/alr-repo",
|
||||
path: "git+%s/git-downloader/git/Plemya-x/xpamych-alr-repo",
|
||||
expected: func(t *testing.T, err error, tmpdir string) {
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
||||
@@ -32,6 +32,14 @@ import (
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/dlcache"
|
||||
)
|
||||
|
||||
func init() {
|
||||
dir, err := os.MkdirTemp("/tmp", "alr-dlcache-test.*")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
config.GetPaths(context.Background()).RepoDir = dir
|
||||
}
|
||||
|
||||
type TestALRConfig struct {
|
||||
CacheDir string
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func init() {
|
||||
|
||||
b2 := lipgloss.RoundedBorder()
|
||||
b2.Left = "\u2524"
|
||||
infoStyle = titleStyle.BorderStyle(b2)
|
||||
infoStyle = titleStyle.Copy().BorderStyle(b2)
|
||||
}
|
||||
|
||||
type Pager struct {
|
||||
|
||||
@@ -164,10 +164,7 @@ func (d *Decoder) DecodeVars(val any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type (
|
||||
ScriptFunc func(ctx context.Context, opts ...interp.RunnerOption) error
|
||||
ScriptFuncWithSubshell func(ctx context.Context, opts ...interp.RunnerOption) (*interp.Runner, error)
|
||||
)
|
||||
type ScriptFunc func(ctx context.Context, opts ...interp.RunnerOption) error
|
||||
|
||||
// GetFunc returns a function corresponding to a bash function
|
||||
// with the given name
|
||||
@@ -200,7 +197,10 @@ func (d *Decoder) GetFuncP(name string, prepare PrepareFunc) (ScriptFunc, bool)
|
||||
}, true
|
||||
}
|
||||
|
||||
func (d *Decoder) GetFuncWithSubshell(name string) (ScriptFuncWithSubshell, bool) {
|
||||
// TODO: replace
|
||||
func (d *Decoder) GetFuncSub(name string) (
|
||||
func(ctx context.Context, opts ...interp.RunnerOption) (*interp.Runner, error), bool,
|
||||
) {
|
||||
fn := d.getFunc(name)
|
||||
if fn == nil {
|
||||
return nil, false
|
||||
|
||||
@@ -22,11 +22,10 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
)
|
||||
|
||||
func NopReadDir(context.Context, string) ([]fs.DirEntry, error) {
|
||||
func NopReadDir(context.Context, string) ([]os.FileInfo, error) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
|
||||
@@ -31,12 +31,12 @@ import (
|
||||
"mvdan.cc/sh/v3/interp"
|
||||
)
|
||||
|
||||
func RestrictedReadDir(allowedPrefixes ...string) interp.ReadDirHandlerFunc2 {
|
||||
return func(ctx context.Context, s string) ([]fs.DirEntry, error) {
|
||||
func RestrictedReadDir(allowedPrefixes ...string) interp.ReadDirHandlerFunc {
|
||||
return func(ctx context.Context, s string) ([]fs.FileInfo, error) {
|
||||
path := filepath.Clean(s)
|
||||
for _, allowedPrefix := range allowedPrefixes {
|
||||
if strings.HasPrefix(path, allowedPrefix) {
|
||||
return interp.DefaultReadDirHandler2()(ctx, s)
|
||||
return interp.DefaultReadDirHandler()(ctx, s)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ msgid "Path to the build script"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:55
|
||||
msgid "Specify subpackage in script (for multi package script only)"
|
||||
msgid "Specify package in script (for multi package script only)"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:60
|
||||
@@ -31,34 +31,34 @@ msgid ""
|
||||
msgstr ""
|
||||
|
||||
#: build.go:75
|
||||
msgid "Error initialization database"
|
||||
msgid "Error db init"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:104
|
||||
msgid "Package not found"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:124
|
||||
#: build.go:122
|
||||
msgid "Error pulling repositories"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:132
|
||||
#: build.go:130
|
||||
msgid "Unable to detect a supported package manager on the system"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:138
|
||||
#: build.go:136
|
||||
msgid "Error parsing os release"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:160
|
||||
#: build.go:157
|
||||
msgid "Error building package"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:167
|
||||
#: build.go:164
|
||||
msgid "Error getting working directory"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:176
|
||||
#: build.go:173
|
||||
msgid "Error moving the package"
|
||||
msgstr ""
|
||||
|
||||
@@ -66,27 +66,27 @@ msgstr ""
|
||||
msgid "Attempt to fix problems with ALR"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:43
|
||||
#: fix.go:44
|
||||
msgid "Removing cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:47
|
||||
#: fix.go:48
|
||||
msgid "Unable to remove cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:51
|
||||
#: fix.go:52
|
||||
msgid "Rebuilding cache"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:55
|
||||
#: fix.go:56
|
||||
msgid "Unable to create new cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:69
|
||||
#: fix.go:62
|
||||
msgid "Error pulling repos"
|
||||
msgstr ""
|
||||
|
||||
#: fix.go:73
|
||||
#: fix.go:66
|
||||
msgid "Done"
|
||||
msgstr ""
|
||||
|
||||
@@ -114,39 +114,35 @@ msgstr ""
|
||||
msgid "No such helper command"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:43
|
||||
#: info.go:42
|
||||
msgid "Print information about a package"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:48
|
||||
#: info.go:47
|
||||
msgid "Show all information, not just for the current distro"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:63
|
||||
msgid "Error getting packages"
|
||||
#: info.go:57
|
||||
msgid "Error initialization database"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:72
|
||||
msgid "Error iterating over packages"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:93
|
||||
#: info.go:64
|
||||
msgid "Command info expected at least 1 argument, got %d"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:107
|
||||
#: info.go:78
|
||||
msgid "Error finding packages"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:129
|
||||
#: info.go:94
|
||||
msgid "Error parsing os-release file"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:138
|
||||
#: info.go:103
|
||||
msgid "Error resolving overrides"
|
||||
msgstr ""
|
||||
|
||||
#: info.go:147 info.go:153
|
||||
#: info.go:112 info.go:118
|
||||
msgid "Error encoding script variables"
|
||||
msgstr ""
|
||||
|
||||
@@ -158,15 +154,23 @@ msgstr ""
|
||||
msgid "Command install expected at least 1 argument, got %d"
|
||||
msgstr ""
|
||||
|
||||
#: install.go:151
|
||||
#: install.go:124
|
||||
msgid "Error getting packages"
|
||||
msgstr ""
|
||||
|
||||
#: install.go:133
|
||||
msgid "Error iterating over packages"
|
||||
msgstr ""
|
||||
|
||||
#: install.go:146
|
||||
msgid "Remove an installed package"
|
||||
msgstr ""
|
||||
|
||||
#: install.go:156
|
||||
#: install.go:151
|
||||
msgid "Command remove expected at least 1 argument, got %d"
|
||||
msgstr ""
|
||||
|
||||
#: install.go:168
|
||||
#: install.go:163
|
||||
msgid "Error removing packages"
|
||||
msgstr ""
|
||||
|
||||
@@ -194,98 +198,46 @@ msgstr ""
|
||||
msgid "Choose which optional package(s) to install"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:93
|
||||
msgid "NAME"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:94
|
||||
msgid "USAGE"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "global options"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "command"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:95
|
||||
msgid "command options"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:96
|
||||
msgid "arguments"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "VERSION"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:98
|
||||
msgid "DESCRIPTION"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "AUTHOR"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "COMMANDS"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "GLOBAL OPTIONS"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "COPYRIGHT"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:97
|
||||
msgid "CATEGORY"
|
||||
msgstr ""
|
||||
|
||||
#: internal/cliutils/template.go:99 internal/cliutils/template.go:100
|
||||
msgid "OPTIONS"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:59
|
||||
#: internal/config/config.go:64
|
||||
msgid "Error opening config file, using defaults"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:72
|
||||
#: internal/config/config.go:77
|
||||
msgid "Error decoding config file, using defaults"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:84
|
||||
#: internal/config/config.go:89
|
||||
msgid "Unable to detect user config directory"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:92
|
||||
#: internal/config/config.go:97
|
||||
msgid "Unable to create ALR config directory"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:101
|
||||
#: internal/config/config.go:106
|
||||
msgid "Unable to create ALR config file"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:107
|
||||
#: internal/config/config.go:112
|
||||
msgid "Error encoding default configuration"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:116
|
||||
#: internal/config/config.go:121
|
||||
msgid "Unable to detect cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:126
|
||||
#: internal/config/config.go:131
|
||||
msgid "Unable to create repo cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/config.go:132
|
||||
#: internal/config/config.go:137
|
||||
msgid "Unable to create package cache directory"
|
||||
msgstr ""
|
||||
|
||||
#: internal/config/lang.go:49
|
||||
msgid "Error parsing system language"
|
||||
msgstr ""
|
||||
|
||||
#: internal/db/db.go:133
|
||||
msgid "Database version mismatch; resetting"
|
||||
msgstr ""
|
||||
@@ -295,6 +247,10 @@ msgid ""
|
||||
"Database version does not exist. Run alr fix if something isn't working."
|
||||
msgstr ""
|
||||
|
||||
#: internal/db/db_legacy.go:101
|
||||
msgid "Error opening database"
|
||||
msgstr ""
|
||||
|
||||
#: internal/dl/dl.go:170
|
||||
msgid "Source can be updated, updating if required"
|
||||
msgstr ""
|
||||
@@ -323,11 +279,11 @@ msgstr ""
|
||||
msgid "ERROR"
|
||||
msgstr ""
|
||||
|
||||
#: list.go:41
|
||||
#: list.go:40
|
||||
msgid "List ALR repo packages"
|
||||
msgstr ""
|
||||
|
||||
#: list.go:92
|
||||
#: list.go:91
|
||||
msgid "Error listing installed packages"
|
||||
msgstr ""
|
||||
|
||||
@@ -343,94 +299,90 @@ msgstr ""
|
||||
msgid "Enable interactive questions and prompts"
|
||||
msgstr ""
|
||||
|
||||
#: main.go:92
|
||||
#: main.go:90
|
||||
msgid ""
|
||||
"Running ALR as root is forbidden as it may cause catastrophic damage to your "
|
||||
"system"
|
||||
msgstr ""
|
||||
|
||||
#: main.go:125
|
||||
msgid "Show help"
|
||||
msgstr ""
|
||||
|
||||
#: main.go:129
|
||||
#: main.go:124
|
||||
msgid "Error while running app"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:156
|
||||
#: pkg/build/build.go:135
|
||||
msgid "Failed to prompt user to view build script"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:160
|
||||
#: pkg/build/build.go:139
|
||||
msgid "Building package"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:208
|
||||
msgid "The checksums array must be the same length as sources"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:235
|
||||
#: pkg/build/build.go:183
|
||||
msgid "Downloading sources"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:257
|
||||
#: pkg/build/build.go:195
|
||||
msgid "Building package metadata"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:279
|
||||
#: pkg/build/build.go:217
|
||||
msgid "Compressing package"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:438
|
||||
#: pkg/build/build.go:359
|
||||
msgid ""
|
||||
"Your system's CPU architecture doesn't match this package. Do you want to "
|
||||
"build anyway?"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:452
|
||||
#: pkg/build/build.go:373
|
||||
msgid "This package is already installed"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:476
|
||||
#: pkg/build/build.go:397
|
||||
msgid "Installing build dependencies"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:517
|
||||
#: pkg/build/build.go:408
|
||||
msgid "Installing dependencies"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:598
|
||||
#: pkg/build/build.go:449
|
||||
msgid "The checksums array must be the same length as sources"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:500
|
||||
msgid "Would you like to remove the build dependencies?"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:661
|
||||
#: pkg/build/build.go:537
|
||||
msgid "Executing version()"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:557
|
||||
msgid "Updating version"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:562
|
||||
msgid "Executing prepare()"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:671
|
||||
#: pkg/build/build.go:572
|
||||
msgid "Executing build()"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:701 pkg/build/build.go:721
|
||||
#: pkg/build/build.go:588 pkg/build/build.go:616
|
||||
msgid "Executing %s()"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:780
|
||||
#: pkg/build/build.go:675
|
||||
msgid "Error installing native packages"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:804
|
||||
#: pkg/build/build.go:701
|
||||
msgid "Error installing package"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:863
|
||||
msgid "AutoProv is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/build.go:874
|
||||
msgid "AutoReq is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/findDeps.go:35
|
||||
msgid "Command not found on the system"
|
||||
msgstr ""
|
||||
@@ -443,6 +395,14 @@ msgstr ""
|
||||
msgid "Required dependency found"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/utils.go:136
|
||||
msgid "AutoProv is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/build/utils.go:147
|
||||
msgid "AutoReq is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
|
||||
#: pkg/repos/pull.go:79
|
||||
msgid "Pulling repository"
|
||||
msgstr ""
|
||||
@@ -473,70 +433,38 @@ msgstr ""
|
||||
msgid "URL of the new repo"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:82 repo.go:147
|
||||
#: repo.go:79 repo.go:136
|
||||
msgid "Error opening config file"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:88 repo.go:153
|
||||
#: repo.go:85 repo.go:142
|
||||
msgid "Error encoding config"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:113
|
||||
#: repo.go:103
|
||||
msgid "Remove an existing repository"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:120
|
||||
#: repo.go:110
|
||||
msgid "Name of the repo to be deleted"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:139
|
||||
#: repo.go:128
|
||||
msgid "Repo does not exist"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:159
|
||||
#: repo.go:148
|
||||
msgid "Error removing repo directory"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:170
|
||||
#: repo.go:154
|
||||
msgid "Error removing packages from database"
|
||||
msgstr ""
|
||||
|
||||
#: repo.go:182
|
||||
#: repo.go:166
|
||||
msgid "Pull all repositories that have changed"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:36
|
||||
msgid "Search packages"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:42
|
||||
msgid "Search by name"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:47
|
||||
msgid "Search by description"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:52
|
||||
msgid "Search by repository"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:57
|
||||
msgid "Search by provides"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:62
|
||||
msgid "Format output using a Go template"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:82 search.go:99
|
||||
msgid "Error parsing format template"
|
||||
msgstr ""
|
||||
|
||||
#: search.go:107
|
||||
msgid "Error executing template"
|
||||
msgstr ""
|
||||
|
||||
#: upgrade.go:47
|
||||
msgid "Upgrade all installed packages"
|
||||
msgstr ""
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#
|
||||
# x1z53 <x1z53@yandex.ru>, 2025.
|
||||
# Maxim Slipenko <maks1ms@alt-gnome.ru>, 2025.
|
||||
# x1z53 <x1z53@yandex.ru>, 2025.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: unnamed project\n"
|
||||
"PO-Revision-Date: 2025-03-09 17:31+0300\n"
|
||||
"Last-Translator: Maxim Slipenko <maks1ms@alt-gnome.ru>\n"
|
||||
"PO-Revision-Date: 2025-01-24 21:20+0300\n"
|
||||
"Last-Translator: x1z53 <x1z53@yandex.ru>\n"
|
||||
"Language-Team: Russian\n"
|
||||
"Language: ru\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
@@ -25,8 +25,8 @@ msgid "Path to the build script"
|
||||
msgstr "Путь к скрипту сборки"
|
||||
|
||||
#: build.go:55
|
||||
msgid "Specify subpackage in script (for multi package script only)"
|
||||
msgstr "Укажите подпакет в скрипте (только для многопакетного скрипта)"
|
||||
msgid "Specify package in script (for multi package script only)"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:60
|
||||
msgid "Name of the package to build and its repo (example: default/go-bin)"
|
||||
@@ -38,34 +38,35 @@ msgid ""
|
||||
msgstr "Создайте пакет с нуля, даже если уже имеется готовый пакет"
|
||||
|
||||
#: build.go:75
|
||||
msgid "Error initialization database"
|
||||
msgstr "Ошибка инициализации базы данных"
|
||||
msgid "Error db init"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:104
|
||||
msgid "Package not found"
|
||||
msgstr "Пакет не найден"
|
||||
msgstr ""
|
||||
|
||||
#: build.go:124
|
||||
#: build.go:122
|
||||
msgid "Error pulling repositories"
|
||||
msgstr "Ошибка при извлечении репозиториев"
|
||||
|
||||
#: build.go:132
|
||||
#: build.go:130
|
||||
msgid "Unable to detect a supported package manager on the system"
|
||||
msgstr "Не удалось обнаружить поддерживаемый менеджер пакетов в системе"
|
||||
|
||||
#: build.go:138
|
||||
#: build.go:136
|
||||
#, fuzzy
|
||||
msgid "Error parsing os release"
|
||||
msgstr "Ошибка при разборе файла выпуска операционной системы"
|
||||
|
||||
#: build.go:160
|
||||
#: build.go:157
|
||||
msgid "Error building package"
|
||||
msgstr "Ошибка при сборке пакета"
|
||||
|
||||
#: build.go:167
|
||||
#: build.go:164
|
||||
msgid "Error getting working directory"
|
||||
msgstr "Ошибка при получении рабочего каталога"
|
||||
|
||||
#: build.go:176
|
||||
#: build.go:173
|
||||
msgid "Error moving the package"
|
||||
msgstr "Ошибка при перемещении пакета"
|
||||
|
||||
@@ -73,27 +74,27 @@ msgstr "Ошибка при перемещении пакета"
|
||||
msgid "Attempt to fix problems with ALR"
|
||||
msgstr "Попытка устранить проблемы с ALR"
|
||||
|
||||
#: fix.go:43
|
||||
#: fix.go:44
|
||||
msgid "Removing cache directory"
|
||||
msgstr "Удаление каталога кэша"
|
||||
|
||||
#: fix.go:47
|
||||
#: fix.go:48
|
||||
msgid "Unable to remove cache directory"
|
||||
msgstr "Не удалось удалить каталог кэша"
|
||||
|
||||
#: fix.go:51
|
||||
#: fix.go:52
|
||||
msgid "Rebuilding cache"
|
||||
msgstr "Восстановление кэша"
|
||||
|
||||
#: fix.go:55
|
||||
#: fix.go:56
|
||||
msgid "Unable to create new cache directory"
|
||||
msgstr "Не удалось создать новый каталог кэша"
|
||||
|
||||
#: fix.go:69
|
||||
#: fix.go:62
|
||||
msgid "Error pulling repos"
|
||||
msgstr "Ошибка при извлечении репозиториев"
|
||||
|
||||
#: fix.go:73
|
||||
#: fix.go:66
|
||||
msgid "Done"
|
||||
msgstr "Сделано"
|
||||
|
||||
@@ -121,39 +122,35 @@ msgstr "Каталог, в который будут устанавливать
|
||||
msgid "No such helper command"
|
||||
msgstr "Такой вспомогательной команды нет"
|
||||
|
||||
#: info.go:43
|
||||
#: info.go:42
|
||||
msgid "Print information about a package"
|
||||
msgstr "Отобразить информацию о пакете"
|
||||
|
||||
#: info.go:48
|
||||
#: info.go:47
|
||||
msgid "Show all information, not just for the current distro"
|
||||
msgstr "Показывать всю информацию, не только для текущего дистрибутива"
|
||||
|
||||
#: info.go:63
|
||||
msgid "Error getting packages"
|
||||
msgstr "Ошибка при получении пакетов"
|
||||
#: info.go:57
|
||||
msgid "Error initialization database"
|
||||
msgstr "Ошибка инициализации базы данных"
|
||||
|
||||
#: info.go:72
|
||||
msgid "Error iterating over packages"
|
||||
msgstr "Ошибка при переборе пакетов"
|
||||
|
||||
#: info.go:93
|
||||
#: info.go:64
|
||||
msgid "Command info expected at least 1 argument, got %d"
|
||||
msgstr "Для команды info ожидался хотя бы 1 аргумент, получено %d"
|
||||
|
||||
#: info.go:107
|
||||
#: info.go:78
|
||||
msgid "Error finding packages"
|
||||
msgstr "Ошибка при поиске пакетов"
|
||||
|
||||
#: info.go:129
|
||||
#: info.go:94
|
||||
msgid "Error parsing os-release file"
|
||||
msgstr "Ошибка при разборе файла выпуска операционной системы"
|
||||
|
||||
#: info.go:138
|
||||
#: info.go:103
|
||||
msgid "Error resolving overrides"
|
||||
msgstr "Ошибка устранения переорпеделений"
|
||||
|
||||
#: info.go:147 info.go:153
|
||||
#: info.go:112 info.go:118
|
||||
msgid "Error encoding script variables"
|
||||
msgstr "Ошибка кодирования переменных скрита"
|
||||
|
||||
@@ -165,15 +162,23 @@ msgstr "Установить новый пакет"
|
||||
msgid "Command install expected at least 1 argument, got %d"
|
||||
msgstr "Для команды install ожидался хотя бы 1 аргумент, получено %d"
|
||||
|
||||
#: install.go:151
|
||||
#: install.go:124
|
||||
msgid "Error getting packages"
|
||||
msgstr "Ошибка при получении пакетов"
|
||||
|
||||
#: install.go:133
|
||||
msgid "Error iterating over packages"
|
||||
msgstr "Ошибка при переборе пакетов"
|
||||
|
||||
#: install.go:146
|
||||
msgid "Remove an installed package"
|
||||
msgstr "Удалить установленный пакет"
|
||||
|
||||
#: install.go:156
|
||||
#: install.go:151
|
||||
msgid "Command remove expected at least 1 argument, got %d"
|
||||
msgstr "Для команды remove ожидался хотя бы 1 аргумент, получено %d"
|
||||
|
||||
#: install.go:168
|
||||
#: install.go:163
|
||||
msgid "Error removing packages"
|
||||
msgstr "Ошибка при удалении пакетов"
|
||||
|
||||
@@ -201,102 +206,50 @@ msgstr "Выберите, какой пакет использовать для
|
||||
msgid "Choose which optional package(s) to install"
|
||||
msgstr "Выберите, какой дополнительный пакет(ы) следует установить"
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:93
|
||||
msgid "NAME"
|
||||
msgstr "НАЗВАНИЕ"
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:94
|
||||
msgid "USAGE"
|
||||
msgstr "ИСПОЛЬЗОВАНИЕ"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "global options"
|
||||
msgstr "глобальные опции"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "command"
|
||||
msgstr "команда"
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:95
|
||||
msgid "command options"
|
||||
msgstr "опции команды"
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:96
|
||||
msgid "arguments"
|
||||
msgstr "аргументы"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "VERSION"
|
||||
msgstr "ВЕРСИЯ"
|
||||
|
||||
#: internal/cliutils/template.go:74 internal/cliutils/template.go:98
|
||||
msgid "DESCRIPTION"
|
||||
msgstr "ОПИСАНИЕ"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "AUTHOR"
|
||||
msgstr "АВТОР"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "COMMANDS"
|
||||
msgstr "КОМАНДЫ"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "GLOBAL OPTIONS"
|
||||
msgstr "ГЛОБАЛЬНЫЕ ОПЦИИ"
|
||||
|
||||
#: internal/cliutils/template.go:74
|
||||
msgid "COPYRIGHT"
|
||||
msgstr "АВТОРСКОЕ ПРАВО"
|
||||
|
||||
#: internal/cliutils/template.go:97
|
||||
msgid "CATEGORY"
|
||||
msgstr "КАТЕГОРИЯ"
|
||||
|
||||
#: internal/cliutils/template.go:99 internal/cliutils/template.go:100
|
||||
msgid "OPTIONS"
|
||||
msgstr "ПАРАМЕТРЫ"
|
||||
|
||||
#: internal/config/config.go:59
|
||||
#: internal/config/config.go:64
|
||||
msgid "Error opening config file, using defaults"
|
||||
msgstr ""
|
||||
"Ошибка при открытии конфигурационного файла, используются значения по "
|
||||
"умолчанию"
|
||||
|
||||
#: internal/config/config.go:72
|
||||
#: internal/config/config.go:77
|
||||
msgid "Error decoding config file, using defaults"
|
||||
msgstr ""
|
||||
"Ошибка при декодировании конфигурационного файла, используются значения по "
|
||||
"умолчанию"
|
||||
|
||||
#: internal/config/config.go:84
|
||||
#: internal/config/config.go:89
|
||||
msgid "Unable to detect user config directory"
|
||||
msgstr "Не удалось обнаружить каталог конфигурации пользователя"
|
||||
|
||||
#: internal/config/config.go:92
|
||||
#: internal/config/config.go:97
|
||||
msgid "Unable to create ALR config directory"
|
||||
msgstr "Не удалось создать каталог конфигурации ALR"
|
||||
|
||||
#: internal/config/config.go:101
|
||||
#: internal/config/config.go:106
|
||||
msgid "Unable to create ALR config file"
|
||||
msgstr "Не удалось создать конфигурационный файл ALR"
|
||||
|
||||
#: internal/config/config.go:107
|
||||
#: internal/config/config.go:112
|
||||
msgid "Error encoding default configuration"
|
||||
msgstr "Ошибка кодирования конфигурации по умолчанию"
|
||||
|
||||
#: internal/config/config.go:116
|
||||
#: internal/config/config.go:121
|
||||
msgid "Unable to detect cache directory"
|
||||
msgstr "Не удалось обнаружить каталог кэша"
|
||||
|
||||
#: internal/config/config.go:126
|
||||
#: internal/config/config.go:131
|
||||
msgid "Unable to create repo cache directory"
|
||||
msgstr "Не удалось создать каталог кэша репозитория"
|
||||
|
||||
#: internal/config/config.go:132
|
||||
#: internal/config/config.go:137
|
||||
msgid "Unable to create package cache directory"
|
||||
msgstr "Не удалось создать каталог кэша пакетов"
|
||||
|
||||
#: internal/config/lang.go:49
|
||||
msgid "Error parsing system language"
|
||||
msgstr "Ошибка при парсинге языка системы"
|
||||
|
||||
#: internal/db/db.go:133
|
||||
msgid "Database version mismatch; resetting"
|
||||
msgstr "Несоответствие версий базы данных; сброс настроек"
|
||||
@@ -307,6 +260,10 @@ msgid ""
|
||||
msgstr ""
|
||||
"Версия базы данных не существует. Запустите alr fix, если что-то не работает."
|
||||
|
||||
#: internal/db/db_legacy.go:101
|
||||
msgid "Error opening database"
|
||||
msgstr "Ошибка при открытии базы данных"
|
||||
|
||||
#: internal/dl/dl.go:170
|
||||
msgid "Source can be updated, updating if required"
|
||||
msgstr "Исходный код можно обновлять, обновляя при необходимости"
|
||||
@@ -325,21 +282,21 @@ msgstr "Скачивание источника"
|
||||
|
||||
#: internal/dl/progress_tui.go:100
|
||||
msgid "%s: done!\n"
|
||||
msgstr "%s: выполнено!\n"
|
||||
msgstr ""
|
||||
|
||||
#: internal/dl/progress_tui.go:104
|
||||
msgid "%s %s downloading at %s/s\n"
|
||||
msgstr "%s %s загружается — %s/с\n"
|
||||
msgstr ""
|
||||
|
||||
#: internal/logger/log.go:47
|
||||
msgid "ERROR"
|
||||
msgstr "ОШИБКА"
|
||||
|
||||
#: list.go:41
|
||||
#: list.go:40
|
||||
msgid "List ALR repo packages"
|
||||
msgstr "Список пакетов репозитория ALR"
|
||||
|
||||
#: list.go:92
|
||||
#: list.go:91
|
||||
msgid "Error listing installed packages"
|
||||
msgstr "Ошибка при составлении списка установленных пакетов"
|
||||
|
||||
@@ -355,7 +312,7 @@ msgstr "Аргументы, которые будут переданы мене
|
||||
msgid "Enable interactive questions and prompts"
|
||||
msgstr "Включение интерактивных вопросов и запросов"
|
||||
|
||||
#: main.go:92
|
||||
#: main.go:90
|
||||
msgid ""
|
||||
"Running ALR as root is forbidden as it may cause catastrophic damage to your "
|
||||
"system"
|
||||
@@ -363,39 +320,31 @@ msgstr ""
|
||||
"Запуск ALR от имени root запрещён, так как это может привести к "
|
||||
"катастрофическому повреждению вашей системы"
|
||||
|
||||
#: main.go:125
|
||||
msgid "Show help"
|
||||
msgstr "Показать справку"
|
||||
|
||||
#: main.go:129
|
||||
#: main.go:124
|
||||
msgid "Error while running app"
|
||||
msgstr "Ошибка при запуске приложения"
|
||||
|
||||
#: pkg/build/build.go:156
|
||||
#: pkg/build/build.go:135
|
||||
msgid "Failed to prompt user to view build script"
|
||||
msgstr "Не удалось предложить пользователю просмотреть скрипт сборки"
|
||||
|
||||
#: pkg/build/build.go:160
|
||||
#: pkg/build/build.go:139
|
||||
msgid "Building package"
|
||||
msgstr "Сборка пакета"
|
||||
|
||||
#: pkg/build/build.go:208
|
||||
msgid "The checksums array must be the same length as sources"
|
||||
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
|
||||
|
||||
#: pkg/build/build.go:235
|
||||
#: pkg/build/build.go:183
|
||||
msgid "Downloading sources"
|
||||
msgstr "Скачивание источников"
|
||||
|
||||
#: pkg/build/build.go:257
|
||||
#: pkg/build/build.go:195
|
||||
msgid "Building package metadata"
|
||||
msgstr "Сборка метаданных пакета"
|
||||
|
||||
#: pkg/build/build.go:279
|
||||
#: pkg/build/build.go:217
|
||||
msgid "Compressing package"
|
||||
msgstr "Сжатие пакета"
|
||||
|
||||
#: pkg/build/build.go:438
|
||||
#: pkg/build/build.go:359
|
||||
msgid ""
|
||||
"Your system's CPU architecture doesn't match this package. Do you want to "
|
||||
"build anyway?"
|
||||
@@ -403,52 +352,55 @@ msgstr ""
|
||||
"Архитектура процессора вашей системы не соответствует этому пакету. Вы все "
|
||||
"равно хотите выполнить сборку?"
|
||||
|
||||
#: pkg/build/build.go:452
|
||||
#: pkg/build/build.go:373
|
||||
msgid "This package is already installed"
|
||||
msgstr "Этот пакет уже установлен"
|
||||
|
||||
#: pkg/build/build.go:476
|
||||
#: pkg/build/build.go:397
|
||||
msgid "Installing build dependencies"
|
||||
msgstr "Установка зависимостей сборки"
|
||||
|
||||
#: pkg/build/build.go:517
|
||||
#: pkg/build/build.go:408
|
||||
msgid "Installing dependencies"
|
||||
msgstr "Установка зависимостей"
|
||||
|
||||
#: pkg/build/build.go:598
|
||||
#: pkg/build/build.go:449
|
||||
msgid "The checksums array must be the same length as sources"
|
||||
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
|
||||
|
||||
#: pkg/build/build.go:500
|
||||
msgid "Would you like to remove the build dependencies?"
|
||||
msgstr "Хотели бы вы удалить зависимости сборки?"
|
||||
|
||||
#: pkg/build/build.go:661
|
||||
#: pkg/build/build.go:537
|
||||
msgid "Executing version()"
|
||||
msgstr "Исполнение версия()"
|
||||
|
||||
#: pkg/build/build.go:557
|
||||
msgid "Updating version"
|
||||
msgstr "Обновление версии"
|
||||
|
||||
#: pkg/build/build.go:562
|
||||
msgid "Executing prepare()"
|
||||
msgstr "Исполнение prepare()"
|
||||
|
||||
#: pkg/build/build.go:671
|
||||
#: pkg/build/build.go:572
|
||||
msgid "Executing build()"
|
||||
msgstr "Исполнение build()"
|
||||
|
||||
#: pkg/build/build.go:701 pkg/build/build.go:721
|
||||
#: pkg/build/build.go:588 pkg/build/build.go:616
|
||||
#, fuzzy
|
||||
msgid "Executing %s()"
|
||||
msgstr "Исполнение %s()"
|
||||
msgstr "Исполнение files()"
|
||||
|
||||
#: pkg/build/build.go:780
|
||||
#: pkg/build/build.go:675
|
||||
msgid "Error installing native packages"
|
||||
msgstr "Ошибка при установке нативных пакетов"
|
||||
|
||||
#: pkg/build/build.go:804
|
||||
#: pkg/build/build.go:701
|
||||
msgid "Error installing package"
|
||||
msgstr "Ошибка при установке пакета"
|
||||
|
||||
#: pkg/build/build.go:863
|
||||
msgid "AutoProv is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
"AutoProv не реализовано для этого формата пакета, поэтому будет пропущено"
|
||||
|
||||
#: pkg/build/build.go:874
|
||||
msgid "AutoReq is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
"AutoReq не реализовано для этого формата пакета, поэтому будет пропущено"
|
||||
|
||||
#: pkg/build/findDeps.go:35
|
||||
msgid "Command not found on the system"
|
||||
msgstr "Команда не найдена в системе"
|
||||
@@ -461,6 +413,16 @@ msgstr "Найденная предоставленная зависимость
|
||||
msgid "Required dependency found"
|
||||
msgstr "Найдена требуемая зависимость"
|
||||
|
||||
#: pkg/build/utils.go:136
|
||||
msgid "AutoProv is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
"AutoProv не реализовано для этого формата пакета, поэтому будет пропущено"
|
||||
|
||||
#: pkg/build/utils.go:147
|
||||
msgid "AutoReq is not implemented for this package format, so it's skipped"
|
||||
msgstr ""
|
||||
"AutoReq не реализовано для этого формата пакета, поэтому будет пропущено"
|
||||
|
||||
#: pkg/repos/pull.go:79
|
||||
msgid "Pulling repository"
|
||||
msgstr "Скачивание репозитория"
|
||||
@@ -493,70 +455,38 @@ msgstr "Название нового репозитория"
|
||||
msgid "URL of the new repo"
|
||||
msgstr "URL-адрес нового репозитория"
|
||||
|
||||
#: repo.go:82 repo.go:147
|
||||
#: repo.go:79 repo.go:136
|
||||
msgid "Error opening config file"
|
||||
msgstr "Ошибка при открытии конфигурационного файла"
|
||||
|
||||
#: repo.go:88 repo.go:153
|
||||
#: repo.go:85 repo.go:142
|
||||
msgid "Error encoding config"
|
||||
msgstr "Ошибка при кодировании конфигурации"
|
||||
|
||||
#: repo.go:113
|
||||
#: repo.go:103
|
||||
msgid "Remove an existing repository"
|
||||
msgstr "Удалить существующий репозиторий"
|
||||
|
||||
#: repo.go:120
|
||||
#: repo.go:110
|
||||
msgid "Name of the repo to be deleted"
|
||||
msgstr "Название репозитория удалён"
|
||||
|
||||
#: repo.go:139
|
||||
#: repo.go:128
|
||||
msgid "Repo does not exist"
|
||||
msgstr "Репозитория не существует"
|
||||
|
||||
#: repo.go:159
|
||||
#: repo.go:148
|
||||
msgid "Error removing repo directory"
|
||||
msgstr "Ошибка при удалении каталога репозитория"
|
||||
|
||||
#: repo.go:170
|
||||
#: repo.go:154
|
||||
msgid "Error removing packages from database"
|
||||
msgstr "Ошибка при удалении пакетов из базы данных"
|
||||
|
||||
#: repo.go:182
|
||||
#: repo.go:166
|
||||
msgid "Pull all repositories that have changed"
|
||||
msgstr "Скачать все изменённые репозитории"
|
||||
|
||||
#: search.go:36
|
||||
msgid "Search packages"
|
||||
msgstr "Поиск пакетов"
|
||||
|
||||
#: search.go:42
|
||||
msgid "Search by name"
|
||||
msgstr "Искать по имени"
|
||||
|
||||
#: search.go:47
|
||||
msgid "Search by description"
|
||||
msgstr "Искать по описанию"
|
||||
|
||||
#: search.go:52
|
||||
msgid "Search by repository"
|
||||
msgstr "Искать по репозиторию"
|
||||
|
||||
#: search.go:57
|
||||
msgid "Search by provides"
|
||||
msgstr "Иcкать по provides"
|
||||
|
||||
#: search.go:62
|
||||
msgid "Format output using a Go template"
|
||||
msgstr "Формат выходных данных с использованием шаблона Go"
|
||||
|
||||
#: search.go:82 search.go:99
|
||||
msgid "Error parsing format template"
|
||||
msgstr "Ошибка при разборе шаблона"
|
||||
|
||||
#: search.go:107
|
||||
msgid "Error executing template"
|
||||
msgstr "Ошибка при выполнении шаблона"
|
||||
|
||||
#: upgrade.go:47
|
||||
msgid "Upgrade all installed packages"
|
||||
msgstr "Обновить все установленные пакеты"
|
||||
@@ -569,17 +499,5 @@ msgstr "Ошибка при проверке обновлений"
|
||||
msgid "There is nothing to do."
|
||||
msgstr "Здесь нечего делать."
|
||||
|
||||
#~ msgid "Error parsing system language"
|
||||
#~ msgstr "Ошибка при парсинге языка системы"
|
||||
|
||||
#~ msgid "Error opening database"
|
||||
#~ msgstr "Ошибка при открытии базы данных"
|
||||
|
||||
#~ msgid "Executing version()"
|
||||
#~ msgstr "Исполнение версия()"
|
||||
|
||||
#~ msgid "Updating version"
|
||||
#~ msgstr "Обновление версии"
|
||||
|
||||
#~ msgid "Executing package()"
|
||||
#~ msgstr "Исполнение package()"
|
||||
|
||||
@@ -23,8 +23,7 @@ import "gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
|
||||
|
||||
type BuildOpts struct {
|
||||
Script string
|
||||
Repository string
|
||||
Packages []string
|
||||
Package string
|
||||
Manager manager.Manager
|
||||
Clean bool
|
||||
Interactive bool
|
||||
@@ -103,7 +102,6 @@ type BuildVars struct {
|
||||
Scripts Scripts `sh:"scripts"`
|
||||
AutoReq []string `sh:"auto_req"`
|
||||
AutoProv []string `sh:"auto_prov"`
|
||||
Base string
|
||||
}
|
||||
|
||||
type Scripts struct {
|
||||
|
||||
16
list.go
16
list.go
@@ -30,7 +30,6 @@ import (
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
|
||||
)
|
||||
@@ -79,7 +78,7 @@ func ListCmd() *cli.Command {
|
||||
}
|
||||
defer result.Close()
|
||||
|
||||
installedAlrPackages := map[string]string{}
|
||||
var installed map[string]string
|
||||
if c.Bool("installed") {
|
||||
mgr := manager.Detect()
|
||||
if mgr == nil {
|
||||
@@ -87,20 +86,11 @@ func ListCmd() *cli.Command {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
installed, err := mgr.ListInstalled(&manager.Opts{AsRoot: false})
|
||||
installed, err = mgr.ListInstalled(&manager.Opts{AsRoot: false})
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error listing installed packages"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for pkgName, version := range installed {
|
||||
matches := build.RegexpALRPackageName.FindStringSubmatch(pkgName)
|
||||
if matches != nil {
|
||||
packageName := matches[build.RegexpALRPackageName.SubexpIndex("package")]
|
||||
repoName := matches[build.RegexpALRPackageName.SubexpIndex("repo")]
|
||||
installedAlrPackages[fmt.Sprintf("%s/%s", repoName, packageName)] = version
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for result.Next() {
|
||||
@@ -116,7 +106,7 @@ func ListCmd() *cli.Command {
|
||||
|
||||
version := pkg.Version
|
||||
if c.Bool("installed") {
|
||||
instVersion, ok := installedAlrPackages[fmt.Sprintf("%s/%s", pkg.Repository, pkg.Name)]
|
||||
instVersion, ok := installed[pkg.Name]
|
||||
if !ok {
|
||||
continue
|
||||
} else {
|
||||
|
||||
17
main.go
17
main.go
@@ -31,8 +31,8 @@ import (
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"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/internal/translations"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
|
||||
|
||||
@@ -81,14 +81,12 @@ func GetApp() *cli.App {
|
||||
GenCmd(),
|
||||
HelperCmd(),
|
||||
VersionCmd(),
|
||||
SearchCmd(),
|
||||
},
|
||||
Before: func(c *cli.Context) error {
|
||||
ctx := c.Context
|
||||
cfg := config.New()
|
||||
|
||||
cmd := c.Args().First()
|
||||
if cmd != "helper" && !cfg.AllowRunAsRoot(ctx) && os.Geteuid() == 0 {
|
||||
if cmd != "helper" && !config.Config(ctx).Unsafe.AllowRunAsRoot && os.Geteuid() == 0 {
|
||||
slog.Error(gotext.Get("Running ALR as root is forbidden as it may cause catastrophic damage to your system"))
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -100,6 +98,9 @@ func GetApp() *cli.App {
|
||||
|
||||
return nil
|
||||
},
|
||||
After: func(ctx *cli.Context) error {
|
||||
return db.Close()
|
||||
},
|
||||
EnableBashCompletion: true,
|
||||
}
|
||||
}
|
||||
@@ -109,21 +110,15 @@ func main() {
|
||||
logger.SetupDefault()
|
||||
|
||||
app := GetApp()
|
||||
cfg := config.New()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set the root command to the one set in the ALR config
|
||||
manager.DefaultRootCmd = cfg.RootCmd(ctx)
|
||||
manager.DefaultRootCmd = config.Config(ctx).RootCmd
|
||||
|
||||
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
// Make the application more internationalized
|
||||
cli.AppHelpTemplate = cliutils.GetAppCliTemplate()
|
||||
cli.CommandHelpTemplate = cliutils.GetCommandHelpTemplate()
|
||||
cli.HelpFlag.(*cli.BoolFlag).Usage = gotext.Get("Show help")
|
||||
|
||||
err := app.RunContext(ctx, os.Args)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error while running app"), "err", err)
|
||||
|
||||
@@ -28,8 +28,6 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -87,12 +85,11 @@ func NewBuilder(
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Builder) UpdateOptsFromPkg(pkg *db.Package, packages []string) {
|
||||
func (b *Builder) UpdateOptsFromPkg(pkg *db.Package) {
|
||||
repodir := b.config.GetPaths(b.ctx).RepoDir
|
||||
b.opts.Repository = pkg.Repository
|
||||
if pkg.BasePkgName != "" {
|
||||
b.opts.Script = filepath.Join(repodir, pkg.Repository, pkg.BasePkgName, "alr.sh")
|
||||
b.opts.Packages = packages
|
||||
b.opts.Package = pkg.Name
|
||||
} else {
|
||||
b.opts.Script = filepath.Join(repodir, pkg.Repository, pkg.Name, "alr.sh")
|
||||
}
|
||||
@@ -106,41 +103,23 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
|
||||
// Первый проход предназначен для получения значений переменных и выполняется
|
||||
// до отображения скрипта, чтобы предотвратить выполнение вредоносного кода.
|
||||
basePkg, varsOfPackages, err := b.executeFirstPass(fl)
|
||||
vars, err := b.executeFirstPass(fl)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
dirs, err := b.getDirs(basePkg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
builtPaths := make([]string, 0)
|
||||
dirs := b.getDirs(vars)
|
||||
|
||||
// Если флаг opts.Clean не установлен, и пакет уже собран,
|
||||
// возвращаем его, а не собираем заново.
|
||||
if !b.opts.Clean {
|
||||
var remainingVars []*types.BuildVars
|
||||
for _, vars := range varsOfPackages {
|
||||
builtPkgPath, ok, err := b.checkForBuiltPackage(
|
||||
vars,
|
||||
getPkgFormat(b.opts.Manager),
|
||||
dirs.BaseDir,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
builtPaths = append(builtPaths, builtPkgPath)
|
||||
} else {
|
||||
remainingVars = append(remainingVars, vars)
|
||||
}
|
||||
builtPkgPath, ok, err := checkForBuiltPackage(b.opts.Manager, vars, getPkgFormat(b.opts.Manager), dirs.BaseDir)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if len(remainingVars) == 0 {
|
||||
return builtPaths, nil, nil
|
||||
if ok {
|
||||
return []string{builtPkgPath}, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +127,7 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
err = cliutils.PromptViewScript(
|
||||
ctx,
|
||||
b.opts.Script,
|
||||
basePkg,
|
||||
vars.Name,
|
||||
b.config.PagerStyle(ctx),
|
||||
b.opts.Interactive,
|
||||
)
|
||||
@@ -157,7 +136,7 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
slog.Info(gotext.Get("Building package"), "name", basePkg)
|
||||
slog.Info(gotext.Get("Building package"), "name", vars.Name, "version", vars.Version)
|
||||
|
||||
// Второй проход будет использоваться для выполнения реального кода,
|
||||
// поэтому он не ограничен. Скрипт уже был показан
|
||||
@@ -173,13 +152,11 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for _, vars := range varsOfPackages {
|
||||
cont, err := b.performChecks(ctx, vars, installed) // Выполняем различные проверки
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
} else if !cont {
|
||||
os.Exit(1) // Если проверки не пройдены, выходим из программы
|
||||
}
|
||||
cont, err := b.performChecks(ctx, vars, installed) // Выполняем различные проверки
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
} else if !cont {
|
||||
os.Exit(1) // Если проверки не пройдены, выходим из программы
|
||||
}
|
||||
|
||||
// Подготавливаем директории для сборки
|
||||
@@ -188,105 +165,60 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
buildDepends := []string{}
|
||||
optDepends := []string{}
|
||||
depends := []string{}
|
||||
sources := []string{}
|
||||
checksums := []string{}
|
||||
for _, vars := range varsOfPackages {
|
||||
buildDepends = append(buildDepends, vars.BuildDepends...)
|
||||
optDepends = append(optDepends, vars.OptDepends...)
|
||||
depends = append(depends, vars.Depends...)
|
||||
sources = append(sources, vars.Sources...)
|
||||
checksums = append(checksums, vars.Checksums...)
|
||||
}
|
||||
buildDepends = removeDuplicates(buildDepends)
|
||||
optDepends = removeDuplicates(optDepends)
|
||||
depends = removeDuplicates(depends)
|
||||
|
||||
if len(sources) != len(checksums) {
|
||||
slog.Error(gotext.Get("The checksums array must be the same length as sources"))
|
||||
os.Exit(1)
|
||||
}
|
||||
sources, checksums = removeDuplicatesSources(sources, checksums)
|
||||
|
||||
mergedVars := types.BuildVars{
|
||||
Sources: sources,
|
||||
Checksums: checksums,
|
||||
}
|
||||
|
||||
buildDeps, err := b.installBuildDeps(ctx, buildDepends) // Устанавливаем зависимости для сборки
|
||||
buildDeps, err := b.installBuildDeps(ctx, vars) // Устанавливаем зависимости для сборки
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
err = b.installOptDeps(ctx, optDepends) // Устанавливаем опциональные зависимости
|
||||
err = b.installOptDeps(ctx, vars) // Устанавливаем опциональные зависимости
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
newBuildPaths, builtNames, repoDeps, err := b.buildALRDeps(ctx, depends) // Собираем зависимости
|
||||
builtPaths, builtNames, repoDeps, err := b.buildALRDeps(ctx, vars) // Собираем зависимости
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
builtPaths = append(builtPaths, newBuildPaths...)
|
||||
|
||||
slog.Info(gotext.Get("Downloading sources")) // Записываем в лог загрузку источников
|
||||
|
||||
err = b.getSources(ctx, dirs, &mergedVars) // Загружаем исходники
|
||||
err = b.getSources(ctx, dirs, vars) // Загружаем исходники
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
err = b.executeFunctions(ctx, dec, dirs) // Выполняем специальные функции
|
||||
funcOut, err := b.executeFunctions(ctx, dec, dirs, vars) // Выполняем специальные функции
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for _, vars := range varsOfPackages {
|
||||
packageName := ""
|
||||
if vars.Base != "" {
|
||||
packageName = vars.Name
|
||||
}
|
||||
funcOut, err := b.executePackageFunctions(ctx, dec, dirs, packageName)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
slog.Info(gotext.Get("Building package metadata"), "name", vars.Name)
|
||||
|
||||
slog.Info(gotext.Get("Building package metadata"), "name", basePkg)
|
||||
pkgFormat := getPkgFormat(b.opts.Manager) // Получаем формат пакета
|
||||
|
||||
pkgFormat := getPkgFormat(b.opts.Manager) // Получаем формат пакета
|
||||
pkgInfo, err := buildPkgMetadata(ctx, vars, dirs, pkgFormat, b.info, append(repoDeps, builtNames...), funcOut.Contents) // Собираем метаданные пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pkgInfo, err := b.buildPkgMetadata(ctx, vars, dirs, pkgFormat, append(repoDeps, builtNames...), funcOut.Contents) // Собираем метаданные пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
packager, err := nfpm.Get(pkgFormat) // Получаем упаковщик для формата пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
packager, err := nfpm.Get(pkgFormat) // Получаем упаковщик для формата пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pkgName := packager.ConventionalFileName(pkgInfo) // Получаем имя файла пакета
|
||||
pkgPath := filepath.Join(dirs.BaseDir, pkgName) // Определяем путь к пакету
|
||||
|
||||
pkgName := packager.ConventionalFileName(pkgInfo) // Получаем имя файла пакета
|
||||
pkgPath := filepath.Join(dirs.BaseDir, pkgName) // Определяем путь к пакету
|
||||
pkgFile, err := os.Create(pkgPath) // Создаём файл пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pkgFile, err := os.Create(pkgPath) // Создаём файл пакета
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
slog.Info(gotext.Get("Compressing package"), "name", pkgName) // Логгируем сжатие пакета
|
||||
|
||||
slog.Info(gotext.Get("Compressing package"), "name", pkgName) // Логгируем сжатие пакета
|
||||
|
||||
err = packager.Package(pkgInfo, pkgFile) // Упаковываем пакет
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Добавляем путь и имя только что собранного пакета в
|
||||
// соответствующие срезы
|
||||
builtPaths = append(builtPaths, pkgPath)
|
||||
builtNames = append(builtNames, vars.Name)
|
||||
err = packager.Package(pkgInfo, pkgFile) // Упаковываем пакет
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
err = b.removeBuildDeps(ctx, buildDeps) // Удаляем зависимости для сборки
|
||||
@@ -294,6 +226,11 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Добавляем путь и имя только что собранного пакета в
|
||||
// соответствующие срезы
|
||||
builtPaths = append(builtPaths, pkgPath)
|
||||
builtNames = append(builtNames, vars.Name)
|
||||
|
||||
// Удаляем дубликаты из pkgPaths и pkgNames.
|
||||
// Дубликаты могут появиться, если несколько зависимостей
|
||||
// зависят от одних и тех же пакетов.
|
||||
@@ -307,9 +244,7 @@ func (b *Builder) BuildPackage(ctx context.Context) ([]string, []string, error)
|
||||
// чтобы извлечь переменные сборки без выполнения реального кода.
|
||||
func (b *Builder) executeFirstPass(
|
||||
fl *syntax.File,
|
||||
) (string, []*types.BuildVars, error) {
|
||||
varsOfPackages := []*types.BuildVars{}
|
||||
|
||||
) (*types.BuildVars, error) {
|
||||
scriptDir := filepath.Dir(b.opts.Script) // Получаем директорию скрипта
|
||||
env := createBuildEnvVars(b.info, types.Directories{ScriptDir: scriptDir}) // Создаём переменные окружения для сборки
|
||||
|
||||
@@ -317,17 +252,17 @@ func (b *Builder) executeFirstPass(
|
||||
interp.Env(expand.ListEnviron(env...)), // Устанавливаем окружение
|
||||
interp.StdIO(os.Stdin, os.Stdout, os.Stderr), // Устанавливаем стандартный ввод-вывод
|
||||
interp.ExecHandler(helpers.Restricted.ExecHandler(handlers.NopExec)), // Ограничиваем выполнение
|
||||
interp.ReadDirHandler2(handlers.RestrictedReadDir(scriptDir)), // Ограничиваем чтение директорий
|
||||
interp.ReadDirHandler(handlers.RestrictedReadDir(scriptDir)), // Ограничиваем чтение директорий
|
||||
interp.StatHandler(handlers.RestrictedStat(scriptDir)), // Ограничиваем доступ к статистике файлов
|
||||
interp.OpenHandler(handlers.RestrictedOpen(scriptDir)), // Ограничиваем открытие файлов
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = runner.Run(b.ctx, fl) // Запускаем скрипт
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dec := decoder.New(b.info, runner) // Создаём новый декодер
|
||||
@@ -340,65 +275,53 @@ func (b *Builder) executeFirstPass(
|
||||
var pkgs packages
|
||||
err = dec.DecodeVars(&pkgs)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return nil, err
|
||||
}
|
||||
if len(pkgs.Names) == 0 {
|
||||
return "", nil, errors.New("package name is missing")
|
||||
return nil, errors.New("package name is missing")
|
||||
}
|
||||
var vars types.BuildVars
|
||||
if len(pkgs.Names) == 1 {
|
||||
err = dec.DecodeVars(&vars) // Декодируем переменные
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return nil, err
|
||||
}
|
||||
varsOfPackages = append(varsOfPackages, &vars)
|
||||
|
||||
return vars.Name, varsOfPackages, nil
|
||||
return &vars, nil
|
||||
}
|
||||
if len(b.opts.Packages) == 0 {
|
||||
return "", nil, errors.New("script has multiple packages but package is not specified")
|
||||
if b.opts.Package == "" {
|
||||
return nil, errors.New("script has multiple packages but package is not specified")
|
||||
}
|
||||
|
||||
for _, pkgName := range b.opts.Packages {
|
||||
var preVars types.BuildVarsPre
|
||||
funcName := fmt.Sprintf("meta_%s", pkgName)
|
||||
meta, ok := dec.GetFuncWithSubshell(funcName)
|
||||
if !ok {
|
||||
return "", nil, errors.New("func is missing")
|
||||
}
|
||||
r, err := meta(b.ctx)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
d := decoder.New(&distro.OSRelease{}, r)
|
||||
err = d.DecodeVars(&preVars)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
vars := preVars.ToBuildVars()
|
||||
vars.Name = pkgName
|
||||
vars.Base = pkgs.BasePkgName
|
||||
|
||||
varsOfPackages = append(varsOfPackages, &vars)
|
||||
var preVars types.BuildVarsPre
|
||||
funcName := fmt.Sprintf("meta_%s", b.opts.Package)
|
||||
meta, ok := dec.GetFuncSub(funcName)
|
||||
if !ok {
|
||||
return nil, errors.New("func is missing")
|
||||
}
|
||||
r, err := meta(b.ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := decoder.New(&distro.OSRelease{}, r)
|
||||
err = d.DecodeVars(&preVars)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vars = preVars.ToBuildVars()
|
||||
vars.Name = b.opts.Package
|
||||
|
||||
return pkgs.BasePkgName, varsOfPackages, nil // Возвращаем переменные сборки
|
||||
return &vars, nil // Возвращаем переменные сборки
|
||||
}
|
||||
|
||||
// Функция getDirs возвращает соответствующие директории для скрипта
|
||||
func (b *Builder) getDirs(basePkg string) (types.Directories, error) {
|
||||
scriptPath, err := filepath.Abs(b.opts.Script)
|
||||
if err != nil {
|
||||
return types.Directories{}, err
|
||||
}
|
||||
|
||||
baseDir := filepath.Join(b.config.GetPaths(b.ctx).PkgsDir, basePkg) // Определяем базовую директорию
|
||||
func (b *Builder) getDirs(vars *types.BuildVars) types.Directories {
|
||||
baseDir := filepath.Join(b.config.GetPaths(b.ctx).PkgsDir, vars.Name) // Определяем базовую директорию
|
||||
return types.Directories{
|
||||
BaseDir: baseDir,
|
||||
SrcDir: filepath.Join(baseDir, "src"),
|
||||
PkgDir: filepath.Join(baseDir, "pkg"),
|
||||
ScriptDir: filepath.Dir(scriptPath),
|
||||
}, nil
|
||||
ScriptDir: filepath.Dir(b.opts.Script),
|
||||
}
|
||||
}
|
||||
|
||||
// Функция executeSecondPass выполняет скрипт сборки второй раз без каких-либо ограничений. Возвращается декодер,
|
||||
@@ -412,11 +335,9 @@ func (b *Builder) executeSecondPass(
|
||||
|
||||
fakeroot := handlers.FakerootExecHandler(2 * time.Second) // Настраиваем "fakeroot" для выполнения
|
||||
runner, err := interp.New(
|
||||
interp.Env(expand.ListEnviron(env...)), // Устанавливаем окружение
|
||||
interp.StdIO(os.Stdin, os.Stdout, os.Stderr), // Устанавливаем стандартный ввод-вывод
|
||||
interp.ExecHandlers(func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
|
||||
return helpers.Helpers.ExecHandler(fakeroot)
|
||||
}), // Обрабатываем выполнение через fakeroot
|
||||
interp.Env(expand.ListEnviron(env...)), // Устанавливаем окружение
|
||||
interp.StdIO(os.Stdin, os.Stdout, os.Stderr), // Устанавливаем стандартный ввод-вывод
|
||||
interp.ExecHandler(helpers.Helpers.ExecHandler(fakeroot)), // Обрабатываем выполнение через fakeroot
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -460,10 +381,10 @@ func (b *Builder) performChecks(ctx context.Context, vars *types.BuildVars, inst
|
||||
|
||||
// Функция installBuildDeps устанавливает все зависимости сборки, которые еще не установлены, и возвращает
|
||||
// срез, содержащий имена всех установленных пакетов.
|
||||
func (b *Builder) installBuildDeps(ctx context.Context, buildDepends []string) ([]string, error) {
|
||||
func (b *Builder) installBuildDeps(ctx context.Context, vars *types.BuildVars) ([]string, error) {
|
||||
var buildDeps []string
|
||||
if len(buildDepends) > 0 {
|
||||
deps, err := removeAlreadyInstalled(b.opts, buildDepends)
|
||||
if len(vars.BuildDepends) > 0 {
|
||||
deps, err := removeAlreadyInstalled(b.opts, vars.BuildDepends)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -482,41 +403,11 @@ func (b *Builder) installBuildDeps(ctx context.Context, buildDepends []string) (
|
||||
return buildDeps, nil
|
||||
}
|
||||
|
||||
func (b *Builder) getBuildersForPackages(pkgs []db.Package) []*Builder {
|
||||
type item struct {
|
||||
pkg *db.Package
|
||||
packages []string
|
||||
}
|
||||
pkgsMap := make(map[string]*item)
|
||||
for _, pkg := range pkgs {
|
||||
if pkgsMap[pkg.BasePkgName] == nil {
|
||||
pkgsMap[pkg.BasePkgName] = &item{
|
||||
pkg: &pkg,
|
||||
}
|
||||
}
|
||||
pkgsMap[pkg.BasePkgName].packages = append(
|
||||
pkgsMap[pkg.BasePkgName].packages,
|
||||
pkg.Name,
|
||||
)
|
||||
}
|
||||
|
||||
builders := []*Builder{}
|
||||
|
||||
for basePkgName := range pkgsMap {
|
||||
pkg := pkgsMap[basePkgName].pkg
|
||||
builder := *b
|
||||
builder.UpdateOptsFromPkg(pkg, pkgsMap[basePkgName].packages)
|
||||
builders = append(builders, &builder)
|
||||
}
|
||||
|
||||
return builders
|
||||
}
|
||||
|
||||
func (b *Builder) buildALRDeps(ctx context.Context, depends []string) (builtPaths, builtNames, repoDeps []string, err error) {
|
||||
if len(depends) > 0 {
|
||||
func (b *Builder) buildALRDeps(ctx context.Context, vars *types.BuildVars) (builtPaths, builtNames, repoDeps []string, err error) {
|
||||
if len(vars.Depends) > 0 {
|
||||
slog.Info(gotext.Get("Installing dependencies"))
|
||||
|
||||
found, notFound, err := b.repos.FindPkgs(ctx, depends) // Поиск зависимостей
|
||||
found, notFound, err := b.repos.FindPkgs(ctx, vars.Depends) // Поиск зависимостей
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
@@ -524,10 +415,14 @@ func (b *Builder) buildALRDeps(ctx context.Context, depends []string) (builtPath
|
||||
|
||||
// Если для некоторых пакетов есть несколько опций, упрощаем их все в один срез
|
||||
pkgs := cliutils.FlattenPkgs(ctx, found, "install", b.opts.Interactive)
|
||||
builders := b.getBuildersForPackages(pkgs)
|
||||
for _, builder := range builders {
|
||||
|
||||
for _, pkg := range pkgs {
|
||||
|
||||
newB := *b
|
||||
newB.UpdateOptsFromPkg(&pkg)
|
||||
|
||||
// Собираем зависимости
|
||||
pkgPaths, pkgNames, err := builder.BuildPackage(ctx)
|
||||
pkgPaths, pkgNames, err := newB.BuildPackage(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
@@ -536,6 +431,8 @@ func (b *Builder) buildALRDeps(ctx context.Context, depends []string) (builtPath
|
||||
builtPaths = append(builtPaths, pkgPaths...)
|
||||
// Добавляем пути всех собранных пакетов в builtPaths
|
||||
builtNames = append(builtNames, pkgNames...)
|
||||
// Добавляем имя текущего пакета в builtNames
|
||||
builtNames = append(builtNames, filepath.Base(filepath.Dir(newB.opts.Script)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,6 +445,11 @@ func (b *Builder) buildALRDeps(ctx context.Context, depends []string) (builtPath
|
||||
}
|
||||
|
||||
func (b *Builder) getSources(ctx context.Context, dirs types.Directories, bv *types.BuildVars) error {
|
||||
if len(bv.Sources) != len(bv.Checksums) {
|
||||
slog.Error(gotext.Get("The checksums array must be the same length as sources"))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for i, src := range bv.Sources {
|
||||
opts := dl.Options{
|
||||
Name: fmt.Sprintf("%s[%d]", bv.Name, i),
|
||||
@@ -628,33 +530,32 @@ func (b *Builder) executeFunctions(
|
||||
ctx context.Context,
|
||||
dec *decoder.Decoder,
|
||||
dirs types.Directories,
|
||||
) error {
|
||||
/*
|
||||
version, ok := dec.GetFunc("version")
|
||||
if ok {
|
||||
slog.Info(gotext.Get("Executing version()"))
|
||||
vars *types.BuildVars,
|
||||
) (*FunctionsOutput, error) {
|
||||
version, ok := dec.GetFunc("version")
|
||||
if ok {
|
||||
slog.Info(gotext.Get("Executing version()"))
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
err := version(
|
||||
ctx,
|
||||
interp.Dir(dirs.SrcDir),
|
||||
interp.StdIO(os.Stdin, buf, os.Stderr),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newVer := strings.TrimSpace(buf.String())
|
||||
err = setVersion(ctx, dec.Runner, newVer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vars.Version = newVer
|
||||
|
||||
slog.Info(gotext.Get("Updating version"), "new", newVer)
|
||||
err := version(
|
||||
ctx,
|
||||
interp.Dir(dirs.SrcDir),
|
||||
interp.StdIO(os.Stdin, buf, os.Stderr),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*/
|
||||
|
||||
newVer := strings.TrimSpace(buf.String())
|
||||
err = setVersion(ctx, dec.Runner, newVer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vars.Version = newVer
|
||||
|
||||
slog.Info(gotext.Get("Updating version"), "new", newVer)
|
||||
}
|
||||
|
||||
prepare, ok := dec.GetFunc("prepare")
|
||||
if ok {
|
||||
@@ -662,7 +563,7 @@ func (b *Builder) executeFunctions(
|
||||
|
||||
err := prepare(ctx, interp.Dir(dirs.SrcDir))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,29 +573,15 @@ func (b *Builder) executeFunctions(
|
||||
|
||||
err := build(ctx, interp.Dir(dirs.SrcDir))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Builder) executePackageFunctions(
|
||||
ctx context.Context,
|
||||
dec *decoder.Decoder,
|
||||
dirs types.Directories,
|
||||
packageName string,
|
||||
) (*FunctionsOutput, error) {
|
||||
output := &FunctionsOutput{}
|
||||
var packageFuncName string
|
||||
var filesFuncName string
|
||||
|
||||
if packageName == "" {
|
||||
if b.opts.Package == "" {
|
||||
packageFuncName = "package"
|
||||
filesFuncName = "files"
|
||||
} else {
|
||||
packageFuncName = fmt.Sprintf("package_%s", packageName)
|
||||
filesFuncName = fmt.Sprintf("files_%s", packageName)
|
||||
packageFuncName = fmt.Sprintf("package_%s", b.opts.Package)
|
||||
}
|
||||
packageFn, ok := dec.GetFunc(packageFuncName)
|
||||
if ok {
|
||||
@@ -705,6 +592,14 @@ func (b *Builder) executePackageFunctions(
|
||||
}
|
||||
}
|
||||
|
||||
output := &FunctionsOutput{}
|
||||
|
||||
var filesFuncName string
|
||||
if b.opts.Package == "" {
|
||||
filesFuncName = "files"
|
||||
} else {
|
||||
filesFuncName = fmt.Sprintf("files_%s", b.opts.Package)
|
||||
}
|
||||
files, ok := dec.GetFuncP(filesFuncName, func(ctx context.Context, s *interp.Runner) error {
|
||||
// It should be done via interp.RunnerOption,
|
||||
// but due to the issues below, it cannot be done.
|
||||
@@ -741,8 +636,8 @@ func (b *Builder) executePackageFunctions(
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (b *Builder) installOptDeps(ctx context.Context, optDepends []string) error {
|
||||
optDeps, err := removeAlreadyInstalled(b.opts, optDepends)
|
||||
func (b *Builder) installOptDeps(ctx context.Context, vars *types.BuildVars) error {
|
||||
optDeps, err := removeAlreadyInstalled(b.opts, vars.OptDepends)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -788,8 +683,10 @@ func (b *Builder) InstallPkgs(
|
||||
}
|
||||
|
||||
func (b *Builder) InstallALRPackages(ctx context.Context, pkgs []db.Package, opts types.BuildOpts) {
|
||||
builders := b.getBuildersForPackages(pkgs)
|
||||
for _, builder := range builders {
|
||||
for _, pkg := range pkgs {
|
||||
builder := *b
|
||||
builder.UpdateOptsFromPkg(&pkg)
|
||||
|
||||
builtPkgs, _, err := builder.BuildPackage(ctx)
|
||||
// Выполняем сборку пакета
|
||||
if err != nil {
|
||||
@@ -807,108 +704,3 @@ func (b *Builder) InstallALRPackages(ctx context.Context, pkgs []db.Package, opt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Функция buildPkgMetadata создает метаданные для пакета, который будет собран.
|
||||
func (b *Builder) buildPkgMetadata(
|
||||
ctx context.Context,
|
||||
vars *types.BuildVars,
|
||||
dirs types.Directories,
|
||||
pkgFormat string,
|
||||
deps []string,
|
||||
preferedContents *[]string,
|
||||
) (*nfpm.Info, error) {
|
||||
pkgInfo := getBasePkgInfo(vars, b.info, &b.opts)
|
||||
pkgInfo.Description = vars.Description
|
||||
pkgInfo.Platform = "linux"
|
||||
pkgInfo.Homepage = vars.Homepage
|
||||
pkgInfo.License = strings.Join(vars.Licenses, ", ")
|
||||
pkgInfo.Maintainer = vars.Maintainer
|
||||
pkgInfo.Overridables = nfpm.Overridables{
|
||||
Conflicts: append(vars.Conflicts, vars.Name),
|
||||
Replaces: vars.Replaces,
|
||||
Provides: append(vars.Provides, vars.Name),
|
||||
Depends: deps,
|
||||
}
|
||||
|
||||
if pkgFormat == "apk" {
|
||||
// Alpine отказывается устанавливать пакеты, которые предоставляют сами себя, поэтому удаляем такие элементы
|
||||
pkgInfo.Overridables.Provides = slices.DeleteFunc(pkgInfo.Overridables.Provides, func(s string) bool {
|
||||
return s == pkgInfo.Name
|
||||
})
|
||||
}
|
||||
|
||||
if vars.Epoch != 0 {
|
||||
pkgInfo.Epoch = strconv.FormatUint(uint64(vars.Epoch), 10)
|
||||
}
|
||||
|
||||
setScripts(vars, pkgInfo, dirs.ScriptDir)
|
||||
|
||||
if slices.Contains(vars.Architectures, "all") {
|
||||
pkgInfo.Arch = "all"
|
||||
}
|
||||
|
||||
contents, err := buildContents(vars, dirs, preferedContents)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pkgInfo.Overridables.Contents = contents
|
||||
|
||||
if len(vars.AutoProv) == 1 && decoder.IsTruthy(vars.AutoProv[0]) {
|
||||
if pkgFormat == "rpm" {
|
||||
err = rpmFindProvides(ctx, pkgInfo, dirs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
slog.Info(gotext.Get("AutoProv is not implemented for this package format, so it's skipped"))
|
||||
}
|
||||
}
|
||||
|
||||
if len(vars.AutoReq) == 1 && decoder.IsTruthy(vars.AutoReq[0]) {
|
||||
if pkgFormat == "rpm" {
|
||||
err = rpmFindRequires(ctx, pkgInfo, dirs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
slog.Info(gotext.Get("AutoReq is not implemented for this package format, so it's skipped"))
|
||||
}
|
||||
}
|
||||
|
||||
return pkgInfo, nil
|
||||
}
|
||||
|
||||
// Функция checkForBuiltPackage пытается обнаружить ранее собранный пакет и вернуть его путь
|
||||
// и true, если нашла. Если нет, возвратит "", false, nil.
|
||||
func (b *Builder) checkForBuiltPackage(
|
||||
vars *types.BuildVars,
|
||||
pkgFormat,
|
||||
baseDir string,
|
||||
) (string, bool, error) {
|
||||
filename, err := b.pkgFileName(vars, pkgFormat)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
pkgPath := filepath.Join(baseDir, filename)
|
||||
|
||||
_, err = os.Stat(pkgPath)
|
||||
if err != nil {
|
||||
return "", false, nil
|
||||
}
|
||||
|
||||
return pkgPath, true, nil
|
||||
}
|
||||
|
||||
// pkgFileName returns the filename of the package if it were to be built.
|
||||
// This is used to check if the package has already been built.
|
||||
func (b *Builder) pkgFileName(vars *types.BuildVars, pkgFormat string) (string, error) {
|
||||
pkgInfo := getBasePkgInfo(vars, b.info, &b.opts)
|
||||
|
||||
packager, err := nfpm.Get(pkgFormat)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return packager.ConventionalFileName(pkgInfo), nil
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ rm -f %s`, tmpFilePath)
|
||||
fl, err := syntax.NewParser().Parse(strings.NewReader(testScript), "alr.sh")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, _, err = b.executeFirstPass(fl)
|
||||
_, err = b.executeFirstPass(fl)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = os.Stat(tmpFilePath)
|
||||
@@ -203,7 +203,7 @@ func TestExecuteFirstPassIsCorrect(t *testing.T) {
|
||||
Name string
|
||||
Script string
|
||||
Opts types.BuildOpts
|
||||
Expected func(t *testing.T, vars []*types.BuildVars)
|
||||
Expected func(t *testing.T, vars *types.BuildVars)
|
||||
}
|
||||
|
||||
for _, tc := range []testCase{{
|
||||
@@ -220,13 +220,12 @@ maintainer='Ivan Ivanov'
|
||||
Manager: &TestManager{},
|
||||
Interactive: false,
|
||||
},
|
||||
Expected: func(t *testing.T, vars []*types.BuildVars) {
|
||||
assert.Equal(t, 1, len(vars))
|
||||
assert.Equal(t, vars[0].Name, "test")
|
||||
assert.Equal(t, vars[0].Version, "1.0.0")
|
||||
assert.Equal(t, vars[0].Release, int(1))
|
||||
assert.Equal(t, vars[0].Epoch, uint(2))
|
||||
assert.Equal(t, vars[0].Description, "Test package")
|
||||
Expected: func(t *testing.T, vars *types.BuildVars) {
|
||||
assert.Equal(t, vars.Name, "test")
|
||||
assert.Equal(t, vars.Version, "1.0.0")
|
||||
assert.Equal(t, vars.Release, int(1))
|
||||
assert.Equal(t, vars.Epoch, uint(2))
|
||||
assert.Equal(t, vars.Description, "Test package")
|
||||
},
|
||||
}, {
|
||||
Name: "multiple packages",
|
||||
@@ -249,14 +248,13 @@ meta_bar() {
|
||||
}
|
||||
`,
|
||||
Opts: types.BuildOpts{
|
||||
Packages: []string{"foo"},
|
||||
Package: "foo",
|
||||
Manager: &TestManager{},
|
||||
Interactive: false,
|
||||
},
|
||||
Expected: func(t *testing.T, vars []*types.BuildVars) {
|
||||
assert.Equal(t, 1, len(vars))
|
||||
assert.Equal(t, vars[0].Name, "foo")
|
||||
assert.Equal(t, vars[0].Description, "Foo package")
|
||||
Expected: func(t *testing.T, vars *types.BuildVars) {
|
||||
assert.Equal(t, vars.Name, "foo")
|
||||
assert.Equal(t, vars.Description, "Foo package")
|
||||
},
|
||||
}} {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
@@ -277,10 +275,10 @@ meta_bar() {
|
||||
fl, err := syntax.NewParser().Parse(strings.NewReader(tc.Script), "alr.sh")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, allVars, err := b.executeFirstPass(fl)
|
||||
vars, err := b.executeFirstPass(fl)
|
||||
assert.NoError(t, err)
|
||||
|
||||
tc.Expected(t, allVars)
|
||||
tc.Expected(t, vars)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,11 @@
|
||||
package build
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -33,6 +33,8 @@ import (
|
||||
_ "github.com/goreleaser/nfpm/v2/arch"
|
||||
_ "github.com/goreleaser/nfpm/v2/deb"
|
||||
_ "github.com/goreleaser/nfpm/v2/rpm"
|
||||
"github.com/leonelquinteros/gotext"
|
||||
"mvdan.cc/sh/v3/interp"
|
||||
"mvdan.cc/sh/v3/syntax"
|
||||
|
||||
"github.com/goreleaser/nfpm/v2"
|
||||
@@ -41,6 +43,7 @@ import (
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
|
||||
@@ -75,6 +78,79 @@ func prepareDirs(dirs types.Directories) error {
|
||||
return os.MkdirAll(dirs.PkgDir, 0o755) // Создаем директорию для пакетов
|
||||
}
|
||||
|
||||
// Функция buildPkgMetadata создает метаданные для пакета, который будет собран.
|
||||
func buildPkgMetadata(
|
||||
ctx context.Context,
|
||||
vars *types.BuildVars,
|
||||
dirs types.Directories,
|
||||
pkgFormat string,
|
||||
info *distro.OSRelease,
|
||||
deps []string,
|
||||
preferedContents *[]string,
|
||||
) (*nfpm.Info, error) {
|
||||
pkgInfo := getBasePkgInfo(vars)
|
||||
pkgInfo.Description = vars.Description
|
||||
pkgInfo.Platform = "linux"
|
||||
pkgInfo.Homepage = vars.Homepage
|
||||
pkgInfo.License = strings.Join(vars.Licenses, ", ")
|
||||
pkgInfo.Maintainer = vars.Maintainer
|
||||
pkgInfo.Overridables = nfpm.Overridables{
|
||||
Conflicts: vars.Conflicts,
|
||||
Replaces: vars.Replaces,
|
||||
Provides: vars.Provides,
|
||||
Depends: deps,
|
||||
}
|
||||
|
||||
if pkgFormat == "apk" {
|
||||
// Alpine отказывается устанавливать пакеты, которые предоставляют сами себя, поэтому удаляем такие элементы
|
||||
pkgInfo.Overridables.Provides = slices.DeleteFunc(pkgInfo.Overridables.Provides, func(s string) bool {
|
||||
return s == pkgInfo.Name
|
||||
})
|
||||
}
|
||||
|
||||
pkgInfo.Release = overrides.ReleasePlatformSpecific(vars.Release, info)
|
||||
|
||||
if vars.Epoch != 0 {
|
||||
pkgInfo.Epoch = strconv.FormatUint(uint64(vars.Epoch), 10)
|
||||
}
|
||||
|
||||
setScripts(vars, pkgInfo, dirs.ScriptDir)
|
||||
|
||||
if slices.Contains(vars.Architectures, "all") {
|
||||
pkgInfo.Arch = "all"
|
||||
}
|
||||
|
||||
contents, err := buildContents(vars, dirs, preferedContents)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pkgInfo.Overridables.Contents = contents
|
||||
|
||||
if len(vars.AutoProv) == 1 && decoder.IsTruthy(vars.AutoProv[0]) {
|
||||
if pkgFormat == "rpm" {
|
||||
err = rpmFindProvides(ctx, pkgInfo, dirs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
slog.Info(gotext.Get("AutoProv is not implemented for this package format, so it's skipped"))
|
||||
}
|
||||
}
|
||||
|
||||
if len(vars.AutoReq) == 1 && decoder.IsTruthy(vars.AutoReq[0]) {
|
||||
if pkgFormat == "rpm" {
|
||||
err = rpmFindRequires(ctx, pkgInfo, dirs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
slog.Info(gotext.Get("AutoReq is not implemented for this package format, so it's skipped"))
|
||||
}
|
||||
}
|
||||
|
||||
return pkgInfo, nil
|
||||
}
|
||||
|
||||
// Функция buildContents создает секцию содержимого пакета, которая содержит файлы,
|
||||
// которые будут включены в конечный пакет.
|
||||
func buildContents(vars *types.BuildVars, dirs types.Directories, preferedContents *[]string) ([]*files.Content, error) {
|
||||
@@ -171,18 +247,47 @@ func buildContents(vars *types.BuildVars, dirs types.Directories, preferedConten
|
||||
return contents, nil
|
||||
}
|
||||
|
||||
var RegexpALRPackageName = regexp.MustCompile(`^(?P<package>[^+]+)\+alr-(?P<repo>.+)$`)
|
||||
// Функция checkForBuiltPackage пытается обнаружить ранее собранный пакет и вернуть его путь
|
||||
// и true, если нашла. Если нет, возвратит "", false, nil.
|
||||
func checkForBuiltPackage(mgr manager.Manager, vars *types.BuildVars, pkgFormat, baseDir string) (string, bool, error) {
|
||||
filename, err := pkgFileName(vars, pkgFormat)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
func getBasePkgInfo(vars *types.BuildVars, info *distro.OSRelease, opts *types.BuildOpts) *nfpm.Info {
|
||||
pkgPath := filepath.Join(baseDir, filename)
|
||||
|
||||
_, err = os.Stat(pkgPath)
|
||||
if err != nil {
|
||||
return "", false, nil
|
||||
}
|
||||
|
||||
return pkgPath, true, nil
|
||||
}
|
||||
|
||||
func getBasePkgInfo(vars *types.BuildVars) *nfpm.Info {
|
||||
return &nfpm.Info{
|
||||
Name: fmt.Sprintf("%s+alr-%s", vars.Name, opts.Repository),
|
||||
Name: vars.Name,
|
||||
Arch: cpu.Arch(),
|
||||
Version: vars.Version,
|
||||
Release: overrides.ReleasePlatformSpecific(vars.Release, info),
|
||||
Release: strconv.Itoa(vars.Release),
|
||||
Epoch: strconv.FormatUint(uint64(vars.Epoch), 10),
|
||||
}
|
||||
}
|
||||
|
||||
// pkgFileName returns the filename of the package if it were to be built.
|
||||
// This is used to check if the package has already been built.
|
||||
func pkgFileName(vars *types.BuildVars, pkgFormat string) (string, error) {
|
||||
pkgInfo := getBasePkgInfo(vars)
|
||||
|
||||
packager, err := nfpm.Get(pkgFormat)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return packager.ConventionalFileName(pkgInfo), nil
|
||||
}
|
||||
|
||||
// Функция getPkgFormat возвращает формат пакета из менеджера пакетов,
|
||||
// или ALR_PKG_FORMAT, если он установлен.
|
||||
func getPkgFormat(mgr manager.Manager) string {
|
||||
@@ -261,7 +366,6 @@ func setScripts(vars *types.BuildVars, info *nfpm.Info, scriptDir string) {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// Функция setVersion изменяет переменную версии в скрипте runner.
|
||||
// Она используется для установки версии на вывод функции version().
|
||||
func setVersion(ctx context.Context, r *interp.Runner, to string) error {
|
||||
@@ -271,7 +375,7 @@ func setVersion(ctx context.Context, r *interp.Runner, to string) error {
|
||||
}
|
||||
return r.Run(ctx, fl)
|
||||
}
|
||||
*/
|
||||
|
||||
// Returns not installed dependencies
|
||||
func removeAlreadyInstalled(opts types.BuildOpts, dependencies []string) ([]string, error) {
|
||||
filteredPackages := []string{}
|
||||
@@ -313,24 +417,3 @@ func removeDuplicates(slice []string) []string {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func removeDuplicatesSources(sources, checksums []string) ([]string, []string) {
|
||||
seen := map[string]string{}
|
||||
keys := make([]string, 0)
|
||||
for i, s := range sources {
|
||||
if val, ok := seen[s]; !ok || strings.EqualFold(val, "SKIP") {
|
||||
if !ok {
|
||||
keys = append(keys, s)
|
||||
}
|
||||
seen[s] = checksums[i]
|
||||
}
|
||||
}
|
||||
|
||||
newSources := make([]string, len(keys))
|
||||
newChecksums := make([]string, len(keys))
|
||||
for i, k := range keys {
|
||||
newSources[i] = k
|
||||
newChecksums[i] = seen[k]
|
||||
}
|
||||
return newSources, newChecksums
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ func ParseOSRelease(ctx context.Context) (*OSRelease, error) {
|
||||
runner, err := interp.New(
|
||||
interp.OpenHandler(handlers.NopOpen),
|
||||
interp.ExecHandler(handlers.NopExec),
|
||||
interp.ReadDirHandler2(handlers.NopReadDir),
|
||||
interp.ReadDirHandler(handlers.NopReadDir),
|
||||
interp.StatHandler(handlers.NopStat),
|
||||
interp.Env(expand.ListEnviron()),
|
||||
)
|
||||
|
||||
@@ -32,19 +32,19 @@ deps=("python3")
|
||||
deps_arch=("python")
|
||||
deps_alpine=("python3")
|
||||
|
||||
build_deps=("python3" "python3-pip")
|
||||
build_deps_arch=("python" "python-pip")
|
||||
build_deps_alpine=("python3" "py3-pip")
|
||||
build_deps=("python3" "python3-setuptools")
|
||||
build_deps_arch=("python" "python-setuptools")
|
||||
build_deps_alpine=("python3" "py3-setuptools")
|
||||
|
||||
sources=("https://files.pythonhosted.org/packages/source/{{.SourceURL.Filename | firstchar}}/{{.Info.Name}}/{{.SourceURL.Filename}}")
|
||||
checksums=('blake2b-256:{{.SourceURL.Digests.blake2b_256}}')
|
||||
|
||||
build() {
|
||||
cd "$srcdir/{{.Info.Name}}-${version}"
|
||||
python3 -m build
|
||||
python3 setup.py build
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$srcdir/{{.Info.Name}}-${version}"
|
||||
pip install --root="${pkgdir}/" . --no-deps --disable-pip-version-check
|
||||
python3 setup.py install --root="${pkgdir}/" --optimize=1 || return 1
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func (rs *Repos) Pull(ctx context.Context, repos []types.Repo) error {
|
||||
}
|
||||
|
||||
slog.Info(gotext.Get("Pulling repository"), "name", repo.Name)
|
||||
repoDir := filepath.Join(rs.cfg.GetPaths(ctx).RepoDir, repo.Name)
|
||||
repoDir := filepath.Join(config.GetPaths(ctx).RepoDir, repo.Name)
|
||||
|
||||
var repoFS billy.Filesystem
|
||||
gitDir := filepath.Join(repoDir, ".git")
|
||||
@@ -223,7 +223,7 @@ func (rs *Repos) updatePkg(ctx context.Context, repo types.Repo, runner *interp.
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
meta, ok := d.GetFuncWithSubshell(funcName)
|
||||
meta, ok := d.GetFuncSub(funcName)
|
||||
if !ok {
|
||||
return errors.New("func is missing")
|
||||
}
|
||||
@@ -264,7 +264,7 @@ func (rs *Repos) processRepoChangesRunner(repoDir, scriptDir string) (*interp.Ru
|
||||
return interp.New(
|
||||
interp.Env(expand.ListEnviron(env...)),
|
||||
interp.ExecHandler(handlers.NopExec),
|
||||
interp.ReadDirHandler2(handlers.RestrictedReadDir(repoDir)),
|
||||
interp.ReadDirHandler(handlers.RestrictedReadDir(repoDir)),
|
||||
interp.StatHandler(handlers.RestrictedStat(repoDir)),
|
||||
interp.OpenHandler(handlers.RestrictedOpen(repoDir)),
|
||||
interp.StdIO(handlers.NopRWC{}, handlers.NopRWC{}, handlers.NopRWC{}),
|
||||
|
||||
69
pkg/repos/repos_legacy.go
Normal file
69
pkg/repos/repos_legacy.go
Normal file
@@ -0,0 +1,69 @@
|
||||
// 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 repos
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
|
||||
)
|
||||
|
||||
// Pull pulls the provided repositories. If a repo doesn't exist, it will be cloned
|
||||
// and its packages will be written to the DB. If it does exist, it will be pulled.
|
||||
// In this case, only changed packages will be processed if possible.
|
||||
// If repos is set to nil, the repos in the ALR config will be used.
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func Pull(ctx context.Context, repos []types.Repo) error {
|
||||
return GetInstance(ctx).Pull(ctx, repos)
|
||||
}
|
||||
|
||||
// FindPkgs looks for packages matching the inputs inside the database.
|
||||
// It returns a map that maps the package name input to any packages found for it.
|
||||
// It also returns a slice that contains the names of all packages that were not found.
|
||||
//
|
||||
// Deprecated: use struct method
|
||||
func FindPkgs_(ctx context.Context, pkgs []string) (map[string][]database.Package, []string, error) {
|
||||
return GetInstance(ctx).FindPkgs(ctx, pkgs)
|
||||
}
|
||||
|
||||
// =======================
|
||||
// FOR LEGACY ONLY
|
||||
// =======================
|
||||
|
||||
var (
|
||||
reposInstance *Repos
|
||||
alrConfigOnce sync.Once
|
||||
)
|
||||
|
||||
// Deprecated: For legacy only
|
||||
func GetInstance(ctx context.Context) *Repos {
|
||||
alrConfigOnce.Do(func() {
|
||||
cfg := config.GetInstance(ctx)
|
||||
db := database.GetInstance(ctx)
|
||||
|
||||
reposInstance = New(
|
||||
cfg,
|
||||
db,
|
||||
)
|
||||
})
|
||||
|
||||
return reposInstance
|
||||
}
|
||||
@@ -21,46 +21,166 @@ package search
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
)
|
||||
|
||||
type PackagesProvider interface {
|
||||
GetPkgs(ctx context.Context, where string, args ...any) (*sqlx.Rows, error)
|
||||
// Filter represents search filters.
|
||||
type Filter int
|
||||
|
||||
// Filters
|
||||
const (
|
||||
FilterNone Filter = iota
|
||||
FilterInRepo
|
||||
FilterSupportsArch
|
||||
)
|
||||
|
||||
// SoryBy represents a value that packages can be sorted by.
|
||||
type SortBy int
|
||||
|
||||
// Sort values
|
||||
const (
|
||||
SortByNone = iota
|
||||
SortByName
|
||||
SortByRepo
|
||||
SortByVersion
|
||||
)
|
||||
|
||||
// Package represents a package from ALR's database
|
||||
type Package struct {
|
||||
Name string
|
||||
Version string
|
||||
Release int
|
||||
Epoch uint
|
||||
Description map[string]string
|
||||
Homepage map[string]string
|
||||
Maintainer map[string]string
|
||||
Architectures []string
|
||||
Licenses []string
|
||||
Provides []string
|
||||
Conflicts []string
|
||||
Replaces []string
|
||||
Depends map[string][]string
|
||||
BuildDepends map[string][]string
|
||||
OptDepends map[string][]string
|
||||
Repository string
|
||||
}
|
||||
|
||||
type Searcher struct {
|
||||
pp PackagesProvider
|
||||
}
|
||||
|
||||
func New(pp PackagesProvider) *Searcher {
|
||||
return &Searcher{
|
||||
pp: pp,
|
||||
func convertPkg(p db.Package) Package {
|
||||
return Package{
|
||||
Name: p.Name,
|
||||
Version: p.Version,
|
||||
Release: p.Release,
|
||||
Epoch: p.Epoch,
|
||||
Description: p.Description.Val,
|
||||
Homepage: p.Homepage.Val,
|
||||
Maintainer: p.Maintainer.Val,
|
||||
Architectures: p.Architectures.Val,
|
||||
Licenses: p.Licenses.Val,
|
||||
Provides: p.Provides.Val,
|
||||
Conflicts: p.Conflicts.Val,
|
||||
Replaces: p.Replaces.Val,
|
||||
Depends: p.Depends.Val,
|
||||
BuildDepends: p.BuildDepends.Val,
|
||||
OptDepends: p.OptDepends.Val,
|
||||
Repository: p.Repository,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Searcher) Search(
|
||||
ctx context.Context,
|
||||
opts *SearchOptions,
|
||||
) ([]database.Package, error) {
|
||||
var packages []database.Package
|
||||
// Options contains the options for a search.
|
||||
type Options struct {
|
||||
Filter Filter
|
||||
FilterValue string
|
||||
SortBy SortBy
|
||||
Limit int64
|
||||
Query string
|
||||
}
|
||||
|
||||
where, args := opts.WhereClause()
|
||||
result, err := s.pp.GetPkgs(ctx, where, args...)
|
||||
// Search searches for packages in the database based on the given options.
|
||||
func Search(ctx context.Context, opts Options) ([]Package, error) {
|
||||
query := "(name LIKE ? OR description LIKE ? OR json_array_contains(provides, ?))"
|
||||
args := []any{"%" + opts.Query + "%", "%" + opts.Query + "%", opts.Query}
|
||||
|
||||
if opts.Filter != FilterNone {
|
||||
switch opts.Filter {
|
||||
case FilterInRepo:
|
||||
query += " AND repository = ?"
|
||||
case FilterSupportsArch:
|
||||
query += " AND json_array_contains(architectures, ?)"
|
||||
}
|
||||
args = append(args, opts.FilterValue)
|
||||
}
|
||||
|
||||
if opts.SortBy != SortByNone {
|
||||
switch opts.SortBy {
|
||||
case SortByName:
|
||||
query += " ORDER BY name"
|
||||
case SortByRepo:
|
||||
query += " ORDER BY repository"
|
||||
case SortByVersion:
|
||||
query += " ORDER BY version"
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Limit != 0 {
|
||||
query += " LIMIT " + strconv.FormatInt(opts.Limit, 10)
|
||||
}
|
||||
|
||||
result, err := db.GetPkgs(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var out []Package
|
||||
for result.Next() {
|
||||
var dbPkg database.Package
|
||||
err = result.StructScan(&dbPkg)
|
||||
pkg := db.Package{}
|
||||
err = result.StructScan(&pkg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packages = append(packages, dbPkg)
|
||||
out = append(out, convertPkg(pkg))
|
||||
}
|
||||
|
||||
return packages, nil
|
||||
return out, err
|
||||
}
|
||||
|
||||
// GetPkg gets a single package from the database and returns it.
|
||||
func GetPkg(ctx context.Context, repo, name string) (Package, error) {
|
||||
pkg, err := db.GetPkg(ctx, "name = ? AND repository = ?", name, repo)
|
||||
return convertPkg(*pkg), err
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrInvalidArgument is an error returned by GetScript when one of its arguments
|
||||
// contain invalid characters
|
||||
ErrInvalidArgument = errors.New("name and repository must not contain . or /")
|
||||
|
||||
// ErrScriptNotFound is returned by GetScript if it can't find the script requested
|
||||
// by the user.
|
||||
ErrScriptNotFound = errors.New("requested script not found")
|
||||
)
|
||||
|
||||
// GetScript returns a reader containing the build script for a given package.
|
||||
func GetScript(ctx context.Context, repo, name string) (io.ReadCloser, error) {
|
||||
if strings.Contains(name, "./") || strings.ContainsAny(repo, "./") {
|
||||
return nil, ErrInvalidArgument
|
||||
}
|
||||
|
||||
scriptPath := filepath.Join(config.GetPaths(ctx).RepoDir, repo, name, "alr.sh")
|
||||
fl, err := os.Open(scriptPath)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, ErrScriptNotFound
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fl, nil
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
// 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 search
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type SearchOptions struct {
|
||||
conditions []string
|
||||
args []any
|
||||
}
|
||||
|
||||
func (o *SearchOptions) WhereClause() (string, []any) {
|
||||
if len(o.conditions) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return strings.Join(o.conditions, " AND "), o.args
|
||||
}
|
||||
|
||||
type SearchOptionsBuilder struct {
|
||||
options SearchOptions
|
||||
}
|
||||
|
||||
func NewSearchOptions() *SearchOptionsBuilder {
|
||||
return &SearchOptionsBuilder{}
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) withGeneralLike(key, value string) *SearchOptionsBuilder {
|
||||
if value != "" {
|
||||
b.options.conditions = append(b.options.conditions, fmt.Sprintf("%s LIKE ?", key))
|
||||
b.options.args = append(b.options.args, "%"+value+"%")
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) withGeneralEqual(key string, value any) *SearchOptionsBuilder {
|
||||
if value != "" {
|
||||
b.options.conditions = append(b.options.conditions, fmt.Sprintf("%s = ?", key))
|
||||
b.options.args = append(b.options.args, value)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) withGeneralJsonArrayContains(key string, value any) *SearchOptionsBuilder {
|
||||
if value != "" {
|
||||
b.options.conditions = append(b.options.conditions, fmt.Sprintf("json_array_contains(%s, ?)", key))
|
||||
b.options.args = append(b.options.args, value)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) WithName(name string) *SearchOptionsBuilder {
|
||||
return b.withGeneralLike("name", name)
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) WithDescription(description string) *SearchOptionsBuilder {
|
||||
return b.withGeneralLike("description", description)
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) WithRepository(repository string) *SearchOptionsBuilder {
|
||||
return b.withGeneralEqual("repository", repository)
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) WithProvides(provides string) *SearchOptionsBuilder {
|
||||
return b.withGeneralJsonArrayContains("provides", provides)
|
||||
}
|
||||
|
||||
func (b *SearchOptionsBuilder) Build() *SearchOptions {
|
||||
return &b.options
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
// 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 search_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search"
|
||||
)
|
||||
|
||||
func TestSearhOptionsBuilder(t *testing.T) {
|
||||
type testCase struct {
|
||||
name string
|
||||
prepare func() *search.SearchOptions
|
||||
expectedWhere string
|
||||
expectedArgs []any
|
||||
}
|
||||
|
||||
for _, tc := range []testCase{
|
||||
{
|
||||
name: "Empty fields",
|
||||
prepare: func() *search.SearchOptions {
|
||||
return search.NewSearchOptions().
|
||||
Build()
|
||||
},
|
||||
expectedWhere: "",
|
||||
expectedArgs: []any{},
|
||||
},
|
||||
{
|
||||
name: "All fields",
|
||||
prepare: func() *search.SearchOptions {
|
||||
return search.NewSearchOptions().
|
||||
WithName("foo").
|
||||
WithDescription("bar").
|
||||
WithRepository("buz").
|
||||
WithProvides("test").
|
||||
Build()
|
||||
},
|
||||
expectedWhere: "name LIKE ? AND description LIKE ? AND repository = ? AND json_array_contains(provides, ?)",
|
||||
expectedArgs: []any{"%foo%", "%bar%", "buz", "test"},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
whereClause, args := tc.prepare().WhereClause()
|
||||
assert.Equal(t, tc.expectedWhere, whereClause)
|
||||
assert.ElementsMatch(t, tc.expectedArgs, args)
|
||||
})
|
||||
}
|
||||
}
|
||||
49
repo.go
49
repo.go
@@ -30,7 +30,7 @@ import (
|
||||
"golang.org/x/exp/slices"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
|
||||
)
|
||||
@@ -60,43 +60,33 @@ func AddRepoCmd() *cli.Command {
|
||||
name := c.String("name")
|
||||
repoURL := c.String("url")
|
||||
|
||||
cfg := config.New()
|
||||
reposSlice := cfg.Repos(ctx)
|
||||
cfg := config.Config(ctx)
|
||||
|
||||
for _, repo := range reposSlice {
|
||||
for _, repo := range cfg.Repos {
|
||||
if repo.URL == repoURL {
|
||||
slog.Error("Repo already exists", "name", repo.Name)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
reposSlice = append(reposSlice, types.Repo{
|
||||
cfg.Repos = append(cfg.Repos, types.Repo{
|
||||
Name: name,
|
||||
URL: repoURL,
|
||||
})
|
||||
|
||||
cfg.SetRepos(ctx, reposSlice)
|
||||
|
||||
cfgFl, err := os.Create(cfg.GetPaths(ctx).ConfigPath)
|
||||
cfgFl, err := os.Create(config.GetPaths(ctx).ConfigPath)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error opening config file"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = cfg.Save(cfgFl)
|
||||
err = toml.NewEncoder(cfgFl).Encode(cfg)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error encoding config"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
db := database.New(cfg)
|
||||
err = db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error pulling repos"), "err", err)
|
||||
}
|
||||
|
||||
rs := repos.New(cfg, db)
|
||||
err = rs.Pull(ctx, cfg.Repos(ctx))
|
||||
err = repos.Pull(ctx, cfg.Repos)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error pulling repos"), "err", err)
|
||||
os.Exit(1)
|
||||
@@ -124,12 +114,11 @@ func RemoveRepoCmd() *cli.Command {
|
||||
ctx := c.Context
|
||||
|
||||
name := c.String("name")
|
||||
cfg := config.New()
|
||||
cfg := config.Config(ctx)
|
||||
|
||||
found := false
|
||||
index := 0
|
||||
reposSlice := cfg.Repos(ctx)
|
||||
for i, repo := range reposSlice {
|
||||
for i, repo := range cfg.Repos {
|
||||
if repo.Name == name {
|
||||
index = i
|
||||
found = true
|
||||
@@ -140,9 +129,9 @@ func RemoveRepoCmd() *cli.Command {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg.SetRepos(ctx, slices.Delete(reposSlice, index, index+1))
|
||||
cfg.Repos = slices.Delete(cfg.Repos, index, index+1)
|
||||
|
||||
cfgFl, err := os.Create(cfg.GetPaths(ctx).ConfigPath)
|
||||
cfgFl, err := os.Create(config.GetPaths(ctx).ConfigPath)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error opening config file"), "err", err)
|
||||
os.Exit(1)
|
||||
@@ -154,17 +143,12 @@ func RemoveRepoCmd() *cli.Command {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = os.RemoveAll(filepath.Join(cfg.GetPaths(ctx).RepoDir, name))
|
||||
err = os.RemoveAll(filepath.Join(config.GetPaths(ctx).RepoDir, name))
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error removing repo directory"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
db := database.New(cfg)
|
||||
err = db.Init(ctx)
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
err = db.DeletePkgs(ctx, "repository = ?", name)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error removing packages from database"), "err", err)
|
||||
@@ -183,14 +167,7 @@ func RefreshCmd() *cli.Command {
|
||||
Aliases: []string{"ref"},
|
||||
Action: func(c *cli.Context) error {
|
||||
ctx := c.Context
|
||||
cfg := config.New()
|
||||
db := database.New(cfg)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
rs := repos.New(cfg, db)
|
||||
err = rs.Pull(ctx, cfg.Repos(ctx))
|
||||
err := repos.Pull(ctx, config.Config(ctx).Repos)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error pulling repos"), "err", err)
|
||||
os.Exit(1)
|
||||
|
||||
@@ -25,7 +25,7 @@ elif (( $(echo "$COVERAGE < 80" | bc -l) )); then
|
||||
COLOR="#dfb317"
|
||||
fi
|
||||
|
||||
cat <<EOF > assets/coverage-badge.svg
|
||||
cat <<EOF > coverage-badge.svg
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="109" height="20">
|
||||
<linearGradient id="smooth" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/bin/bash
|
||||
# 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/>.
|
||||
|
||||
|
||||
TRANSLATIONS_DIR="internal/translations/po"
|
||||
|
||||
if [ ! -d "$TRANSLATIONS_DIR" ]; then
|
||||
echo "Error: directory '$TRANSLATIONS_DIR' not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
declare -A TOTAL_STRINGS_MAP
|
||||
declare -A TRANSLATED_STRINGS_MAP
|
||||
|
||||
for PO_FILE in $(find "$TRANSLATIONS_DIR" -type f -name "*.po"); do
|
||||
LANG_DIR=$(dirname "$PO_FILE")
|
||||
LANG=$(basename "$LANG_DIR")
|
||||
|
||||
STATS=$(LC_ALL=C msgfmt --statistics -o /dev/null "$PO_FILE" 2>&1)
|
||||
|
||||
NUMBERS=($(echo "$STATS" | grep -o '[0-9]\+'))
|
||||
|
||||
case ${#NUMBERS[@]} in
|
||||
1) TRANSLATED_STRINGS=${NUMBERS[0]}; UNTRANSLATED_STRINGS=0 ;; # all translated
|
||||
2) TRANSLATED_STRINGS=${NUMBERS[0]}; UNTRANSLATED_STRINGS=${NUMBERS[1]} ;; # no fuzzy
|
||||
3) TRANSLATED_STRINGS=${NUMBERS[0]}; UNTRANSLATED_STRINGS=${NUMBERS[2]} ;; # with fuzzy
|
||||
*) TRANSLATED_STRINGS=0; UNTRANSLATED_STRINGS=0 ;;
|
||||
esac
|
||||
|
||||
TOTAL_STRINGS=$((TRANSLATED_STRINGS + UNTRANSLATED_STRINGS))
|
||||
|
||||
TOTAL_STRINGS_MAP[$LANG]=$((TOTAL_STRINGS_MAP[$LANG] + TOTAL_STRINGS))
|
||||
TRANSLATED_STRINGS_MAP[$LANG]=$((TRANSLATED_STRINGS_MAP[$LANG] + TRANSLATED_STRINGS))
|
||||
done
|
||||
|
||||
for LANG in "${!TOTAL_STRINGS_MAP[@]}"; do
|
||||
TOTAL=${TOTAL_STRINGS_MAP[$LANG]}
|
||||
TRANSLATED=${TRANSLATED_STRINGS_MAP[$LANG]}
|
||||
if [ "$TOTAL" -eq 0 ]; then
|
||||
PERCENTAGE="0.00"
|
||||
else
|
||||
PERCENTAGE=$(echo "scale=2; ($TRANSLATED / $TOTAL) * 100" | bc)
|
||||
fi
|
||||
COLOR="#4c1"
|
||||
if (( $(echo "$PERCENTAGE < 50" | bc -l) )); then
|
||||
COLOR="#e05d44"
|
||||
elif (( $(echo "$PERCENTAGE < 80" | bc -l) )); then
|
||||
COLOR="#dfb317"
|
||||
fi
|
||||
cat <<EOF > assets/i18n-$LANG-badge.svg
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="129" height="20">
|
||||
<linearGradient id="smooth" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<mask id="round">
|
||||
<rect width="129" height="20" rx="3" fill="#fff"/>
|
||||
</mask>
|
||||
<g mask="url(#round)">
|
||||
<rect width="75" height="20" fill="#555"/>
|
||||
<rect x="75" width="64" height="20" fill="${COLOR}"/>
|
||||
<rect width="129" height="20" fill="url(#smooth)"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
|
||||
<text x="37" y="15" fill="#010101" fill-opacity=".3">$LANG translate</text>
|
||||
<text x="37" y="14">$LANG translate</text>
|
||||
<text x="100" y="15" fill="#010101" fill-opacity=".3">${PERCENTAGE}%</text>
|
||||
<text x="100" y="14">${PERCENTAGE}%</text>
|
||||
</g>
|
||||
</svg>
|
||||
EOF
|
||||
done
|
||||
119
search.go
119
search.go
@@ -1,119 +0,0 @@
|
||||
// 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 main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"text/template"
|
||||
|
||||
"github.com/leonelquinteros/gotext"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search"
|
||||
)
|
||||
|
||||
func SearchCmd() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "search",
|
||||
Usage: gotext.Get("Search packages"),
|
||||
Aliases: []string{"s"},
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "name",
|
||||
Aliases: []string{"n"},
|
||||
Usage: gotext.Get("Search by name"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "description",
|
||||
Aliases: []string{"d"},
|
||||
Usage: gotext.Get("Search by description"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "repository",
|
||||
Aliases: []string{"repo"},
|
||||
Usage: gotext.Get("Search by repository"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "provides",
|
||||
Aliases: []string{"p"},
|
||||
Usage: gotext.Get("Search by provides"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "format",
|
||||
Aliases: []string{"f"},
|
||||
Usage: gotext.Get("Format output using a Go template"),
|
||||
},
|
||||
},
|
||||
Action: func(c *cli.Context) error {
|
||||
ctx := c.Context
|
||||
cfg := config.New()
|
||||
db := database.New(cfg)
|
||||
err := db.Init(ctx)
|
||||
defer db.Close()
|
||||
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
format := c.String("format")
|
||||
var tmpl *template.Template
|
||||
if format != "" {
|
||||
tmpl, err = template.New("format").Parse(format)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error parsing format template"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
s := search.New(db)
|
||||
|
||||
packages, err := s.Search(
|
||||
ctx,
|
||||
search.NewSearchOptions().
|
||||
WithName(c.String("name")).
|
||||
WithDescription(c.String("description")).
|
||||
WithRepository(c.String("repository")).
|
||||
WithProvides(c.String("provides")).
|
||||
Build(),
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error parsing format template"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for _, dbPkg := range packages {
|
||||
if tmpl != nil {
|
||||
err = tmpl.Execute(os.Stdout, dbPkg)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error executing template"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println()
|
||||
} else {
|
||||
fmt.Println(dbPkg.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
86
upgrade.go
86
upgrade.go
@@ -29,6 +29,7 @@ import (
|
||||
"github.com/urfave/cli/v2"
|
||||
"go.elara.ws/vercmp"
|
||||
"golang.org/x/exp/maps"
|
||||
"golang.org/x/exp/slices"
|
||||
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
|
||||
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
|
||||
@@ -38,7 +39,6 @@ import (
|
||||
"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"
|
||||
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search"
|
||||
)
|
||||
|
||||
func UpgradeCmd() *cli.Command {
|
||||
@@ -61,7 +61,7 @@ func UpgradeCmd() *cli.Command {
|
||||
rs := repos.New(cfg, db)
|
||||
err := db.Init(ctx)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error initialization database"), "err", err)
|
||||
slog.Error(gotext.Get("Error db init"), "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func UpgradeCmd() *cli.Command {
|
||||
}
|
||||
}
|
||||
|
||||
updates, err := checkForUpdates(ctx, mgr, cfg, db, rs, info)
|
||||
updates, err := checkForUpdates(ctx, mgr, cfg, rs, info)
|
||||
if err != nil {
|
||||
slog.Error(gotext.Get("Error checking for updates"), "err", err)
|
||||
os.Exit(1)
|
||||
@@ -121,7 +121,6 @@ func checkForUpdates(
|
||||
ctx context.Context,
|
||||
mgr manager.Manager,
|
||||
cfg *config.ALRConfig,
|
||||
db *database.Database,
|
||||
rs *repos.Repos,
|
||||
info *distro.OSRelease,
|
||||
) ([]database.Package, error) {
|
||||
@@ -131,51 +130,42 @@ func checkForUpdates(
|
||||
}
|
||||
|
||||
pkgNames := maps.Keys(installed)
|
||||
|
||||
s := search.New(db)
|
||||
|
||||
var out []database.Package
|
||||
for _, pkgName := range pkgNames {
|
||||
matches := build.RegexpALRPackageName.FindStringSubmatch(pkgName)
|
||||
if matches != nil {
|
||||
packageName := matches[build.RegexpALRPackageName.SubexpIndex("package")]
|
||||
repoName := matches[build.RegexpALRPackageName.SubexpIndex("repo")]
|
||||
|
||||
pkgs, err := s.Search(
|
||||
ctx,
|
||||
search.NewSearchOptions().
|
||||
WithName(packageName).
|
||||
WithRepository(repoName).
|
||||
Build(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(pkgs) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
pkg := pkgs[0]
|
||||
|
||||
repoVer := pkg.Version
|
||||
releaseStr := overrides.ReleasePlatformSpecific(pkg.Release, info)
|
||||
|
||||
if pkg.Release != 0 && pkg.Epoch == 0 {
|
||||
repoVer = fmt.Sprintf("%s-%s", pkg.Version, releaseStr)
|
||||
} else if pkg.Release != 0 && pkg.Epoch != 0 {
|
||||
repoVer = fmt.Sprintf("%d:%s-%s", pkg.Epoch, pkg.Version, releaseStr)
|
||||
}
|
||||
|
||||
c := vercmp.Compare(repoVer, installed[pkgName])
|
||||
if c == 0 || c == -1 {
|
||||
continue
|
||||
} else if c == 1 {
|
||||
out = append(out, pkg)
|
||||
}
|
||||
}
|
||||
|
||||
found, _, err := rs.FindPkgs(ctx, pkgNames)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var out []database.Package
|
||||
for pkgName, pkgs := range found {
|
||||
if slices.Contains(cfg.IgnorePkgUpdates(ctx), pkgName) {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(pkgs) > 1 {
|
||||
// Puts the element with the highest version first
|
||||
slices.SortFunc(pkgs, func(a, b database.Package) int {
|
||||
return vercmp.Compare(a.Version, b.Version)
|
||||
})
|
||||
}
|
||||
|
||||
// First element is the package we want to install
|
||||
pkg := pkgs[0]
|
||||
|
||||
repoVer := pkg.Version
|
||||
releaseStr := overrides.ReleasePlatformSpecific(pkg.Release, info)
|
||||
|
||||
if pkg.Release != 0 && pkg.Epoch == 0 {
|
||||
repoVer = fmt.Sprintf("%s-%s", pkg.Version, releaseStr)
|
||||
} else if pkg.Release != 0 && pkg.Epoch != 0 {
|
||||
repoVer = fmt.Sprintf("%d:%s-%s", pkg.Epoch, pkg.Version, releaseStr)
|
||||
}
|
||||
|
||||
c := vercmp.Compare(repoVer, installed[pkgName])
|
||||
if c == 0 || c == -1 {
|
||||
continue
|
||||
} else if c == 1 {
|
||||
out = append(out, pkg)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user