46 Commits

Author SHA1 Message Date
65ab4de561 refactor: move distro from internal to pkg 2025-06-09 22:58:34 +03:00
1cdab8dfed refactor: move alr.sh parsing to pkg 2025-06-09 17:56:46 +03:00
237e2c338d refactor: move types from internal to pkg 2025-06-09 13:34:43 +03:00
703ab8e8c4 refactor: move pkg/ to internal/ and update imports
Some checks failed
E2E / tests (pull_request) Has been cancelled
Pre-commit / pre-commit (pull_request) Successful in 5m35s
Restructure project by relocating package contents from pkg/ to internal/ to better reflect internal-only usage. This commit is initial step to prepare project for public api
2025-06-09 10:15:47 +03:00
06fcab4ce7 fix: prevent for building dependencies twice (#99)
closes #94

Reviewed-on: #99
Co-authored-by: Maxim Slipenko <no-reply@maxim.slipenko.com>
Co-committed-by: Maxim Slipenko <no-reply@maxim.slipenko.com>
2025-06-08 17:57:18 +00:00
7741c7368b исправление ссылки на alr-LG 2025-06-06 13:49:14 +00:00
69f4af0a4d ci: fix
Some checks failed
Create Release / changelog (push) Failing after 2m2s
2025-05-30 20:01:16 +03:00
bcf627f176 ci: try add privileged true
Some checks failed
Create Release / changelog (push) Has been cancelled
2025-05-30 20:00:15 +03:00
6ec95e4bd9 ci: add bindfs install
Some checks failed
Create Release / changelog (push) Failing after 2m5s
2025-05-30 19:50:59 +03:00
578da7ff52 Revert "fix: use mount only for non-root users"
This reverts commit c51caf5c52.
2025-05-30 19:50:38 +03:00
c51caf5c52 fix: use mount only for non-root users
Some checks failed
Create Release / changelog (push) Failing after 2m0s
2025-05-30 19:41:17 +03:00
09dba577c6 ci: fix
Some checks failed
Create Release / changelog (push) Failing after 2m0s
2025-05-30 19:31:12 +03:00
ca82bf3024 ci: fix
Some checks failed
Create Release / changelog (push) Failing after 2m3s
2025-05-30 19:26:08 +03:00
c0023db6cd chore: fix install
Some checks failed
Create Release / changelog (push) Failing after 2m12s
2025-05-30 19:02:04 +03:00
152e5077ec ci(release): add make install
Some checks failed
Create Release / changelog (push) Failing after 2m0s
2025-05-30 18:53:17 +03:00
15ba8700e8 ci: set gitea/runner-images:ubuntu-latest for release
Some checks failed
Create Release / changelog (push) Failing after 1m50s
2025-05-30 17:36:51 +03:00
a8aefc0524 chore: replace git urls in tests
Some checks failed
E2E / tests (pull_request) Failing after 2m4s
Pre-commit / pre-commit (pull_request) Successful in 14m15s
Create Release / changelog (push) Has been cancelled
2025-05-30 07:49:58 +03:00
9540030579 изменение: скрипт установки берёт бинарники из релиза, README.md 2025-05-29 17:48:40 +03:00
4f9d4260b8 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 32s
2025-05-17 19:41:50 +03:00
38b5e6f581 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 33s
2025-05-17 19:19:09 +03:00
408bd12302 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 33s
2025-05-17 19:12:19 +03:00
fb83d544de добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 32s
2025-05-17 19:08:54 +03:00
2cb963d4b2 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 33s
2025-05-17 19:00:04 +03:00
e74d74cdf6 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 35s
2025-05-17 18:54:59 +03:00
5b3d53d253 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 34s
2025-05-17 18:41:57 +03:00
36e704f735 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза 2025-05-17 18:32:25 +03:00
07356d5e55 добавление изменения версии в репозитории alr-default + сборка бинарников для релиза
Some checks failed
Create Release / changelog (push) Failing after 1m5s
2025-05-17 18:06:49 +03:00
52bd6aca93 Исправление README.md 2025-05-17 12:11:57 +03:00
2f1770b43b Дополнение README.md 2025-05-16 23:07:18 +03:00
9d5b5b51ff Дополнение README.md 2025-05-16 23:05:58 +03:00
c88478a450 ci: fix release workflow
All checks were successful
Create Release / changelog (push) Successful in 54s
2025-05-16 21:45:14 +03:00
3e61fec67c ci: fix release workflow
Some checks failed
Create Release / changelog (push) Has been cancelled
2025-05-16 21:42:56 +03:00
6f484a1169 ci: fix release workflow
All checks were successful
Create Release / changelog (push) Successful in 49s
2025-05-16 21:30:57 +03:00
dddcb9b7b0 ci: fix release workflow
Some checks failed
Create Release / changelog (push) Failing after 40s
2025-05-16 21:27:04 +03:00
b03d94e48b ci: add release workflow
Some checks failed
E2E / tests (pull_request) Successful in 1m45s
Pre-commit / pre-commit (pull_request) Successful in 1m38s
Create Release / changelog (push) Failing after 11s
2025-05-16 21:14:37 +03:00
f92bd7089a add set-ref command and refactor tests
All checks were successful
E2E / tests (pull_request) Successful in 1m42s
Pre-commit / pre-commit (pull_request) Successful in 1m23s
2025-05-16 20:48:14 +03:00
eb2356458c ci: add e2e (#90)
Reviewed-on: #90
Co-authored-by: Maxim Slipenko <no-reply@maxim.slipenko.com>
Co-committed-by: Maxim Slipenko <no-reply@maxim.slipenko.com>
2025-05-16 16:19:24 +00:00
131f455eff add repo subcommand
All checks were successful
Pre-commit / pre-commit (pull_request) Successful in 1m36s
2025-05-14 23:04:28 +03:00
1e52d30f4c fix list command
All checks were successful
Pre-commit / pre-commit (pull_request) Successful in 1m35s
2025-05-13 23:31:56 +03:00
40ec0ac6e1 add --upgradable option for list
All checks were successful
Pre-commit / pre-commit (pull_request) Successful in 1m36s
2025-05-13 23:26:12 +03:00
443e481561 fix support of multiple packages in one alr.sh
All checks were successful
Pre-commit / pre-commit (pull_request) Successful in 1m37s
2025-05-13 21:55:23 +03:00
c892310f69 fix Makefile
All checks were successful
Pre-commit / pre-commit (pull_request) Successful in 2m49s
2025-05-12 20:11:55 +03:00
750513b119 fix ci
Some checks failed
Pre-commit / pre-commit (pull_request) Failing after 2m36s
2025-05-12 19:46:52 +03:00
ce1836b646 ci: use go 1.24
Some checks failed
Pre-commit / pre-commit (pull_request) Failing after 3m52s
2025-05-12 19:30:15 +03:00
56b9f3211c ci: add simple workflow for pre-commit
Some checks failed
Pre-commit / pre-commit (pull_request) Failing after 5m29s
2025-05-12 19:22:50 +03:00
fae63e28f9 fix license-header.tmpl 2025-05-12 19:22:28 +03:00
97 changed files with 1840 additions and 1084 deletions

View File

@@ -0,0 +1,56 @@
# ALR - Any Linux Repository
# Copyright (C) 2025 The ALR Authors
#
# 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/>.
name: E2E
on:
push:
branches: [ main ]
pull_request:
jobs:
tests:
runs-on: ubuntu-latest
container:
image: altlinux.space/maks1ms/actions-container-runner:latest
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: https://github.com/actions/setup-go@v5
with:
go-version: '1.24'
cache: false
# - name: Cache Podman images
# uses: actions/cache@v4
# with:
# path: |
# ~/.local/share/containers/storage
# /var/lib/containers/storage
# key: ${{ runner.os }}-primes
- name: Run E2E tests
env:
IGNORE_ROOT_CHECK: 1
run: |
make e2e-test

View File

@@ -0,0 +1,51 @@
# ALR - Any Linux Repository
# Copyright (C) 2025 The ALR Authors
#
# 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/>.
name: Pre-commit
on:
push:
branches: [ main ]
pull_request:
jobs:
pre-commit:
runs-on: ubuntu-latest
container:
image: docker.gitea.com/runner-images:ubuntu-latest
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
- name: Set up Go
uses: https://github.com/actions/setup-go@v5
with:
go-version: '1.24'
- name: Set up Python for pre-commit
uses: https://github.com/actions/setup-python@v5
with:
python-version: '3.12'
- name: Install deps
run: apt-get update && apt-get install -y gettext bc
- run: pip install pre-commit
- run: pre-commit install
- run: pre-commit run --all-files

View File

@@ -0,0 +1,120 @@
# ALR - Any Linux Repository
# Copyright (C) 2025 The ALR Authors
#
# 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/>.
name: Create Release
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
jobs:
changelog:
runs-on: ubuntu-latest
steps:
- name: Checkout this repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Get Changes between Tags
id: changes
uses: simbo/changes-between-tags-action@v1
- name: Set version
run: |
version=$(echo "${GITHUB_REF##*/}" | sed 's/^v//')
echo "Version - $version"
echo "VERSION=$version" >> $GITHUB_ENV
- name: Prepare for install
run: |
apt-get update && apt-get install -y libcap2-bin bindfs
- name: Build alr
env:
IGNORE_ROOT_CHECK: 1
run: |
make build
- name: Create tar.gz
run: |
mkdir -p ./out/completion
cp alr ./out
cp scripts/completion/bash ./out/completion/alr
cp scripts/completion/zsh ./out/completion/_alr
( cd out && tar -czvf ../alr-${{ env.VERSION }}-linux-x86_64.tar.gz * )
- name: Release
uses: akkuman/gitea-release-action@v1
with:
body: ${{ steps.changes.outputs.changes }}
files: |-
alr-${{ env.VERSION }}-linux-x86_64.tar.gz
- name: Checkout alr-default repository
uses: actions/checkout@v4
with:
repository: Plemya-x/alr-default
token: ${{ secrets.GITEAPUBLIC }}
path: alr-default
- name: Update version in alr-bin
run: |
# Замените значения в файле с конфигурацией
sed -i "s/version='[0-9]\+\.[0-9]\+\.[0-9]\+'/version='${{ env.VERSION }}'/g" alr-default/alr-bin/alr.sh
sed -i "s/release='[0-9]\+'/release='1'/g" alr-default/alr-bin/alr.sh
- name: Install alr
run: |
make install
# temporary fix
groupadd wheel
usermod -aG wheel root
- name: Build packages
run: |
SCRIPT_PATH=alr-default/alr-bin/alr.sh
ALR_DISTRO=altlinux ALR_PKG_FORMAT=rpm alr build -s "$SCRIPT_PATH"
ALR_PKG_FORMAT=rpm alr build -s "$SCRIPT_PATH"
ALR_PKG_FORMAT=deb alr build -s "$SCRIPT_PATH"
ALR_PKG_FORMAT=archlinux alr build -s "$SCRIPT_PATH"
- name: Upload assets
uses: akkuman/gitea-release-action@v1
with:
body: ${{ steps.changes.outputs.changes }}
files: |-
alr-bin+alr-default_${{ env.VERSION }}-1.red80_amd64.deb \
alr-bin+alr-default-${{ env.VERSION }}-1-x86_64.pkg.tar.zst \
alr-bin+alr-default-${{ env.VERSION }}-1.red80.x86_64.rpm \
alr-bin+alr-default-${{ env.VERSION }}-alt1.x86_64.rpm
- name: Commit changes
run: |
cd alr-default
git config user.name "gitea"
git config user.email "admin@plemya-x.ru"
git add .
git commit -m "Обновление версии до ${{ env.VERSION }}"
git push

View File

@@ -1,6 +1,6 @@
NAME := alr NAME := alr
GIT_VERSION = $(shell git describe --tags ) GIT_VERSION = $(shell git describe --tags )
IGNORE_ROOT_CHECK ?= 0
DESTDIR ?= DESTDIR ?=
PREFIX ?= /usr/local PREFIX ?= /usr/local
BIN := ./$(NAME) BIN := ./$(NAME)
@@ -24,8 +24,9 @@ $(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/Plemya-x/ALR/internal/config.Version=$(GIT_VERSION)'" -o $@
check-no-root: check-no-root:
@if [[ "$$(whoami)" == 'root' ]]; then \ @if [ "$$IGNORE_ROOT_CHECK" != "1" ] && [ "`whoami`" = "root" ]; then \
echo "This target shouldn't run as root" 1>&2; \ echo "This target shouldn't run as root" 1>&2; \
echo "Set IGNORE_ROOT_CHECK=1 to override" 1>&2; \
exit 1; \ exit 1; \
fi fi
@@ -38,6 +39,12 @@ install: \
$(INSTALED_BIN): $(BIN) $(INSTALED_BIN): $(BIN)
install -Dm755 $< $@ install -Dm755 $< $@
setcap cap_setuid,cap_setgid+ep $(INSTALED_BIN) setcap cap_setuid,cap_setgid+ep $(INSTALED_BIN)
@if id alr >/dev/null 2>&1; then \
echo "User 'alr' already exists. Skipping."; \
else \
useradd -r -s /usr/sbin/nologin alr; \
fi
install -d -o alr -g alr -m 755 /var/cache/alr /etc/alr
$(INSTALLED_BASH_COMPLETION): $(BASH_COMPLETION) $(INSTALLED_BASH_COMPLETION): $(BASH_COMPLETION)
install -Dm755 $< $@ install -Dm755 $< $@
@@ -54,7 +61,7 @@ uninstall:
clean clear: clean clear:
rm -f $(BIN) rm -f $(BIN)
OLD_FILES=$$(< old-files) OLD_FILES=$(shell cat old-files)
IGNORE_OLD_FILES := $(foreach file,$(shell cat old-files),-ignore $(file)) IGNORE_OLD_FILES := $(foreach file,$(shell cat old-files),-ignore $(file))
update-license: update-license:
$(ADD_LICENSE_BIN) -v -f license-header-old-files.tmpl $(OLD_FILES) $(ADD_LICENSE_BIN) -v -f license-header-old-files.tmpl $(OLD_FILES)
@@ -76,7 +83,9 @@ test-coverage:
update-deps-cve: update-deps-cve:
bash scripts/update-deps-cve.sh bash scripts/update-deps-cve.sh
e2e-test: clean build prepare-for-e2e-test: clean build
rm -f ./e2e-tests/alr rm -f ./e2e-tests/alr
cp alr e2e-tests cp alr e2e-tests
e2e-test: prepare-for-e2e-test
go test -tags=e2e ./... go test -tags=e2e ./...

View File

@@ -20,10 +20,10 @@ ALR написан на чистом Go и после сборки не имее
Установочный скрипт автоматически загрузит и установит соответствующий пакет ALR в вашей системе. Чтобы использовать его, просто выполните следующую команду: Установочный скрипт автоматически загрузит и установит соответствующий пакет ALR в вашей системе. Чтобы использовать его, просто выполните следующую команду:
```bash ```bash
curl -fsSL plemya-x.ru/alr/install.sh | bash curl -fsSL https://gitea.plemya-x.ru/Plemya-x/ALR/raw/branch/master/scripts/install.sh | bash
``` ```
**ВАЖНО**: При этом скрипт будет загружен и запущен с <https://plemya-x.ru/alr/install.sh>. Пожалуйста, просматривайте любые скрипты, которые вы скачиваете из Интернета (включая этот), прежде чем запускать их. **ВАЖНО**: При этом скрипт будет загружен и запущен [скрипт](https://gitea.plemya-x.ru/Plemya-x/ALR/src/branch/master/scripts/install.sh). Пожалуйста, просматривайте любые скрипты, которые вы скачиваете из Интернета (включая этот), прежде чем запускать их.
### Сборка из исходного кода ### Сборка из исходного кода
@@ -52,9 +52,17 @@ ALR был создан потому, что упаковка программн
Репозитории alr - это git-хранилища, которые содержат каталог для каждого пакета с файлом `alr.sh` внутри. Файл `alr.sh` содержит все инструкции по сборке пакета и информацию о нем. Скрипты `alr.sh` аналогичны скриптам Aur PKGBUILD. Репозитории 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 [Plemya-x/alr-default](https://gitea.plemya-x.ru/Plemya-x/alr-default.git)
``` ```
alr addrepo --name alr-repo --url https://gitea.plemya-x.ru/Plemya-x/alr-repo.git alr repo add alr-default https://gitea.plemya-x.ru/Plemya-x/alr-default.git
```
Репозиторий пакетов [Plemya-x/alr-repo](https://gitea.plemya-x.ru/Plemya-x/alr-repo.git) можно подключить так:
```
alr repo add alr-repo https://gitea.plemya-x.ru/Plemya-x/alr-repo.git
```
Репозиторий Linux-Gaming [Plemya-x/alr-LG](https://gitea.plemya-x.ru/Plemya-x/alr-LG.git) можно подключить так:
```
alr repo add alr-LG https://gitea.plemya-x.ru/Plemya-x/alr-LG.git
``` ```
--- ---

View File

@@ -11,7 +11,7 @@
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"> <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="15" fill="#010101" fill-opacity=".3">coverage</text>
<text x="33.5" y="14">coverage</text> <text x="33.5" y="14">coverage</text>
<text x="86" y="15" fill="#010101" fill-opacity=".3">17.0%</text> <text x="86" y="15" fill="#010101" fill-opacity=".3">16.7%</text>
<text x="86" y="14">17.0%</text> <text x="86" y="14">16.7%</text>
</g> </g>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 926 B

After

Width:  |  Height:  |  Size: 926 B

View File

@@ -28,12 +28,12 @@ import (
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/osutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/osutils"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
func BuildCmd() *cli.Command { func BuildCmd() *cli.Command {
@@ -97,7 +97,7 @@ func BuildCmd() *cli.Command {
var script string var script string
var packages []string var packages []string
var res *build.BuildResult var res []*build.BuiltDep
var scriptArgs *build.BuildPackageFromScriptArgs var scriptArgs *build.BuildPackageFromScriptArgs
var dbArgs *build.BuildPackageFromDbArgs var dbArgs *build.BuildPackageFromDbArgs
@@ -118,7 +118,11 @@ func BuildCmd() *cli.Command {
return cliutils.FormatCliExit(gotext.Get("Cannot get absolute script path"), err) return cliutils.FormatCliExit(gotext.Get("Cannot get absolute script path"), err)
} }
packages = append(packages, c.String("script-package")) subpackage := c.String("subpackage")
if subpackage != "" {
packages = append(packages, subpackage)
}
scriptArgs = &build.BuildPackageFromScriptArgs{ scriptArgs = &build.BuildPackageFromScriptArgs{
Script: script, Script: script,
@@ -218,9 +222,9 @@ func BuildCmd() *cli.Command {
return cliutils.FormatCliExit(gotext.Get("Error building package"), err) return cliutils.FormatCliExit(gotext.Get("Error building package"), err)
} }
for _, pkgPath := range res.PackagePaths { for _, pkg := range res {
name := filepath.Base(pkgPath) name := filepath.Base(pkg.Path)
err = osutils.Move(pkgPath, filepath.Join(wd, name)) err = osutils.Move(pkg.Path, filepath.Join(wd, name))
if err != nil { if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error moving the package"), err) return cliutils.FormatCliExit(gotext.Get("Error moving the package"), err)
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,10 +30,7 @@ func TestE2EBashCompletion(t *testing.T) {
"bash-completion", "bash-completion",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( execShouldNoError(t, r, "alr", "install", "--generate-bash-completion")
"alr", "install", "--generate-bash-completion",
))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -25,7 +25,6 @@ import (
"io" "io"
"log" "log"
"os" "os"
"os/exec"
"testing" "testing"
"time" "time"
@@ -121,29 +120,6 @@ var COMMON_SYSTEMS []string = []string{
"ubuntu-24.04", "ubuntu-24.04",
} }
func init() {
for _, id := range ALL_SYSTEMS {
buildAlrTestImage(id)
}
}
func buildAlrTestImage(id string) {
cmd := exec.Command(
"docker",
"build",
"-t", fmt.Sprintf("alr-testimage-%s", id),
"-f", fmt.Sprintf("images/Dockerfile.%s", id),
".",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Println("Error:", err)
return
}
}
func dockerMultipleRun(t *testing.T, name string, ids []string, f func(t *testing.T, runnable e2e.Runnable)) { func dockerMultipleRun(t *testing.T, name string, ids []string, f func(t *testing.T, runnable e2e.Runnable)) {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
for _, id := range ids { for _, id := range ids {
@@ -158,23 +134,39 @@ func dockerMultipleRun(t *testing.T, name string, ids []string, f func(t *testin
e, err := e2e.New(e2e.WithVerbose(), e2e.WithName(fmt.Sprintf("alr-%s", truncatedHash))) e, err := e2e.New(e2e.WithVerbose(), e2e.WithName(fmt.Sprintf("alr-%s", truncatedHash)))
assert.NoError(t, err) assert.NoError(t, err)
t.Cleanup(e.Close) t.Cleanup(e.Close)
imageId := fmt.Sprintf("alr-testimage-%s", id) imageId := fmt.Sprintf("ghcr.io/maks1ms/alr-e2e-test-image-%s", id)
runnable := e.Runnable(dockerName).Init( runnable := e.Runnable(dockerName).Init(
e2e.StartOptions{ e2e.StartOptions{
Image: imageId, Image: imageId,
Volumes: []string{ Volumes: []string{
// "./alr:/usr/bin/alr", "./alr:/tmp/alr",
}, },
Privileged: true, Privileged: true,
}, },
) )
assert.NoError(t, e2e.StartAndWaitReady(runnable)) assert.NoError(t, e2e.StartAndWaitReady(runnable))
err = runnable.Exec(e2e.NewCommand("/bin/alr-test-setup", "alr-install"))
if err != nil {
panic(err)
}
err = runnable.Exec(e2e.NewCommand("/bin/alr-test-setup", "passwordless-sudo-setup"))
if err != nil {
panic(err)
}
f(t, runnable) f(t, runnable)
}) })
} }
}) })
} }
func execShouldNoError(t *testing.T, r e2e.Runnable, cmd string, args ...string) {
assert.NoError(t, r.Exec(e2e.NewCommand(cmd, args...)))
}
func execShouldError(t *testing.T, r e2e.Runnable, cmd string, args ...string) {
assert.Error(t, r.Exec(e2e.NewCommand(cmd, args...)))
}
func runTestCommands(t *testing.T, r e2e.Runnable, timeout time.Duration, expects []expect.Batcher) { func runTestCommands(t *testing.T, r e2e.Runnable, timeout time.Duration, expects []expect.Batcher) {
exp, _, err, _ := e2eSpawn( exp, _, err, _ := e2eSpawn(
r, r,
@@ -188,3 +180,23 @@ func runTestCommands(t *testing.T, r e2e.Runnable, timeout time.Duration, expect
) )
assert.NoError(t, err) assert.NoError(t, err)
} }
const REPO_NAME_FOR_E2E_TESTS = "alr-repo"
const REPO_URL_FOR_E2E_TESTS = "https://gitea.plemya-x.ru/Plemya-x/repo-for-tests.git"
func defaultPrepare(t *testing.T, r e2e.Runnable) {
execShouldNoError(t, r,
"sudo",
"alr",
"repo",
"add",
REPO_NAME_FOR_E2E_TESTS,
REPO_URL_FOR_E2E_TESTS,
)
execShouldNoError(t, r,
"sudo",
"alr",
"ref",
)
}

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,26 +30,9 @@ func TestE2EGroupAndSummaryField(t *testing.T) {
"group-and-summary-field", "group-and-summary-field",
RPM_SYSTEMS, RPM_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "sh", "-c", "alr search --name test-group-and-summary --format \"{{.Group}}\" | grep ^System/Base$")
"alr", execShouldNoError(t, r, "sh", "-c", "alr search --name test-group-and-summary --format \"{{.Summary}}\" | grep \"^Custom summary$\"")
"addrepo",
"--name",
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sh", "-c", "alr search --name test-group-and-summary --format \"{{.Group}}\" | grep ^System/Base$",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sh", "-c", "alr search --name test-group-and-summary --format \"{{.Summary}}\" | grep \"^Custom summary$\"",
))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -1,4 +0,0 @@
FROM alpine:latest
RUN adduser -s /bin/bash alr-user
USER alr-user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,6 +0,0 @@
FROM registry.altlinux.org/sisyphus/alt:latest
RUN apt-get update && apt-get install -y ca-certificates rpm-build
RUN useradd -m -s /bin/bash alr-user
USER alr-user
WORKDIR /home/alr-user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,4 +0,0 @@
FROM archlinux:latest
RUN useradd -m -s /bin/bash alr-user
USER alr-user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,18 +0,0 @@
FROM fedora:41
RUN dnf install -y ca-certificates sudo rpm-build bindfs
RUN <<EOF
useradd -m -s /bin/bash -G wheel user
echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/user
chmod 0440 /etc/sudoers.d/user
useradd -m -s /bin/bash alr
mkdir -p /var/cache/alr /etc/alr
chown alr:alr /var/cache/alr /etc/alr
EOF
COPY ./alr /usr/bin
RUN <<EOF
setcap cap_setuid,cap_setgid+ep /usr/bin/alr
EOF
USER user
WORKDIR /home/user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,4 +0,0 @@
FROM opensuse/leap:latest
RUN useradd -m -s /bin/bash alr-user
USER alr-user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,4 +0,0 @@
FROM registry.red-soft.ru/ubi8/ubi:latest
RUN useradd -m -s /bin/bash alr-user
USER alr-user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -1,17 +0,0 @@
FROM ubuntu:24.10
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates sudo libcap2-bin
RUN <<EOF
useradd -m -s /bin/bash user
echo "user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/user
chmod 0440 /etc/sudoers.d/user
useradd -m -s /bin/bash alr
mkdir -p /var/cache/alr /etc/alr
chown alr:alr /var/cache/alr /etc/alr
EOF
COPY ./alr /usr/bin
RUN <<EOF
setcap cap_setuid,cap_setgid+ep /usr/bin/alr
EOF
USER user
ENTRYPOINT ["tail", "-f", "/dev/null"]

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,21 +30,11 @@ func TestE2EIssue32Interactive(t *testing.T) {
"issue-32-interactive", "issue-32-interactive",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
assert.NoError(t, r.Exec(e2e.NewCommand( execShouldNoError(t, r, "alr", "--interactive=false", "remove", "ca-certificates")
"sudo", "alr", "--interactive=false", "remove", "ca-certificates", execShouldNoError(t, r, "sudo", "alr", "--interactive=false", "remove", "openssl")
))) execShouldNoError(t, r, "alr", "fix")
execShouldNoError(t, r, "sudo", "apt-get", "update")
assert.NoError(t, r.Exec(e2e.NewCommand( execShouldNoError(t, r, "sudo", "alr", "--interactive=false", "install", "ca-certificates")
"sudo", "alr", "--interactive=false", "remove", "openssl",
)))
assert.NoError(t, r.Exec(e2e.NewCommand(
"alr", "fix",
)))
assert.NoError(t, r.Exec(e2e.NewCommand(
"sudo", "alr", "--interactive=false", "install", "ca-certificates",
)))
}, },
) )
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,51 +30,11 @@ func TestE2EIssue41AutoreqSkiplist(t *testing.T) {
"issue-41-autoreq-skiplist", "issue-41-autoreq-skiplist",
AUTOREQ_AUTOPROV_SYSTEMS, AUTOREQ_AUTOPROV_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "alr", "build", "-p", "alr-repo/test-autoreq-autoprov")
"alr", execShouldNoError(t, r, "sh", "-c", "rpm -qp --requires *.rpm | grep \"^/bin/sh$\"")
"addrepo", execShouldError(t, r, "sh", "-c", "rpm -qp --requires *.rpm | grep \"^/bin/bash$\"")
"--name", execShouldError(t, r, "sh", "-c", "rpm -qp --requires *.rpm | grep \"^/bin/zsh$\"")
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"alr",
"ref",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"alr",
"build",
"-p",
"alr-repo/test-autoreq-autoprov",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sh",
"-c",
"rpm -qp --requires *.rpm | grep \"^/bin/sh$\"",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sh",
"-c",
"rpm -qp --requires *.rpm | grep \"^/bin/bash$\"",
))
assert.Error(t, err)
err = r.Exec(e2e.NewCommand(
"sh",
"-c",
"rpm -qp --requires *.rpm | grep \"^/bin/zsh$\"",
))
assert.Error(t, err)
}, },
) )
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,26 +30,10 @@ func TestE2EIssue50InstallMultiple(t *testing.T) {
"issue-50-install-multiple", "issue-50-install-multiple",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "sudo", "alr", "in", "foo-pkg", "bar-pkg")
"alr", execShouldNoError(t, r, "cat", "/opt/foo")
"addrepo", execShouldNoError(t, r, "cat", "/opt/bar")
"--name",
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sudo", "alr", "in", "foo-pkg", "bar-pkg",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand("cat", "/opt/foo"))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand("cat", "/opt/bar"))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,23 +30,8 @@ func TestE2EIssue53LcAllCInfo(t *testing.T) {
"issue-53-lc-all-c-info", "issue-53-lc-all-c-info",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "bash", "-c", "LANG=C alr info foo-pkg")
"alr",
"addrepo",
"--name",
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Plemya-x/alr-repo.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"bash",
"-c",
"LANG=C alr info alr-bin",
))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,28 +30,11 @@ func TestE2EIssue59RmCompletion(t *testing.T) {
"issue-59-rm-completion", "issue-59-rm-completion",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "sudo", "alr", "in", "foo-pkg", "bar-pkg")
"alr", execShouldNoError(t, r, "sh", "-c", "alr rm --generate-bash-completion | grep ^foo-pkg$")
"addrepo", execShouldNoError(t, r, "sh", "-c", "alr rm --generate-bash-completion | grep ^bar-pkg$")
"--name", execShouldError(t, r, "sh", "-c", "alr rm --generate-bash-completion | grep ^test-autoreq-autoprov$")
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sudo", "alr", "in", "foo-pkg", "bar-pkg",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand("sh", "-c", "alr rm --generate-bash-completion | grep ^foo-pkg$"))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand("sh", "-c", "alr rm --generate-bash-completion | grep ^bar-pkg$"))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand("sh", "-c", "alr rm --generate-bash-completion | grep ^test-autoreq-autoprov$"))
assert.Error(t, err)
}, },
) )
} }

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,21 +30,8 @@ func TestE2EIssue72InstallWithDeps(t *testing.T) {
"issue-72-install-with-deps", "issue-72-install-with-deps",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "sudo", "alr", "in", "test-app-with-lib")
"alr",
"addrepo",
"--name",
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sudo", "alr", "in", "test-app-with-lib",
))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -0,0 +1,43 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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/>.
//go:build e2e
package e2etests_test
import (
"testing"
"github.com/efficientgo/e2e"
)
func TestE2EIssue74Upgradable(t *testing.T) {
dockerMultipleRun(
t,
"issue-74-upgradable",
COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) {
defaultPrepare(t, r)
execShouldNoError(t, r, "sudo", "alr", "repo", "set-ref", "alr-repo", "bd26236cd7")
execShouldNoError(t, r, "alr", "ref")
execShouldNoError(t, r, "sudo", "alr", "in", "bar-pkg")
execShouldNoError(t, r, "sh", "-c", "test $(alr list -U | wc -l) -eq 0 || exit 1")
execShouldNoError(t, r, "sudo", "alr", "repo", "set-ref", "alr-repo", "d9a3541561")
execShouldNoError(t, r, "sudo", "alr", "ref")
execShouldNoError(t, r, "sh", "-c", "test $(alr list -U | wc -l) -eq 1 || exit 1")
},
)
}

