30 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
74 changed files with 882 additions and 551 deletions

View File

@@ -39,19 +39,18 @@ jobs:
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: 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:
DOCKER_HOST: unix:///tmp/podman.sock
IGNORE_ROOT_CHECK: 1
run: |
podman system service -t 0 unix:///tmp/podman.sock &
make e2e-test

View File

@@ -26,6 +26,8 @@ on:
jobs:
pre-commit:
runs-on: ubuntu-latest
container:
image: docker.gitea.com/runner-images:ubuntu-latest
steps:
- name: Checkout

View File

@@ -45,9 +45,15 @@ jobs:
echo "Version - $version"
echo "VERSION=$version" >> $GITHUB_ENV
- name: Build alr binary
- name: Prepare for install
run: |
CGO_ENABLED=0 go build -ldflags "-X gitea.plemya-x.ru/Plemya-x/ALR/internal/config.Version=${{ env.VERSION }}" -o alr
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: |
@@ -65,3 +71,50 @@ jobs:
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

@@ -24,7 +24,7 @@ $(BIN):
go build -ldflags="-X 'gitea.plemya-x.ru/Plemya-x/ALR/internal/config.Version=$(GIT_VERSION)'" -o $@
check-no-root:
@if [[ "$(IGNORE_ROOT_CHECK)" != "1" ]] && [[ "$$(whoami)" == 'root' ]]; then \
@if [ "$$IGNORE_ROOT_CHECK" != "1" ] && [ "`whoami`" = "root" ]; then \
echo "This target shouldn't run as root" 1>&2; \
echo "Set IGNORE_ROOT_CHECK=1 to override" 1>&2; \
exit 1; \
@@ -39,6 +39,12 @@ install: \
$(INSTALED_BIN): $(BIN)
install -Dm755 $< $@
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)
install -Dm755 $< $@

View File

