mirror of
https://github.com/EnumeratedDev/bpm.git
synced 2026-09-16 10:36:12 +00:00
Move go code to src/ subdirectory
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
module gitlab.com/bubble-package-manager/bpm
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
github.com/elliotchance/orderedmap/v2 v2.4.0 // indirect
|
||||
github.com/knqyf263/go-rpm-version v0.0.0-20240918084003-2afd7dc6a38f // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
github.com/elliotchance/orderedmap/v2 v2.4.0 h1:6tUmMwD9F998FNpwFxA5E6NQvSpk2PVw7RKsVq3+2Cw=
|
||||
github.com/elliotchance/orderedmap/v2 v2.4.0/go.mod h1:85lZyVbpGaGvHvnKa7Qhx7zncAdBIBq6u56Hb1PRU5Q=
|
||||
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
|
||||
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/knqyf263/go-rpm-version v0.0.0-20240918084003-2afd7dc6a38f h1:xt29M2T6STgldg+WEP51gGePQCsQvklmP2eIhPIBK3g=
|
||||
github.com/knqyf263/go-rpm-version v0.0.0-20240918084003-2afd7dc6a38f/go.mod h1:i4sF0l1fFnY1aiw08QQSwVAFxHEm311Me3WsU/X7nL0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
+793
@@ -0,0 +1,793 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"gitlab.com/bubble-package-manager/bpm/utils"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
/* -------------BPM | Bubble Package Manager-------------- */
|
||||
/* Made By EnumDev (Previously CapCreeperGR) */
|
||||
/* A simple-to-use package manager */
|
||||
/* ------------------------------------------------------- */
|
||||
|
||||
var bpmVer = "0.5.0"
|
||||
|
||||
var subcommand = "help"
|
||||
var subcommandArgs []string
|
||||
|
||||
// Flags
|
||||
var rootDir = "/"
|
||||
var verbose = false
|
||||
var yesAll = false
|
||||
var buildSource = false
|
||||
var skipCheck = false
|
||||
var keepTempDir = false
|
||||
var force = false
|
||||
var pkgListNumbers = false
|
||||
var pkgListNames = false
|
||||
var reinstall = false
|
||||
var reinstallAll = false
|
||||
var noOptional = false
|
||||
var installationReason = ""
|
||||
var nosync = true
|
||||
var removeUnused = false
|
||||
var doCleanup = false
|
||||
var showRepoInfo = false
|
||||
|
||||
func main() {
|
||||
utils.ReadConfig()
|
||||
resolveFlags()
|
||||
resolveCommand()
|
||||
}
|
||||
|
||||
type commandType uint8
|
||||
|
||||
const (
|
||||
_default commandType = iota
|
||||
help
|
||||
info
|
||||
list
|
||||
search
|
||||
install
|
||||
update
|
||||
sync
|
||||
remove
|
||||
cleanup
|
||||
file
|
||||
)
|
||||
|
||||
func getCommandType() commandType {
|
||||
switch subcommand {
|
||||
case "version":
|
||||
return _default
|
||||
case "info":
|
||||
return info
|
||||
case "list":
|
||||
return list
|
||||
case "search":
|
||||
return search
|
||||
case "install":
|
||||
return install
|
||||
case "update":
|
||||
return update
|
||||
case "sync":
|
||||
return sync
|
||||
case "remove":
|
||||
return remove
|
||||
case "cleanup":
|
||||
return cleanup
|
||||
case "file":
|
||||
return file
|
||||
default:
|
||||
return help
|
||||
}
|
||||
}
|
||||
|
||||
func resolveCommand() {
|
||||
switch getCommandType() {
|
||||
case _default:
|
||||
fmt.Println("Bubble Package Manager (BPM)")
|
||||
fmt.Println("Version: " + bpmVer)
|
||||
case info:
|
||||
packages := subcommandArgs
|
||||
if len(packages) == 0 {
|
||||
fmt.Println("No packages were given")
|
||||
return
|
||||
}
|
||||
for n, pkg := range packages {
|
||||
var info *utils.PackageInfo
|
||||
isFile := false
|
||||
if showRepoInfo {
|
||||
var err error
|
||||
var entry *utils.RepositoryEntry
|
||||
entry, _, err = utils.GetRepositoryEntry(pkg)
|
||||
if err != nil {
|
||||
if entry = utils.ResolveVirtualPackage(pkg); entry == nil {
|
||||
log.Fatalf("Error: could not find package (%s) in any repository\n", pkg)
|
||||
}
|
||||
}
|
||||
info = entry.Info
|
||||
} else if stat, err := os.Stat(pkg); err == nil && !stat.IsDir() {
|
||||
bpmpkg, err := utils.ReadPackage(pkg)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not read package: %s\n", err)
|
||||
}
|
||||
info = bpmpkg.PkgInfo
|
||||
isFile = true
|
||||
} else {
|
||||
if isVirtual, p := utils.IsVirtualPackage(pkg, rootDir); isVirtual {
|
||||
info = utils.GetPackageInfo(p, rootDir)
|
||||
} else {
|
||||
info = utils.GetPackageInfo(pkg, rootDir)
|
||||
}
|
||||
}
|
||||
if info == nil {
|
||||
log.Fatalf("Error: package (%s) is not installed\n", pkg)
|
||||
}
|
||||
if n != 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
if isFile {
|
||||
abs, err := filepath.Abs(pkg)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get absolute path of file (%s)\n", abs)
|
||||
}
|
||||
fmt.Println("File: " + abs)
|
||||
}
|
||||
fmt.Println(utils.CreateReadableInfo(true, true, true, info, rootDir))
|
||||
}
|
||||
case list:
|
||||
packages, err := utils.GetInstalledPackages(rootDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get installed packages: %s", err.Error())
|
||||
return
|
||||
}
|
||||
if pkgListNumbers {
|
||||
fmt.Println(len(packages))
|
||||
} else if pkgListNames {
|
||||
for _, pkg := range packages {
|
||||
fmt.Println(pkg)
|
||||
}
|
||||
} else {
|
||||
if len(packages) == 0 {
|
||||
fmt.Println("No packages have been installed")
|
||||
return
|
||||
}
|
||||
for n, pkg := range packages {
|
||||
info := utils.GetPackageInfo(pkg, rootDir)
|
||||
if info == nil {
|
||||
fmt.Printf("Package (%s) could not be found\n", pkg)
|
||||
continue
|
||||
}
|
||||
if n != 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Println(utils.CreateReadableInfo(true, true, true, info, rootDir))
|
||||
}
|
||||
}
|
||||
case search:
|
||||
searchTerms := subcommandArgs
|
||||
if len(searchTerms) == 0 {
|
||||
log.Fatalf("Error: no search terms given")
|
||||
}
|
||||
for i, term := range searchTerms {
|
||||
nameResults := make([]*utils.PackageInfo, 0)
|
||||
descResults := make([]*utils.PackageInfo, 0)
|
||||
for _, repo := range utils.BPMConfig.Repositories {
|
||||
for _, entry := range repo.Entries {
|
||||
if strings.Contains(entry.Info.Name, term) {
|
||||
nameResults = append(nameResults, entry.Info)
|
||||
} else if strings.Contains(entry.Info.Description, term) {
|
||||
descResults = append(descResults, entry.Info)
|
||||
}
|
||||
}
|
||||
}
|
||||
results := append(nameResults, descResults...)
|
||||
if len(results) == 0 {
|
||||
log.Fatalf("Error: no results for term (%s) were found\n", term)
|
||||
}
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Printf("Results for term (%s)\n", term)
|
||||
for j, result := range results {
|
||||
fmt.Printf("%d) %s: %s (%s)\n", j+1, result.Name, result.Description, result.GetFullVersion())
|
||||
}
|
||||
}
|
||||
case install:
|
||||
if os.Getuid() != 0 {
|
||||
log.Fatalf("Error: this subcommand needs to be run with superuser permissions")
|
||||
}
|
||||
pkgs := subcommandArgs
|
||||
if len(pkgs) == 0 {
|
||||
fmt.Println("No packages or files were given to install")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if installationReason argument is valid
|
||||
ir := utils.Unknown
|
||||
if installationReason == "manual" {
|
||||
ir = utils.Manual
|
||||
} else if installationReason == "dependency" {
|
||||
ir = utils.Dependency
|
||||
} else if installationReason != "" {
|
||||
log.Fatalf("Error: %s is not a valid installation reason", installationReason)
|
||||
}
|
||||
|
||||
operation := utils.BPMOperation{
|
||||
Actions: make([]utils.OperationAction, 0),
|
||||
UnresolvedDepends: make([]string, 0),
|
||||
Changes: make(map[string]string),
|
||||
RootDir: rootDir,
|
||||
ForceInstallationReason: ir,
|
||||
}
|
||||
|
||||
// Search for packages
|
||||
for _, pkg := range pkgs {
|
||||
if stat, err := os.Stat(pkg); err == nil && !stat.IsDir() {
|
||||
bpmpkg, err := utils.ReadPackage(pkg)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not read package: %s\n", err)
|
||||
}
|
||||
if !reinstall && utils.IsPackageInstalled(bpmpkg.PkgInfo.Name, rootDir) && utils.GetPackageInfo(bpmpkg.PkgInfo.Name, rootDir).GetFullVersion() == bpmpkg.PkgInfo.GetFullVersion() {
|
||||
continue
|
||||
}
|
||||
operation.AppendAction(&utils.InstallPackageAction{
|
||||
File: pkg,
|
||||
IsDependency: false,
|
||||
BpmPackage: bpmpkg,
|
||||
})
|
||||
} else {
|
||||
var entry *utils.RepositoryEntry
|
||||
|
||||
if e, _, err := utils.GetRepositoryEntry(pkg); err == nil {
|
||||
entry = e
|
||||
} else if isVirtual, p := utils.IsVirtualPackage(pkg, rootDir); isVirtual {
|
||||
entry, _, err = utils.GetRepositoryEntry(p)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not find package (%s) in any repository\n", p)
|
||||
}
|
||||
} else if e := utils.ResolveVirtualPackage(pkg); e != nil {
|
||||
entry = e
|
||||
} else {
|
||||
log.Fatalf("Error: could not find package (%s) in any repository\n", pkg)
|
||||
}
|
||||
if !reinstall && utils.IsPackageInstalled(entry.Info.Name, rootDir) && utils.GetPackageInfo(entry.Info.Name, rootDir).GetFullVersion() == entry.Info.GetFullVersion() {
|
||||
continue
|
||||
}
|
||||
operation.AppendAction(&utils.FetchPackageAction{
|
||||
IsDependency: false,
|
||||
RepositoryEntry: entry,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve dependencies
|
||||
err := operation.ResolveDependencies(reinstallAll, !noOptional, verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not resolve dependencies: %s\n", err)
|
||||
}
|
||||
if len(operation.UnresolvedDepends) != 0 {
|
||||
if !force {
|
||||
log.Fatalf("Error: the following dependencies could not be found in any repositories: %s\n", strings.Join(operation.UnresolvedDepends, ", "))
|
||||
} else {
|
||||
log.Println("Warning: The following dependencies could not be found in any repositories: " + strings.Join(operation.UnresolvedDepends, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
// Replace obsolete packages
|
||||
operation.ReplaceObsoletePackages()
|
||||
|
||||
// Check for conflicts
|
||||
conflicts, err := operation.CheckForConflicts()
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not complete package conflict check: %s\n", err)
|
||||
}
|
||||
if len(conflicts) > 0 {
|
||||
if !force {
|
||||
log.Println("Error: conflicting packages found")
|
||||
} else {
|
||||
log.Fatalf("Warning: conflicting packages found")
|
||||
}
|
||||
for pkg, conflict := range conflicts {
|
||||
fmt.Printf("%s is in conflict with the following packages: %s\n", pkg, strings.Join(conflict, ", "))
|
||||
}
|
||||
if !force {
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Show operation summary
|
||||
operation.ShowOperationSummary()
|
||||
|
||||
// Confirmation Prompt
|
||||
if !yesAll {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
if len(operation.Actions) == 1 {
|
||||
fmt.Printf("Do you wish to install this package? [y\\N] ")
|
||||
} else {
|
||||
fmt.Printf("Do you wish to install these %d packages? [y\\N] ", len(operation.Actions))
|
||||
}
|
||||
|
||||
text, _ := reader.ReadString('\n')
|
||||
if strings.TrimSpace(strings.ToLower(text)) != "y" && strings.TrimSpace(strings.ToLower(text)) != "yes" {
|
||||
fmt.Println("Cancelling package installation...")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute operation
|
||||
err = operation.Execute(verbose, force)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not complete operation: %s\n", err)
|
||||
}
|
||||
|
||||
// Executing hooks
|
||||
fmt.Println("Running hooks...")
|
||||
err = operation.RunHooks(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not run hooks: %s\n", err)
|
||||
}
|
||||
case update:
|
||||
if os.Getuid() != 0 {
|
||||
log.Fatalf("Error: this subcommand needs to be run with superuser permissions")
|
||||
}
|
||||
|
||||
// Sync repositories
|
||||
if !nosync {
|
||||
for _, repo := range utils.BPMConfig.Repositories {
|
||||
fmt.Printf("Fetching package database for repository (%s)...\n", repo.Name)
|
||||
err := repo.SyncLocalDatabase()
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not sync local database for repository (%s): %s\n", repo.Name, err)
|
||||
}
|
||||
}
|
||||
fmt.Println("All package databases synced successfully!")
|
||||
}
|
||||
|
||||
utils.ReadConfig()
|
||||
|
||||
// Get installed packages and check for updates
|
||||
pkgs, err := utils.GetInstalledPackages(rootDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get installed packages: %s\n", err)
|
||||
}
|
||||
|
||||
operation := utils.BPMOperation{
|
||||
Actions: make([]utils.OperationAction, 0),
|
||||
UnresolvedDepends: make([]string, 0),
|
||||
Changes: make(map[string]string),
|
||||
RootDir: rootDir,
|
||||
ForceInstallationReason: utils.Unknown,
|
||||
}
|
||||
|
||||
// Search for packages
|
||||
for _, pkg := range pkgs {
|
||||
if slices.Contains(utils.BPMConfig.IgnorePackages, pkg) {
|
||||
continue
|
||||
}
|
||||
var entry *utils.RepositoryEntry
|
||||
// Check if installed package can be replaced and install that instead
|
||||
if e := utils.FindReplacement(pkg); e != nil {
|
||||
entry = e
|
||||
} else if entry, _, err = utils.GetRepositoryEntry(pkg); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
installedInfo := utils.GetPackageInfo(pkg, rootDir)
|
||||
if installedInfo == nil {
|
||||
log.Fatalf("Error: could not get package info for (%s)\n", pkg)
|
||||
} else {
|
||||
comparison := utils.ComparePackageVersions(*entry.Info, *installedInfo)
|
||||
if comparison > 0 || reinstall {
|
||||
operation.AppendAction(&utils.FetchPackageAction{
|
||||
IsDependency: false,
|
||||
RepositoryEntry: entry,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for new dependencies in updated packages
|
||||
err = operation.ResolveDependencies(reinstallAll, !noOptional, verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not resolve dependencies: %s\n", err)
|
||||
}
|
||||
if len(operation.UnresolvedDepends) != 0 {
|
||||
if !force {
|
||||
log.Fatalf("Error: the following dependencies could not be found in any repositories: %s\n", strings.Join(operation.UnresolvedDepends, ", "))
|
||||
} else {
|
||||
log.Println("Warning: The following dependencies could not be found in any repositories: " + strings.Join(operation.UnresolvedDepends, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
// Replace obsolete packages
|
||||
operation.ReplaceObsoletePackages()
|
||||
|
||||
// Show operation summary
|
||||
operation.ShowOperationSummary()
|
||||
|
||||
// Confirmation Prompt
|
||||
if !yesAll {
|
||||
fmt.Printf("Are you sure you wish to update all %d packages? [y\\N] ", len(operation.Actions))
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
text, _ := reader.ReadString('\n')
|
||||
if strings.TrimSpace(strings.ToLower(text)) != "y" && strings.TrimSpace(strings.ToLower(text)) != "yes" {
|
||||
fmt.Println("Cancelling package update...")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute operation
|
||||
err = operation.Execute(verbose, force)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not complete operation: %s\n", err)
|
||||
}
|
||||
|
||||
// Executing hooks
|
||||
fmt.Println("Running hooks...")
|
||||
err = operation.RunHooks(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not run hooks: %s\n", err)
|
||||
}
|
||||
case sync:
|
||||
if os.Getuid() != 0 {
|
||||
log.Fatalf("Error: this subcommand needs to be run with superuser permissions")
|
||||
}
|
||||
if !yesAll {
|
||||
fmt.Printf("Are you sure you wish to sync all databases? [y\\N] ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
text, _ := reader.ReadString('\n')
|
||||
if strings.TrimSpace(strings.ToLower(text)) != "y" && strings.TrimSpace(strings.ToLower(text)) != "yes" {
|
||||
fmt.Println("Cancelling database synchronization...")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
for _, repo := range utils.BPMConfig.Repositories {
|
||||
fmt.Printf("Fetching package database for repository (%s)...\n", repo.Name)
|
||||
err := repo.SyncLocalDatabase()
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not sync local database for repository (%s): %s\n", repo.Name, err)
|
||||
}
|
||||
}
|
||||
fmt.Println("All package databases synced successfully!")
|
||||
case remove:
|
||||
if os.Getuid() != 0 {
|
||||
log.Fatalf("Error: this subcommand needs to be run with superuser permissions")
|
||||
}
|
||||
packages := subcommandArgs
|
||||
if len(packages) == 0 {
|
||||
fmt.Println("No packages were given")
|
||||
return
|
||||
}
|
||||
|
||||
operation := &utils.BPMOperation{
|
||||
Actions: make([]utils.OperationAction, 0),
|
||||
UnresolvedDepends: make([]string, 0),
|
||||
Changes: make(map[string]string),
|
||||
RootDir: rootDir,
|
||||
}
|
||||
|
||||
// Search for packages
|
||||
for _, pkg := range packages {
|
||||
bpmpkg := utils.GetPackage(pkg, rootDir)
|
||||
if bpmpkg == nil {
|
||||
continue
|
||||
}
|
||||
operation.AppendAction(&utils.RemovePackageAction{BpmPackage: bpmpkg})
|
||||
}
|
||||
|
||||
// Skip needed packages if the --unused flag is on
|
||||
if removeUnused {
|
||||
err := operation.RemoveNeededPackages()
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not skip needed packages: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Do package cleanup
|
||||
if doCleanup {
|
||||
err := operation.Cleanup(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not perform cleanup for operation: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Show operation summary
|
||||
operation.ShowOperationSummary()
|
||||
|
||||
// Confirmation Prompt
|
||||
if !yesAll {
|
||||
fmt.Printf("Are you sure you wish to remove all %d packages? [y\\N] ", len(operation.Actions))
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
text, _ := reader.ReadString('\n')
|
||||
if strings.TrimSpace(strings.ToLower(text)) != "y" && strings.TrimSpace(strings.ToLower(text)) != "yes" {
|
||||
fmt.Println("Cancelling package removal...")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute operation
|
||||
err := operation.Execute(verbose, force)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not complete operation: %s\n", err)
|
||||
}
|
||||
|
||||
// Executing hooks
|
||||
fmt.Println("Running hooks...")
|
||||
err = operation.RunHooks(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not run hooks: %s\n", err)
|
||||
}
|
||||
case cleanup:
|
||||
if os.Getuid() != 0 {
|
||||
log.Fatalf("Error: this subcommand needs to be run with superuser permissions")
|
||||
}
|
||||
|
||||
operation := &utils.BPMOperation{
|
||||
Actions: make([]utils.OperationAction, 0),
|
||||
UnresolvedDepends: make([]string, 0),
|
||||
Changes: make(map[string]string),
|
||||
RootDir: rootDir,
|
||||
}
|
||||
|
||||
// Do package cleanup
|
||||
err := operation.Cleanup(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not perform cleanup for operation: %s\n", err)
|
||||
}
|
||||
|
||||
// Show operation summary
|
||||
operation.ShowOperationSummary()
|
||||
|
||||
// Confirmation Prompt
|
||||
if !yesAll {
|
||||
fmt.Printf("Are you sure you wish to remove all %d packages? [y\\N] ", len(operation.Actions))
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
text, _ := reader.ReadString('\n')
|
||||
if strings.TrimSpace(strings.ToLower(text)) != "y" && strings.TrimSpace(strings.ToLower(text)) != "yes" {
|
||||
fmt.Println("Cancelling package removal...")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute operation
|
||||
err = operation.Execute(verbose, force)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not complete operation: %s\n", err)
|
||||
}
|
||||
|
||||
// Executing hooks
|
||||
fmt.Println("Running hooks...")
|
||||
err = operation.RunHooks(verbose)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not run hooks: %s\n", err)
|
||||
}
|
||||
case file:
|
||||
files := subcommandArgs
|
||||
if len(files) == 0 {
|
||||
fmt.Println("No files were given to get which packages manage it")
|
||||
return
|
||||
}
|
||||
for _, file := range files {
|
||||
absFile, err := filepath.Abs(file)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get absolute path of file (%s)\n", file)
|
||||
}
|
||||
stat, err := os.Stat(absFile)
|
||||
if os.IsNotExist(err) {
|
||||
log.Fatalf("Error: file (%s) does not exist!\n", absFile)
|
||||
}
|
||||
pkgs, err := utils.GetInstalledPackages(rootDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get installed packages: %s\n", err.Error())
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(absFile, rootDir) {
|
||||
log.Fatalf("Error: could not get path of file (%s) relative to root path", absFile)
|
||||
}
|
||||
absFile, err = filepath.Rel(rootDir, absFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get path of file (%s) relative to root path", absFile)
|
||||
}
|
||||
absFile = strings.TrimPrefix(absFile, "/")
|
||||
if stat.IsDir() {
|
||||
absFile = absFile + "/"
|
||||
}
|
||||
|
||||
var pkgList []string
|
||||
for _, pkg := range pkgs {
|
||||
if slices.ContainsFunc(utils.GetPackageFiles(pkg, rootDir), func(entry *utils.PackageFileEntry) bool {
|
||||
return entry.Path == absFile
|
||||
}) {
|
||||
pkgList = append(pkgList, pkg)
|
||||
}
|
||||
}
|
||||
if len(pkgList) == 0 {
|
||||
fmt.Println(absFile + " is not managed by any packages")
|
||||
} else {
|
||||
fmt.Println(absFile + " is managed by the following packages:")
|
||||
for _, pkg := range pkgList {
|
||||
fmt.Println("- " + pkg)
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
printHelp()
|
||||
}
|
||||
}
|
||||
|
||||
func printHelp() {
|
||||
fmt.Println("\033[1m---- Command Format ----\033[0m")
|
||||
fmt.Println("-> command format: bpm <subcommand> [-flags]...")
|
||||
fmt.Println("-> flags will be read if passed right after the subcommand otherwise they will be read as subcommand arguments")
|
||||
fmt.Println("\033[1m---- Command List ----\033[0m")
|
||||
fmt.Println("-> bpm version | shows information on the installed version of bpm")
|
||||
fmt.Println("-> bpm info [-R, --repos] <packages...> | shows information on an installed package")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" --repos show information on package in repository")
|
||||
fmt.Println("-> bpm list [-R, -c, -n] | lists all installed packages")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -c lists the amount of installed packages")
|
||||
fmt.Println(" -n lists only the names of installed packages")
|
||||
fmt.Println("-> bpm search <search terms...> | Searches for packages through declared repositories")
|
||||
fmt.Println("-> bpm install [-R, -v, -y, -f, -o, -c, -b, -k, --reinstall, --reinstall-all, --no-optional, --installation-reason] <packages...> | installs the following files")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -v Show additional information about what BPM is doing")
|
||||
fmt.Println(" -y skips the confirmation prompt")
|
||||
fmt.Println(" -f skips dependency, conflict and architecture checking")
|
||||
fmt.Println(" -o=<path> set the binary package output directory (defaults to /var/lib/bpm/compiled)")
|
||||
fmt.Println(" -c=<path> set the compilation directory (defaults to /var/tmp)")
|
||||
fmt.Println(" -b creates a binary package from a source package after compilation and saves it in the binary package output directory")
|
||||
fmt.Println(" -k keeps the compilation directory created by BPM after source package installation")
|
||||
fmt.Println(" --reinstall Reinstalls packages even if they do not have a newer version available")
|
||||
fmt.Println(" --reinstall-all Same as --reinstall but also reinstalls dependencies")
|
||||
fmt.Println(" --no-optional Prevents installation of optional dependencies")
|
||||
fmt.Println(" --installation-reason=<manual/dependency> sets the installation reason for all newly installed packages")
|
||||
fmt.Println("-> bpm update [-R, -v, -y, -f, --reinstall, --no-sync] | updates all packages that are available in the repositories")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -v Show additional information about what BPM is doing")
|
||||
fmt.Println(" -y skips the confirmation prompt")
|
||||
fmt.Println(" -f skips dependency, conflict and architecture checking")
|
||||
fmt.Println(" --reinstall Fetches and reinstalls all packages even if they do not have a newer version available")
|
||||
fmt.Println(" --no-sync Skips package database syncing")
|
||||
fmt.Println("-> bpm sync [-R, -v, -y] | Syncs package databases without updating packages")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -v Show additional information about what BPM is doing")
|
||||
fmt.Println(" -y skips the confirmation prompt")
|
||||
fmt.Println("-> bpm remove [-R, -v, -y, --unused, --cleanup] <packages...> | removes the following packages")
|
||||
fmt.Println(" -v Show additional information about what BPM is doing")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -y skips the confirmation prompt")
|
||||
fmt.Println(" -unused removes only packages that aren't required as dependencies by other packages")
|
||||
fmt.Println(" -cleanup performs a dependency cleanup")
|
||||
fmt.Println("-> bpm cleanup [-R, -v, -y] | remove all unused dependency packages")
|
||||
fmt.Println(" -v Show additional information about what BPM is doing")
|
||||
fmt.Println(" -R=<path> lets you define the root path which will be used")
|
||||
fmt.Println(" -y skips the confirmation prompt")
|
||||
fmt.Println("-> bpm file [-R] <files...> | shows what packages the following packages are managed by")
|
||||
fmt.Println(" -R=<root_path> lets you define the root path which will be used")
|
||||
fmt.Println("\033[1m----------------\033[0m")
|
||||
}
|
||||
|
||||
func resolveFlags() {
|
||||
// List flags
|
||||
listFlagSet := flag.NewFlagSet("List flags", flag.ExitOnError)
|
||||
listFlagSet.Usage = printHelp
|
||||
listFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
listFlagSet.BoolVar(&pkgListNumbers, "c", false, "List the number of all packages installed with BPM")
|
||||
listFlagSet.BoolVar(&pkgListNames, "n", false, "List the names of all packages installed with BPM")
|
||||
// Info flags
|
||||
infoFlagSet := flag.NewFlagSet("Info flags", flag.ExitOnError)
|
||||
infoFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
infoFlagSet.BoolVar(&showRepoInfo, "repos", false, "Show information on package in repository")
|
||||
infoFlagSet.Usage = printHelp
|
||||
// Install flags
|
||||
installFlagSet := flag.NewFlagSet("Install flags", flag.ExitOnError)
|
||||
installFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
installFlagSet.BoolVar(&verbose, "v", false, "Show additional information about what BPM is doing")
|
||||
installFlagSet.BoolVar(&yesAll, "y", false, "Skip confirmation prompts")
|
||||
installFlagSet.StringVar(&utils.BPMConfig.BinaryOutputDir, "o", utils.BPMConfig.BinaryOutputDir, "Set the binary output directory")
|
||||
installFlagSet.StringVar(&utils.BPMConfig.CompilationDir, "c", utils.BPMConfig.CompilationDir, "Set the compilation directory")
|
||||
installFlagSet.BoolVar(&buildSource, "b", false, "Build binary package from source package")
|
||||
installFlagSet.BoolVar(&skipCheck, "s", false, "Skip check function during source compilation")
|
||||
installFlagSet.BoolVar(&keepTempDir, "k", false, "Keep temporary directory after source compilation")
|
||||
installFlagSet.BoolVar(&force, "f", false, "Force installation by skipping architecture and dependency resolution")
|
||||
installFlagSet.BoolVar(&reinstall, "reinstall", false, "Reinstalls packages even if they do not have a newer version available")
|
||||
installFlagSet.BoolVar(&reinstallAll, "reinstall-all", false, "Same as --reinstall but also reinstalls dependencies")
|
||||
installFlagSet.BoolVar(&noOptional, "no-optional", false, "Prevents installation of optional dependencies")
|
||||
installFlagSet.StringVar(&installationReason, "installation-reason", "", "Set the installation reason for all newly installed packages")
|
||||
installFlagSet.Usage = printHelp
|
||||
// Update flags
|
||||
updateFlagSet := flag.NewFlagSet("Update flags", flag.ExitOnError)
|
||||
updateFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
updateFlagSet.BoolVar(&verbose, "v", false, "Show additional information about what BPM is doing")
|
||||
updateFlagSet.BoolVar(&yesAll, "y", false, "Skip confirmation prompts")
|
||||
updateFlagSet.BoolVar(&force, "f", false, "Force update by skipping architecture and dependency resolution")
|
||||
updateFlagSet.BoolVar(&reinstall, "reinstall", false, "Fetches and reinstalls all packages even if they do not have a newer version available")
|
||||
updateFlagSet.BoolVar(&nosync, "no-sync", false, "Skips package database syncing")
|
||||
updateFlagSet.Usage = printHelp
|
||||
// Sync flags
|
||||
syncFlagSet := flag.NewFlagSet("Sync flags", flag.ExitOnError)
|
||||
syncFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
syncFlagSet.BoolVar(&verbose, "v", false, "Show additional information about what BPM is doing")
|
||||
syncFlagSet.BoolVar(&yesAll, "y", false, "Skip confirmation prompts")
|
||||
syncFlagSet.Usage = printHelp
|
||||
// Remove flags
|
||||
removeFlagSet := flag.NewFlagSet("Remove flags", flag.ExitOnError)
|
||||
removeFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
removeFlagSet.BoolVar(&verbose, "v", false, "Show additional information about what BPM is doing")
|
||||
removeFlagSet.BoolVar(&yesAll, "y", false, "Skip confirmation prompts")
|
||||
removeFlagSet.BoolVar(&removeUnused, "unused", false, "Removes only packages that aren't required as dependencies by other packages")
|
||||
removeFlagSet.BoolVar(&doCleanup, "cleanup", false, "Perform a dependency cleanup")
|
||||
removeFlagSet.Usage = printHelp
|
||||
// Cleanup flags
|
||||
cleanupFlagSet := flag.NewFlagSet("Cleanup flags", flag.ExitOnError)
|
||||
cleanupFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
cleanupFlagSet.BoolVar(&verbose, "v", false, "Show additional information about what BPM is doing")
|
||||
cleanupFlagSet.BoolVar(&yesAll, "y", false, "Skip confirmation prompts")
|
||||
cleanupFlagSet.Usage = printHelp
|
||||
// File flags
|
||||
fileFlagSet := flag.NewFlagSet("Remove flags", flag.ExitOnError)
|
||||
fileFlagSet.StringVar(&rootDir, "R", "/", "Set the destination root")
|
||||
fileFlagSet.Usage = printHelp
|
||||
if len(os.Args[1:]) <= 0 {
|
||||
subcommand = "help"
|
||||
} else {
|
||||
subcommand = os.Args[1]
|
||||
subcommandArgs = os.Args[2:]
|
||||
if getCommandType() == list {
|
||||
err := listFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = listFlagSet.Args()
|
||||
} else if getCommandType() == info {
|
||||
err := infoFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = infoFlagSet.Args()
|
||||
} else if getCommandType() == install {
|
||||
err := installFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = installFlagSet.Args()
|
||||
} else if getCommandType() == update {
|
||||
err := updateFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = updateFlagSet.Args()
|
||||
} else if getCommandType() == sync {
|
||||
err := syncFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = syncFlagSet.Args()
|
||||
} else if getCommandType() == remove {
|
||||
err := removeFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = removeFlagSet.Args()
|
||||
} else if getCommandType() == file {
|
||||
err := fileFlagSet.Parse(subcommandArgs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
subcommandArgs = fileFlagSet.Args()
|
||||
}
|
||||
if reinstallAll {
|
||||
reinstall = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"gopkg.in/yaml.v3"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type BPMConfigStruct struct {
|
||||
CompilationEnv []string `yaml:"compilation_env"`
|
||||
SilentCompilation bool `yaml:"silent_compilation"`
|
||||
BinaryOutputDir string `yaml:"binary_output_dir"`
|
||||
CompilationDir string `yaml:"compilation_dir"`
|
||||
IgnorePackages []string `yaml:"ignore_packages"`
|
||||
Repositories []*Repository `yaml:"repositories"`
|
||||
}
|
||||
|
||||
var BPMConfig BPMConfigStruct
|
||||
|
||||
func ReadConfig() {
|
||||
if _, err := os.Stat("/etc/bpm.conf"); os.IsNotExist(err) {
|
||||
log.Fatal(err)
|
||||
}
|
||||
bytes, err := os.ReadFile("/etc/bpm.conf")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
BPMConfig = BPMConfigStruct{
|
||||
CompilationEnv: make([]string, 0),
|
||||
SilentCompilation: false,
|
||||
BinaryOutputDir: "/var/lib/bpm/compiled/",
|
||||
CompilationDir: "/var/tmp/",
|
||||
}
|
||||
err = yaml.Unmarshal(bytes, &BPMConfig)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for i := len(BPMConfig.Repositories) - 1; i >= 0; i-- {
|
||||
if BPMConfig.Repositories[i].Disabled != nil && *BPMConfig.Repositories[i].Disabled {
|
||||
BPMConfig.Repositories = append(BPMConfig.Repositories[:i], BPMConfig.Repositories[i+1:]...)
|
||||
}
|
||||
}
|
||||
for _, repo := range BPMConfig.Repositories {
|
||||
repo.Entries = make(map[string]*RepositoryEntry)
|
||||
repo.VirtualPackages = make(map[string][]string)
|
||||
err := repo.ReadLocalDatabase()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type TarballFileReader struct {
|
||||
tarReader *tar.Reader
|
||||
file *os.File
|
||||
}
|
||||
|
||||
func ReadTarballContent(tarballPath, fileToExtract string) (*TarballFileReader, error) {
|
||||
file, err := os.Open(tarballPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tr := tar.NewReader(file)
|
||||
for {
|
||||
header, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if header.Name == fileToExtract {
|
||||
if header.Typeflag != tar.TypeReg {
|
||||
return nil, errors.New("file to extract must be a regular file")
|
||||
}
|
||||
|
||||
return &TarballFileReader{
|
||||
tarReader: tr,
|
||||
file: file,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("could not file in tarball")
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func GetArch() string {
|
||||
uname := syscall.Utsname{}
|
||||
err := syscall.Uname(&uname)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
var byteString [65]byte
|
||||
var indexLength int
|
||||
for ; uname.Machine[indexLength] != 0; indexLength++ {
|
||||
byteString[indexLength] = uint8(uname.Machine[indexLength])
|
||||
}
|
||||
return string(byteString[:indexLength])
|
||||
}
|
||||
|
||||
func copyFileContents(src, dst string) (err error) {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
cerr := out.Close()
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
}()
|
||||
if _, err = io.Copy(out, in); err != nil {
|
||||
return
|
||||
}
|
||||
err = out.Sync()
|
||||
return
|
||||
}
|
||||
|
||||
func stringSliceRemove(s []string, r string) []string {
|
||||
for i, v := range s {
|
||||
if v == r {
|
||||
return append(s[:i], s[i+1:]...)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func UnsignedBytesToHumanReadable(b uint64) string {
|
||||
bf := float64(b)
|
||||
for _, unit := range []string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"} {
|
||||
if math.Abs(bf) < 1024.0 {
|
||||
return fmt.Sprintf("%3.1f%sB", bf, unit)
|
||||
}
|
||||
bf /= 1024.0
|
||||
}
|
||||
return fmt.Sprintf("%.1fYiB", bf)
|
||||
}
|
||||
|
||||
func BytesToHumanReadable(b int64) string {
|
||||
bf := float64(b)
|
||||
for _, unit := range []string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"} {
|
||||
if math.Abs(bf) < 1024.0 {
|
||||
return fmt.Sprintf("%3.1f%sB", bf, unit)
|
||||
}
|
||||
bf /= 1024.0
|
||||
}
|
||||
return fmt.Sprintf("%.1fYiB", bf)
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"gopkg.in/yaml.v3"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
type BPMHook struct {
|
||||
SourcePath string
|
||||
SourceContent string
|
||||
TriggerOperations []string `yaml:"trigger_operations"`
|
||||
TargetType string `yaml:"target_type"`
|
||||
Targets []string `yaml:"targets"`
|
||||
Depends []string `yaml:"depends"`
|
||||
Run string `yaml:"run"`
|
||||
}
|
||||
|
||||
// CreateHook returns a BPMHook instance based on the content of the given string
|
||||
func CreateHook(sourcePath string) (*BPMHook, error) {
|
||||
// Read hook from source path
|
||||
bytes, err := os.ReadFile(sourcePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create base hook structure
|
||||
hook := &BPMHook{
|
||||
SourcePath: sourcePath,
|
||||
SourceContent: string(bytes),
|
||||
TriggerOperations: nil,
|
||||
TargetType: "",
|
||||
Targets: nil,
|
||||
Depends: nil,
|
||||
Run: "",
|
||||
}
|
||||
|
||||
// Unmarshal yaml string
|
||||
err = yaml.Unmarshal(bytes, hook)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Ensure hook is valid
|
||||
if err := hook.IsValid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return hook, nil
|
||||
}
|
||||
|
||||
// IsValid ensures hook is valid
|
||||
func (hook *BPMHook) IsValid() error {
|
||||
ValidOperations := []string{"install", "upgrade", "remove"}
|
||||
|
||||
// Return error if any trigger operation is not valid or none are given
|
||||
if len(hook.TriggerOperations) == 0 {
|
||||
return errors.New("no trigger operations specified")
|
||||
}
|
||||
for _, operation := range hook.TriggerOperations {
|
||||
if !slices.Contains(ValidOperations, operation) {
|
||||
return errors.New("trigger operation '" + operation + "' is not valid")
|
||||
}
|
||||
}
|
||||
|
||||
if hook.TargetType != "package" && hook.TargetType != "path" {
|
||||
return errors.New("target type '" + hook.TargetType + "' is not valid")
|
||||
}
|
||||
|
||||
if len(hook.Run) == 0 {
|
||||
return errors.New("command to run is empty")
|
||||
}
|
||||
|
||||
// Return nil as hook is valid
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute hook if all conditions are met
|
||||
func (hook *BPMHook) Execute(packageChanges map[string]string, verbose bool, rootDir string) error {
|
||||
// Check if package dependencies are met
|
||||
installedPackages, err := GetInstalledPackages(rootDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, depend := range hook.Depends {
|
||||
if !slices.Contains(installedPackages, depend) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Get modified files slice
|
||||
modifiedFiles := make([]*PackageFileEntry, 0)
|
||||
for pkg := range packageChanges {
|
||||
modifiedFiles = append(modifiedFiles, GetPackageFiles(pkg, rootDir)...)
|
||||
}
|
||||
|
||||
// Check if any targets are met
|
||||
targetMet := false
|
||||
for _, target := range hook.Targets {
|
||||
if targetMet {
|
||||
break
|
||||
}
|
||||
if hook.TargetType == "package" {
|
||||
for change, operation := range packageChanges {
|
||||
if target == change && slices.Contains(hook.TriggerOperations, operation) {
|
||||
targetMet = true
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
glob, err := filepath.Glob(path.Join(rootDir, target))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, change := range modifiedFiles {
|
||||
if slices.Contains(glob, path.Join(rootDir, change.Path)) {
|
||||
targetMet = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !targetMet {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute the command
|
||||
splitCommand := strings.Split(hook.Run, " ")
|
||||
cmd := exec.Command(splitCommand[0], splitCommand[1:]...)
|
||||
// Setup subprocess environment
|
||||
cmd.Dir = "/"
|
||||
// Run hook in chroot if using the -R flag
|
||||
if rootDir != "/" {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Chroot: rootDir}
|
||||
}
|
||||
|
||||
if verbose {
|
||||
fmt.Printf("Running hook (%s) with run command: %s\n", hook.SourcePath, strings.Join(splitCommand, " "))
|
||||
}
|
||||
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type BPMOperation struct {
|
||||
Actions []OperationAction
|
||||
UnresolvedDepends []string
|
||||
Changes map[string]string
|
||||
RootDir string
|
||||
ForceInstallationReason InstallationReason
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) ActionsContainPackage(pkg string) bool {
|
||||
for _, action := range operation.Actions {
|
||||
if action.GetActionType() == "install" {
|
||||
if action.(*InstallPackageAction).BpmPackage.PkgInfo.Name == pkg {
|
||||
return true
|
||||
}
|
||||
} else if action.GetActionType() == "fetch" {
|
||||
if action.(*FetchPackageAction).RepositoryEntry.Info.Name == pkg {
|
||||
return true
|
||||
}
|
||||
} else if action.GetActionType() == "remove" {
|
||||
if action.(*RemovePackageAction).BpmPackage.PkgInfo.Name == pkg {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) AppendAction(action OperationAction) {
|
||||
operation.InsertActionAt(len(operation.Actions), action)
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) InsertActionAt(index int, action OperationAction) {
|
||||
if len(operation.Actions) == index { // nil or empty slice or after last element
|
||||
operation.Actions = append(operation.Actions, action)
|
||||
} else {
|
||||
operation.Actions = append(operation.Actions[:index+1], operation.Actions[index:]...) // index < len(a)
|
||||
operation.Actions[index] = action
|
||||
}
|
||||
|
||||
if action.GetActionType() == "install" {
|
||||
pkgInfo := action.(*InstallPackageAction).BpmPackage.PkgInfo
|
||||
if !IsPackageInstalled(pkgInfo.Name, operation.RootDir) {
|
||||
operation.Changes[pkgInfo.Name] = "install"
|
||||
} else {
|
||||
operation.Changes[pkgInfo.Name] = "upgrade"
|
||||
}
|
||||
} else if action.GetActionType() == "fetch" {
|
||||
pkgInfo := action.(*FetchPackageAction).RepositoryEntry.Info
|
||||
if !IsPackageInstalled(pkgInfo.Name, operation.RootDir) {
|
||||
operation.Changes[pkgInfo.Name] = "install"
|
||||
} else {
|
||||
operation.Changes[pkgInfo.Name] = "upgrade"
|
||||
}
|
||||
} else if action.GetActionType() == "remove" {
|
||||
operation.Changes[action.(*RemovePackageAction).BpmPackage.PkgInfo.Name] = "remove"
|
||||
}
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) RemoveAction(pkg, actionType string) {
|
||||
operation.Actions = slices.DeleteFunc(operation.Actions, func(a OperationAction) bool {
|
||||
if a.GetActionType() != actionType {
|
||||
return false
|
||||
}
|
||||
if a.GetActionType() == "install" {
|
||||
return a.(*InstallPackageAction).BpmPackage.PkgInfo.Name == pkg
|
||||
} else if a.GetActionType() == "fetch" {
|
||||
return a.(*FetchPackageAction).RepositoryEntry.Info.Name == pkg
|
||||
} else if a.GetActionType() == "remove" {
|
||||
return a.(*RemovePackageAction).BpmPackage.PkgInfo.Name == pkg
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) GetTotalDownloadSize() uint64 {
|
||||
var ret uint64 = 0
|
||||
for _, action := range operation.Actions {
|
||||
if action.GetActionType() == "fetch" {
|
||||
ret += action.(*FetchPackageAction).RepositoryEntry.DownloadSize
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) GetTotalInstalledSize() uint64 {
|
||||
var ret uint64 = 0
|
||||
for _, action := range operation.Actions {
|
||||
if action.GetActionType() == "install" {
|
||||
ret += action.(*InstallPackageAction).BpmPackage.GetInstalledSize()
|
||||
} else if action.GetActionType() == "fetch" {
|
||||
ret += action.(*FetchPackageAction).RepositoryEntry.InstalledSize
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) GetFinalActionSize(rootDir string) int64 {
|
||||
var ret int64 = 0
|
||||
for _, action := range operation.Actions {
|
||||
if action.GetActionType() == "install" {
|
||||
ret += int64(action.(*InstallPackageAction).BpmPackage.GetInstalledSize())
|
||||
if IsPackageInstalled(action.(*InstallPackageAction).BpmPackage.PkgInfo.Name, rootDir) {
|
||||
ret -= int64(GetPackage(action.(*InstallPackageAction).BpmPackage.PkgInfo.Name, rootDir).GetInstalledSize())
|
||||
}
|
||||
} else if action.GetActionType() == "fetch" {
|
||||
ret += int64(action.(*FetchPackageAction).RepositoryEntry.InstalledSize)
|
||||
} else if action.GetActionType() == "remove" {
|
||||
ret -= int64(action.(*RemovePackageAction).BpmPackage.GetInstalledSize())
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) ResolveDependencies(reinstallDependencies, installOptionalDependencies, verbose bool) error {
|
||||
pos := 0
|
||||
for _, value := range slices.Clone(operation.Actions) {
|
||||
var pkgInfo *PackageInfo
|
||||
if value.GetActionType() == "install" {
|
||||
action := value.(*InstallPackageAction)
|
||||
pkgInfo = action.BpmPackage.PkgInfo
|
||||
} else if value.GetActionType() == "fetch" {
|
||||
action := value.(*FetchPackageAction)
|
||||
pkgInfo = action.RepositoryEntry.Info
|
||||
} else {
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
|
||||
resolved, unresolved := pkgInfo.ResolveDependencies(&[]string{}, &[]string{}, pkgInfo.Type == "source", installOptionalDependencies, !reinstallDependencies, verbose, operation.RootDir)
|
||||
|
||||
operation.UnresolvedDepends = append(operation.UnresolvedDepends, unresolved...)
|
||||
|
||||
for _, depend := range resolved {
|
||||
if !operation.ActionsContainPackage(depend) && depend != pkgInfo.Name {
|
||||
if !reinstallDependencies && IsPackageInstalled(depend, operation.RootDir) {
|
||||
continue
|
||||
}
|
||||
entry, _, err := GetRepositoryEntry(depend)
|
||||
if err != nil {
|
||||
return errors.New("could not get repository entry for package (" + depend + ")")
|
||||
}
|
||||
operation.InsertActionAt(pos, &FetchPackageAction{
|
||||
IsDependency: true,
|
||||
RepositoryEntry: entry,
|
||||
})
|
||||
pos++
|
||||
}
|
||||
}
|
||||
pos++
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) RemoveNeededPackages() error {
|
||||
removeActions := make(map[string]*RemovePackageAction)
|
||||
for _, action := range slices.Clone(operation.Actions) {
|
||||
if action.GetActionType() == "remove" {
|
||||
removeActions[action.(*RemovePackageAction).BpmPackage.PkgInfo.Name] = action.(*RemovePackageAction)
|
||||
}
|
||||
}
|
||||
|
||||
for pkg, action := range removeActions {
|
||||
dependants, err := action.BpmPackage.PkgInfo.GetDependants(operation.RootDir)
|
||||
if err != nil {
|
||||
return errors.New("could not get dependant packages for package (" + pkg + ")")
|
||||
}
|
||||
dependants = slices.DeleteFunc(dependants, func(d string) bool {
|
||||
if _, ok := removeActions[d]; ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
if len(dependants) != 0 {
|
||||
operation.RemoveAction(pkg, action.GetActionType())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) Cleanup(verbose bool) error {
|
||||
// Get all installed packages
|
||||
installedPackageNames, err := GetInstalledPackages(operation.RootDir)
|
||||
if err != nil {
|
||||
log.Fatalf("Error: could not get installed packages: %s\n", err)
|
||||
}
|
||||
installedPackages := make([]*PackageInfo, len(installedPackageNames))
|
||||
for i, value := range installedPackageNames {
|
||||
bpmpkg := GetPackage(value, operation.RootDir)
|
||||
if bpmpkg == nil {
|
||||
return errors.New("could not find installed package (" + value + ")")
|
||||
}
|
||||
installedPackages[i] = bpmpkg.PkgInfo
|
||||
}
|
||||
|
||||
// Get packages to remove
|
||||
removeActions := make(map[string]*RemovePackageAction)
|
||||
for _, action := range slices.Clone(operation.Actions) {
|
||||
if action.GetActionType() == "remove" {
|
||||
removeActions[action.(*RemovePackageAction).BpmPackage.PkgInfo.Name] = action.(*RemovePackageAction)
|
||||
}
|
||||
}
|
||||
|
||||
// Get manually installed packages, resolve all their dependencies and add them to the keepPackages slice
|
||||
keepPackages := make([]string, 0)
|
||||
for _, pkg := range slices.Clone(installedPackages) {
|
||||
if GetInstallationReason(pkg.Name, operation.RootDir) != Manual {
|
||||
continue
|
||||
}
|
||||
|
||||
// Do not resolve dependencies or add package to keepPackages slice if package removal action exists for it
|
||||
if _, ok := removeActions[pkg.Name]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
keepPackages = append(keepPackages, pkg.Name)
|
||||
resolved, _ := pkg.ResolveDependencies(&[]string{}, &[]string{}, false, true, false, verbose, operation.RootDir)
|
||||
for _, value := range resolved {
|
||||
if !slices.Contains(keepPackages, value) && slices.Contains(installedPackageNames, value) {
|
||||
keepPackages = append(keepPackages, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get all installed packages that are not in the keepPackages slice and add them to the BPM operation
|
||||
for _, pkg := range installedPackageNames {
|
||||
// Do not add package removal action if there already is one
|
||||
if _, ok := removeActions[pkg]; ok {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(keepPackages, pkg) {
|
||||
bpmpkg := GetPackage(pkg, operation.RootDir)
|
||||
if bpmpkg == nil {
|
||||
return errors.New("Error: could not find installed package (" + pkg + ")")
|
||||
}
|
||||
operation.Actions = append(operation.Actions, &RemovePackageAction{BpmPackage: bpmpkg})
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) ReplaceObsoletePackages() {
|
||||
for _, value := range slices.Clone(operation.Actions) {
|
||||
var pkgInfo *PackageInfo
|
||||
if value.GetActionType() == "install" {
|
||||
action := value.(*InstallPackageAction)
|
||||
pkgInfo = action.BpmPackage.PkgInfo
|
||||
|
||||
} else if value.GetActionType() == "fetch" {
|
||||
action := value.(*FetchPackageAction)
|
||||
pkgInfo = action.RepositoryEntry.Info
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, r := range pkgInfo.Replaces {
|
||||
if bpmpkg := GetPackage(r, operation.RootDir); bpmpkg != nil && !operation.ActionsContainPackage(bpmpkg.PkgInfo.Name) {
|
||||
operation.InsertActionAt(0, &RemovePackageAction{
|
||||
BpmPackage: bpmpkg,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) CheckForConflicts() (map[string][]string, error) {
|
||||
conflicts := make(map[string][]string)
|
||||
installedPackages, err := GetInstalledPackages(operation.RootDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allPackages := make([]*PackageInfo, len(installedPackages))
|
||||
for i, value := range installedPackages {
|
||||
bpmpkg := GetPackage(value, operation.RootDir)
|
||||
if bpmpkg == nil {
|
||||
return nil, errors.New(fmt.Sprintf("could not find installed package (%s)", value))
|
||||
}
|
||||
allPackages[i] = bpmpkg.PkgInfo
|
||||
}
|
||||
|
||||
// Add all new packages to the allPackages slice
|
||||
for _, value := range slices.Clone(operation.Actions) {
|
||||
if value.GetActionType() == "install" {
|
||||
action := value.(*InstallPackageAction)
|
||||
pkgInfo := action.BpmPackage.PkgInfo
|
||||
allPackages = append(allPackages, pkgInfo)
|
||||
} else if value.GetActionType() == "fetch" {
|
||||
action := value.(*FetchPackageAction)
|
||||
pkgInfo := action.RepositoryEntry.Info
|
||||
allPackages = append(allPackages, pkgInfo)
|
||||
} else if value.GetActionType() == "remove" {
|
||||
action := value.(*RemovePackageAction)
|
||||
pkgInfo := action.BpmPackage.PkgInfo
|
||||
for i := len(allPackages) - 1; i >= 0; i-- {
|
||||
info := allPackages[i]
|
||||
if info.Name == pkgInfo.Name {
|
||||
allPackages = append(allPackages[:i], allPackages[i+1:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range allPackages {
|
||||
for _, conflict := range value.Conflicts {
|
||||
if slices.ContainsFunc(allPackages, func(info *PackageInfo) bool {
|
||||
return info.Name == conflict
|
||||
}) {
|
||||
conflicts[value.Name] = append(conflicts[value.Name], conflict)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conflicts, nil
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) ShowOperationSummary() {
|
||||
if len(operation.Actions) == 0 {
|
||||
fmt.Println("All packages are up to date!")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
for _, value := range operation.Actions {
|
||||
var pkgInfo *PackageInfo
|
||||
if value.GetActionType() == "install" {
|
||||
pkgInfo = value.(*InstallPackageAction).BpmPackage.PkgInfo
|
||||
} else if value.GetActionType() == "fetch" {
|
||||
pkgInfo = value.(*FetchPackageAction).RepositoryEntry.Info
|
||||
} else {
|
||||
pkgInfo = value.(*RemovePackageAction).BpmPackage.PkgInfo
|
||||
fmt.Printf("%s: %s (Remove)\n", pkgInfo.Name, pkgInfo.GetFullVersion())
|
||||
continue
|
||||
}
|
||||
|
||||
installedInfo := GetPackageInfo(pkgInfo.Name, operation.RootDir)
|
||||
sourceInfo := ""
|
||||
if pkgInfo.Type == "source" {
|
||||
if operation.RootDir != "/" {
|
||||
log.Fatalf("cannot compile and install source packages to a different root directory")
|
||||
}
|
||||
sourceInfo = "(From Source)"
|
||||
}
|
||||
|
||||
if installedInfo == nil {
|
||||
fmt.Printf("%s: %s (Install) %s\n", pkgInfo.Name, pkgInfo.GetFullVersion(), sourceInfo)
|
||||
} else {
|
||||
comparison := ComparePackageVersions(*pkgInfo, *installedInfo)
|
||||
if comparison < 0 {
|
||||
fmt.Printf("%s: %s -> %s (Downgrade) %s\n", pkgInfo.Name, installedInfo.GetFullVersion(), pkgInfo.GetFullVersion(), sourceInfo)
|
||||
} else if comparison > 0 {
|
||||
fmt.Printf("%s: %s -> %s (Upgrade) %s\n", pkgInfo.Name, installedInfo.GetFullVersion(), pkgInfo.GetFullVersion(), sourceInfo)
|
||||
} else {
|
||||
fmt.Printf("%s: %s (Reinstall) %s\n", pkgInfo.Name, pkgInfo.GetFullVersion(), sourceInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if operation.RootDir != "/" {
|
||||
fmt.Println("Warning: Operating in " + operation.RootDir)
|
||||
}
|
||||
if operation.GetTotalDownloadSize() > 0 {
|
||||
fmt.Printf("%s will be downloaded to complete this operation\n", UnsignedBytesToHumanReadable(operation.GetTotalDownloadSize()))
|
||||
}
|
||||
if operation.GetFinalActionSize(operation.RootDir) > 0 {
|
||||
fmt.Printf("A total of %s will be installed after the operation finishes\n", BytesToHumanReadable(operation.GetFinalActionSize(operation.RootDir)))
|
||||
} else if operation.GetFinalActionSize(operation.RootDir) < 0 {
|
||||
fmt.Printf("A total of %s will be freed after the operation finishes\n", strings.TrimPrefix(BytesToHumanReadable(operation.GetFinalActionSize(operation.RootDir)), "-"))
|
||||
}
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) RunHooks(verbose bool) error {
|
||||
// Get directory entries in hooks directory
|
||||
dirEntries, err := os.ReadDir(path.Join(operation.RootDir, "var/lib/bpm/hooks"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Find all hooks, validate and execute them
|
||||
for _, entry := range dirEntries {
|
||||
if entry.Type().IsRegular() && strings.HasSuffix(entry.Name(), ".bpmhook") {
|
||||
hook, err := CreateHook(path.Join(operation.RootDir, "var/lib/bpm/hooks", entry.Name()))
|
||||
if err != nil {
|
||||
log.Printf("Error while reading hook (%s): %s", entry.Name(), err)
|
||||
}
|
||||
|
||||
err = hook.Execute(operation.Changes, verbose, operation.RootDir)
|
||||
if err != nil {
|
||||
log.Printf("Warning: could not execute hook (%s): %s\n", entry.Name(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (operation *BPMOperation) Execute(verbose, force bool) error {
|
||||
// Fetch packages from repositories
|
||||
if slices.ContainsFunc(operation.Actions, func(action OperationAction) bool {
|
||||
return action.GetActionType() == "fetch"
|
||||
}) {
|
||||
fmt.Println("Fetching packages from available repositories...")
|
||||
for i, action := range operation.Actions {
|
||||
if action.GetActionType() != "fetch" {
|
||||
continue
|
||||
}
|
||||
entry := action.(*FetchPackageAction).RepositoryEntry
|
||||
fetchedPackage, err := entry.Repository.FetchPackage(entry.Info.Name)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not fetch package (%s): %s\n", entry.Info.Name, err))
|
||||
}
|
||||
bpmpkg, err := ReadPackage(fetchedPackage)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not fetch package (%s): %s\n", entry.Info.Name, err))
|
||||
}
|
||||
fmt.Printf("Package (%s) was successfully fetched!\n", bpmpkg.PkgInfo.Name)
|
||||
operation.Actions[i] = &InstallPackageAction{
|
||||
File: fetchedPackage,
|
||||
IsDependency: action.(*FetchPackageAction).IsDependency,
|
||||
BpmPackage: bpmpkg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine words to be used for the following message
|
||||
words := make([]string, 0)
|
||||
if slices.ContainsFunc(operation.Actions, func(action OperationAction) bool {
|
||||
return action.GetActionType() == "install"
|
||||
}) {
|
||||
words = append(words, "Installing")
|
||||
}
|
||||
|
||||
if slices.ContainsFunc(operation.Actions, func(action OperationAction) bool {
|
||||
return action.GetActionType() == "remove"
|
||||
}) {
|
||||
words = append(words, "Removing")
|
||||
}
|
||||
|
||||
if len(words) == 0 {
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%s packages...\n", strings.Join(words, "/"))
|
||||
|
||||
// Installing/Removing packages from system
|
||||
for _, action := range operation.Actions {
|
||||
if action.GetActionType() == "remove" {
|
||||
pkgInfo := action.(*RemovePackageAction).BpmPackage.PkgInfo
|
||||
err := RemovePackage(pkgInfo.Name, verbose, operation.RootDir)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not remove package (%s): %s\n", pkgInfo.Name, err))
|
||||
}
|
||||
} else if action.GetActionType() == "install" {
|
||||
value := action.(*InstallPackageAction)
|
||||
bpmpkg := value.BpmPackage
|
||||
isReinstall := IsPackageInstalled(bpmpkg.PkgInfo.Name, operation.RootDir)
|
||||
var err error
|
||||
if value.IsDependency {
|
||||
err = InstallPackage(value.File, operation.RootDir, verbose, true, false, false, false)
|
||||
} else {
|
||||
err = InstallPackage(value.File, operation.RootDir, verbose, force, false, false, false)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not install package (%s): %s\n", bpmpkg.PkgInfo.Name, err))
|
||||
}
|
||||
if operation.ForceInstallationReason != Unknown && !value.IsDependency {
|
||||
err := SetInstallationReason(bpmpkg.PkgInfo.Name, operation.ForceInstallationReason, operation.RootDir)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not set installation reason for package (%s): %s\n", value.BpmPackage.PkgInfo.Name, err))
|
||||
}
|
||||
} else if value.IsDependency && !isReinstall {
|
||||
err := SetInstallationReason(bpmpkg.PkgInfo.Name, Dependency, operation.RootDir)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("could not set installation reason for package (%s): %s\n", value.BpmPackage.PkgInfo.Name, err))
|
||||
}
|
||||
}
|
||||
fmt.Printf("Package (%s) was successfully installed\n", bpmpkg.PkgInfo.Name)
|
||||
}
|
||||
}
|
||||
fmt.Println("Operation complete!")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type OperationAction interface {
|
||||
GetActionType() string
|
||||
}
|
||||
|
||||
type InstallPackageAction struct {
|
||||
File string
|
||||
IsDependency bool
|
||||
BpmPackage *BPMPackage
|
||||
}
|
||||
|
||||
func (action *InstallPackageAction) GetActionType() string {
|
||||
return "install"
|
||||
}
|
||||
|
||||
type FetchPackageAction struct {
|
||||
IsDependency bool
|
||||
RepositoryEntry *RepositoryEntry
|
||||
}
|
||||
|
||||
func (action *FetchPackageAction) GetActionType() string {
|
||||
return "fetch"
|
||||
}
|
||||
|
||||
type RemovePackageAction struct {
|
||||
BpmPackage *BPMPackage
|
||||
}
|
||||
|
||||
func (action *RemovePackageAction) GetActionType() string {
|
||||
return "remove"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,204 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gopkg.in/yaml.v3"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
Name string `yaml:"name"`
|
||||
Source string `yaml:"source"`
|
||||
Disabled *bool `yaml:"disabled"`
|
||||
Entries map[string]*RepositoryEntry
|
||||
VirtualPackages map[string][]string
|
||||
}
|
||||
|
||||
type RepositoryEntry struct {
|
||||
Info *PackageInfo `yaml:"info"`
|
||||
Download string `yaml:"download"`
|
||||
DownloadSize uint64 `yaml:"download_size"`
|
||||
InstalledSize uint64 `yaml:"installed_size"`
|
||||
Repository *Repository
|
||||
}
|
||||
|
||||
func (repo *Repository) ContainsPackage(pkg string) bool {
|
||||
_, ok := repo.Entries[pkg]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (repo *Repository) ReadLocalDatabase() error {
|
||||
repoFile := "/var/lib/bpm/repositories/" + repo.Name + ".bpmdb"
|
||||
if _, err := os.Stat(repoFile); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
bytes, err := os.ReadFile(repoFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data := string(bytes)
|
||||
for _, b := range strings.Split(data, "---") {
|
||||
entry := RepositoryEntry{
|
||||
Info: &PackageInfo{
|
||||
Name: "",
|
||||
Description: "",
|
||||
Version: "",
|
||||
Revision: 1,
|
||||
Url: "",
|
||||
License: "",
|
||||
Arch: "",
|
||||
Type: "",
|
||||
Keep: make([]string, 0),
|
||||
Depends: make([]string, 0),
|
||||
MakeDepends: make([]string, 0),
|
||||
OptionalDepends: make([]string, 0),
|
||||
Conflicts: make([]string, 0),
|
||||
Provides: make([]string, 0),
|
||||
},
|
||||
Download: "",
|
||||
DownloadSize: 0,
|
||||
InstalledSize: 0,
|
||||
Repository: repo,
|
||||
}
|
||||
err := yaml.Unmarshal([]byte(b), &entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, p := range entry.Info.Provides {
|
||||
repo.VirtualPackages[p] = append(repo.VirtualPackages[p], entry.Info.Name)
|
||||
}
|
||||
repo.Entries[entry.Info.Name] = &entry
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repo *Repository) SyncLocalDatabase() error {
|
||||
repoFile := "/var/lib/bpm/repositories/" + repo.Name + ".bpmdb"
|
||||
err := os.MkdirAll(path.Dir(repoFile), 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u, err := url.JoinPath(repo.Source, "database.bpmdb")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := http.Get(u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
out, err := os.Create(repoFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetRepository(name string) *Repository {
|
||||
for _, repo := range BPMConfig.Repositories {
|
||||
if repo.Name == name {
|
||||
return repo
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetRepositoryEntry(str string) (*RepositoryEntry, *Repository, error) {
|
||||
split := strings.Split(str, "/")
|
||||
if len(split) == 1 {
|
||||
pkgName := strings.TrimSpace(split[0])
|
||||
if pkgName == "" {
|
||||
return nil, nil, errors.New("could not find repository entry for this package")
|
||||
}
|
||||
for _, repo := range BPMConfig.Repositories {
|
||||
if repo.ContainsPackage(pkgName) {
|
||||
return repo.Entries[pkgName], repo, nil
|
||||
}
|
||||
}
|
||||
return nil, nil, errors.New("could not find repository entry for this package")
|
||||
} else if len(split) == 2 {
|
||||
repoName := strings.TrimSpace(split[0])
|
||||
pkgName := strings.TrimSpace(split[1])
|
||||
if repoName == "" || pkgName == "" {
|
||||
return nil, nil, errors.New("could not find repository entry for this package")
|
||||
}
|
||||
repo := GetRepository(repoName)
|
||||
if repo == nil || !repo.ContainsPackage(pkgName) {
|
||||
return nil, nil, errors.New("could not find repository entry for this package")
|
||||
}
|
||||
return repo.Entries[pkgName], repo, nil
|
||||
} else {
|
||||
return nil, nil, errors.New("could not find repository entry for this package")
|
||||
}
|
||||
}
|
||||
|
||||
func FindReplacement(pkg string) *RepositoryEntry {
|
||||
for _, repo := range BPMConfig.Repositories {
|
||||
for _, entry := range repo.Entries {
|
||||
for _, replaced := range entry.Info.Replaces {
|
||||
if replaced == pkg {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ResolveVirtualPackage(vpkg string) *RepositoryEntry {
|
||||
for _, repo := range BPMConfig.Repositories {
|
||||
if v, ok := repo.VirtualPackages[vpkg]; ok {
|
||||
for _, pkg := range v {
|
||||
return repo.Entries[pkg]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repo *Repository) FetchPackage(pkg string) (string, error) {
|
||||
if !repo.ContainsPackage(pkg) {
|
||||
return "", errors.New("could not fetch package '" + pkg + "'")
|
||||
}
|
||||
entry := repo.Entries[pkg]
|
||||
URL, err := url.JoinPath(repo.Source, entry.Download)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := http.Get(URL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
err = os.MkdirAll("/var/cache/bpm/packages/", 0755)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out, err := os.Create("/var/cache/bpm/packages/" + path.Base(entry.Download))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return "/var/cache/bpm/packages/" + path.Base(entry.Download), nil
|
||||
}
|
||||
Reference in New Issue
Block a user