View File

@@ -21,7 +21,6 @@ package e2etests_test
import ( import (
"testing" "testing"
"github.com/alecthomas/assert/v2"
"github.com/efficientgo/e2e" "github.com/efficientgo/e2e"
) )
@@ -31,32 +30,9 @@ func TestE2EIssue75InstallWithDeps(t *testing.T) {
"issue-75-ref-specify", "issue-75-ref-specify",
COMMON_SYSTEMS, COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) { func(t *testing.T, r e2e.Runnable) {
err := r.Exec(e2e.NewCommand( defaultPrepare(t, r)
"sudo", execShouldNoError(t, r, "sudo", "alr", "repo", "set-ref", "alr-repo", "bd26236cd7")
"alr", execShouldNoError(t, r, "sh", "-c", "test $(alr list | wc -l) -eq 2 || exit 1")
"addrepo",
"--name",
"alr-repo",
"--url",
"https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sudo", "alr", "ref",
))
assert.NoError(t, err)
// TODO: replace with alr command when it be added
err = r.Exec(e2e.NewCommand(
"sudo", "sh", "-c", "sed -i 's/ref = .*/ref = \"bd26236cd7\"/' /etc/alr/alr.toml",
))
assert.NoError(t, err)
err = r.Exec(e2e.NewCommand(
"sh", "-c", "test $(alr list | wc -l) -eq 2 || exit 1",
))
assert.NoError(t, err)
}, },
) )
} }