@@ -20,10 +20,10 @@ ALR написан на чистом Go и после сборки не имее
Установочный скрипт автоматически загрузит и установит соответствующий пакет ALR в вашей системе. Чтобы использовать его, просто выполните следующую команду:
```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.
Например, репозиторий [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">
<text x="33.5" y="15" fill="#010101" fill-opacity=".3">coverage</text>
<text x="33.5" y="14">coverage</text>
<text x="86" y="15" fill="#010101" fill-opacity=".3">16.9%</text>
<text x="86" y="14">16.9%</text>
<text x="86" y="15" fill="#010101" fill-opacity=".3">16.7%</text>
<text x="86" y="14">16.7%</text>
</g>
</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/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
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/types"
"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 {
@@ -97,7 +97,7 @@ func BuildCmd() *cli.Command {
var script string
var packages []string
var res *build.BuildResult
var res []*build.BuiltDep
var scriptArgs *build.BuildPackageFromScriptArgs
var dbArgs *build.BuildPackageFromDbArgs
@@ -222,9 +222,9 @@ func BuildCmd() *cli.Command {
return cliutils.FormatCliExit(gotext.Get("Error building package"), err)
}
for _, pkgPath := range res.PackagePaths {
name := filepath.Base(pkgPath)
err = osutils.Move(pkgPath, filepath.Join(wd, name))
for _, pkg := range res {
name := filepath.Base(pkg.Path)
err = osutils.Move(pkg.Path, filepath.Join(wd, name))
if err != nil {
return cliutils.FormatCliExit(gotext.Get("Error moving the package"), err)
}

View File

@@ -182,7 +182,7 @@ func runTestCommands(t *testing.T, r e2e.Runnable, timeout time.Duration, expect
}
const REPO_NAME_FOR_E2E_TESTS = "alr-repo"
const REPO_URL_FOR_E2E_TESTS = "https://gitea.plemya-x.ru/Maks1mS/repo-for-tests.git"
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,

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/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 {

View File

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

View File

@@ -32,14 +32,14 @@ import (
"github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
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/constants"
"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/pkg/build"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
)
func InternalBuildCmd() *cli.Command {

View File

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

View File

@@ -23,7 +23,7 @@ import (
"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 {

View File

@@ -24,8 +24,8 @@ import (
"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/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
type Checker struct {

View File

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

View File

@@ -27,7 +27,7 @@ import (
"github.com/goreleaser/nfpm/v2"
"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 {

View File

@@ -23,7 +23,7 @@ import (
"github.com/goreleaser/nfpm/v2"
"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{}

View File

@@ -28,7 +28,7 @@ import (
"github.com/goreleaser/nfpm/v2"
"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{}

View File

@@ -21,8 +21,8 @@ import (
"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/types"
)
type ProvReqFinder interface {

View File

@@ -17,7 +17,7 @@
package build
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 {

View File

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

View File

@@ -28,7 +28,7 @@ import (
"github.com/hashicorp/go-plugin"
"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 {

View File

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

View File

@@ -19,7 +19,6 @@ package build
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"os"
@@ -36,12 +35,12 @@ import (
"mvdan.cc/sh/v3/interp"
"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/handlers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/shutils/helpers"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
finddeps "gitea.plemya-x.ru/Plemya-x/ALR/pkg/build/find_deps"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/alrsh"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
type LocalScriptExecutor struct {
@@ -54,107 +53,12 @@ func NewLocalScriptExecutor(cfg Config) *LocalScriptExecutor {
}
}
func (e *LocalScriptExecutor) ReadScript(ctx context.Context, scriptPath string) (*ScriptFile, error) {
fl, err := readScript(scriptPath)
if err != nil {
return nil, err
}
return &ScriptFile{
Path: scriptPath,
File: fl,
}, nil
func (e *LocalScriptExecutor) ReadScript(ctx context.Context, scriptPath string) (*alrsh.ALRSh, error) {
return alrsh.ReadFromLocal(scriptPath)
}
func (e *LocalScriptExecutor) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *ScriptFile) (string, []*types.BuildVars, error) {
varsOfPackages := []*types.BuildVars{}
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
}
var pkgNames []string
if len(input.packages) != 0 {
pkgNames = input.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
}
type SecondPassResult struct {
BuiltPaths []string
BuiltNames []string
func (e *LocalScriptExecutor) ExecuteFirstPass(ctx context.Context, input *BuildInput, sf *alrsh.ALRSh) (string, []*types.BuildVars, error) {
return sf.ParseBuildVars(ctx, input.info, input.packages)
}
func (e *LocalScriptExecutor) PrepareDirs(
@@ -182,13 +86,13 @@ func (e *LocalScriptExecutor) PrepareDirs(
func (e *LocalScriptExecutor) ExecuteSecondPass(
ctx context.Context,
input *BuildInput,
sf *ScriptFile,
sf *alrsh.ALRSh,
varsOfPackages []*types.BuildVars,
repoDeps []string,
builtNames []string,
builtDeps []*BuiltDep,
basePkg string,
) (*SecondPassResult, error) {
dirs, err := getDirs(e.cfg, sf.Path, basePkg)
) ([]*BuiltDep, error) {
dirs, err := getDirs(e.cfg, sf.Path(), basePkg)
if err != nil {
return nil, err
}
@@ -206,14 +110,14 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
return nil, err
}
err = runner.Run(ctx, sf.File)
err = runner.Run(ctx, sf.File())
if err != nil {
return nil, err
}
dec := decoder.New(input.info, runner)
var builtPaths []string
// var builtPaths []string
err = e.ExecuteFunctions(ctx, dirs, dec)
if err != nil {
@@ -247,7 +151,7 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
dirs,
append(
repoDeps,
builtNames...,
GetBuiltName(builtDeps)...,
),
funcOut.Contents,
)
@@ -273,14 +177,13 @@ func (e *LocalScriptExecutor) ExecuteSecondPass(
return nil, err
}
builtPaths = append(builtPaths, pkgPath)
builtNames = append(builtNames, vars.Name)
builtDeps = append(builtDeps, &BuiltDep{
Name: vars.Name,
Path: pkgPath,
})
}
return &SecondPassResult{
BuiltPaths: builtPaths,
BuiltNames: builtNames,
}, nil
return builtDeps, nil
}
func buildPkgMetadata(

View File

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

View File

@@ -33,34 +33,17 @@ import (
_ "github.com/goreleaser/nfpm/v2/arch"
_ "github.com/goreleaser/nfpm/v2/deb"
_ "github.com/goreleaser/nfpm/v2/rpm"
"mvdan.cc/sh/v3/syntax"
"github.com/goreleaser/nfpm/v2"
"github.com/goreleaser/nfpm/v2/files"
"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/types"
"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 подготавливает директории для сборки.
func prepareDirs(dirs types.Directories) error {
err := os.RemoveAll(dirs.BaseDir) // Удаляем базовую директорию, если она существует
@@ -288,14 +271,14 @@ func packageNames(pkgs []db.Package) []string {
*/
// Функция removeDuplicates убирает любые дубликаты из предоставленного среза.
func removeDuplicates(slice []string) []string {
seen := map[string]struct{}{}
result := []string{}
func removeDuplicates[T comparable](slice []T) []T {
seen := map[T]struct{}{}
result := []T{}
for _, s := range slice {
if _, ok := seen[s]; !ok {
seen[s] = struct{}{}
result = append(result, s)
for _, item := range slice {
if _, ok := seen[item]; !ok {
seen[item] = struct{}{}
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/config"
"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/manager"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
)
type AppDeps struct {

View File

@@ -29,7 +29,7 @@ import (
"github.com/pelletier/go-toml/v2"
"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 {

View File

@@ -25,8 +25,8 @@ import (
"testing"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/db"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/repos"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/repos"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
func TestFindPkgs(t *testing.T) {
@@ -41,7 +41,7 @@ func TestFindPkgs(t *testing.T) {
err := rs.Pull(e.Ctx, []types.Repo{
{
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 {

View File

@@ -44,7 +44,7 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
"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"
)
type actionType uint8

View File

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

View File

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

View File

@@ -35,10 +35,10 @@ import (
"mvdan.cc/sh/v3/syntax"
"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/types"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/distro"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/parser"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
// isValid makes sure the path of the file being updated is valid.

View File

@@ -21,7 +21,7 @@ import (
"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) {

View File

@@ -178,6 +178,68 @@ msgstr ""
msgid "Error removing packages"
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
msgid "Error loading config"
msgstr ""
@@ -321,6 +383,24 @@ msgstr ""
msgid "ERROR"
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
msgid "Error on dropping capabilities"
msgstr ""
@@ -377,86 +457,6 @@ msgstr ""
msgid "Error while running app"
msgstr ""
#: pkg/build/build.go:395
msgid "Building package"
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:241
msgid "Building package metadata"
msgstr ""
#: pkg/build/script_executor.go:372
msgid "Executing prepare()"
msgstr ""
#: pkg/build/script_executor.go:381
msgid "Executing build()"
msgstr ""
#: pkg/build/script_executor.go:410 pkg/build/script_executor.go:430
msgid "Executing %s()"
msgstr ""
#: pkg/repos/pull.go:77
msgid "Pulling repository"
msgstr ""
#: pkg/repos/pull.go:113
msgid "Repository up to date"
msgstr ""
#: pkg/repos/pull.go:204
msgid "Git repository does not appear to be a valid ALR repo"
msgstr ""
#: pkg/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 ""
#: refresh.go:30
msgid "Pull all repositories that have changed"
msgstr ""

View File

@@ -12,8 +12,8 @@ msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Generator: Gtranslator 48.0\n"
#: build.go:42
@@ -185,6 +185,72 @@ msgstr "Для команды remove ожидался хотя бы 1 аргум
msgid "Error removing packages"
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
msgid "Error loading config"
msgstr "Ошибка при загрузке"
@@ -290,8 +356,8 @@ msgid ""
"This command is deprecated and would be removed in the future, use \"%s\" "
"instead!"
msgstr ""
"Эта команда устарела и будет удалена в будущем, используйте вместо нее "
"\"%s\"!"
"Эта команда устарела и будет удалена в будущем, используйте вместо нее \"%s"
"\"!"
#: internal/db/db.go:137
msgid "Database version mismatch; resetting"
@@ -331,6 +397,26 @@ msgstr "%s %s загружается — %s/с\n"
msgid "ERROR"
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
msgid "Error on dropping capabilities"
msgstr "Ошибка при понижении привилегий"
@@ -387,92 +473,6 @@ msgstr "Показать справку"
msgid "Error while running app"
msgstr "Ошибка при запуске приложения"
#: pkg/build/build.go:395
msgid "Building package"
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:241
msgid "Building package metadata"
msgstr "Сборка метаданных пакета"
#: pkg/build/script_executor.go:372
msgid "Executing prepare()"
msgstr "Выполнение prepare()"
#: pkg/build/script_executor.go:381
msgid "Executing build()"
msgstr "Выполнение build()"
#: pkg/build/script_executor.go:410 pkg/build/script_executor.go:430
msgid "Executing %s()"
msgstr "Выполнение %s()"
#: pkg/repos/pull.go:77
msgid "Pulling repository"
msgstr "Скачивание репозитория"
#: pkg/repos/pull.go:113
msgid "Repository up to date"
msgstr "Репозиторий уже обновлён"
#: pkg/repos/pull.go:204
msgid "Git repository does not appear to be a valid ALR repo"
msgstr "Репозиторий Git не поддерживается репозиторием ALR"
#: pkg/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, если что-то не работает."
#: refresh.go:30
msgid "Pull all repositories that have changed"
msgstr "Скачать все изменённые репозитории"

View File

@@ -29,12 +29,12 @@ import (
"github.com/leonelquinteros/gotext"
"github.com/urfave/cli/v2"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
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/pkg/build"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/manager"
)
func ListCmd() *cli.Command {

View File

@@ -33,8 +33,8 @@ import (
"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/manager"
"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"
)

View File

@@ -52,9 +52,9 @@
./internal/translations/files/lure.en.toml
./internal/translations/files/lure.ru.toml
./internal/translations/translations.go
./internal/types/build.go
./internal/types/config.go
./internal/types/repo.go
./pkg/types/build.go
./pkg/types/config.go
./pkg/types/repo.go
./list.go
./main.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
}

View File

@@ -29,8 +29,8 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
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/pkg/types"
)
func RepoCmd() *cli.Command {

View File

@@ -41,10 +41,10 @@ installPkg() {
fi
case $1 in
pacman) $rootCmd pacman --noconfirm -U ${@:2} ;;
apk) $rootCmd apk add --allow-untrusted ${@:2} ;;
zypper) $rootCmd zypper --no-gpg-checks install ${@:2} ;;
*) $rootCmd $1 install -y ${@:2} ;;
pacman) $rootCmd pacman --noconfirm -U "${@:2}" ;;
apk) $rootCmd apk add --allow-untrusted "${@:2}" ;;
zypper) $rootCmd zypper --no-gpg-checks install "${@:2}" ;;
*) $rootCmd "$1" install -y "${@:2}" ;;
esac
}
@@ -88,60 +88,51 @@ else
fi
if [ -z "$noPkgMgr" ]; then
info "Получение списка файлов с https://plemya-x.ru/"
pageContent=$(curl -s https://plemya-x.ru/?dir=alr)
info "Получение списка файлов с https://gitea.plemya-x.ru/Plemya-x/ALR/releases"
# Изменено URL и регулярное выражение для списка файлов
pageContent=$(curl -s https://gitea.plemya-x.ru/Plemya-x/ALR/releases)
# Извлечение списка файлов из 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 "$fileList"
if [ "$pkgMgr" == "pacman" ]; then
if [ "$pkgMgr" == "pacman" ]; then
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)
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)
elif [ "$pkgMgr" == "apt-get" ]; then
elif [[ "$pkgMgr" == "dnf" || "$pkgMgr" == "yum" || "$pkgMgr" == "zypper" ]]; then
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
latestFile=$(echo "$fileList" | grep -E 'alr-bin-.*-alt[0-9]+\.x86_64\.rpm' | sort -V | tail -n 1)
else
error "Не поддерживаемый менеджер пакетов для автоматической установки"
fi
if [ -z "$latestFile" ]; then
error "Не удалось найти соответствующий пакет для $pkgMgr"
fi
info "Найдена последняя версия ALR: $latestFile"
fname="$(mktemp -u -p /tmp "alr.XXXXXXXXXX").${pkgFormat}"
info "Загрузка пакета ALR"
curl -o $fname -L "$latestFile"
if [ ! -f "$fname" ]; then
error "Ошибка загрузки пакета ALR"
fi
info "Установка пакета ALR"
installPkg "$pkgMgr" "$fname"
info "Очистка"
rm "$fname"
info "Готово!"
else
error "Не поддерживаемый менеджер пакетов для автоматической установки"
fi
if [ -z "$latestFile" ]; then
error "Не удалось найти соответствующий пакет для $pkgMgr"
fi
info "Найдена последняя версия ALR: $latestFile"
url="https://plemya-x.ru/$latestFile"
fname="$(mktemp -u -p /tmp "alr.XXXXXXXXXX").${pkgFormat}"
info "Загрузка пакета ALR"
curl -L $url -o $fname
if [ ! -f "$fname" ]; then
error "Ошибка загрузки пакета ALR"
fi
info "Установка пакета ALR"
installPkg $pkgMgr $fname
info "Очистка"
rm $fname
info "Готово!"
else
info "Клонирование репозитория ALR"
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 "Все задачи выполнены!"
echo "Не найден поддерживаемый менеджер пакетов. О_о"
fi

View File

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

View File

@@ -29,16 +29,16 @@ import (
"go.elara.ws/vercmp"
"golang.org/x/exp/maps"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/build"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils"
appbuilder "gitea.plemya-x.ru/Plemya-x/ALR/internal/cliutils/app_builder"
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/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/pkg/build"
"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/search"
"gitea.plemya-x.ru/Plemya-x/ALR/pkg/types"
)
func UpgradeCmd() *cli.Command {