mirror of
https://github.com/Valkyrie00/bold-brew.git
synced 2026-03-14 14:25:53 +01:00
* refactor(services): split brew.go into focused modules Reorganize the services package for better maintainability: - brew.go: Interface and struct definitions - data.go: Data loading, caching, and tap package management - cache.go: Low-level cache I/O helpers - packages.go: Package retrieval (GetFormulae, GetPackages) - operations.go: Package operations (install, update, remove) - parser.go: Brewfile parsing - brewfile.go: Brewfile-specific app logic (extracted from app.go) This reduces the largest file from 1124 to 322 lines and improves separation of concerns across the codebase. * refactor(services): introduce DataProvider pattern for data loading Extract data loading logic into a dedicated DataProvider service that handles all data retrieval operations (formulae, casks, analytics, cache). BrewService now delegates to DataProvider via interface for better testability and separation of concerns. Also centralizes cache file name constants in dataprovider.go for maintainability. * refactor(services): centralize data in DataProvider and improve naming consistency Move all data-related fields and retrieval methods from BrewService to DataProvider, making BrewService focused solely on brew operations. Rename formula fields (all, installed, remote, analytics) to be consistent with cask naming convention (allFormulae, installedFormulae, etc.). Remove redundant data.go and packages.go files. * refactor(services): consolidate code and fix shared dependencies - IOService now receives BrewService as parameter instead of creating new instance - Move API URL constants from brew.go to dataprovider.go (now private) - Move getCacheDir to cache.go where it belongs - Remove unused GetPrefixPath from BrewService interface - Consolidate Brewfile parsing into brewfile.go as standalone function - Delete parser.go (logic merged into brewfile.go) * fix(brewfile): prevent duplicate packages in list after refresh Add duplicate detection checks in loadBrewfilePackages to ensure each package appears only once in the Brewfile package list, even when refreshing after install/remove operations. * refactor(services): extract search methods to dedicated file Move search(), setResults(), and forceRefreshResults() from app.go to search.go for better code organization and separation of concerns. * refactor(services): remove dead code and unify helpers Remove unused methods and fields: - GetFormulae(), IsPackageInstalled() from DataProvider - InstallAllPackages(), RemoveAllPackages() from BrewService - allFormulae, allCasks fields from DataProvider Unify GetInstalledCaskNames and GetInstalledFormulaNames with a common getInstalledNames helper to reduce code duplication. * docs(brewfile): add package documentation with execution sequence Document Brewfile mode functionality including parsing, tap installation, and package loading. Add execution sequence diagram and note that methods are only active in Brewfile mode (bbrew -f <file>). * refactor(services): move fetchFromAPI to dataprovider Move HTTP fetch function from cache.go to dataprovider.go where it belongs semantically. cache.go now contains only cache I/O operations. * refactor(dataprovider): improve method naming consistency Rename Load* methods to Get* with forceRefresh parameter for clarity: - LoadInstalledFormulae → GetInstalledFormulae - LoadRemoteFormulae → GetRemoteFormulae - LoadTapPackages → GetTapPackages (and similar) Rename Get* methods that execute commands to Fetch* for accuracy: - GetInstalledCaskNames → FetchInstalledCaskNames - GetInstalledFormulaNames → FetchInstalledFormulaNames Replace forceDownload parameter with forceRefresh throughout. * refactor(input): rename io.go to input.go and simplify code Rename IOService/IOAction to InputService/InputAction for semantic correctness (io in Go refers to file I/O, not keyboard input). Simplify handleFilterEvent with helper methods: isFilterActive(), setFilterActive(), updateFilterUI() reducing ~30 lines of repetitive code. Extract handleBatchPackageOperation() helper for InstallAll/RemoveAll operations, reducing ~90 lines of duplicate code with a configurable batchOperation struct. * refactor(filters): replace 4 booleans with FilterType enum Replace showOnlyInstalled, showOnlyOutdated, showOnlyLeaves, showOnlyCasks with a single activeFilter field of type FilterType. Add FilterNone constant for no active filter state. Simplify handleFilterEvent to simple toggle logic. Extract applyFilter method with clean switch statement. Remove redundant isFilterActive and setFilterActive helpers. * refactor(brew): merge operations.go into brew.go Consolidate all BrewService methods into a single file. Add section comments to organize code into logical groups: - Core info (GetBrewVersion) - Package operations (Update/Install/Remove) - Tap support (InstallTap/IsTapInstalled) - Internal helpers (executeCommand) * fix(dataprovider): suppress gosec G107 false positive The URL passed to http.Get comes from internal constants (Homebrew API URLs), not from user input.
208 lines
5.5 KiB
Go
208 lines
5.5 KiB
Go
package services
|
|
|
|
import (
|
|
"bbrew/internal/models"
|
|
"fmt"
|
|
"io"
|
|
"os/exec"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/rivo/tview"
|
|
)
|
|
|
|
// BrewServiceInterface defines the contract for Homebrew operations.
|
|
// BrewService is a pure executor of brew commands - it does NOT hold data.
|
|
// For data retrieval, use DataProviderInterface.
|
|
type BrewServiceInterface interface {
|
|
// Core info
|
|
GetBrewVersion() (string, error)
|
|
|
|
// Package operations
|
|
UpdateHomebrew() error
|
|
UpdateAllPackages(app *tview.Application, outputView *tview.TextView) error
|
|
UpdatePackage(info models.Package, app *tview.Application, outputView *tview.TextView) error
|
|
RemovePackage(info models.Package, app *tview.Application, outputView *tview.TextView) error
|
|
InstallPackage(info models.Package, app *tview.Application, outputView *tview.TextView) error
|
|
|
|
// Tap support
|
|
InstallTap(tapName string, app *tview.Application, outputView *tview.TextView) error
|
|
IsTapInstalled(tapName string) bool
|
|
}
|
|
|
|
// BrewService provides methods to execute Homebrew commands.
|
|
// It is a pure executor - no data storage. Use DataProvider for data.
|
|
type BrewService struct {
|
|
brewVersion string
|
|
}
|
|
|
|
// NewBrewService creates a new instance of BrewService.
|
|
var NewBrewService = func() BrewServiceInterface {
|
|
return &BrewService{}
|
|
}
|
|
|
|
// GetBrewVersion retrieves the version of Homebrew installed on the system, caching it for future calls.
|
|
func (s *BrewService) GetBrewVersion() (string, error) {
|
|
if s.brewVersion != "" {
|
|
return s.brewVersion, nil
|
|
}
|
|
|
|
cmd := exec.Command("brew", "--version")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
s.brewVersion = strings.TrimSpace(string(output))
|
|
return s.brewVersion, nil
|
|
}
|
|
|
|
// UpdateHomebrew updates the Homebrew package manager by running the `brew update` command.
|
|
func (s *BrewService) UpdateHomebrew() error {
|
|
cmd := exec.Command("brew", "update")
|
|
return cmd.Run()
|
|
}
|
|
|
|
// UpdateAllPackages upgrades all outdated packages.
|
|
func (s *BrewService) UpdateAllPackages(app *tview.Application, outputView *tview.TextView) error {
|
|
cmd := exec.Command("brew", "upgrade") // #nosec G204
|
|
return s.executeCommand(app, cmd, outputView)
|
|
}
|
|
|
|
// UpdatePackage upgrades a specific package.
|
|
func (s *BrewService) UpdatePackage(info models.Package, app *tview.Application, outputView *tview.TextView) error {
|
|
var cmd *exec.Cmd
|
|
if info.Type == models.PackageTypeCask {
|
|
cmd = exec.Command("brew", "upgrade", "--cask", info.Name) // #nosec G204
|
|
} else {
|
|
cmd = exec.Command("brew", "upgrade", info.Name) // #nosec G204
|
|
}
|
|
return s.executeCommand(app, cmd, outputView)
|
|
}
|
|
|
|
// RemovePackage uninstalls a package.
|
|
func (s *BrewService) RemovePackage(info models.Package, app *tview.Application, outputView *tview.TextView) error {
|
|
var cmd *exec.Cmd
|
|
if info.Type == models.PackageTypeCask {
|
|
cmd = exec.Command("brew", "uninstall", "--cask", info.Name) // #nosec G204
|
|
} else {
|
|
cmd = exec.Command("brew", "uninstall", info.Name) // #nosec G204
|
|
}
|
|
return s.executeCommand(app, cmd, outputView)
|
|
}
|
|
|
|
// InstallPackage installs a package.
|
|
func (s *BrewService) InstallPackage(info models.Package, app *tview.Application, outputView *tview.TextView) error {
|
|
var cmd *exec.Cmd
|
|
if info.Type == models.PackageTypeCask {
|
|
cmd = exec.Command("brew", "install", "--cask", info.Name) // #nosec G204
|
|
} else {
|
|
cmd = exec.Command("brew", "install", info.Name) // #nosec G204
|
|
}
|
|
return s.executeCommand(app, cmd, outputView)
|
|
}
|
|
|
|
// InstallTap installs a Homebrew tap.
|
|
func (s *BrewService) InstallTap(tapName string, app *tview.Application, outputView *tview.TextView) error {
|
|
cmd := exec.Command("brew", "tap", tapName) // #nosec G204
|
|
return s.executeCommand(app, cmd, outputView)
|
|
}
|
|
|
|
// IsTapInstalled checks if a tap is already installed.
|
|
func (s *BrewService) IsTapInstalled(tapName string) bool {
|
|
cmd := exec.Command("brew", "tap")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
taps := strings.Split(strings.TrimSpace(string(output)), "\n")
|
|
for _, tap := range taps {
|
|
if strings.TrimSpace(tap) == tapName {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// executeCommand runs a command and captures its output, updating the provided TextView.
|
|
func (s *BrewService) executeCommand(
|
|
app *tview.Application,
|
|
cmd *exec.Cmd,
|
|
outputView *tview.TextView,
|
|
) error {
|
|
stdoutPipe, stdoutWriter := io.Pipe()
|
|
stderrPipe, stderrWriter := io.Pipe()
|
|
cmd.Stdout = stdoutWriter
|
|
cmd.Stderr = stderrWriter
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
return err
|
|
}
|
|
|
|
var wg sync.WaitGroup
|
|
wg.Add(3)
|
|
|
|
cmdErrCh := make(chan error, 1)
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
defer stdoutWriter.Close()
|
|
defer stderrWriter.Close()
|
|
cmdErrCh <- cmd.Wait()
|
|
}()
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
defer stdoutPipe.Close()
|
|
buf := make([]byte, 1024)
|
|
for {
|
|
n, err := stdoutPipe.Read(buf)
|
|
if n > 0 {
|
|
output := make([]byte, n)
|
|
copy(output, buf[:n])
|
|
app.QueueUpdateDraw(func() {
|
|
_, _ = outputView.Write(output) // #nosec G104
|
|
outputView.ScrollToEnd()
|
|
})
|
|
}
|
|
if err != nil {
|
|
if err != io.EOF {
|
|
app.QueueUpdateDraw(func() {
|
|
fmt.Fprintf(outputView, "\nError: %v\n", err)
|
|
})
|
|
}
|
|
break
|
|
}
|
|
}
|
|
}()
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
defer stderrPipe.Close()
|
|
buf := make([]byte, 1024)
|
|
for {
|
|
n, err := stderrPipe.Read(buf)
|
|
if n > 0 {
|
|
output := make([]byte, n)
|
|
copy(output, buf[:n])
|
|
app.QueueUpdateDraw(func() {
|
|
_, _ = outputView.Write(output) // #nosec G104
|
|
outputView.ScrollToEnd()
|
|
})
|
|
}
|
|
if err != nil {
|
|
if err != io.EOF {
|
|
app.QueueUpdateDraw(func() {
|
|
fmt.Fprintf(outputView, "\nError: %v\n", err)
|
|
})
|
|
}
|
|
break
|
|
}
|
|
}
|
|
}()
|
|
|
|
wg.Wait()
|
|
|
|
return <-cmdErrCh
|
|
}
|