View File

@@ -0,0 +1,38 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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/>.
//go:build e2e
package e2etests_test
import (
"testing"
"github.com/efficientgo/e2e"
)
func TestE2EIssue81MultiplePackages(t *testing.T) {
dockerMultipleRun(
t,
"issue-81-multiple-packages",
COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) {
defaultPrepare(t, r)
execShouldNoError(t, r, "sudo", "alr", "in", "first-package-with-dashes")
execShouldNoError(t, r, "cat", "/opt/first-package")
},
)
}

View File

@@ -0,0 +1,40 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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/>.
//go:build e2e
package e2etests_test
import (
"testing"
"github.com/efficientgo/e2e"
)
func TestE2EIssue91MultiplePackages(t *testing.T) {
dockerMultipleRun(
t,
"issue-91-set-repo-ref",
COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) {
defaultPrepare(t, r)
execShouldError(t, r, "sudo", "alr", "repo", "set-ref")
execShouldError(t, r, "sudo", "alr", "repo", "set-ref", "alr-repo")
execShouldNoError(t, r, "sudo", "alr", "repo", "set-ref", "alr-repo", "bd26236cd7")
execShouldNoError(t, r, "sh", "-c", "test $(alr list | wc -l) -eq 2 || exit 1")
},
)
}

View File

@@ -0,0 +1,49 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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/>.
//go:build e2e
package e2etests_test
import (
"bytes"
"strings"
"testing"
"github.com/efficientgo/e2e"
"github.com/stretchr/testify/assert"
)
func TestE2EIssue94TwiceBuild(t *testing.T) {
dockerMultipleRun(
t,
"issue-94-twice-build",
COMMON_SYSTEMS,
func(t *testing.T, r e2e.Runnable) {
defaultPrepare(t, r)
var stderr bytes.Buffer
err := r.Exec(
e2e.NewCommand("sudo", "alr", "in", "test-94-app"),
e2e.WithExecOptionStderr(&stderr),
)
assert.NoError(t, err, "command failed")
output := stderr.String()
assert.Equal(t, 1, strings.Count(output, "Building package name=test-94-dep"))
},
)
}

2
gen.go
View File

