Compare commits

..

1 commit
dev ... main

Author SHA1 Message Date
Virgil
6abb69e1a4 refactor(container): complete AX compliance pass
Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-29 17:37:24 +00:00
39 changed files with 1006 additions and 1982 deletions

View file

@ -36,7 +36,7 @@ Three packages with a clear dependency direction: `devenv` -> `container` (root)
## Coding Standards
- UK English (colour, organisation, honour)
- Tests use testify; naming convention: `TestSubject_Function_{Good,Bad,Ugly}`
- Error wrapping: `core.E("Op", "message", err)`
- Tests use testify; naming convention: `_Good` (happy path), `_Bad` (expected errors), `_Ugly` (edge cases)
- Error wrapping: `fmt.Errorf("context: %w", err)`
- Context propagation: all blocking operations take `context.Context` as first parameter
- Licence: EUPL-1.2

View file

@ -1,436 +0,0 @@
# Upgrade Report: dappco.re/go/core v0.8.0-alpha.1
## Scope
- Repository: `core/go-container`
- Branch: `agent/create-an-upgrade-plan-for-this-package`
- Requested target: `dappco.re/go/core v0.8.0-alpha.1`
- Consumers called out for break-risk review: `core`, `go-devops`
## Baseline Verification
- `go build ./...`: passed
- `go vet ./...`: passed
- `go test ./... -count=1 -timeout 120s`: passed
- `go test -cover ./...`: passed (`container` 81.7%, `cmd/vm` 0.0%, `devenv` 53.3%, `sources` 72.7%)
- `go mod tidy`: not run because this task is report-only and should not introduce dependency churn
## 1. go.mod Upgrade Plan
- Current core version: `dappco.re/go/core v0.5.0` at `go.mod:16`
- Required bump: `dappco.re/go/core v0.5.0` -> `dappco.re/go/core v0.8.0-alpha.1` at `go.mod:16`
- Direct `dappco.re/go/core/*` dependencies that should be compatibility-checked in the same upgrade pass:
- `go.mod:6` `dappco.re/go/core/i18n v0.2.0`
- `go.mod:7` `dappco.re/go/core/io v0.2.0`
- `go.mod:8` `dappco.re/go/core/log v0.1.0`
- Legacy `forge.lthn.ai` modules still present in `go.mod`; these should be reviewed during the core bump because they may pin older transitive core APIs:
- `go.mod:9` `forge.lthn.ai/core/cli v0.3.7`
- `go.mod:10` `forge.lthn.ai/core/config v0.1.8`
- `go.mod:17` `forge.lthn.ai/core/go v0.3.3`
- `go.mod:18` `forge.lthn.ai/core/go-i18n v0.1.7`
- `go.mod:19` `forge.lthn.ai/core/go-inference v0.1.6`
- `go.mod:20` `forge.lthn.ai/core/go-io v0.1.7`
- `go.mod:21` `forge.lthn.ai/core/go-log v0.0.4`
## 2. Banned Stdlib Imports
Each group lists every import site and the required Core replacement.
### `os`
- Replacement: Replace with core.Env/core.Fs
- `cmd/vm/cmd_container.go:7`
- `cmd/vm/cmd_templates.go:6`
- `devenv/claude.go:6`
- `devenv/config.go:4`
- `devenv/config_test.go:4`
- `devenv/devops.go:7`
- `devenv/devops_test.go:5`
- `devenv/images.go:7`
- `devenv/images_test.go:5`
- `devenv/serve.go:6`
- `devenv/serve_test.go:4`
- `devenv/shell.go:6`
- `devenv/ssh_utils.go:6`
- `devenv/test_test.go:4`
- `hypervisor.go:6`
- `linuxkit.go:8`
- `linuxkit_test.go:5`
- `sources/cdn.go:8`
- `sources/cdn_test.go:8`
- `sources/github.go:5`
- `state.go:5`
- `state_test.go:4`
- `templates.go:7`
- `templates_test.go:4`
### `os/exec`
- Replacement: No direct replacement was provided in the task; requires a manual audit for the v0.8.0-alpha.1 command-exec path
- `cmd/vm/cmd_templates.go:7`
- `devenv/claude.go:7`
- `devenv/devops_test.go:6`
- `devenv/serve.go:7`
- `devenv/shell.go:7`
- `devenv/ssh_utils.go:7`
- `hypervisor.go:7`
- `linuxkit.go:9`
- `linuxkit_test.go:6`
- `sources/github.go:6`
### `encoding/json`
- Replacement: Replace with core.JSONMarshalString/JSONUnmarshalString
- `devenv/images.go:5`
- `devenv/test.go:5`
- `state.go:4`
### `fmt`
- Replacement: Replace with core.Sprintf/core.Concat/core.E
- `cmd/vm/cmd_container.go:5`
- `cmd/vm/cmd_templates.go:5`
- `devenv/claude.go:5`
- `devenv/devops.go:6`
- `devenv/images.go:6`
- `devenv/serve.go:5`
- `devenv/shell.go:5`
- `devenv/ssh_utils.go:5`
- `hypervisor.go:5`
- `linuxkit.go:6`
- `sources/cdn.go:5`
- `sources/cdn_test.go:5`
### `errors`
- Replacement: Replace with core.E/core.Is
- No occurrences found
### `strings`
- Replacement: Replace with core.Contains/core.HasPrefix/core.Split/core.Trim/core.Replace
- `cmd/vm/cmd_container.go:8`
- `cmd/vm/cmd_templates.go:9`
- `devenv/claude.go:9`
- `devenv/ssh_utils.go:9`
- `devenv/test.go:7`
- `hypervisor.go:10`
- `sources/github.go:7`
- `templates.go:11`
- `templates_test.go:6`
### `path/filepath`
- Replacement: Replace with core.JoinPath/core.PathBase/core.PathDir
- `cmd/vm/cmd_templates.go:8`
- `devenv/claude.go:8`
- `devenv/config.go:5`
- `devenv/config_test.go:5`
- `devenv/devops.go:8`
- `devenv/devops_test.go:7`
- `devenv/images.go:8`
- `devenv/images_test.go:6`
- `devenv/serve.go:8`
- `devenv/serve_test.go:5`
- `devenv/ssh_utils.go:8`
- `devenv/test.go:6`
- `devenv/test_test.go:5`
- `hypervisor.go:8`
- `linuxkit_test.go:7`
- `sources/cdn.go:9`
- `sources/cdn_test.go:9`
- `state.go:6`
- `state_test.go:5`
- `templates.go:8`
- `templates_test.go:5`
## 3. Tests Not Matching `TestFile_Function_{Good,Bad,Ugly}`
- Total mismatches found: 236
- `devenv/claude_test.go:9` `TestClaudeOptions_Default`
- `devenv/claude_test.go:16` `TestClaudeOptions_Custom`
- `devenv/claude_test.go:27` `TestFormatAuthList_Good_NoAuth`
- `devenv/claude_test.go:33` `TestFormatAuthList_Good_Default`
- `devenv/claude_test.go:39` `TestFormatAuthList_Good_CustomAuth`
- `devenv/claude_test.go:47` `TestFormatAuthList_Good_MultipleAuth`
- `devenv/claude_test.go:55` `TestFormatAuthList_Good_EmptyAuth`
- `devenv/config_test.go:13` `TestDefaultConfig`
- `devenv/config_test.go:20` `TestConfigPath`
- `devenv/config_test.go:26` `TestLoadConfig_Good`
- `devenv/config_test.go:65` `TestLoadConfig_Bad`
- `devenv/config_test.go:82` `TestConfig_Struct`
- `devenv/config_test.go:105` `TestDefaultConfig_Complete`
- `devenv/config_test.go:114` `TestLoadConfig_Good_PartialConfig`
- `devenv/config_test.go:139` `TestLoadConfig_Good_AllSourceTypes`
- `devenv/config_test.go:208` `TestImagesConfig_Struct`
- `devenv/config_test.go:217` `TestGitHubConfig_Struct`
- `devenv/config_test.go:222` `TestRegistryConfig_Struct`
- `devenv/config_test.go:227` `TestCDNConfig_Struct`
- `devenv/config_test.go:232` `TestLoadConfig_Bad_UnreadableFile`
- `devenv/devops_test.go:18` `TestImageName`
- `devenv/devops_test.go:26` `TestImagesDir`
- `devenv/devops_test.go:48` `TestImagePath`
- `devenv/devops_test.go:58` `TestDefaultBootOptions`
- `devenv/devops_test.go:66` `TestIsInstalled_Bad`
- `devenv/devops_test.go:78` `TestIsInstalled_Good`
- `devenv/devops_test.go:142` `TestDevOps_Status_Good_NotInstalled`
- `devenv/devops_test.go:168` `TestDevOps_Status_Good_NoContainer`
- `devenv/devops_test.go:232` `TestDevOps_IsRunning_Bad_NotRunning`
- `devenv/devops_test.go:255` `TestDevOps_IsRunning_Bad_ContainerStopped`
- `devenv/devops_test.go:323` `TestDevOps_findContainer_Bad_NotFound`
- `devenv/devops_test.go:346` `TestDevOps_Stop_Bad_NotFound`
- `devenv/devops_test.go:369` `TestBootOptions_Custom`
- `devenv/devops_test.go:382` `TestDevStatus_Struct`
- `devenv/devops_test.go:403` `TestDevOps_Boot_Bad_NotInstalled`
- `devenv/devops_test.go:426` `TestDevOps_Boot_Bad_AlreadyRunning`
- `devenv/devops_test.go:465` `TestDevOps_Status_Good_WithImageVersion`
- `devenv/devops_test.go:501` `TestDevOps_findContainer_Good_MultipleContainers`
- `devenv/devops_test.go:546` `TestDevOps_Status_Good_ContainerWithUptime`
- `devenv/devops_test.go:583` `TestDevOps_IsRunning_Bad_DifferentContainerName`
- `devenv/devops_test.go:618` `TestDevOps_Boot_Good_FreshFlag`
- `devenv/devops_test.go:668` `TestDevOps_Stop_Bad_ContainerNotRunning`
- `devenv/devops_test.go:703` `TestDevOps_Boot_Good_FreshWithNoExisting`
- `devenv/devops_test.go:741` `TestImageName_Format`
- `devenv/devops_test.go:750` `TestDevOps_Install_Delegates`
- `devenv/devops_test.go:768` `TestDevOps_CheckUpdate_Delegates`
- `devenv/devops_test.go:786` `TestDevOps_Boot_Good_Success`
- `devenv/devops_test.go:818` `TestDevOps_Config`
- `devenv/images_test.go:16` `TestImageManager_Good_IsInstalled`
- `devenv/images_test.go:36` `TestNewImageManager_Good`
- `devenv/images_test.go:66` `TestManifest_Save`
- `devenv/images_test.go:94` `TestLoadManifest_Bad`
- `devenv/images_test.go:106` `TestCheckUpdate_Bad`
- `devenv/images_test.go:121` `TestNewImageManager_Good_AutoSource`
- `devenv/images_test.go:134` `TestNewImageManager_Good_UnknownSourceFallsToAuto`
- `devenv/images_test.go:147` `TestLoadManifest_Good_Empty`
- `devenv/images_test.go:159` `TestLoadManifest_Good_ExistingData`
- `devenv/images_test.go:174` `TestImageInfo_Struct`
- `devenv/images_test.go:187` `TestManifest_Save_Good_CreatesDirs`
- `devenv/images_test.go:207` `TestManifest_Save_Good_Overwrite`
- `devenv/images_test.go:239` `TestImageManager_Install_Bad_NoSourceAvailable`
- `devenv/images_test.go:256` `TestNewImageManager_Good_CreatesDir`
- `devenv/images_test.go:295` `TestImageManager_Install_Good_WithMockSource`
- `devenv/images_test.go:323` `TestImageManager_Install_Bad_DownloadError`
- `devenv/images_test.go:345` `TestImageManager_Install_Bad_VersionError`
- `devenv/images_test.go:367` `TestImageManager_Install_Good_SkipsUnavailableSource`
- `devenv/images_test.go:396` `TestImageManager_CheckUpdate_Good_WithMockSource`
- `devenv/images_test.go:426` `TestImageManager_CheckUpdate_Good_NoUpdate`
- `devenv/images_test.go:456` `TestImageManager_CheckUpdate_Bad_NoSource`
- `devenv/images_test.go:483` `TestImageManager_CheckUpdate_Bad_VersionError`
- `devenv/images_test.go:511` `TestImageManager_Install_Bad_EmptySources`
- `devenv/images_test.go:527` `TestImageManager_Install_Bad_AllUnavailable`
- `devenv/images_test.go:546` `TestImageManager_CheckUpdate_Good_FirstSourceUnavailable`
- `devenv/images_test.go:573` `TestManifest_Struct`
- `devenv/serve_test.go:12` `TestDetectServeCommand_Good_Laravel`
- `devenv/serve_test.go:21` `TestDetectServeCommand_Good_NodeDev`
- `devenv/serve_test.go:31` `TestDetectServeCommand_Good_NodeStart`
- `devenv/serve_test.go:41` `TestDetectServeCommand_Good_PHP`
- `devenv/serve_test.go:50` `TestDetectServeCommand_Good_GoMain`
- `devenv/serve_test.go:61` `TestDetectServeCommand_Good_GoWithoutMain`
- `devenv/serve_test.go:71` `TestDetectServeCommand_Good_Django`
- `devenv/serve_test.go:80` `TestDetectServeCommand_Good_Fallback`
- `devenv/serve_test.go:87` `TestDetectServeCommand_Good_Priority`
- `devenv/serve_test.go:99` `TestServeOptions_Default`
- `devenv/serve_test.go:105` `TestServeOptions_Custom`
- `devenv/serve_test.go:114` `TestHasFile_Good`
- `devenv/serve_test.go:123` `TestHasFile_Bad`
- `devenv/serve_test.go:129` `TestHasFile_Bad_Directory`
- `devenv/shell_test.go:9` `TestShellOptions_Default`
- `devenv/shell_test.go:15` `TestShellOptions_Console`
- `devenv/shell_test.go:23` `TestShellOptions_Command`
- `devenv/shell_test.go:31` `TestShellOptions_ConsoleWithCommand`
- `devenv/shell_test.go:40` `TestShellOptions_EmptyCommand`
- `devenv/test_test.go:11` `TestDetectTestCommand_Good_ComposerJSON`
- `devenv/test_test.go:21` `TestDetectTestCommand_Good_PackageJSON`
- `devenv/test_test.go:31` `TestDetectTestCommand_Good_GoMod`
- `devenv/test_test.go:41` `TestDetectTestCommand_Good_CoreTestYaml`
- `devenv/test_test.go:53` `TestDetectTestCommand_Good_Pytest`
- `devenv/test_test.go:63` `TestDetectTestCommand_Good_Taskfile`
- `devenv/test_test.go:73` `TestDetectTestCommand_Bad_NoFiles`
- `devenv/test_test.go:82` `TestDetectTestCommand_Good_Priority`
- `devenv/test_test.go:96` `TestLoadTestConfig_Good`
- `devenv/test_test.go:135` `TestLoadTestConfig_Bad_NotFound`
- `devenv/test_test.go:144` `TestHasPackageScript_Good`
- `devenv/test_test.go:156` `TestHasPackageScript_Bad_MissingScript`
- `devenv/test_test.go:165` `TestHasComposerScript_Good`
- `devenv/test_test.go:174` `TestHasComposerScript_Bad_MissingScript`
- `devenv/test_test.go:183` `TestTestConfig_Struct`
- `devenv/test_test.go:204` `TestTestCommand_Struct`
- `devenv/test_test.go:217` `TestTestOptions_Struct`
- `devenv/test_test.go:230` `TestDetectTestCommand_Good_TaskfileYml`
- `devenv/test_test.go:240` `TestDetectTestCommand_Good_Pyproject`
- `devenv/test_test.go:250` `TestHasPackageScript_Bad_NoFile`
- `devenv/test_test.go:258` `TestHasPackageScript_Bad_InvalidJSON`
- `devenv/test_test.go:267` `TestHasPackageScript_Bad_NoScripts`
- `devenv/test_test.go:276` `TestHasComposerScript_Bad_NoFile`
- `devenv/test_test.go:284` `TestHasComposerScript_Bad_InvalidJSON`
- `devenv/test_test.go:293` `TestHasComposerScript_Bad_NoScripts`
- `devenv/test_test.go:302` `TestLoadTestConfig_Bad_InvalidYAML`
- `devenv/test_test.go:314` `TestLoadTestConfig_Good_MinimalConfig`
- `devenv/test_test.go:332` `TestDetectTestCommand_Good_ComposerWithoutScript`
- `devenv/test_test.go:344` `TestDetectTestCommand_Good_PackageJSONWithoutScript`
- `hypervisor_test.go:23` `TestQemuHypervisor_Available_Bad_InvalidBinary`
- `hypervisor_test.go:47` `TestHyperkitHypervisor_Available_Bad_NotDarwin`
- `hypervisor_test.go:59` `TestHyperkitHypervisor_Available_Bad_InvalidBinary`
- `hypervisor_test.go:69` `TestIsKVMAvailable_Good`
- `hypervisor_test.go:83` `TestDetectHypervisor_Good`
- `hypervisor_test.go:98` `TestGetHypervisor_Good_Qemu`
- `hypervisor_test.go:110` `TestGetHypervisor_Good_QemuUppercase`
- `hypervisor_test.go:122` `TestGetHypervisor_Good_Hyperkit`
- `hypervisor_test.go:140` `TestGetHypervisor_Bad_Unknown`
- `hypervisor_test.go:147` `TestQemuHypervisor_BuildCommand_Good_WithPortsAndVolumes`
- `hypervisor_test.go:175` `TestQemuHypervisor_BuildCommand_Good_QCow2Format`
- `hypervisor_test.go:195` `TestQemuHypervisor_BuildCommand_Good_VMDKFormat`
- `hypervisor_test.go:215` `TestQemuHypervisor_BuildCommand_Good_RawFormat`
- `hypervisor_test.go:235` `TestHyperkitHypervisor_BuildCommand_Good_WithPorts`
- `hypervisor_test.go:258` `TestHyperkitHypervisor_BuildCommand_Good_QCow2Format`
- `hypervisor_test.go:269` `TestHyperkitHypervisor_BuildCommand_Good_RawFormat`
- `hypervisor_test.go:280` `TestHyperkitHypervisor_BuildCommand_Good_NoPorts`
- `hypervisor_test.go:296` `TestQemuHypervisor_BuildCommand_Good_NoSSHPort`
- `hypervisor_test.go:312` `TestQemuHypervisor_BuildCommand_Bad_UnknownFormat`
- `hypervisor_test.go:323` `TestHyperkitHypervisor_BuildCommand_Bad_UnknownFormat`
- `hypervisor_test.go:339` `TestHyperkitHypervisor_BuildCommand_Good_ISOFormat`
- `linuxkit_test.go:76` `TestNewLinuxKitManagerWithHypervisor_Good`
- `linuxkit_test.go:89` `TestLinuxKitManager_Run_Good_Detached`
- `linuxkit_test.go:128` `TestLinuxKitManager_Run_Good_DefaultValues`
- `linuxkit_test.go:153` `TestLinuxKitManager_Run_Bad_ImageNotFound`
- `linuxkit_test.go:164` `TestLinuxKitManager_Run_Bad_UnsupportedFormat`
- `linuxkit_test.go:204` `TestLinuxKitManager_Stop_Bad_NotFound`
- `linuxkit_test.go:214` `TestLinuxKitManager_Stop_Bad_NotRunning`
- `linuxkit_test.go:251` `TestLinuxKitManager_List_Good_VerifiesRunningStatus`
- `linuxkit_test.go:303` `TestLinuxKitManager_Logs_Bad_NotFound`
- `linuxkit_test.go:313` `TestLinuxKitManager_Logs_Bad_NoLogFile`
- `linuxkit_test.go:336` `TestLinuxKitManager_Exec_Bad_NotFound`
- `linuxkit_test.go:346` `TestLinuxKitManager_Exec_Bad_NotRunning`
- `linuxkit_test.go:359` `TestDetectImageFormat_Good`
- `linuxkit_test.go:381` `TestDetectImageFormat_Bad_Unknown`
- `linuxkit_test.go:429` `TestLinuxKitManager_Logs_Good_Follow`
- `linuxkit_test.go:467` `TestFollowReader_Read_Good_WithData`
- `linuxkit_test.go:500` `TestFollowReader_Read_Good_ContextCancel`
- `linuxkit_test.go:544` `TestNewFollowReader_Bad_FileNotFound`
- `linuxkit_test.go:551` `TestLinuxKitManager_Run_Bad_BuildCommandError`
- `linuxkit_test.go:570` `TestLinuxKitManager_Run_Good_Foreground`
- `linuxkit_test.go:598` `TestLinuxKitManager_Stop_Good_ContextCancelled`
- `linuxkit_test.go:635` `TestIsProcessRunning_Good_ExistingProcess`
- `linuxkit_test.go:641` `TestIsProcessRunning_Bad_NonexistentProcess`
- `linuxkit_test.go:647` `TestLinuxKitManager_Run_Good_WithPortsAndVolumes`
- `linuxkit_test.go:676` `TestFollowReader_Read_Bad_ReaderError`
- `linuxkit_test.go:697` `TestLinuxKitManager_Run_Bad_StartError`
- `linuxkit_test.go:718` `TestLinuxKitManager_Run_Bad_ForegroundStartError`
- `linuxkit_test.go:739` `TestLinuxKitManager_Run_Good_ForegroundWithError`
- `linuxkit_test.go:762` `TestLinuxKitManager_Stop_Good_ProcessExitedWhileRunning`
- `sources/cdn_test.go:16` `TestCDNSource_Good_Available`
- `sources/cdn_test.go:26` `TestCDNSource_Bad_NoURL`
- `sources/cdn_test.go:118` `TestCDNSource_LatestVersion_Bad_NoManifest`
- `sources/cdn_test.go:134` `TestCDNSource_LatestVersion_Bad_ServerError`
- `sources/cdn_test.go:150` `TestCDNSource_Download_Good_NoProgress`
- `sources/cdn_test.go:174` `TestCDNSource_Download_Good_LargeFile`
- `sources/cdn_test.go:206` `TestCDNSource_Download_Bad_HTTPErrorCodes`
- `sources/cdn_test.go:238` `TestCDNSource_InterfaceCompliance`
- `sources/cdn_test.go:243` `TestCDNSource_Config`
- `sources/cdn_test.go:254` `TestNewCDNSource_Good`
- `sources/cdn_test.go:268` `TestCDNSource_Download_Good_CreatesDestDir`
- `sources/cdn_test.go:294` `TestSourceConfig_Struct`
- `sources/github_test.go:9` `TestGitHubSource_Good_Available`
- `sources/github_test.go:23` `TestGitHubSource_Name`
- `sources/github_test.go:28` `TestGitHubSource_Config`
- `sources/github_test.go:40` `TestGitHubSource_Good_Multiple`
- `sources/github_test.go:51` `TestNewGitHubSource_Good`
- `sources/github_test.go:65` `TestGitHubSource_InterfaceCompliance`
- `sources/source_test.go:9` `TestSourceConfig_Empty`
- `sources/source_test.go:17` `TestSourceConfig_Complete`
- `sources/source_test.go:31` `TestImageSource_Interface`
- `state_test.go:13` `TestNewState_Good`
- `state_test.go:21` `TestLoadState_Good_NewFile`
- `state_test.go:33` `TestLoadState_Good_ExistingFile`
- `state_test.go:64` `TestLoadState_Bad_InvalidJSON`
- `state_test.go:142` `TestState_Get_Bad_NotFound`
- `state_test.go:162` `TestState_SaveState_Good_CreatesDirectory`
- `state_test.go:177` `TestDefaultStateDir_Good`
- `state_test.go:183` `TestDefaultStatePath_Good`
- `state_test.go:189` `TestDefaultLogsDir_Good`
- `state_test.go:195` `TestLogPath_Good`
- `state_test.go:201` `TestEnsureLogsDir_Good`
- `state_test.go:211` `TestGenerateID_Good`
- `templates_test.go:13` `TestListTemplates_Good`
- `templates_test.go:44` `TestGetTemplate_Good_CoreDev`
- `templates_test.go:55` `TestGetTemplate_Good_ServerPhp`
- `templates_test.go:66` `TestGetTemplate_Bad_NotFound`
- `templates_test.go:73` `TestApplyVariables_Good_SimpleSubstitution`
- `templates_test.go:86` `TestApplyVariables_Good_WithDefaults`
- `templates_test.go:99` `TestApplyVariables_Good_AllDefaults`
- `templates_test.go:109` `TestApplyVariables_Good_MixedSyntax`
- `templates_test.go:128` `TestApplyVariables_Good_EmptyDefault`
- `templates_test.go:138` `TestApplyVariables_Bad_MissingRequired`
- `templates_test.go:149` `TestApplyVariables_Bad_MultipleMissing`
- `templates_test.go:164` `TestApplyTemplate_Good`
- `templates_test.go:178` `TestApplyTemplate_Bad_TemplateNotFound`
- `templates_test.go:189` `TestApplyTemplate_Bad_MissingVariable`
- `templates_test.go:199` `TestExtractVariables_Good`
- `templates_test.go:221` `TestExtractVariables_Good_NoVariables`
- `templates_test.go:230` `TestExtractVariables_Good_OnlyDefaults`
- `templates_test.go:241` `TestScanUserTemplates_Good`
- `templates_test.go:265` `TestScanUserTemplates_Good_MultipleTemplates`
- `templates_test.go:287` `TestScanUserTemplates_Good_EmptyDirectory`
- `templates_test.go:295` `TestScanUserTemplates_Bad_NonexistentDirectory`
- `templates_test.go:301` `TestExtractTemplateDescription_Good`
- `templates_test.go:318` `TestExtractTemplateDescription_Good_NoComments`
- `templates_test.go:333` `TestExtractTemplateDescription_Bad_FileNotFound`
- `templates_test.go:339` `TestVariablePatternEdgeCases_Good`
- `templates_test.go:387` `TestScanUserTemplates_Good_SkipsBuiltinNames`
- `templates_test.go:405` `TestScanUserTemplates_Good_SkipsDirectories`
- `templates_test.go:422` `TestScanUserTemplates_Good_YamlExtension`
- `templates_test.go:443` `TestExtractTemplateDescription_Good_EmptyComment`
- `templates_test.go:461` `TestExtractTemplateDescription_Good_MultipleEmptyComments`
- `templates_test.go:481` `TestScanUserTemplates_Good_DefaultDescription`
## 4. Exported Functions Missing Usage-Example Doc Comments
- Total exported functions missing a usage example marker: 38
- Note: every function listed below has a doc comment, but none of the comments include an obvious usage example marker such as `Usage:` or `Example:`.
- `cmd/vm/cmd_templates.go:150` `RunFromTemplate` (missing usage example)
- `cmd/vm/cmd_templates.go:296` `ParseVarFlags` (missing usage example)
- `cmd/vm/cmd_vm.go:28` `AddVMCommands` (missing usage example)
- `container.go:84` `GenerateID` (missing usage example)
- `devenv/config.go:41` `DefaultConfig` (missing usage example)
- `devenv/config.go:57` `ConfigPath` (missing usage example)
- `devenv/config.go:67` `LoadConfig` (missing usage example)
- `devenv/devops.go:31` `New` (missing usage example)
- `devenv/devops.go:56` `ImageName` (missing usage example)
- `devenv/devops.go:61` `ImagesDir` (missing usage example)
- `devenv/devops.go:73` `ImagePath` (missing usage example)
- `devenv/devops.go:109` `DefaultBootOptions` (missing usage example)
- `devenv/images.go:40` `NewImageManager` (missing usage example)
- `devenv/serve.go:75` `DetectServeCommand` (missing usage example)
- `devenv/test.go:75` `DetectTestCommand` (missing usage example)
- `devenv/test.go:115` `LoadTestConfig` (missing usage example)
- `hypervisor.go:50` `NewQemuHypervisor` (missing usage example)
- `hypervisor.go:155` `NewHyperkitHypervisor` (missing usage example)
- `hypervisor.go:222` `DetectImageFormat` (missing usage example)
- `hypervisor.go:239` `DetectHypervisor` (missing usage example)
- `hypervisor.go:258` `GetHypervisor` (missing usage example)
- `linuxkit.go:25` `NewLinuxKitManager` (missing usage example)
- `linuxkit.go:49` `NewLinuxKitManagerWithHypervisor` (missing usage example)
- `sources/cdn.go:24` `NewCDNSource` (missing usage example)
- `sources/github.go:22` `NewGitHubSource` (missing usage example)
- `state.go:22` `DefaultStateDir` (missing usage example)
- `state.go:31` `DefaultStatePath` (missing usage example)
- `state.go:40` `DefaultLogsDir` (missing usage example)
- `state.go:49` `NewState` (missing usage example)
- `state.go:58` `LoadState` (missing usage example)
- `state.go:157` `LogPath` (missing usage example)
- `state.go:166` `EnsureLogsDir` (missing usage example)
- `templates.go:47` `ListTemplates` (missing usage example)
- `templates.go:52` `ListTemplatesIter` (missing usage example)
- `templates.go:75` `GetTemplate` (missing usage example)
- `templates.go:107` `ApplyTemplate` (missing usage example)
- `templates.go:120` `ApplyVariables` (missing usage example)
- `templates.go:169` `ExtractVariables` (missing usage example)
## Risk Notes
- Breaking-change surface is moderate because this repo is consumed by two modules: `core` and `go-devops`.
- The highest-effort part of the upgrade is not the version bump itself; it is the repo-wide removal of banned stdlib imports, especially the current `os/exec` usage across runtime code and tests.
- The doc-comment and test-renaming work is mechanically simple, but it touches many files and will create broad diff surface for downstream review.

