system_setup_tool/internal/utils/utils.go

80 lines
1.6 KiB
Go

package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/charmbracelet/huh"
)
func GetSudoPassword() (string, error) {
var password string
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Enter your password").
EchoMode(huh.EchoModePassword).
Value(&password),
),
).WithTheme(huh.ThemeCatppuccin())
err := form.Run()
if err != nil {
return "", fmt.Errorf("error at password-dialog: %v", err)
}
return password, nil
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
const (
maxHistoryLines = 2000
historyFileName = "sst_history"
)
func LogToHistory(action, pkg, manager string) error {
dirname, err := os.UserConfigDir()
if err != nil {
return fmt.Errorf("cant obtain config dir: %v", err)
}
historyFile := filepath.Join(dirname, "sst", historyFileName)
lines, err := readHistoryLines(historyFile)
if err != nil {
return err
}
timestamp := time.Now().Format("2006-01-02 15:04:05")
logEntry := fmt.Sprintf("%s: action: [%s] - package: [%s] - packagemanager: [%s]", timestamp, action, pkg, manager)
lines = append(lines, logEntry)
if len(lines) > maxHistoryLines {
lines = lines[len(lines)-maxHistoryLines:]
}
return writeHistoryLines(historyFile, lines)
}
func readHistoryLines(filePath string) ([]string, error) {
content, err := os.ReadFile(filePath)
if err != nil {
if os.IsNotExist(err) {
return []string{}, nil
}
return nil, err
}
return strings.Split(string(content), "\n"), nil
}
func writeHistoryLines(filePath string, lines []string) error {
content := strings.Join(lines, "\n")
return os.WriteFile(filePath, []byte(content), 0644)
}