@@ -25,7 +25,7 @@ import (
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/gen" "gitea.plemya-x.ru/Plemya-x/ALR/internal/gen"
) )
func GenCmd() *cli.Command { func GenCmd() *cli.Command {

View File

@@ -25,13 +25,13 @@ import (
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db" database "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/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
) )
func InstallCmd() *cli.Command { func InstallCmd() *cli.Command {
@@ -98,7 +98,7 @@ func InstallCmd() *cli.Command {
return err return err
} }
err = builder.InstallPkgs( _, err = builder.InstallPkgs(
ctx, ctx,
&build.BuildArgs{ &build.BuildArgs{
Opts: &types.BuildOpts{ Opts: &types.BuildOpts{

View File

@@ -32,14 +32,14 @@ import (
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/constants" "gitea.plemya-x.ru/Plemya-x/ALR/internal/constants"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/logger" "gitea.plemya-x.ru/Plemya-x/ALR/internal/logger"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
) )
func InternalBuildCmd() *cli.Command { func InternalBuildCmd() *cli.Command {

View File

@@ -27,15 +27,14 @@ import (
"log/slog" "log/slog"
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"mvdan.cc/sh/v3/syntax"
"mvdan.cc/sh/v3/syntax/typedjson"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "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/config"
"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/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/alrsh"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "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/types"
) )
type BuildInput struct { type BuildInput struct {
@@ -133,50 +132,29 @@ type RepositoryProvider interface {
// ================================================ // ================================================
type ScriptFile struct { type BuiltDep struct {
File *syntax.File Name string
Path string Path string
} }
func (s *ScriptFile) GobEncode() ([]byte, error) { func Map[T, R any](items []T, f func(T) R) []R {
var buf bytes.Buffer res := make([]R, len(items))
enc := gob.NewEncoder(&buf) for i, item := range items {
if err := enc.Encode(s.Path); err != nil { res[i] = f(item)
return nil, err
} }
var fileBuf bytes.Buffer return res
if err := typedjson.Encode(&fileBuf, s.File); err != nil {
return nil, err
}
fileData := fileBuf.Bytes()
if err := enc.Encode(fileData); err != nil {
return nil, err
}
return buf.Bytes(), nil
} }
func (s *ScriptFile) GobDecode(data []byte) error { func GetBuiltPaths(deps []*BuiltDep) []string {
buf := bytes.NewBuffer(data) return Map(deps, func(dep *BuiltDep) string {
dec := gob.NewDecoder(buf) return dep.Path
if err := dec.Decode(&s.Path); err != nil { })
return err
}
var fileData []byte
if err := dec.Decode(&fileData); err != nil {
return err
}
fileReader := bytes.NewReader(fileData)
file, err := typedjson.Decode(fileReader)
if err != nil {
return err
}
s.File = file.(*syntax.File)
return nil
} }
type BuildResult struct { func GetBuiltName(deps []*BuiltDep) []string {
PackagePaths []string return Map(deps, func(dep *BuiltDep) string {
PackageNames []string return dep.Name
})
} }
type PackageFinder interface { type PackageFinder interface {
@@ -199,8 +177,8 @@ type ScriptResolverExecutor interface {
} }
type ScriptExecutor interface { type ScriptExecutor interface {
ReadScript(ctx context.Context, scriptPath string) (*ScriptFile, error) ReadScript(ctx context.Context, scriptPath string) (*alrsh.ALRSh, error)
ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *ScriptFile) (string, []*types.BuildVars, error) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *alrsh.ALRSh) (string, []*types.BuildVars, error)
PrepareDirs( PrepareDirs(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
@@ -209,12 +187,12 @@ type ScriptExecutor interface {
ExecuteSecondPass( ExecuteSecondPass(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
sf *ScriptFile, sf *alrsh.ALRSh,
varsOfPackages []*types.BuildVars, varsOfPackages []*types.BuildVars,
repoDeps []string, repoDeps []string,
builtNames []string, builtDeps []*BuiltDep,
basePkg string, basePkg string,
) (*SecondPassResult, error) ) ([]*BuiltDep, error)
} }
type CacheExecutor interface { type CacheExecutor interface {
@@ -222,7 +200,7 @@ type CacheExecutor interface {
} }
type ScriptViewerExecutor interface { type ScriptViewerExecutor interface {
ViewScript(ctx context.Context, input *BuildInput, sf *ScriptFile, basePkg string) error ViewScript(ctx context.Context, input *BuildInput, sf *alrsh.ALRSh, basePkg string) error
} }
type CheckerExecutor interface { type CheckerExecutor interface {
@@ -320,7 +298,7 @@ type BuildPackageFromScriptArgs struct {
func (b *Builder) BuildPackageFromDb( func (b *Builder) BuildPackageFromDb(
ctx context.Context, ctx context.Context,
args *BuildPackageFromDbArgs, args *BuildPackageFromDbArgs,
) (*BuildResult, error) { ) ([]*BuiltDep, error) {
scriptInfo := b.scriptResolver.ResolveScript(ctx, args.Package) scriptInfo := b.scriptResolver.ResolveScript(ctx, args.Package)
return b.BuildPackage(ctx, &BuildInput{ return b.BuildPackage(ctx, &BuildInput{
@@ -336,7 +314,7 @@ func (b *Builder) BuildPackageFromDb(
func (b *Builder) BuildPackageFromScript( func (b *Builder) BuildPackageFromScript(
ctx context.Context, ctx context.Context,
args *BuildPackageFromScriptArgs, args *BuildPackageFromScriptArgs,
) (*BuildResult, error) { ) ([]*BuiltDep, error) {
return b.BuildPackage(ctx, &BuildInput{ return b.BuildPackage(ctx, &BuildInput{
script: args.Script, script: args.Script,
repository: "default", repository: "default",
@@ -350,7 +328,7 @@ func (b *Builder) BuildPackageFromScript(
func (b *Builder) BuildPackage( func (b *Builder) BuildPackage(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
) (*BuildResult, error) { ) ([]*BuiltDep, error) {
scriptPath := input.script scriptPath := input.script
slog.Debug("ReadScript") slog.Debug("ReadScript")
@@ -365,7 +343,7 @@ func (b *Builder) BuildPackage(
return nil, err return nil, err
} }
builtPaths := make([]string, 0) var builtDeps []*BuiltDep
if !input.opts.Clean { if !input.opts.Clean {
var remainingVars []*types.BuildVars var remainingVars []*types.BuildVars
@@ -375,14 +353,16 @@ func (b *Builder) BuildPackage(
return nil, err return nil, err
} }
if ok { if ok {
builtPaths = append(builtPaths, builtPkgPath) builtDeps = append(builtDeps, &BuiltDep{
Path: builtPkgPath,
})
} else { } else {
remainingVars = append(remainingVars, vars) remainingVars = append(remainingVars, vars)
} }
} }
if len(remainingVars) == 0 { if len(remainingVars) == 0 {
return &BuildResult{builtPaths, nil}, nil return builtDeps, nil
} }
} }
@@ -427,19 +407,32 @@ func (b *Builder) BuildPackage(
sources, checksums = removeDuplicatesSources(sources, checksums) sources, checksums = removeDuplicatesSources(sources, checksums)
slog.Debug("installBuildDeps") slog.Debug("installBuildDeps")
err = b.installBuildDeps(ctx, input, buildDepends) alrBuildDeps, err := b.installBuildDeps(ctx, input, buildDepends)
if err != nil { if err != nil {
return nil, err return nil, err
} }
slog.Debug("installOptDeps") slog.Debug("installOptDeps")
err = b.installOptDeps(ctx, input, optDepends) _, err = b.installOptDeps(ctx, input, optDepends)
if err != nil { if err != nil {
return nil, err return nil, err
} }
depNames := make(map[string]struct{})
for _, dep := range alrBuildDeps {
depNames[dep.Name] = struct{}{}
}
// We filter so as not to re-build what has already been built at the `installBuildDeps` stage.
var filteredDepends []string
for _, d := range depends {
if _, found := depNames[d]; !found {
filteredDepends = append(filteredDepends, d)
}
}
slog.Debug("BuildALRDeps") slog.Debug("BuildALRDeps")
builtPaths, builtNames, repoDeps, err := b.BuildALRDeps(ctx, input, depends) newBuiltDeps, repoDeps, err := b.BuildALRDeps(ctx, input, filteredDepends)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -450,8 +443,6 @@ func (b *Builder) BuildPackage(
return nil, err return nil, err
} }
// builtPaths = append(builtPaths, newBuildPaths...)
slog.Info(gotext.Get("Downloading sources")) slog.Info(gotext.Get("Downloading sources"))
slog.Debug("DownloadSources") slog.Debug("DownloadSources")
err = b.sourceExecutor.DownloadSources( err = b.sourceExecutor.DownloadSources(
@@ -467,6 +458,8 @@ func (b *Builder) BuildPackage(
return nil, err return nil, err
} }
builtDeps = removeDuplicates(append(builtDeps, newBuiltDeps...))
slog.Debug("ExecuteSecondPass") slog.Debug("ExecuteSecondPass")
res, err := b.scriptExecutor.ExecuteSecondPass( res, err := b.scriptExecutor.ExecuteSecondPass(
ctx, ctx,
@@ -474,20 +467,16 @@ func (b *Builder) BuildPackage(
sf, sf,
varsOfPackages, varsOfPackages,
repoDeps, repoDeps,
builtNames, builtDeps,
basePkg, basePkg,
) )
if err != nil { if err != nil {
return nil, err return nil, err
} }
pkgPaths := removeDuplicates(append(builtPaths, res.BuiltPaths...)) builtDeps = removeDuplicates(append(builtDeps, res...))
pkgNames := removeDuplicates(append(builtNames, res.BuiltNames...))
return &BuildResult{ return builtDeps, nil
PackagePaths: pkgPaths,
PackageNames: pkgNames,
}, nil
} }
type InstallPkgsArgs struct { type InstallPkgsArgs struct {
@@ -523,7 +512,7 @@ func (b *Builder) InstallALRPackages(
} }
err = b.installerExecutor.InstallLocal( err = b.installerExecutor.InstallLocal(
res.PackagePaths, GetBuiltPaths(res),
&manager.Opts{ &manager.Opts{
NoConfirm: !input.BuildOpts().Interactive, NoConfirm: !input.BuildOpts().Interactive,
}, },
@@ -544,13 +533,13 @@ func (b *Builder) BuildALRDeps(
PkgFormatProvider PkgFormatProvider
}, },
depends []string, depends []string,
) (builtPaths, builtNames, repoDeps []string, err error) { ) (buildDeps []*BuiltDep, repoDeps []string, err error) {
if len(depends) > 0 { if len(depends) > 0 {
slog.Info(gotext.Get("Installing dependencies")) slog.Info(gotext.Get("Installing dependencies"))
found, notFound, err := b.repos.FindPkgs(ctx, depends) // Поиск зависимостей found, notFound, err := b.repos.FindPkgs(ctx, depends) // Поиск зависимостей
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, err
} }
repoDeps = notFound repoDeps = notFound
@@ -597,20 +586,17 @@ func (b *Builder) BuildALRDeps(
}, },
) )
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, err
} }
builtPaths = append(builtPaths, res.PackagePaths...) buildDeps = append(buildDeps, res...)
builtNames = append(builtNames, res.PackageNames...)
} }
} }
// Удаляем возможные дубликаты, которые могут быть введены, если
// несколько зависимостей зависят от одних и тех же пакетов.
repoDeps = removeDuplicates(repoDeps) repoDeps = removeDuplicates(repoDeps)
builtPaths = removeDuplicates(builtPaths) buildDeps = removeDuplicates(buildDeps)
builtNames = removeDuplicates(builtNames)
return builtPaths, builtNames, repoDeps, nil return buildDeps, repoDeps, nil
} }
func (i *Builder) installBuildDeps( func (i *Builder) installBuildDeps(
@@ -621,19 +607,20 @@ func (i *Builder) installBuildDeps(
PkgFormatProvider PkgFormatProvider
}, },
pkgs []string, pkgs []string,
) error { ) ([]*BuiltDep, error) {
var builtDeps []*BuiltDep
if len(pkgs) > 0 { if len(pkgs) > 0 {
deps, err := i.installerExecutor.RemoveAlreadyInstalled(pkgs) deps, err := i.installerExecutor.RemoveAlreadyInstalled(pkgs)
if err != nil { if err != nil {
return err return nil, err
} }
err = i.InstallPkgs(ctx, input, deps) // Устанавливаем выбранные пакеты builtDeps, err = i.InstallPkgs(ctx, input, deps) // Устанавливаем выбранные пакеты
if err != nil { if err != nil {
return err return nil, err
} }
} }
return nil return builtDeps, nil
} }
func (i *Builder) installOptDeps( func (i *Builder) installOptDeps(
@@ -644,10 +631,11 @@ func (i *Builder) installOptDeps(
PkgFormatProvider PkgFormatProvider
}, },
pkgs []string, pkgs []string,
) error { ) ([]*BuiltDep, error) {
var builtDeps []*BuiltDep
optDeps, err := i.installerExecutor.RemoveAlreadyInstalled(pkgs) optDeps, err := i.installerExecutor.RemoveAlreadyInstalled(pkgs)
if err != nil { if err != nil {
return err return nil, err
} }
if len(optDeps) > 0 { if len(optDeps) > 0 {
optDeps, err := cliutils.ChooseOptDepends( optDeps, err := cliutils.ChooseOptDepends(
@@ -657,19 +645,19 @@ func (i *Builder) installOptDeps(
input.BuildOpts().Interactive, input.BuildOpts().Interactive,
) // Пользователя просят выбрать опциональные зависимости ) // Пользователя просят выбрать опциональные зависимости
if err != nil { if err != nil {
return err return nil, err
} }
if len(optDeps) == 0 { if len(optDeps) == 0 {
return nil return builtDeps, nil
} }
err = i.InstallPkgs(ctx, input, optDeps) // Устанавливаем выбранные пакеты builtDeps, err = i.InstallPkgs(ctx, input, optDeps) // Устанавливаем выбранные пакеты
if err != nil { if err != nil {
return err return nil, err
} }
} }
return nil return builtDeps, nil
} }
func (i *Builder) InstallPkgs( func (i *Builder) InstallPkgs(
@@ -680,18 +668,18 @@ func (i *Builder) InstallPkgs(
PkgFormatProvider PkgFormatProvider
}, },
pkgs []string, pkgs []string,
) error { ) ([]*BuiltDep, error) {
builtPaths, _, repoDeps, err := i.BuildALRDeps(ctx, input, pkgs) builtDeps, repoDeps, err := i.BuildALRDeps(ctx, input, pkgs)
if err != nil { if err != nil {
return err return nil, err
} }
if len(builtPaths) > 0 { if len(builtDeps) > 0 {
err = i.installerExecutor.InstallLocal(builtPaths, &manager.Opts{ err = i.installerExecutor.InstallLocal(GetBuiltPaths(builtDeps), &manager.Opts{
NoConfirm: !input.BuildOpts().Interactive, NoConfirm: !input.BuildOpts().Interactive,
}) })
if err != nil { if err != nil {
return err return nil, err
} }
} }
@@ -700,9 +688,9 @@ func (i *Builder) InstallPkgs(
NoConfirm: !input.BuildOpts().Interactive, NoConfirm: !input.BuildOpts().Interactive,
}) })
if err != nil { if err != nil {
return err return nil, err
} }
} }
return nil return builtDeps, nil
} }

View File

@@ -28,9 +28,9 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "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/db"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "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/internal/manager"
) )
type TestPackageFinder struct { type TestPackageFinder struct {

View File

@@ -23,7 +23,7 @@ import (
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type Cache struct { type Cache struct {

View File

@@ -24,8 +24,8 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type Checker struct { type Checker struct {

View File

@@ -19,7 +19,7 @@ package build
import ( import (
"path/filepath" "path/filepath"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type BaseDirProvider interface { type BaseDirProvider interface {

View File

@@ -27,7 +27,7 @@ import (
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
func rpmFindDependenciesALTLinux(ctx context.Context, pkgInfo *nfpm.Info, dirs types.Directories, command string, envs []string, updateFunc func(string)) error { func rpmFindDependenciesALTLinux(ctx context.Context, pkgInfo *nfpm.Info, dirs types.Directories, command string, envs []string, updateFunc func(string)) error {

View File

@@ -23,7 +23,7 @@ import (
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type EmptyFindProvReq struct{} type EmptyFindProvReq struct{}

View File

@@ -28,7 +28,7 @@ import (
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type FedoraFindProvReq struct{} type FedoraFindProvReq struct{}

View File

@@ -21,8 +21,8 @@ import (
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"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/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type ProvReqFinder interface { type ProvReqFinder interface {

View File

@@ -17,7 +17,7 @@
package build package build
import ( import (
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager" "gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
) )
func NewInstaller(mgr manager.Manager) *Installer { func NewInstaller(mgr manager.Manager) *Installer {

View File

@@ -17,7 +17,7 @@
package build package build
import ( import (
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager" "gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
) )
func NewMainBuilder( func NewMainBuilder(

View File

@@ -28,7 +28,7 @@ import (
"github.com/hashicorp/go-plugin" "github.com/hashicorp/go-plugin"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/logger" "gitea.plemya-x.ru/Plemya-x/ALR/internal/logger"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager" "gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
) )
type InstallerPlugin struct { type InstallerPlugin struct {

View File

@@ -28,7 +28,8 @@ import (
"github.com/hashicorp/go-plugin" "github.com/hashicorp/go-plugin"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/logger" "gitea.plemya-x.ru/Plemya-x/ALR/internal/logger"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/alrsh"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
var HandshakeConfig = plugin.HandshakeConfig{ var HandshakeConfig = plugin.HandshakeConfig{
@@ -50,13 +51,13 @@ type ScriptExecutorRPCServer struct {
// ReadScript // ReadScript
// //
func (s *ScriptExecutorRPC) ReadScript(ctx context.Context, scriptPath string) (*ScriptFile, error) { func (s *ScriptExecutorRPC) ReadScript(ctx context.Context, scriptPath string) (*alrsh.ALRSh, error) {
var resp *ScriptFile var resp *alrsh.ALRSh
err := s.client.Call("Plugin.ReadScript", scriptPath, &resp) err := s.client.Call("Plugin.ReadScript", scriptPath, &resp)
return resp, err return resp, err
} }
func (s *ScriptExecutorRPCServer) ReadScript(scriptPath string, resp *ScriptFile) error { func (s *ScriptExecutorRPCServer) ReadScript(scriptPath string, resp *alrsh.ALRSh) error {
file, err := s.Impl.ReadScript(context.Background(), scriptPath) file, err := s.Impl.ReadScript(context.Background(), scriptPath)
if err != nil { if err != nil {
return err return err
@@ -72,7 +73,7 @@ func (s *ScriptExecutorRPCServer) ReadScript(scriptPath string, resp *ScriptFile
type ExecuteFirstPassArgs struct { type ExecuteFirstPassArgs struct {
Input *BuildInput Input *BuildInput
Sf *ScriptFile Sf *alrsh.ALRSh
} }
type ExecuteFirstPassResp struct { type ExecuteFirstPassResp struct {
@@ -80,7 +81,7 @@ type ExecuteFirstPassResp struct {
VarsOfPackages []*types.BuildVars VarsOfPackages []*types.BuildVars
} }
func (s *ScriptExecutorRPC) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *ScriptFile) (string, []*types.BuildVars, error) { func (s *ScriptExecutorRPC) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *alrsh.ALRSh) (string, []*types.BuildVars, error) {
var resp *ExecuteFirstPassResp var resp *ExecuteFirstPassResp
err := s.client.Call("Plugin.ExecuteFirstPass", &ExecuteFirstPassArgs{ err := s.client.Call("Plugin.ExecuteFirstPass", &ExecuteFirstPassArgs{
Input: input, Input: input,
@@ -148,29 +149,29 @@ func (s *ScriptExecutorRPCServer) PrepareDirs(args *PrepareDirsArgs, reply *stru
type ExecuteSecondPassArgs struct { type ExecuteSecondPassArgs struct {
Input *BuildInput Input *BuildInput
Sf *ScriptFile Sf *alrsh.ALRSh
VarsOfPackages []*types.BuildVars VarsOfPackages []*types.BuildVars
RepoDeps []string RepoDeps []string
BuiltNames []string BuiltDeps []*BuiltDep
BasePkg string BasePkg string
} }
func (s *ScriptExecutorRPC) ExecuteSecondPass( func (s *ScriptExecutorRPC) ExecuteSecondPass(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
sf *ScriptFile, sf *alrsh.ALRSh,
varsOfPackages []*types.BuildVars, varsOfPackages []*types.BuildVars,
repoDeps []string, repoDeps []string,
builtNames []string, builtDeps []*BuiltDep,
basePkg string, basePkg string,
) (*SecondPassResult, error) { ) ([]*BuiltDep, error) {
var resp *SecondPassResult var resp []*BuiltDep
err := s.client.Call("Plugin.ExecuteSecondPass", &ExecuteSecondPassArgs{ err := s.client.Call("Plugin.ExecuteSecondPass", &ExecuteSecondPassArgs{
Input: input, Input: input,
Sf: sf, Sf: sf,
VarsOfPackages: varsOfPackages, VarsOfPackages: varsOfPackages,
RepoDeps: repoDeps, RepoDeps: repoDeps,
BuiltNames: builtNames, BuiltDeps: builtDeps,
BasePkg: basePkg, BasePkg: basePkg,
}, &resp) }, &resp)
if err != nil { if err != nil {
@@ -179,20 +180,20 @@ func (s *ScriptExecutorRPC) ExecuteSecondPass(
return resp, nil return resp, nil
} }
func (s *ScriptExecutorRPCServer) ExecuteSecondPass(args *ExecuteSecondPassArgs, resp *SecondPassResult) error { func (s *ScriptExecutorRPCServer) ExecuteSecondPass(args *ExecuteSecondPassArgs, resp *[]*BuiltDep) error {
res, err := s.Impl.ExecuteSecondPass( res, err := s.Impl.ExecuteSecondPass(
context.Background(), context.Background(),
args.Input, args.Input,
args.Sf, args.Sf,
args.VarsOfPackages, args.VarsOfPackages,
args.RepoDeps, args.RepoDeps,
args.BuiltNames, args.BuiltDeps,
args.BasePkg, args.BasePkg,
) )
if err != nil { if err != nil {
return err return err
} }
*resp = *res *resp = res
return err return err
} }

View File

@@ -19,7 +19,6 @@ package build
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"log/slog" "log/slog"
"os" "os"
@@ -36,12 +35,12 @@ import (
"mvdan.cc/sh/v3/interp" "mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax" "mvdan.cc/sh/v3/syntax"
finddeps "gitea.plemya-x.ru/Plemya-x/ALR/internal/build/find_deps"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder" "gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/handlers" "gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/handlers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/helpers" "gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/helpers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/alrsh"
finddeps "gitea.plemya-x.ru/Plemya-x/ALR/pkg/build/find_deps" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
) )
type LocalScriptExecutor struct { type LocalScriptExecutor struct {
@@ -54,103 +53,12 @@ func NewLocalScriptExecutor(cfg Config) *LocalScriptExecutor {
} }
} }
func (e *LocalScriptExecutor) ReadScript(ctx context.Context, scriptPath string) (*ScriptFile, error) { func (e *LocalScriptExecutor) ReadScript(ctx context.Context, scriptPath string) (*alrsh.ALRSh, error) {
fl, err := readScript(scriptPath) return alrsh.ReadFromLocal(scriptPath)
if err != nil {
return nil, err
}
return &ScriptFile{
Path: scriptPath,
File: fl,
}, nil
} }
func (e *LocalScriptExecutor) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *ScriptFile) (string, []*types.BuildVars, error) { func (e *LocalScriptExecutor) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *alrsh.ALRSh) (string, []*types.BuildVars, error) {
varsOfPackages := []*types.BuildVars{} return sf.ParseBuildVars(ctx, input.info, input.packages)
scriptDir := filepath.Dir(sf.Path)
env := createBuildEnvVars(input.info, types.Directories{ScriptDir: scriptDir})
runner, err := interp.New(
interp.Env(expand.ListEnviron(env...)), // Устанавливаем окружение
interp.StdIO(os.Stdin, os.Stderr, os.Stderr), // Устанавливаем стандартный ввод-вывод
interp.ExecHandler(helpers.Restricted.ExecHandler(handlers.NopExec)), // Ограничиваем выполнение
interp.ReadDirHandler2(handlers.RestrictedReadDir(scriptDir)), // Ограничиваем чтение директорий
interp.StatHandler(handlers.RestrictedStat(scriptDir)), // Ограничиваем доступ к статистике файлов
interp.OpenHandler(handlers.RestrictedOpen(scriptDir)), // Ограничиваем открытие файлов
interp.Dir(scriptDir),
)
if err != nil {
return "", nil, err
}
err = runner.Run(ctx, sf.File) // Запускаем скрипт
if err != nil {
return "", nil, err
}
dec := decoder.New(input.info, runner) // Создаём новый декодер
type packages struct {
BasePkgName string `sh:"basepkg_name"`
Names []string `sh:"name"`
}
var pkgs packages
err = dec.DecodeVars(&pkgs)
if err != nil {
return "", nil, err
}
if len(pkgs.Names) == 0 {
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
}
varsOfPackages = append(varsOfPackages, &vars)
return vars.Name, varsOfPackages, nil
}
if len(input.packages) == 0 {
return "", nil, errors.New("script has multiple packages but package is not specified")
}
for _, pkgName := range input.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(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)
}
return pkgs.BasePkgName, varsOfPackages, nil
}
type SecondPassResult struct {
BuiltPaths []string
BuiltNames []string
} }
func (e *LocalScriptExecutor) PrepareDirs( func (e *LocalScriptExecutor) PrepareDirs(
@@ -178,13 +86,13 @@ func (e *LocalScriptExecutor) PrepareDirs(
func (e *LocalScriptExecutor) ExecuteSecondPass( func (e *LocalScriptExecutor) ExecuteSecondPass(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
sf *ScriptFile, sf *alrsh.ALRSh,
varsOfPackages []*types.BuildVars, varsOfPackages []*types.BuildVars,
repoDeps []string, repoDeps []string,
builtNames []string, builtDeps []*BuiltDep,
basePkg string, basePkg string,
) (*SecondPassResult, error) { ) ([]*BuiltDep, error) {
dirs, err := getDirs(e.cfg, sf.Path, basePkg) dirs, err := getDirs(e.cfg, sf.Path(), basePkg)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -202,14 +110,14 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
return nil, err return nil, err
} }
err = runner.Run(ctx, sf.File) err = runner.Run(ctx, sf.File())
if err != nil { if err != nil {
return nil, err return nil, err
} }
dec := decoder.New(input.info, runner) dec := decoder.New(input.info, runner)
var builtPaths []string // var builtPaths []string
err = e.ExecuteFunctions(ctx, dirs, dec) err = e.ExecuteFunctions(ctx, dirs, dec)
if err != nil { if err != nil {
@@ -243,7 +151,7 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
dirs, dirs,
append( append(
repoDeps, repoDeps,
builtNames..., GetBuiltName(builtDeps)...,
), ),
funcOut.Contents, funcOut.Contents,
) )
@@ -269,14 +177,13 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
return nil, err return nil, err
} }
builtPaths = append(builtPaths, pkgPath) builtDeps = append(builtDeps, &BuiltDep{
builtNames = append(builtNames, vars.Name) Name: vars.Name,
Path: pkgPath,
})
} }
return &SecondPassResult{ return builtDeps, nil
BuiltPaths: builtPaths,
BuiltNames: builtNames,
}, nil
} }
func buildPkgMetadata( func buildPkgMetadata(

View File

@@ -20,6 +20,7 @@ import (
"context" "context"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/alrsh"
) )
type ScriptViewerConfig interface { type ScriptViewerConfig interface {
@@ -33,12 +34,12 @@ type ScriptViewer struct {
func (s *ScriptViewer) ViewScript( func (s *ScriptViewer) ViewScript(
ctx context.Context, ctx context.Context,
input *BuildInput, input *BuildInput,
sf *ScriptFile, a *alrsh.ALRSh,
basePkg string, basePkg string,
) error { ) error {
return cliutils.PromptViewScript( return cliutils.PromptViewScript(
ctx, ctx,
sf.Path, a.Path(),
basePkg, basePkg,
s.config.PagerStyle(), s.config.PagerStyle(),
input.opts.Interactive, input.opts.Interactive,

View File

@@ -33,34 +33,17 @@ import (
_ "github.com/goreleaser/nfpm/v2/arch" _ "github.com/goreleaser/nfpm/v2/arch"
_ "github.com/goreleaser/nfpm/v2/deb" _ "github.com/goreleaser/nfpm/v2/deb"
_ "github.com/goreleaser/nfpm/v2/rpm" _ "github.com/goreleaser/nfpm/v2/rpm"
"mvdan.cc/sh/v3/syntax"
"github.com/goreleaser/nfpm/v2" "github.com/goreleaser/nfpm/v2"
"github.com/goreleaser/nfpm/v2/files" "github.com/goreleaser/nfpm/v2/files"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides" "gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides"
"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/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
// Функция readScript анализирует скрипт сборки с использованием встроенной реализации bash
func readScript(script string) (*syntax.File, error) {
fl, err := os.Open(script) // Открываем файл скрипта
if err != nil {
return nil, err
}
defer fl.Close() // Закрываем файл после выполнения
file, err := syntax.NewParser().Parse(fl, "alr.sh") // Парсим скрипт с помощью синтаксического анализатора
if err != nil {
return nil, err
}
return file, nil // Возвращаем синтаксическое дерево
}
// Функция prepareDirs подготавливает директории для сборки. // Функция prepareDirs подготавливает директории для сборки.
func prepareDirs(dirs types.Directories) error { func prepareDirs(dirs types.Directories) error {
err := os.RemoveAll(dirs.BaseDir) // Удаляем базовую директорию, если она существует err := os.RemoveAll(dirs.BaseDir) // Удаляем базовую директорию, если она существует
@@ -288,14 +271,14 @@ func packageNames(pkgs []db.Package) []string {
*/ */
// Функция removeDuplicates убирает любые дубликаты из предоставленного среза. // Функция removeDuplicates убирает любые дубликаты из предоставленного среза.
func removeDuplicates(slice []string) []string { func removeDuplicates[T comparable](slice []T) []T {
seen := map[string]struct{}{} seen := map[T]struct{}{}
result := []string{} result := []T{}
for _, s := range slice { for _, item := range slice {
if _, ok := seen[s]; !ok { if _, ok := seen[item]; !ok {
seen[s] = struct{}{} seen[item] = struct{}{}
result = append(result, s) result = append(result, item)
} }
} }

View File

@@ -26,9 +26,9 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "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/config"
"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/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/repos"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
) )
type AppDeps struct { type AppDeps struct {

View File

@@ -21,6 +21,7 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@@ -61,3 +62,11 @@ func FormatCliExitWithCode(msg string, err error, exitCode int) cli.ExitCoder {
} }
return cli.Exit(fmt.Errorf("%s: %w", msg, err), exitCode) return cli.Exit(fmt.Errorf("%s: %w", msg, err), exitCode)
} }
func WarnLegacyCommand(newSyntax string) {
slog.Warn(
gotext.Get(
"This command is deprecated and would be removed in the future, use \"%s\" instead!", newSyntax,
),
)
}

View File

@@ -29,7 +29,7 @@ import (
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/constants" "gitea.plemya-x.ru/Plemya-x/ALR/internal/constants"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type ALRConfig struct { type ALRConfig struct {

View File

@@ -104,7 +104,7 @@ func Resolve(info *distro.OSRelease, opts *Opts) ([]string, error) {
out = append(out, opts.Name) out = append(out, opts.Name)
for index, item := range out { for index, item := range out {
out[index] = strings.TrimPrefix(strings.ReplaceAll(item, "-", "_"), "_") out[index] = strings.TrimPrefix(item, "_")
} }
return out, nil return out, nil

38
internal/parser/parser.go Normal file
View File

@@ -0,0 +1,38 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 parser
import (
"fmt"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder"
)
type PackageNames struct {
BasePkgName string `sh:"basepkg_name"`
Names []string `sh:"name"`
}
func ParseNames(dec *decoder.Decoder) (*PackageNames, error) {
var pkgs PackageNames
err := dec.DecodeVars(&pkgs)
if err != nil {
return nil, fmt.Errorf("fail parse names: %w", err)
}
return &pkgs, nil
}

View File

@@ -25,8 +25,8 @@ import (
"testing" "testing"
"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/internal/repos"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
func TestFindPkgs(t *testing.T) { func TestFindPkgs(t *testing.T) {
@@ -41,7 +41,7 @@ func TestFindPkgs(t *testing.T) {
err := rs.Pull(e.Ctx, []types.Repo{ err := rs.Pull(e.Ctx, []types.Repo{
{ {
Name: "default", Name: "default",
URL: "https://gitea.plemya-x.ru/xpamych/xpamych-alr-repo.git", URL: "https://gitea.plemya-x.ru/Plemya-x/alr-default.git",
}, },
}) })
if err != nil { if err != nil {

View File

@@ -43,11 +43,8 @@ import (
"mvdan.cc/sh/v3/syntax" "mvdan.cc/sh/v3/syntax"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "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/shutils/decoder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/handlers" "gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/handlers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
) )
type actionType uint8 type actionType uint8
@@ -231,79 +228,19 @@ func (rs *Repos) Pull(ctx context.Context, repos []types.Repo) error {
func (rs *Repos) updatePkg(ctx context.Context, repo types.Repo, runner *interp.Runner, scriptFl io.ReadCloser) error { func (rs *Repos) updatePkg(ctx context.Context, repo types.Repo, runner *interp.Runner, scriptFl io.ReadCloser) error {
parser := syntax.NewParser() parser := syntax.NewParser()
defer scriptFl.Close() pkgs, err := parseScript(ctx, repo, parser, runner, scriptFl)
fl, err := parser.Parse(scriptFl, "alr.sh")
if err != nil { if err != nil {
return err return err
} }
runner.Reset() for _, pkg := range pkgs {
err = runner.Run(ctx, fl)
if err != nil {
return err
}
type packages struct {
BasePkgName string `sh:"basepkg_name"`
Names []string `sh:"name"`
}
var pkgs packages
d := decoder.New(&distro.OSRelease{}, runner)
d.Overrides = false
d.LikeDistros = false
err = d.DecodeVars(&pkgs)
if err != nil {
return err
}
if len(pkgs.Names) > 1 {
if pkgs.BasePkgName == "" {
pkgs.BasePkgName = pkgs.Names[0]
}
for _, pkgName := range pkgs.Names {
pkgInfo := PackageInfo{}
funcName := fmt.Sprintf("meta_%s", pkgName)
runner.Reset()
err = runner.Run(ctx, fl)
if err != nil {
return err
}
meta, ok := d.GetFuncWithSubshell(funcName)
if !ok {
return errors.New("func is missing")
}
r, err := meta(ctx)
if err != nil {
return err
}
d := decoder.New(&distro.OSRelease{}, r)
d.Overrides = false
d.LikeDistros = false
err = d.DecodeVars(&pkgInfo)
if err != nil {
return err
}
pkg := pkgInfo.ToPackage(repo.Name)
resolveOverrides(r, pkg)
pkg.Name = pkgName
pkg.BasePkgName = pkgs.BasePkgName
err = rs.db.InsertPackage(ctx, *pkg) err = rs.db.InsertPackage(ctx, *pkg)
if err != nil { if err != nil {
return err return err
} }
} }
return nil
}
pkg := EmptyPackage(repo.Name) return nil
err = d.DecodeVars(pkg)
if err != nil {
return err
}
resolveOverrides(runner, pkg)
return rs.db.InsertPackage(ctx, *pkg)
} }
func (rs *Repos) processRepoChangesRunner(repoDir, scriptDir string) (*interp.Runner, error) { func (rs *Repos) processRepoChangesRunner(repoDir, scriptDir string) (*interp.Runner, error) {
@@ -399,16 +336,17 @@ func (rs *Repos) processRepoChanges(ctx context.Context, repo types.Repo, r *git
return nil return nil
} }
var pkg db.Package pkgs, err := parseScript(ctx, repo, parser, runner, r)
err = parseScript(ctx, parser, runner, r, &pkg)
if err != nil { if err != nil {
return err return err
} }
for _, pkg := range pkgs {
err = rs.db.DeletePkgs(ctx, "name = ? AND repository = ?", pkg.Name, repo.Name) err = rs.db.DeletePkgs(ctx, "name = ? AND repository = ?", pkg.Name, repo.Name)
if err != nil { if err != nil {
return err return err
} }
}
case actionUpdate: case actionUpdate:
if filepath.Base(action.File) != "alr.sh" { if filepath.Base(action.File) != "alr.sh" {
action.File = filepath.Join(filepath.Dir(action.File), "alr.sh") action.File = filepath.Join(filepath.Dir(action.File), "alr.sh")

View File

@@ -27,7 +27,7 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "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/db"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type TestALRConfig struct{} type TestALRConfig struct{}

View File

@@ -28,8 +28,8 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "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/db"
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db" database "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/internal/repos"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
type TestEnv struct { type TestEnv struct {

View File

@@ -19,7 +19,7 @@ package repos
import ( import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config" "gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db" database "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/types"
) )
type Config interface { type Config interface {

View File

@@ -18,6 +18,7 @@ package repos
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"path/filepath" "path/filepath"
@@ -34,8 +35,10 @@ import (
"mvdan.cc/sh/v3/syntax" "mvdan.cc/sh/v3/syntax"
"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/parser"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder" "gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
// isValid makes sure the path of the file being updated is valid. // isValid makes sure the path of the file being updated is valid.
@@ -54,23 +57,85 @@ func isValid(from, to diff.File) bool {
return match return match
} }
func parseScript(ctx context.Context, parser *syntax.Parser, runner *interp.Runner, r io.ReadCloser, pkg *db.Package) error { func parseScript(
defer r.Close() ctx context.Context,
fl, err := parser.Parse(r, "alr.sh") repo types.Repo,
syntaxParser *syntax.Parser,
runner *interp.Runner,
r io.ReadCloser,
) ([]*db.Package, error) {
fl, err := syntaxParser.Parse(r, "alr.sh")
if err != nil { if err != nil {
return err return nil, err
} }
runner.Reset() runner.Reset()
err = runner.Run(ctx, fl) err = runner.Run(ctx, fl)
if err != nil { if err != nil {
return err return nil, err
} }
d := decoder.New(&distro.OSRelease{}, runner) d := decoder.New(&distro.OSRelease{}, runner)
d.Overrides = false d.Overrides = false
d.LikeDistros = false d.LikeDistros = false
return d.DecodeVars(pkg)
pkgNames, err := parser.ParseNames(d)
if err != nil {
return nil, fmt.Errorf("failed parsing package names: %w", err)
}
if len(pkgNames.Names) == 0 {
return nil, errors.New("package name is missing")
}
var dbPkgs []*db.Package
if len(pkgNames.Names) > 1 {
if pkgNames.BasePkgName == "" {
pkgNames.BasePkgName = pkgNames.Names[0]
}
for _, pkgName := range pkgNames.Names {
pkgInfo := PackageInfo{}
funcName := fmt.Sprintf("meta_%s", pkgName)
runner.Reset()
err = runner.Run(ctx, fl)
if err != nil {
return nil, err
}
meta, ok := d.GetFuncWithSubshell(funcName)
if !ok {
return nil, fmt.Errorf("func %s is missing", funcName)
}
r, err := meta(ctx)
if err != nil {
return nil, err
}
d := decoder.New(&distro.OSRelease{}, r)
d.Overrides = false
d.LikeDistros = false
err = d.DecodeVars(&pkgInfo)
if err != nil {
return nil, err
}
pkg := pkgInfo.ToPackage(repo.Name)
resolveOverrides(r, pkg)
pkg.Name = pkgName
pkg.BasePkgName = pkgNames.BasePkgName
dbPkgs = append(dbPkgs, pkg)
}
return dbPkgs, nil
}
pkg := EmptyPackage(repo.Name)
err = d.DecodeVars(pkg)
if err != nil {
return nil, err
}
resolveOverrides(runner, pkg)
dbPkgs = append(dbPkgs, pkg)
return dbPkgs, nil
} }
type PackageInfo struct { type PackageInfo struct {

View File

@@ -21,7 +21,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search" "gitea.plemya-x.ru/Plemya-x/ALR/internal/search"
) )
func TestSearhOptionsBuilder(t *testing.T) { func TestSearhOptionsBuilder(t *testing.T) {

View File

@@ -38,23 +38,23 @@ msgstr ""
msgid "Cannot get absolute script path" msgid "Cannot get absolute script path"
msgstr "" msgstr ""
#: build.go:148 #: build.go:152
msgid "Package not found" msgid "Package not found"
msgstr "" msgstr ""
#: build.go:161 #: build.go:165
msgid "Nothing to build" msgid "Nothing to build"
msgstr "" msgstr ""
#: build.go:218 #: build.go:222
msgid "Error building package" msgid "Error building package"
msgstr "" msgstr ""
#: build.go:225 #: build.go:229
msgid "Error moving the package" msgid "Error moving the package"
msgstr "" msgstr ""
#: build.go:229 #: build.go:233
msgid "Done" msgid "Done"
msgstr "" msgstr ""
@@ -178,6 +178,68 @@ msgstr ""
msgid "Error removing packages" msgid "Error removing packages"
msgstr "" msgstr ""
#: internal/build/build.go:375
msgid "Building package"
msgstr ""
#: internal/build/build.go:404
msgid "The checksums array must be the same length as sources"
msgstr ""
#: internal/build/build.go:446
msgid "Downloading sources"
msgstr ""
#: internal/build/build.go:538
msgid "Installing dependencies"
msgstr ""
#: internal/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
#: internal/build/checker.go:67
msgid "This package is already installed"
msgstr ""
#: internal/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr ""
#: internal/build/find_deps/alt_linux.go:86
msgid "Provided dependency found"
msgstr ""
#: internal/build/find_deps/alt_linux.go:93
msgid "Required dependency found"
msgstr ""
#: internal/build/find_deps/empty.go:32
msgid "AutoProv is not implemented for this package format, so it's skipped"
msgstr ""
#: internal/build/find_deps/empty.go:37
msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
#: internal/build/script_executor.go:145
msgid "Building package metadata"
msgstr ""
#: internal/build/script_executor.go:275
msgid "Executing prepare()"
msgstr ""
#: internal/build/script_executor.go:284
msgid "Executing build()"
msgstr ""
#: internal/build/script_executor.go:313 internal/build/script_executor.go:333
msgid "Executing %s()"
msgstr ""
#: internal/cliutils/app_builder/builder.go:75 #: internal/cliutils/app_builder/builder.go:75
msgid "Error loading config" msgid "Error loading config"
msgstr "" msgstr ""
@@ -278,6 +340,12 @@ msgstr ""
msgid "OPTIONS" msgid "OPTIONS"
msgstr "" msgstr ""
#: internal/cliutils/utils.go:69
msgid ""
"This command is deprecated and would be removed in the future, use \"%s\" "
"instead!"
msgstr ""
#: internal/db/db.go:137 #: internal/db/db.go:137
msgid "Database version mismatch; resetting" msgid "Database version mismatch; resetting"
msgstr "" msgstr ""
@@ -315,6 +383,24 @@ msgstr ""
msgid "ERROR" msgid "ERROR"
msgstr "" msgstr ""
#: internal/repos/pull.go:77
msgid "Pulling repository"
msgstr ""
#: internal/repos/pull.go:113
msgid "Repository up to date"
msgstr ""
#: internal/repos/pull.go:204
msgid "Git repository does not appear to be a valid ALR repo"
msgstr ""
#: internal/repos/pull.go:220
msgid ""
"ALR repo's minimum ALR version is greater than the current version. Try "
"updating ALR if something doesn't work."
msgstr ""
#: internal/utils/cmd.go:97 #: internal/utils/cmd.go:97
msgid "Error on dropping capabilities" msgid "Error on dropping capabilities"
msgstr "" msgstr ""
@@ -327,10 +413,30 @@ msgstr ""
msgid "You need to be root to perform this action" msgid "You need to be root to perform this action"
msgstr "" msgstr ""
#: list.go:41 #: list.go:43
msgid "List ALR repo packages" msgid "List ALR repo packages"
msgstr "" msgstr ""
#: list.go:57
msgid "Format output using a Go template"
msgstr ""
#: list.go:89
msgid "Error getting packages for upgrade"
msgstr ""
#: list.go:92
msgid "No packages for upgrade"
msgstr ""
#: list.go:102 list.go:187
msgid "Error parsing format template"
msgstr ""
#: list.go:108 list.go:191
msgid "Error executing template"
msgstr ""
#: main.go:45 #: main.go:45
msgid "Print the current ALR version and exit" msgid "Print the current ALR version and exit"
msgstr "" msgstr ""
@@ -343,136 +449,76 @@ msgstr ""
msgid "Enable interactive questions and prompts" msgid "Enable interactive questions and prompts"
msgstr "" msgstr ""
#: main.go:145 #: main.go:146
msgid "Show help" msgid "Show help"
msgstr "" msgstr ""
#: main.go:149 #: main.go:150
msgid "Error while running app" msgid "Error while running app"
msgstr "" msgstr ""
#: pkg/build/build.go:395 #: refresh.go:30
msgid "Building package" msgid "Pull all repositories that have changed"
msgstr ""
#: pkg/build/build.go:424
msgid "The checksums array must be the same length as sources"
msgstr ""
#: pkg/build/build.go:455
msgid "Downloading sources"
msgstr ""
#: pkg/build/build.go:549
msgid "Installing dependencies"
msgstr ""
#: pkg/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
#: pkg/build/checker.go:67
msgid "This package is already installed"
msgstr ""
#: pkg/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr ""
#: pkg/build/find_deps/alt_linux.go:86
msgid "Provided dependency found"
msgstr ""
#: pkg/build/find_deps/alt_linux.go:93
msgid "Required dependency found"
msgstr ""
#: pkg/build/find_deps/empty.go:32
msgid "AutoProv is not implemented for this package format, so it's skipped"
msgstr ""
#: pkg/build/find_deps/empty.go:37
msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
#: pkg/build/script_executor.go:237
msgid "Building package metadata"
msgstr ""
#: pkg/build/script_executor.go:368
msgid "Executing prepare()"
msgstr ""
#: pkg/build/script_executor.go:377
msgid "Executing build()"
msgstr ""
#: pkg/build/script_executor.go:406 pkg/build/script_executor.go:426
msgid "Executing %s()"
msgstr ""
#: pkg/repos/pull.go:80
msgid "Pulling repository"
msgstr ""
#: pkg/repos/pull.go:116
msgid "Repository up to date"
msgstr ""
#: pkg/repos/pull.go:207
msgid "Git repository does not appear to be a valid ALR repo"
msgstr ""
#: pkg/repos/pull.go:223
msgid ""
"ALR repo's minimum ALR version is greater than the current version. Try "
"updating ALR if something doesn't work."
msgstr "" msgstr ""
#: repo.go:39 #: repo.go:39
msgid "Add a new repository" msgid "Manage repos"
msgstr "" msgstr ""
#: repo.go:46 #: repo.go:51 repo.go:269
msgid "Name of the new repo"
msgstr ""
#: repo.go:52
msgid "URL of the new repo"
msgstr ""
#: repo.go:75
msgid "Repo \"%s\" already exists"
msgstr ""
#: repo.go:86 repo.go:159
msgid "Error saving config"
msgstr ""
#: repo.go:112
msgid "Remove an existing repository" msgid "Remove an existing repository"
msgstr "" msgstr ""
#: repo.go:119 #: repo.go:53
msgid "Name of the repo to be deleted" msgid "<name>"
msgstr "" msgstr ""
#: repo.go:148 #: repo.go:83
msgid "Repo \"%s\" does not exist" msgid "Repo \"%s\" does not exist"
msgstr "" msgstr ""
#: repo.go:155 #: repo.go:90
msgid "Error removing repo directory" msgid "Error removing repo directory"
msgstr "" msgstr ""
#: repo.go:178 #: repo.go:94 repo.go:161 repo.go:219
msgid "Error saving config"
msgstr ""
#: repo.go:113
msgid "Error removing packages from database" msgid "Error removing packages from database"
msgstr "" msgstr ""
#: repo.go:189 #: repo.go:124 repo.go:239
msgid "Pull all repositories that have changed" msgid "Add a new repository"
msgstr ""
#: repo.go:125
msgid "<name> <url>"
msgstr ""
#: repo.go:150
msgid "Repo \"%s\" already exists"
msgstr ""
#: repo.go:187
msgid "Set the reference of the repository"
msgstr ""
#: repo.go:188
msgid "<name> <ref>"
msgstr ""
#: repo.go:246
msgid "Name of the new repo"
msgstr ""
#: repo.go:252
msgid "URL of the new repo"
msgstr ""
#: repo.go:276
msgid "Name of the repo to be deleted"
msgstr "" msgstr ""
#: search.go:40 #: search.go:40
@@ -495,22 +541,10 @@ msgstr ""
msgid "Search by provides" msgid "Search by provides"
msgstr "" msgstr ""
#: search.go:71
msgid "Format output using a Go template"
msgstr ""
#: search.go:130 #: search.go:130
msgid "Error while executing search" msgid "Error while executing search"
msgstr "" msgstr ""
#: search.go:138
msgid "Error parsing format template"
msgstr ""
#: search.go:153
msgid "Error executing template"
msgstr ""
#: upgrade.go:47 #: upgrade.go:47
msgid "Upgrade all installed packages" msgid "Upgrade all installed packages"
msgstr "" msgstr ""

View File

@@ -5,7 +5,7 @@
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: unnamed project\n" "Project-Id-Version: unnamed project\n"
"PO-Revision-Date: 2025-04-27 18:27+0300\n" "PO-Revision-Date: 2025-05-16 20:47+0300\n"
"Last-Translator: Maxim Slipenko <maks1ms@alt-gnome.ru>\n" "Last-Translator: Maxim Slipenko <maks1ms@alt-gnome.ru>\n"
"Language-Team: Russian\n" "Language-Team: Russian\n"
"Language: ru\n" "Language: ru\n"
@@ -45,23 +45,23 @@ msgstr "Ошибка при получении рабочего каталога
msgid "Cannot get absolute script path" msgid "Cannot get absolute script path"
msgstr "Невозможно получить абсолютный путь к скрипту" msgstr "Невозможно получить абсолютный путь к скрипту"
#: build.go:148 #: build.go:152
msgid "Package not found" msgid "Package not found"
msgstr "Пакет не найден" msgstr "Пакет не найден"
#: build.go:161 #: build.go:165
msgid "Nothing to build" msgid "Nothing to build"
msgstr "Нечего собирать" msgstr "Нечего собирать"
#: build.go:218 #: build.go:222
msgid "Error building package" msgid "Error building package"
msgstr "Ошибка при сборке пакета" msgstr "Ошибка при сборке пакета"
#: build.go:225 #: build.go:229
msgid "Error moving the package" msgid "Error moving the package"
msgstr "Ошибка при перемещении пакета" msgstr "Ошибка при перемещении пакета"
#: build.go:229 #: build.go:233
msgid "Done" msgid "Done"
msgstr "Сделано" msgstr "Сделано"
@@ -185,6 +185,72 @@ msgstr "Для команды remove ожидался хотя бы 1 аргум
msgid "Error removing packages" msgid "Error removing packages"
msgstr "Ошибка при удалении пакетов" msgstr "Ошибка при удалении пакетов"
#: internal/build/build.go:375
msgid "Building package"
msgstr "Сборка пакета"
#: internal/build/build.go:404
msgid "The checksums array must be the same length as sources"
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
#: internal/build/build.go:446
msgid "Downloading sources"
msgstr "Скачивание источников"
#: internal/build/build.go:538
msgid "Installing dependencies"
msgstr "Установка зависимостей"
#: internal/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
"Архитектура процессора вашей системы не соответствует этому пакету. Вы все "
"равно хотите выполнить сборку?"
#: internal/build/checker.go:67
msgid "This package is already installed"
msgstr "Этот пакет уже установлен"
#: internal/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr "Команда не найдена в системе"
#: internal/build/find_deps/alt_linux.go:86
msgid "Provided dependency found"
msgstr "Найденная предоставленная зависимость"
#: internal/build/find_deps/alt_linux.go:93
msgid "Required dependency found"
msgstr "Найдена требуемая зависимость"
#: internal/build/find_deps/empty.go:32
msgid "AutoProv is not implemented for this package format, so it's skipped"
msgstr ""
"AutoProv не реализовано для этого формата пакета, поэтому будет пропущено"
#: internal/build/find_deps/empty.go:37
msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
"AutoReq не реализовано для этого формата пакета, поэтому будет пропущено"
#: internal/build/script_executor.go:145
msgid "Building package metadata"
msgstr "Сборка метаданных пакета"
#: internal/build/script_executor.go:275
msgid "Executing prepare()"
msgstr "Выполнение prepare()"
#: internal/build/script_executor.go:284
msgid "Executing build()"
msgstr "Выполнение build()"
#: internal/build/script_executor.go:313 internal/build/script_executor.go:333
msgid "Executing %s()"
msgstr "Выполнение %s()"
#: internal/cliutils/app_builder/builder.go:75 #: internal/cliutils/app_builder/builder.go:75
msgid "Error loading config" msgid "Error loading config"
msgstr "Ошибка при загрузке" msgstr "Ошибка при загрузке"
@@ -285,6 +351,14 @@ msgstr "КАТЕГОРИЯ"
msgid "OPTIONS" msgid "OPTIONS"
msgstr "ПАРАМЕТРЫ" msgstr "ПАРАМЕТРЫ"
#: internal/cliutils/utils.go:69
msgid ""
"This command is deprecated and would be removed in the future, use \"%s\" "
"instead!"
msgstr ""
"Эта команда устарела и будет удалена в будущем, используйте вместо нее \"%s"
"\"!"
#: internal/db/db.go:137 #: internal/db/db.go:137
msgid "Database version mismatch; resetting" msgid "Database version mismatch; resetting"
msgstr "Несоответствие версий базы данных; сброс настроек" msgstr "Несоответствие версий базы данных; сброс настроек"
@@ -323,6 +397,26 @@ msgstr "%s %s загружается — %s/с\n"
msgid "ERROR" msgid "ERROR"
msgstr "ОШИБКА" msgstr "ОШИБКА"
#: internal/repos/pull.go:77
msgid "Pulling repository"
msgstr "Скачивание репозитория"
#: internal/repos/pull.go:113
msgid "Repository up to date"
msgstr "Репозиторий уже обновлён"
#: internal/repos/pull.go:204
msgid "Git repository does not appear to be a valid ALR repo"
msgstr "Репозиторий Git не поддерживается репозиторием ALR"
#: internal/repos/pull.go:220
msgid ""
"ALR repo's minimum ALR version is greater than the current version. Try "
"updating ALR if something doesn't work."
msgstr ""
"Минимальная версия ALR для ALR-репозитория выше текущей версии. Попробуйте "
"обновить ALR, если что-то не работает."
#: internal/utils/cmd.go:97 #: internal/utils/cmd.go:97
msgid "Error on dropping capabilities" msgid "Error on dropping capabilities"
msgstr "Ошибка при понижении привилегий" msgstr "Ошибка при понижении привилегий"
@@ -335,10 +429,30 @@ msgstr "Вы должны быть членом %s чтобы выполнить
msgid "You need to be root to perform this action" msgid "You need to be root to perform this action"
msgstr "Вы должны быть root чтобы выполнить это" msgstr "Вы должны быть root чтобы выполнить это"
#: list.go:41 #: list.go:43
msgid "List ALR repo packages" msgid "List ALR repo packages"
msgstr "Список пакетов репозитория ALR" msgstr "Список пакетов репозитория ALR"
#: list.go:57
msgid "Format output using a Go template"
msgstr "Формат выходных данных с использованием шаблона Go"
#: list.go:89
msgid "Error getting packages for upgrade"
msgstr "Ошибка при получении пакетов для обновления"
#: list.go:92
msgid "No packages for upgrade"
msgstr "Нет пакетов к обновлению"
#: list.go:102 list.go:187
msgid "Error parsing format template"
msgstr "Ошибка при разборе шаблона"
#: list.go:108 list.go:191
msgid "Error executing template"
msgstr "Ошибка при выполнении шаблона"
#: main.go:45 #: main.go:45
msgid "Print the current ALR version and exit" msgid "Print the current ALR version and exit"
msgstr "Показать текущую версию ALR и выйти" msgstr "Показать текущую версию ALR и выйти"
@@ -351,143 +465,77 @@ msgstr "Аргументы, которые будут переданы мене
msgid "Enable interactive questions and prompts" msgid "Enable interactive questions and prompts"
msgstr "Включение интерактивных вопросов и запросов" msgstr "Включение интерактивных вопросов и запросов"
#: main.go:145 #: main.go:146
msgid "Show help" msgid "Show help"
msgstr "Показать справку" msgstr "Показать справку"
#: main.go:149 #: main.go:150
msgid "Error while running app" msgid "Error while running app"
msgstr "Ошибка при запуске приложения" msgstr "Ошибка при запуске приложения"
#: pkg/build/build.go:395 #: refresh.go:30
msgid "Building package" msgid "Pull all repositories that have changed"
msgstr "Сборка пакета" msgstr "Скачать все изменённые репозитории"
#: pkg/build/build.go:424
msgid "The checksums array must be the same length as sources"
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
#: pkg/build/build.go:455
msgid "Downloading sources"
msgstr "Скачивание источников"
#: pkg/build/build.go:549
msgid "Installing dependencies"
msgstr "Установка зависимостей"
#: pkg/build/checker.go:43
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
"Архитектура процессора вашей системы не соответствует этому пакету. Вы все "
"равно хотите выполнить сборку?"
#: pkg/build/checker.go:67
msgid "This package is already installed"
msgstr "Этот пакет уже установлен"
#: pkg/build/find_deps/alt_linux.go:35
msgid "Command not found on the system"
msgstr "Команда не найдена в системе"
#: pkg/build/find_deps/alt_linux.go:86
msgid "Provided dependency found"
msgstr "Найденная предоставленная зависимость"
#: pkg/build/find_deps/alt_linux.go:93
msgid "Required dependency found"
msgstr "Найдена требуемая зависимость"
#: pkg/build/find_deps/empty.go:32
msgid "AutoProv is not implemented for this package format, so it's skipped"
msgstr ""
"AutoProv не реализовано для этого формата пакета, поэтому будет пропущено"
#: pkg/build/find_deps/empty.go:37
msgid "AutoReq is not implemented for this package format, so it's skipped"
msgstr ""
"AutoReq не реализовано для этого формата пакета, поэтому будет пропущено"
#: pkg/build/script_executor.go:237
msgid "Building package metadata"
msgstr "Сборка метаданных пакета"
#: pkg/build/script_executor.go:368
msgid "Executing prepare()"
msgstr "Выполнение prepare()"
#: pkg/build/script_executor.go:377
msgid "Executing build()"
msgstr "Выполнение build()"
#: pkg/build/script_executor.go:406 pkg/build/script_executor.go:426
msgid "Executing %s()"
msgstr "Выполнение %s()"
#: pkg/repos/pull.go:80
msgid "Pulling repository"
msgstr "Скачивание репозитория"
#: pkg/repos/pull.go:116
msgid "Repository up to date"
msgstr "Репозиторий уже обновлён"
#: pkg/repos/pull.go:207
msgid "Git repository does not appear to be a valid ALR repo"
msgstr "Репозиторий Git не поддерживается репозиторием ALR"
#: pkg/repos/pull.go:223
msgid ""
"ALR repo's minimum ALR version is greater than the current version. Try "
"updating ALR if something doesn't work."
msgstr ""
"Минимальная версия ALR для ALR-репозитория выше текущей версии. Попробуйте "
"обновить ALR, если что-то не работает."
#: repo.go:39 #: repo.go:39
msgid "Add a new repository" msgid "Manage repos"
msgstr "Добавить новый репозиторий" msgstr "Управление репозиториями"
#: repo.go:46 #: repo.go:51 repo.go:269
msgid "Name of the new repo"
msgstr "Название нового репозитория"
#: repo.go:52
msgid "URL of the new repo"
msgstr "URL-адрес нового репозитория"
#: repo.go:75
msgid "Repo \"%s\" already exists"
msgstr "Репозиторий \"%s\" уже существует"
#: repo.go:86 repo.go:159
msgid "Error saving config"
msgstr "Ошибка при сохранении конфигурации"
#: repo.go:112
msgid "Remove an existing repository" msgid "Remove an existing repository"
msgstr "Удалить существующий репозиторий" msgstr "Удалить существующий репозиторий"
#: repo.go:119 #: repo.go:53
msgid "Name of the repo to be deleted" msgid "<name>"
msgstr "Название репозитория удалён" msgstr "<имя>"
#: repo.go:148 #: repo.go:83
msgid "Repo \"%s\" does not exist" msgid "Repo \"%s\" does not exist"
msgstr "Репозитория \"%s\" не существует" msgstr "Репозитория \"%s\" не существует"
#: repo.go:155 #: repo.go:90
msgid "Error removing repo directory" msgid "Error removing repo directory"
msgstr "Ошибка при удалении каталога репозитория" msgstr "Ошибка при удалении каталога репозитория"
#: repo.go:178 #: repo.go:94 repo.go:161 repo.go:219
msgid "Error saving config"
msgstr "Ошибка при сохранении конфигурации"
#: repo.go:113
msgid "Error removing packages from database" msgid "Error removing packages from database"
msgstr "Ошибка при удалении пакетов из базы данных" msgstr "Ошибка при удалении пакетов из базы данных"
#: repo.go:189 #: repo.go:124 repo.go:239
msgid "Pull all repositories that have changed" msgid "Add a new repository"
msgstr "Скачать все изменённые репозитории" msgstr "Добавить новый репозиторий"
#: repo.go:125
msgid "<name> <url>"
msgstr "<имя> <url>"
#: repo.go:150
msgid "Repo \"%s\" already exists"
msgstr "Репозиторий \"%s\" уже существует"
#: repo.go:187
msgid "Set the reference of the repository"
msgstr "Установить ссылку на версию репозитория"
#: repo.go:188
msgid "<name> <ref>"
msgstr "<имя> <ссылкааерсию>"
#: repo.go:246
msgid "Name of the new repo"
msgstr "Название нового репозитория"
#: repo.go:252
msgid "URL of the new repo"
msgstr "URL-адрес нового репозитория"
#: repo.go:276
msgid "Name of the repo to be deleted"
msgstr "Название репозитория удалён"
#: search.go:40 #: search.go:40
msgid "Search packages" msgid "Search packages"
@@ -509,22 +557,10 @@ msgstr "Искать по репозиторию"
msgid "Search by provides" msgid "Search by provides"
msgstr "Иcкать по provides" msgstr "Иcкать по provides"
#: search.go:71
msgid "Format output using a Go template"
msgstr "Формат выходных данных с использованием шаблона Go"
#: search.go:130 #: search.go:130
msgid "Error while executing search" msgid "Error while executing search"
msgstr "Ошибка при выполнении поиска" msgstr "Ошибка при выполнении поиска"
#: search.go:138
msgid "Error parsing format template"
msgstr "Ошибка при разборе шаблона"
#: search.go:153
msgid "Error executing template"
msgstr "Ошибка при выполнении шаблона"
#: upgrade.go:47 #: upgrade.go:47
msgid "Upgrade all installed packages" msgid "Upgrade all installed packages"
msgstr "Обновить все установленные пакеты" msgstr "Обновить все установленные пакеты"

View File

@@ -1,5 +1,5 @@
ALR - Any Linux Repository ALR - Any Linux Repository
Copyright (C) {{ .Year }} Евгений Храмов Copyright (C) {{ .Year }} The ALR Authors
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by

76
list.go
View File

@@ -22,17 +22,19 @@ package main
import ( import (
"fmt" "fmt"
"log/slog" "log/slog"
"os"
"slices"
"text/template"
"github.com/leonelquinteros/gotext" "github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"golang.org/x/exp/slices"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db" database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
) )
func ListCmd() *cli.Command { func ListCmd() *cli.Command {
@@ -45,6 +47,15 @@ func ListCmd() *cli.Command {
Name: "installed", Name: "installed",
Aliases: []string{"I"}, Aliases: []string{"I"},
}, },
&cli.BoolFlag{
Name: "upgradable",
Aliases: []string{"U"},
},
&cli.StringFlag{
Name: "format",
Aliases: []string{"f"},
Usage: gotext.Get("Format output using a Go template"),
},
}, },
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
if err := utils.ExitIfCantDropCapsToAlrUserNoPrivs(); err != nil { if err := utils.ExitIfCantDropCapsToAlrUserNoPrivs(); err != nil {
@@ -57,8 +68,10 @@ func ListCmd() *cli.Command {
New(ctx). New(ctx).
WithConfig(). WithConfig().
WithDB(). WithDB().
WithManager().
// autoPull only // autoPull only
WithRepos(). WithRepos().
WithDistroInfo().
Build() Build()
if err != nil { if err != nil {
return err return err
@@ -67,6 +80,39 @@ func ListCmd() *cli.Command {
cfg := deps.Cfg cfg := deps.Cfg
db := deps.DB db := deps.DB
mgr := deps.Manager
info := deps.Info
if c.Bool("upgradable") {
updates, err := checkForUpdates(ctx, mgr, db, info)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error getting packages for upgrade"), err)
}
if len(updates) == 0 {
slog.Info(gotext.Get("No packages for upgrade"))
return nil
}
format := c.String("format")
if format == "" {
format = "{{.Package.Repository}}/{{.Package.Name}} {{.FromVersion}} -> {{.ToVersion}}\n"
}
tmpl, err := template.New("format").Parse(format)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error parsing format template"), err)
}
for _, updateInfo := range updates {
err = tmpl.Execute(os.Stdout, updateInfo)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error executing template"), err)
}
}
return nil
}
// TODO: refactor code below
where := "true" where := "true"
args := []any(nil) args := []any(nil)
@@ -115,17 +161,35 @@ func ListCmd() *cli.Command {
continue continue
} }
version := pkg.Version type packageInfo struct {
Package *database.Package
Version string
}
pkgInfo := &packageInfo{}
pkgInfo.Package = &pkg
pkgInfo.Version = pkg.Version
if c.Bool("installed") { if c.Bool("installed") {
instVersion, ok := installedAlrPackages[fmt.Sprintf("%s/%s", pkg.Repository, pkg.Name)] instVersion, ok := installedAlrPackages[fmt.Sprintf("%s/%s", pkg.Repository, pkg.Name)]
if !ok { if !ok {
continue continue
} else { } else {
version = instVersion pkgInfo.Version = instVersion
} }
} }
fmt.Printf("%s/%s %s\n", pkg.Repository, pkg.Name, version) format := c.String("format")
if format == "" {
format = "{{.Package.Repository}}/{{.Package.Name}} {{.Version}}\n"
}
tmpl, err := template.New("format").Parse(format)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error parsing format template"), err)
}
err = tmpl.Execute(os.Stdout, pkgInfo)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error executing template"), err)
}
} }
return nil return nil

View File

@@ -33,8 +33,8 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "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/config"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/translations" "gitea.plemya-x.ru/Plemya-x/ALR/internal/translations"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/logger" "gitea.plemya-x.ru/Plemya-x/ALR/internal/logger"
) )
@@ -74,14 +74,15 @@ func GetApp() *cli.App {
InfoCmd(), InfoCmd(),
ListCmd(), ListCmd(),
BuildCmd(), BuildCmd(),
AddRepoCmd(), LegacyAddRepoCmd(),
RemoveRepoCmd(), LegacyRemoveRepoCmd(),
RefreshCmd(), RefreshCmd(),
FixCmd(), FixCmd(),
GenCmd(), GenCmd(),
HelperCmd(), HelperCmd(),
VersionCmd(), VersionCmd(),
SearchCmd(), SearchCmd(),
RepoCmd(),
// Internal commands // Internal commands
InternalBuildCmd(), InternalBuildCmd(),
InternalInstallCmd(), InternalInstallCmd(),

View File

@@ -52,9 +52,9 @@
./internal/translations/files/lure.en.toml ./internal/translations/files/lure.en.toml
./internal/translations/files/lure.ru.toml ./internal/translations/files/lure.ru.toml
./internal/translations/translations.go ./internal/translations/translations.go
./internal/types/build.go ./pkg/types/build.go
./internal/types/config.go ./pkg/types/config.go
./internal/types/repo.go ./pkg/types/repo.go
./list.go ./list.go
./main.go ./main.go
./pkg/build/build.go ./pkg/build/build.go

168
pkg/alrsh/alrsh.go Normal file
View File

@@ -0,0 +1,168 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 alrsh
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cpu"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/decoder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/handlers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/helpers"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
type ALRSh struct {
file *syntax.File
path string
}
func createBuildEnvVars(info *distro.OSRelease, dirs types.Directories) []string {
env := os.Environ()
env = append(
env,
"DISTRO_NAME="+info.Name,
"DISTRO_PRETTY_NAME="+info.PrettyName,
"DISTRO_ID="+info.ID,
"DISTRO_VERSION_ID="+info.VersionID,
"DISTRO_ID_LIKE="+strings.Join(info.Like, " "),
"ARCH="+cpu.Arch(),
"NCPU="+strconv.Itoa(runtime.NumCPU()),
)
if dirs.ScriptDir != "" {
env = append(env, "scriptdir="+dirs.ScriptDir)
}
if dirs.PkgDir != "" {
env = append(env, "pkgdir="+dirs.PkgDir)
}
if dirs.SrcDir != "" {
env = append(env, "srcdir="+dirs.SrcDir)
}
return env
}
func (s *ALRSh) ParseBuildVars(ctx context.Context, info *distro.OSRelease, packages []string) (string, []*types.BuildVars, error) {
varsOfPackages := []*types.BuildVars{}
scriptDir := filepath.Dir(s.path)
env := createBuildEnvVars(info, types.Directories{ScriptDir: scriptDir})
runner, err := interp.New(
interp.Env(expand.ListEnviron(env...)), // Устанавливаем окружение
interp.StdIO(os.Stdin, os.Stderr, os.Stderr), // Устанавливаем стандартный ввод-вывод
interp.ExecHandler(helpers.Restricted.ExecHandler(handlers.NopExec)), // Ограничиваем выполнение
interp.ReadDirHandler2(handlers.RestrictedReadDir(scriptDir)), // Ограничиваем чтение директорий
interp.StatHandler(handlers.RestrictedStat(scriptDir)), // Ограничиваем доступ к статистике файлов
interp.OpenHandler(handlers.RestrictedOpen(scriptDir)), // Ограничиваем открытие файлов
interp.Dir(scriptDir),
)
if err != nil {
return "", nil, err
}
err = runner.Run(ctx, s.file) // Запускаем скрипт
if err != nil {
return "", nil, err
}
dec := decoder.New(info, runner) // Создаём новый декодер
type Packages struct {
BasePkgName string `sh:"basepkg_name"`
Names []string `sh:"name"`
}
var pkgs Packages
err = dec.DecodeVars(&pkgs)
if err != nil {
return "", nil, err
}
if len(pkgs.Names) == 0 {
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
}
varsOfPackages = append(varsOfPackages, &vars)
return vars.Name, varsOfPackages, nil
}
var pkgNames []string
if len(packages) != 0 {
pkgNames = packages
} else {
pkgNames = pkgs.Names
}
for _, pkgName := range pkgNames {
var preVars types.BuildVarsPre
funcName := fmt.Sprintf("meta_%s", pkgName)
meta, ok := dec.GetFuncWithSubshell(funcName)
if !ok {
return "", nil, fmt.Errorf("func %s is missing", funcName)
}
r, err := meta(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)
}
return pkgs.BasePkgName, varsOfPackages, nil
}
func (a *ALRSh) Path() string {
return a.path
}
func (a *ALRSh) File() *syntax.File {
return a.file
}

61
pkg/alrsh/gob.go Normal file
View File

@@ -0,0 +1,61 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 alrsh
import (
"bytes"
"encoding/gob"
"mvdan.cc/sh/v3/syntax"
"mvdan.cc/sh/v3/syntax/typedjson"
)
func (s *ALRSh) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(s.path); err != nil {
return nil, err
}
var fileBuf bytes.Buffer
if err := typedjson.Encode(&fileBuf, s.file); err != nil {
return nil, err
}
fileData := fileBuf.Bytes()
if err := enc.Encode(fileData); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (s *ALRSh) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
if err := dec.Decode(&s.path); err != nil {
return err
}
var fileData []byte
if err := dec.Decode(&fileData); err != nil {
return err
}
fileReader := bytes.NewReader(fileData)
file, err := typedjson.Decode(fileReader)
if err != nil {
return err
}
s.file = file.(*syntax.File)
return nil
}

52
pkg/alrsh/read.go Normal file
View File

@@ -0,0 +1,52 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 alrsh
import (
"fmt"
"io/fs"
"os"
"mvdan.cc/sh/v3/syntax"
)
type localFs struct{}
func (fs *localFs) Open(name string) (fs.File, error) {
return os.Open(name)
}
func ReadFromFS(fsys fs.FS, script string) (*ALRSh, error) {
fl, err := fsys.Open(script)
if err != nil {
return nil, fmt.Errorf("failed to open alr.sh: %w", err)
}
defer fl.Close()
file, err := syntax.NewParser().Parse(fl, "alr.sh")
if err != nil {
return nil, err
}
return &ALRSh{
file: file,
path: script,
}, nil
}
func ReadFromLocal(script string) (*ALRSh, error) {
return ReadFromFS(&localFs{}, script)
}

66
pkg/types/script.go Normal file
View File

@@ -0,0 +1,66 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 types
import (
"bytes"
"encoding/gob"
"mvdan.cc/sh/v3/syntax"
"mvdan.cc/sh/v3/syntax/typedjson"
)
type ScriptFile struct {
File *syntax.File
Path string
}
func (s *ScriptFile) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(s.Path); err != nil {
return nil, err
}
var fileBuf bytes.Buffer
if err := typedjson.Encode(&fileBuf, s.File); err != nil {
return nil, err
}
fileData := fileBuf.Bytes()
if err := enc.Encode(fileData); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (s *ScriptFile) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
if err := dec.Decode(&s.Path); err != nil {
return err
}
var fileData []byte
if err := dec.Decode(&fileData); err != nil {
return err
}
fileReader := bytes.NewReader(fileData)
file, err := typedjson.Decode(fileReader)
if err != nil {
return err
}
s.File = file.(*syntax.File)
return nil
}

52
refresh.go Normal file
View File

@@ -0,0 +1,52 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 The ALR Authors
//
// 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 (
"github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
)
func RefreshCmd() *cli.Command {
return &cli.Command{
Name: "refresh",
Usage: gotext.Get("Pull all repositories that have changed"),
Aliases: []string{"ref"},
Action: func(c *cli.Context) error {
if err := utils.ExitIfCantDropCapsToAlrUser(); err != nil {
return err
}
ctx := c.Context
deps, err := appbuilder.
New(ctx).
WithConfig().
WithDB().
WithReposForcePull().
Build()
if err != nil {
return err
}
defer deps.Defer()
return nil
},
}
}

249
repo.go
View File

@@ -29,100 +29,35 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
) )
func AddRepoCmd() *cli.Command { func RepoCmd() *cli.Command {
return &cli.Command{ return &cli.Command{
Name: "addrepo", Name: "repo",
Usage: gotext.Get("Add a new repository"), Usage: gotext.Get("Manage repos"),
Aliases: []string{"ar"}, Subcommands: []*cli.Command{
Flags: []cli.Flag{ RemoveRepoCmd(),
&cli.StringFlag{ AddRepoCmd(),
Name: "name", SetRepoRefCmd(),
Aliases: []string{"n"},
Required: true,
Usage: gotext.Get("Name of the new repo"),
}, },
&cli.StringFlag{
Name: "url",
Aliases: []string{"u"},
Required: true,
Usage: gotext.Get("URL of the new repo"),
},
},
Action: utils.RootNeededAction(func(c *cli.Context) error {
name := c.String("name")
repoURL := c.String("url")
ctx := c.Context
deps, err := appbuilder.
New(ctx).
WithConfig().
Build()
if err != nil {
return err
}
defer deps.Defer()
cfg := deps.Cfg
reposSlice := cfg.Repos()
for _, repo := range reposSlice {
if repo.URL == repoURL || repo.Name == name {
return cliutils.FormatCliExit(gotext.Get("Repo \"%s\" already exists", repo.Name), nil)
}
}
reposSlice = append(reposSlice, types.Repo{
Name: name,
URL: repoURL,
})
cfg.SetRepos(reposSlice)
err = cfg.SaveUserConfig()
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error saving config"), err)
}
if err := utils.ExitIfCantDropCapsToAlrUserNoPrivs(); err != nil {
return err
}
deps, err = appbuilder.
New(ctx).
UseConfig(cfg).
WithDB().
WithReposForcePull().
Build()
if err != nil {
return err
}
defer deps.Defer()
return nil
}),
} }
} }
func RemoveRepoCmd() *cli.Command { func RemoveRepoCmd() *cli.Command {
return &cli.Command{ return &cli.Command{
Name: "removerepo", Name: "remove",
Usage: gotext.Get("Remove an existing repository"), Usage: gotext.Get("Remove an existing repository"),
Aliases: []string{"rr"}, Aliases: []string{"rm"},
Flags: []cli.Flag{ ArgsUsage: gotext.Get("<name>"),
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Required: true,
Usage: gotext.Get("Name of the repo to be deleted"),
},
},
Action: utils.RootNeededAction(func(c *cli.Context) error { Action: utils.RootNeededAction(func(c *cli.Context) error {
ctx := c.Context if c.Args().Len() < 1 {
return cliutils.FormatCliExit("missing args", nil)
}
name := c.Args().Get(0)
name := c.String("name") ctx := c.Context
deps, err := appbuilder. deps, err := appbuilder.
New(ctx). New(ctx).
@@ -183,21 +118,56 @@ func RemoveRepoCmd() *cli.Command {
} }
} }
func RefreshCmd() *cli.Command { func AddRepoCmd() *cli.Command {
return &cli.Command{ return &cli.Command{
Name: "refresh", Name: "add",
Usage: gotext.Get("Pull all repositories that have changed"), Usage: gotext.Get("Add a new repository"),
Aliases: []string{"ref"}, ArgsUsage: gotext.Get("<name> <url>"),
Action: func(c *cli.Context) error { Action: utils.RootNeededAction(func(c *cli.Context) error {
if err := utils.ExitIfCantDropCapsToAlrUser(); err != nil { if c.Args().Len() < 2 {
return err return cliutils.FormatCliExit("missing args", nil)
} }
name := c.Args().Get(0)
repoURL := c.Args().Get(1)
ctx := c.Context ctx := c.Context
deps, err := appbuilder. deps, err := appbuilder.
New(ctx). New(ctx).
WithConfig(). WithConfig().
Build()
if err != nil {
return err
}
defer deps.Defer()
cfg := deps.Cfg
reposSlice := cfg.Repos()
for _, repo := range reposSlice {
if repo.URL == repoURL || repo.Name == name {
return cliutils.FormatCliExit(gotext.Get("Repo \"%s\" already exists", repo.Name), nil)
}
}
reposSlice = append(reposSlice, types.Repo{
Name: name,
URL: repoURL,
})
cfg.SetRepos(reposSlice)
err = cfg.SaveUserConfig()
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error saving config"), err)
}
if err := utils.ExitIfCantDropCapsToAlrUserNoPrivs(); err != nil {
return err
}
deps, err = appbuilder.
New(ctx).
UseConfig(cfg).
WithDB(). WithDB().
WithReposForcePull(). WithReposForcePull().
Build() Build()
@@ -205,7 +175,110 @@ func RefreshCmd() *cli.Command {
return err return err
} }
defer deps.Defer() defer deps.Defer()
return nil return nil
}),
}
}
func SetRepoRefCmd() *cli.Command {
return &cli.Command{
Name: "set-ref",
Usage: gotext.Get("Set the reference of the repository"),
ArgsUsage: gotext.Get("<name> <ref>"),
Action: utils.RootNeededAction(func(c *cli.Context) error {
if c.Args().Len() < 2 {
return cliutils.FormatCliExit("missing args", nil)
}
name := c.Args().Get(0)
ref := c.Args().Get(1)
deps, err := appbuilder.
New(c.Context).
WithConfig().
WithDB().
WithReposNoPull().
Build()
if err != nil {
return err
}
defer deps.Defer()
repos := deps.Cfg.Repos()
newRepos := []types.Repo{}
for _, repo := range repos {
if repo.Name == name {
repo.Ref = ref
}
newRepos = append(newRepos, repo)
}
deps.Cfg.SetRepos(newRepos)
err = deps.Cfg.SaveUserConfig()
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error saving config"), err)
}
err = deps.Repos.Pull(c.Context, newRepos)
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error pulling repositories"), err)
}
return nil
}),
}
}
// TODO: remove
//
// Deprecated: use "alr repo add"
func LegacyAddRepoCmd() *cli.Command {
return &cli.Command{
Hidden: true,
Name: "addrepo",
Usage: gotext.Get("Add a new repository"),
Aliases: []string{"ar"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Required: true,
Usage: gotext.Get("Name of the new repo"),
}, },
&cli.StringFlag{
Name: "url",
Aliases: []string{"u"},
Required: true,
Usage: gotext.Get("URL of the new repo"),
},
},
Action: utils.RootNeededAction(func(c *cli.Context) error {
cliutils.WarnLegacyCommand("alr repo add <name> <url>")
return c.App.RunContext(c.Context, []string{"", "repo", "add", c.String("name"), c.String("url")})
}),
}
}
// TODO: remove
//
// Deprecated: use "alr repo rm"
func LegacyRemoveRepoCmd() *cli.Command {
return &cli.Command{
Hidden: true,
Name: "removerepo",
Usage: gotext.Get("Remove an existing repository"),
Aliases: []string{"rr"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Required: true,
Usage: gotext.Get("Name of the repo to be deleted"),
},
},
Action: utils.RootNeededAction(func(c *cli.Context) error {
cliutils.WarnLegacyCommand("alr repo remove <name>")
return c.App.RunContext(c.Context, []string{"", "repo", "remove", c.String("name")})
}),
} }
} }

View File

@@ -41,10 +41,10 @@ installPkg() {
fi fi
case $1 in case $1 in
pacman) $rootCmd pacman --noconfirm -U ${@:2} ;; pacman) $rootCmd pacman --noconfirm -U "${@:2}" ;;
apk) $rootCmd apk add --allow-untrusted ${@:2} ;; apk) $rootCmd apk add --allow-untrusted "${@:2}" ;;
zypper) $rootCmd zypper --no-gpg-checks install ${@:2} ;; zypper) $rootCmd zypper --no-gpg-checks install "${@:2}" ;;
*) $rootCmd $1 install -y ${@:2} ;; *) $rootCmd "$1" install -y "${@:2}" ;;
esac esac
} }
@@ -88,20 +88,23 @@ else
fi fi
if [ -z "$noPkgMgr" ]; then if [ -z "$noPkgMgr" ]; then
info "Получение списка файлов с https://plemya-x.ru/" info "Получение списка файлов с https://gitea.plemya-x.ru/Plemya-x/ALR/releases"
pageContent=$(curl -s https://plemya-x.ru/?dir=alr)
# Изменено URL и регулярное выражение для списка файлов
pageContent=$(curl -s https://gitea.plemya-x.ru/Plemya-x/ALR/releases)
# Извлечение списка файлов из HTML # Извлечение списка файлов из HTML
fileList=$(echo "$pageContent" | grep -oP '(?<=href=").*?(?=")' | grep -E 'alr-bin-.*.(pkg.tar.zst|rpm|deb)') fileList=$(echo "$pageContent" | grep -oP '(?<=href=").*?(?=")' | grep -E 'alr-bin.*\.(pkg.tar.zst|rpm|deb)')
echo "Полученный список файлов:" echo "Полученный список файлов:"
echo "$fileList" echo "$fileList"
if [ "$pkgMgr" == "pacman" ]; then if [ "$pkgMgr" == "pacman" ]; then
latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*\.pkg\.tar\.zst' | sort -V | tail -n 1) latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*\.pkg\.tar\.zst' | sort -V | tail -n 1)
elif [ "$pkgMgr" == "apt" ]; then elif [ "$pkgMgr" == "apt" ]; then
latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*\.amd64\.deb' | sort -V | tail -n 1) latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*\.amd64\.deb' | sort -V | tail -n 1)
elif [[ "$pkgMgr" == "dnf" || "$pkgMgr" == "yum" || "$pkgMgr" == "zypper" ]]; then elif [[ "$pkgMgr" == "dnf" || "$pkgMgr" == "yum" || "$pkgMgr" == "zypper" ]]; then
latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*\.x86_64\.rpm' | grep -v 'alt1' | sort -V | tail -n 1) latestFile=$(printf "%s\n" "${fileList[@]}" | grep -E 'alr-bin-.*\.x86_64\.rpm' | grep -v 'alt[0-9]*' | sort -V | tail -n 1)
elif [ "$pkgMgr" == "apt-get" ]; then elif [ "$pkgMgr" == "apt-get" ]; then
latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*-alt[0-9]+\.x86_64\.rpm' | sort -V | tail -n 1) latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*-alt[0-9]+\.x86_64\.rpm' | sort -V | tail -n 1)
else else
@@ -114,34 +117,22 @@ fi
info "Найдена последняя версия ALR: $latestFile" info "Найдена последняя версия ALR: $latestFile"
url="https://plemya-x.ru/$latestFile"
fname="$(mktemp -u -p /tmp "alr.XXXXXXXXXX").${pkgFormat}" fname="$(mktemp -u -p /tmp "alr.XXXXXXXXXX").${pkgFormat}"
info "Загрузка пакета ALR" info "Загрузка пакета ALR"
curl -L $url -o $fname curl -o $fname -L "$latestFile"
if [ ! -f "$fname" ]; then if [ ! -f "$fname" ]; then
error "Ошибка загрузки пакета ALR" error "Ошибка загрузки пакета ALR"
fi fi
info "Установка пакета ALR" info "Установка пакета ALR"
installPkg $pkgMgr $fname installPkg "$pkgMgr" "$fname"
info "Очистка" info "Очистка"
rm $fname rm "$fname"
info "Готово!" info "Готово!"
else else
info "Клонирование репозитория ALR" echo "Не найден поддерживаемый менеджер пакетов. О_о"
git clone https://gitea.plemya-x.ru/xpamych/ALR.git /tmp/alr
info "Установка ALR"
cd /tmp/alr
sudo make install
info "Очистка репозитория ALR"
rm -rf /tmp/alr
info "Все задачи выполнены!"
fi fi

View File

@@ -29,9 +29,9 @@ import (
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
"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/internal/overrides"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/search"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search"
) )
func SearchCmd() *cli.Command { func SearchCmd() *cli.Command {

View File

@@ -29,16 +29,16 @@ import (
"go.elara.ws/vercmp" "go.elara.ws/vercmp"
"golang.org/x/exp/maps" "golang.org/x/exp/maps"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder" appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db" database "gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides" "gitea.plemya-x.ru/Plemya-x/ALR/internal/overrides"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types" "gitea.plemya-x.ru/Plemya-x/ALR/internal/search"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/utils" "gitea.plemya-x.ru/Plemya-x/ALR/internal/utils"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/build"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro" "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/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/search"
) )
func UpgradeCmd() *cli.Command { func UpgradeCmd() *cli.Command {
@@ -116,7 +116,7 @@ func UpgradeCmd() *cli.Command {
Info: deps.Info, Info: deps.Info,
PkgFormat_: build.GetPkgFormat(deps.Manager), PkgFormat_: build.GetPkgFormat(deps.Manager),
}, },
updates, mapUptatesInfoToPackages(updates),
) )
if err != nil { if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error checking for updates"), err) return cliutils.FormatCliExit(gotext.Get("Error checking for updates"), err)
@@ -130,12 +130,27 @@ func UpgradeCmd() *cli.Command {
} }
} }
func mapUptatesInfoToPackages(updates []UpdateInfo) []database.Package {
var pkgs []database.Package
for _, info := range updates {
pkgs = append(pkgs, *info.Package)
}
return pkgs
}
type UpdateInfo struct {
Package *database.Package
FromVersion string
ToVersion string
}
func checkForUpdates( func checkForUpdates(
ctx context.Context, ctx context.Context,
mgr manager.Manager, mgr manager.Manager,
db *database.Database, db *database.Database,
info *distro.OSRelease, info *distro.OSRelease,
) ([]database.Package, error) { ) ([]UpdateInfo, error) {
installed, err := mgr.ListInstalled(nil) installed, err := mgr.ListInstalled(nil)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -145,7 +160,7 @@ func checkForUpdates(
s := search.New(db) s := search.New(db)
var out []database.Package var out []UpdateInfo
for _, pkgName := range pkgNames { for _, pkgName := range pkgNames {
matches := build.RegexpALRPackageName.FindStringSubmatch(pkgName) matches := build.RegexpALRPackageName.FindStringSubmatch(pkgName)
if matches != nil { if matches != nil {
@@ -179,10 +194,13 @@ func checkForUpdates(
} }
c := vercmp.Compare(repoVer, installed[pkgName]) c := vercmp.Compare(repoVer, installed[pkgName])
if c == 0 || c == -1 {
continue if c == 1 {
} else if c == 1 { out = append(out, UpdateInfo{
out = append(out, pkg) Package: &pkg,
FromVersion: installed[pkgName],
ToVersion: repoVer,
})
} }
} }