chore: refactor code

- remove legacy code
- refactor search and add tests
This commit is contained in:
2025-02-22 09:44:59 +03:00
parent 88b8d2fbf3
commit 9bb14312bd
28 changed files with 421 additions and 665 deletions

View File

@ -152,6 +152,13 @@ func (c *ALRConfig) Repos(ctx context.Context) []types.Repo {
return c.cfg.Repos
}
func (c *ALRConfig) SetRepos(ctx context.Context, repos []types.Repo) {
c.cfgOnce.Do(func() {
c.Load(ctx)
})
c.cfg.Repos = repos
}
func (c *ALRConfig) IgnorePkgUpdates(ctx context.Context) []string {
c.cfgOnce.Do(func() {
c.Load(ctx)
@ -172,3 +179,17 @@ func (c *ALRConfig) PagerStyle(ctx context.Context) string {
})
return c.cfg.PagerStyle
}
func (c *ALRConfig) AllowRunAsRoot(ctx context.Context) bool {
c.cfgOnce.Do(func() {
c.Load(ctx)
})
return c.cfg.Unsafe.AllowRunAsRoot
}
func (c *ALRConfig) RootCmd(ctx context.Context) string {
c.cfgOnce.Do(func() {
c.Load(ctx)
})
return c.cfg.RootCmd
}

View File

@ -1,52 +0,0 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package config
import (
"context"
"sync"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/types"
)
// Config returns a ALR configuration struct.
// The first time it's called, it'll load the config from a file.
// Subsequent calls will just return the same value.
//
// Deprecated: use struct method
func Config(ctx context.Context) *types.Config {
return GetInstance(ctx).cfg
}
// =======================
// FOR LEGACY ONLY
// =======================
var (
alrConfig *ALRConfig
alrConfigOnce sync.Once
)
// Deprecated: For legacy only
func GetInstance(ctx context.Context) *ALRConfig {
alrConfigOnce.Do(func() {
alrConfig = New()
alrConfig.Load(ctx)
})
return alrConfig
}

View File

@ -1,70 +0,0 @@
// This file was originally part of the project "LURE - Linux User REpository", created by Elara Musayelyan.
// It has been modified as part of "ALR - Any Linux Repository" by Евгений Храмов.
//
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package config
import (
"context"
"log/slog"
"os"
"strings"
"sync"
"github.com/leonelquinteros/gotext"
"golang.org/x/text/language"
)
var (
langMtx sync.Mutex
lang language.Tag
langSet bool
)
// Language returns the system language.
// The first time it's called, it'll detect the langauge based on
// the $LANG environment variable.
// Subsequent calls will just return the same value.
func Language(ctx context.Context) language.Tag {
langMtx.Lock()
if !langSet {
syslang := SystemLang()
tag, err := language.Parse(syslang)
if err != nil {
slog.Error(gotext.Get("Error parsing system language"), "err", err)
langMtx.Unlock()
os.Exit(1)
}
base, _ := tag.Base()
lang = language.Make(base.String())
langSet = true
}
langMtx.Unlock()
return lang
}
// SystemLang returns the system language based on
// the $LANG environment variable.
func SystemLang() string {
lang := os.Getenv("LANG")
lang, _, _ = strings.Cut(lang, ".")
if lang == "" || lang == "C" {
lang = "en"
}
return lang
}

View File

@ -19,10 +19,6 @@
package config
import (
"context"
)
// Paths contains various paths used by ALR
type Paths struct {
ConfigDir string
@ -32,14 +28,3 @@ type Paths struct {
PkgsDir string
DBPath string
}
// GetPaths returns a Paths struct.
// The first time it's called, it'll generate the struct
// using information from the system.
// Subsequent calls will return the same value.
//
// Deprecated: use struct API
func GetPaths(ctx context.Context) *Paths {
alrConfig := GetInstance(ctx)
return alrConfig.GetPaths(ctx)
}

View File

@ -1,106 +0,0 @@
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package db
import (
"context"
"log/slog"
"os"
"sync"
"github.com/jmoiron/sqlx"
"github.com/leonelquinteros/gotext"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
)
// DB returns the ALR database.
// The first time it's called, it opens the SQLite database file.
// Subsequent calls return the same connection.
//
// Deprecated: use struct method
func DB(ctx context.Context) *sqlx.DB {
return GetInstance(ctx).GetConn()
}
// Close closes the database
//
// Deprecated: use struct method
func Close() error {
if database != nil {
return database.Close()
}
return nil
}
// IsEmpty returns true if the database has no packages in it, otherwise it returns false.
//
// Deprecated: use struct method
func IsEmpty(ctx context.Context) bool {
return GetInstance(ctx).IsEmpty(ctx)
}
// InsertPackage adds a package to the database
//
// Deprecated: use struct method
func InsertPackage(ctx context.Context, pkg Package) error {
return GetInstance(ctx).InsertPackage(ctx, pkg)
}
// GetPkgs returns a result containing packages that match the where conditions
//
// Deprecated: use struct method
func GetPkgs(ctx context.Context, where string, args ...any) (*sqlx.Rows, error) {
return GetInstance(ctx).GetPkgs(ctx, where, args...)
}
// GetPkg returns a single package that matches the where conditions
//
// Deprecated: use struct method
func GetPkg(ctx context.Context, where string, args ...any) (*Package, error) {
return GetInstance(ctx).GetPkg(ctx, where, args...)
}
// DeletePkgs deletes all packages matching the where conditions
//
// Deprecated: use struct method
func DeletePkgs(ctx context.Context, where string, args ...any) error {
return GetInstance(ctx).DeletePkgs(ctx, where, args...)
}
// =======================
// FOR LEGACY ONLY
// =======================
var (
dbOnce sync.Once
database *Database
)
// Deprecated: For legacy only
func GetInstance(ctx context.Context) *Database {
dbOnce.Do(func() {
cfg := config.GetInstance(ctx)
database = New(cfg)
err := database.Init(ctx)
if err != nil {
slog.Error(gotext.Get("Error opening database"), "err", err)
os.Exit(1)
}
})
return database
}

View File

@ -32,14 +32,6 @@ import (
"gitea.plemya-x.ru/Plemya-x/ALR/internal/dlcache"
)
func init() {
dir, err := os.MkdirTemp("/tmp", "alr-dlcache-test.*")
if err != nil {
panic(err)
}
config.GetPaths(context.Background()).RepoDir = dir
}
type TestALRConfig struct {
CacheDir string
}

View File

@ -41,7 +41,7 @@ func init() {
b2 := lipgloss.RoundedBorder()
b2.Left = "\u2524"
infoStyle = titleStyle.Copy().BorderStyle(b2)
infoStyle = titleStyle.BorderStyle(b2)
}
type Pager struct {

View File

@ -22,10 +22,11 @@ package handlers
import (
"context"
"io"
"io/fs"
"os"
)
func NopReadDir(context.Context, string) ([]os.FileInfo, error) {
func NopReadDir(context.Context, string) ([]fs.DirEntry, error) {
return nil, os.ErrNotExist
}

View File

@ -31,12 +31,12 @@ import (
"mvdan.cc/sh/v3/interp"
)
func RestrictedReadDir(allowedPrefixes ...string) interp.ReadDirHandlerFunc {
return func(ctx context.Context, s string) ([]fs.FileInfo, error) {
func RestrictedReadDir(allowedPrefixes ...string) interp.ReadDirHandlerFunc2 {
return func(ctx context.Context, s string) ([]fs.DirEntry, error) {
path := filepath.Clean(s)
for _, allowedPrefix := range allowedPrefixes {
if strings.HasPrefix(path, allowedPrefix) {
return interp.DefaultReadDirHandler()(ctx, s)
return interp.DefaultReadDirHandler2()(ctx, s)
}
}

View File

@ -31,7 +31,7 @@ msgid ""
msgstr ""
#: build.go:75
msgid "Error db init"
msgid "Error initialization database"
msgstr ""
#: build.go:105
@ -66,27 +66,27 @@ msgstr ""
msgid "Attempt to fix problems with ALR"
msgstr ""
#: fix.go:44
#: fix.go:43
msgid "Removing cache directory"
msgstr ""
#: fix.go:48
#: fix.go:47
msgid "Unable to remove cache directory"
msgstr ""
#: fix.go:52
#: fix.go:51
msgid "Rebuilding cache"
msgstr ""
#: fix.go:56
#: fix.go:55
msgid "Unable to create new cache directory"
msgstr ""
#: fix.go:62
#: fix.go:69
msgid "Error pulling repos"
msgstr ""
#: fix.go:66
#: fix.go:73
msgid "Done"
msgstr ""
@ -114,35 +114,39 @@ msgstr ""
msgid "No such helper command"
msgstr ""
#: info.go:42
#: info.go:43
msgid "Print information about a package"
msgstr ""
#: info.go:47
#: info.go:48
msgid "Show all information, not just for the current distro"
msgstr ""
#: info.go:57
msgid "Error initialization database"
#: info.go:63
msgid "Error getting packages"
msgstr ""
#: info.go:64
#: info.go:72
msgid "Error iterating over packages"
msgstr ""
#: info.go:93
msgid "Command info expected at least 1 argument, got %d"
msgstr ""
#: info.go:78
#: info.go:107
msgid "Error finding packages"
msgstr ""
#: info.go:94
#: info.go:129
msgid "Error parsing os-release file"
msgstr ""
#: info.go:103
#: info.go:138
msgid "Error resolving overrides"
msgstr ""
#: info.go:112 info.go:118
#: info.go:147 info.go:153
msgid "Error encoding script variables"
msgstr ""
@ -154,14 +158,6 @@ msgstr ""
msgid "Command install expected at least 1 argument, got %d"
msgstr ""
#: install.go:124
msgid "Error getting packages"
msgstr ""
#: install.go:133
msgid "Error iterating over packages"
msgstr ""
#: install.go:146
msgid "Remove an installed package"
msgstr ""
@ -234,10 +230,6 @@ msgstr ""
msgid "Unable to create package cache directory"
msgstr ""
#: internal/config/lang.go:49
msgid "Error parsing system language"
msgstr ""
#: internal/db/db.go:133
msgid "Database version mismatch; resetting"
msgstr ""
@ -247,10 +239,6 @@ msgid ""
"Database version does not exist. Run alr fix if something isn't working."
msgstr ""
#: internal/db/db_legacy.go:101
msgid "Error opening database"
msgstr ""
#: internal/dl/dl.go:170
msgid "Source can be updated, updating if required"
msgstr ""
@ -287,15 +275,15 @@ msgstr ""
msgid "Error listing installed packages"
msgstr ""
#: main.go:45
#: main.go:44
msgid "Print the current ALR version and exit"
msgstr ""
#: main.go:61
#: main.go:60
msgid "Arguments to be passed on to the package manager"
msgstr ""
#: main.go:67
#: main.go:66
msgid "Enable interactive questions and prompts"
msgstr ""
@ -305,7 +293,7 @@ msgid ""
"system"
msgstr ""
#: main.go:125
#: main.go:123
msgid "Error while running app"
msgstr ""
@ -329,49 +317,49 @@ msgstr ""
msgid "Compressing package"
msgstr ""
#: pkg/build/build.go:419
#: pkg/build/build.go:421
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
msgstr ""
#: pkg/build/build.go:433
#: pkg/build/build.go:435
msgid "This package is already installed"
msgstr ""
#: pkg/build/build.go:457
#: pkg/build/build.go:459
msgid "Installing build dependencies"
msgstr ""
#: pkg/build/build.go:498
#: pkg/build/build.go:500
msgid "Installing dependencies"
msgstr ""
#: pkg/build/build.go:533
#: pkg/build/build.go:535
msgid "The checksums array must be the same length as sources"
msgstr ""
#: pkg/build/build.go:584
#: pkg/build/build.go:586
msgid "Would you like to remove the build dependencies?"
msgstr ""
#: pkg/build/build.go:647
#: pkg/build/build.go:649
msgid "Executing prepare()"
msgstr ""
#: pkg/build/build.go:657
#: pkg/build/build.go:659
msgid "Executing build()"
msgstr ""
#: pkg/build/build.go:687 pkg/build/build.go:707
#: pkg/build/build.go:689 pkg/build/build.go:709
msgid "Executing %s()"
msgstr ""
#: pkg/build/build.go:766
#: pkg/build/build.go:768
msgid "Error installing native packages"
msgstr ""
#: pkg/build/build.go:790
#: pkg/build/build.go:792
msgid "Error installing package"
msgstr ""
@ -425,35 +413,35 @@ msgstr ""
msgid "URL of the new repo"
msgstr ""
#: repo.go:79 repo.go:136
#: repo.go:82 repo.go:147
msgid "Error opening config file"
msgstr ""
#: repo.go:85 repo.go:142
#: repo.go:88 repo.go:153
msgid "Error encoding config"
msgstr ""
#: repo.go:103
#: repo.go:113
msgid "Remove an existing repository"
msgstr ""
#: repo.go:110
#: repo.go:120
msgid "Name of the repo to be deleted"
msgstr ""
#: repo.go:128
#: repo.go:139
msgid "Repo does not exist"
msgstr ""
#: repo.go:148
#: repo.go:159
msgid "Error removing repo directory"
msgstr ""
#: repo.go:154
#: repo.go:170
msgid "Error removing packages from database"
msgstr ""
#: repo.go:166
#: repo.go:182
msgid "Pull all repositories that have changed"
msgstr ""
@ -481,19 +469,11 @@ msgstr ""
msgid "Format output using a Go template"
msgstr ""
#: search.go:94
msgid "At least one search parameter is required"
msgstr ""
#: search.go:100
msgid "Error db search"
msgstr ""
#: search.go:109
#: search.go:82 search.go:99
msgid "Error parsing format template"
msgstr ""
#: search.go:124
#: search.go:107
msgid "Error executing template"
msgstr ""

View File

@ -38,8 +38,8 @@ msgid ""
msgstr "Создайте пакет с нуля, даже если уже имеется готовый пакет"
#: build.go:75
msgid "Error db init"
msgstr ""
msgid "Error initialization database"
msgstr "Ошибка инициализации базы данных"
#: build.go:105
msgid "Package not found"
@ -74,27 +74,27 @@ msgstr "Ошибка при перемещении пакета"
msgid "Attempt to fix problems with ALR"
msgstr "Попытка устранить проблемы с ALR"
#: fix.go:44
#: fix.go:43
msgid "Removing cache directory"
msgstr "Удаление каталога кэша"
#: fix.go:48
#: fix.go:47
msgid "Unable to remove cache directory"
msgstr "Не удалось удалить каталог кэша"
#: fix.go:52
#: fix.go:51
msgid "Rebuilding cache"
msgstr "Восстановление кэша"
#: fix.go:56
#: fix.go:55
msgid "Unable to create new cache directory"
msgstr "Не удалось создать новый каталог кэша"
#: fix.go:62
#: fix.go:69
msgid "Error pulling repos"
msgstr "Ошибка при извлечении репозиториев"
#: fix.go:66
#: fix.go:73
msgid "Done"
msgstr "Сделано"
@ -122,35 +122,39 @@ msgstr "Каталог, в который будут устанавливать
msgid "No such helper command"
msgstr "Такой вспомогательной команды нет"
#: info.go:42
#: info.go:43
msgid "Print information about a package"
msgstr "Отобразить информацию о пакете"
#: info.go:47
#: info.go:48
msgid "Show all information, not just for the current distro"
msgstr "Показывать всю информацию, не только для текущего дистрибутива"
#: info.go:57
msgid "Error initialization database"
msgstr "Ошибка инициализации базы данных"
#: info.go:63
msgid "Error getting packages"
msgstr "Ошибка при получении пакетов"
#: info.go:64
#: info.go:72
msgid "Error iterating over packages"
msgstr "Ошибка при переборе пакетов"
#: info.go:93
msgid "Command info expected at least 1 argument, got %d"
msgstr "Для команды info ожидался хотя бы 1 аргумент, получено %d"
#: info.go:78
#: info.go:107
msgid "Error finding packages"
msgstr "Ошибка при поиске пакетов"
#: info.go:94
#: info.go:129
msgid "Error parsing os-release file"
msgstr "Ошибка при разборе файла выпуска операционной системы"
#: info.go:103
#: info.go:138
msgid "Error resolving overrides"
msgstr "Ошибка устранения переорпеделений"
#: info.go:112 info.go:118
#: info.go:147 info.go:153
msgid "Error encoding script variables"
msgstr "Ошибка кодирования переменных скрита"
@ -162,14 +166,6 @@ msgstr "Установить новый пакет"
msgid "Command install expected at least 1 argument, got %d"
msgstr "Для команды install ожидался хотя бы 1 аргумент, получено %d"
#: install.go:124
msgid "Error getting packages"
msgstr "Ошибка при получении пакетов"
#: install.go:133
msgid "Error iterating over packages"
msgstr "Ошибка при переборе пакетов"
#: install.go:146
msgid "Remove an installed package"
msgstr "Удалить установленный пакет"
@ -246,10 +242,6 @@ msgstr "Не удалось создать каталог кэша репози
msgid "Unable to create package cache directory"
msgstr "Не удалось создать каталог кэша пакетов"
#: internal/config/lang.go:49
msgid "Error parsing system language"
msgstr "Ошибка при парсинге языка системы"
#: internal/db/db.go:133
msgid "Database version mismatch; resetting"
msgstr "Несоответствие версий базы данных; сброс настроек"
@ -260,10 +252,6 @@ msgid ""
msgstr ""
"Версия базы данных не существует. Запустите alr fix, если что-то не работает."
#: internal/db/db_legacy.go:101
msgid "Error opening database"
msgstr "Ошибка при открытии базы данных"
#: internal/dl/dl.go:170
msgid "Source can be updated, updating if required"
msgstr "Исходный код можно обновлять, обновляя при необходимости"
@ -300,15 +288,15 @@ msgstr "Список пакетов репозитория ALR"
msgid "Error listing installed packages"
msgstr "Ошибка при составлении списка установленных пакетов"
#: main.go:45
#: main.go:44
msgid "Print the current ALR version and exit"
msgstr "Показать текущую версию ALR и выйти"
#: main.go:61
#: main.go:60
msgid "Arguments to be passed on to the package manager"
msgstr "Аргументы, которые будут переданы менеджеру пакетов"
#: main.go:67
#: main.go:66
msgid "Enable interactive questions and prompts"
msgstr "Включение интерактивных вопросов и запросов"
@ -320,7 +308,7 @@ msgstr ""
"Запуск ALR от имени root запрещён, так как это может привести к "
"катастрофическому повреждению вашей системы"
#: main.go:125
#: main.go:123
msgid "Error while running app"
msgstr "Ошибка при запуске приложения"
@ -344,7 +332,7 @@ msgstr "Сборка метаданных пакета"
msgid "Compressing package"
msgstr "Сжатие пакета"
#: pkg/build/build.go:419
#: pkg/build/build.go:421
msgid ""
"Your system's CPU architecture doesn't match this package. Do you want to "
"build anyway?"
@ -352,44 +340,44 @@ msgstr ""
"Архитектура процессора вашей системы не соответствует этому пакету. Вы все "
"равно хотите выполнить сборку?"
#: pkg/build/build.go:433
#: pkg/build/build.go:435
msgid "This package is already installed"
msgstr "Этот пакет уже установлен"
#: pkg/build/build.go:457
#: pkg/build/build.go:459
msgid "Installing build dependencies"
msgstr "Установка зависимостей сборки"
#: pkg/build/build.go:498
#: pkg/build/build.go:500
msgid "Installing dependencies"
msgstr "Установка зависимостей"
#: pkg/build/build.go:533
#: pkg/build/build.go:535
msgid "The checksums array must be the same length as sources"
msgstr "Массив контрольных сумм должен быть той же длины, что и источники"
#: pkg/build/build.go:584
#: pkg/build/build.go:586
msgid "Would you like to remove the build dependencies?"
msgstr "Хотели бы вы удалить зависимости сборки?"
#: pkg/build/build.go:647
#: pkg/build/build.go:649
msgid "Executing prepare()"
msgstr "Исполнение prepare()"
#: pkg/build/build.go:657
#: pkg/build/build.go:659
msgid "Executing build()"
msgstr "Исполнение build()"
#: pkg/build/build.go:687 pkg/build/build.go:707
#: pkg/build/build.go:689 pkg/build/build.go:709
#, fuzzy
msgid "Executing %s()"
msgstr "Исполнение files()"
#: pkg/build/build.go:766
#: pkg/build/build.go:768
msgid "Error installing native packages"
msgstr "Ошибка при установке нативных пакетов"
#: pkg/build/build.go:790
#: pkg/build/build.go:792
msgid "Error installing package"
msgstr "Ошибка при установке пакета"
@ -447,35 +435,35 @@ msgstr "Название нового репозитория"
msgid "URL of the new repo"
msgstr "URL-адрес нового репозитория"
#: repo.go:79 repo.go:136
#: repo.go:82 repo.go:147
msgid "Error opening config file"
msgstr "Ошибка при открытии конфигурационного файла"
#: repo.go:85 repo.go:142
#: repo.go:88 repo.go:153
msgid "Error encoding config"
msgstr "Ошибка при кодировании конфигурации"
#: repo.go:103
#: repo.go:113
msgid "Remove an existing repository"
msgstr "Удалить существующий репозиторий"
#: repo.go:110
#: repo.go:120
msgid "Name of the repo to be deleted"
msgstr "Название репозитория удалён"
#: repo.go:128
#: repo.go:139
msgid "Repo does not exist"
msgstr "Репозитория не существует"
#: repo.go:148
#: repo.go:159
msgid "Error removing repo directory"
msgstr "Ошибка при удалении каталога репозитория"
#: repo.go:154
#: repo.go:170
msgid "Error removing packages from database"
msgstr "Ошибка при удалении пакетов из базы данных"
#: repo.go:166
#: repo.go:182
msgid "Pull all repositories that have changed"
msgstr "Скачать все изменённые репозитории"
@ -504,20 +492,12 @@ msgstr ""
msgid "Format output using a Go template"
msgstr ""
#: search.go:94
msgid "At least one search parameter is required"
msgstr ""
#: search.go:100
msgid "Error db search"
msgstr ""
#: search.go:109
#: search.go:82 search.go:99
#, fuzzy
msgid "Error parsing format template"
msgstr "Ошибка при разборе файла выпуска операционной системы"
#: search.go:124
#: search.go:107
#, fuzzy
msgid "Error executing template"
msgstr "Ошибка при получении пакетов"
@ -534,6 +514,12 @@ msgstr "Ошибка при проверке обновлений"
msgid "There is nothing to do."
msgstr "Здесь нечего делать."
#~ msgid "Error parsing system language"
#~ msgstr "Ошибка при парсинге языка системы"
#~ msgid "Error opening database"
#~ msgstr "Ошибка при открытии базы данных"
#~ msgid "Executing version()"
#~ msgstr "Исполнение версия()"