View file

@ -2,13 +2,14 @@ package vm
import (
"context"
"fmt"
goio "io"
"os"
"strings"
"text/tabwriter"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/container"
"dappco.re/go/core/container/internal/proc"
"dappco.re/go/core/i18n"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
@ -81,12 +82,12 @@ func runContainer(image, name string, detach bool, memory, cpus, sshPort int) er
SSHPort: sshPort,
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.Label("image")), image)
fmt.Printf("%s %s\n", dimStyle.Render(i18n.Label("image")), image)
if name != "" {
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.name")), name)
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.name")), name)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.hypervisor")), manager.Hypervisor().Name())
core.Println()
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.hypervisor")), manager.Hypervisor().Name())
fmt.Println()
ctx := context.Background()
c, err := manager.Run(ctx, image, opts)
@ -95,14 +96,13 @@ func runContainer(image, name string, detach bool, memory, cpus, sshPort int) er
}
if detach {
core.Print(nil, "%s %s", successStyle.Render(i18n.Label("started")), c.ID)
core.Print(nil, "%s %d", dimStyle.Render(i18n.T("cmd.vm.label.pid")), c.PID)
core.Println()
core.Println(i18n.T("cmd.vm.hint.view_logs", map[string]any{"ID": c.ID[:8]}))
core.Println(i18n.T("cmd.vm.hint.stop", map[string]any{"ID": c.ID[:8]}))
fmt.Printf("%s %s\n", successStyle.Render(i18n.Label("started")), c.ID)
fmt.Printf("%s %d\n", dimStyle.Render(i18n.T("cmd.vm.label.pid")), c.PID)
fmt.Println()
fmt.Println(i18n.T("cmd.vm.hint.view_logs", map[string]any{"ID": c.ID[:8]}))
fmt.Println(i18n.T("cmd.vm.hint.stop", map[string]any{"ID": c.ID[:8]}))
} else {
core.Println()
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.container_stopped")), c.ID)
fmt.Printf("\n%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.container_stopped")), c.ID)
}
return nil
@ -151,16 +151,16 @@ func listContainers(all bool) error {
if len(containers) == 0 {
if all {
core.Println(i18n.T("cmd.vm.ps.no_containers"))
fmt.Println(i18n.T("cmd.vm.ps.no_containers"))
} else {
core.Println(i18n.T("cmd.vm.ps.no_running"))
fmt.Println(i18n.T("cmd.vm.ps.no_running"))
}
return nil
}
w := tabwriter.NewWriter(proc.Stdout, 0, 0, 2, ' ', 0)
core.Print(w, "%s", i18n.T("cmd.vm.ps.header"))
core.Print(w, "%s", "--\t----\t-----\t------\t-------\t---")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(w, i18n.T("cmd.vm.ps.header"))
_, _ = fmt.Fprintln(w, "--\t----\t-----\t------\t-------\t---")
for _, c := range containers {
// Shorten image path
@ -183,7 +183,7 @@ func listContainers(all bool) error {
status = errorStyle.Render(status)
}
core.Print(w, "%s\t%s\t%s\t%s\t%s\t%d",
_, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%d\n",
c.ID[:8], c.Name, imageName, status, duration, c.PID)
}
@ -193,15 +193,15 @@ func listContainers(all bool) error {
func formatDuration(d time.Duration) string {
if d < time.Minute {
return core.Sprintf("%ds", int(d.Seconds()))
return fmt.Sprintf("%ds", int(d.Seconds()))
}
if d < time.Hour {
return core.Sprintf("%dm", int(d.Minutes()))
return fmt.Sprintf("%dm", int(d.Minutes()))
}
if d < 24*time.Hour {
return core.Sprintf("%dh", int(d.Hours()))
return fmt.Sprintf("%dh", int(d.Hours()))
}
return core.Sprintf("%dd", int(d.Hours()/24))
return fmt.Sprintf("%dd", int(d.Hours()/24))
}
// addVMStopCommand adds the 'stop' command under vm.
@ -230,17 +230,17 @@ func stopContainer(id string) error {
// Support partial ID matching
fullID, err := resolveContainerID(manager, id)
if err != nil {
return err
return coreerr.E("stopContainer", "resolve container ID", err)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.stop.stopping")), fullID[:8])
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("cmd.vm.stop.stopping")), fullID[:8])
ctx := context.Background()
if err := manager.Stop(ctx, fullID); err != nil {
return coreerr.E("stopContainer", i18n.T("i18n.fail.stop", "container"), err)
}
core.Print(nil, "%s", successStyle.Render(i18n.T("common.status.stopped")))
fmt.Printf("%s\n", successStyle.Render(i18n.T("common.status.stopped")))
return nil
}
@ -249,12 +249,12 @@ func resolveContainerID(manager *container.LinuxKitManager, partialID string) (s
ctx := context.Background()
containers, err := manager.List(ctx)
if err != nil {
return "", err
return "", coreerr.E("resolveContainerID", "list containers", err)
}
var matches []*container.Container
for _, c := range containers {
if core.HasPrefix(c.ID, partialID) || core.HasPrefix(c.Name, partialID) {
if strings.HasPrefix(c.ID, partialID) || strings.HasPrefix(c.Name, partialID) {
matches = append(matches, c)
}
}
@ -298,7 +298,7 @@ func viewLogs(id string, follow bool) error {
fullID, err := resolveContainerID(manager, id)
if err != nil {
return err
return coreerr.E("viewLogs", "resolve container ID", err)
}
ctx := context.Background()
@ -308,8 +308,11 @@ func viewLogs(id string, follow bool) error {
}
defer func() { _ = reader.Close() }()
_, err = goio.Copy(proc.Stdout, reader)
return err
_, err = goio.Copy(os.Stdout, reader)
if err != nil {
return coreerr.E("viewLogs", "copy log output", err)
}
return nil
}
// addVMExecCommand adds the 'exec' command under vm.
@ -337,9 +340,12 @@ func execInContainer(id string, cmd []string) error {
fullID, err := resolveContainerID(manager, id)
if err != nil {
return err
return coreerr.E("execInContainer", "resolve container ID", err)
}
ctx := context.Background()
return manager.Exec(ctx, fullID, cmd)
if err := manager.Exec(ctx, fullID, cmd); err != nil {
return coreerr.E("execInContainer", "run command in container", err)
}
return nil
}

View file

@ -2,12 +2,14 @@ package vm
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"text/tabwriter"
core "dappco.re/go/core"
"dappco.re/go/core/container"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
"dappco.re/go/core/i18n"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
@ -70,30 +72,29 @@ func listTemplates() error {
templates := container.ListTemplates()
if len(templates) == 0 {
core.Println(i18n.T("cmd.vm.templates.no_templates"))
fmt.Println(i18n.T("cmd.vm.templates.no_templates"))
return nil
}
core.Print(nil, "%s", repoNameStyle.Render(i18n.T("cmd.vm.templates.title")))
core.Println()
fmt.Printf("%s\n\n", repoNameStyle.Render(i18n.T("cmd.vm.templates.title")))
w := tabwriter.NewWriter(proc.Stdout, 0, 0, 2, ' ', 0)
core.Print(w, "%s", i18n.T("cmd.vm.templates.header"))
core.Print(w, "%s", "----\t-----------")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(w, i18n.T("cmd.vm.templates.header"))
_, _ = fmt.Fprintln(w, "----\t-----------")
for _, tmpl := range templates {
desc := tmpl.Description
if len(desc) > 60 {
desc = desc[:57] + "..."
}
core.Print(w, "%s\t%s", repoNameStyle.Render(tmpl.Name), desc)
_, _ = fmt.Fprintf(w, "%s\t%s\n", repoNameStyle.Render(tmpl.Name), desc)
}
_ = w.Flush()
core.Println()
core.Print(nil, "%s %s", i18n.T("cmd.vm.templates.hint.show"), dimStyle.Render("core vm templates show <name>"))
core.Print(nil, "%s %s", i18n.T("cmd.vm.templates.hint.vars"), dimStyle.Render("core vm templates vars <name>"))
core.Print(nil, "%s %s", i18n.T("cmd.vm.templates.hint.run"), dimStyle.Render("core vm run --template <name> --var SSH_KEY=\"...\""))
fmt.Println()
fmt.Printf("%s %s\n", i18n.T("cmd.vm.templates.hint.show"), dimStyle.Render("core vm templates show <name>"))
fmt.Printf("%s %s\n", i18n.T("cmd.vm.templates.hint.vars"), dimStyle.Render("core vm templates vars <name>"))
fmt.Printf("%s %s\n", i18n.T("cmd.vm.templates.hint.run"), dimStyle.Render("core vm run --template <name> --var SSH_KEY=\"...\""))
return nil
}
@ -101,12 +102,11 @@ func listTemplates() error {
func showTemplate(name string) error {
content, err := container.GetTemplate(name)
if err != nil {
return err
return coreerr.E("showTemplate", "get template", err)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(name))
core.Println()
core.Println(content)
fmt.Printf("%s %s\n\n", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(name))
fmt.Println(content)
return nil
}
@ -114,44 +114,39 @@ func showTemplate(name string) error {
func showTemplateVars(name string) error {
content, err := container.GetTemplate(name)
if err != nil {
return err
return coreerr.E("showTemplateVars", "get template", err)
}
required, optional := container.ExtractVariables(content)
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(name))
core.Println()
fmt.Printf("%s %s\n\n", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(name))
if len(required) > 0 {
core.Print(nil, "%s", errorStyle.Render(i18n.T("cmd.vm.templates.vars.required")))
fmt.Printf("%s\n", errorStyle.Render(i18n.T("cmd.vm.templates.vars.required")))
for _, v := range required {
core.Print(nil, " %s", varStyle.Render("${"+v+"}"))
fmt.Printf(" %s\n", varStyle.Render("${"+v+"}"))
}
core.Println()
fmt.Println()
}
if len(optional) > 0 {
core.Print(nil, "%s", successStyle.Render(i18n.T("cmd.vm.templates.vars.optional")))
fmt.Printf("%s\n", successStyle.Render(i18n.T("cmd.vm.templates.vars.optional")))
for v, def := range optional {
core.Print(nil, " %s = %s",
fmt.Printf(" %s = %s\n",
varStyle.Render("${"+v+"}"),
defaultStyle.Render(def))
}
core.Println()
fmt.Println()
}
if len(required) == 0 && len(optional) == 0 {
core.Println(i18n.T("cmd.vm.templates.vars.none"))
fmt.Println(i18n.T("cmd.vm.templates.vars.none"))
}
return nil
}
// RunFromTemplate builds and runs a LinuxKit image from a template.
//
// Usage:
//
// err := RunFromTemplate("core-dev", vars, runOpts)
func RunFromTemplate(templateName string, vars map[string]string, runOpts container.RunOptions) error {
// Apply template with variables
content, err := container.ApplyTemplate(templateName, vars)
@ -160,23 +155,27 @@ func RunFromTemplate(templateName string, vars map[string]string, runOpts contai
}
// Create a temporary directory for the build
tmpDir, err := coreutil.MkdirTemp("core-linuxkit-")
tmpID, err := container.GenerateID()
if err != nil {
return coreerr.E("RunFromTemplate", i18n.T("common.error.failed", map[string]any{"Action": "create temp directory"}), err)
}
tmpDir := filepath.Join(os.TempDir(), "core-linuxkit-"+tmpID)
if err := io.Local.EnsureDir(tmpDir); err != nil {
return coreerr.E("RunFromTemplate", i18n.T("common.error.failed", map[string]any{"Action": "create temp directory"}), err)
}
defer func() { _ = io.Local.DeleteAll(tmpDir) }()
// Write the YAML file
yamlPath := coreutil.JoinPath(tmpDir, core.Concat(templateName, ".yml"))
yamlPath := filepath.Join(tmpDir, templateName+".yml")
if err := io.Local.Write(yamlPath, content); err != nil {
return coreerr.E("RunFromTemplate", i18n.T("common.error.failed", map[string]any{"Action": "write template"}), err)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(templateName))
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.building")), yamlPath)
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("common.label.template")), repoNameStyle.Render(templateName))
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.building")), yamlPath)
// Build the image using linuxkit
outputPath := coreutil.JoinPath(tmpDir, templateName)
outputPath := filepath.Join(tmpDir, templateName)
if err := buildLinuxKitImage(yamlPath, outputPath); err != nil {
return coreerr.E("RunFromTemplate", i18n.T("common.error.failed", map[string]any{"Action": "build image"}), err)
}
@ -187,8 +186,8 @@ func RunFromTemplate(templateName string, vars map[string]string, runOpts contai
return coreerr.E("RunFromTemplate", i18n.T("cmd.vm.error.no_image_found"), nil)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("common.label.image")), imagePath)
core.Println()
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("common.label.image")), imagePath)
fmt.Println()
// Run the image
manager, err := container.NewLinuxKitManager(io.Local)
@ -196,8 +195,8 @@ func RunFromTemplate(templateName string, vars map[string]string, runOpts contai
return coreerr.E("RunFromTemplate", i18n.T("common.error.failed", map[string]any{"Action": "initialize container manager"}), err)
}
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.hypervisor")), manager.Hypervisor().Name())
core.Println()
fmt.Printf("%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.hypervisor")), manager.Hypervisor().Name())
fmt.Println()
ctx := context.Background()
c, err := manager.Run(ctx, imagePath, runOpts)
@ -206,14 +205,13 @@ func RunFromTemplate(templateName string, vars map[string]string, runOpts contai
}
if runOpts.Detach {
core.Print(nil, "%s %s", successStyle.Render(i18n.T("common.label.started")), c.ID)
core.Print(nil, "%s %d", dimStyle.Render(i18n.T("cmd.vm.label.pid")), c.PID)
core.Println()
core.Println(i18n.T("cmd.vm.hint.view_logs", map[string]any{"ID": c.ID[:8]}))
core.Println(i18n.T("cmd.vm.hint.stop", map[string]any{"ID": c.ID[:8]}))
fmt.Printf("%s %s\n", successStyle.Render(i18n.T("common.label.started")), c.ID)
fmt.Printf("%s %d\n", dimStyle.Render(i18n.T("cmd.vm.label.pid")), c.PID)
fmt.Println()
fmt.Println(i18n.T("cmd.vm.hint.view_logs", map[string]any{"ID": c.ID[:8]}))
fmt.Println(i18n.T("cmd.vm.hint.stop", map[string]any{"ID": c.ID[:8]}))
} else {
core.Println()
core.Print(nil, "%s %s", dimStyle.Render(i18n.T("cmd.vm.label.container_stopped")), c.ID)
fmt.Printf("\n%s %s\n", dimStyle.Render(i18n.T("cmd.vm.label.container_stopped")), c.ID)
}
return nil
@ -224,20 +222,23 @@ func buildLinuxKitImage(yamlPath, outputPath string) error {
// Check if linuxkit is available
lkPath, err := lookupLinuxKit()
if err != nil {
return err
return coreerr.E("buildLinuxKitImage", "find linuxkit binary", err)
}
// Build the image
// linuxkit build --format iso-bios --name <output> <yaml>
cmd := proc.NewCommand(lkPath, "build",
cmd := exec.Command(lkPath, "build",
"--format", "iso-bios",
"--name", outputPath,
yamlPath)
cmd.Stdout = proc.Stdout
cmd.Stderr = proc.Stderr
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
if err := cmd.Run(); err != nil {
return coreerr.E("buildLinuxKitImage", "run linuxkit build", err)
}
return nil
}
// findBuiltImage finds the built image file.
@ -246,15 +247,15 @@ func findBuiltImage(basePath string) string {
extensions := []string{".iso", "-bios.iso", ".qcow2", ".raw", ".vmdk"}
for _, ext := range extensions {
path := core.Concat(basePath, ext)
path := basePath + ext
if io.Local.IsFile(path) {
return path
}
}
// Check directory for any image file
dir := core.PathDir(basePath)
base := core.PathBase(basePath)
dir := filepath.Dir(basePath)
base := filepath.Base(basePath)
entries, err := io.Local.List(dir)
if err != nil {
@ -263,10 +264,10 @@ func findBuiltImage(basePath string) string {
for _, entry := range entries {
name := entry.Name()
if core.HasPrefix(name, base) {
if strings.HasPrefix(name, base) {
for _, ext := range []string{".iso", ".qcow2", ".raw", ".vmdk"} {
if core.HasSuffix(name, ext) {
return coreutil.JoinPath(dir, name)
if strings.HasSuffix(name, ext) {
return filepath.Join(dir, name)
}
}
}
@ -278,7 +279,7 @@ func findBuiltImage(basePath string) string {
// lookupLinuxKit finds the linuxkit binary.
func lookupLinuxKit() (string, error) {
// Check PATH first
if path, err := proc.LookPath("linuxkit"); err == nil {
if path, err := exec.LookPath("linuxkit"); err == nil {
return path, nil
}
@ -289,7 +290,7 @@ func lookupLinuxKit() (string, error) {
}
for _, p := range paths {
if io.Local.Exists(p) {
if io.Local.IsFile(p) {
return p, nil
}
}
@ -299,36 +300,19 @@ func lookupLinuxKit() (string, error) {
// ParseVarFlags parses --var flags into a map.
// Format: --var KEY=VALUE or --var KEY="VALUE"
//
// Usage:
//
// vars := ParseVarFlags([]string{"SSH_KEY=abc", "PORT=2222"})
func ParseVarFlags(varFlags []string) map[string]string {
vars := make(map[string]string)
for _, v := range varFlags {
parts := core.SplitN(v, "=", 2)
parts := strings.SplitN(v, "=", 2)
if len(parts) == 2 {
key := core.Trim(parts[0])
value := core.Trim(parts[1])
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
// Remove surrounding quotes if present
value = stripWrappingQuotes(value)
value = strings.Trim(value, "\"'")
vars[key] = value
}
}
return vars
}
func stripWrappingQuotes(value string) string {
if len(value) < 2 {
return value
}
if core.HasPrefix(value, "\"") && core.HasSuffix(value, "\"") {
return core.TrimSuffix(core.TrimPrefix(value, "\""), "\"")
}
if core.HasPrefix(value, "'") && core.HasSuffix(value, "'") {
return core.TrimSuffix(core.TrimPrefix(value, "'"), "'")
}
return value
}

View file

@ -25,10 +25,6 @@ var (
)
// AddVMCommands adds container-related commands under 'vm' to the CLI.
//
// Usage:
//
// AddVMCommands(root)
func AddVMCommands(root *cli.Command) {
vmCmd := &cli.Command{
Use: "vm",

View file

@ -9,6 +9,8 @@ import (
"encoding/hex"
"io"
"time"
coreerr "dappco.re/go/core/log"
)
// Container represents a running LinuxKit container/VM instance.
@ -81,14 +83,10 @@ type Manager interface {
}
// GenerateID creates a new unique container ID (8 hex characters).
//
// Usage:
//
// id, err := GenerateID()
func GenerateID() (string, error) {
bytes := make([]byte, 4)
if _, err := rand.Read(bytes); err != nil {
return "", err
return "", coreerr.E("GenerateID", "read random bytes", err)
}
return hex.EncodeToString(bytes), nil
}

View file

@ -2,13 +2,14 @@ package devenv
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
)
// ClaudeOptions configures the Claude sandbox session.
@ -23,10 +24,10 @@ func (d *DevOps) Claude(ctx context.Context, projectDir string, opts ClaudeOptio
// Auto-boot if not running
running, err := d.IsRunning(ctx)
if err != nil {
return err
return coreerr.E("DevOps.Claude", "check running state", err)
}
if !running {
core.Println("Dev environment not running, booting...")
fmt.Println("Dev environment not running, booting...")
if err := d.Boot(ctx, DefaultBootOptions()); err != nil {
return coreerr.E("DevOps.Claude", "failed to boot", err)
}
@ -49,22 +50,20 @@ func (d *DevOps) Claude(ctx context.Context, projectDir string, opts ClaudeOptio
for _, auth := range authTypes {
switch auth {
case "anthropic":
if key := core.Env("ANTHROPIC_API_KEY"); key != "" {
envVars = append(envVars, core.Concat("ANTHROPIC_API_KEY=", key))
if key := os.Getenv("ANTHROPIC_API_KEY"); key != "" {
envVars = append(envVars, "ANTHROPIC_API_KEY="+key)
}
case "git":
// Forward git config
name, _ := proc.NewCommand("git", "config", "user.name").Output()
email, _ := proc.NewCommand("git", "config", "user.email").Output()
name, _ := exec.Command("git", "config", "user.name").Output()
email, _ := exec.Command("git", "config", "user.email").Output()
if len(name) > 0 {
trimmed := core.Trim(string(name))
envVars = append(envVars, core.Concat("GIT_AUTHOR_NAME=", trimmed))
envVars = append(envVars, core.Concat("GIT_COMMITTER_NAME=", trimmed))
envVars = append(envVars, "GIT_AUTHOR_NAME="+strings.TrimSpace(string(name)))
envVars = append(envVars, "GIT_COMMITTER_NAME="+strings.TrimSpace(string(name)))
}
if len(email) > 0 {
trimmed := core.Trim(string(email))
envVars = append(envVars, core.Concat("GIT_AUTHOR_EMAIL=", trimmed))
envVars = append(envVars, core.Concat("GIT_COMMITTER_EMAIL=", trimmed))
envVars = append(envVars, "GIT_AUTHOR_EMAIL="+strings.TrimSpace(string(email)))
envVars = append(envVars, "GIT_COMMITTER_EMAIL="+strings.TrimSpace(string(email)))
}
}
}
@ -76,7 +75,7 @@ func (d *DevOps) Claude(ctx context.Context, projectDir string, opts ClaudeOptio
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
"-A", // SSH agent forwarding
"-p", core.Sprintf("%d", DefaultSSHPort),
"-p", fmt.Sprintf("%d", DefaultSSHPort),
}
args = append(args, "root@localhost")
@ -89,20 +88,23 @@ func (d *DevOps) Claude(ctx context.Context, projectDir string, opts ClaudeOptio
args = append(args, claudeCmd)
// Set environment for SSH
cmd := proc.NewCommandContext(ctx, "ssh", args...)
cmd.Stdin = proc.Stdin
cmd.Stdout = proc.Stdout
cmd.Stderr = proc.Stderr
cmd := exec.CommandContext(ctx, "ssh", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Pass environment variables through SSH
if len(envVars) > 0 {
cmd.Env = append(proc.Environ(), envVars...)
for _, env := range envVars {
parts := strings.SplitN(env, "=", 2)
if len(parts) == 2 {
cmd.Env = append(os.Environ(), env)
}
}
core.Println("Starting Claude in sandboxed environment...")
core.Println("Project mounted at /app")
core.Println(core.Concat("Auth forwarded: SSH agent", formatAuthList(opts)))
core.Println()
fmt.Println("Starting Claude in sandboxed environment...")
fmt.Println("Project mounted at /app")
fmt.Println("Auth forwarded: SSH agent" + formatAuthList(opts))
fmt.Println()
return cmd.Run()
}
@ -114,27 +116,27 @@ func formatAuthList(opts ClaudeOptions) string {
if len(opts.Auth) == 0 {
return ", gh, anthropic, git"
}
return core.Concat(", ", core.Join(", ", opts.Auth...))
return ", " + strings.Join(opts.Auth, ", ")
}
// CopyGHAuth copies GitHub CLI auth to the VM.
func (d *DevOps) CopyGHAuth(ctx context.Context) error {
home := coreutil.HomeDir()
if home == "" {
return coreerr.E("DevOps.CopyGHAuth", "home directory not available", nil)
home, err := os.UserHomeDir()
if err != nil {
return coreerr.E("DevOps.CopyGHAuth", "get home dir", err)
}
ghConfigDir := coreutil.JoinPath(home, ".config", "gh")
ghConfigDir := filepath.Join(home, ".config", "gh")
if !io.Local.IsDir(ghConfigDir) {
return nil // No gh config to copy
}
// Use scp to copy gh config
cmd := proc.NewCommandContext(ctx, "scp",
cmd := exec.CommandContext(ctx, "scp",
"-o", "StrictHostKeyChecking=yes",
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
"-P", core.Sprintf("%d", DefaultSSHPort),
"-P", fmt.Sprintf("%d", DefaultSSHPort),
"-r", ghConfigDir,
"root@localhost:/root/.config/",
)

View file

@ -6,14 +6,14 @@ import (
"github.com/stretchr/testify/assert"
)
func TestClaudeOptions_Default_Good(t *testing.T) {
func TestClaudeOptions_Good_Default(t *testing.T) {
opts := ClaudeOptions{}
assert.False(t, opts.NoAuth)
assert.Nil(t, opts.Auth)
assert.Empty(t, opts.Model)
}
func TestClaudeOptions_Custom_Good(t *testing.T) {
func TestClaudeOptions_Good_Custom(t *testing.T) {
opts := ClaudeOptions{
NoAuth: true,
Auth: []string{"gh", "anthropic"},
@ -24,19 +24,19 @@ func TestClaudeOptions_Custom_Good(t *testing.T) {
assert.Equal(t, "opus", opts.Model)
}
func TestFormatAuthList_NoAuth_Good(t *testing.T) {
func TestFormatAuthList_Good_NoAuth(t *testing.T) {
opts := ClaudeOptions{NoAuth: true}
result := formatAuthList(opts)
assert.Equal(t, " (none)", result)
}
func TestFormatAuthList_Default_Good(t *testing.T) {
func TestFormatAuthList_Good_Default(t *testing.T) {
opts := ClaudeOptions{}
result := formatAuthList(opts)
assert.Equal(t, ", gh, anthropic, git", result)
}
func TestFormatAuthList_CustomAuth_Good(t *testing.T) {
func TestFormatAuthList_Good_CustomAuth(t *testing.T) {
opts := ClaudeOptions{
Auth: []string{"gh"},
}
@ -44,7 +44,7 @@ func TestFormatAuthList_CustomAuth_Good(t *testing.T) {
assert.Equal(t, ", gh", result)
}
func TestFormatAuthList_MultipleAuth_Good(t *testing.T) {
func TestFormatAuthList_Good_MultipleAuth(t *testing.T) {
opts := ClaudeOptions{
Auth: []string{"gh", "ssh", "git"},
}
@ -52,7 +52,7 @@ func TestFormatAuthList_MultipleAuth_Good(t *testing.T) {
assert.Equal(t, ", gh, ssh, git", result)
}
func TestFormatAuthList_EmptyAuth_Good(t *testing.T) {
func TestFormatAuthList_Good_EmptyAuth(t *testing.T) {
opts := ClaudeOptions{
Auth: []string{},
}

View file

@ -1,12 +1,12 @@
package devenv
import (
"os"
"path/filepath"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"forge.lthn.ai/core/config"
core "dappco.re/go/core"
"dappco.re/go/core/container/internal/coreutil"
)
// Config holds global devops configuration from ~/.core/config.yaml.
@ -39,10 +39,6 @@ type CDNConfig struct {
}
// DefaultConfig returns sensible defaults.
//
// Usage:
//
// cfg := DefaultConfig()
func DefaultConfig() *Config {
return &Config{
Version: 1,
@ -59,24 +55,16 @@ func DefaultConfig() *Config {
}
// ConfigPath returns the path to the config file.
//
// Usage:
//
// path, err := ConfigPath()
func ConfigPath() (string, error) {
home := coreutil.HomeDir()
if home == "" {
return "", core.E("ConfigPath", "home directory not available", nil)
home, err := os.UserHomeDir()
if err != nil {
return "", coreerr.E("ConfigPath", "get home dir", err)
}
return coreutil.JoinPath(home, ".core", "config.yaml"), nil
return filepath.Join(home, ".core", "config.yaml"), nil
}
// LoadConfig loads configuration from ~/.core/config.yaml using the provided medium.
// Returns default config if file doesn't exist.
//
// Usage:
//
// cfg, err := LoadConfig(io.Local)
func LoadConfig(m io.Medium) (*Config, error) {
configPath, err := ConfigPath()
if err != nil {
@ -92,11 +80,11 @@ func LoadConfig(m io.Medium) (*Config, error) {
// Use centralized config service
c, err := config.New(config.WithMedium(m), config.WithPath(configPath))
if err != nil {
return nil, err
return nil, coreerr.E("LoadConfig", "create config service", err)
}
if err := c.Get("", cfg); err != nil {
return nil, err
return nil, coreerr.E("LoadConfig", "load config", err)
}
return cfg, nil

View file

@ -1,33 +1,35 @@
package devenv
import (
"syscall"
"os"
"path/filepath"
"testing"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfig_DefaultConfig_Good(t *testing.T) {
func TestDefaultConfig_Good(t *testing.T) {
cfg := DefaultConfig()
assert.Equal(t, 1, cfg.Version)
assert.Equal(t, "auto", cfg.Images.Source)
assert.Equal(t, "host-uk/core-images", cfg.Images.GitHub.Repo)
}
func TestConfig_ConfigPath_Good(t *testing.T) {
func TestConfigPath_Good(t *testing.T) {
path, err := ConfigPath()
assert.NoError(t, err)
assert.Contains(t, path, ".core/config.yaml")
}
func TestConfig_LoadConfig_Good(t *testing.T) {
func TestLoadConfig_Good(t *testing.T) {
t.Run("returns default if not exists", func(t *testing.T) {
// Mock HOME to a temp dir
tempHome := t.TempDir()
origHome := os.Getenv("HOME")
t.Setenv("HOME", tempHome)
defer func() { _ = os.Setenv("HOME", origHome) }()
cfg, err := LoadConfig(io.Local)
assert.NoError(t, err)
@ -38,8 +40,8 @@ func TestConfig_LoadConfig_Good(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
coreDir := coreutil.JoinPath(tempHome, ".core")
err := io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tempHome, ".core")
err := os.MkdirAll(coreDir, 0755)
require.NoError(t, err)
configData := `
@ -49,7 +51,7 @@ images:
cdn:
url: https://cdn.example.com
`
err = io.Local.Write(coreutil.JoinPath(coreDir, "config.yaml"), configData)
err = os.WriteFile(filepath.Join(coreDir, "config.yaml"), []byte(configData), 0644)
require.NoError(t, err)
cfg, err := LoadConfig(io.Local)
@ -60,16 +62,16 @@ images:
})
}
func TestConfig_LoadConfig_Bad(t *testing.T) {
func TestLoadConfig_Bad(t *testing.T) {
t.Run("invalid yaml", func(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
coreDir := coreutil.JoinPath(tempHome, ".core")
err := io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tempHome, ".core")
err := os.MkdirAll(coreDir, 0755)
require.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(coreDir, "config.yaml"), "invalid: yaml: :")
err = os.WriteFile(filepath.Join(coreDir, "config.yaml"), []byte("invalid: yaml: :"), 0644)
require.NoError(t, err)
_, err = LoadConfig(io.Local)
@ -77,7 +79,7 @@ func TestConfig_LoadConfig_Bad(t *testing.T) {
})
}
func TestConfig_Struct_Good(t *testing.T) {
func TestConfig_Good_Struct(t *testing.T) {
cfg := &Config{
Version: 2,
Images: ImagesConfig{
@ -100,7 +102,7 @@ func TestConfig_Struct_Good(t *testing.T) {
assert.Equal(t, "https://cdn.example.com", cfg.Images.CDN.URL)
}
func TestDefaultConfig_Complete_Good(t *testing.T) {
func TestDefaultConfig_Good_Complete(t *testing.T) {
cfg := DefaultConfig()
assert.Equal(t, 1, cfg.Version)
assert.Equal(t, "auto", cfg.Images.Source)
@ -109,12 +111,12 @@ func TestDefaultConfig_Complete_Good(t *testing.T) {
assert.Empty(t, cfg.Images.CDN.URL)
}
func TestLoadConfig_PartialConfig_Good(t *testing.T) {
func TestLoadConfig_Good_PartialConfig(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
coreDir := coreutil.JoinPath(tempHome, ".core")
err := io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tempHome, ".core")
err := os.MkdirAll(coreDir, 0755)
require.NoError(t, err)
// Config only specifies source, should merge with defaults
@ -123,7 +125,7 @@ version: 1
images:
source: github
`
err = io.Local.Write(coreutil.JoinPath(coreDir, "config.yaml"), configData)
err = os.WriteFile(filepath.Join(coreDir, "config.yaml"), []byte(configData), 0644)
require.NoError(t, err)
cfg, err := LoadConfig(io.Local)
@ -134,7 +136,7 @@ images:
assert.Equal(t, "host-uk/core-images", cfg.Images.GitHub.Repo)
}
func TestLoadConfig_AllSourceTypes_Good(t *testing.T) {
func TestLoadConfig_Good_AllSourceTypes(t *testing.T) {
tests := []struct {
name string
config string
@ -189,11 +191,11 @@ images:
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
coreDir := coreutil.JoinPath(tempHome, ".core")
err := io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tempHome, ".core")
err := os.MkdirAll(coreDir, 0755)
require.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(coreDir, "config.yaml"), tt.config)
err = os.WriteFile(filepath.Join(coreDir, "config.yaml"), []byte(tt.config), 0644)
require.NoError(t, err)
cfg, err := LoadConfig(io.Local)
@ -203,7 +205,7 @@ images:
}
}
func TestImagesConfig_Struct_Good(t *testing.T) {
func TestImagesConfig_Good_Struct(t *testing.T) {
ic := ImagesConfig{
Source: "auto",
GitHub: GitHubConfig{Repo: "test/repo"},
@ -212,42 +214,42 @@ func TestImagesConfig_Struct_Good(t *testing.T) {
assert.Equal(t, "test/repo", ic.GitHub.Repo)
}
func TestGitHubConfig_Struct_Good(t *testing.T) {
func TestGitHubConfig_Good_Struct(t *testing.T) {
gc := GitHubConfig{Repo: "owner/repo"}
assert.Equal(t, "owner/repo", gc.Repo)
}
func TestRegistryConfig_Struct_Good(t *testing.T) {
func TestRegistryConfig_Good_Struct(t *testing.T) {
rc := RegistryConfig{Image: "ghcr.io/owner/image:latest"}
assert.Equal(t, "ghcr.io/owner/image:latest", rc.Image)
}
func TestCDNConfig_Struct_Good(t *testing.T) {
func TestCDNConfig_Good_Struct(t *testing.T) {
cc := CDNConfig{URL: "https://cdn.example.com/images"}
assert.Equal(t, "https://cdn.example.com/images", cc.URL)
}
func TestLoadConfig_UnreadableFile_Bad(t *testing.T) {
func TestLoadConfig_Bad_UnreadableFile(t *testing.T) {
// This test is platform-specific and may not work on all systems
// Skip if we can't test file permissions properly
if syscall.Getuid() == 0 {
if os.Getuid() == 0 {
t.Skip("Skipping permission test when running as root")
}
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
coreDir := coreutil.JoinPath(tempHome, ".core")
err := io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tempHome, ".core")
err := os.MkdirAll(coreDir, 0755)
require.NoError(t, err)
configPath := coreutil.JoinPath(coreDir, "config.yaml")
err = io.Local.WriteMode(configPath, "version: 1", 0000)
configPath := filepath.Join(coreDir, "config.yaml")
err = os.WriteFile(configPath, []byte("version: 1"), 0000)
require.NoError(t, err)
_, err = LoadConfig(io.Local)
assert.Error(t, err)
// Restore permissions so cleanup works
_ = syscall.Chmod(configPath, 0644)
_ = os.Chmod(configPath, 0644)
}

View file

@ -3,15 +3,15 @@ package devenv
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/container"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
)
const (
@ -28,10 +28,6 @@ type DevOps struct {
}
// New creates a new DevOps instance using the provided medium.
//
// Usage:
//
// dev, err := New(io.Local)
func New(m io.Medium) (*DevOps, error) {
cfg, err := LoadConfig(m)
if err != nil {
@ -57,41 +53,29 @@ func New(m io.Medium) (*DevOps, error) {
}
// ImageName returns the platform-specific image name.
//
// Usage:
//
// name := ImageName()
func ImageName() string {
return core.Sprintf("core-devops-%s-%s.qcow2", runtime.GOOS, runtime.GOARCH)
return fmt.Sprintf("core-devops-%s-%s.qcow2", runtime.GOOS, runtime.GOARCH)
}
// ImagesDir returns the path to the images directory.
//
// Usage:
//
// dir, err := ImagesDir()
func ImagesDir() (string, error) {
if dir := core.Env("CORE_IMAGES_DIR"); dir != "" {
if dir := os.Getenv("CORE_IMAGES_DIR"); dir != "" {
return dir, nil
}
home := coreutil.HomeDir()
if home == "" {
return "", core.E("ImagesDir", "home directory not available", nil)
home, err := os.UserHomeDir()
if err != nil {
return "", coreerr.E("ImagesDir", "get home dir", err)
}
return coreutil.JoinPath(home, ".core", "images"), nil
return filepath.Join(home, ".core", "images"), nil
}
// ImagePath returns the full path to the platform-specific image.
//
// Usage:
//
// path, err := ImagePath()
func ImagePath() (string, error) {
dir, err := ImagesDir()
if err != nil {
return "", err
return "", coreerr.E("ImagePath", "get images directory", err)
}
return coreutil.JoinPath(dir, ImageName()), nil
return filepath.Join(dir, ImageName()), nil
}
// IsInstalled checks if the dev image is installed.
@ -122,10 +106,6 @@ type BootOptions struct {
}
// DefaultBootOptions returns sensible defaults.
//
// Usage:
//
// opts := DefaultBootOptions()
func DefaultBootOptions() BootOptions {
return BootOptions{
Memory: 4096,
@ -155,7 +135,7 @@ func (d *DevOps) Boot(ctx context.Context, opts BootOptions) error {
imagePath, err := ImagePath()
if err != nil {
return err
return coreerr.E("DevOps.Boot", "get image path", err)
}
// Build run options for LinuxKitManager
@ -169,7 +149,7 @@ func (d *DevOps) Boot(ctx context.Context, opts BootOptions) error {
_, err = d.container.Run(ctx, imagePath, runOpts)
if err != nil {
return err
return coreerr.E("DevOps.Boot", "run container", err)
}
// Wait for SSH to be ready and scan host key
@ -195,7 +175,7 @@ func (d *DevOps) Boot(ctx context.Context, opts BootOptions) error {
func (d *DevOps) Stop(ctx context.Context) error {
c, err := d.findContainer(ctx, "core-dev")
if err != nil {
return err
return coreerr.E("DevOps.Stop", "find container", err)
}
if c == nil {
return coreerr.E("DevOps.Stop", "dev environment not found", nil)
@ -207,7 +187,7 @@ func (d *DevOps) Stop(ctx context.Context) error {
func (d *DevOps) IsRunning(ctx context.Context) (bool, error) {
c, err := d.findContainer(ctx, "core-dev")
if err != nil {
return false, err
return false, coreerr.E("DevOps.IsRunning", "find container", err)
}
return c != nil && c.Status == container.StatusRunning, nil
}
@ -216,7 +196,7 @@ func (d *DevOps) IsRunning(ctx context.Context) (bool, error) {
func (d *DevOps) findContainer(ctx context.Context, name string) (*container.Container, error) {
containers, err := d.container.List(ctx)
if err != nil {
return nil, err
return nil, coreerr.E("DevOps.findContainer", "list containers", err)
}
for _, c := range containers {
if c.Name == name {

View file

@ -2,29 +2,20 @@ package devenv
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"syscall"
"testing"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/container"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newManagedTempDir(t *testing.T, prefix string) string {
t.Helper()
dir, err := coreutil.MkdirTemp(prefix)
require.NoError(t, err)
t.Cleanup(func() { _ = io.Local.DeleteAll(dir) })
return dir
}
func TestDevOps_ImageName_Good(t *testing.T) {
func TestImageName_Good(t *testing.T) {
name := ImageName()
assert.Contains(t, name, "core-devops-")
assert.Contains(t, name, runtime.GOOS)
@ -32,9 +23,12 @@ func TestDevOps_ImageName_Good(t *testing.T) {
assert.True(t, (name[len(name)-6:] == ".qcow2"))
}
func TestDevOps_ImagesDir_Good(t *testing.T) {
func TestImagesDir_Good(t *testing.T) {
t.Run("default directory", func(t *testing.T) {
t.Setenv("CORE_IMAGES_DIR", "")
// Unset env if it exists
orig := os.Getenv("CORE_IMAGES_DIR")
_ = os.Unsetenv("CORE_IMAGES_DIR")
defer func() { _ = os.Setenv("CORE_IMAGES_DIR", orig) }()
dir, err := ImagesDir()
assert.NoError(t, err)
@ -51,17 +45,17 @@ func TestDevOps_ImagesDir_Good(t *testing.T) {
})
}
func TestDevOps_ImagePath_Good(t *testing.T) {
func TestImagePath_Good(t *testing.T) {
customDir := "/tmp/images"
t.Setenv("CORE_IMAGES_DIR", customDir)
path, err := ImagePath()
assert.NoError(t, err)
expected := coreutil.JoinPath(customDir, ImageName())
expected := filepath.Join(customDir, ImageName())
assert.Equal(t, expected, path)
}
func TestDevOps_DefaultBootOptions_Good(t *testing.T) {
func TestDefaultBootOptions_Good(t *testing.T) {
opts := DefaultBootOptions()
assert.Equal(t, 4096, opts.Memory)
assert.Equal(t, 2, opts.CPUs)
@ -69,7 +63,7 @@ func TestDevOps_DefaultBootOptions_Good(t *testing.T) {
assert.False(t, opts.Fresh)
}
func TestDevOps_IsInstalled_Bad(t *testing.T) {
func TestIsInstalled_Bad(t *testing.T) {
t.Run("returns false for non-existent image", func(t *testing.T) {
// Point to a temp directory that is empty
tempDir := t.TempDir()
@ -81,14 +75,14 @@ func TestDevOps_IsInstalled_Bad(t *testing.T) {
})
}
func TestDevOps_IsInstalled_Good(t *testing.T) {
func TestIsInstalled_Good(t *testing.T) {
t.Run("returns true when image exists", func(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create the image file
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake image data")
imagePath := filepath.Join(tempDir, ImageName())
err := os.WriteFile(imagePath, []byte("fake image data"), 0644)
require.NoError(t, err)
d := &DevOps{medium: io.Local}
@ -100,8 +94,8 @@ type mockHypervisor struct{}
func (m *mockHypervisor) Name() string { return "mock" }
func (m *mockHypervisor) Available() bool { return true }
func (m *mockHypervisor) BuildCommand(ctx context.Context, image string, opts *container.HypervisorOptions) (*proc.Command, error) {
return proc.NewCommand("true"), nil
func (m *mockHypervisor) BuildCommand(ctx context.Context, image string, opts *container.HypervisorOptions) (*exec.Cmd, error) {
return exec.Command("true"), nil
}
func TestDevOps_Status_Good(t *testing.T) {
@ -113,7 +107,7 @@ func TestDevOps_Status_Good(t *testing.T) {
require.NoError(t, err)
// Setup mock container manager
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -128,7 +122,7 @@ func TestDevOps_Status_Good(t *testing.T) {
ID: "test-id",
Name: "core-dev",
Status: container.StatusRunning,
PID: syscall.Getpid(), // Use our own PID so isProcessRunning returns true
PID: os.Getpid(), // Use our own PID so isProcessRunning returns true
StartedAt: time.Now().Add(-time.Hour),
Memory: 2048,
CPUs: 4,
@ -145,7 +139,7 @@ func TestDevOps_Status_Good(t *testing.T) {
assert.Equal(t, 4, status.CPUs)
}
func TestDevOps_Status_NotInstalled_Good(t *testing.T) {
func TestDevOps_Status_Good_NotInstalled(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -153,7 +147,7 @@ func TestDevOps_Status_NotInstalled_Good(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -171,20 +165,20 @@ func TestDevOps_Status_NotInstalled_Good(t *testing.T) {
assert.Equal(t, 2222, status.SSHPort)
}
func TestDevOps_Status_NoContainer_Good(t *testing.T) {
func TestDevOps_Status_Good_NoContainer(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image to mark as installed
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err := os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -210,7 +204,7 @@ func TestDevOps_IsRunning_Good(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -224,7 +218,7 @@ func TestDevOps_IsRunning_Good(t *testing.T) {
ID: "test-id",
Name: "core-dev",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
err = state.Add(c)
@ -235,7 +229,7 @@ func TestDevOps_IsRunning_Good(t *testing.T) {
assert.True(t, running)
}
func TestDevOps_IsRunning_NotRunning_Bad(t *testing.T) {
func TestDevOps_IsRunning_Bad_NotRunning(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -243,7 +237,7 @@ func TestDevOps_IsRunning_NotRunning_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -258,7 +252,7 @@ func TestDevOps_IsRunning_NotRunning_Bad(t *testing.T) {
assert.False(t, running)
}
func TestDevOps_IsRunning_ContainerStopped_Bad(t *testing.T) {
func TestDevOps_IsRunning_Bad_ContainerStopped(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -266,7 +260,7 @@ func TestDevOps_IsRunning_ContainerStopped_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -299,7 +293,7 @@ func TestDevOps_findContainer_Good(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -313,7 +307,7 @@ func TestDevOps_findContainer_Good(t *testing.T) {
ID: "test-id",
Name: "my-container",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
err = state.Add(c)
@ -326,7 +320,7 @@ func TestDevOps_findContainer_Good(t *testing.T) {
assert.Equal(t, "my-container", found.Name)
}
func TestDevOps_findContainer_NotFound_Bad(t *testing.T) {
func TestDevOps_findContainer_Bad_NotFound(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -334,7 +328,7 @@ func TestDevOps_findContainer_NotFound_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -349,7 +343,7 @@ func TestDevOps_findContainer_NotFound_Bad(t *testing.T) {
assert.Nil(t, found)
}
func TestDevOps_Stop_NotFound_Bad(t *testing.T) {
func TestDevOps_Stop_Bad_NotFound(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -357,7 +351,7 @@ func TestDevOps_Stop_NotFound_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -372,7 +366,7 @@ func TestDevOps_Stop_NotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "not found")
}
func TestBootOptions_Custom_Good(t *testing.T) {
func TestBootOptions_Good_Custom(t *testing.T) {
opts := BootOptions{
Memory: 8192,
CPUs: 4,
@ -385,7 +379,7 @@ func TestBootOptions_Custom_Good(t *testing.T) {
assert.True(t, opts.Fresh)
}
func TestDevStatus_Struct_Good(t *testing.T) {
func TestDevStatus_Good_Struct(t *testing.T) {
status := DevStatus{
Installed: true,
Running: true,
@ -406,7 +400,7 @@ func TestDevStatus_Struct_Good(t *testing.T) {
assert.Equal(t, time.Hour, status.Uptime)
}
func TestDevOps_Boot_NotInstalled_Bad(t *testing.T) {
func TestDevOps_Boot_Bad_NotInstalled(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -414,7 +408,7 @@ func TestDevOps_Boot_NotInstalled_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -429,20 +423,20 @@ func TestDevOps_Boot_NotInstalled_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "not installed")
}
func TestDevOps_Boot_AlreadyRunning_Bad(t *testing.T) {
func TestDevOps_Boot_Bad_AlreadyRunning(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err := os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -457,7 +451,7 @@ func TestDevOps_Boot_AlreadyRunning_Bad(t *testing.T) {
ID: "test-id",
Name: "core-dev",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
err = state.Add(c)
@ -468,13 +462,13 @@ func TestDevOps_Boot_AlreadyRunning_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "already running")
}
func TestDevOps_Status_WithImageVersion_Good(t *testing.T) {
func TestDevOps_Status_Good_WithImageVersion(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err := os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
@ -487,7 +481,7 @@ func TestDevOps_Status_WithImageVersion_Good(t *testing.T) {
Source: "test",
}
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -504,7 +498,7 @@ func TestDevOps_Status_WithImageVersion_Good(t *testing.T) {
assert.Equal(t, "v1.2.3", status.ImageVersion)
}
func TestDevOps_findContainer_MultipleContainers_Good(t *testing.T) {
func TestDevOps_findContainer_Good_MultipleContainers(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -512,7 +506,7 @@ func TestDevOps_findContainer_MultipleContainers_Good(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -527,14 +521,14 @@ func TestDevOps_findContainer_MultipleContainers_Good(t *testing.T) {
ID: "id-1",
Name: "container-1",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
c2 := &container.Container{
ID: "id-2",
Name: "container-2",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
err = state.Add(c1)
@ -549,7 +543,7 @@ func TestDevOps_findContainer_MultipleContainers_Good(t *testing.T) {
assert.Equal(t, "id-2", found.ID)
}
func TestDevOps_Status_ContainerWithUptime_Good(t *testing.T) {
func TestDevOps_Status_Good_ContainerWithUptime(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -557,7 +551,7 @@ func TestDevOps_Status_ContainerWithUptime_Good(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -572,7 +566,7 @@ func TestDevOps_Status_ContainerWithUptime_Good(t *testing.T) {
ID: "test-id",
Name: "core-dev",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: startTime,
Memory: 4096,
CPUs: 2,
@ -586,7 +580,7 @@ func TestDevOps_Status_ContainerWithUptime_Good(t *testing.T) {
assert.GreaterOrEqual(t, status.Uptime.Hours(), float64(1))
}
func TestDevOps_IsRunning_DifferentContainerName_Bad(t *testing.T) {
func TestDevOps_IsRunning_Bad_DifferentContainerName(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -594,7 +588,7 @@ func TestDevOps_IsRunning_DifferentContainerName_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -609,7 +603,7 @@ func TestDevOps_IsRunning_DifferentContainerName_Bad(t *testing.T) {
ID: "test-id",
Name: "other-container",
Status: container.StatusRunning,
PID: syscall.Getpid(),
PID: os.Getpid(),
StartedAt: time.Now(),
}
err = state.Add(c)
@ -621,21 +615,23 @@ func TestDevOps_IsRunning_DifferentContainerName_Bad(t *testing.T) {
assert.False(t, running)
}
func TestDevOps_Boot_FreshFlag_Good(t *testing.T) {
func TestDevOps_Boot_Good_FreshFlag(t *testing.T) {
t.Setenv("CORE_SKIP_SSH_SCAN", "true")
tempDir := newManagedTempDir(t, "devops-test-")
tempDir, err := os.MkdirTemp("", "devops-test-*")
require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(tempDir) })
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err = os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -669,7 +665,7 @@ func TestDevOps_Boot_FreshFlag_Good(t *testing.T) {
assert.NoError(t, err)
}
func TestDevOps_Stop_ContainerNotRunning_Bad(t *testing.T) {
func TestDevOps_Stop_Bad_ContainerNotRunning(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -677,7 +673,7 @@ func TestDevOps_Stop_ContainerNotRunning_Bad(t *testing.T) {
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -704,21 +700,23 @@ func TestDevOps_Stop_ContainerNotRunning_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "not running")
}
func TestDevOps_Boot_FreshWithNoExisting_Good(t *testing.T) {
func TestDevOps_Boot_Good_FreshWithNoExisting(t *testing.T) {
t.Setenv("CORE_SKIP_SSH_SCAN", "true")
tempDir := newManagedTempDir(t, "devops-boot-fresh-")
tempDir, err := os.MkdirTemp("", "devops-boot-fresh-*")
require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(tempDir) })
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err = os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -740,16 +738,16 @@ func TestDevOps_Boot_FreshWithNoExisting_Good(t *testing.T) {
assert.NoError(t, err)
}
func TestImageName_Format_Good(t *testing.T) {
func TestImageName_Good_Format(t *testing.T) {
name := ImageName()
// Check format: core-devops-{os}-{arch}.qcow2
assert.Contains(t, name, "core-devops-")
assert.Contains(t, name, runtime.GOOS)
assert.Contains(t, name, runtime.GOARCH)
assert.True(t, core.PathExt(name) == ".qcow2")
assert.True(t, filepath.Ext(name) == ".qcow2")
}
func TestDevOps_Install_Delegates_Good(t *testing.T) {
func TestDevOps_Install_Good_Delegates(t *testing.T) {
// This test verifies the Install method delegates to ImageManager
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -767,7 +765,7 @@ func TestDevOps_Install_Delegates_Good(t *testing.T) {
assert.Error(t, err)
}
func TestDevOps_CheckUpdate_Delegates_Good(t *testing.T) {
func TestDevOps_CheckUpdate_Good_Delegates(t *testing.T) {
// This test verifies the CheckUpdate method delegates to ImageManager
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)
@ -785,21 +783,23 @@ func TestDevOps_CheckUpdate_Delegates_Good(t *testing.T) {
assert.Error(t, err)
}
func TestDevOps_Boot_Success_Good(t *testing.T) {
func TestDevOps_Boot_Good_Success(t *testing.T) {
t.Setenv("CORE_SKIP_SSH_SCAN", "true")
tempDir := newManagedTempDir(t, "devops-boot-success-")
tempDir, err := os.MkdirTemp("", "devops-boot-success-*")
require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(tempDir) })
t.Setenv("CORE_IMAGES_DIR", tempDir)
// Create fake image
imagePath := coreutil.JoinPath(tempDir, ImageName())
err := io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tempDir, ImageName())
err = os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
cfg := DefaultConfig()
mgr, err := NewImageManager(io.Local, cfg)
require.NoError(t, err)
statePath := coreutil.JoinPath(tempDir, "containers.json")
statePath := filepath.Join(tempDir, "containers.json")
state := container.NewState(statePath)
h := &mockHypervisor{}
cm := container.NewLinuxKitManagerWithHypervisor(io.Local, state, h)
@ -815,7 +815,7 @@ func TestDevOps_Boot_Success_Good(t *testing.T) {
assert.NoError(t, err) // Mock hypervisor succeeds
}
func TestDevOps_Config_Good(t *testing.T) {
func TestDevOps_Good_Config(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tempDir)

View file

@ -2,15 +2,14 @@ package devenv
import (
"context"
"io/fs"
"encoding/json"
"fmt"
"path/filepath"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/container/sources"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
)
// ImageManager handles image downloads and updates.
@ -37,26 +36,22 @@ type ImageInfo struct {
}
// NewImageManager creates a new image manager.
//
// Usage:
//
// manager, err := NewImageManager(io.Local, cfg)
func NewImageManager(m io.Medium, cfg *Config) (*ImageManager, error) {
imagesDir, err := ImagesDir()
if err != nil {
return nil, err
return nil, coreerr.E("NewImageManager", "get images directory", err)
}
// Ensure images directory exists
if err := m.EnsureDir(imagesDir); err != nil {
return nil, err
return nil, coreerr.E("NewImageManager", "ensure images directory", err)
}
// Load or create manifest
manifestPath := coreutil.JoinPath(imagesDir, "manifest.json")
manifestPath := filepath.Join(imagesDir, "manifest.json")
manifest, err := loadManifest(m, manifestPath)
if err != nil {
return nil, err
return nil, coreerr.E("NewImageManager", "load manifest", err)
}
// Build source list based on config
@ -102,7 +97,7 @@ func (m *ImageManager) IsInstalled() bool {
func (m *ImageManager) Install(ctx context.Context, progress func(downloaded, total int64)) error {
imagesDir, err := ImagesDir()
if err != nil {
return err
return coreerr.E("ImageManager.Install", "get images directory", err)
}
// Find first available source
@ -123,11 +118,11 @@ func (m *ImageManager) Install(ctx context.Context, progress func(downloaded, to
return coreerr.E("ImageManager.Install", "failed to get latest version", err)
}
core.Print(nil, "Downloading %s from %s...", ImageName(), src.Name())
fmt.Printf("Downloading %s from %s...\n", ImageName(), src.Name())
// Download
if err := src.Download(ctx, m.medium, imagesDir, progress); err != nil {
return err
return coreerr.E("ImageManager.Install", "download image", err)
}
// Update manifest
@ -137,7 +132,10 @@ func (m *ImageManager) Install(ctx context.Context, progress func(downloaded, to
Source: src.Name(),
}
return m.manifest.Save()
if err := m.manifest.Save(); err != nil {
return coreerr.E("ImageManager.Install", "save manifest", err)
}
return nil
}
// CheckUpdate checks if an update is available.
@ -162,7 +160,7 @@ func (m *ImageManager) CheckUpdate(ctx context.Context) (current, latest string,
latest, err = src.LatestVersion(ctx)
if err != nil {
return current, "", false, err
return current, "", false, coreerr.E("ImageManager.CheckUpdate", "get latest version", err)
}
hasUpdate = current != latest
@ -176,17 +174,17 @@ func loadManifest(m io.Medium, path string) (*Manifest, error) {
path: path,
}
content, err := m.Read(path)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return manifest, nil
}
return nil, err
if !m.Exists(path) {
return manifest, nil
}
result := core.JSONUnmarshalString(content, manifest)
if !result.OK {
return nil, result.Value.(error)
content, err := m.Read(path)
if err != nil {
return nil, coreerr.E("loadManifest", "read manifest", err)
}
if err := json.Unmarshal([]byte(content), manifest); err != nil {
return nil, coreerr.E("loadManifest", "unmarshal manifest", err)
}
manifest.medium = m
manifest.path = path
@ -196,9 +194,12 @@ func loadManifest(m io.Medium, path string) (*Manifest, error) {
// Save writes the manifest to disk.
func (m *Manifest) Save() error {
result := core.JSONMarshal(m)
if !result.OK {
return result.Value.(error)
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return coreerr.E("Manifest.Save", "marshal manifest", err)
}
return m.medium.Write(m.path, string(result.Value.([]byte)))
if err := m.medium.Write(m.path, string(data)); err != nil {
return coreerr.E("Manifest.Save", "write manifest", err)
}
return nil
}

View file

@ -2,17 +2,18 @@ package devenv
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/sources"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestImageManager_IsInstalled_Good(t *testing.T) {
func TestImageManager_Good_IsInstalled(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -24,15 +25,15 @@ func TestImageManager_IsInstalled_Good(t *testing.T) {
assert.False(t, mgr.IsInstalled())
// Create fake image
imagePath := coreutil.JoinPath(tmpDir, ImageName())
err = io.Local.Write(imagePath, "fake")
imagePath := filepath.Join(tmpDir, ImageName())
err = os.WriteFile(imagePath, []byte("fake"), 0644)
require.NoError(t, err)
// Now installed
assert.True(t, mgr.IsInstalled())
}
func TestImages_NewImageManager_Good(t *testing.T) {
func TestNewImageManager_Good(t *testing.T) {
t.Run("creates manager with cdn source", func(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -64,7 +65,7 @@ func TestImages_NewImageManager_Good(t *testing.T) {
func TestManifest_Save_Good(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "manifest.json")
path := filepath.Join(tmpDir, "manifest.json")
m := &Manifest{
medium: io.Local,
@ -81,7 +82,8 @@ func TestManifest_Save_Good(t *testing.T) {
assert.NoError(t, err)
// Verify file exists and has content
assert.True(t, io.Local.IsFile(path))
_, err = os.Stat(path)
assert.NoError(t, err)
// Reload
m2, err := loadManifest(io.Local, path)
@ -89,11 +91,11 @@ func TestManifest_Save_Good(t *testing.T) {
assert.Equal(t, "1.0.0", m2.Images["test.img"].Version)
}
func TestImages_LoadManifest_Bad(t *testing.T) {
func TestLoadManifest_Bad(t *testing.T) {
t.Run("invalid json", func(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "manifest.json")
err := io.Local.Write(path, "invalid json")
path := filepath.Join(tmpDir, "manifest.json")
err := os.WriteFile(path, []byte("invalid json"), 0644)
require.NoError(t, err)
_, err = loadManifest(io.Local, path)
@ -101,7 +103,7 @@ func TestImages_LoadManifest_Bad(t *testing.T) {
})
}
func TestImages_CheckUpdate_Bad(t *testing.T) {
func TestCheckUpdate_Bad(t *testing.T) {
t.Run("image not installed", func(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -116,7 +118,7 @@ func TestImages_CheckUpdate_Bad(t *testing.T) {
})
}
func TestNewImageManager_AutoSource_Good(t *testing.T) {
func TestNewImageManager_Good_AutoSource(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -129,7 +131,7 @@ func TestNewImageManager_AutoSource_Good(t *testing.T) {
assert.Len(t, mgr.sources, 2) // github and cdn
}
func TestNewImageManager_UnknownSourceFallsToAuto_Good(t *testing.T) {
func TestNewImageManager_Good_UnknownSourceFallsToAuto(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -142,9 +144,9 @@ func TestNewImageManager_UnknownSourceFallsToAuto_Good(t *testing.T) {
assert.Len(t, mgr.sources, 2) // falls to default (auto) which is github + cdn
}
func TestLoadManifest_Empty_Good(t *testing.T) {
func TestLoadManifest_Good_Empty(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "nonexistent.json")
path := filepath.Join(tmpDir, "nonexistent.json")
m, err := loadManifest(io.Local, path)
assert.NoError(t, err)
@ -154,12 +156,12 @@ func TestLoadManifest_Empty_Good(t *testing.T) {
assert.Equal(t, path, m.path)
}
func TestLoadManifest_ExistingData_Good(t *testing.T) {
func TestLoadManifest_Good_ExistingData(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "manifest.json")
path := filepath.Join(tmpDir, "manifest.json")
data := `{"images":{"test.img":{"version":"2.0.0","source":"cdn"}}}`
err := io.Local.Write(path, data)
err := os.WriteFile(path, []byte(data), 0644)
require.NoError(t, err)
m, err := loadManifest(io.Local, path)
@ -169,7 +171,7 @@ func TestLoadManifest_ExistingData_Good(t *testing.T) {
assert.Equal(t, "cdn", m.Images["test.img"].Source)
}
func TestImageInfo_Struct_Good(t *testing.T) {
func TestImageInfo_Good_Struct(t *testing.T) {
info := ImageInfo{
Version: "1.0.0",
SHA256: "abc123",
@ -182,9 +184,9 @@ func TestImageInfo_Struct_Good(t *testing.T) {
assert.Equal(t, "github", info.Source)
}
func TestManifest_Save_CreatesDirs_Good(t *testing.T) {
func TestManifest_Save_Good_CreatesDirs(t *testing.T) {
tmpDir := t.TempDir()
nestedPath := coreutil.JoinPath(tmpDir, "nested", "dir", "manifest.json")
nestedPath := filepath.Join(tmpDir, "nested", "dir", "manifest.json")
m := &Manifest{
medium: io.Local,
@ -198,12 +200,13 @@ func TestManifest_Save_CreatesDirs_Good(t *testing.T) {
assert.NoError(t, err)
// Verify file was created
assert.True(t, io.Local.IsFile(nestedPath))
_, err = os.Stat(nestedPath)
assert.NoError(t, err)
}
func TestManifest_Save_Overwrite_Good(t *testing.T) {
func TestManifest_Save_Good_Overwrite(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "manifest.json")
path := filepath.Join(tmpDir, "manifest.json")
// First save
m1 := &Manifest{
@ -233,7 +236,7 @@ func TestManifest_Save_Overwrite_Good(t *testing.T) {
assert.False(t, exists)
}
func TestImageManager_Install_NoSourceAvailable_Bad(t *testing.T) {
func TestImageManager_Install_Bad_NoSourceAvailable(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -241,7 +244,7 @@ func TestImageManager_Install_NoSourceAvailable_Bad(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: nil, // no sources
}
@ -250,9 +253,9 @@ func TestImageManager_Install_NoSourceAvailable_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "no image source available")
}
func TestNewImageManager_CreatesDir_Good(t *testing.T) {
func TestNewImageManager_Good_CreatesDir(t *testing.T) {
tmpDir := t.TempDir()
imagesDir := coreutil.JoinPath(tmpDir, "images")
imagesDir := filepath.Join(tmpDir, "images")
t.Setenv("CORE_IMAGES_DIR", imagesDir)
cfg := DefaultConfig()
@ -261,7 +264,7 @@ func TestNewImageManager_CreatesDir_Good(t *testing.T) {
assert.NotNil(t, mgr)
// Verify directory was created
info, err := io.Local.Stat(imagesDir)
info, err := os.Stat(imagesDir)
assert.NoError(t, err)
assert.True(t, info.IsDir())
}
@ -285,11 +288,11 @@ func (m *mockImageSource) Download(ctx context.Context, medium io.Medium, dest s
return m.downloadErr
}
// Create a fake image file
imagePath := coreutil.JoinPath(dest, ImageName())
return medium.Write(imagePath, "mock image content")
imagePath := filepath.Join(dest, ImageName())
return os.WriteFile(imagePath, []byte("mock image content"), 0644)
}
func TestImageManager_Install_WithMockSource_Good(t *testing.T) {
func TestImageManager_Install_Good_WithMockSource(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -302,7 +305,7 @@ func TestImageManager_Install_WithMockSource_Good(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{mock},
}
@ -317,7 +320,7 @@ func TestImageManager_Install_WithMockSource_Good(t *testing.T) {
assert.Equal(t, "mock", info.Source)
}
func TestImageManager_Install_DownloadError_Bad(t *testing.T) {
func TestImageManager_Install_Bad_DownloadError(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -331,7 +334,7 @@ func TestImageManager_Install_DownloadError_Bad(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{mock},
}
@ -339,7 +342,7 @@ func TestImageManager_Install_DownloadError_Bad(t *testing.T) {
assert.Error(t, err)
}
func TestImageManager_Install_VersionError_Bad(t *testing.T) {
func TestImageManager_Install_Bad_VersionError(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -352,7 +355,7 @@ func TestImageManager_Install_VersionError_Bad(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{mock},
}
@ -361,7 +364,7 @@ func TestImageManager_Install_VersionError_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "failed to get latest version")
}
func TestImageManager_Install_SkipsUnavailableSource_Good(t *testing.T) {
func TestImageManager_Install_Good_SkipsUnavailableSource(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -378,7 +381,7 @@ func TestImageManager_Install_SkipsUnavailableSource_Good(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{unavailableMock, availableMock},
}
@ -390,7 +393,7 @@ func TestImageManager_Install_SkipsUnavailableSource_Good(t *testing.T) {
assert.Equal(t, "available", info.Source)
}
func TestImageManager_CheckUpdate_WithMockSource_Good(t *testing.T) {
func TestImageManager_CheckUpdate_Good_WithMockSource(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -408,7 +411,7 @@ func TestImageManager_CheckUpdate_WithMockSource_Good(t *testing.T) {
Images: map[string]ImageInfo{
ImageName(): {Version: "v1.0.0", Source: "mock"},
},
path: coreutil.JoinPath(tmpDir, "manifest.json"),
path: filepath.Join(tmpDir, "manifest.json"),
},
sources: []sources.ImageSource{mock},
}
@ -420,7 +423,7 @@ func TestImageManager_CheckUpdate_WithMockSource_Good(t *testing.T) {
assert.True(t, hasUpdate)
}
func TestImageManager_CheckUpdate_NoUpdate_Good(t *testing.T) {
func TestImageManager_CheckUpdate_Good_NoUpdate(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -438,7 +441,7 @@ func TestImageManager_CheckUpdate_NoUpdate_Good(t *testing.T) {
Images: map[string]ImageInfo{
ImageName(): {Version: "v1.0.0", Source: "mock"},
},
path: coreutil.JoinPath(tmpDir, "manifest.json"),
path: filepath.Join(tmpDir, "manifest.json"),
},
sources: []sources.ImageSource{mock},
}
@ -450,7 +453,7 @@ func TestImageManager_CheckUpdate_NoUpdate_Good(t *testing.T) {
assert.False(t, hasUpdate)
}
func TestImageManager_CheckUpdate_NoSource_Bad(t *testing.T) {
func TestImageManager_CheckUpdate_Bad_NoSource(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -467,7 +470,7 @@ func TestImageManager_CheckUpdate_NoSource_Bad(t *testing.T) {
Images: map[string]ImageInfo{
ImageName(): {Version: "v1.0.0", Source: "mock"},
},
path: coreutil.JoinPath(tmpDir, "manifest.json"),
path: filepath.Join(tmpDir, "manifest.json"),
},
sources: []sources.ImageSource{unavailableMock},
}
@ -477,7 +480,7 @@ func TestImageManager_CheckUpdate_NoSource_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "no image source available")
}
func TestImageManager_CheckUpdate_VersionError_Bad(t *testing.T) {
func TestImageManager_CheckUpdate_Bad_VersionError(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -495,7 +498,7 @@ func TestImageManager_CheckUpdate_VersionError_Bad(t *testing.T) {
Images: map[string]ImageInfo{
ImageName(): {Version: "v1.0.0", Source: "mock"},
},
path: coreutil.JoinPath(tmpDir, "manifest.json"),
path: filepath.Join(tmpDir, "manifest.json"),
},
sources: []sources.ImageSource{mock},
}
@ -505,14 +508,14 @@ func TestImageManager_CheckUpdate_VersionError_Bad(t *testing.T) {
assert.Equal(t, "v1.0.0", current) // Current should still be returned
}
func TestImageManager_Install_EmptySources_Bad(t *testing.T) {
func TestImageManager_Install_Bad_EmptySources(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{}, // Empty slice, not nil
}
@ -521,7 +524,7 @@ func TestImageManager_Install_EmptySources_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "no image source available")
}
func TestImageManager_Install_AllUnavailable_Bad(t *testing.T) {
func TestImageManager_Install_Bad_AllUnavailable(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -531,7 +534,7 @@ func TestImageManager_Install_AllUnavailable_Bad(t *testing.T) {
mgr := &ImageManager{
medium: io.Local,
config: DefaultConfig(),
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: coreutil.JoinPath(tmpDir, "manifest.json")},
manifest: &Manifest{medium: io.Local, Images: make(map[string]ImageInfo), path: filepath.Join(tmpDir, "manifest.json")},
sources: []sources.ImageSource{mock1, mock2},
}
@ -540,7 +543,7 @@ func TestImageManager_Install_AllUnavailable_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "no image source available")
}
func TestImageManager_CheckUpdate_FirstSourceUnavailable_Good(t *testing.T) {
func TestImageManager_CheckUpdate_Good_FirstSourceUnavailable(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("CORE_IMAGES_DIR", tmpDir)
@ -555,7 +558,7 @@ func TestImageManager_CheckUpdate_FirstSourceUnavailable_Good(t *testing.T) {
Images: map[string]ImageInfo{
ImageName(): {Version: "v1.0.0", Source: "available"},
},
path: coreutil.JoinPath(tmpDir, "manifest.json"),
path: filepath.Join(tmpDir, "manifest.json"),
},
sources: []sources.ImageSource{unavailable, available},
}
@ -567,7 +570,7 @@ func TestImageManager_CheckUpdate_FirstSourceUnavailable_Good(t *testing.T) {
assert.True(t, hasUpdate)
}
func TestManifest_Struct_Good(t *testing.T) {
func TestManifest_Good_Struct(t *testing.T) {
m := &Manifest{
Images: map[string]ImageInfo{
"test.img": {Version: "1.0.0"},

View file

@ -2,13 +2,13 @@ package devenv
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
)
// ServeOptions configures the dev server.
@ -21,7 +21,7 @@ type ServeOptions struct {
func (d *DevOps) Serve(ctx context.Context, projectDir string, opts ServeOptions) error {
running, err := d.IsRunning(ctx)
if err != nil {
return err
return coreerr.E("DevOps.Serve", "check running state", err)
}
if !running {
return coreerr.E("DevOps.Serve", "dev environment not running (run 'core dev boot' first)", nil)
@ -33,7 +33,7 @@ func (d *DevOps) Serve(ctx context.Context, projectDir string, opts ServeOptions
servePath := projectDir
if opts.Path != "" {
servePath = coreutil.JoinPath(projectDir, opts.Path)
servePath = filepath.Join(projectDir, opts.Path)
}
// Mount project directory via SSHFS
@ -43,8 +43,8 @@ func (d *DevOps) Serve(ctx context.Context, projectDir string, opts ServeOptions
// Detect and run serve command
serveCmd := DetectServeCommand(d.medium, servePath)
core.Print(nil, "Starting server: %s", serveCmd)
core.Print(nil, "Listening on http://localhost:%d", opts.Port)
fmt.Printf("Starting server: %s\n", serveCmd)
fmt.Printf("Listening on http://localhost:%d\n", opts.Port)
// Run serve command via SSH
return d.sshShell(ctx, []string{"cd", "/app", "&&", serveCmd})
@ -52,27 +52,29 @@ func (d *DevOps) Serve(ctx context.Context, projectDir string, opts ServeOptions
// mountProject mounts a directory into the VM via SSHFS.
func (d *DevOps) mountProject(ctx context.Context, path string) error {
absPath := coreutil.AbsPath(path)
absPath, err := filepath.Abs(path)
if err != nil {
return coreerr.E("DevOps.mountProject", "get absolute path", err)
}
// Use reverse SSHFS mount
// The VM connects back to host to mount the directory
cmd := proc.NewCommandContext(ctx, "ssh",
cmd := exec.CommandContext(ctx, "ssh",
"-o", "StrictHostKeyChecking=yes",
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
"-R", "10000:localhost:22", // Reverse tunnel for SSHFS
"-p", core.Sprintf("%d", DefaultSSHPort),
"-p", fmt.Sprintf("%d", DefaultSSHPort),
"root@localhost",
core.Sprintf("mkdir -p /app && sshfs -p 10000 %s@localhost:%s /app -o allow_other", core.Env("USER"), absPath),
fmt.Sprintf("mkdir -p /app && sshfs -p 10000 %s@localhost:%s /app -o allow_other", os.Getenv("USER"), absPath),
)
return cmd.Run()
if err := cmd.Run(); err != nil {
return coreerr.E("DevOps.mountProject", "run sshfs mount", err)
}
return nil
}
// DetectServeCommand auto-detects the serve command for a project.
//
// Usage:
//
// cmd := DetectServeCommand(io.Local, ".")
func DetectServeCommand(m io.Medium, projectDir string) string {
// Laravel/Octane
if hasFile(m, projectDir, "artisan") {

View file

@ -1,65 +1,66 @@
package devenv
import (
"os"
"path/filepath"
"testing"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
)
func TestDetectServeCommand_Laravel_Good(t *testing.T) {
func TestDetectServeCommand_Good_Laravel(t *testing.T) {
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "artisan"), "#!/usr/bin/env php")
err := os.WriteFile(filepath.Join(tmpDir, "artisan"), []byte("#!/usr/bin/env php"), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "php artisan octane:start --host=0.0.0.0 --port=8000", cmd)
}
func TestDetectServeCommand_NodeDev_Good(t *testing.T) {
func TestDetectServeCommand_Good_NodeDev(t *testing.T) {
tmpDir := t.TempDir()
packageJSON := `{"scripts":{"dev":"vite","start":"node index.js"}}`
err := io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), packageJSON)
err := os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(packageJSON), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "npm run dev -- --host 0.0.0.0", cmd)
}
func TestDetectServeCommand_NodeStart_Good(t *testing.T) {
func TestDetectServeCommand_Good_NodeStart(t *testing.T) {
tmpDir := t.TempDir()
packageJSON := `{"scripts":{"start":"node server.js"}}`
err := io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), packageJSON)
err := os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(packageJSON), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "npm start", cmd)
}
func TestDetectServeCommand_PHP_Good(t *testing.T) {
func TestDetectServeCommand_Good_PHP(t *testing.T) {
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"require":{}}`)
err := os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"require":{}}`), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "frankenphp php-server -l :8000", cmd)
}
func TestDetectServeCommand_GoMain_Good(t *testing.T) {
func TestDetectServeCommand_Good_GoMain(t *testing.T) {
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "go.mod"), "module example")
err := os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module example"), 0644)
assert.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(tmpDir, "main.go"), "package main")
err = os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte("package main"), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "go run .", cmd)
}
func TestDetectServeCommand_GoWithoutMain_Good(t *testing.T) {
func TestDetectServeCommand_Good_GoWithoutMain(t *testing.T) {
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "go.mod"), "module example")
err := os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module example"), 0644)
assert.NoError(t, err)
// No main.go, so falls through to fallback
@ -67,41 +68,41 @@ func TestDetectServeCommand_GoWithoutMain_Good(t *testing.T) {
assert.Equal(t, "python3 -m http.server 8000", cmd)
}
func TestDetectServeCommand_Django_Good(t *testing.T) {
func TestDetectServeCommand_Good_Django(t *testing.T) {
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "manage.py"), "#!/usr/bin/env python")
err := os.WriteFile(filepath.Join(tmpDir, "manage.py"), []byte("#!/usr/bin/env python"), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "python manage.py runserver 0.0.0.0:8000", cmd)
}
func TestDetectServeCommand_Fallback_Good(t *testing.T) {
func TestDetectServeCommand_Good_Fallback(t *testing.T) {
tmpDir := t.TempDir()
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "python3 -m http.server 8000", cmd)
}
func TestDetectServeCommand_Priority_Good(t *testing.T) {
func TestDetectServeCommand_Good_Priority(t *testing.T) {
// Laravel (artisan) should take priority over PHP (composer.json)
tmpDir := t.TempDir()
err := io.Local.Write(coreutil.JoinPath(tmpDir, "artisan"), "#!/usr/bin/env php")
err := os.WriteFile(filepath.Join(tmpDir, "artisan"), []byte("#!/usr/bin/env php"), 0644)
assert.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"require":{}}`)
err = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"require":{}}`), 0644)
assert.NoError(t, err)
cmd := DetectServeCommand(io.Local, tmpDir)
assert.Equal(t, "php artisan octane:start --host=0.0.0.0 --port=8000", cmd)
}
func TestServeOptions_Default_Good(t *testing.T) {
func TestServeOptions_Good_Default(t *testing.T) {
opts := ServeOptions{}
assert.Equal(t, 0, opts.Port)
assert.Equal(t, "", opts.Path)
}
func TestServeOptions_Custom_Good(t *testing.T) {
func TestServeOptions_Good_Custom(t *testing.T) {
opts := ServeOptions{
Port: 3000,
Path: "public",
@ -110,25 +111,25 @@ func TestServeOptions_Custom_Good(t *testing.T) {
assert.Equal(t, "public", opts.Path)
}
func TestServe_HasFile_Good(t *testing.T) {
func TestHasFile_Good(t *testing.T) {
tmpDir := t.TempDir()
testFile := coreutil.JoinPath(tmpDir, "test.txt")
err := io.Local.Write(testFile, "content")
testFile := filepath.Join(tmpDir, "test.txt")
err := os.WriteFile(testFile, []byte("content"), 0644)
assert.NoError(t, err)
assert.True(t, hasFile(io.Local, tmpDir, "test.txt"))
}
func TestServe_HasFile_Bad(t *testing.T) {
func TestHasFile_Bad(t *testing.T) {
tmpDir := t.TempDir()
assert.False(t, hasFile(io.Local, tmpDir, "nonexistent.txt"))
}
func TestHasFile_Directory_Bad(t *testing.T) {
func TestHasFile_Bad_Directory(t *testing.T) {
tmpDir := t.TempDir()
subDir := coreutil.JoinPath(tmpDir, "subdir")
err := io.Local.EnsureDir(subDir)
subDir := filepath.Join(tmpDir, "subdir")
err := os.Mkdir(subDir, 0755)
assert.NoError(t, err)
// hasFile correctly returns false for directories (only true for regular files)

View file

@ -2,11 +2,11 @@ package devenv
import (
"context"
"fmt"
"os"
"os/exec"
core "dappco.re/go/core"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/proc"
)
// ShellOptions configures the shell connection.
@ -19,7 +19,7 @@ type ShellOptions struct {
func (d *DevOps) Shell(ctx context.Context, opts ShellOptions) error {
running, err := d.IsRunning(ctx)
if err != nil {
return err
return coreerr.E("DevOps.Shell", "check running state", err)
}
if !running {
return coreerr.E("DevOps.Shell", "dev environment not running (run 'core dev boot' first)", nil)
@ -39,7 +39,7 @@ func (d *DevOps) sshShell(ctx context.Context, command []string) error {
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
"-A", // Agent forwarding
"-p", core.Sprintf("%d", DefaultSSHPort),
"-p", fmt.Sprintf("%d", DefaultSSHPort),
"root@localhost",
}
@ -47,12 +47,15 @@ func (d *DevOps) sshShell(ctx context.Context, command []string) error {
args = append(args, command...)
}
cmd := proc.NewCommandContext(ctx, "ssh", args...)
cmd.Stdin = proc.Stdin
cmd.Stdout = proc.Stdout
cmd.Stderr = proc.Stderr
cmd := exec.CommandContext(ctx, "ssh", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
if err := cmd.Run(); err != nil {
return coreerr.E("DevOps.sshShell", "run ssh command", err)
}
return nil
}
// serialConsole attaches to the QEMU serial console.
@ -60,17 +63,20 @@ func (d *DevOps) serialConsole(ctx context.Context) error {
// Find the container to get its console socket
c, err := d.findContainer(ctx, "core-dev")
if err != nil {
return err
return coreerr.E("DevOps.serialConsole", "find container", err)
}
if c == nil {
return coreerr.E("DevOps.serialConsole", "console not available: container not found", nil)
}
// Use socat to connect to the console socket
socketPath := core.Sprintf("/tmp/core-%s-console.sock", c.ID)
cmd := proc.NewCommandContext(ctx, "socat", "-,raw,echo=0", "unix-connect:"+socketPath)
cmd.Stdin = proc.Stdin
cmd.Stdout = proc.Stdout
cmd.Stderr = proc.Stderr
return cmd.Run()
socketPath := fmt.Sprintf("/tmp/core-%s-console.sock", c.ID)
cmd := exec.CommandContext(ctx, "socat", "-,raw,echo=0", "unix-connect:"+socketPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return coreerr.E("DevOps.serialConsole", "run socat", err)
}
return nil
}

View file

@ -6,13 +6,13 @@ import (
"github.com/stretchr/testify/assert"
)
func TestShellOptions_Default_Good(t *testing.T) {
func TestShellOptions_Good_Default(t *testing.T) {
opts := ShellOptions{}
assert.False(t, opts.Console)
assert.Nil(t, opts.Command)
}
func TestShellOptions_Console_Good(t *testing.T) {
func TestShellOptions_Good_Console(t *testing.T) {
opts := ShellOptions{
Console: true,
}
@ -20,7 +20,7 @@ func TestShellOptions_Console_Good(t *testing.T) {
assert.Nil(t, opts.Command)
}
func TestShellOptions_Command_Good(t *testing.T) {
func TestShellOptions_Good_Command(t *testing.T) {
opts := ShellOptions{
Command: []string{"ls", "-la"},
}
@ -28,7 +28,7 @@ func TestShellOptions_Command_Good(t *testing.T) {
assert.Equal(t, []string{"ls", "-la"}, opts.Command)
}
func TestShellOptions_ConsoleWithCommand_Good(t *testing.T) {
func TestShellOptions_Good_ConsoleWithCommand(t *testing.T) {
opts := ShellOptions{
Console: true,
Command: []string{"echo", "hello"},
@ -37,7 +37,7 @@ func TestShellOptions_ConsoleWithCommand_Good(t *testing.T) {
assert.Equal(t, []string{"echo", "hello"}, opts.Command)
}
func TestShellOptions_EmptyCommand_Good(t *testing.T) {
func TestShellOptions_Good_EmptyCommand(t *testing.T) {
opts := ShellOptions{
Command: []string{},
}

View file

@ -2,37 +2,38 @@ package devenv
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
core "dappco.re/go/core"
coreio "dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
)
// ensureHostKey ensures that the host key for the dev environment is in the known hosts file.
// This is used after boot to allow StrictHostKeyChecking=yes to work.
func ensureHostKey(ctx context.Context, port int) error {
// Skip if requested (used in tests)
if core.Env("CORE_SKIP_SSH_SCAN") == "true" {
if os.Getenv("CORE_SKIP_SSH_SCAN") == "true" {
return nil
}
home := coreutil.HomeDir()
if home == "" {
return coreerr.E("ensureHostKey", "get home dir", nil)
home, err := os.UserHomeDir()
if err != nil {
return coreerr.E("ensureHostKey", "get home dir", err)
}
knownHostsPath := coreutil.JoinPath(home, ".core", "known_hosts")
knownHostsPath := filepath.Join(home, ".core", "known_hosts")
// Ensure directory exists
if err := coreio.Local.EnsureDir(core.PathDir(knownHostsPath)); err != nil {
if err := coreio.Local.EnsureDir(filepath.Dir(knownHostsPath)); err != nil {
return coreerr.E("ensureHostKey", "create known_hosts dir", err)
}
// Get host key using ssh-keyscan
cmd := proc.NewCommandContext(ctx, "ssh-keyscan", "-p", core.Sprintf("%d", port), "localhost")
cmd := exec.CommandContext(ctx, "ssh-keyscan", "-p", fmt.Sprintf("%d", port), "localhost")
out, err := cmd.Output()
if err != nil {
return coreerr.E("ensureHostKey", "ssh-keyscan failed", err)
@ -43,33 +44,42 @@ func ensureHostKey(ctx context.Context, port int) error {
}
// Read existing known_hosts to avoid duplicates
existingStr, _ := coreio.Local.Read(knownHostsPath)
if !coreio.Local.Exists(knownHostsPath) {
if err := coreio.Local.WriteMode(knownHostsPath, "", 0600); err != nil {
return coreerr.E("ensureHostKey", "create known_hosts", err)
existingStr := ""
if coreio.Local.IsFile(knownHostsPath) {
existingStr, err = coreio.Local.Read(knownHostsPath)
if err != nil {
return coreerr.E("ensureHostKey", "read known_hosts", err)
}
}
// Append new keys that aren't already there
f, err := coreio.Local.Append(knownHostsPath)
if err != nil {
return coreerr.E("ensureHostKey", "open known_hosts", err)
var updated strings.Builder
updated.WriteString(existingStr)
if len(existingStr) > 0 && !strings.HasSuffix(existingStr, "\n") {
updated.WriteString("\n")
}
defer f.Close()
lines := core.Split(string(out), "\n")
wroteLine := false
lines := strings.Split(string(out), "\n")
for _, line := range lines {
line = core.Trim(line)
if line == "" || core.HasPrefix(line, "#") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if !core.Contains(existingStr, line) {
if _, err := f.Write([]byte(core.Concat(line, "\n"))); err != nil {
return coreerr.E("ensureHostKey", "write known_hosts", err)
}
if !strings.Contains(existingStr, line) {
updated.WriteString(line)
updated.WriteString("\n")
wroteLine = true
}
}
if !wroteLine {
return nil
}
if err := coreio.Local.WriteMode(knownHostsPath, updated.String(), 0600); err != nil {
return coreerr.E("ensureHostKey", "write known_hosts", err)
}
return nil
}

View file

@ -2,13 +2,13 @@ package devenv
import (
"context"
"encoding/json"
"path/filepath"
"strings"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"gopkg.in/yaml.v3"
"dappco.re/go/core/container/internal/coreutil"
)
// TestConfig holds test configuration from .core/test.yaml.
@ -35,7 +35,7 @@ type TestOptions struct {
func (d *DevOps) Test(ctx context.Context, projectDir string, opts TestOptions) error {
running, err := d.IsRunning(ctx)
if err != nil {
return err
return coreerr.E("DevOps.Test", "check running state", err)
}
if !running {
return coreerr.E("DevOps.Test", "dev environment not running (run 'core dev boot' first)", nil)
@ -45,11 +45,11 @@ func (d *DevOps) Test(ctx context.Context, projectDir string, opts TestOptions)
// Priority: explicit command > named command > auto-detect
if len(opts.Command) > 0 {
cmd = core.Join(" ", opts.Command...)
cmd = strings.Join(opts.Command, " ")
} else if opts.Name != "" {
cfg, err := LoadTestConfig(d.medium, projectDir)
if err != nil {
return err
return coreerr.E("DevOps.Test", "load test config", err)
}
for _, c := range cfg.Commands {
if c.Name == opts.Name {
@ -72,10 +72,6 @@ func (d *DevOps) Test(ctx context.Context, projectDir string, opts TestOptions)
}
// DetectTestCommand auto-detects the test command for a project.
//
// Usage:
//
// cmd := DetectTestCommand(io.Local, ".")
func DetectTestCommand(m io.Medium, projectDir string) string {
// 1. Check .core/test.yaml
cfg, err := LoadTestConfig(m, projectDir)
@ -116,33 +112,41 @@ func DetectTestCommand(m io.Medium, projectDir string) string {
}
// LoadTestConfig loads .core/test.yaml.
//
// Usage:
//
// cfg, err := LoadTestConfig(io.Local, ".")
func LoadTestConfig(m io.Medium, projectDir string) (*TestConfig, error) {
absPath := coreutil.AbsPath(coreutil.JoinPath(projectDir, ".core", "test.yaml"))
path := filepath.Join(projectDir, ".core", "test.yaml")
absPath, err := filepath.Abs(path)
if err != nil {
return nil, coreerr.E("LoadTestConfig", "get absolute path", err)
}
content, err := m.Read(absPath)
if err != nil {
return nil, err
return nil, coreerr.E("LoadTestConfig", "read test config", err)
}
var cfg TestConfig
if err := yaml.Unmarshal([]byte(content), &cfg); err != nil {
return nil, err
return nil, coreerr.E("LoadTestConfig", "unmarshal test config", err)
}
return &cfg, nil
}
func hasFile(m io.Medium, dir, name string) bool {
absPath := coreutil.AbsPath(coreutil.JoinPath(dir, name))
path := filepath.Join(dir, name)
absPath, err := filepath.Abs(path)
if err != nil {
return false
}
return m.IsFile(absPath)
}
func hasPackageScript(m io.Medium, projectDir, script string) bool {
absPath := coreutil.AbsPath(coreutil.JoinPath(projectDir, "package.json"))
path := filepath.Join(projectDir, "package.json")
absPath, err := filepath.Abs(path)
if err != nil {
return false
}
content, err := m.Read(absPath)
if err != nil {
@ -152,8 +156,7 @@ func hasPackageScript(m io.Medium, projectDir, script string) bool {
var pkg struct {
Scripts map[string]string `json:"scripts"`
}
result := core.JSONUnmarshalString(content, &pkg)
if !result.OK {
if err := json.Unmarshal([]byte(content), &pkg); err != nil {
return false
}
@ -162,7 +165,11 @@ func hasPackageScript(m io.Medium, projectDir, script string) bool {
}
func hasComposerScript(m io.Medium, projectDir, script string) bool {
absPath := coreutil.AbsPath(coreutil.JoinPath(projectDir, "composer.json"))
path := filepath.Join(projectDir, "composer.json")
absPath, err := filepath.Abs(path)
if err != nil {
return false
}
content, err := m.Read(absPath)
if err != nil {
@ -172,8 +179,7 @@ func hasComposerScript(m io.Medium, projectDir, script string) bool {
var pkg struct {
Scripts map[string]any `json:"scripts"`
}
result := core.JSONUnmarshalString(content, &pkg)
if !result.OK {
if err := json.Unmarshal([]byte(content), &pkg); err != nil {
return false
}

View file

@ -1,15 +1,16 @@
package devenv
import (
"os"
"path/filepath"
"testing"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/io"
)
func TestDetectTestCommand_ComposerJSON_Good(t *testing.T) {
func TestDetectTestCommand_Good_ComposerJSON(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"scripts":{"test":"pest"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"scripts":{"test":"pest"}}`), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "composer test" {
@ -17,9 +18,9 @@ func TestDetectTestCommand_ComposerJSON_Good(t *testing.T) {
}
}
func TestDetectTestCommand_PackageJSON_Good(t *testing.T) {
func TestDetectTestCommand_Good_PackageJSON(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `{"scripts":{"test":"vitest"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`{"scripts":{"test":"vitest"}}`), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "npm test" {
@ -27,9 +28,9 @@ func TestDetectTestCommand_PackageJSON_Good(t *testing.T) {
}
}
func TestDetectTestCommand_GoMod_Good(t *testing.T) {
func TestDetectTestCommand_Good_GoMod(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "go.mod"), "module example")
_ = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module example"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "go test ./..." {
@ -37,11 +38,11 @@ func TestDetectTestCommand_GoMod_Good(t *testing.T) {
}
}
func TestDetectTestCommand_CoreTestYaml_Good(t *testing.T) {
func TestDetectTestCommand_Good_CoreTestYaml(t *testing.T) {
tmpDir := t.TempDir()
coreDir := coreutil.JoinPath(tmpDir, ".core")
_ = io.Local.EnsureDir(coreDir)
_ = io.Local.Write(coreutil.JoinPath(coreDir, "test.yaml"), "command: custom-test")
coreDir := filepath.Join(tmpDir, ".core")
_ = os.MkdirAll(coreDir, 0755)
_ = os.WriteFile(filepath.Join(coreDir, "test.yaml"), []byte("command: custom-test"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "custom-test" {
@ -49,9 +50,9 @@ func TestDetectTestCommand_CoreTestYaml_Good(t *testing.T) {
}
}
func TestDetectTestCommand_Pytest_Good(t *testing.T) {
func TestDetectTestCommand_Good_Pytest(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "pytest.ini"), "[pytest]")
_ = os.WriteFile(filepath.Join(tmpDir, "pytest.ini"), []byte("[pytest]"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "pytest" {
@ -59,9 +60,9 @@ func TestDetectTestCommand_Pytest_Good(t *testing.T) {
}
}
func TestDetectTestCommand_Taskfile_Good(t *testing.T) {
func TestDetectTestCommand_Good_Taskfile(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "Taskfile.yaml"), "version: '3'")
_ = os.WriteFile(filepath.Join(tmpDir, "Taskfile.yaml"), []byte("version: '3'"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "task test" {
@ -69,7 +70,7 @@ func TestDetectTestCommand_Taskfile_Good(t *testing.T) {
}
}
func TestDetectTestCommand_NoFiles_Bad(t *testing.T) {
func TestDetectTestCommand_Bad_NoFiles(t *testing.T) {
tmpDir := t.TempDir()
cmd := DetectTestCommand(io.Local, tmpDir)
@ -78,13 +79,13 @@ func TestDetectTestCommand_NoFiles_Bad(t *testing.T) {
}
}
func TestDetectTestCommand_Priority_Good(t *testing.T) {
func TestDetectTestCommand_Good_Priority(t *testing.T) {
// .core/test.yaml should take priority over other detection methods
tmpDir := t.TempDir()
coreDir := coreutil.JoinPath(tmpDir, ".core")
_ = io.Local.EnsureDir(coreDir)
_ = io.Local.Write(coreutil.JoinPath(coreDir, "test.yaml"), "command: my-custom-test")
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "go.mod"), "module example")
coreDir := filepath.Join(tmpDir, ".core")
_ = os.MkdirAll(coreDir, 0755)
_ = os.WriteFile(filepath.Join(coreDir, "test.yaml"), []byte("command: my-custom-test"), 0644)
_ = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module example"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "my-custom-test" {
@ -92,10 +93,10 @@ func TestDetectTestCommand_Priority_Good(t *testing.T) {
}
}
func TestTest_LoadTestConfig_Good(t *testing.T) {
func TestLoadTestConfig_Good(t *testing.T) {
tmpDir := t.TempDir()
coreDir := coreutil.JoinPath(tmpDir, ".core")
_ = io.Local.EnsureDir(coreDir)
coreDir := filepath.Join(tmpDir, ".core")
_ = os.MkdirAll(coreDir, 0755)
configYAML := `version: 1
command: default-test
@ -107,7 +108,7 @@ commands:
env:
CI: "true"
`
_ = io.Local.Write(coreutil.JoinPath(coreDir, "test.yaml"), configYAML)
_ = os.WriteFile(filepath.Join(coreDir, "test.yaml"), []byte(configYAML), 0644)
cfg, err := LoadTestConfig(io.Local, tmpDir)
if err != nil {
@ -131,7 +132,7 @@ env:
}
}
func TestLoadTestConfig_NotFound_Bad(t *testing.T) {
func TestLoadTestConfig_Bad_NotFound(t *testing.T) {
tmpDir := t.TempDir()
_, err := LoadTestConfig(io.Local, tmpDir)
@ -140,9 +141,9 @@ func TestLoadTestConfig_NotFound_Bad(t *testing.T) {
}
}
func TestTest_HasPackageScript_Good(t *testing.T) {
func TestHasPackageScript_Good(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `{"scripts":{"test":"jest","build":"webpack"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`{"scripts":{"test":"jest","build":"webpack"}}`), 0644)
if !hasPackageScript(io.Local, tmpDir, "test") {
t.Error("expected to find 'test' script")
@ -152,34 +153,34 @@ func TestTest_HasPackageScript_Good(t *testing.T) {
}
}
func TestHasPackageScript_MissingScript_Bad(t *testing.T) {
func TestHasPackageScript_Bad_MissingScript(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `{"scripts":{"build":"webpack"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`{"scripts":{"build":"webpack"}}`), 0644)
if hasPackageScript(io.Local, tmpDir, "test") {
t.Error("expected not to find 'test' script")
}
}
func TestTest_HasComposerScript_Good(t *testing.T) {
func TestHasComposerScript_Good(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"scripts":{"test":"pest","post-install-cmd":"@php artisan migrate"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"scripts":{"test":"pest","post-install-cmd":"@php artisan migrate"}}`), 0644)
if !hasComposerScript(io.Local, tmpDir, "test") {
t.Error("expected to find 'test' script")
}
}
func TestHasComposerScript_MissingScript_Bad(t *testing.T) {
func TestHasComposerScript_Bad_MissingScript(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"scripts":{"build":"@php build.php"}}`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"scripts":{"build":"@php build.php"}}`), 0644)
if hasComposerScript(io.Local, tmpDir, "test") {
t.Error("expected not to find 'test' script")
}
}
func TestTestConfig_Struct_Good(t *testing.T) {
func TestTestConfig_Good_Struct(t *testing.T) {
cfg := &TestConfig{
Version: 2,
Command: "my-test",
@ -200,7 +201,7 @@ func TestTestConfig_Struct_Good(t *testing.T) {
}
}
func TestTestCommand_Struct_Good(t *testing.T) {
func TestTestCommand_Good_Struct(t *testing.T) {
cmd := TestCommand{
Name: "integration",
Run: "go test -tags=integration ./...",
@ -213,7 +214,7 @@ func TestTestCommand_Struct_Good(t *testing.T) {
}
}
func TestTestOptions_Struct_Good(t *testing.T) {
func TestTestOptions_Good_Struct(t *testing.T) {
opts := TestOptions{
Name: "unit",
Command: []string{"go", "test", "-v"},
@ -226,9 +227,9 @@ func TestTestOptions_Struct_Good(t *testing.T) {
}
}
func TestDetectTestCommand_TaskfileYml_Good(t *testing.T) {
func TestDetectTestCommand_Good_TaskfileYml(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "Taskfile.yml"), "version: '3'")
_ = os.WriteFile(filepath.Join(tmpDir, "Taskfile.yml"), []byte("version: '3'"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "task test" {
@ -236,9 +237,9 @@ func TestDetectTestCommand_TaskfileYml_Good(t *testing.T) {
}
}
func TestDetectTestCommand_Pyproject_Good(t *testing.T) {
func TestDetectTestCommand_Good_Pyproject(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "pyproject.toml"), "[tool.pytest]")
_ = os.WriteFile(filepath.Join(tmpDir, "pyproject.toml"), []byte("[tool.pytest]"), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
if cmd != "pytest" {
@ -246,7 +247,7 @@ func TestDetectTestCommand_Pyproject_Good(t *testing.T) {
}
}
func TestHasPackageScript_NoFile_Bad(t *testing.T) {
func TestHasPackageScript_Bad_NoFile(t *testing.T) {
tmpDir := t.TempDir()
if hasPackageScript(io.Local, tmpDir, "test") {
@ -254,25 +255,25 @@ func TestHasPackageScript_NoFile_Bad(t *testing.T) {
}
}
func TestHasPackageScript_InvalidJSON_Bad(t *testing.T) {
func TestHasPackageScript_Bad_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `invalid json`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`invalid json`), 0644)
if hasPackageScript(io.Local, tmpDir, "test") {
t.Error("expected false for invalid JSON")
}
}
func TestHasPackageScript_NoScripts_Bad(t *testing.T) {
func TestHasPackageScript_Bad_NoScripts(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `{"name":"test"}`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`{"name":"test"}`), 0644)
if hasPackageScript(io.Local, tmpDir, "test") {
t.Error("expected false for missing scripts section")
}
}
func TestHasComposerScript_NoFile_Bad(t *testing.T) {
func TestHasComposerScript_Bad_NoFile(t *testing.T) {
tmpDir := t.TempDir()
if hasComposerScript(io.Local, tmpDir, "test") {
@ -280,29 +281,29 @@ func TestHasComposerScript_NoFile_Bad(t *testing.T) {
}
}
func TestHasComposerScript_InvalidJSON_Bad(t *testing.T) {
func TestHasComposerScript_Bad_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `invalid json`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`invalid json`), 0644)
if hasComposerScript(io.Local, tmpDir, "test") {
t.Error("expected false for invalid JSON")
}
}
func TestHasComposerScript_NoScripts_Bad(t *testing.T) {
func TestHasComposerScript_Bad_NoScripts(t *testing.T) {
tmpDir := t.TempDir()
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"name":"test/pkg"}`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"name":"test/pkg"}`), 0644)
if hasComposerScript(io.Local, tmpDir, "test") {
t.Error("expected false for missing scripts section")
}
}
func TestLoadTestConfig_InvalidYAML_Bad(t *testing.T) {
func TestLoadTestConfig_Bad_InvalidYAML(t *testing.T) {
tmpDir := t.TempDir()
coreDir := coreutil.JoinPath(tmpDir, ".core")
_ = io.Local.EnsureDir(coreDir)
_ = io.Local.Write(coreutil.JoinPath(coreDir, "test.yaml"), "invalid: yaml: :")
coreDir := filepath.Join(tmpDir, ".core")
_ = os.MkdirAll(coreDir, 0755)
_ = os.WriteFile(filepath.Join(coreDir, "test.yaml"), []byte("invalid: yaml: :"), 0644)
_, err := LoadTestConfig(io.Local, tmpDir)
if err == nil {
@ -310,11 +311,11 @@ func TestLoadTestConfig_InvalidYAML_Bad(t *testing.T) {
}
}
func TestLoadTestConfig_MinimalConfig_Good(t *testing.T) {
func TestLoadTestConfig_Good_MinimalConfig(t *testing.T) {
tmpDir := t.TempDir()
coreDir := coreutil.JoinPath(tmpDir, ".core")
_ = io.Local.EnsureDir(coreDir)
_ = io.Local.Write(coreutil.JoinPath(coreDir, "test.yaml"), "version: 1")
coreDir := filepath.Join(tmpDir, ".core")
_ = os.MkdirAll(coreDir, 0755)
_ = os.WriteFile(filepath.Join(coreDir, "test.yaml"), []byte("version: 1"), 0644)
cfg, err := LoadTestConfig(io.Local, tmpDir)
if err != nil {
@ -328,10 +329,10 @@ func TestLoadTestConfig_MinimalConfig_Good(t *testing.T) {
}
}
func TestDetectTestCommand_ComposerWithoutScript_Good(t *testing.T) {
func TestDetectTestCommand_Good_ComposerWithoutScript(t *testing.T) {
tmpDir := t.TempDir()
// composer.json without test script should not return composer test
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "composer.json"), `{"name":"test/pkg"}`)
_ = os.WriteFile(filepath.Join(tmpDir, "composer.json"), []byte(`{"name":"test/pkg"}`), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
// Falls through to empty (no match)
@ -340,10 +341,10 @@ func TestDetectTestCommand_ComposerWithoutScript_Good(t *testing.T) {
}
}
func TestDetectTestCommand_PackageJSONWithoutScript_Good(t *testing.T) {
func TestDetectTestCommand_Good_PackageJSONWithoutScript(t *testing.T) {
tmpDir := t.TempDir()
// package.json without test or dev script
_ = io.Local.Write(coreutil.JoinPath(tmpDir, "package.json"), `{"name":"test"}`)
_ = os.WriteFile(filepath.Join(tmpDir, "package.json"), []byte(`{"name":"test"}`), 0644)
cmd := DetectTestCommand(io.Local, tmpDir)
// Falls through to empty

View file

@ -40,7 +40,7 @@ Tests use `testify` for assertions. Most tests are self-contained and do not req
## Test naming convention
Tests follow the `TestSubject_Function_{Good,Bad,Ugly}` pattern:
Tests follow a `_Good`, `_Bad`, `_Ugly` suffix pattern:
| Suffix | Meaning |
|--------|---------|
@ -51,9 +51,9 @@ Tests follow the `TestSubject_Function_{Good,Bad,Ugly}` pattern:
Examples from the codebase:
```go
func TestState_NewState_Good(t *testing.T) { /* creates state successfully */ }
func TestLoadState_InvalidJSON_Bad(t *testing.T) { /* handles corrupt state file */ }
func TestGetHypervisor_Unknown_Bad(t *testing.T) { /* rejects unknown hypervisor name */ }
func TestNewState_Good(t *testing.T) { /* creates state successfully */ }
func TestLoadState_Bad_InvalidJSON(t *testing.T) { /* handles corrupt state file */ }
func TestGetHypervisor_Bad_Unknown(t *testing.T) { /* rejects unknown hypervisor name */ }
```
@ -108,7 +108,7 @@ go-container/
- **UK English** in all strings, comments, and documentation (colour, organisation, honour).
- **Strict typing** -- All function parameters and return values are typed. No `interface{}` without justification.
- **Error wrapping** -- Use `core.E("Op", "message", err)` rather than `fmt.Errorf`.
- **Error wrapping** -- Use `fmt.Errorf("context: %w", err)` for all error returns.
- **`io.Medium` abstraction** -- File system operations go through `io.Medium` (from `core/io`) rather than directly calling `os` functions. This enables testing with mock file systems. The `io.Local` singleton is used for real file system access.
- **Compile-time interface checks** -- Use `var _ Interface = (*Impl)(nil)` to verify implementations at compile time (see `sources/cdn.go` and `sources/github.go`).
- **Context propagation** -- All operations that might block accept a `context.Context` as their first parameter.
@ -125,14 +125,14 @@ type MyHypervisor struct {
func (h *MyHypervisor) Name() string { return "my-hypervisor" }
func (h *MyHypervisor) Available() bool { /* check if binary exists */ }
func (h *MyHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*proc.Command, error) {
// Build and return the command.
func (h *MyHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error) {
// Build and return exec.Cmd
}
```
2. Register it in `DetectHypervisor()` and `GetHypervisor()` in `hypervisor.go`.
3. Add tests following the `TestSubject_Function_{Good,Bad,Ugly}` naming convention.
3. Add tests following the `_Good`/`_Bad` naming convention.
## Adding a new image source

2
go.mod
View file

@ -3,7 +3,6 @@ module dappco.re/go/core/container
go 1.26.0
require (
dappco.re/go/core v0.8.0-alpha.1
dappco.re/go/core/i18n v0.2.0
dappco.re/go/core/io v0.2.0
dappco.re/go/core/log v0.1.0
@ -14,6 +13,7 @@ require (
)
require (
dappco.re/go/core v0.5.0 // indirect
forge.lthn.ai/core/go v0.3.3 // indirect
forge.lthn.ai/core/go-i18n v0.1.7 // indirect
forge.lthn.ai/core/go-inference v0.1.6 // indirect

4
go.sum
View file

@ -1,5 +1,5 @@
dappco.re/go/core v0.8.0-alpha.1 h1:gj7+Scv+L63Z7wMxbJYHhaRFkHJo2u4MMPuUSv/Dhtk=
dappco.re/go/core v0.8.0-alpha.1/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
dappco.re/go/core v0.5.0 h1:P5DJoaCiK5Q+af5UiTdWqUIW4W4qYKzpgGK50thm21U=
dappco.re/go/core v0.5.0/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
dappco.re/go/core/i18n v0.2.0 h1:NHzk6RCU93/qVRA3f2jvMr9P1R6FYheR/sHL+TnvKbI=
dappco.re/go/core/i18n v0.2.0/go.mod h1:9eSVJXr3OpIGWQvDynfhqcp27xnLMwlYLgsByU+p7ok=
dappco.re/go/core/io v0.2.0 h1:zuudgIiTsQQ5ipVt97saWdGLROovbEB/zdVyy9/l+I4=

View file

@ -2,13 +2,14 @@ package container
import (
"context"
"fmt"
"os/exec"
"path/filepath"
"runtime"
"strings"
core "dappco.re/go/core"
coreio "dappco.re/go/core/io"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/proc"
)
// Hypervisor defines the interface for VM hypervisors.
@ -18,7 +19,7 @@ type Hypervisor interface {
// Available checks if the hypervisor is available on the system.
Available() bool
// BuildCommand builds the command to run a VM with the given options.
BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*proc.Command, error)
BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error)
}
// HypervisorOptions contains options for running a VM.
@ -46,10 +47,6 @@ type QemuHypervisor struct {
}
// NewQemuHypervisor creates a new QEMU hypervisor instance.
//
// Usage:
//
// hv := NewQemuHypervisor()
func NewQemuHypervisor() *QemuHypervisor {
return &QemuHypervisor{
Binary: "qemu-system-x86_64",
@ -63,20 +60,20 @@ func (q *QemuHypervisor) Name() string {
// Available checks if QEMU is installed and accessible.
func (q *QemuHypervisor) Available() bool {
_, err := proc.LookPath(q.Binary)
_, err := exec.LookPath(q.Binary)
return err == nil
}
// BuildCommand creates the QEMU command for running a VM.
func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*proc.Command, error) {
func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error) {
format := DetectImageFormat(image)
if format == FormatUnknown {
return nil, coreerr.E("QemuHypervisor.BuildCommand", "unknown image format: "+image, nil)
}
args := []string{
"-m", core.Sprintf("%d", opts.Memory),
"-smp", core.Sprintf("%d", opts.CPUs),
"-m", fmt.Sprintf("%d", opts.Memory),
"-smp", fmt.Sprintf("%d", opts.CPUs),
"-enable-kvm",
}
@ -86,11 +83,11 @@ func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *H
args = append(args, "-cdrom", image)
args = append(args, "-boot", "d")
case FormatQCOW2:
args = append(args, "-drive", core.Sprintf("file=%s,format=qcow2", image))
args = append(args, "-drive", fmt.Sprintf("file=%s,format=qcow2", image))
case FormatVMDK:
args = append(args, "-drive", core.Sprintf("file=%s,format=vmdk", image))
args = append(args, "-drive", fmt.Sprintf("file=%s,format=vmdk", image))
case FormatRaw:
args = append(args, "-drive", core.Sprintf("file=%s,format=raw", image))
args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw", image))
}
// Always run in nographic mode for container-like behavior
@ -102,10 +99,10 @@ func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *H
// Network with port forwarding
netdev := "user,id=net0"
if opts.SSHPort > 0 {
netdev += core.Sprintf(",hostfwd=tcp::%d-:22", opts.SSHPort)
netdev += fmt.Sprintf(",hostfwd=tcp::%d-:22", opts.SSHPort)
}
for hostPort, guestPort := range opts.Ports {
netdev += core.Sprintf(",hostfwd=tcp::%d-:%d", hostPort, guestPort)
netdev += fmt.Sprintf(",hostfwd=tcp::%d-:%d", hostPort, guestPort)
}
args = append(args, "-netdev", netdev)
args = append(args, "-device", "virtio-net-pci,netdev=net0")
@ -113,10 +110,10 @@ func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *H
// Add 9p shares for volumes
shareID := 0
for hostPath, guestPath := range opts.Volumes {
tag := core.Sprintf("share%d", shareID)
tag := fmt.Sprintf("share%d", shareID)
args = append(args,
"-fsdev", core.Sprintf("local,id=%s,path=%s,security_model=none", tag, hostPath),
"-device", core.Sprintf("virtio-9p-pci,fsdev=%s,mount_tag=%s", tag, core.PathBase(guestPath)),
"-fsdev", fmt.Sprintf("local,id=%s,path=%s,security_model=none", tag, hostPath),
"-device", fmt.Sprintf("virtio-9p-pci,fsdev=%s,mount_tag=%s", tag, filepath.Base(guestPath)),
)
shareID++
}
@ -138,12 +135,13 @@ func (q *QemuHypervisor) BuildCommand(ctx context.Context, image string, opts *H
}
}
return proc.NewCommandContext(ctx, q.Binary, args...), nil
cmd := exec.CommandContext(ctx, q.Binary, args...)
return cmd, nil
}
// isKVMAvailable checks if KVM is available on the system.
func isKVMAvailable() bool {
return coreio.Local.Exists("/dev/kvm")
return io.Local.Exists("/dev/kvm")
}
// HyperkitHypervisor implements Hypervisor for macOS Hyperkit.
@ -153,10 +151,6 @@ type HyperkitHypervisor struct {
}
// NewHyperkitHypervisor creates a new Hyperkit hypervisor instance.
//
// Usage:
//
// hv := NewHyperkitHypervisor()
func NewHyperkitHypervisor() *HyperkitHypervisor {
return &HyperkitHypervisor{
Binary: "hyperkit",
@ -173,20 +167,20 @@ func (h *HyperkitHypervisor) Available() bool {
if runtime.GOOS != "darwin" {
return false
}
_, err := proc.LookPath(h.Binary)
_, err := exec.LookPath(h.Binary)
return err == nil
}
// BuildCommand creates the Hyperkit command for running a VM.
func (h *HyperkitHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*proc.Command, error) {
func (h *HyperkitHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error) {
format := DetectImageFormat(image)
if format == FormatUnknown {
return nil, coreerr.E("HyperkitHypervisor.BuildCommand", "unknown image format: "+image, nil)
}
args := []string{
"-m", core.Sprintf("%dM", opts.Memory),
"-c", core.Sprintf("%d", opts.CPUs),
"-m", fmt.Sprintf("%dM", opts.Memory),
"-c", fmt.Sprintf("%d", opts.CPUs),
"-A", // ACPI
"-u", // Unlimited console output
"-s", "0:0,hostbridge",
@ -197,9 +191,9 @@ func (h *HyperkitHypervisor) BuildCommand(ctx context.Context, image string, opt
// Add PCI slot for disk (slot 2)
switch format {
case FormatISO:
args = append(args, "-s", core.Sprintf("2:0,ahci-cd,%s", image))
args = append(args, "-s", fmt.Sprintf("2:0,ahci-cd,%s", image))
case FormatQCOW2, FormatVMDK, FormatRaw:
args = append(args, "-s", core.Sprintf("2:0,virtio-blk,%s", image))
args = append(args, "-s", fmt.Sprintf("2:0,virtio-blk,%s", image))
}
// Network with port forwarding (slot 3)
@ -208,27 +202,24 @@ func (h *HyperkitHypervisor) BuildCommand(ctx context.Context, image string, opt
// Hyperkit uses slirp for user networking with port forwarding
portForwards := make([]string, 0)
if opts.SSHPort > 0 {
portForwards = append(portForwards, core.Sprintf("tcp:%d:22", opts.SSHPort))
portForwards = append(portForwards, fmt.Sprintf("tcp:%d:22", opts.SSHPort))
}
for hostPort, guestPort := range opts.Ports {
portForwards = append(portForwards, core.Sprintf("tcp:%d:%d", hostPort, guestPort))
portForwards = append(portForwards, fmt.Sprintf("tcp:%d:%d", hostPort, guestPort))
}
if len(portForwards) > 0 {
netArgs += "," + core.Join(",", portForwards...)
netArgs += "," + strings.Join(portForwards, ",")
}
}
args = append(args, "-s", "3:0,"+netArgs)
return proc.NewCommandContext(ctx, h.Binary, args...), nil
cmd := exec.CommandContext(ctx, h.Binary, args...)
return cmd, nil
}
// DetectImageFormat determines the image format from its file extension.
//
// Usage:
//
// format := DetectImageFormat("/tmp/core-dev.qcow2")
func DetectImageFormat(path string) ImageFormat {
ext := core.Lower(core.PathExt(path))
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".iso":
return FormatISO
@ -244,10 +235,6 @@ func DetectImageFormat(path string) ImageFormat {
}
// DetectHypervisor returns the best available hypervisor for the current platform.
//
// Usage:
//
// hv, err := DetectHypervisor()
func DetectHypervisor() (Hypervisor, error) {
// On macOS, prefer Hyperkit if available, fall back to QEMU
if runtime.GOOS == "darwin" {
@ -267,12 +254,8 @@ func DetectHypervisor() (Hypervisor, error) {
}
// GetHypervisor returns a specific hypervisor by name.
//
// Usage:
//
// hv, err := GetHypervisor("qemu")
func GetHypervisor(name string) (Hypervisor, error) {
switch core.Lower(name) {
switch strings.ToLower(name) {
case "qemu":
h := NewQemuHypervisor()
if !h.Available() {

View file

@ -20,7 +20,7 @@ func TestQemuHypervisor_Available_Good(t *testing.T) {
assert.IsType(t, true, available)
}
func TestQemuHypervisor_Available_InvalidBinary_Bad(t *testing.T) {
func TestQemuHypervisor_Available_Bad_InvalidBinary(t *testing.T) {
q := &QemuHypervisor{
Binary: "nonexistent-qemu-binary-that-does-not-exist",
}
@ -44,7 +44,7 @@ func TestHyperkitHypervisor_Available_Good(t *testing.T) {
}
}
func TestHyperkitHypervisor_Available_NotDarwin_Bad(t *testing.T) {
func TestHyperkitHypervisor_Available_Bad_NotDarwin(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("This test only runs on non-darwin systems")
}
@ -56,7 +56,7 @@ func TestHyperkitHypervisor_Available_NotDarwin_Bad(t *testing.T) {
assert.False(t, available, "Hyperkit should not be available on non-darwin systems")
}
func TestHyperkitHypervisor_Available_InvalidBinary_Bad(t *testing.T) {
func TestHyperkitHypervisor_Available_Bad_InvalidBinary(t *testing.T) {
h := &HyperkitHypervisor{
Binary: "nonexistent-hyperkit-binary-that-does-not-exist",
}
@ -66,7 +66,7 @@ func TestHyperkitHypervisor_Available_InvalidBinary_Bad(t *testing.T) {
assert.False(t, available)
}
func TestHypervisor_IsKVMAvailable_Good(t *testing.T) {
func TestIsKVMAvailable_Good(t *testing.T) {
// This test verifies the function runs without error
// The actual result depends on the system
result := isKVMAvailable()
@ -80,7 +80,7 @@ func TestHypervisor_IsKVMAvailable_Good(t *testing.T) {
}
}
func TestHypervisor_DetectHypervisor_Good(t *testing.T) {
func TestDetectHypervisor_Good(t *testing.T) {
// DetectHypervisor tries to find an available hypervisor
hv, err := DetectHypervisor()
@ -95,7 +95,7 @@ func TestHypervisor_DetectHypervisor_Good(t *testing.T) {
}
}
func TestGetHypervisor_Qemu_Good(t *testing.T) {
func TestGetHypervisor_Good_Qemu(t *testing.T) {
hv, err := GetHypervisor("qemu")
// Depends on whether qemu is installed
@ -107,7 +107,7 @@ func TestGetHypervisor_Qemu_Good(t *testing.T) {
}
}
func TestGetHypervisor_QemuUppercase_Good(t *testing.T) {
func TestGetHypervisor_Good_QemuUppercase(t *testing.T) {
hv, err := GetHypervisor("QEMU")
// Depends on whether qemu is installed
@ -119,7 +119,7 @@ func TestGetHypervisor_QemuUppercase_Good(t *testing.T) {
}
}
func TestGetHypervisor_Hyperkit_Good(t *testing.T) {
func TestGetHypervisor_Good_Hyperkit(t *testing.T) {
hv, err := GetHypervisor("hyperkit")
// On non-darwin systems, should always fail
@ -137,14 +137,14 @@ func TestGetHypervisor_Hyperkit_Good(t *testing.T) {
}
}
func TestGetHypervisor_Unknown_Bad(t *testing.T) {
func TestGetHypervisor_Bad_Unknown(t *testing.T) {
_, err := GetHypervisor("unknown-hypervisor")
assert.Error(t, err)
assert.Contains(t, err.Error(), "unknown hypervisor")
}
func TestQemuHypervisor_BuildCommand_WithPortsAndVolumes_Good(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Good_WithPortsAndVolumes(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -172,7 +172,7 @@ func TestQemuHypervisor_BuildCommand_WithPortsAndVolumes_Good(t *testing.T) {
assert.Contains(t, args, "4")
}
func TestQemuHypervisor_BuildCommand_QCow2Format_Good(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Good_QCow2Format(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -192,7 +192,7 @@ func TestQemuHypervisor_BuildCommand_QCow2Format_Good(t *testing.T) {
assert.True(t, found, "Should have qcow2 drive argument")
}
func TestQemuHypervisor_BuildCommand_VMDKFormat_Good(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Good_VMDKFormat(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -212,7 +212,7 @@ func TestQemuHypervisor_BuildCommand_VMDKFormat_Good(t *testing.T) {
assert.True(t, found, "Should have vmdk drive argument")
}
func TestQemuHypervisor_BuildCommand_RawFormat_Good(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Good_RawFormat(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -232,7 +232,7 @@ func TestQemuHypervisor_BuildCommand_RawFormat_Good(t *testing.T) {
assert.True(t, found, "Should have raw drive argument")
}
func TestHyperkitHypervisor_BuildCommand_WithPorts_Good(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Good_WithPorts(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()
@ -255,7 +255,7 @@ func TestHyperkitHypervisor_BuildCommand_WithPorts_Good(t *testing.T) {
assert.Contains(t, args, "2")
}
func TestHyperkitHypervisor_BuildCommand_QCow2Format_Good(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Good_QCow2Format(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()
@ -266,7 +266,7 @@ func TestHyperkitHypervisor_BuildCommand_QCow2Format_Good(t *testing.T) {
assert.NotNil(t, cmd)
}
func TestHyperkitHypervisor_BuildCommand_RawFormat_Good(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Good_RawFormat(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()
@ -277,7 +277,7 @@ func TestHyperkitHypervisor_BuildCommand_RawFormat_Good(t *testing.T) {
assert.NotNil(t, cmd)
}
func TestHyperkitHypervisor_BuildCommand_NoPorts_Good(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Good_NoPorts(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()
@ -293,7 +293,7 @@ func TestHyperkitHypervisor_BuildCommand_NoPorts_Good(t *testing.T) {
assert.NotNil(t, cmd)
}
func TestQemuHypervisor_BuildCommand_NoSSHPort_Good(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Good_NoSSHPort(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -309,7 +309,7 @@ func TestQemuHypervisor_BuildCommand_NoSSHPort_Good(t *testing.T) {
assert.NotNil(t, cmd)
}
func TestQemuHypervisor_BuildCommand_UnknownFormat_Bad(t *testing.T) {
func TestQemuHypervisor_BuildCommand_Bad_UnknownFormat(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
@ -320,7 +320,7 @@ func TestQemuHypervisor_BuildCommand_UnknownFormat_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "unknown image format")
}
func TestHyperkitHypervisor_BuildCommand_UnknownFormat_Bad(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Bad_UnknownFormat(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()
@ -336,7 +336,7 @@ func TestHyperkitHypervisor_Name_Good(t *testing.T) {
assert.Equal(t, "hyperkit", h.Name())
}
func TestHyperkitHypervisor_BuildCommand_ISOFormat_Good(t *testing.T) {
func TestHyperkitHypervisor_BuildCommand_Good_ISOFormat(t *testing.T) {
h := NewHyperkitHypervisor()
ctx := context.Background()

View file

@ -1,76 +0,0 @@
package coreutil
import (
core "dappco.re/go/core"
coreio "dappco.re/go/core/io"
)
// DirSep returns the active directory separator.
func DirSep() string {
if ds := core.Env("DS"); ds != "" {
return ds
}
return "/"
}
// JoinPath joins path segments using the active directory separator.
func JoinPath(parts ...string) string {
if len(parts) == 0 {
return ""
}
return core.CleanPath(core.Join(DirSep(), parts...), DirSep())
}
// HomeDir returns the current home directory, honouring test-time env overrides.
func HomeDir() string {
if home := core.Env("CORE_HOME"); home != "" {
return home
}
if home := core.Env("HOME"); home != "" {
return home
}
if home := core.Env("USERPROFILE"); home != "" {
return home
}
return core.Env("DIR_HOME")
}
// CurrentDir returns the current working directory, honouring shell PWD.
func CurrentDir() string {
if pwd := core.Env("PWD"); pwd != "" {
return pwd
}
return core.Env("DIR_CWD")
}
// TempDir returns the process temp directory, honouring TMPDIR.
func TempDir() string {
if dir := core.Env("TMPDIR"); dir != "" {
return dir
}
return core.Env("DIR_TMP")
}
// AbsPath resolves a path against the current working directory.
func AbsPath(path string) string {
if path == "" {
return CurrentDir()
}
if core.PathIsAbs(path) {
return core.CleanPath(path, DirSep())
}
return JoinPath(CurrentDir(), path)
}
// MkdirTemp creates a temporary directory with a deterministic Core-generated name.
func MkdirTemp(prefix string) (string, error) {
name := prefix
if name == "" {
name = "tmp-"
}
path := JoinPath(TempDir(), core.Concat(name, core.ID()))
if err := coreio.Local.EnsureDir(path); err != nil {
return "", err
}
return path, nil
}

View file

@ -1,401 +0,0 @@
package proc
import (
"context"
goio "io"
"sync"
"syscall"
core "dappco.re/go/core"
coreio "dappco.re/go/core/io"
"dappco.re/go/core/container/internal/coreutil"
)
type fdProvider interface {
Fd() uintptr
}
type Process struct {
Pid int
}
func (p *Process) Kill() error {
if p == nil || p.Pid <= 0 {
return nil
}
return syscall.Kill(p.Pid, syscall.SIGKILL)
}
func (p *Process) Signal(sig syscall.Signal) error {
if p == nil || p.Pid <= 0 {
return nil
}
return syscall.Kill(p.Pid, sig)
}
type Command struct {
Path string
Args []string
Dir string
Env []string
Stdin goio.Reader
Stdout goio.Writer
Stderr goio.Writer
Process *Process
ctx context.Context
started bool
done chan struct{}
waitErr error
waited bool
waitMu sync.Mutex
stdoutPipe *pipeReader
stderrPipe *pipeReader
}
type pipeReader struct {
fd int
childFD int
}
func (p *pipeReader) Read(data []byte) (int, error) {
n, err := syscall.Read(p.fd, data)
if err != nil {
return n, err
}
if n == 0 {
return 0, goio.EOF
}
return n, nil
}
func (p *pipeReader) Close() error {
var first error
if p.fd >= 0 {
if err := syscall.Close(p.fd); err != nil {
first = err
}
p.fd = -1
}
if p.childFD >= 0 {
if err := syscall.Close(p.childFD); err != nil && first == nil {
first = err
}
p.childFD = -1
}
return first
}
type stdioReader struct {
fd int
}
func (s *stdioReader) Read(data []byte) (int, error) {
n, err := syscall.Read(s.fd, data)
if err != nil {
return n, err
}
if n == 0 {
return 0, goio.EOF
}
return n, nil
}
func (s *stdioReader) Close() error { return nil }
func (s *stdioReader) Fd() uintptr { return uintptr(s.fd) }
type stdioWriter struct {
fd int
}
func (s *stdioWriter) Write(data []byte) (int, error) {
total := 0
for len(data) > 0 {
n, err := syscall.Write(s.fd, data)
total += n
if err != nil {
return total, err
}
data = data[n:]
}
return total, nil
}
func (s *stdioWriter) Close() error { return nil }
func (s *stdioWriter) Fd() uintptr { return uintptr(s.fd) }
var (
Stdin goio.ReadCloser = &stdioReader{fd: 0}
Stdout goio.WriteCloser = &stdioWriter{fd: 1}
Stderr goio.WriteCloser = &stdioWriter{fd: 2}
)
var (
nullFD int
nullOnce sync.Once
nullErr error
)
func Environ() []string {
return syscall.Environ()
}
func NewCommandContext(ctx context.Context, name string, args ...string) *Command {
if ctx == nil {
ctx = context.Background()
}
return &Command{
Path: name,
Args: append([]string{name}, args...),
ctx: ctx,
}
}
func NewCommand(name string, args ...string) *Command {
return NewCommandContext(context.Background(), name, args...)
}
func LookPath(name string) (string, error) {
if name == "" {
return "", core.E("proc.LookPath", "empty command", nil)
}
if core.Contains(name, "/") || core.Contains(name, "\\") {
if isExecutable(name) {
return name, nil
}
return "", core.E("proc.LookPath", core.Concat("executable not found: ", name), nil)
}
pathEnv := core.Env("PATH")
sep := core.Env("PS")
if sep == "" {
sep = ":"
}
for _, dir := range core.Split(pathEnv, sep) {
if dir == "" {
dir = "."
}
candidate := coreutil.JoinPath(dir, name)
if isExecutable(candidate) {
return candidate, nil
}
}
return "", core.E("proc.LookPath", core.Concat("executable not found: ", name), nil)
}
func (c *Command) StdoutPipe() (goio.ReadCloser, error) {
if c.started {
return nil, core.E("proc.Command.StdoutPipe", "command already started", nil)
}
if c.stdoutPipe != nil {
return nil, core.E("proc.Command.StdoutPipe", "stdout pipe already requested", nil)
}
fds := make([]int, 2)
if err := syscall.Pipe(fds); err != nil {
return nil, err
}
c.stdoutPipe = &pipeReader{fd: fds[0], childFD: fds[1]}
return c.stdoutPipe, nil
}
func (c *Command) StderrPipe() (goio.ReadCloser, error) {
if c.started {
return nil, core.E("proc.Command.StderrPipe", "command already started", nil)
}
if c.stderrPipe != nil {
return nil, core.E("proc.Command.StderrPipe", "stderr pipe already requested", nil)
}
fds := make([]int, 2)
if err := syscall.Pipe(fds); err != nil {
return nil, err
}
c.stderrPipe = &pipeReader{fd: fds[0], childFD: fds[1]}
return c.stderrPipe, nil
}
func (c *Command) Start() error {
if c.started {
return core.E("proc.Command.Start", "command already started", nil)
}
if c.ctx != nil {
if err := c.ctx.Err(); err != nil {
return err
}
}
path, err := LookPath(c.Path)
if err != nil {
return err
}
files := []uintptr{
c.inputFD(),
c.outputFD(c.stdoutPipe, c.Stdout),
c.outputFD(c.stderrPipe, c.Stderr),
}
env := c.Env
if env == nil {
env = Environ()
}
pid, _, err := syscall.StartProcess(path, c.Args, &syscall.ProcAttr{
Dir: c.Dir,
Env: env,
Files: files,
})
if err != nil {
return err
}
c.Process = &Process{Pid: pid}
c.done = make(chan struct{})
c.started = true
c.closeChildPipeEnds()
c.watchContext()
return nil
}
func (c *Command) Run() error {
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
func (c *Command) Output() ([]byte, error) {
if c.Stdout != nil {
return nil, core.E("proc.Command.Output", "stdout already configured", nil)
}
reader, err := c.StdoutPipe()
if err != nil {
return nil, err
}
defer func() { _ = reader.Close() }()
if err := c.Start(); err != nil {
return nil, err
}
data, readErr := goio.ReadAll(reader)
waitErr := c.Wait()
if readErr != nil {
return nil, readErr
}
if waitErr != nil {
return data, waitErr
}
return data, nil
}
func (c *Command) Wait() error {
c.waitMu.Lock()
defer c.waitMu.Unlock()
if !c.started {
return core.E("proc.Command.Wait", "command not started", nil)
}
if c.waited {
return c.waitErr
}
var status syscall.WaitStatus
for {
_, err := syscall.Wait4(c.Process.Pid, &status, 0, nil)
if err == syscall.EINTR {
continue
}
if err != nil {
c.waitErr = err
break
}
if status.Exited() && status.ExitStatus() != 0 {
c.waitErr = core.E("proc.Command.Wait", core.Sprintf("exit status %d", status.ExitStatus()), nil)
}
if status.Signaled() {
c.waitErr = core.E("proc.Command.Wait", core.Sprintf("signal %d", status.Signal()), nil)
}
break
}
c.waited = true
close(c.done)
return c.waitErr
}
func (c *Command) inputFD() uintptr {
if c.Stdin == nil {
return uintptr(openNull())
}
if file, ok := c.Stdin.(fdProvider); ok {
return file.Fd()
}
return uintptr(openNull())
}
func (c *Command) outputFD(pipe *pipeReader, writer goio.Writer) uintptr {
if pipe != nil {
return uintptr(pipe.childFD)
}
if writer == nil {
return uintptr(openNull())
}
if file, ok := writer.(fdProvider); ok {
return file.Fd()
}
return uintptr(openNull())
}
func (c *Command) closeChildPipeEnds() {
if c.stdoutPipe != nil && c.stdoutPipe.childFD >= 0 {
_ = syscall.Close(c.stdoutPipe.childFD)
c.stdoutPipe.childFD = -1
}
if c.stderrPipe != nil && c.stderrPipe.childFD >= 0 {
_ = syscall.Close(c.stderrPipe.childFD)
c.stderrPipe.childFD = -1
}
}
func (c *Command) watchContext() {
if c.ctx == nil || c.done == nil || c.Process == nil {
return
}
go func() {
select {
case <-c.ctx.Done():
_ = c.Process.Kill()
case <-c.done:
}
}()
}
func isExecutable(path string) bool {
info, err := coreio.Local.Stat(path)
if err != nil {
return false
}
if !info.Mode().IsRegular() {
return false
}
return info.Mode()&0111 != 0
}
func openNull() int {
nullOnce.Do(func() {
nullFD, nullErr = syscall.Open("/dev/null", syscall.O_RDWR, 0)
})
if nullErr != nil {
return 2
}
return nullFD
}

View file

@ -3,15 +3,15 @@ package container
import (
"bufio"
"context"
"fmt"
goio "io"
"os"
"os/exec"
"syscall"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/proc"
)
// LinuxKitManager implements the Manager interface for LinuxKit VMs.
@ -22,10 +22,6 @@ type LinuxKitManager struct {
}
// NewLinuxKitManager creates a new LinuxKit manager with auto-detected hypervisor.
//
// Usage:
//
// manager, err := NewLinuxKitManager(io.Local)
func NewLinuxKitManager(m io.Medium) (*LinuxKitManager, error) {
statePath, err := DefaultStatePath()
if err != nil {
@ -39,7 +35,7 @@ func NewLinuxKitManager(m io.Medium) (*LinuxKitManager, error) {
hypervisor, err := DetectHypervisor()
if err != nil {
return nil, err
return nil, coreerr.E("NewLinuxKitManager", "detect hypervisor", err)
}
return &LinuxKitManager{
@ -50,10 +46,6 @@ func NewLinuxKitManager(m io.Medium) (*LinuxKitManager, error) {
}
// NewLinuxKitManagerWithHypervisor creates a manager with a specific hypervisor.
//
// Usage:
//
// manager := NewLinuxKitManagerWithHypervisor(io.Local, state, hypervisor)
func NewLinuxKitManagerWithHypervisor(m io.Medium, state *State, hypervisor Hypervisor) *LinuxKitManager {
return &LinuxKitManager{
state: state,
@ -204,11 +196,11 @@ func (m *LinuxKitManager) Run(ctx context.Context, image string, opts RunOptions
// Copy output to both log and stdout
go func() {
mw := goio.MultiWriter(logFile, proc.Stdout)
mw := goio.MultiWriter(logFile, os.Stdout)
_, _ = goio.Copy(mw, stdout)
}()
go func() {
mw := goio.MultiWriter(logFile, proc.Stderr)
mw := goio.MultiWriter(logFile, os.Stderr)
_, _ = goio.Copy(mw, stderr)
}()
@ -228,7 +220,7 @@ func (m *LinuxKitManager) Run(ctx context.Context, image string, opts RunOptions
}
// waitForExit monitors a detached process and updates state when it exits.
func (m *LinuxKitManager) waitForExit(id string, cmd *proc.Command) {
func (m *LinuxKitManager) waitForExit(id string, cmd *exec.Cmd) {
err := cmd.Wait()
container, ok := m.state.Get(id)
@ -257,7 +249,16 @@ func (m *LinuxKitManager) Stop(ctx context.Context, id string) error {
}
// Find the process
if err := syscall.Kill(container.PID, syscall.SIGTERM); err != nil {
process, err := os.FindProcess(container.PID)
if err != nil {
// Process doesn't exist, update state
container.Status = StatusStopped
_ = m.state.Update(container)
return nil
}
// Send SIGTERM
if err := process.Signal(syscall.SIGTERM); err != nil {
// Process might already be gone
container.Status = StatusStopped
_ = m.state.Update(container)
@ -266,23 +267,28 @@ func (m *LinuxKitManager) Stop(ctx context.Context, id string) error {
// Honour already-cancelled contexts before waiting
if err := ctx.Err(); err != nil {
_ = syscall.Kill(container.PID, syscall.SIGKILL)
_ = process.Signal(syscall.SIGKILL)
return err
}
deadline := time.After(10 * time.Second)
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
// Wait for graceful shutdown with timeout
done := make(chan struct{})
go func() {
_, _ = process.Wait()
close(done)
}()
for isProcessRunning(container.PID) {
select {
case <-deadline:
_ = syscall.Kill(container.PID, syscall.SIGKILL)
case <-ctx.Done():
_ = syscall.Kill(container.PID, syscall.SIGKILL)
return ctx.Err()
case <-ticker.C:
}
select {
case <-done:
// Process exited gracefully
case <-time.After(10 * time.Second):
// Force kill
_ = process.Signal(syscall.SIGKILL)
<-done
case <-ctx.Done():
// Context cancelled
_ = process.Signal(syscall.SIGKILL)
return ctx.Err()
}
container.Status = StatusStopped
@ -292,7 +298,7 @@ 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
return nil, coreerr.E("LinuxKitManager.List", "check context", err)
}
containers := m.state.All()
@ -311,16 +317,20 @@ func (m *LinuxKitManager) List(ctx context.Context) ([]*Container, error) {
// isProcessRunning checks if a process with the given PID is still running.
func isProcessRunning(pid int) bool {
if pid <= 0 {
process, err := os.FindProcess(pid)
if err != nil {
return false
}
return syscall.Kill(pid, syscall.Signal(0)) == nil
// On Unix, FindProcess always succeeds, so we need to send signal 0 to check
err = process.Signal(syscall.Signal(0))
return err == nil
}
// 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
return nil, coreerr.E("LinuxKitManager.Logs", "check context", err)
}
_, ok := m.state.Get(id)
if !ok {
@ -338,11 +348,19 @@ func (m *LinuxKitManager) Logs(ctx context.Context, id string, follow bool) (goi
if !follow {
// Simple case: just open and return the file
return m.medium.Open(logPath)
file, err := m.medium.Open(logPath)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Logs", "open log file", err)
}
return file, nil
}
// Follow mode: create a reader that tails the file
return newFollowReader(ctx, m.medium, logPath)
reader, err := newFollowReader(ctx, m.medium, logPath)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Logs", "create follow reader", err)
}
return reader, nil
}
// followReader implements goio.ReadCloser for following log files.
@ -358,7 +376,7 @@ type followReader struct {
func newFollowReader(ctx context.Context, m io.Medium, path string) (*followReader, error) {
file, err := m.Open(path)
if err != nil {
return nil, err
return nil, coreerr.E("newFollowReader", "open log file", err)
}
// Note: We don't seek here because Medium.Open doesn't guarantee Seekability.
@ -388,7 +406,7 @@ func (f *followReader) Read(p []byte) (int, error) {
return n, nil
}
if err != nil && err != goio.EOF {
return 0, err
return 0, coreerr.E("followReader.Read", "read log stream", err)
}
// No data available, wait a bit and try again
@ -410,7 +428,7 @@ 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
return coreerr.E("LinuxKitManager.Exec", "check context", err)
}
container, ok := m.state.Get(id)
if !ok {
@ -426,7 +444,7 @@ func (m *LinuxKitManager) Exec(ctx context.Context, id string, cmd []string) err
// Build SSH command
sshArgs := []string{
"-p", core.Sprintf("%d", sshPort),
"-p", fmt.Sprintf("%d", sshPort),
"-o", "StrictHostKeyChecking=yes",
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
@ -434,12 +452,15 @@ func (m *LinuxKitManager) Exec(ctx context.Context, id string, cmd []string) err
}
sshArgs = append(sshArgs, cmd...)
sshCmd := proc.NewCommandContext(ctx, "ssh", sshArgs...)
sshCmd.Stdin = proc.Stdin
sshCmd.Stdout = proc.Stdout
sshCmd.Stderr = proc.Stderr
sshCmd := exec.CommandContext(ctx, "ssh", sshArgs...)
sshCmd.Stdin = os.Stdin
sshCmd.Stdout = os.Stdout
sshCmd.Stderr = os.Stderr
return sshCmd.Run()
if err := sshCmd.Run(); err != nil {
return coreerr.E("LinuxKitManager.Exec", "run ssh command", err)
}
return nil
}
// State returns the manager's state (for testing).

View file

@ -2,13 +2,12 @@ package container
import (
"context"
"syscall"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/container/internal/proc"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -40,30 +39,30 @@ func (m *MockHypervisor) Available() bool {
return m.available
}
func (m *MockHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*proc.Command, error) {
func (m *MockHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error) {
m.lastImage = image
m.lastOpts = opts
if m.buildErr != nil {
return nil, m.buildErr
}
// Return a simple command that exits quickly
return proc.NewCommandContext(ctx, m.commandToRun, "test"), nil
return exec.CommandContext(ctx, m.commandToRun, "test"), nil
}
// newTestManager creates a LinuxKitManager with mock hypervisor for testing.
// Uses manual temp directory management to avoid race conditions with t.TempDir cleanup.
func newTestManager(t *testing.T) (*LinuxKitManager, *MockHypervisor, string) {
tmpDir, err := coreutil.MkdirTemp("linuxkit-test-")
tmpDir, err := os.MkdirTemp("", "linuxkit-test-*")
require.NoError(t, err)
// Manual cleanup that handles race conditions with state file writes
t.Cleanup(func() {
// Give any pending file operations time to complete
time.Sleep(10 * time.Millisecond)
_ = io.Local.DeleteAll(tmpDir)
_ = os.RemoveAll(tmpDir)
})
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
@ -74,9 +73,9 @@ func newTestManager(t *testing.T) (*LinuxKitManager, *MockHypervisor, string) {
return manager, mock, tmpDir
}
func TestLinuxKit_NewLinuxKitManagerWithHypervisor_Good(t *testing.T) {
func TestNewLinuxKitManagerWithHypervisor_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, _ := LoadState(statePath)
mock := NewMockHypervisor()
@ -87,12 +86,12 @@ func TestLinuxKit_NewLinuxKitManagerWithHypervisor_Good(t *testing.T) {
assert.Equal(t, mock, manager.Hypervisor())
}
func TestLinuxKitManager_Run_Detached_Good(t *testing.T) {
func TestLinuxKitManager_Run_Good_Detached(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that runs briefly then exits
@ -126,11 +125,11 @@ func TestLinuxKitManager_Run_Detached_Good(t *testing.T) {
time.Sleep(100 * time.Millisecond)
}
func TestLinuxKitManager_Run_DefaultValues_Good(t *testing.T) {
func TestLinuxKitManager_Run_Good_DefaultValues(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.qcow2")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.qcow2")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
ctx := context.Background()
@ -151,7 +150,7 @@ func TestLinuxKitManager_Run_DefaultValues_Good(t *testing.T) {
time.Sleep(50 * time.Millisecond)
}
func TestLinuxKitManager_Run_ImageNotFound_Bad(t *testing.T) {
func TestLinuxKitManager_Run_Bad_ImageNotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
@ -162,11 +161,11 @@ func TestLinuxKitManager_Run_ImageNotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "image not found")
}
func TestLinuxKitManager_Run_UnsupportedFormat_Bad(t *testing.T) {
func TestLinuxKitManager_Run_Bad_UnsupportedFormat(t *testing.T) {
manager, _, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.txt")
err := io.Local.Write(imagePath, "not an image")
imagePath := filepath.Join(tmpDir, "test.txt")
err := os.WriteFile(imagePath, []byte("not an image"), 0644)
require.NoError(t, err)
ctx := context.Background()
@ -202,7 +201,7 @@ func TestLinuxKitManager_Stop_Good(t *testing.T) {
assert.Equal(t, StatusStopped, c.Status)
}
func TestLinuxKitManager_Stop_NotFound_Bad(t *testing.T) {
func TestLinuxKitManager_Stop_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
@ -212,9 +211,9 @@ func TestLinuxKitManager_Stop_NotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Stop_NotRunning_Bad(t *testing.T) {
func TestLinuxKitManager_Stop_Bad_NotRunning(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
@ -234,7 +233,7 @@ func TestLinuxKitManager_Stop_NotRunning_Bad(t *testing.T) {
func TestLinuxKitManager_List_Good(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
@ -249,9 +248,9 @@ func TestLinuxKitManager_List_Good(t *testing.T) {
assert.Len(t, containers, 2)
}
func TestLinuxKitManager_List_VerifiesRunningStatus_Good(t *testing.T) {
func TestLinuxKitManager_List_Good_VerifiesRunningStatus(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
@ -276,8 +275,8 @@ func TestLinuxKitManager_Logs_Good(t *testing.T) {
manager, _, tmpDir := newTestManager(t)
// Create a log file manually
logsDir := coreutil.JoinPath(tmpDir, "logs")
require.NoError(t, io.Local.EnsureDir(logsDir))
logsDir := filepath.Join(tmpDir, "logs")
require.NoError(t, os.MkdirAll(logsDir, 0755))
container := &Container{ID: "abc12345"}
_ = manager.State().Add(container)
@ -287,8 +286,8 @@ func TestLinuxKitManager_Logs_Good(t *testing.T) {
logContent := "test log content\nline 2\n"
logPath, err := LogPath("abc12345")
require.NoError(t, err)
require.NoError(t, io.Local.EnsureDir(core.PathDir(logPath)))
require.NoError(t, io.Local.Write(logPath, logContent))
require.NoError(t, os.MkdirAll(filepath.Dir(logPath), 0755))
require.NoError(t, os.WriteFile(logPath, []byte(logContent), 0644))
ctx := context.Background()
reader, err := manager.Logs(ctx, "abc12345", false)
@ -301,7 +300,7 @@ func TestLinuxKitManager_Logs_Good(t *testing.T) {
assert.Equal(t, logContent, string(buf[:n]))
}
func TestLinuxKitManager_Logs_NotFound_Bad(t *testing.T) {
func TestLinuxKitManager_Logs_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
@ -311,7 +310,7 @@ func TestLinuxKitManager_Logs_NotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Logs_NoLogFile_Bad(t *testing.T) {
func TestLinuxKitManager_Logs_Bad_NoLogFile(t *testing.T) {
manager, _, _ := newTestManager(t)
// Use a unique ID that won't have a log file
@ -334,7 +333,7 @@ func TestLinuxKitManager_Logs_NoLogFile_Bad(t *testing.T) {
}
}
func TestLinuxKitManager_Exec_NotFound_Bad(t *testing.T) {
func TestLinuxKitManager_Exec_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
@ -344,7 +343,7 @@ func TestLinuxKitManager_Exec_NotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Exec_NotRunning_Bad(t *testing.T) {
func TestLinuxKitManager_Exec_Bad_NotRunning(t *testing.T) {
manager, _, _ := newTestManager(t)
container := &Container{ID: "abc12345", Status: StatusStopped}
@ -357,7 +356,7 @@ func TestLinuxKitManager_Exec_NotRunning_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "not running")
}
func TestLinuxKit_DetectImageFormat_Good(t *testing.T) {
func TestDetectImageFormat_Good(t *testing.T) {
tests := []struct {
path string
format ImageFormat
@ -379,7 +378,7 @@ func TestLinuxKit_DetectImageFormat_Good(t *testing.T) {
}
}
func TestDetectImageFormat_Unknown_Bad(t *testing.T) {
func TestDetectImageFormat_Bad_Unknown(t *testing.T) {
tests := []string{
"/path/to/image.txt",
"/path/to/image",
@ -427,7 +426,7 @@ func TestQemuHypervisor_BuildCommand_Good(t *testing.T) {
assert.Contains(t, args, "-nographic")
}
func TestLinuxKitManager_Logs_Follow_Good(t *testing.T) {
func TestLinuxKitManager_Logs_Good_Follow(t *testing.T) {
manager, _, _ := newTestManager(t)
// Create a unique container ID
@ -439,10 +438,10 @@ func TestLinuxKitManager_Logs_Follow_Good(t *testing.T) {
// Create a log file at the expected location
logPath, err := LogPath(uniqueID)
require.NoError(t, err)
require.NoError(t, io.Local.EnsureDir(core.PathDir(logPath)))
require.NoError(t, os.MkdirAll(filepath.Dir(logPath), 0755))
// Write initial content
err = io.Local.Write(logPath, "initial log content\n")
err = os.WriteFile(logPath, []byte("initial log content\n"), 0644)
require.NoError(t, err)
// Create a cancellable context
@ -465,13 +464,13 @@ func TestLinuxKitManager_Logs_Follow_Good(t *testing.T) {
assert.NoError(t, reader.Close())
}
func TestFollowReader_Read_WithData_Good(t *testing.T) {
func TestFollowReader_Read_Good_WithData(t *testing.T) {
tmpDir := t.TempDir()
logPath := coreutil.JoinPath(tmpDir, "test.log")
logPath := filepath.Join(tmpDir, "test.log")
// Create log file with content
content := "test log line 1\ntest log line 2\n"
err := io.Local.Write(logPath, content)
err := os.WriteFile(logPath, []byte(content), 0644)
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
@ -482,9 +481,9 @@ func TestFollowReader_Read_WithData_Good(t *testing.T) {
defer func() { _ = reader.Close() }()
// The followReader seeks to end, so we need to append more content
f, err := io.Local.Append(logPath)
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0644)
require.NoError(t, err)
_, err = f.Write([]byte("new line\n"))
_, err = f.WriteString("new line\n")
require.NoError(t, err)
require.NoError(t, f.Close())
@ -498,12 +497,12 @@ func TestFollowReader_Read_WithData_Good(t *testing.T) {
}
}
func TestFollowReader_Read_ContextCancel_Good(t *testing.T) {
func TestFollowReader_Read_Good_ContextCancel(t *testing.T) {
tmpDir := t.TempDir()
logPath := coreutil.JoinPath(tmpDir, "test.log")
logPath := filepath.Join(tmpDir, "test.log")
// Create log file
err := io.Local.Write(logPath, "initial content\n")
err := os.WriteFile(logPath, []byte("initial content\n"), 0644)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
@ -524,9 +523,9 @@ func TestFollowReader_Read_ContextCancel_Good(t *testing.T) {
func TestFollowReader_Close_Good(t *testing.T) {
tmpDir := t.TempDir()
logPath := coreutil.JoinPath(tmpDir, "test.log")
logPath := filepath.Join(tmpDir, "test.log")
err := io.Local.Write(logPath, "content\n")
err := os.WriteFile(logPath, []byte("content\n"), 0644)
require.NoError(t, err)
ctx := context.Background()
@ -542,19 +541,19 @@ func TestFollowReader_Close_Good(t *testing.T) {
assert.Error(t, readErr)
}
func TestNewFollowReader_FileNotFound_Bad(t *testing.T) {
func TestNewFollowReader_Bad_FileNotFound(t *testing.T) {
ctx := context.Background()
_, err := newFollowReader(ctx, io.Local, "/nonexistent/path/to/file.log")
assert.Error(t, err)
}
func TestLinuxKitManager_Run_BuildCommandError_Bad(t *testing.T) {
func TestLinuxKitManager_Run_Bad_BuildCommandError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Configure mock to return an error
@ -568,12 +567,12 @@ func TestLinuxKitManager_Run_BuildCommandError_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "failed to build hypervisor command")
}
func TestLinuxKitManager_Run_Foreground_Good(t *testing.T) {
func TestLinuxKitManager_Run_Good_Foreground(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use echo which exits quickly
@ -596,12 +595,12 @@ func TestLinuxKitManager_Run_Foreground_Good(t *testing.T) {
assert.Equal(t, StatusStopped, container.Status)
}
func TestLinuxKitManager_Stop_ContextCancelled_Good(t *testing.T) {
func TestLinuxKitManager_Stop_Good_ContextCancelled(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that takes a long time
@ -630,26 +629,26 @@ func TestLinuxKitManager_Stop_ContextCancelled_Good(t *testing.T) {
err = manager.Stop(cancelCtx, container.ID)
// Should return context error
assert.Error(t, err)
assert.Equal(t, context.Canceled, err)
assert.ErrorIs(t, err, context.Canceled)
}
func TestIsProcessRunning_ExistingProcess_Good(t *testing.T) {
func TestIsProcessRunning_Good_ExistingProcess(t *testing.T) {
// Use our own PID which definitely exists
running := isProcessRunning(syscall.Getpid())
running := isProcessRunning(os.Getpid())
assert.True(t, running)
}
func TestIsProcessRunning_NonexistentProcess_Bad(t *testing.T) {
func TestIsProcessRunning_Bad_NonexistentProcess(t *testing.T) {
// Use a PID that almost certainly doesn't exist
running := isProcessRunning(999999)
assert.False(t, running)
}
func TestLinuxKitManager_Run_WithPortsAndVolumes_Good(t *testing.T) {
func TestLinuxKitManager_Run_Good_WithPortsAndVolumes(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
ctx := context.Background()
@ -674,12 +673,12 @@ func TestLinuxKitManager_Run_WithPortsAndVolumes_Good(t *testing.T) {
time.Sleep(50 * time.Millisecond)
}
func TestFollowReader_Read_ReaderError_Bad(t *testing.T) {
func TestFollowReader_Read_Bad_ReaderError(t *testing.T) {
tmpDir := t.TempDir()
logPath := coreutil.JoinPath(tmpDir, "test.log")
logPath := filepath.Join(tmpDir, "test.log")
// Create log file
err := io.Local.Write(logPath, "content\n")
err := os.WriteFile(logPath, []byte("content\n"), 0644)
require.NoError(t, err)
ctx := context.Background()
@ -695,11 +694,11 @@ func TestFollowReader_Read_ReaderError_Bad(t *testing.T) {
assert.Error(t, readErr)
}
func TestLinuxKitManager_Run_StartError_Bad(t *testing.T) {
func TestLinuxKitManager_Run_Bad_StartError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that doesn't exist to cause Start() to fail
@ -716,11 +715,11 @@ func TestLinuxKitManager_Run_StartError_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "failed to start VM")
}
func TestLinuxKitManager_Run_ForegroundStartError_Bad(t *testing.T) {
func TestLinuxKitManager_Run_Bad_ForegroundStartError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that doesn't exist to cause Start() to fail
@ -737,11 +736,11 @@ func TestLinuxKitManager_Run_ForegroundStartError_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "failed to start VM")
}
func TestLinuxKitManager_Run_ForegroundWithError_Good(t *testing.T) {
func TestLinuxKitManager_Run_Good_ForegroundWithError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := coreutil.JoinPath(tmpDir, "test.iso")
err := io.Local.Write(imagePath, "fake image")
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that exits with error
@ -760,7 +759,7 @@ func TestLinuxKitManager_Run_ForegroundWithError_Good(t *testing.T) {
assert.Equal(t, StatusError, container.Status)
}
func TestLinuxKitManager_Stop_ProcessExitedWhileRunning_Good(t *testing.T) {
func TestLinuxKitManager_Stop_Good_ProcessExitedWhileRunning(t *testing.T) {
manager, _, _ := newTestManager(t)
// Add a "running" container with a process that has already exited

View file

@ -2,14 +2,13 @@ package sources
import (
"context"
"fmt"
goio "io"
"net/http"
"path/filepath"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
)
// CDNSource downloads images from a CDN or S3 bucket.
@ -21,10 +20,6 @@ type CDNSource struct {
var _ ImageSource = (*CDNSource)(nil)
// NewCDNSource creates a new CDN source.
//
// Usage:
//
// src := NewCDNSource(cfg)
func NewCDNSource(cfg SourceConfig) *CDNSource {
return &CDNSource{config: cfg}
}
@ -42,7 +37,7 @@ func (s *CDNSource) Available() bool {
// LatestVersion fetches version from manifest or returns "latest".
func (s *CDNSource) LatestVersion(ctx context.Context) (string, error) {
// Try to fetch manifest.json for version info
url := core.Sprintf("%s/manifest.json", s.config.CDNURL)
url := fmt.Sprintf("%s/manifest.json", s.config.CDNURL)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return "latest", nil
@ -60,7 +55,7 @@ func (s *CDNSource) LatestVersion(ctx context.Context) (string, error) {
// Download downloads the image from CDN.
func (s *CDNSource) Download(ctx context.Context, m io.Medium, dest string, progress func(downloaded, total int64)) error {
url := core.Sprintf("%s/%s", s.config.CDNURL, s.config.ImageName)
url := fmt.Sprintf("%s/%s", s.config.CDNURL, s.config.ImageName)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
@ -74,7 +69,7 @@ func (s *CDNSource) Download(ctx context.Context, m io.Medium, dest string, prog
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
return coreerr.E("cdn.Download", core.Sprintf("HTTP %d", resp.StatusCode), nil)
return coreerr.E("cdn.Download", fmt.Sprintf("HTTP %d", resp.StatusCode), nil)
}
// Ensure dest directory exists
@ -83,7 +78,7 @@ func (s *CDNSource) Download(ctx context.Context, m io.Medium, dest string, prog
}
// Create destination file
destPath := coreutil.JoinPath(dest, s.config.ImageName)
destPath := filepath.Join(dest, s.config.ImageName)
f, err := m.Create(destPath)
if err != nil {
return coreerr.E("cdn.Download", "create destination file", err)

View file

@ -2,18 +2,18 @@ package sources
import (
"context"
goio "io"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
core "dappco.re/go/core"
"dappco.re/go/core/container/internal/coreutil"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
)
func TestCDNSource_Available_Good(t *testing.T) {
func TestCDNSource_Good_Available(t *testing.T) {
src := NewCDNSource(SourceConfig{
CDNURL: "https://images.example.com",
ImageName: "core-devops-darwin-arm64.qcow2",
@ -23,7 +23,7 @@ func TestCDNSource_Available_Good(t *testing.T) {
assert.True(t, src.Available())
}
func TestCDNSource_NoURL_Bad(t *testing.T) {
func TestCDNSource_Bad_NoURL(t *testing.T) {
src := NewCDNSource(SourceConfig{
ImageName: "core-devops-darwin-arm64.qcow2",
})
@ -35,7 +35,7 @@ func TestCDNSource_LatestVersion_Good(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/manifest.json" {
w.WriteHeader(http.StatusOK)
_, _ = goio.WriteString(w, `{"version": "1.2.3"}`)
_, _ = fmt.Fprint(w, `{"version": "1.2.3"}`)
} else {
w.WriteHeader(http.StatusNotFound)
}
@ -57,7 +57,7 @@ func TestCDNSource_Download_Good(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/test.img" {
w.WriteHeader(http.StatusOK)
_, _ = goio.WriteString(w, content)
_, _ = fmt.Fprint(w, content)
} else {
w.WriteHeader(http.StatusNotFound)
}
@ -80,9 +80,9 @@ func TestCDNSource_Download_Good(t *testing.T) {
assert.True(t, progressCalled)
// Verify file content
data, err := io.Local.Read(coreutil.JoinPath(dest, imageName))
data, err := os.ReadFile(filepath.Join(dest, imageName))
assert.NoError(t, err)
assert.Equal(t, content, data)
assert.Equal(t, content, string(data))
}
func TestCDNSource_Download_Bad(t *testing.T) {
@ -115,7 +115,7 @@ func TestCDNSource_Download_Bad(t *testing.T) {
})
}
func TestCDNSource_LatestVersion_NoManifest_Bad(t *testing.T) {
func TestCDNSource_LatestVersion_Bad_NoManifest(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
@ -131,7 +131,7 @@ func TestCDNSource_LatestVersion_NoManifest_Bad(t *testing.T) {
assert.Equal(t, "latest", version)
}
func TestCDNSource_LatestVersion_ServerError_Bad(t *testing.T) {
func TestCDNSource_LatestVersion_Bad_ServerError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
@ -147,12 +147,12 @@ func TestCDNSource_LatestVersion_ServerError_Bad(t *testing.T) {
assert.Equal(t, "latest", version)
}
func TestCDNSource_Download_NoProgress_Good(t *testing.T) {
func TestCDNSource_Download_Good_NoProgress(t *testing.T) {
content := "test content"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", core.Sprintf("%d", len(content)))
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
w.WriteHeader(http.StatusOK)
_, _ = goio.WriteString(w, content)
_, _ = fmt.Fprint(w, content)
}))
defer server.Close()
@ -166,12 +166,12 @@ func TestCDNSource_Download_NoProgress_Good(t *testing.T) {
err := src.Download(context.Background(), io.Local, dest, nil)
assert.NoError(t, err)
data, err := io.Local.Read(coreutil.JoinPath(dest, "test.img"))
data, err := os.ReadFile(filepath.Join(dest, "test.img"))
assert.NoError(t, err)
assert.Equal(t, content, data)
assert.Equal(t, content, string(data))
}
func TestCDNSource_Download_LargeFile_Good(t *testing.T) {
func TestCDNSource_Download_Good_LargeFile(t *testing.T) {
// Create content larger than buffer size (32KB)
content := make([]byte, 64*1024) // 64KB
for i := range content {
@ -179,7 +179,7 @@ func TestCDNSource_Download_LargeFile_Good(t *testing.T) {
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", core.Sprintf("%d", len(content)))
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(content)
}))
@ -203,7 +203,7 @@ func TestCDNSource_Download_LargeFile_Good(t *testing.T) {
assert.Equal(t, int64(len(content)), lastDownloaded)
}
func TestCDNSource_Download_HTTPErrorCodes_Bad(t *testing.T) {
func TestCDNSource_Download_Bad_HTTPErrorCodes(t *testing.T) {
testCases := []struct {
name string
statusCode int
@ -230,17 +230,17 @@ func TestCDNSource_Download_HTTPErrorCodes_Bad(t *testing.T) {
err := src.Download(context.Background(), io.Local, dest, nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), core.Sprintf("HTTP %d", tc.statusCode))
assert.Contains(t, err.Error(), fmt.Sprintf("HTTP %d", tc.statusCode))
})
}
}
func TestCDNSource_InterfaceCompliance_Good(t *testing.T) {
func TestCDNSource_Good_InterfaceCompliance(t *testing.T) {
// Verify CDNSource implements ImageSource
var _ ImageSource = (*CDNSource)(nil)
}
func TestCDNSource_Config_Good(t *testing.T) {
func TestCDNSource_Good_Config(t *testing.T) {
cfg := SourceConfig{
CDNURL: "https://cdn.example.com",
ImageName: "my-image.qcow2",
@ -251,7 +251,7 @@ func TestCDNSource_Config_Good(t *testing.T) {
assert.Equal(t, "my-image.qcow2", src.config.ImageName)
}
func TestCDN_NewCDNSource_Good(t *testing.T) {
func TestNewCDNSource_Good(t *testing.T) {
cfg := SourceConfig{
GitHubRepo: "host-uk/core-images",
RegistryImage: "ghcr.io/host-uk/core-devops",
@ -265,16 +265,16 @@ func TestCDN_NewCDNSource_Good(t *testing.T) {
assert.Equal(t, cfg.CDNURL, src.config.CDNURL)
}
func TestCDNSource_Download_CreatesDestDir_Good(t *testing.T) {
func TestCDNSource_Download_Good_CreatesDestDir(t *testing.T) {
content := "test content"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = goio.WriteString(w, content)
_, _ = fmt.Fprint(w, content)
}))
defer server.Close()
tmpDir := t.TempDir()
dest := coreutil.JoinPath(tmpDir, "nested", "dir")
dest := filepath.Join(tmpDir, "nested", "dir")
// dest doesn't exist yet
src := NewCDNSource(SourceConfig{
@ -286,12 +286,12 @@ func TestCDNSource_Download_CreatesDestDir_Good(t *testing.T) {
assert.NoError(t, err)
// Verify nested dir was created
info, err := io.Local.Stat(dest)
info, err := os.Stat(dest)
assert.NoError(t, err)
assert.True(t, info.IsDir())
}
func TestSourceConfig_Struct_Good(t *testing.T) {
func TestSourceConfig_Good_Struct(t *testing.T) {
cfg := SourceConfig{
GitHubRepo: "owner/repo",
RegistryImage: "ghcr.io/owner/image",

View file

@ -2,12 +2,12 @@ package sources
import (
"context"
"os"
"os/exec"
"strings"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/proc"
)
// GitHubSource downloads images from GitHub Releases.
@ -19,10 +19,6 @@ type GitHubSource struct {
var _ ImageSource = (*GitHubSource)(nil)
// NewGitHubSource creates a new GitHub source.
//
// Usage:
//
// src := NewGitHubSource(cfg)
func NewGitHubSource(cfg SourceConfig) *GitHubSource {
return &GitHubSource{config: cfg}
}
@ -34,18 +30,18 @@ func (s *GitHubSource) Name() string {
// Available checks if gh CLI is installed and authenticated.
func (s *GitHubSource) Available() bool {
_, err := proc.LookPath("gh")
_, err := exec.LookPath("gh")
if err != nil {
return false
}
// Check if authenticated
cmd := proc.NewCommand("gh", "auth", "status")
cmd := exec.Command("gh", "auth", "status")
return cmd.Run() == nil
}
// LatestVersion returns the latest release tag.
func (s *GitHubSource) LatestVersion(ctx context.Context) (string, error) {
cmd := proc.NewCommandContext(ctx, "gh", "release", "view",
cmd := exec.CommandContext(ctx, "gh", "release", "view",
"-R", s.config.GitHubRepo,
"--json", "tagName",
"-q", ".tagName",
@ -54,20 +50,20 @@ func (s *GitHubSource) LatestVersion(ctx context.Context) (string, error) {
if err != nil {
return "", coreerr.E("github.LatestVersion", "failed", err)
}
return core.Trim(string(out)), nil
return strings.TrimSpace(string(out)), nil
}
// Download downloads the image from the latest release.
func (s *GitHubSource) Download(ctx context.Context, m io.Medium, dest string, progress func(downloaded, total int64)) error {
// Get release assets to find our image
cmd := proc.NewCommandContext(ctx, "gh", "release", "download",
cmd := exec.CommandContext(ctx, "gh", "release", "download",
"-R", s.config.GitHubRepo,
"-p", s.config.ImageName,
"-D", dest,
"--clobber",
)
cmd.Stdout = proc.Stdout
cmd.Stderr = proc.Stderr
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return coreerr.E("github.Download", "failed", err)

View file

@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
)
func TestGitHubSource_Available_Good(t *testing.T) {
func TestGitHubSource_Good_Available(t *testing.T) {
src := NewGitHubSource(SourceConfig{
GitHubRepo: "host-uk/core-images",
ImageName: "core-devops-darwin-arm64.qcow2",
@ -20,12 +20,12 @@ func TestGitHubSource_Available_Good(t *testing.T) {
_ = src.Available()
}
func TestGitHubSource_Name_Good(t *testing.T) {
func TestGitHubSource_Good_Name(t *testing.T) {
src := NewGitHubSource(SourceConfig{})
assert.Equal(t, "github", src.Name())
}
func TestGitHubSource_Config_Good(t *testing.T) {
func TestGitHubSource_Good_Config(t *testing.T) {
cfg := SourceConfig{
GitHubRepo: "owner/repo",
ImageName: "test-image.qcow2",
@ -37,7 +37,7 @@ func TestGitHubSource_Config_Good(t *testing.T) {
assert.Equal(t, "test-image.qcow2", src.config.ImageName)
}
func TestGitHubSource_Multiple_Good(t *testing.T) {
func TestGitHubSource_Good_Multiple(t *testing.T) {
// Test creating multiple sources with different configs
src1 := NewGitHubSource(SourceConfig{GitHubRepo: "org1/repo1", ImageName: "img1.qcow2"})
src2 := NewGitHubSource(SourceConfig{GitHubRepo: "org2/repo2", ImageName: "img2.qcow2"})
@ -48,7 +48,7 @@ func TestGitHubSource_Multiple_Good(t *testing.T) {
assert.Equal(t, "github", src2.Name())
}
func TestGitHub_NewGitHubSource_Good(t *testing.T) {
func TestNewGitHubSource_Good(t *testing.T) {
cfg := SourceConfig{
GitHubRepo: "host-uk/core-images",
RegistryImage: "ghcr.io/host-uk/core-devops",
@ -62,7 +62,7 @@ func TestGitHub_NewGitHubSource_Good(t *testing.T) {
assert.Equal(t, cfg.GitHubRepo, src.config.GitHubRepo)
}
func TestGitHubSource_InterfaceCompliance_Good(t *testing.T) {
func TestGitHubSource_Good_InterfaceCompliance(t *testing.T) {
// Verify GitHubSource implements ImageSource
var _ ImageSource = (*GitHubSource)(nil)
}

View file

@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
)
func TestSourceConfig_Empty_Good(t *testing.T) {
func TestSourceConfig_Good_Empty(t *testing.T) {
cfg := SourceConfig{}
assert.Empty(t, cfg.GitHubRepo)
assert.Empty(t, cfg.RegistryImage)
@ -14,7 +14,7 @@ func TestSourceConfig_Empty_Good(t *testing.T) {
assert.Empty(t, cfg.ImageName)
}
func TestSourceConfig_Complete_Good(t *testing.T) {
func TestSourceConfig_Good_Complete(t *testing.T) {
cfg := SourceConfig{
GitHubRepo: "owner/repo",
RegistryImage: "ghcr.io/owner/image:v1",
@ -28,7 +28,7 @@ func TestSourceConfig_Complete_Good(t *testing.T) {
assert.Equal(t, "my-image-darwin-arm64.qcow2", cfg.ImageName)
}
func TestImageSource_Interface_Good(t *testing.T) {
func TestImageSource_Good_Interface(t *testing.T) {
// Ensure both sources implement the interface
var _ ImageSource = (*GitHubSource)(nil)
var _ ImageSource = (*CDNSource)(nil)

View file

@ -1,13 +1,13 @@
package container
import (
"io/fs"
"encoding/json"
"os"
"path/filepath"
"sync"
core "dappco.re/go/core"
"dappco.re/go/core/io"
"dappco.re/go/core/container/internal/coreutil"
coreerr "dappco.re/go/core/log"
)
// State manages persistent container state.
@ -20,49 +20,33 @@ type State struct {
}
// DefaultStateDir returns the default directory for state files (~/.core).
//
// Usage:
//
// dir, err := DefaultStateDir()
func DefaultStateDir() (string, error) {
home := coreutil.HomeDir()
if home == "" {
return "", core.E("DefaultStateDir", "home directory not available", nil)
home, err := os.UserHomeDir()
if err != nil {
return "", coreerr.E("DefaultStateDir", "get home dir", err)
}
return coreutil.JoinPath(home, ".core"), nil
return filepath.Join(home, ".core"), nil
}
// DefaultStatePath returns the default path for the state file.
//
// Usage:
//
// path, err := DefaultStatePath()
func DefaultStatePath() (string, error) {
dir, err := DefaultStateDir()
if err != nil {
return "", err
return "", coreerr.E("DefaultStatePath", "get state directory", err)
}
return coreutil.JoinPath(dir, "containers.json"), nil
return filepath.Join(dir, "containers.json"), nil
}
// DefaultLogsDir returns the default directory for container logs.
//
// Usage:
//
// dir, err := DefaultLogsDir()
func DefaultLogsDir() (string, error) {
dir, err := DefaultStateDir()
if err != nil {
return "", err
return "", coreerr.E("DefaultLogsDir", "get state directory", err)
}
return coreutil.JoinPath(dir, "logs"), nil
return filepath.Join(dir, "logs"), nil
}
// NewState creates a new State instance.
//
// Usage:
//
// state := NewState("/tmp/containers.json")
func NewState(filePath string) *State {
return &State{
Containers: make(map[string]*Container),
@ -72,24 +56,20 @@ func NewState(filePath string) *State {
// LoadState loads the state from the given file path.
// If the file doesn't exist, returns an empty state.
//
// Usage:
//
// state, err := LoadState("/tmp/containers.json")
func LoadState(filePath string) (*State, error) {
state := NewState(filePath)
dataStr, err := io.Local.Read(filePath)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return state, nil
}
return nil, err
if !io.Local.Exists(filePath) {
return state, nil
}
result := core.JSONUnmarshalString(dataStr, state)
if !result.OK {
return nil, result.Value.(error)
dataStr, err := io.Local.Read(filePath)
if err != nil {
return nil, coreerr.E("LoadState", "read state file", err)
}
if err := json.Unmarshal([]byte(dataStr), state); err != nil {
return nil, coreerr.E("LoadState", "unmarshal state file", err)
}
return state, nil
@ -101,17 +81,20 @@ func (s *State) SaveState() error {
defer s.mu.RUnlock()
// Ensure the directory exists
dir := core.PathDir(s.filePath)
dir := filepath.Dir(s.filePath)
if err := io.Local.EnsureDir(dir); err != nil {
return err
return coreerr.E("State.SaveState", "ensure state directory", err)
}
result := core.JSONMarshal(s)
if !result.OK {
return result.Value.(error)
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return coreerr.E("State.SaveState", "marshal state", err)
}
return io.Local.Write(s.filePath, string(result.Value.([]byte)))
if err := io.Local.Write(s.filePath, string(data)); err != nil {
return coreerr.E("State.SaveState", "write state file", err)
}
return nil
}
// Add adds a container to the state and persists it.
@ -176,27 +159,22 @@ func (s *State) FilePath() string {
}
// LogPath returns the log file path for a given container ID.
//
// Usage:
//
// path, err := LogPath(containerID)
func LogPath(id string) (string, error) {
logsDir, err := DefaultLogsDir()
if err != nil {
return "", err
return "", coreerr.E("LogPath", "get logs directory", err)
}
return coreutil.JoinPath(logsDir, core.Concat(id, ".log")), nil
return filepath.Join(logsDir, id+".log"), nil
}
// EnsureLogsDir ensures the logs directory exists.
//
// Usage:
//
// err := EnsureLogsDir()
func EnsureLogsDir() error {
logsDir, err := DefaultLogsDir()
if err != nil {
return err
return coreerr.E("EnsureLogsDir", "get logs directory", err)
}
return io.Local.EnsureDir(logsDir)
if err := io.Local.EnsureDir(logsDir); err != nil {
return coreerr.E("EnsureLogsDir", "ensure logs directory", err)
}
return nil
}

View file

@ -1,18 +1,16 @@
package container
import (
"os"
"path/filepath"
"testing"
"time"
core "dappco.re/go/core"
"dappco.re/go/core/io"
"dappco.re/go/core/container/internal/coreutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestState_NewState_Good(t *testing.T) {
func TestNewState_Good(t *testing.T) {
state := NewState("/tmp/test-state.json")
assert.NotNil(t, state)
@ -20,10 +18,10 @@ func TestState_NewState_Good(t *testing.T) {
assert.Equal(t, "/tmp/test-state.json", state.FilePath())
}
func TestLoadState_NewFile_Good(t *testing.T) {
func TestLoadState_Good_NewFile(t *testing.T) {
// Test loading from non-existent file
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
@ -32,9 +30,9 @@ func TestLoadState_NewFile_Good(t *testing.T) {
assert.Empty(t, state.Containers)
}
func TestLoadState_ExistingFile_Good(t *testing.T) {
func TestLoadState_Good_ExistingFile(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
// Create a state file with data
content := `{
@ -49,7 +47,7 @@ func TestLoadState_ExistingFile_Good(t *testing.T) {
}
}
}`
err := io.Local.Write(statePath, content)
err := os.WriteFile(statePath, []byte(content), 0644)
require.NoError(t, err)
state, err := LoadState(statePath)
@ -63,12 +61,12 @@ func TestLoadState_ExistingFile_Good(t *testing.T) {
assert.Equal(t, StatusRunning, c.Status)
}
func TestLoadState_InvalidJSON_Bad(t *testing.T) {
func TestLoadState_Bad_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
// Create invalid JSON
err := io.Local.Write(statePath, "invalid json{")
err := os.WriteFile(statePath, []byte("invalid json{"), 0644)
require.NoError(t, err)
_, err = LoadState(statePath)
@ -77,7 +75,7 @@ func TestLoadState_InvalidJSON_Bad(t *testing.T) {
func TestState_Add_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state := NewState(statePath)
container := &Container{
@ -98,12 +96,13 @@ func TestState_Add_Good(t *testing.T) {
assert.Equal(t, container.Name, c.Name)
// Verify file was created
assert.True(t, io.Local.IsFile(statePath))
_, err = os.Stat(statePath)
assert.NoError(t, err)
}
func TestState_Update_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state := NewState(statePath)
container := &Container{
@ -125,7 +124,7 @@ func TestState_Update_Good(t *testing.T) {
func TestState_Remove_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state := NewState(statePath)
container := &Container{
@ -140,7 +139,7 @@ func TestState_Remove_Good(t *testing.T) {
assert.False(t, ok)
}
func TestState_Get_NotFound_Bad(t *testing.T) {
func TestState_Get_Bad_NotFound(t *testing.T) {
state := NewState("/tmp/test-state.json")
_, ok := state.Get("nonexistent")
@ -149,7 +148,7 @@ func TestState_Get_NotFound_Bad(t *testing.T) {
func TestState_All_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := coreutil.JoinPath(tmpDir, "containers.json")
statePath := filepath.Join(tmpDir, "containers.json")
state := NewState(statePath)
_ = state.Add(&Container{ID: "aaa11111"})
@ -160,9 +159,9 @@ func TestState_All_Good(t *testing.T) {
assert.Len(t, all, 3)
}
func TestState_SaveState_CreatesDirectory_Good(t *testing.T) {
func TestState_SaveState_Good_CreatesDirectory(t *testing.T) {
tmpDir := t.TempDir()
nestedPath := coreutil.JoinPath(tmpDir, "nested", "dir", "containers.json")
nestedPath := filepath.Join(tmpDir, "nested", "dir", "containers.json")
state := NewState(nestedPath)
_ = state.Add(&Container{ID: "abc12345"})
@ -171,43 +170,45 @@ func TestState_SaveState_CreatesDirectory_Good(t *testing.T) {
require.NoError(t, err)
// Verify directory was created
assert.True(t, io.Local.IsDir(core.PathDir(nestedPath)))
_, err = os.Stat(filepath.Dir(nestedPath))
assert.NoError(t, err)
}
func TestState_DefaultStateDir_Good(t *testing.T) {
func TestDefaultStateDir_Good(t *testing.T) {
dir, err := DefaultStateDir()
require.NoError(t, err)
assert.Contains(t, dir, ".core")
}
func TestState_DefaultStatePath_Good(t *testing.T) {
func TestDefaultStatePath_Good(t *testing.T) {
path, err := DefaultStatePath()
require.NoError(t, err)
assert.Contains(t, path, "containers.json")
}
func TestState_DefaultLogsDir_Good(t *testing.T) {
func TestDefaultLogsDir_Good(t *testing.T) {
dir, err := DefaultLogsDir()
require.NoError(t, err)
assert.Contains(t, dir, "logs")
}
func TestState_LogPath_Good(t *testing.T) {
func TestLogPath_Good(t *testing.T) {
path, err := LogPath("abc12345")
require.NoError(t, err)
assert.Contains(t, path, "abc12345.log")
}
func TestState_EnsureLogsDir_Good(t *testing.T) {
func TestEnsureLogsDir_Good(t *testing.T) {
// This test creates real directories - skip in CI if needed
err := EnsureLogsDir()
assert.NoError(t, err)
logsDir, _ := DefaultLogsDir()
assert.True(t, io.Local.IsDir(logsDir))
_, err = os.Stat(logsDir)
assert.NoError(t, err)
}
func TestState_GenerateID_Good(t *testing.T) {
func TestGenerateID_Good(t *testing.T) {
id1, err := GenerateID()
require.NoError(t, err)
assert.Len(t, id1, 8)

View file

@ -4,14 +4,14 @@ import (
"embed"
"iter"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
core "dappco.re/go/core"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/container/internal/coreutil"
)
//go:embed templates/*.yml
@ -44,19 +44,11 @@ var builtinTemplates = []Template{
// ListTemplates returns all available LinuxKit templates.
// It combines embedded templates with any templates found in the user's
// .core/linuxkit directory.
//
// Usage:
//
// templates := ListTemplates()
func ListTemplates() []Template {
return slices.Collect(ListTemplatesIter())
}
// ListTemplatesIter returns an iterator for all available LinuxKit templates.
//
// Usage:
//
// for template := range ListTemplatesIter() { _ = template }
func ListTemplatesIter() iter.Seq[Template] {
return func(yield func(Template) bool) {
// Yield builtin templates
@ -80,10 +72,6 @@ func ListTemplatesIter() iter.Seq[Template] {
// GetTemplate returns the content of a template by name.
// It first checks embedded templates, then user templates.
//
// Usage:
//
// content, err := GetTemplate("core-dev")
func GetTemplate(name string) (string, error) {
// Check embedded templates first
for _, t := range builtinTemplates {
@ -99,7 +87,7 @@ func GetTemplate(name string) (string, error) {
// Check user templates
userTemplatesDir := getUserTemplatesDir()
if userTemplatesDir != "" {
templatePath := coreutil.JoinPath(userTemplatesDir, core.Concat(name, ".yml"))
templatePath := filepath.Join(userTemplatesDir, name+".yml")
if io.Local.IsFile(templatePath) {
content, err := io.Local.Read(templatePath)
if err != nil {
@ -116,14 +104,10 @@ func GetTemplate(name string) (string, error) {
// It supports two syntaxes:
// - ${VAR} - required variable, returns error if not provided
// - ${VAR:-default} - variable with default value
//
// Usage:
//
// content, err := ApplyTemplate("core-dev", vars)
func ApplyTemplate(name string, vars map[string]string) (string, error) {
content, err := GetTemplate(name)
if err != nil {
return "", err
return "", coreerr.E("ApplyTemplate", "get template", err)
}
return ApplyVariables(content, vars)
@ -133,10 +117,6 @@ func ApplyTemplate(name string, vars map[string]string) (string, error) {
// It supports two syntaxes:
// - ${VAR} - required variable, returns error if not provided
// - ${VAR:-default} - variable with default value
//
// Usage:
//
// content, err := ApplyVariables(raw, vars)
func ApplyVariables(content string, vars map[string]string) (string, error) {
// Pattern for ${VAR:-default} syntax
defaultPattern := regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}`)
@ -178,7 +158,7 @@ func ApplyVariables(content string, vars map[string]string) (string, error) {
})
if len(missingVars) > 0 {
return "", coreerr.E("ApplyVariables", core.Concat("missing required variables: ", core.Join(", ", missingVars...)), nil)
return "", coreerr.E("ApplyVariables", "missing required variables: "+strings.Join(missingVars, ", "), nil)
}
return result, nil
@ -186,10 +166,6 @@ func ApplyVariables(content string, vars map[string]string) (string, error) {
// ExtractVariables extracts all variable names from a template.
// Returns two slices: required variables and optional variables (with defaults).
//
// Usage:
//
// required, optional := ExtractVariables(content)
func ExtractVariables(content string) (required []string, optional map[string]string) {
optional = make(map[string]string)
requiredSet := make(map[string]bool)
@ -230,18 +206,21 @@ func ExtractVariables(content string) (required []string, optional map[string]st
// Returns empty string if the directory doesn't exist.
func getUserTemplatesDir() string {
// Try workspace-relative .core/linuxkit first
wsDir := coreutil.JoinPath(coreutil.CurrentDir(), ".core", "linuxkit")
if io.Local.IsDir(wsDir) {
return wsDir
cwd, err := os.Getwd()
if err == nil {
wsDir := filepath.Join(cwd, ".core", "linuxkit")
if io.Local.IsDir(wsDir) {
return wsDir
}
}
// Try home directory
home := coreutil.HomeDir()
if home == "" {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
homeDir := coreutil.JoinPath(home, ".core", "linuxkit")
homeDir := filepath.Join(home, ".core", "linuxkit")
if io.Local.IsDir(homeDir) {
return homeDir
}
@ -264,12 +243,12 @@ func scanUserTemplates(dir string) []Template {
}
name := entry.Name()
if !core.HasSuffix(name, ".yml") && !core.HasSuffix(name, ".yaml") {
if !strings.HasSuffix(name, ".yml") && !strings.HasSuffix(name, ".yaml") {
continue
}
// Extract template name from filename
templateName := core.TrimSuffix(core.TrimSuffix(name, ".yml"), ".yaml")
templateName := strings.TrimSuffix(strings.TrimSuffix(name, ".yml"), ".yaml")
// Skip if this is a builtin template name (embedded takes precedence)
isBuiltin := false
@ -284,7 +263,7 @@ func scanUserTemplates(dir string) []Template {
}
// Read file to extract description from comments
description := extractTemplateDescription(coreutil.JoinPath(dir, name))
description := extractTemplateDescription(filepath.Join(dir, name))
if description == "" {
description = "User-defined template"
}
@ -292,7 +271,7 @@ func scanUserTemplates(dir string) []Template {
templates = append(templates, Template{
Name: templateName,
Description: description,
Path: coreutil.JoinPath(dir, name),
Path: filepath.Join(dir, name),
})
}
@ -307,14 +286,14 @@ func extractTemplateDescription(path string) string {
return ""
}
lines := core.Split(content, "\n")
lines := strings.Split(content, "\n")
var descLines []string
for _, line := range lines {
trimmed := core.Trim(line)
if core.HasPrefix(trimmed, "#") {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "#") {
// Remove the # and trim
comment := core.Trim(core.TrimPrefix(trimmed, "#"))
comment := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
if comment != "" {
descLines = append(descLines, comment)
// Only take the first meaningful comment line as description

View file

@ -1,17 +1,16 @@
package container
import (
"os"
"path/filepath"
"strings"
"testing"
core "dappco.re/go/core"
"dappco.re/go/core/io"
"dappco.re/go/core/container/internal/coreutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTemplates_ListTemplates_Good(t *testing.T) {
func TestListTemplates_Good(t *testing.T) {
templates := ListTemplates()
// Should have at least the builtin templates
@ -42,7 +41,7 @@ func TestTemplates_ListTemplates_Good(t *testing.T) {
assert.True(t, found, "server-php template should exist")
}
func TestGetTemplate_CoreDev_Good(t *testing.T) {
func TestGetTemplate_Good_CoreDev(t *testing.T) {
content, err := GetTemplate("core-dev")
require.NoError(t, err)
@ -53,7 +52,7 @@ func TestGetTemplate_CoreDev_Good(t *testing.T) {
assert.Contains(t, content, "services:")
}
func TestGetTemplate_ServerPhp_Good(t *testing.T) {
func TestGetTemplate_Good_ServerPhp(t *testing.T) {
content, err := GetTemplate("server-php")
require.NoError(t, err)
@ -64,14 +63,14 @@ func TestGetTemplate_ServerPhp_Good(t *testing.T) {
assert.Contains(t, content, "${DOMAIN:-localhost}")
}
func TestGetTemplate_NotFound_Bad(t *testing.T) {
func TestGetTemplate_Bad_NotFound(t *testing.T) {
_, err := GetTemplate("nonexistent-template")
assert.Error(t, err)
assert.Contains(t, err.Error(), "template not found")
}
func TestApplyVariables_SimpleSubstitution_Good(t *testing.T) {
func TestApplyVariables_Good_SimpleSubstitution(t *testing.T) {
content := "Hello ${NAME}, welcome to ${PLACE}!"
vars := map[string]string{
"NAME": "World",
@ -84,7 +83,7 @@ func TestApplyVariables_SimpleSubstitution_Good(t *testing.T) {
assert.Equal(t, "Hello World, welcome to Core!", result)
}
func TestApplyVariables_WithDefaults_Good(t *testing.T) {
func TestApplyVariables_Good_WithDefaults(t *testing.T) {
content := "Memory: ${MEMORY:-1024}MB, CPUs: ${CPUS:-2}"
vars := map[string]string{
"MEMORY": "2048",
@ -97,7 +96,7 @@ func TestApplyVariables_WithDefaults_Good(t *testing.T) {
assert.Equal(t, "Memory: 2048MB, CPUs: 2", result)
}
func TestApplyVariables_AllDefaults_Good(t *testing.T) {
func TestApplyVariables_Good_AllDefaults(t *testing.T) {
content := "${HOST:-localhost}:${PORT:-8080}"
vars := map[string]string{} // No vars provided
@ -107,7 +106,7 @@ func TestApplyVariables_AllDefaults_Good(t *testing.T) {
assert.Equal(t, "localhost:8080", result)
}
func TestApplyVariables_MixedSyntax_Good(t *testing.T) {
func TestApplyVariables_Good_MixedSyntax(t *testing.T) {
content := `
hostname: ${HOSTNAME:-myhost}
ssh_key: ${SSH_KEY}
@ -126,7 +125,7 @@ memory: ${MEMORY:-512}
assert.Contains(t, result, "memory: 512")
}
func TestApplyVariables_EmptyDefault_Good(t *testing.T) {
func TestApplyVariables_Good_EmptyDefault(t *testing.T) {
content := "value: ${OPT:-}"
vars := map[string]string{}
@ -136,7 +135,7 @@ func TestApplyVariables_EmptyDefault_Good(t *testing.T) {
assert.Equal(t, "value: ", result)
}
func TestApplyVariables_MissingRequired_Bad(t *testing.T) {
func TestApplyVariables_Bad_MissingRequired(t *testing.T) {
content := "SSH Key: ${SSH_KEY}"
vars := map[string]string{} // Missing required SSH_KEY
@ -147,7 +146,7 @@ func TestApplyVariables_MissingRequired_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "SSH_KEY")
}
func TestApplyVariables_MultipleMissing_Bad(t *testing.T) {
func TestApplyVariables_Bad_MultipleMissing(t *testing.T) {
content := "${VAR1} and ${VAR2} and ${VAR3}"
vars := map[string]string{
"VAR2": "provided",
@ -159,10 +158,10 @@ func TestApplyVariables_MultipleMissing_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "missing required variables")
// Should mention both missing vars
errStr := err.Error()
assert.True(t, core.Contains(errStr, "VAR1") || core.Contains(errStr, "VAR3"))
assert.True(t, strings.Contains(errStr, "VAR1") || strings.Contains(errStr, "VAR3"))
}
func TestTemplates_ApplyTemplate_Good(t *testing.T) {
func TestApplyTemplate_Good(t *testing.T) {
vars := map[string]string{
"SSH_KEY": "ssh-rsa AAAA... user@host",
}
@ -176,7 +175,7 @@ func TestTemplates_ApplyTemplate_Good(t *testing.T) {
assert.Contains(t, result, "core-dev") // HOSTNAME default
}
func TestApplyTemplate_TemplateNotFound_Bad(t *testing.T) {
func TestApplyTemplate_Bad_TemplateNotFound(t *testing.T) {
vars := map[string]string{
"SSH_KEY": "test",
}
@ -187,7 +186,7 @@ func TestApplyTemplate_TemplateNotFound_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "template not found")
}
func TestApplyTemplate_MissingVariable_Bad(t *testing.T) {
func TestApplyTemplate_Bad_MissingVariable(t *testing.T) {
// server-php requires SSH_KEY
vars := map[string]string{} // Missing required SSH_KEY
@ -197,7 +196,7 @@ func TestApplyTemplate_MissingVariable_Bad(t *testing.T) {
assert.Contains(t, err.Error(), "missing required variables")
}
func TestTemplates_ExtractVariables_Good(t *testing.T) {
func TestExtractVariables_Good(t *testing.T) {
content := `
hostname: ${HOSTNAME:-myhost}
ssh_key: ${SSH_KEY}
@ -219,7 +218,7 @@ api_key: ${API_KEY}
assert.Len(t, optional, 3)
}
func TestExtractVariables_NoVariables_Good(t *testing.T) {
func TestExtractVariables_Good_NoVariables(t *testing.T) {
content := "This has no variables at all"
required, optional := ExtractVariables(content)
@ -228,7 +227,7 @@ func TestExtractVariables_NoVariables_Good(t *testing.T) {
assert.Empty(t, optional)
}
func TestExtractVariables_OnlyDefaults_Good(t *testing.T) {
func TestExtractVariables_Good_OnlyDefaults(t *testing.T) {
content := "${A:-default1} ${B:-default2}"
required, optional := ExtractVariables(content)
@ -239,7 +238,7 @@ func TestExtractVariables_OnlyDefaults_Good(t *testing.T) {
assert.Equal(t, "default2", optional["B"])
}
func TestTemplates_ScanUserTemplates_Good(t *testing.T) {
func TestScanUserTemplates_Good(t *testing.T) {
// Create a temporary directory with template files
tmpDir := t.TempDir()
@ -249,11 +248,11 @@ func TestTemplates_ScanUserTemplates_Good(t *testing.T) {
kernel:
image: linuxkit/kernel:6.6
`
err := io.Local.Write(coreutil.JoinPath(tmpDir, "custom.yml"), templateContent)
err := os.WriteFile(filepath.Join(tmpDir, "custom.yml"), []byte(templateContent), 0644)
require.NoError(t, err)
// Create a non-template file (should be ignored)
err = io.Local.Write(coreutil.JoinPath(tmpDir, "readme.txt"), "Not a template")
err = os.WriteFile(filepath.Join(tmpDir, "readme.txt"), []byte("Not a template"), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)
@ -263,13 +262,13 @@ kernel:
assert.Equal(t, "My Custom Template", templates[0].Description)
}
func TestScanUserTemplates_MultipleTemplates_Good(t *testing.T) {
func TestScanUserTemplates_Good_MultipleTemplates(t *testing.T) {
tmpDir := t.TempDir()
// Create multiple template files
err := io.Local.Write(coreutil.JoinPath(tmpDir, "web.yml"), "# Web Server\nkernel:")
err := os.WriteFile(filepath.Join(tmpDir, "web.yml"), []byte("# Web Server\nkernel:"), 0644)
require.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(tmpDir, "db.yaml"), "# Database Server\nkernel:")
err = os.WriteFile(filepath.Join(tmpDir, "db.yaml"), []byte("# Database Server\nkernel:"), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)
@ -285,7 +284,7 @@ func TestScanUserTemplates_MultipleTemplates_Good(t *testing.T) {
assert.True(t, names["db"])
}
func TestScanUserTemplates_EmptyDirectory_Good(t *testing.T) {
func TestScanUserTemplates_Good_EmptyDirectory(t *testing.T) {
tmpDir := t.TempDir()
templates := scanUserTemplates(tmpDir)
@ -293,22 +292,22 @@ func TestScanUserTemplates_EmptyDirectory_Good(t *testing.T) {
assert.Empty(t, templates)
}
func TestScanUserTemplates_NonexistentDirectory_Bad(t *testing.T) {
func TestScanUserTemplates_Bad_NonexistentDirectory(t *testing.T) {
templates := scanUserTemplates("/nonexistent/path/to/templates")
assert.Empty(t, templates)
}
func TestTemplates_ExtractTemplateDescription_Good(t *testing.T) {
func TestExtractTemplateDescription_Good(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "test.yml")
path := filepath.Join(tmpDir, "test.yml")
content := `# My Template Description
# More details here
kernel:
image: test
`
err := io.Local.Write(path, content)
err := os.WriteFile(path, []byte(content), 0644)
require.NoError(t, err)
desc := extractTemplateDescription(path)
@ -316,14 +315,14 @@ kernel:
assert.Equal(t, "My Template Description", desc)
}
func TestExtractTemplateDescription_NoComments_Good(t *testing.T) {
func TestExtractTemplateDescription_Good_NoComments(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "test.yml")
path := filepath.Join(tmpDir, "test.yml")
content := `kernel:
image: test
`
err := io.Local.Write(path, content)
err := os.WriteFile(path, []byte(content), 0644)
require.NoError(t, err)
desc := extractTemplateDescription(path)
@ -331,13 +330,13 @@ func TestExtractTemplateDescription_NoComments_Good(t *testing.T) {
assert.Empty(t, desc)
}
func TestExtractTemplateDescription_FileNotFound_Bad(t *testing.T) {
func TestExtractTemplateDescription_Bad_FileNotFound(t *testing.T) {
desc := extractTemplateDescription("/nonexistent/file.yml")
assert.Empty(t, desc)
}
func TestTemplates_VariablePatternEdgeCases_Good(t *testing.T) {
func TestVariablePatternEdgeCases_Good(t *testing.T) {
tests := []struct {
name string
content string
@ -385,15 +384,15 @@ func TestTemplates_VariablePatternEdgeCases_Good(t *testing.T) {
}
}
func TestScanUserTemplates_SkipsBuiltinNames_Good(t *testing.T) {
func TestScanUserTemplates_Good_SkipsBuiltinNames(t *testing.T) {
tmpDir := t.TempDir()
// Create a template with a builtin name (should be skipped)
err := io.Local.Write(coreutil.JoinPath(tmpDir, "core-dev.yml"), "# Duplicate\nkernel:")
err := os.WriteFile(filepath.Join(tmpDir, "core-dev.yml"), []byte("# Duplicate\nkernel:"), 0644)
require.NoError(t, err)
// Create a unique template
err = io.Local.Write(coreutil.JoinPath(tmpDir, "unique.yml"), "# Unique\nkernel:")
err = os.WriteFile(filepath.Join(tmpDir, "unique.yml"), []byte("# Unique\nkernel:"), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)
@ -403,15 +402,15 @@ func TestScanUserTemplates_SkipsBuiltinNames_Good(t *testing.T) {
assert.Equal(t, "unique", templates[0].Name)
}
func TestScanUserTemplates_SkipsDirectories_Good(t *testing.T) {
func TestScanUserTemplates_Good_SkipsDirectories(t *testing.T) {
tmpDir := t.TempDir()
// Create a subdirectory (should be skipped)
err := io.Local.EnsureDir(coreutil.JoinPath(tmpDir, "subdir"))
err := os.MkdirAll(filepath.Join(tmpDir, "subdir"), 0755)
require.NoError(t, err)
// Create a valid template
err = io.Local.Write(coreutil.JoinPath(tmpDir, "valid.yml"), "# Valid\nkernel:")
err = os.WriteFile(filepath.Join(tmpDir, "valid.yml"), []byte("# Valid\nkernel:"), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)
@ -420,13 +419,13 @@ func TestScanUserTemplates_SkipsDirectories_Good(t *testing.T) {
assert.Equal(t, "valid", templates[0].Name)
}
func TestScanUserTemplates_YamlExtension_Good(t *testing.T) {
func TestScanUserTemplates_Good_YamlExtension(t *testing.T) {
tmpDir := t.TempDir()
// Create templates with both extensions
err := io.Local.Write(coreutil.JoinPath(tmpDir, "template1.yml"), "# Template 1\nkernel:")
err := os.WriteFile(filepath.Join(tmpDir, "template1.yml"), []byte("# Template 1\nkernel:"), 0644)
require.NoError(t, err)
err = io.Local.Write(coreutil.JoinPath(tmpDir, "template2.yaml"), "# Template 2\nkernel:")
err = os.WriteFile(filepath.Join(tmpDir, "template2.yaml"), []byte("# Template 2\nkernel:"), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)
@ -441,9 +440,9 @@ func TestScanUserTemplates_YamlExtension_Good(t *testing.T) {
assert.True(t, names["template2"])
}
func TestExtractTemplateDescription_EmptyComment_Good(t *testing.T) {
func TestExtractTemplateDescription_Good_EmptyComment(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "test.yml")
path := filepath.Join(tmpDir, "test.yml")
// First comment is empty, second has content
content := `#
@ -451,7 +450,7 @@ func TestExtractTemplateDescription_EmptyComment_Good(t *testing.T) {
kernel:
image: test
`
err := io.Local.Write(path, content)
err := os.WriteFile(path, []byte(content), 0644)
require.NoError(t, err)
desc := extractTemplateDescription(path)
@ -459,9 +458,9 @@ kernel:
assert.Equal(t, "Actual description here", desc)
}
func TestExtractTemplateDescription_MultipleEmptyComments_Good(t *testing.T) {
func TestExtractTemplateDescription_Good_MultipleEmptyComments(t *testing.T) {
tmpDir := t.TempDir()
path := coreutil.JoinPath(tmpDir, "test.yml")
path := filepath.Join(tmpDir, "test.yml")
// Multiple empty comments before actual content
content := `#
@ -471,7 +470,7 @@ func TestExtractTemplateDescription_MultipleEmptyComments_Good(t *testing.T) {
kernel:
image: test
`
err := io.Local.Write(path, content)
err := os.WriteFile(path, []byte(content), 0644)
require.NoError(t, err)
desc := extractTemplateDescription(path)
@ -479,14 +478,14 @@ kernel:
assert.Equal(t, "Real description", desc)
}
func TestScanUserTemplates_DefaultDescription_Good(t *testing.T) {
func TestScanUserTemplates_Good_DefaultDescription(t *testing.T) {
tmpDir := t.TempDir()
// Create a template without comments
content := `kernel:
image: test
`
err := io.Local.Write(coreutil.JoinPath(tmpDir, "nocomment.yml"), content)
err := os.WriteFile(filepath.Join(tmpDir, "nocomment.yml"), []byte(content), 0644)
require.NoError(t, err)
templates := scanUserTemplates(tmpDir)