Skip to content

Commit

Permalink
feat: snaps can be declared as absent
Browse files Browse the repository at this point in the history
  • Loading branch information
femnad committed Dec 27, 2023
1 parent 2460578 commit cf815b3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
1 change: 1 addition & 0 deletions entity/snap.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package entity

type Snap struct {
Absent bool `yaml:"absent"`
Name string `yaml:"name"`
Classic bool `yaml:"classic"`
}
3 changes: 2 additions & 1 deletion internal/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ func maybeWarnPasswordRequired(cmdStr string) {
return
}

Log.Warningf("Sudo authentication required for escalating privileges to run command %s", cmdStr)
cmdHead := strings.Split(cmdStr, " ")[0]
Log.Warningf("Sudo authentication required for escalating privileges to run command %s", cmdHead)
}

func MaybeRunWithSudo(cmdStr string) error {
Expand Down
34 changes: 30 additions & 4 deletions provision/snap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ import (
"github.com/femnad/fup/common"
"github.com/femnad/fup/entity"
"github.com/femnad/fup/internal"
marecmd "github.com/femnad/mare/cmd"
)

func isSnapInstalled(snap entity.Snap) bool {
out, _ := marecmd.RunFormatError(marecmd.Input{Command: fmt.Sprintf("snap list %s", snap.Name)})
return out.Code == 0
}

func installSnap(snap entity.Snap) error {
err := internal.Run(fmt.Sprintf("snap list %s", snap.Name))
if err == nil {
if isSnapInstalled(snap) {
return nil
}

Expand All @@ -22,7 +27,7 @@ func installSnap(snap entity.Snap) error {
cmd += " --classic"
}

err = internal.MaybeRunWithSudo(cmd)
err := internal.MaybeRunWithSudo(cmd)
if err != nil {
internal.Log.Errorf("error installing snap %s: %v", snap.Name, err)
return err
Expand All @@ -31,6 +36,23 @@ func installSnap(snap entity.Snap) error {
return nil
}

func uninstallSnap(snap entity.Snap) error {
if !isSnapInstalled(snap) {
return nil
}

internal.Log.Infof("Uninstalling snap %s", snap.Name)
cmd := fmt.Sprintf("snap remove %s", snap.Name)

err := internal.MaybeRunWithSudo(cmd)
if err != nil {
internal.Log.Errorf("error uninstalling snap %s: %v", snap.Name, err)
return err
}

return nil
}

func snapInstall(config base.Config) error {
_, err := common.Which("snap")
if err != nil {
Expand All @@ -40,7 +62,11 @@ func snapInstall(config base.Config) error {

var snapErr []error
for _, snap := range config.SnapPackages {
err = installSnap(snap)
if snap.Absent {
err = uninstallSnap(snap)
} else {
err = installSnap(snap)
}
snapErr = append(snapErr, err)
}

Expand Down

0 comments on commit cf815b3

Please sign in to comment.