diff --git a/internal/cmd/dev/cmd_apply.go b/internal/cmd/dev/cmd_apply.go index 738ad606..e3655b02 100644 --- a/internal/cmd/dev/cmd_apply.go +++ b/internal/cmd/dev/cmd_apply.go @@ -225,12 +225,12 @@ func runApply() error { // getApplyTargetRepos gets repos to apply command to func getApplyTargetRepos() ([]*repos.Repo, error) { // Load registry - registryPath, err := repos.FindRegistry() + registryPath, err := repos.FindRegistry(io.Local) if err != nil { return nil, core.E("dev.apply", "failed to find registry", err) } - registry, err := repos.LoadRegistry(registryPath) + registry, err := repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, core.E("dev.apply", "failed to load registry", err) } diff --git a/internal/cmd/dev/cmd_ci.go b/internal/cmd/dev/cmd_ci.go index de0ef97b..1b6e9842 100644 --- a/internal/cmd/dev/cmd_ci.go +++ b/internal/cmd/dev/cmd_ci.go @@ -10,6 +10,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" ) @@ -75,20 +76,20 @@ func runCI(registryPath string, branch string, failedOnly bool) error { var err error if registryPath != "" { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return cli.Wrap(err, "failed to load registry") } } else { - registryPath, err = repos.FindRegistry() + registryPath, err = repos.FindRegistry(io.Local) if err == nil { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return cli.Wrap(err, "failed to load registry") } } else { cwd, _ := os.Getwd() - reg, err = repos.ScanDirectory(cwd) + reg, err = repos.ScanDirectory(io.Local, cwd) if err != nil { return cli.Wrap(err, "failed to scan directory") } diff --git a/internal/cmd/dev/cmd_file_sync.go b/internal/cmd/dev/cmd_file_sync.go index 736c1c41..3f24df1e 100644 --- a/internal/cmd/dev/cmd_file_sync.go +++ b/internal/cmd/dev/cmd_file_sync.go @@ -195,12 +195,12 @@ func runFileSync(source string) error { // resolveTargetRepos resolves the --to pattern to actual repos func resolveTargetRepos(pattern string) ([]*repos.Repo, error) { // Load registry - registryPath, err := repos.FindRegistry() + registryPath, err := repos.FindRegistry(coreio.Local) if err != nil { return nil, log.E("dev.sync", "failed to find registry", err) } - registry, err := repos.LoadRegistry(registryPath) + registry, err := repos.LoadRegistry(coreio.Local, registryPath) if err != nil { return nil, log.E("dev.sync", "failed to load registry", err) } diff --git a/internal/cmd/dev/cmd_impact.go b/internal/cmd/dev/cmd_impact.go index 22a499df..345733d6 100644 --- a/internal/cmd/dev/cmd_impact.go +++ b/internal/cmd/dev/cmd_impact.go @@ -6,6 +6,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" ) @@ -42,14 +43,14 @@ func runImpact(registryPath string, repoName string) error { var err error if registryPath != "" { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return cli.Wrap(err, "failed to load registry") } } else { - registryPath, err = repos.FindRegistry() + registryPath, err = repos.FindRegistry(io.Local) if err == nil { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return cli.Wrap(err, "failed to load registry") } diff --git a/internal/cmd/dev/registry.go b/internal/cmd/dev/registry.go index 8ead92a1..1a9dc7b9 100644 --- a/internal/cmd/dev/registry.go +++ b/internal/cmd/dev/registry.go @@ -8,6 +8,7 @@ import ( "github.com/host-uk/core/internal/cmd/workspace" "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" ) @@ -18,16 +19,16 @@ func loadRegistryWithConfig(registryPath string) (*repos.Registry, string, error var registryDir string if registryPath != "" { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, "", cli.Wrap(err, "failed to load registry") } cli.Print("%s %s\n\n", dimStyle.Render(i18n.Label("registry")), registryPath) registryDir = filepath.Dir(registryPath) } else { - registryPath, err = repos.FindRegistry() + registryPath, err = repos.FindRegistry(io.Local) if err == nil { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, "", cli.Wrap(err, "failed to load registry") } @@ -36,7 +37,7 @@ func loadRegistryWithConfig(registryPath string) (*repos.Registry, string, error } else { // Fallback: scan current directory cwd, _ := os.Getwd() - reg, err = repos.ScanDirectory(cwd) + reg, err = repos.ScanDirectory(io.Local, cwd) if err != nil { return nil, "", cli.Wrap(err, "failed to scan directory") } diff --git a/internal/cmd/docs/cmd_scan.go b/internal/cmd/docs/cmd_scan.go index 2fb9574d..7f4d6b5c 100644 --- a/internal/cmd/docs/cmd_scan.go +++ b/internal/cmd/docs/cmd_scan.go @@ -30,22 +30,22 @@ func loadRegistry(registryPath string) (*repos.Registry, string, error) { var registryDir string if registryPath != "" { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, "", cli.Wrap(err, i18n.T("i18n.fail.load", "registry")) } registryDir = filepath.Dir(registryPath) } else { - registryPath, err = repos.FindRegistry() + registryPath, err = repos.FindRegistry(io.Local) if err == nil { - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, "", cli.Wrap(err, i18n.T("i18n.fail.load", "registry")) } registryDir = filepath.Dir(registryPath) } else { cwd, _ := os.Getwd() - reg, err = repos.ScanDirectory(cwd) + reg, err = repos.ScanDirectory(io.Local, cwd) if err != nil { return nil, "", cli.Wrap(err, i18n.T("i18n.fail.scan", "directory")) } diff --git a/internal/cmd/doctor/cmd_environment.go b/internal/cmd/doctor/cmd_environment.go index 2e8ea280..c0eb8dff 100644 --- a/internal/cmd/doctor/cmd_environment.go +++ b/internal/cmd/doctor/cmd_environment.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" ) @@ -43,11 +44,11 @@ func checkGitHubCLI() bool { // checkWorkspace checks for repos.yaml and counts cloned repos func checkWorkspace() { - registryPath, err := repos.FindRegistry() + registryPath, err := repos.FindRegistry(io.Local) if err == nil { fmt.Printf(" %s %s\n", successStyle.Render("✓"), i18n.T("cmd.doctor.repos_yaml_found", map[string]interface{}{"Path": registryPath})) - reg, err := repos.LoadRegistry(registryPath) + reg, err := repos.LoadRegistry(io.Local, registryPath) if err == nil { basePath := reg.BasePath if basePath == "" { diff --git a/internal/cmd/monitor/cmd_monitor.go b/internal/cmd/monitor/cmd_monitor.go index 847fc991..96e7ad58 100644 --- a/internal/cmd/monitor/cmd_monitor.go +++ b/internal/cmd/monitor/cmd_monitor.go @@ -18,6 +18,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/log" "github.com/host-uk/core/pkg/repos" ) @@ -177,12 +178,12 @@ func resolveRepos() ([]string, error) { if monitorAll { // All repos from registry - registry, err := repos.FindRegistry() + registry, err := repos.FindRegistry(io.Local) if err != nil { return nil, log.E("monitor", "failed to find registry", err) } - loaded, err := repos.LoadRegistry(registry) + loaded, err := repos.LoadRegistry(io.Local, registry) if err != nil { return nil, log.E("monitor", "failed to load registry", err) } diff --git a/internal/cmd/pkgcmd/cmd_install.go b/internal/cmd/pkgcmd/cmd_install.go index b5052325..6e85f50a 100644 --- a/internal/cmd/pkgcmd/cmd_install.go +++ b/internal/cmd/pkgcmd/cmd_install.go @@ -51,8 +51,8 @@ func runPkgInstall(repoArg, targetDir string, addToRegistry bool) error { // Determine target directory if targetDir == "" { - if regPath, err := repos.FindRegistry(); err == nil { - if reg, err := repos.LoadRegistry(regPath); err == nil { + if regPath, err := repos.FindRegistry(coreio.Local); err == nil { + if reg, err := repos.LoadRegistry(coreio.Local, regPath); err == nil { targetDir = reg.BasePath if targetDir == "" { targetDir = "./packages" @@ -110,12 +110,12 @@ func runPkgInstall(repoArg, targetDir string, addToRegistry bool) error { } func addToRegistryFile(org, repoName string) error { - regPath, err := repos.FindRegistry() + regPath, err := repos.FindRegistry(coreio.Local) if err != nil { return errors.New(i18n.T("cmd.pkg.error.no_repos_yaml")) } - reg, err := repos.LoadRegistry(regPath) + reg, err := repos.LoadRegistry(coreio.Local, regPath) if err != nil { return err } diff --git a/internal/cmd/pkgcmd/cmd_manage.go b/internal/cmd/pkgcmd/cmd_manage.go index 9d40f901..c89cbd4f 100644 --- a/internal/cmd/pkgcmd/cmd_manage.go +++ b/internal/cmd/pkgcmd/cmd_manage.go @@ -28,12 +28,12 @@ func addPkgListCommand(parent *cobra.Command) { } func runPkgList() error { - regPath, err := repos.FindRegistry() + regPath, err := repos.FindRegistry(coreio.Local) if err != nil { return errors.New(i18n.T("cmd.pkg.error.no_repos_yaml_workspace")) } - reg, err := repos.LoadRegistry(regPath) + reg, err := repos.LoadRegistry(coreio.Local, regPath) if err != nil { return fmt.Errorf("%s: %w", i18n.T("i18n.fail.load", "registry"), err) } @@ -113,12 +113,12 @@ func addPkgUpdateCommand(parent *cobra.Command) { } func runPkgUpdate(packages []string, all bool) error { - regPath, err := repos.FindRegistry() + regPath, err := repos.FindRegistry(coreio.Local) if err != nil { return errors.New(i18n.T("cmd.pkg.error.no_repos_yaml")) } - reg, err := repos.LoadRegistry(regPath) + reg, err := repos.LoadRegistry(coreio.Local, regPath) if err != nil { return fmt.Errorf("%s: %w", i18n.T("i18n.fail.load", "registry"), err) } @@ -193,12 +193,12 @@ func addPkgOutdatedCommand(parent *cobra.Command) { } func runPkgOutdated() error { - regPath, err := repos.FindRegistry() + regPath, err := repos.FindRegistry(coreio.Local) if err != nil { return errors.New(i18n.T("cmd.pkg.error.no_repos_yaml")) } - reg, err := repos.LoadRegistry(regPath) + reg, err := repos.LoadRegistry(coreio.Local, regPath) if err != nil { return fmt.Errorf("%s: %w", i18n.T("i18n.fail.load", "registry"), err) } diff --git a/internal/cmd/pkgcmd/cmd_search.go b/internal/cmd/pkgcmd/cmd_search.go index 5b34cbc1..4b573b81 100644 --- a/internal/cmd/pkgcmd/cmd_search.go +++ b/internal/cmd/pkgcmd/cmd_search.go @@ -13,6 +13,7 @@ import ( "github.com/host-uk/core/pkg/cache" "github.com/host-uk/core/pkg/i18n" + coreio "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" "github.com/spf13/cobra" ) @@ -69,7 +70,7 @@ type ghRepo struct { func runPkgSearch(org, pattern, repoType string, limit int, refresh bool) error { // Initialize cache in workspace .core/ directory var cacheDir string - if regPath, err := repos.FindRegistry(); err == nil { + if regPath, err := repos.FindRegistry(coreio.Local); err == nil { cacheDir = filepath.Join(filepath.Dir(regPath), ".core", "cache") } diff --git a/internal/cmd/qa/cmd_health.go b/internal/cmd/qa/cmd_health.go index f34cee3d..4a5d1c8c 100644 --- a/internal/cmd/qa/cmd_health.go +++ b/internal/cmd/qa/cmd_health.go @@ -14,6 +14,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/log" "github.com/host-uk/core/pkg/repos" ) @@ -71,13 +72,13 @@ func runHealth() error { var err error if healthRegistry != "" { - reg, err = repos.LoadRegistry(healthRegistry) + reg, err = repos.LoadRegistry(io.Local, healthRegistry) } else { - registryPath, findErr := repos.FindRegistry() + registryPath, findErr := repos.FindRegistry(io.Local) if findErr != nil { return log.E("qa.health", i18n.T("error.registry_not_found"), nil) } - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) } if err != nil { return log.E("qa.health", "failed to load registry", err) diff --git a/internal/cmd/qa/cmd_issues.go b/internal/cmd/qa/cmd_issues.go index 2b038c6d..3001c7a9 100644 --- a/internal/cmd/qa/cmd_issues.go +++ b/internal/cmd/qa/cmd_issues.go @@ -17,6 +17,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/log" "github.com/host-uk/core/pkg/repos" ) @@ -100,13 +101,13 @@ func runQAIssues() error { var err error if issuesRegistry != "" { - reg, err = repos.LoadRegistry(issuesRegistry) + reg, err = repos.LoadRegistry(io.Local, issuesRegistry) } else { - registryPath, findErr := repos.FindRegistry() + registryPath, findErr := repos.FindRegistry(io.Local) if findErr != nil { return log.E("qa.issues", i18n.T("error.registry_not_found"), nil) } - reg, err = repos.LoadRegistry(registryPath) + reg, err = repos.LoadRegistry(io.Local, registryPath) } if err != nil { return log.E("qa.issues", "failed to load registry", err) diff --git a/internal/cmd/security/cmd_security.go b/internal/cmd/security/cmd_security.go index 12358b86..242c4ba4 100644 --- a/internal/cmd/security/cmd_security.go +++ b/internal/cmd/security/cmd_security.go @@ -8,6 +8,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" ) @@ -106,18 +107,18 @@ type SecretScanningAlert struct { // loadRegistry loads the repository registry. func loadRegistry(registryPath string) (*repos.Registry, error) { if registryPath != "" { - reg, err := repos.LoadRegistry(registryPath) + reg, err := repos.LoadRegistry(io.Local, registryPath) if err != nil { return nil, cli.Wrap(err, "load registry") } return reg, nil } - path, err := repos.FindRegistry() + path, err := repos.FindRegistry(io.Local) if err != nil { return nil, cli.Wrap(err, "find registry") } - reg, err := repos.LoadRegistry(path) + reg, err := repos.LoadRegistry(io.Local, path) if err != nil { return nil, cli.Wrap(err, "load registry") } diff --git a/internal/cmd/setup/cmd_bootstrap.go b/internal/cmd/setup/cmd_bootstrap.go index 4ea2839c..3006396d 100644 --- a/internal/cmd/setup/cmd_bootstrap.go +++ b/internal/cmd/setup/cmd_bootstrap.go @@ -30,7 +30,7 @@ func runSetupOrchestrator(registryPath, only string, dryRun, all bool, projectNa if registryPath != "" { foundRegistry = registryPath } else { - foundRegistry, err = repos.FindRegistry() + foundRegistry, err = repos.FindRegistry(coreio.Local) } // If registry exists, use registry mode @@ -128,7 +128,7 @@ func runBootstrap(ctx context.Context, only string, dryRun, all bool, projectNam return nil } - reg, err := repos.LoadRegistry(registryPath) + reg, err := repos.LoadRegistry(coreio.Local, registryPath) if err != nil { return fmt.Errorf("failed to load registry from %s: %w", devopsRepo, err) } diff --git a/internal/cmd/setup/cmd_github.go b/internal/cmd/setup/cmd_github.go index 47a20e03..5eda47b2 100644 --- a/internal/cmd/setup/cmd_github.go +++ b/internal/cmd/setup/cmd_github.go @@ -24,6 +24,7 @@ import ( "github.com/host-uk/core/pkg/cli" "github.com/host-uk/core/pkg/i18n" + coreio "github.com/host-uk/core/pkg/io" "github.com/host-uk/core/pkg/repos" "github.com/spf13/cobra" ) @@ -78,12 +79,12 @@ func runGitHubSetup() error { } // Find registry - registryPath, err := repos.FindRegistry() + registryPath, err := repos.FindRegistry(coreio.Local) if err != nil { return cli.Wrap(err, i18n.T("error.registry_not_found")) } - reg, err := repos.LoadRegistry(registryPath) + reg, err := repos.LoadRegistry(coreio.Local, registryPath) if err != nil { return cli.Wrap(err, "failed to load registry") } diff --git a/internal/cmd/setup/cmd_registry.go b/internal/cmd/setup/cmd_registry.go index a06e10ef..9f3b8b04 100644 --- a/internal/cmd/setup/cmd_registry.go +++ b/internal/cmd/setup/cmd_registry.go @@ -22,7 +22,7 @@ import ( // runRegistrySetup loads a registry from path and runs setup. func runRegistrySetup(ctx context.Context, registryPath, only string, dryRun, all, runBuild bool) error { - reg, err := repos.LoadRegistry(registryPath) + reg, err := repos.LoadRegistry(coreio.Local, registryPath) if err != nil { return fmt.Errorf("failed to load registry: %w", err) } diff --git a/pkg/cli/daemon.go b/pkg/cli/daemon.go index e43df9f1..692ccd6b 100644 --- a/pkg/cli/daemon.go +++ b/pkg/cli/daemon.go @@ -74,13 +74,14 @@ func IsStderrTTY() bool { // PIDFile manages a process ID file for single-instance enforcement. type PIDFile struct { - path string - mu sync.Mutex + medium io.Medium + path string + mu sync.Mutex } // NewPIDFile creates a PID file manager. -func NewPIDFile(path string) *PIDFile { - return &PIDFile{path: path} +func NewPIDFile(m io.Medium, path string) *PIDFile { + return &PIDFile{medium: m, path: path} } // Acquire writes the current PID to the file. @@ -90,7 +91,7 @@ func (p *PIDFile) Acquire() error { defer p.mu.Unlock() // Check if PID file exists - if data, err := io.Local.Read(p.path); err == nil { + if data, err := p.medium.Read(p.path); err == nil { pid, err := strconv.Atoi(data) if err == nil && pid > 0 { // Check if process is still running @@ -101,19 +102,19 @@ func (p *PIDFile) Acquire() error { } } // Stale PID file, remove it - _ = io.Local.Delete(p.path) + _ = p.medium.Delete(p.path) } // Ensure directory exists if dir := filepath.Dir(p.path); dir != "." { - if err := io.Local.EnsureDir(dir); err != nil { + if err := p.medium.EnsureDir(dir); err != nil { return fmt.Errorf("failed to create PID directory: %w", err) } } // Write current PID pid := os.Getpid() - if err := io.Local.Write(p.path, strconv.Itoa(pid)); err != nil { + if err := p.medium.Write(p.path, strconv.Itoa(pid)); err != nil { return fmt.Errorf("failed to write PID file: %w", err) } @@ -124,7 +125,7 @@ func (p *PIDFile) Acquire() error { func (p *PIDFile) Release() error { p.mu.Lock() defer p.mu.Unlock() - return io.Local.Delete(p.path) + return p.medium.Delete(p.path) } // Path returns the PID file path. @@ -246,6 +247,10 @@ func (h *HealthServer) Addr() string { // DaemonOptions configures daemon mode execution. type DaemonOptions struct { + // Medium is the storage backend for PID files. + // Defaults to io.Local if not set. + Medium io.Medium + // PIDFile path for single-instance enforcement. // Leave empty to skip PID file management. PIDFile string @@ -282,6 +287,9 @@ func NewDaemon(opts DaemonOptions) *Daemon { if opts.ShutdownTimeout == 0 { opts.ShutdownTimeout = 30 * time.Second } + if opts.Medium == nil { + opts.Medium = io.Local + } d := &Daemon{ opts: opts, @@ -289,7 +297,7 @@ func NewDaemon(opts DaemonOptions) *Daemon { } if opts.PIDFile != "" { - d.pid = NewPIDFile(opts.PIDFile) + d.pid = NewPIDFile(opts.Medium, opts.PIDFile) } if opts.HealthAddr != "" { diff --git a/pkg/cli/daemon_test.go b/pkg/cli/daemon_test.go index 5eb51329..a2c04c7d 100644 --- a/pkg/cli/daemon_test.go +++ b/pkg/cli/daemon_test.go @@ -3,11 +3,10 @@ package cli import ( "context" "net/http" - "os" - "path/filepath" "testing" "time" + "github.com/host-uk/core/pkg/io" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -28,37 +27,36 @@ func TestDetectMode(t *testing.T) { func TestPIDFile(t *testing.T) { t.Run("acquire and release", func(t *testing.T) { - tmpDir := t.TempDir() - pidPath := filepath.Join(tmpDir, "test.pid") + m := io.NewMockMedium() + pidPath := "/tmp/test.pid" - pid := NewPIDFile(pidPath) + pid := NewPIDFile(m, pidPath) // Acquire should succeed err := pid.Acquire() require.NoError(t, err) // File should exist with our PID - data, err := os.ReadFile(pidPath) + data, err := m.Read(pidPath) require.NoError(t, err) - assert.Contains(t, string(data), "") + assert.NotEmpty(t, data) // Release should remove file err = pid.Release() require.NoError(t, err) - _, err = os.Stat(pidPath) - assert.True(t, os.IsNotExist(err)) + assert.False(t, m.Exists(pidPath)) }) t.Run("stale pid file", func(t *testing.T) { - tmpDir := t.TempDir() - pidPath := filepath.Join(tmpDir, "stale.pid") + m := io.NewMockMedium() + pidPath := "/tmp/stale.pid" // Write a stale PID (non-existent process) - err := os.WriteFile(pidPath, []byte("999999999"), 0644) + err := m.Write(pidPath, "999999999") require.NoError(t, err) - pid := NewPIDFile(pidPath) + pid := NewPIDFile(m, pidPath) // Should acquire successfully (stale PID removed) err = pid.Acquire() @@ -69,23 +67,23 @@ func TestPIDFile(t *testing.T) { }) t.Run("creates parent directory", func(t *testing.T) { - tmpDir := t.TempDir() - pidPath := filepath.Join(tmpDir, "subdir", "nested", "test.pid") + m := io.NewMockMedium() + pidPath := "/tmp/subdir/nested/test.pid" - pid := NewPIDFile(pidPath) + pid := NewPIDFile(m, pidPath) err := pid.Acquire() require.NoError(t, err) - _, err = os.Stat(pidPath) - require.NoError(t, err) + assert.True(t, m.Exists(pidPath)) err = pid.Release() require.NoError(t, err) }) t.Run("path getter", func(t *testing.T) { - pid := NewPIDFile("/tmp/test.pid") + m := io.NewMockMedium() + pid := NewPIDFile(m, "/tmp/test.pid") assert.Equal(t, "/tmp/test.pid", pid.Path()) }) } @@ -157,10 +155,12 @@ func TestHealthServer(t *testing.T) { func TestDaemon(t *testing.T) { t.Run("start and stop", func(t *testing.T) { - tmpDir := t.TempDir() + m := io.NewMockMedium() + pidPath := "/tmp/test.pid" d := NewDaemon(DaemonOptions{ - PIDFile: filepath.Join(tmpDir, "test.pid"), + Medium: m, + PIDFile: pidPath, HealthAddr: "127.0.0.1:0", ShutdownTimeout: 5 * time.Second, }) @@ -182,8 +182,7 @@ func TestDaemon(t *testing.T) { require.NoError(t, err) // PID file should be removed - _, err = os.Stat(filepath.Join(tmpDir, "test.pid")) - assert.True(t, os.IsNotExist(err)) + assert.False(t, m.Exists(pidPath)) }) t.Run("double start fails", func(t *testing.T) { diff --git a/pkg/container/linuxkit.go b/pkg/container/linuxkit.go index a5371f73..d3bba481 100644 --- a/pkg/container/linuxkit.go +++ b/pkg/container/linuxkit.go @@ -235,6 +235,9 @@ func (m *LinuxKitManager) waitForExit(id string, cmd *exec.Cmd) { // Stop stops a running container by sending SIGTERM. func (m *LinuxKitManager) Stop(ctx context.Context, id string) error { + if err := ctx.Err(); err != nil { + return err + } container, ok := m.state.Get(id) if !ok { return fmt.Errorf("container not found: %s", id) @@ -293,6 +296,9 @@ func (m *LinuxKitManager) Stop(ctx context.Context, id string) error { // List returns all known containers, verifying process state. func (m *LinuxKitManager) List(ctx context.Context) ([]*Container, error) { + if err := ctx.Err(); err != nil { + return nil, err + } containers := m.state.All() // Verify each running container's process is still alive @@ -322,6 +328,9 @@ func isProcessRunning(pid int) bool { // Logs returns a reader for the container's log output. func (m *LinuxKitManager) Logs(ctx context.Context, id string, follow bool) (goio.ReadCloser, error) { + if err := ctx.Err(); err != nil { + return nil, err + } _, ok := m.state.Get(id) if !ok { return nil, fmt.Errorf("container not found: %s", id) @@ -409,6 +418,9 @@ func (f *followReader) Close() error { // Exec executes a command inside the container via SSH. func (m *LinuxKitManager) Exec(ctx context.Context, id string, cmd []string) error { + if err := ctx.Err(); err != nil { + return err + } container, ok := m.state.Get(id) if !ok { return fmt.Errorf("container not found: %s", id) diff --git a/pkg/repos/registry.go b/pkg/repos/registry.go index 6122fd42..620585dd 100644 --- a/pkg/repos/registry.go +++ b/pkg/repos/registry.go @@ -20,6 +20,7 @@ type Registry struct { BasePath string `yaml:"base_path"` Repos map[string]*Repo `yaml:"repos"` Defaults RegistryDefaults `yaml:"defaults"` + medium io.Medium `yaml:"-"` } // RegistryDefaults contains default values applied to all repos. @@ -56,17 +57,14 @@ type Repo struct { Clone *bool `yaml:"clone,omitempty"` // nil = true, false = skip cloning // Computed fields - Path string `yaml:"-"` // Full path to repo directory + Path string `yaml:"-"` // Full path to repo directory + registry *Registry `yaml:"-"` } -// LoadRegistry reads and parses a repos.yaml file. -func LoadRegistry(path string) (*Registry, error) { - absPath, err := filepath.Abs(path) - if err != nil { - return nil, fmt.Errorf("failed to resolve path: %w", err) - } - - content, err := io.Local.Read(absPath) +// LoadRegistry reads and parses a repos.yaml file from the given medium. +// The path should be a valid path for the provided medium. +func LoadRegistry(m io.Medium, path string) (*Registry, error) { + content, err := m.Read(path) if err != nil { return nil, fmt.Errorf("failed to read registry file: %w", err) } @@ -77,6 +75,8 @@ func LoadRegistry(path string) (*Registry, error) { return nil, fmt.Errorf("failed to parse registry file: %w", err) } + reg.medium = m + // Expand base path reg.BasePath = expandPath(reg.BasePath) @@ -84,6 +84,7 @@ func LoadRegistry(path string) (*Registry, error) { for name, repo := range reg.Repos { repo.Name = name repo.Path = filepath.Join(reg.BasePath, name) + repo.registry = ® // Apply defaults if not set if repo.CI == "" { @@ -96,7 +97,8 @@ func LoadRegistry(path string) (*Registry, error) { // FindRegistry searches for repos.yaml in common locations. // It checks: current directory, parent directories, and home directory. -func FindRegistry() (string, error) { +// This function is primarily intended for use with io.Local or other local-like filesystems. +func FindRegistry(m io.Medium) (string, error) { // Check current directory and parents dir, err := os.Getwd() if err != nil { @@ -105,7 +107,7 @@ func FindRegistry() (string, error) { for { candidate := filepath.Join(dir, "repos.yaml") - if io.Local.Exists(candidate) { + if m.Exists(candidate) { return candidate, nil } @@ -128,7 +130,7 @@ func FindRegistry() (string, error) { } for _, p := range commonPaths { - if io.Local.Exists(p) { + if m.Exists(p) { return p, nil } } @@ -138,21 +140,18 @@ func FindRegistry() (string, error) { // ScanDirectory creates a Registry by scanning a directory for git repos. // This is used as a fallback when no repos.yaml is found. -func ScanDirectory(dir string) (*Registry, error) { - absDir, err := filepath.Abs(dir) - if err != nil { - return nil, fmt.Errorf("failed to resolve directory path: %w", err) - } - - entries, err := io.Local.List(absDir) +// The dir should be a valid path for the provided medium. +func ScanDirectory(m io.Medium, dir string) (*Registry, error) { + entries, err := m.List(dir) if err != nil { return nil, fmt.Errorf("failed to read directory: %w", err) } reg := &Registry{ Version: 1, - BasePath: absDir, + BasePath: dir, Repos: make(map[string]*Repo), + medium: m, } // Try to detect org from git remote @@ -161,24 +160,25 @@ func ScanDirectory(dir string) (*Registry, error) { continue } - repoPath := filepath.Join(absDir, entry.Name()) + repoPath := filepath.Join(dir, entry.Name()) gitPath := filepath.Join(repoPath, ".git") - if !io.Local.IsDir(gitPath) { + if !m.IsDir(gitPath) { continue // Not a git repo } repo := &Repo{ - Name: entry.Name(), - Path: repoPath, - Type: "module", // Default type + Name: entry.Name(), + Path: repoPath, + Type: "module", // Default type + registry: reg, } reg.Repos[entry.Name()] = repo // Try to detect org from first repo's remote if reg.Org == "" { - reg.Org = detectOrg(repoPath) + reg.Org = detectOrg(m, repoPath) } } @@ -186,10 +186,10 @@ func ScanDirectory(dir string) (*Registry, error) { } // detectOrg tries to extract the GitHub org from a repo's origin remote. -func detectOrg(repoPath string) string { +func detectOrg(m io.Medium, repoPath string) string { // Try to read git remote configPath := filepath.Join(repoPath, ".git", "config") - content, err := io.Local.Read(configPath) + content, err := m.Read(configPath) if err != nil { return "" } @@ -301,13 +301,20 @@ func (r *Registry) TopologicalOrder() ([]*Repo, error) { // Exists checks if the repo directory exists on disk. func (repo *Repo) Exists() bool { - return io.Local.IsDir(repo.Path) + return repo.getMedium().IsDir(repo.Path) } // IsGitRepo checks if the repo directory contains a .git folder. func (repo *Repo) IsGitRepo() bool { gitPath := filepath.Join(repo.Path, ".git") - return io.Local.IsDir(gitPath) + return repo.getMedium().IsDir(gitPath) +} + +func (repo *Repo) getMedium() io.Medium { + if repo.registry != nil && repo.registry.medium != nil { + return repo.registry.medium + } + return io.Local } // expandPath expands ~ to home directory. diff --git a/pkg/repos/registry_test.go b/pkg/repos/registry_test.go new file mode 100644 index 00000000..2f8eda24 --- /dev/null +++ b/pkg/repos/registry_test.go @@ -0,0 +1,77 @@ +package repos + +import ( + "testing" + + "github.com/host-uk/core/pkg/io" + "github.com/stretchr/testify/assert" +) + +func TestLoadRegistry(t *testing.T) { + m := io.NewMockMedium() + yaml := ` +version: 1 +org: host-uk +base_path: /tmp/repos +repos: + core: + type: foundation + description: Core package +` + _ = m.Write("/tmp/repos.yaml", yaml) + + reg, err := LoadRegistry(m, "/tmp/repos.yaml") + assert.NoError(t, err) + assert.NotNil(t, reg) + assert.Equal(t, "host-uk", reg.Org) + assert.Equal(t, "/tmp/repos", reg.BasePath) + assert.Equal(t, m, reg.medium) + + repo, ok := reg.Get("core") + assert.True(t, ok) + assert.Equal(t, "core", repo.Name) + assert.Equal(t, "/tmp/repos/core", repo.Path) + assert.Equal(t, reg, repo.registry) +} + +func TestRepo_Exists(t *testing.T) { + m := io.NewMockMedium() + reg := &Registry{ + medium: m, + BasePath: "/tmp/repos", + Repos: make(map[string]*Repo), + } + repo := &Repo{ + Name: "core", + Path: "/tmp/repos/core", + registry: reg, + } + + // Not exists yet + assert.False(t, repo.Exists()) + + // Create directory in mock + _ = m.EnsureDir("/tmp/repos/core") + assert.True(t, repo.Exists()) +} + +func TestRepo_IsGitRepo(t *testing.T) { + m := io.NewMockMedium() + reg := &Registry{ + medium: m, + BasePath: "/tmp/repos", + Repos: make(map[string]*Repo), + } + repo := &Repo{ + Name: "core", + Path: "/tmp/repos/core", + registry: reg, + } + + // Not a git repo yet + assert.False(t, repo.IsGitRepo()) + + // Create .git directory in mock + _ = m.EnsureDir("/tmp/repos/core/.git") + assert.True(t, repo.IsGitRepo()) +}