28 Commits

Author SHA1 Message Date
46e2d3166f Add version command
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-22 12:54:03 -08:00
3437df8676 Add a way to check the minimum version supported by a LURE repo 2022-11-22 12:51:45 -08:00
3361358b3c Add documentation for helper commands
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-22 12:26:06 -08:00
3ca052fea7 Use slice for list of distros excluded from /usr/lib64
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-22 11:44:00 -08:00
001e33dd2f Use /usr/lib for libraries on Arch, Alpine, and Void linux
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-21 22:16:06 -08:00
f30f4c7081 Add install-library helper command
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-21 21:45:18 -08:00
5bc81e3a30 Add DISTRO_ID_LIKE environment variable
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-21 21:03:56 -08:00
d941ce231e Install manuals in the proper locations
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-21 16:34:47 -08:00
e22bc0f10c Add install-completion helper command
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-21 15:20:22 -08:00
8ff903b68f Change name of install-bin to install-binary
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 20:56:34 -08:00
3bb7fe3690 Add initial helper functions (#39)
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 20:52:38 -08:00
26d139c34e Add environment variables to table of contents
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 14:17:20 -08:00
8ceb61de9a Run version function before anything else and set the version variable to its output
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 14:15:31 -08:00
24c807a941 Resolve ARM variant in the value of the environment variable
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 13:57:59 -08:00
da7830d0e3 Make the architecture match on all machines
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 13:54:49 -08:00
98a3b26a27 Add documentation for environment variables
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 13:50:03 -08:00
da630f648d Expose distro version ID as an environment variable
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 21:45:45 +00:00
c489f4864e Parse distro version ID instead of build ID
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-20 21:43:58 +00:00
320342cfb4 Switch badge to self-hosted CI
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-18 08:20:46 +00:00
45ad9fbe39 Add woodpecker CI config
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-11-18 08:18:02 +00:00
3f2ec8ebd3 Remove epoch from reported version if it is zero 2022-11-14 14:59:16 -08:00
2c2a27c9f7 Fix maintainer spelling in goreleaser config 2022-11-14 14:29:01 -08:00
05a1ecea64 Add provides and conflicts to goreleaser config 2022-11-14 14:25:19 -08:00
d32437e8b2 Show repo name when prompting to select package 2022-11-14 14:04:46 -08:00
8f95ff4676 Actually pass the repodir parameter this time 2022-11-13 19:30:23 -08:00
7442da7105 Add repodir variable 2022-11-13 19:08:58 -08:00
07e41849e9 Remove installed build dependencies from list 2022-11-13 18:49:55 -08:00
27fb08d5ba Make SKIP case-insensitive 2022-11-06 14:48:31 -08:00
18 changed files with 607 additions and 52 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
/lure /lure
/dist/ /dist/
/version.txt

View File

@@ -1,6 +1,7 @@
before: before:
hooks: hooks:
- go mod tidy - go mod tidy
- go generate
builds: builds:
- id: lure - id: lure
env: env:
@@ -29,18 +30,22 @@ nfpms:
amd64: x86_64 amd64: x86_64
arm64: aarch64 arm64: aarch64
homepage: 'https://gitea.arsenm.dev/Arsen6331/lure' homepage: 'https://gitea.arsenm.dev/Arsen6331/lure'
maintainer: 'Arsen Musyaelyan <arsen@arsenm.dev>' maintainer: 'Arsen Musayelyan <arsen@arsenm.dev>'
license: GPLv3 license: GPLv3
formats: formats:
- apk - apk
- deb - deb
- rpm - rpm
provides:
- lure
conflicts:
- lure
aurs: aurs:
- name: lure-bin - name: lure-bin
homepage: 'https://gitea.arsenm.dev/Arsen6331/lure' homepage: 'https://gitea.arsenm.dev/Arsen6331/lure'
description: "Linux User REpository" description: "Linux User REpository"
maintainers: maintainers:
- 'Arsen Musyaelyan <arsen@arsenm.dev>' - 'Arsen Musayelyan <arsen@arsenm.dev>'
license: GPLv3 license: GPLv3
private_key: '{{ .Env.AUR_KEY }}' private_key: '{{ .Env.AUR_KEY }}'
git_url: 'ssh://aur@aur.archlinux.org/lure-bin.git' git_url: 'ssh://aur@aur.archlinux.org/lure-bin.git'

8
.woodpecker.yml Normal file
View File

@@ -0,0 +1,8 @@
pipeline:
release:
image: goreleaser/goreleaser
commands:
- goreleaser release
secrets: [ gitea_token, aur_key ]
when:
event: tag

View File

@@ -1,4 +1,4 @@
lure: lure: version.txt
go build go build
clean: clean:
@@ -10,4 +10,7 @@ install: lure
uninstall: uninstall:
rm -f /usr/local/bin/lure rm -f /usr/local/bin/lure
version.txt:
go generate
.PHONY: install clean uninstall .PHONY: install clean uninstall

View File

@@ -1,7 +1,7 @@
# LURE (Linux User REpository) # LURE (Linux User REpository)
[![Go Report Card](https://goreportcard.com/badge/go.arsenm.dev/lure)](https://goreportcard.com/report/go.arsenm.dev/lure) [![Go Report Card](https://goreportcard.com/badge/go.arsenm.dev/lure)](https://goreportcard.com/report/go.arsenm.dev/lure)
[![Build status](https://ci.appveyor.com/api/projects/status/7anjwy7xcp4dxfu6?svg=true)](https://ci.appveyor.com/project/moussaelianarsen/lure) [![status-badge](https://ci.arsenm.dev/api/badges/Arsen6331/lure/status.svg)](https://ci.arsenm.dev/Arsen6331/lure)
[![lure-bin AUR package](https://img.shields.io/aur/version/lure-bin?label=lure-bin&logo=archlinux)](https://aur.archlinux.org/packages/lure-bin/) [![lure-bin AUR package](https://img.shields.io/aur/version/lure-bin?label=lure-bin&logo=archlinux)](https://aur.archlinux.org/packages/lure-bin/)
LURE is intended to bring the AUR to all distros. It is currently in an ***alpha*** state and may not be stable. It can download a repository, build packages in it using a bash script similar to [PKGBUILD](https://wiki.archlinux.org/title/PKGBUILD), and then install them using your system package manager. LURE is intended to bring the AUR to all distros. It is currently in an ***alpha*** state and may not be stable. It can download a repository, build packages in it using a bash script similar to [PKGBUILD](https://wiki.archlinux.org/title/PKGBUILD), and then install them using your system package manager.

103
build.go
View File

@@ -122,6 +122,9 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
var distroChanged bool var distroChanged bool
if distID, ok := os.LookupEnv("LURE_DISTRO"); ok { if distID, ok := os.LookupEnv("LURE_DISTRO"); ok {
info.ID = distID info.ID = distID
// Since the distro was overwritten, we don't know what the
// like distros are, so set to nil
info.Like = nil
distroChanged = true distroChanged = true
} }
@@ -142,6 +145,7 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
runner, err := interp.New( runner, err := interp.New(
interp.Env(expand.ListEnviron(env...)), interp.Env(expand.ListEnviron(env...)),
interp.StdIO(os.Stdin, os.Stdout, os.Stderr), interp.StdIO(os.Stdin, os.Stdout, os.Stderr),
interp.ExecHandler(helpers.ExecHandler),
) )
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@@ -160,6 +164,30 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
dec.LikeDistros = false dec.LikeDistros = false
} }
fn, ok := dec.GetFunc("version")
if ok {
log.Info("Executing version()").Send()
buf := &bytes.Buffer{}
err = fn(
ctx,
interp.Dir(filepath.Dir(script)),
interp.StdIO(os.Stdin, buf, os.Stderr),
)
if err != nil {
return nil, nil, err
}
newVer := strings.TrimSpace(buf.String())
err = setVersion(ctx, runner, newVer)
if err != nil {
return nil, nil, err
}
log.Info("Updating version").Str("new", newVer).Send()
}
var vars BuildVars var vars BuildVars
err = dec.DecodeVars(&vars) err = dec.DecodeVars(&vars)
if err != nil { if err != nil {
@@ -201,9 +229,21 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
return nil, nil, err return nil, nil, err
} }
if len(vars.BuildDepends) > 0 { installed, err := mgr.ListInstalled(nil)
if err != nil {
return nil, nil, err
}
var buildDeps []string
for _, pkgName := range vars.BuildDepends {
if _, ok := installed[pkgName]; !ok {
buildDeps = append(buildDeps, pkgName)
}
}
if len(buildDeps) > 0 {
log.Info("Installing build dependencies").Send() log.Info("Installing build dependencies").Send()
installPkgs(ctx, vars.BuildDepends, mgr, false) installPkgs(ctx, buildDeps, mgr, false)
} }
var builtDeps, builtNames, repoDeps []string var builtDeps, builtNames, repoDeps []string
@@ -230,12 +270,14 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
return nil, nil, err return nil, nil, err
} }
err = setDirVars(ctx, runner, srcdir, pkgdir) repodir := filepath.Dir(script)
err = setDirVars(ctx, runner, srcdir, pkgdir, repodir)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
fn, ok := dec.GetFunc("prepare") fn, ok = dec.GetFunc("prepare")
if ok { if ok {
log.Info("Executing prepare()").Send() log.Info("Executing prepare()").Send()
@@ -245,26 +287,6 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
} }
} }
fn, ok = dec.GetFunc("version")
if ok {
log.Info("Executing version()").Send()
buf := &bytes.Buffer{}
err = fn(
ctx,
interp.Dir(srcdir),
interp.StdIO(os.Stdin, buf, os.Stderr),
)
if err != nil {
return nil, nil, err
}
vars.Version = strings.TrimSpace(buf.String())
log.Info("Updating version").Str("new", vars.Version).Send()
}
fn, ok = dec.GetFunc("build") fn, ok = dec.GetFunc("build")
if ok { if ok {
log.Info("Executing build()").Send() log.Info("Executing build()").Send()
@@ -418,7 +440,7 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
return nil, nil, err return nil, nil, err
} }
if len(vars.BuildDepends) > 0 { if len(buildDeps) > 0 {
var removeBuildDeps bool var removeBuildDeps bool
err = survey.AskOne(&survey.Confirm{ err = survey.AskOne(&survey.Confirm{
Message: "Would you like to remove build dependencies?", Message: "Would you like to remove build dependencies?",
@@ -433,7 +455,7 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
AsRoot: true, AsRoot: true,
NoConfirm: true, NoConfirm: true,
}, },
vars.BuildDepends..., buildDeps...,
) )
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@@ -448,14 +470,21 @@ func buildPackage(ctx context.Context, script string, mgr manager.Manager) ([]st
func genBuildEnv(info *distro.OSRelease) []string { func genBuildEnv(info *distro.OSRelease) []string {
env := os.Environ() env := os.Environ()
arch := runtime.GOARCH
if arch == "arm" {
arch = cpu.ARMVariant()
}
env = append( env = append(
env, env,
"DISTRO_NAME="+info.Name, "DISTRO_NAME="+info.Name,
"DISTRO_PRETTY_NAME="+info.PrettyName, "DISTRO_PRETTY_NAME="+info.PrettyName,
"DISTRO_ID="+info.ID, "DISTRO_ID="+info.ID,
"DISTRO_BUILD_ID="+info.BuildID, "DISTRO_VERSION_ID="+info.VersionID,
"DISTRO_ID_LIKE="+strings.Join(info.Like, " "),
"ARCH="+runtime.GOARCH, "ARCH="+arch,
"NCPU="+strconv.Itoa(runtime.NumCPU()), "NCPU="+strconv.Itoa(runtime.NumCPU()),
) )
@@ -474,7 +503,7 @@ func getSources(ctx context.Context, srcdir string, bv *BuildVars) error {
EncloseGit: true, EncloseGit: true,
} }
if bv.Checksums[i] != "SKIP" { if !strings.EqualFold(bv.Checksums[i], "SKIP") {
checksum, err := hex.DecodeString(bv.Checksums[i]) checksum, err := hex.DecodeString(bv.Checksums[i])
if err != nil { if err != nil {
return err return err
@@ -493,8 +522,8 @@ func getSources(ctx context.Context, srcdir string, bv *BuildVars) error {
// setDirVars sets srcdir and pkgdir. It's a very hacky way of doing so, // setDirVars sets srcdir and pkgdir. It's a very hacky way of doing so,
// but setting the runner's Env and Vars fields doesn't seem to work. // but setting the runner's Env and Vars fields doesn't seem to work.
func setDirVars(ctx context.Context, runner *interp.Runner, srcdir, pkgdir string) error { func setDirVars(ctx context.Context, runner *interp.Runner, srcdir, pkgdir, repodir string) error {
cmd := "srcdir='" + srcdir + "'\npkgdir='" + pkgdir + "'\n" cmd := "srcdir='" + srcdir + "'\npkgdir='" + pkgdir + "'\nrepodir='" + repodir + "'\n"
fl, err := syntax.NewParser().Parse(strings.NewReader(cmd), "vars") fl, err := syntax.NewParser().Parse(strings.NewReader(cmd), "vars")
if err != nil { if err != nil {
return err return err
@@ -580,6 +609,10 @@ func getBuildVars(ctx context.Context, script string, info *distro.OSRelease) (*
} }
func archMatches(architectures []string) bool { func archMatches(architectures []string) bool {
if slices.Contains(architectures, "all") {
return true
}
arch := runtime.GOARCH arch := runtime.GOARCH
if arch == "arm" { if arch == "arm" {
@@ -593,6 +626,14 @@ func archMatches(architectures []string) bool {
return slices.Contains(architectures, arch) return slices.Contains(architectures, arch)
} }
func setVersion(ctx context.Context, r *interp.Runner, to string) error {
fl, err := syntax.NewParser().Parse(strings.NewReader("version='"+to+"'"), "")
if err != nil {
return err
}
return r.Run(ctx, fl)
}
func uniq(ss ...*[]string) { func uniq(ss ...*[]string) {
for _, s := range ss { for _, s := range ss {
slices.Sort(*s) slices.Sort(*s)

View File

@@ -37,7 +37,7 @@ type OSRelease struct {
PrettyName string PrettyName string
ID string ID string
Like []string Like []string
BuildID string VersionID string
ANSIColor string ANSIColor string
HomeURL string HomeURL string
DocumentationURL string DocumentationURL string
@@ -86,7 +86,7 @@ func ParseOSRelease(ctx context.Context) (*OSRelease, error) {
Name: runner.Vars["NAME"].Str, Name: runner.Vars["NAME"].Str,
PrettyName: runner.Vars["PRETTY_NAME"].Str, PrettyName: runner.Vars["PRETTY_NAME"].Str,
ID: runner.Vars["ID"].Str, ID: runner.Vars["ID"].Str,
BuildID: runner.Vars["BUILD_ID"].Str, VersionID: runner.Vars["VERSION_ID"].Str,
ANSIColor: runner.Vars["ANSI_COLOR"].Str, ANSIColor: runner.Vars["ANSI_COLOR"].Str,
HomeURL: runner.Vars["HOME_URL"].Str, HomeURL: runner.Vars["HOME_URL"].Str,
DocumentationURL: runner.Vars["DOCUMENTATION_URL"].Str, DocumentationURL: runner.Vars["DOCUMENTATION_URL"].Str,

View File

@@ -31,6 +31,23 @@ LURE uses build scripts similar to the AUR's PKGBUILDs. This is the documentatio
- [version](#version-1) - [version](#version-1)
- [build](#build) - [build](#build)
- [package](#package) - [package](#package)
- [Environment Variables](#environment-variables)
- [DISTRO_NAME](#distro_name)
- [DISTRO_PRETTY_NAME](#distro_pretty_name)
- [DISTRO_ID](#distro_id)
- [DISTRO_VERSION_ID](#distro_version_id)
- [ARCH](#arch)
- [NCPU](#ncpu)
- [Helper Commands](#helper-commands)
- [install-binary](#install-binary)
- [install-systemd](#install-systemd)
- [install-systemd-user](#install-systemd-user)
- [install-config](#install-config)
- [install-license](#install-license)
- [install-completion](#install-completion)
- [install-manual](#install-manual)
- [install-desktop](#install-desktop)
- [install-library](#install-library)
--- ---
@@ -223,17 +240,13 @@ The rest of the scripts are available in all packages.
## Functions ## Functions
Any variables marked with `(*)` are required This section documents user-defined functions that can be added to build scripts. Any functions marked with `(*)` are required.
All functions start in the `$srcdir` directory All functions except for `version()` are executed in the `$srcdir` directory
### prepare
The `prepare()` function runs first. It is meant to prepare the sources for building and packaging. This is the function in which patches should be applied, for example, by the `patch` command, and where tools like `go generate` should be executed.
### version ### version
The `version()` function updates the `version` variable. This allows for automatically deriving the version from sources. This is most useful for git packages, which usually don't need to be changed, so their `version` variable stays the same. The `version()` function is the first to run. It updates the `version` variable. This allows for automatically deriving the version from sources. This is most useful for git packages, which usually don't need to be changed, so their `version` variable stays the same.
An example of using this for git: An example of using this for git:
@@ -246,6 +259,12 @@ version() {
The AUR equivalent is the [`pkgver()` function](https://wiki.archlinux.org/title/VCS_package_guidelines#The_pkgver()_function) The AUR equivalent is the [`pkgver()` function](https://wiki.archlinux.org/title/VCS_package_guidelines#The_pkgver()_function)
This function does not run in `$srcdir` because it is executed before the source directory is even created. Instead, it runs in `$repodir`.
### prepare
The `prepare()` function is meant to prepare the sources for building and packaging. This is the function in which patches should be applied, for example, by the `patch` command, and where tools like `go generate` should be executed.
### build ### build
The `build()` function is where the package is actually built. Use the same commands that would be used to manually compile the software. Often, this function is just one line: The `build()` function is where the package is actually built. Use the same commands that would be used to manually compile the software. Often, this function is just one line:
@@ -268,3 +287,184 @@ package() {
install -Dm644 bin.cfg ${pkgdir}/etc/bin.cfg install -Dm644 bin.cfg ${pkgdir}/etc/bin.cfg
} }
``` ```
---
## Environment Variables
LURE exposes several values as environment variables for use in build scripts.
### DISTRO_NAME
The `DISTRO_NAME` variable is the name of the distro as defined in its `os-release` file.
For example, it's set to `Fedora Linux` in a Fedora 36 docker image
### DISTRO_PRETTY_NAME
The `DISTRO_PRETTY_NAME` variable is the "pretty" name of the distro as defined in its `os-release` file.
For example, it's set to `Fedora Linux 36 (Container Image)` in a Fedora 36 docker image
### DISTRO_ID
The `DISTRO_ID` variable is the identifier of the distro as defined in its `os-release` file. This is the same as what LURE uses for overrides.
For example, it's set to `fedora` in a Fedora 36 docker image
### DISTRO_ID_LIKE
The `DISTRO_ID_LIKE` variable contains identifiers of similar distros to the one running, separated by spaces.
For example, it's set to `opensuse suse` in an OpenSUSE Tumbleweed docker image and `rhel fedora` in a CentOS 8 docker image.
### DISTRO_VERSION_ID
The `DISTRO_VERSION_ID` variable is the version identifier of the distro as defined in its `os-release` file.
For example, it's set to `36` in a Fedora 36 docker image and `11` in a Debian Bullseye docker image
### ARCH
The `ARCH` variable is the architecture of the machine running the script. It uses the same naming convention as the values in the `architectures` array
### NCPU
The `NCPU` variable is the amount of CPUs available on the machine running the script. It will be set to `8` on a quad core machine with hyperthreading, for example.
---
## Helper Commands
LURE provides various commands to help packagers create proper cross-distro packages. These commands should be used wherever possible instead of doing the tasks manually.
### install-binary
`install-binary` accepts 1-2 arguments. The first argument is the binary you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-binary ./itd
install-binary ./itd itd-2
```
### install-systemd
`install-systemd` installs regular systemd system services (see `install-systemd-user` for user services)
It accepts 1-2 arguments. The first argument is the service you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-systemd ./syncthing@.service
install-systemd-user ./syncthing@.service sync-thing@.service
```
### install-systemd-user
`install-systemd-user` installs systemd user services (services like `itd` meant to be started with `--user`).
It accepts 1-2 arguments. The first argument is the service you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-systemd-user ./itd.service
install-systemd-user ./itd.service infinitime-daemon.service
```
### install-config
`install-config` installs configuration files into the `/etc` directory
It accepts 1-2 arguments. The first argument is the config you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-config ./itd.toml
install-config ./itd.example.toml itd.toml
```
### install-license
`install-license` installs a license file
It accepts 1-2 arguments. The first argument is the config you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-license ./LICENSE itd/LICENSE
```
### install-completion
`install-completion` installs shell completions
It currently supports `bash`, `zsh`, and `fish`
Completions are read from stdin, so they can either be piped in or retrieved from files
Two arguments are required for this function. The first one is the name of the shell and the second is the name of the completion.
Examples:
```bash
./k9s completion fish | install-completion fish k9s
install-completion bash k9s <./k9s/completions/k9s.fish
```
### install-manual
`install-manual` installs manpages. It accepts a single argument, which is the path to the manpage.
The install path will be determined based on the number at the end of the filename. If a number cannot be extracted, an error will be returned.
Examples:
```bash
install-manual ./man/strelaysrv.1
install-manual ./mdoc.7
```
### install-desktop
`install-desktop` installs desktop files for applications. It accepts 1-2 arguments. The first argument is the config you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-desktop ./${name}/share/admc.desktop
install-desktop ./${name}/share/admc.desktop admc-app.desktop
```
### install-library
`install-library` installs shared and static libraries to the correct location.
This is the most important helper as it contains logic to figure out where to install libraries based on the target distro and CPU architecture. It should almost always be used to install all libraries.
It accepts 1-2 arguments. The first argument is the config you'd like to install. The second is the filename that should be used.
If the filename argument is not provided, tha name of the input file will be used.
Examples:
```bash
install-library ./${name}/build/libadldap.so
```

View File

@@ -227,6 +227,11 @@ func extractFile(ctx context.Context, input io.Reader, hash hash.Hash, format ar
return err return err
} }
defer fr.Close() defer fr.Close()
fi, err := f.Stat()
if err != nil {
return err
}
fm := fi.Mode()
path := filepath.Join(opts.Destination, f.NameInArchive) path := filepath.Join(opts.Destination, f.NameInArchive)
@@ -241,7 +246,7 @@ func extractFile(ctx context.Context, input io.Reader, hash hash.Hash, format ar
return err return err
} }
} else { } else {
outFl, err := os.Create(path) outFl, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fm.Perm())
if err != nil { if err != nil {
return err return err
} }

212
helpers.go Normal file
View File

@@ -0,0 +1,212 @@
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"unsafe"
"go.arsenm.dev/lure/internal/shutils"
"golang.org/x/exp/slices"
"mvdan.cc/sh/v3/interp"
)
var (
ErrNoPipe = errors.New("command requires data to be piped in")
ErrNoDetectManNum = errors.New("manual number cannot be detected from the filename")
)
var helpers = shutils.ExecFuncs{
"install-binary": installHelperCmd("/usr/bin", 0o755),
"install-systemd-user": installHelperCmd("/usr/lib/systemd/user", 0o644),
"install-systemd": installHelperCmd("/usr/lib/systemd/system", 0o644),
"install-config": installHelperCmd("/etc", 0o644),
"install-license": installHelperCmd("/usr/share/licenses", 0o644),
"install-desktop": installHelperCmd("/usr/share/applications", 0o644),
"install-manual": installManualCmd,
"install-completion": installCompletionCmd,
"install-library": installLibraryCmd,
}
func installHelperCmd(prefix string, perms os.FileMode) shutils.ExecFunc {
return func(hc interp.HandlerContext, cmd string, args []string) error {
if len(args) < 1 {
return shutils.InsufficientArgsError(cmd, 1, len(args))
}
from := args[0]
to := ""
if len(args) > 1 {
to = filepath.Join(hc.Env.Get("pkgdir").Str, prefix, args[1])
} else {
to = filepath.Join(hc.Env.Get("pkgdir").Str, prefix, filepath.Base(from))
}
err := helperInstall(from, to, perms)
if err != nil {
return fmt.Errorf("%s: %w", cmd, err)
}
return nil
}
}
func installManualCmd(hc interp.HandlerContext, cmd string, args []string) error {
if len(args) < 1 {
return shutils.InsufficientArgsError(cmd, 1, len(args))
}
from := args[0]
number := filepath.Base(from)
// The man page may be compressed with gzip.
// If it is, the .gz extension must be removed to properly
// detect the number at the end of the filename.
number = strings.TrimSuffix(number, ".gz")
number = strings.TrimPrefix(filepath.Ext(number), ".")
// If number is not actually a number, return an error
if _, err := strconv.Atoi(number); err != nil {
return fmt.Errorf("install-manual: %w", ErrNoDetectManNum)
}
prefix := "/usr/share/man/man" + number
to := filepath.Join(hc.Env.Get("pkgdir").Str, prefix, filepath.Base(from))
return helperInstall(from, to, 0o644)
}
func installCompletionCmd(hc interp.HandlerContext, cmd string, args []string) error {
// If the command's stdin is the same as the system's,
// that means nothing was piped in. In this case, return an error.
if hc.Stdin == os.Stdin {
return fmt.Errorf("install-completion: %w", ErrNoPipe)
}
if len(args) < 2 {
return shutils.InsufficientArgsError(cmd, 2, len(args))
}
shell := args[0]
name := args[1]
var prefix string
switch shell {
case "bash":
prefix = "/usr/share/bash-completion/completion"
case "zsh":
prefix = "/usr/share/zsh/site-functions"
name = "_" + name
case "fish":
prefix = "/usr/share/fish/vendor_completions.d"
name += ".fish"
}
path := filepath.Join(hc.Env.Get("pkgdir").Str, prefix, name)
err := os.MkdirAll(filepath.Dir(path), 0o755)
if err != nil {
return err
}
dst, err := os.OpenFile(path, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return err
}
defer dst.Close()
_, err = io.Copy(dst, hc.Stdin)
return err
}
func installLibraryCmd(hc interp.HandlerContext, cmd string, args []string) error {
prefix := getLibPrefix(hc)
fn := installHelperCmd(prefix, 0o755)
return fn(hc, cmd, args)
}
// See https://wiki.debian.org/Multiarch/Tuples
var multiarchTupleMap = map[string]string{
"386": "i386-linux-gnu",
"amd64": "x86_64-linux-gnu",
"arm5": "arm-linux-gnueabi",
"arm6": "arm-linux-gnueabihf",
"arm7": "arm-linux-gnueabihf",
"arm64": "aarch64-linux-gnu",
"mips": "mips-linux-gnu",
"mipsle": "mipsel-linux-gnu",
"mips64": "mips64-linux-gnuabi64",
"mips64le": "mips64el-linux-gnuabi64",
"ppc64": "powerpc64-linux-gnu",
"ppc64le": "powerpc64le-linux-gnu",
"s390x": "s390x-linux-gnu",
"riscv64": "riscv64-linux-gnu",
"loong64": "loongarch64-linux-gnu",
}
// usrLibDistros is a list of distros that don't support
// /usr/lib64, and must use /usr/lib
var usrLibDistros = []string{
"arch",
"alpine",
"void",
"chimera",
}
// Based on CMake's GNUInstallDirs
func getLibPrefix(hc interp.HandlerContext) string {
if dir, ok := os.LookupEnv("LURE_LIB_DIR"); ok {
return dir
}
out := "/usr/lib"
distroID := hc.Env.Get("DISTRO_ID").Str
distroLike := strings.Split(hc.Env.Get("DISTRO_ID_LIKE").Str, " ")
for _, usrLibDistro := range usrLibDistros {
if distroID == usrLibDistro || slices.Contains(distroLike, usrLibDistro) {
return out
}
}
wordSize := unsafe.Sizeof(uintptr(0))
if wordSize == 8 {
out = "/usr/lib64"
}
architecture := hc.Env.Get("ARCH").Str
if distroID == "debian" || slices.Contains(distroLike, "debian") {
triple, ok := multiarchTupleMap[architecture]
if ok {
out = filepath.Join("/usr/lib", triple)
}
}
return out
}
func helperInstall(from, to string, perms os.FileMode) error {
err := os.MkdirAll(filepath.Dir(to), 0o755)
if err != nil {
return err
}
src, err := os.Open(from)
if err != nil {
return err
}
defer src.Close()
dst, err := os.OpenFile(to, os.O_TRUNC|os.O_CREATE|os.O_RDWR, perms)
if err != nil {
return err
}
defer dst.Close()
_, err = io.Copy(dst, src)
return err
}

View File

@@ -20,21 +20,34 @@ package shutils
import ( import (
"context" "context"
"fmt"
"time" "time"
"mvdan.cc/sh/v3/interp" "mvdan.cc/sh/v3/interp"
) )
type ExecFuncs map[string]func(interp.HandlerContext, []string) uint8 func InsufficientArgsError(cmd string, exp, got int) error {
argsWord := "arguments"
if exp == 1 {
argsWord = "argument"
}
return fmt.Errorf("%s: command requires at least %d %s, got %d", cmd, exp, argsWord, got)
}
type ExecFunc func(hc interp.HandlerContext, name string, args []string) error
type ExecFuncs map[string]ExecFunc
func (ef ExecFuncs) ExecHandler(ctx context.Context, args []string) error { func (ef ExecFuncs) ExecHandler(ctx context.Context, args []string) error {
name := args[0] name := args[0]
if fn, ok := ef[name]; ok { if fn, ok := ef[name]; ok {
hctx := interp.HandlerCtx(ctx) hctx := interp.HandlerCtx(ctx)
ec := fn(hctx, args) if len(args) > 1 {
if ec != 0 { return fn(hctx, args[0], args[1:])
return interp.NewExitStatus(ec) } else {
return fn(hctx, args[0], nil)
} }
} }

10
main.go
View File

@@ -128,6 +128,11 @@ func main() {
Aliases: []string{"ref"}, Aliases: []string{"ref"},
Action: refreshCmd, Action: refreshCmd,
}, },
{
Name: "version",
Usage: "Display the current LURE version and exit",
Action: displayVersion,
},
}, },
} }
@@ -136,3 +141,8 @@ func main() {
log.Error("Error while running app").Err(err).Send() log.Error("Error while running app").Err(err).Send()
} }
} }
func displayVersion(c *cli.Context) error {
print(version)
return nil
}

View File

@@ -137,6 +137,7 @@ func (d *DNF) ListInstalled(opts *Opts) (map[string]string, error) {
if !ok { if !ok {
continue continue
} }
version = strings.TrimPrefix(version, "0:")
out[name] = version out[name] = version
} }

View File

@@ -137,6 +137,7 @@ func (y *YUM) ListInstalled(opts *Opts) (map[string]string, error) {
if !ok { if !ok {
continue continue
} }
version = strings.TrimPrefix(version, "0:")
out[name] = version out[name] = version
} }

View File

@@ -137,6 +137,7 @@ func (z *Zypper) ListInstalled(opts *Opts) (map[string]string, error) {
if !ok { if !ok {
continue continue
} }
version = strings.TrimPrefix(version, "0:")
out[name] = version out[name] = version
} }

47
repo.go
View File

@@ -41,6 +41,12 @@ func (p PkgNotFoundError) Error() string {
return "package '" + p.pkgName + "' could not be found in any repository" return "package '" + p.pkgName + "' could not be found in any repository"
} }
type RepoConfig struct {
Repo struct {
MinVersion string `toml:"minVersion"`
}
}
func addrepoCmd(c *cli.Context) error { func addrepoCmd(c *cli.Context) error {
name := c.String("name") name := c.String("name")
repoURL := c.String("url") repoURL := c.String("url")
@@ -146,7 +152,9 @@ func findPkg(pkg string) ([]string, error) {
func pkgPrompt(options []string) ([]string, error) { func pkgPrompt(options []string) ([]string, error) {
names := make([]string, len(options)) names := make([]string, len(options))
for i, option := range options { for i, option := range options {
names[i] = filepath.Base(filepath.Dir(option)) pkgDir := filepath.Dir(option)
repoDir := filepath.Dir(pkgDir)
names[i] = filepath.Base(repoDir) + "/" + filepath.Base(pkgDir)
} }
prompt := &survey.MultiSelect{ prompt := &survey.MultiSelect{
@@ -221,6 +229,26 @@ func pullRepos(ctx context.Context) error {
} else if err != nil { } else if err != nil {
return err return err
} }
fl, err := w.Filesystem.Open("lure-repo.toml")
if err != nil {
log.Warn("Git repository does not appear to be a valid LURE repo").Str("repo", repo.Name).Send()
continue
}
var repoCfg RepoConfig
err = toml.NewDecoder(fl).Decode(&repoCfg)
if err != nil {
return err
}
fl.Close()
currentVer, _, _ := strings.Cut(version, "-")
if vercmp(currentVer, repoCfg.Repo.MinVersion) == -1 {
log.Warn("LURE repo's minumum LURE version is greater than the current version. Try updating LURE if something doesn't work.").Str("repo", repo.Name).Send()
}
continue
} }
err = os.RemoveAll(repoDir) err = os.RemoveAll(repoDir)
@@ -244,6 +272,23 @@ func pullRepos(ctx context.Context) error {
if err != nil { if err != nil {
return err return err
} }
fl, err := os.Open(filepath.Join(repoDir, "lure-repo.toml"))
if err != nil {
log.Warn("Git repository does not appear to be a valid LURE repo").Str("repo", repo.Name).Send()
}
var repoCfg RepoConfig
err = toml.NewDecoder(fl).Decode(&repoCfg)
if err != nil {
return err
}
fl.Close()
currentVer, _, _ := strings.Cut(version, "-")
if vercmp(currentVer, repoCfg.Repo.MinVersion) == -1 {
log.Warn("LURE repo's minumum LURE version is greater than the current version. Try updating LURE if something doesn't work.").Str("repo", repo.Name).Send()
}
} }
return nil return nil

3
scripts/gen-version.sh Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/bash
git describe --tags > version.txt

View File

@@ -19,12 +19,18 @@
package main package main
import ( import (
_ "embed"
"strconv" "strconv"
"strings" "strings"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
) )
//go:generate scripts/gen-version.sh
//go:embed version.txt
var version string
// vercmp compares two version strings. // vercmp compares two version strings.
// It returns 1 if v1 is greater, // It returns 1 if v1 is greater,
// 0 if the versions are equal, // 0 if the versions are equal,