Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make env decoupled + add CI support #24

Merged
merged 4 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ ublue-upd
output/*
*.key
*.private
*.log
59 changes: 54 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ package cmd
import (
"fmt"
"log"
"log/slog"
"os"
"os/user"
"path"
"path/filepath"

"github.com/spf13/cobra"
appLogging "github.com/ublue-os/uupd/pkg/logging"
"golang.org/x/term"
)

Expand All @@ -23,10 +27,11 @@ func assertRoot(cmd *cobra.Command, args []string) {

var (
rootCmd = &cobra.Command{
Use: "uupd",
Short: "uupd (Universal Update) is the successor to ublue-update, built for bootc",
PreRun: assertRoot,
Run: Update,
Use: "uupd",
Short: "uupd (Universal Update) is the successor to ublue-update, built for bootc",
PersistentPreRunE: initLogging,
PreRun: assertRoot,
Run: Update,
}

waitCmd = &cobra.Command{
Expand Down Expand Up @@ -56,6 +61,10 @@ var (
PreRun: assertRoot,
Run: ImageOutdated,
}

fLogFile string
fLogLevel string
fNoLogging bool
)

func Execute() {
Expand All @@ -65,14 +74,54 @@ func Execute() {
}
}

func initLogging(cmd *cobra.Command, args []string) error {
var logWriter *os.File = os.Stdout
if fLogFile != "-" {
abs, err := filepath.Abs(path.Clean(fLogFile))
if err != nil {
return err
}
logWriter, err = os.OpenFile(abs, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
if err != nil {
return err
}
}

logLevel, err := appLogging.StrToLogLevel(fLogLevel)
if err != nil {
return err
}

main_app_logger := slog.New(appLogging.SetupAppLogger(logWriter, logLevel, fLogFile != "-"))

if fNoLogging {
slog.SetDefault(appLogging.NewMuteLogger())
} else {
slog.SetDefault(main_app_logger)
}
return nil
}

func init() {
rootCmd.AddCommand(waitCmd)
rootCmd.AddCommand(updateCheckCmd)
rootCmd.AddCommand(hardwareCheckCmd)
rootCmd.AddCommand(imageOutdatedCmd)
interactiveProgress := true
if fLogFile != "-" {
interactiveProgress = false
}
isTerminal := term.IsTerminal(int(os.Stdout.Fd()))
rootCmd.Flags().BoolP("no-progress", "p", !isTerminal, "Do not show progress bars")
if !isTerminal {
interactiveProgress = false
}
rootCmd.Flags().BoolP("no-progress", "p", interactiveProgress, "Do not show progress bars")
rootCmd.Flags().BoolP("hw-check", "c", false, "Run hardware check before running updates")
rootCmd.Flags().BoolP("dry-run", "n", false, "Do a dry run")
rootCmd.Flags().BoolP("verbose", "v", false, "Display command outputs after run")
rootCmd.Flags().Bool("ci", false, "Makes some modifications to behavior if is running in CI")

rootCmd.PersistentFlags().StringVar(&fLogFile, "log-file", "-", "File where user-facing logs will be written to")
rootCmd.PersistentFlags().StringVar(&fLogLevel, "log-level", "info", "Log level for user-facing logs")
rootCmd.PersistentFlags().BoolVar(&fNoLogging, "quiet", false, "Make logs quiet")
}
90 changes: 48 additions & 42 deletions cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,71 +2,81 @@ package cmd

import (
"fmt"
"log"
"log/slog"
"os"

"github.com/jedib0t/go-pretty/v6/progress"
"github.com/spf13/cobra"
"github.com/ublue-os/uupd/checks"
"github.com/ublue-os/uupd/drv"
"github.com/ublue-os/uupd/lib"
"gopkg.in/yaml.v3"
)

func Update(cmd *cobra.Command, args []string) {
lock, err := lib.AcquireLock()
if err != nil {
log.Fatalf("%v, is uupd already running?", err)
slog.Error(fmt.Sprintf("%v, is uupd already running?", err))
return
}
defer lib.ReleaseLock(lock)

hwCheck, err := cmd.Flags().GetBool("hw-check")
if err != nil {
log.Fatalf("Failed to get hw-check flag: %v", err)
slog.Error("Failed to get hw-check flag", "error", err)
return
}
dryRun, err := cmd.Flags().GetBool("dry-run")
if err != nil {
log.Fatalf("Failed to get dry-run flag: %v", err)
slog.Error("Failed to get dry-run flag", "error", err)
return
}
verboseRun, err := cmd.Flags().GetBool("verbose")
if err != nil {
log.Fatalf("Failed to get verbose flag: %v", err)
slog.Error("Failed to get verbose flag", "error", err)
return
}

if hwCheck {
err := checks.RunHwChecks()
if err != nil {
log.Fatalf("Hardware checks failed: %v", err)
slog.Error("Hardware checks failed", "error", err)
return
}
log.Println("Hardware checks passed")
slog.Info("Hardware checks passed")
}

users, err := lib.ListUsers()
if err != nil {
log.Fatalf("Failed to list users")
slog.Error("Failed to list users", "users", users)
return
}

systemUpdater, err := drv.SystemUpdater{}.New(dryRun)
initConfiguration := drv.UpdaterInitConfiguration{}.New()
_, empty := os.LookupEnv("CI")
initConfiguration.Ci = !empty
initConfiguration.DryRun = dryRun
initConfiguration.Verbose = verboseRun

systemUpdater, err := drv.SystemUpdater{}.New(*initConfiguration)
if err != nil {
systemUpdater.Config.Enabled = false
} else {
systemUpdater.Check()
enableUpd, err := systemUpdater.Check()
if err != nil {
slog.Error("Failed checking for updates")
}
systemUpdater.Config.Enabled = enableUpd
}

brewUpdater, err := drv.BrewUpdater{}.New(dryRun)
if err != nil {
brewUpdater.Config.Enabled = false
}
brewUpdater, err := drv.BrewUpdater{}.New(*initConfiguration)
brewUpdater.Config.Enabled = err == nil

flatpakUpdater, err := drv.FlatpakUpdater{}.New(dryRun)
if err != nil {
flatpakUpdater.Config.Enabled = false
}
flatpakUpdater, err := drv.FlatpakUpdater{}.New(*initConfiguration)
flatpakUpdater.Config.Enabled = err == nil
flatpakUpdater.SetUsers(users)

distroboxUpdater, err := drv.DistroboxUpdater{}.New(dryRun)
if err != nil {
distroboxUpdater.Config.Enabled = false
}
distroboxUpdater, err := drv.DistroboxUpdater{}.New(*initConfiguration)
distroboxUpdater.Config.Enabled = err == nil
distroboxUpdater.SetUsers(users)

totalSteps := brewUpdater.Steps() + systemUpdater.Steps() + flatpakUpdater.Steps() + distroboxUpdater.Steps()
Expand All @@ -76,7 +86,8 @@ func Update(cmd *cobra.Command, args []string) {

progressEnabled, err := cmd.Flags().GetBool("no-progress")
if err != nil {
log.Fatalf("Failed to get no-progress flag: %v", err)
slog.Error("Failed to get no-progress flag", "error", err)
return
}
// Move this to its actual boolean value (~no-progress)
progressEnabled = !progressEnabled
Expand All @@ -100,19 +111,20 @@ func Update(cmd *cobra.Command, args []string) {
var outputs = []drv.CommandOutput{}

if systemUpdater.Outdated {
lib.Notify("System Warning", "There hasn't been an update in over a month. Consider rebooting or running updates manually")
log.Printf("There hasn't been an update in over a month. Consider rebooting or running updates manually")
const OUTDATED_WARNING = "There hasn't been an update in over a month. Consider rebooting or running updates manually"
lib.Notify("System Warning", OUTDATED_WARNING)
slog.Warn(OUTDATED_WARNING)
}

if systemUpdater.Config.Enabled {
lib.ChangeTrackerMessageFancy(pw, tracker, progressEnabled, fmt.Sprintf("Updating %s (%s)", systemUpdater.Config.Description, systemUpdater.Config.Title))
lib.ChangeTrackerMessageFancy(pw, tracker, progressEnabled, lib.TrackerMessage{Title: systemUpdater.Config.Title, Description: systemUpdater.Config.Description})
out, err := systemUpdater.Update()
outputs = append(outputs, *out...)
tracker.IncrementSection(err)
}

if brewUpdater.Config.Enabled {
lib.ChangeTrackerMessageFancy(pw, tracker, progressEnabled, fmt.Sprintf("Updating %s (%s)", brewUpdater.Config.Description, brewUpdater.Config.Title))
lib.ChangeTrackerMessageFancy(pw, tracker, progressEnabled, lib.TrackerMessage{Title: brewUpdater.Config.Title, Description: brewUpdater.Config.Description})
out, err := brewUpdater.Update()
outputs = append(outputs, *out...)
tracker.IncrementSection(err)
Expand All @@ -131,16 +143,13 @@ func Update(cmd *cobra.Command, args []string) {
}

pw.Stop()

if verboseRun {
log.Println("Verbose run requested")
slog.Info("Verbose run requested")

b, err := yaml.Marshal(outputs)
if err != nil {
log.Fatalf("Failure!")
return
for _, output := range outputs {
slog.Info("CommandOutput", slog.String("context", output.Context), slog.String("stdout", output.Stdout), slog.Any("stderr", output.Stderr))
}
log.Printf("%s", string(b))

return
}

Expand All @@ -152,17 +161,14 @@ func Update(cmd *cobra.Command, args []string) {
}

if len(failures) > 0 {
log.Println("Exited with failed updates.\nFailures found:")
slog.Warn("Exited with failed updates.")

b, err := yaml.Marshal(failures)
if err != nil {
log.Fatalf("Failure!")
return
for _, output := range failures {
slog.Info("CommandOutput", slog.String("context", output.Context), slog.String("stdout", output.Stdout), slog.Any("stderr", output.Stderr))
}
log.Printf("%s", string(b))

return
}

log.Printf("Updates Completed")
slog.Info("Updates Completed Successfully")
}
24 changes: 17 additions & 7 deletions drv/brew.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,24 @@ type BrewUpdater struct {
Environment map[string]string
}

func (up BrewUpdater) New(dryrun bool) (BrewUpdater, error) {
// TODO: add support for actual environment variables to override this
var (
func (up BrewUpdater) New(config UpdaterInitConfiguration) (BrewUpdater, error) {
brewPrefix, empty := os.LookupEnv("HOMEBREW_PREFIX")
if empty || brewPrefix == "" {
brewPrefix = "/home/linuxbrew/.linuxbrew"
}
brewRepo, empty := os.LookupEnv("HOMEBREW_REPOSITORY")
if empty || brewRepo == "" {
brewRepo = fmt.Sprintf("%s/Homebrew", brewPrefix)
}
brewCellar, empty := os.LookupEnv("HOMEBREW_CELLAR")
if empty || brewCellar == "" {
brewCellar = fmt.Sprintf("%s/Cellar", brewPrefix)
brewRepo = fmt.Sprintf("%s/Homebrew", brewPrefix)
brewPath = fmt.Sprintf("%s/bin/brew", brewPrefix)
)
}
brewPath, empty := os.LookupEnv("HOMEBREW_PATH")
if empty || brewPath == "" {
brewPath = fmt.Sprintf("%s/bin/brew", brewPrefix)
}

up.Environment = map[string]string{
"HOMEBREW_PREFIX": brewPrefix,
"HOMEBREW_REPOSITORY": brewRepo,
Expand All @@ -84,7 +94,7 @@ func (up BrewUpdater) New(dryrun bool) (BrewUpdater, error) {
Description: "CLI Apps",
Enabled: true,
MultiUser: false,
DryRun: dryrun,
DryRun: config.DryRun,
}

if up.Config.DryRun {
Expand Down
23 changes: 15 additions & 8 deletions drv/distrobox.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,25 @@ type DistroboxUpdater struct {
}

func (up DistroboxUpdater) Steps() int {
return (1 + len(up.users))
if up.Config.Enabled {
var steps = 1
if up.usersEnabled {
steps += len(up.users)
}
return steps
}
return 0
}

func (up DistroboxUpdater) New(dryrun bool) (DistroboxUpdater, error) {
func (up DistroboxUpdater) New(initconfig UpdaterInitConfiguration) (DistroboxUpdater, error) {
userdesc := "Distroboxes for User:"
up.Config = DriverConfiguration{
Title: "Distrobox",
Description: "Rootful Distroboxes",
UserDescription: &userdesc,
Enabled: true,
MultiUser: true,
DryRun: dryrun,
DryRun: initconfig.DryRun,
}
up.usersEnabled = false
up.Tracker = nil
Expand All @@ -47,19 +54,19 @@ func (up *DistroboxUpdater) Update() (*[]CommandOutput, error) {
var finalOutput = []CommandOutput{}

if up.Config.DryRun {
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, fmt.Sprintf("Updating %s (%s)", up.Config.Description, up.Config.Title))
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, lib.TrackerMessage{Title: up.Config.Title, Description: up.Config.Description})
up.Tracker.Tracker.IncrementSection(nil)

var err error = nil
for _, user := range up.users {
up.Tracker.Tracker.IncrementSection(err)
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, fmt.Sprintf("Updating %s %s (%s)", *up.Config.UserDescription, user.Name, up.Config.Title))
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, lib.TrackerMessage{Title: up.Config.Title, Description: *up.Config.UserDescription + " " + user.Name})
}
return &finalOutput, nil
}

// TODO: add env support for Flatpak and Distrobox updaters
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, fmt.Sprintf("Updating %s (%s)", up.Config.Description, up.Config.Title))
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, lib.TrackerMessage{Title: up.Config.Title, Description: up.Config.Description})
flatpakCmd := exec.Command("/usr/bin/distrobox", "upgrade", "-a")
out, err := flatpakCmd.CombinedOutput()
tmpout := CommandOutput{}.New(out, err)
Expand All @@ -71,8 +78,8 @@ func (up *DistroboxUpdater) Update() (*[]CommandOutput, error) {
err = nil
for _, user := range up.users {
up.Tracker.Tracker.IncrementSection(err)
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, fmt.Sprintf("Updating %s %s (%s)", *up.Config.UserDescription, user.Name, up.Config.Title))
out, err := lib.RunUID(user.UID, []string{"/usr/bin/flatpak", "update", "-y"}, nil)
lib.ChangeTrackerMessageFancy(*up.Tracker.Writer, up.Tracker.Tracker, up.Tracker.Progress, lib.TrackerMessage{Title: up.Config.Title, Description: *up.Config.UserDescription + " " + user.Name})
out, err := lib.RunUID(user.UID, []string{"/usr/bin/distrobox", "upgrade", "-a"}, nil)
tmpout = CommandOutput{}.New(out, err)
if err != nil {
tmpout.SetFailureContext(fmt.Sprintf("Distroboxes for User: %s", user.Name))
Expand Down
Loading