mirror of
https://github.com/89luca89/distrobox.git
synced 2026-08-19 01:14:49 -05:00
refactor(cli): rename and move root validation
This commit is contained in:
committed by
Emanuele De Cupis
parent
a5c4373c86
commit
5ddceca6b0
+2
-15
@@ -5,10 +5,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"github.com/89luca89/distrobox/internal/rootful"
|
||||
"github.com/89luca89/distrobox/pkg/config"
|
||||
"github.com/89luca89/distrobox/pkg/containermanager"
|
||||
"github.com/89luca89/distrobox/pkg/containermanager/providers"
|
||||
@@ -55,19 +55,6 @@ func printInvalidContainerManager(p *ui.Printer, containerManagerType string) {
|
||||
p.Println("The available choices are: 'autodetect', 'podman', 'podman-launcher', 'docker'")
|
||||
}
|
||||
|
||||
func validateSudo(ctx context.Context) error {
|
||||
cmd := exec.CommandContext(ctx, "sudo", "-v")
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("failed to validate sudo: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func subcommands(cfg *config.Values) []*cli.Command {
|
||||
return []*cli.Command{
|
||||
composeCommand(
|
||||
@@ -152,7 +139,7 @@ func withRoot(_ *config.Values, cmd *cli.Command) *cli.Command {
|
||||
}
|
||||
}
|
||||
if c.Bool("root") {
|
||||
if err := validateSudo(ctx); err != nil {
|
||||
if err := rootful.Validate(ctx); err != nil {
|
||||
return nil, fmt.Errorf("cannot run in root mode: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Package rootful provides utilities for running operations that require
|
||||
// root privileges via sudo.
|
||||
package rootful
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals // singleton: process-wide memoization is the intent
|
||||
var (
|
||||
validateOnce sync.Once
|
||||
errValidate error
|
||||
)
|
||||
|
||||
// Validate ensures that sudo is available and the user can elevate.
|
||||
// It runs `sudo -v` at most once per process: the first call performs the
|
||||
// check and caches the result; subsequent calls return the cached result
|
||||
// without re-running the command.
|
||||
func Validate(ctx context.Context) error {
|
||||
validateOnce.Do(func() {
|
||||
cmd := exec.CommandContext(ctx, "sudo", "-v")
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
errValidate = fmt.Errorf("failed to validate sudo: %w", err)
|
||||
}
|
||||
})
|
||||
return errValidate
|
||||
}
|
||||
Reference in New Issue
Block a user