Skip to content

Modern Docker Management, Designed for Everyone

refactor(cli): constructor-based commands, generic helpers, shared types

Kyle Mendell0d07bea3fd76
diff --git a/backend/cli/generate/api_key_test.go b/backend/cli/generate/api_key_test.go
index 806c1242e..7dbd4b364 100644
--- a/backend/cli/generate/api_key_test.go
+++ b/backend/cli/generate/api_key_test.go
@@ -4,11 +4,12 @@ import (
"strings"
"testing"
+ cligenerate "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
"github.com/stretchr/testify/require"
)
func TestAPIKeyCommandAvailableInBackendCLI(t *testing.T) {
- cmd := GenerateCmd
+ cmd := cligenerate.Command()
cmd.SetArgs([]string{"api-key"})
out, err := captureOutput(func() error {
diff --git a/backend/cli/generate/generate.go b/backend/cli/generate/generate.go
deleted file mode 100644
index 1f050e947..000000000
--- a/backend/cli/generate/generate.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package generate
-
-import (
- cligenerate "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
-)
-
-var GenerateCmd = cligenerate.GenerateCmd
diff --git a/backend/cli/generate/secret_test.go b/backend/cli/generate/secret_test.go
index 821d44c2f..699e0c246 100644
--- a/backend/cli/generate/secret_test.go
+++ b/backend/cli/generate/secret_test.go
@@ -9,6 +9,7 @@ import (
"strings"
"testing"
+ cligenerate "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
"github.com/stretchr/testify/require"
)
@@ -37,7 +38,7 @@ func captureOutput(fn func() error) (string, error) {
}
func TestSecretDefaultBase64(t *testing.T) {
- cmd := GenerateCmd
+ cmd := cligenerate.Command()
cmd.SetArgs([]string{"secret"})
out, err := captureOutput(func() error {
@@ -78,7 +79,7 @@ func TestSecretDefaultBase64(t *testing.T) {
}
func TestSecretAllFormatContainsSections(t *testing.T) {
- cmd := GenerateCmd
+ cmd := cligenerate.Command()
cmd.SetArgs([]string{"secret", "-f", "all"})
out, err := captureOutput(func() error {
diff --git a/backend/cli/root.go b/backend/cli/root.go
index 713f1c2b8..2628788fe 100644
--- a/backend/cli/root.go
+++ b/backend/cli/root.go
@@ -5,11 +5,11 @@ import (
"log/slog"
"os"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
"github.com/spf13/cobra"
"go.getarcane.app/kit/pkg/signals"
"github.com/getarcaneapp/arcane/backend/v2/cli/admin"
- "github.com/getarcaneapp/arcane/backend/v2/cli/generate"
"github.com/getarcaneapp/arcane/backend/v2/cli/recovery"
"github.com/getarcaneapp/arcane/backend/v2/cli/upgrade"
"github.com/getarcaneapp/arcane/backend/v2/internal/bootstrap"
@@ -43,5 +43,5 @@ func init() {
rootCmd.AddCommand(admin.AdminCmd)
rootCmd.AddCommand(upgrade.UpgradeCmd)
rootCmd.AddCommand(recovery.RestoreCmd)
- rootCmd.AddCommand(generate.GenerateCmd)
+ rootCmd.AddCommand(generate.Command())
}
diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.go
index 0c1188612..327a55ebd 100644
--- a/backend/internal/container/handler.go
+++ b/backend/internal/container/handler.go
@@ -104,9 +104,7 @@ type DeleteContainerInput struct {
type SetAutoUpdateInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ContainerID string `path:"containerId" doc:"Container ID"`
- Body struct {
- Enabled bool `json:"enabled" doc:"Whether auto-update is enabled for this container"`
- }
+ Body container.SetAutoUpdateRequest
}
// KillContainerInput carries the optional signal for a container kill.
@@ -511,7 +509,7 @@ func (h *ContainerHandler) GenerateCompose(ctx context.Context, input *GenerateC
}
func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
- return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
+ return h.runContainerAction(ctx, input, containerActionConfig{
ActivityType: activitytypes.TypeContainerStart,
Step: "Starting container",
StartMessage: "Container start requested",
@@ -527,7 +525,7 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerA
}
func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
- return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
+ return h.runContainerAction(ctx, input, containerActionConfig{
ActivityType: activitytypes.TypeContainerStop,
Step: "Stopping container",
StartMessage: "Container stop requested",
@@ -543,7 +541,7 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAc
}
func (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
- return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
+ return h.runContainerAction(ctx, input, containerActionConfig{
ActivityType: activitytypes.TypeContainerRestart,
Step: "Restarting container",
StartMessage: "Container restart requested",
@@ -560,7 +558,7 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containe
func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainerInput) (*handlerutil.Out[base.MessageResponse], error) {
signal := strings.TrimSpace(input.Signal)
- return h.runContainerActionInternal(ctx, &ContainerActionInput{EnvironmentID: input.EnvironmentID, ContainerID: input.ContainerID}, containerActionConfigInternal{
+ return h.runContainerAction(ctx, &ContainerActionInput{EnvironmentID: input.EnvironmentID, ContainerID: input.ContainerID}, containerActionConfig{
ActivityType: activitytypes.TypeContainerKill,
Step: "Killing container",
StartMessage: "Container kill requested",
@@ -576,7 +574,7 @@ func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContain
}
func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
- return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
+ return h.runContainerAction(ctx, input, containerActionConfig{
ActivityType: activitytypes.TypeContainerPause,
Step: "Pausing container",
StartMessage: "Container pause requested",
@@ -592,7 +590,7 @@ func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerA
}
func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *ContainerActionInput) (*handlerutil.Out[base.MessageResponse], error) {
- return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{
+ return h.runContainerAction(ctx, input, containerActionConfig{
ActivityType: activitytypes.TypeContainerUnpause,
Step: "Unpausing container",
StartMessage: "Container unpause requested",
@@ -607,7 +605,7 @@ func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *Containe
})
}
-type containerActionConfigInternal struct {
+type containerActionConfig struct {
ActivityType activitytypes.Type
Step string
StartMessage string
@@ -617,8 +615,8 @@ type containerActionConfigInternal struct {
Error func(error) error
}
-// containerActivityNameInternal returns the container's name for activity records, falling back to its ID.
-func (h *ContainerHandler) containerActivityNameInternal(ctx context.Context, containerID string) string {
+// containerActivityName returns the container's name for activity records, falling back to its ID.
+func (h *ContainerHandler) containerActivityName(ctx context.Context, containerID string) string {
name, err := h.containerService.GetContainerNameByID(ctx, containerID)
if err != nil || name == "" {
return containerID
@@ -626,7 +624,7 @@ func (h *ContainerHandler) containerActivityNameInternal(ctx context.Context, co
return name
}
-func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input *ContainerActionInput, cfg containerActionConfigInternal) (*handlerutil.Out[base.MessageResponse], error) {
+func (h *ContainerHandler) runContainerAction(ctx context.Context, input *ContainerActionInput, cfg containerActionConfig) (*handlerutil.Out[base.MessageResponse], error) {
user, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
@@ -640,7 +638,7 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
cfg.ActivityType,
"container",
input.ContainerID,
- h.containerActivityNameInternal(
+ h.containerActivityName(
runtimeCtx,
input.ContainerID,
),
@@ -698,7 +696,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
activitytypes.TypeContainerRedeploy,
"container",
input.ContainerID,
- h.containerActivityNameInternal(
+ h.containerActivityName(
runtimeCtx,
input.ContainerID,
),
@@ -762,7 +760,7 @@ func (h *ContainerHandler) GetContainerEditConfig(ctx context.Context, input *Ge
}, nil
}
-func editContainerHTTPErrorInternal(err error) error {
+func editContainerHTTPError(err error) error {
switch {
case errors.Is(err, common.ErrConflict):
return huma.Error409Conflict(err.Error())
@@ -787,7 +785,7 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
activitytypes.TypeContainerEdit,
"container",
input.ContainerID,
- h.containerActivityNameInternal(
+ h.containerActivityName(
runtimeCtx,
input.ContainerID,
),
@@ -806,7 +804,7 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
if err != nil {
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container edit failed", err)
- return nil, editContainerHTTPErrorInternal(err)
+ return nil, editContainerHTTPError(err)
}
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container edited", nil)
@@ -851,7 +849,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
activitytypes.TypeContainerDelete,
"container",
input.ContainerID,
- h.containerActivityNameInternal(
+ h.containerActivityName(
runtimeCtx,
input.ContainerID,
),
diff --git a/backend/internal/environment/service.go b/backend/internal/environment/service.go
index 48cd6b76e..5b419e57a 100644
--- a/backend/internal/environment/service.go
+++ b/backend/internal/environment/service.go
@@ -17,6 +17,7 @@ import (
"uuid"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
+ "github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"github.com/getarcaneapp/arcane/types/v2/environment"
"github.com/getarcaneapp/arcane/types/v2/scheduler"
@@ -1377,9 +1378,7 @@ func (s *EnvironmentService) CheckS3DestinationReferences(ctx context.Context, d
if env.AccessToken == nil || strings.TrimSpace(*env.AccessToken) == "" {
continue
}
- var result struct {
- InUse bool `json:"inUse"`
- }
+ var result backup.S3DestinationUsage
path := "/api/backups/s3/" + url.PathEscape(destinationID) + "/in-use"
if proxyErr := s.ProxyJSONRequestForEnvironment(ctx, env, http.MethodGet, path, nil, &result); proxyErr != nil {
return fmt.Errorf("cannot verify S3 destination references on environment %s; restore connectivity before deleting: %w", env.Name, proxyErr)
diff --git a/backend/internal/event/handler.go b/backend/internal/event/handler.go
index 73ff7a464..38f8ddf6c 100644
--- a/backend/internal/event/handler.go
+++ b/backend/internal/event/handler.go
@@ -68,14 +68,14 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
}
// GetEventStats returns global event counts grouped by severity.
-func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*handlerutil.Out[EventSeverityCounts], error) {
+func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*handlerutil.Out[event.SeverityCounts], error) {
counts, err := h.eventService.GetEventSeverityCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("Failed to load event statistics: " + err.Error())
}
- return &handlerutil.Out[EventSeverityCounts]{
- Body: base.ApiResponse[EventSeverityCounts]{
+ return &handlerutil.Out[event.SeverityCounts]{
+ Body: base.ApiResponse[event.SeverityCounts]{
Success: true,
Data: counts,
},
diff --git a/backend/internal/event/service.go b/backend/internal/event/service.go
index 793b9a590..d8d80ef1f 100644
--- a/backend/internal/event/service.go
+++ b/backend/internal/event/service.go
@@ -410,16 +410,7 @@ func applyEventTypeFilter(q *gorm.DB, value string) *gorm.DB {
return q.Where(strings.Join(conds, " OR "), args...)
}
-// EventSeverityCounts holds global event counts per severity.
-type EventSeverityCounts struct {
- Total int64 `json:"total"`
- Info int64 `json:"info"`
- Success int64 `json:"success"`
- Warning int64 `json:"warning"`
- Error int64 `json:"error"`
-}
-
-func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeverityCounts, error) {
+func (s *EventService) GetEventSeverityCounts(ctx context.Context) (event.SeverityCounts, error) {
var rows []struct {
Severity string
Count int64
@@ -428,10 +419,10 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeverit
Select("severity, COUNT(*) AS count").
Group("severity").
Scan(&rows).Error; err != nil {
- return EventSeverityCounts{}, fmt.Errorf("failed to count events by severity: %w", err)
+ return event.SeverityCounts{}, fmt.Errorf("failed to count events by severity: %w", err)
}
- var counts EventSeverityCounts
+ var counts event.SeverityCounts
for _, r := range rows {
switch EventSeverity(r.Severity) {
case EventSeveritySuccess:
diff --git a/backend/internal/event/service_test.go b/backend/internal/event/service_test.go
index eb7f73ef0..085e2a51a 100644
--- a/backend/internal/event/service_test.go
+++ b/backend/internal/event/service_test.go
@@ -318,7 +318,7 @@ func TestEventService_GetEventSeverityCounts(t *testing.T) {
counts, err := svc.GetEventSeverityCounts(ctx)
require.NoError(t, err)
- require.Equal(t, EventSeverityCounts{Total: 4, Info: 2, Success: 1, Warning: 0, Error: 1}, counts)
+ require.Equal(t, event.SeverityCounts{Total: 4, Info: 2, Success: 1, Warning: 0, Error: 1}, counts)
}
func TestEventService_ListEventsPaginated_TypeCategoryFilter(t *testing.T) {
diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.go
index ac7ef2401..588fe103b 100644
--- a/backend/internal/project/handler.go
+++ b/backend/internal/project/handler.go
@@ -124,9 +124,7 @@ type RestartProjectInput struct {
type UpdateProjectServicesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
- Body *struct {
- Services []string `json:"services,omitempty" doc:"Service names to update; empty updates all services"`
- }
+ Body *project.UpdateServicesRequest
}
type ArchiveProjectInput struct {
@@ -147,12 +145,7 @@ type PullProjectImagesInput struct {
type BuildProjectInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
ProjectID string `path:"projectId" doc:"Project ID"`
- Body *struct {
- Services []string `json:"services,omitempty" doc:"Service names to build"`
- Provider string `json:"provider,omitempty" doc:"Build provider override"`
- Push *bool `json:"push,omitempty" doc:"Push images"`
- Load *bool `json:"load,omitempty" doc:"Load images into Docker"`
- }
+ Body *project.BuildRequest
}
// ListProjects returns a paginated list of projects.
@@ -245,7 +238,7 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProj
Type: activitytypes.TypeResourceAction,
ResourceType: "project",
ResourceID: input.ProjectID,
- ResourceName: h.projectActivityNameInternal(runtimeCtx, input.ProjectID),
+ ResourceName: h.projectActivityName(runtimeCtx, input.ProjectID),
User: user,
Step: "Updating project tags",
Message: "Updating project tags",
@@ -277,10 +270,10 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProj
}
// DeployProject deploys a Docker Compose project.
-// projectStreamOperationConfigInternal describes one streamed project
+// projectStreamOperationConfig describes one streamed project
// operation (deploy, redeploy, pull, build): the activity it records and the
// action whose raw docker CLI output is streamed to the client.
-type projectStreamOperationConfigInternal struct {
+type projectStreamOperationConfig struct {
ActivityType activitytypes.Type
Step string
StartMessage string
@@ -294,8 +287,8 @@ type projectStreamOperationConfigInternal struct {
Action func(ctx context.Context, writer io.Writer) error
}
-// projectActivityNameInternal returns the project's name for activity records, falling back to its ID.
-func (h *ProjectHandler) projectActivityNameInternal(ctx context.Context, projectID string) string {
+// projectActivityName returns the project's name for activity records, falling back to its ID.
+func (h *ProjectHandler) projectActivityName(ctx context.Context, projectID string) string {
proj, err := h.projectService.GetProjectFromDatabaseByID(ctx, projectID)
if err != nil || proj.Name == "" {
return projectID
@@ -303,11 +296,11 @@ func (h *ProjectHandler) projectActivityNameInternal(ctx context.Context, projec
return proj.Name
}
-// streamProjectOperationInternal is the shared scaffold for the streamed
+// streamProjectOperation is the shared scaffold for the streamed
// project endpoints: NDJSON headers, activity lifecycle (started frame, queue
// slot, completion), the activity-teeing writer, and the terminal done/error
// frames.
-func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectID string, user *usertypes.Actor, cfg projectStreamOperationConfigInternal) *huma.StreamResponse {
+func (h *ProjectHandler) streamProjectOperation(environmentID, projectID string, user *usertypes.Actor, cfg projectStreamOperationConfig) *huma.StreamResponse {
return &huma.StreamResponse{
Body: func(humaCtx huma.Context) {
httpx.SetJSONStreamHeaders(humaCtx)
@@ -325,7 +318,7 @@ func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectID
cfg.ActivityType,
"project",
projectID,
- h.projectActivityNameInternal(runtimeCtx, projectID),
+ h.projectActivityName(runtimeCtx, projectID),
user,
cfg.Step,
cfg.StartMessage,
@@ -369,7 +362,7 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
}
//nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
+ return h.streamProjectOperation(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfig{
ActivityType: activitytypes.TypeProjectDeploy,
Step: "Starting deployment",
StartMessage: "Project deployment started",
@@ -397,7 +390,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
activitytypes.TypeProjectDown,
"project",
input.ProjectID,
- h.projectActivityNameInternal(
+ h.projectActivityName(
runtimeCtx,
input.ProjectID,
),
@@ -425,7 +418,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
return handlerutil.MessageOutput("Project brought down successfully", activityID), nil
}
-func projectUpdateHTTPErrorInternal(err error) error {
+func projectUpdateHTTPError(err error) error {
if conflictErr, ok := errors.AsType[*volume.ProjectVolumeRenameConflictError](err); ok {
return huma.Error409Conflict(conflictErr.Error())
}
@@ -435,12 +428,12 @@ func projectUpdateHTTPErrorInternal(err error) error {
if spaceErr, ok := errors.AsType[*volume.ProjectVolumeRenameInsufficientSpaceError](err); ok {
return huma.NewError(http.StatusInsufficientStorage, spaceErr.Error())
}
- return projectWorkspaceRequestHTTPErrorInternal(err)
+ return projectWorkspaceRequestHTTPError(err)
}
-// projectWorkspaceRequestHTTPErrorInternal maps workspace validation errors that
+// projectWorkspaceRequestHTTPError maps workspace validation errors that
// can also surface during atomic project creation or configuration updates.
-func projectWorkspaceRequestHTTPErrorInternal(err error) error {
+func projectWorkspaceRequestHTTPError(err error) error {
if errors.Is(err, common.ErrProjectWorkspaceConflict) {
return huma.Error409Conflict(err.Error())
}
@@ -505,7 +498,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
return createErr
})
if err != nil {
- if httpErr := projectWorkspaceRequestHTTPErrorInternal(err); httpErr != nil {
+ if httpErr := projectWorkspaceRequestHTTPError(err); httpErr != nil {
return nil, httpErr
}
return nil, huma.Error500InternalServerError("Failed to create project: " + err.Error())
@@ -557,7 +550,7 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)
}, nil
}
-func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*handlerutil.Out[project.Details], error) {
+func (h *ProjectHandler) getProjectDetailsWithOptions(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*handlerutil.Out[project.Details], error) {
if input.ProjectID == "" {
return nil, huma.Error400BadRequest("Project ID is required")
}
@@ -576,7 +569,7 @@ func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Contex
}
func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
- return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
+ return h.getProjectDetailsWithOptions(ctx, input, project.DetailsOptions{
IncludeComposeContent: true,
IncludeEnvState: true,
IncludeIncludeFiles: true,
@@ -585,13 +578,13 @@ func (h *ProjectHandler) GetProjectCompose(ctx context.Context, input *GetProjec
}
func (h *ProjectHandler) GetProjectRuntime(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
- return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
+ return h.getProjectDetailsWithOptions(ctx, input, project.DetailsOptions{
IncludeRuntimeServices: true,
})
}
func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjectInput) (*handlerutil.Out[project.Details], error) {
- return h.getProjectDetailsWithOptionsInternal(ctx, input, project.DetailsOptions{
+ return h.getProjectDetailsWithOptions(ctx, input, project.DetailsOptions{
IncludeServiceConfigs: true,
IncludeUpdateInfo: true,
})
@@ -611,7 +604,7 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
}
//nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
+ return h.streamProjectOperation(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfig{
ActivityType: activitytypes.TypeProjectRedeploy,
Step: "Starting redeploy",
StartMessage: "Project redeploy started",
@@ -655,7 +648,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
activitytypes.TypeProjectDestroy,
"project",
input.ProjectID,
- h.projectActivityNameInternal(
+ h.projectActivityName(
runtimeCtx,
input.ProjectID,
),
@@ -710,7 +703,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
return updateErr
})
if err != nil {
- if httpErr := projectUpdateHTTPErrorInternal(err); httpErr != nil {
+ if httpErr := projectUpdateHTTPError(err); httpErr != nil {
return nil, httpErr
}
return nil, huma.Error400BadRequest("Failed to update project: " + err.Error())
@@ -740,7 +733,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
// RestartProject restarts the given services in a project (all services when none
// are specified).
func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*handlerutil.Out[base.MessageResponse], error) {
- response, err := h.runProjectActivityActionResponseInternal(ctx, input.EnvironmentID, input.ProjectID, h.restartProjectActivityConfigInternal(input.Services))
+ response, err := h.runProjectActivityActionResponse(ctx, input.EnvironmentID, input.ProjectID, h.restartProjectActivityConfig(input.Services))
if err != nil {
return nil, err
}
@@ -757,7 +750,7 @@ func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *Updat
serviceNames = input.Body.Services
}
- response, err := h.runProjectActivityActionResponseInternal(ctx, input.EnvironmentID, input.ProjectID, h.updateProjectServicesActivityConfigInternal(serviceNames))
+ response, err := h.runProjectActivityActionResponse(ctx, input.EnvironmentID, input.ProjectID, h.updateProjectServicesActivityConfig(serviceNames))
if err != nil {
return nil, err
}
@@ -767,7 +760,7 @@ func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *Updat
}, nil
}
-type projectActivityActionConfigInternal struct {
+type projectActivityActionConfig struct {
ActivityType activitytypes.Type
Step string
StartMessage string
@@ -782,8 +775,8 @@ type projectActivityActionConfigInternal struct {
Error func(error) error
}
-func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []string) projectActivityActionConfigInternal {
- return projectActivityActionConfigInternal{
+func (h *ProjectHandler) updateProjectServicesActivityConfig(services []string) projectActivityActionConfig {
+ return projectActivityActionConfig{
ActivityType: activitytypes.TypeAutoUpdate,
Step: "Updating project services",
StartMessage: "Project services update requested",
@@ -795,14 +788,14 @@ func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []
Action: func(runtimeCtx context.Context, projectID string, user usertypes.Actor) error {
return h.projectService.UpdateProjectServices(runtimeCtx, projectID, services, user, true)
},
- Error: projectArchivedActionErrorInternal(func(err error) error {
+ Error: projectArchivedActionError(func(err error) error {
return huma.Error400BadRequest("Failed to update project: " + err.Error())
}),
}
}
-func (h *ProjectHandler) restartProjectActivityConfigInternal(services []string) projectActivityActionConfigInternal {
- return projectActivityActionConfigInternal{
+func (h *ProjectHandler) restartProjectActivityConfig(services []string) projectActivityActionConfig {
+ return projectActivityActionConfig{
ActivityType: activitytypes.TypeProjectRestart,
Step: "Restarting project",
StartMessage: "Project restart requested",
@@ -813,13 +806,13 @@ func (h *ProjectHandler) restartProjectActivityConfigInternal(services []string)
Action: func(runtimeCtx context.Context, projectID string, user usertypes.Actor) error {
return h.projectService.RestartProject(runtimeCtx, projectID, services, user)
},
- Error: projectArchivedActionErrorInternal(func(err error) error {
+ Error: projectArchivedActionError(func(err error) error {
return huma.Error400BadRequest("Failed to restart project: " + err.Error())
}),
}
}
-func projectArchivedActionErrorInternal(fallback func(error) error) func(error) error {
+func projectArchivedActionError(fallback func(error) error) func(error) error {
return func(err error) error {
if errors.Is(err, common.ErrProjectArchived) {
return huma.Error400BadRequest(err.Error())
@@ -828,13 +821,13 @@ func projectArchivedActionErrorInternal(fallback func(error) error) func(error)
}
}
-func (h *ProjectHandler) runProjectActivityActionResponseInternal(
+func (h *ProjectHandler) runProjectActivityActionResponse(
ctx context.Context,
environmentID string,
projectID string,
- cfg projectActivityActionConfigInternal,
+ cfg projectActivityActionConfig,
) (base.ApiResponse[base.MessageResponse], error) {
- message, err := h.runProjectActivityActionInternal(ctx, environmentID, projectID, cfg)
+ message, err := h.runProjectActivityAction(ctx, environmentID, projectID, cfg)
if err != nil {
return base.ApiResponse[base.MessageResponse]{}, err
}
@@ -845,7 +838,7 @@ func (h *ProjectHandler) runProjectActivityActionResponseInternal(
}, nil
}
-func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, environmentID, projectID string, cfg projectActivityActionConfigInternal) (base.MessageResponse, error) {
+func (h *ProjectHandler) runProjectActivityAction(ctx context.Context, environmentID, projectID string, cfg projectActivityActionConfig) (base.MessageResponse, error) {
if projectID == "" {
return base.MessageResponse{}, huma.Error400BadRequest("Project ID is required")
}
@@ -856,7 +849,7 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, e
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- projectName := h.projectActivityNameInternal(runtimeCtx, projectID)
+ projectName := h.projectActivityName(runtimeCtx, projectID)
var activityID string
if cfg.Queue {
activityID, runtimeCtx = activitylib.StartHandlerActivity(
@@ -959,7 +952,7 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
}
//nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
+ return h.streamProjectOperation(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfig{
ActivityType: activitytypes.TypeProjectPull,
Step: "Pulling project images",
StartMessage: "Project image pull started",
@@ -992,7 +985,7 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro
}
//nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
+ return h.streamProjectOperation(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfig{
ActivityType: activitytypes.TypeProjectBuild,
Step: "Building project images",
StartMessage: "Project image build started",
@@ -1023,7 +1016,7 @@ type UpdateProjectWorkspaceInput struct {
RawBody multipart.Form `contentType:"multipart/form-data"`
}
-func projectWorkspaceHTTPErrorInternal(err error) error {
+func projectWorkspaceHTTPError(err error) error {
switch {
case errors.Is(err, common.ErrProjectWorkspaceConflict):
return huma.Error409Conflict(err.Error())
@@ -1043,7 +1036,7 @@ func projectWorkspaceHTTPErrorInternal(err error) error {
func (h *ProjectHandler) GetProjectWorkspace(ctx context.Context, input *GetProjectWorkspaceInput) (*handlerutil.Out[workspacetypes.Workspace], error) {
result, err := h.projectService.GetProjectWorkspace(ctx, input.ProjectID)
if err != nil {
- return nil, projectWorkspaceHTTPErrorInternal(err)
+ return nil, projectWorkspaceHTTPError(err)
}
return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
}
@@ -1051,7 +1044,7 @@ func (h *ProjectHandler) GetProjectWorkspace(ctx context.Context, input *GetProj
func (h *ProjectHandler) GetProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*handlerutil.Out[workspacetypes.FileContent], error) {
result, err := h.projectService.GetProjectWorkspaceFile(ctx, input.ProjectID, input.RelativePath)
if err != nil {
- return nil, projectWorkspaceHTTPErrorInternal(err)
+ return nil, projectWorkspaceHTTPError(err)
}
return &handlerutil.Out[workspacetypes.FileContent]{Body: base.ApiResponse[workspacetypes.FileContent]{Success: true, Data: *result}}, nil
}
@@ -1059,7 +1052,7 @@ func (h *ProjectHandler) GetProjectWorkspaceFile(ctx context.Context, input *Get
func (h *ProjectHandler) DownloadProjectWorkspaceFile(ctx context.Context, input *GetProjectWorkspaceFileInput) (*huma.StreamResponse, error) {
reader, size, name, err := h.projectService.DownloadProjectWorkspaceFile(ctx, input.ProjectID, input.RelativePath)
if err != nil {
- return nil, projectWorkspaceHTTPErrorInternal(err)
+ return nil, projectWorkspaceHTTPError(err)
}
return handlerutil.DownloadResponse(reader, size, name), nil
}
@@ -1084,7 +1077,7 @@ func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *Upda
var result *workspacetypes.Workspace
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
- EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: h.projectActivityNameInternal(
+ EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: h.projectActivityName(
runtimeCtx,
input.ProjectID,
), User: user,
@@ -1096,7 +1089,7 @@ func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *Upda
return updateErr
})
if err != nil {
- return nil, projectWorkspaceHTTPErrorInternal(err)
+ return nil, projectWorkspaceHTTPError(err)
}
result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()
return &handlerutil.Out[workspacetypes.Workspace]{Body: base.ApiResponse[workspacetypes.Workspace]{Success: true, Data: *result}}, nil
diff --git a/backend/internal/s3/handler.go b/backend/internal/s3/handler.go
index 25be76263..5519b880e 100644
--- a/backend/internal/s3/handler.go
+++ b/backend/internal/s3/handler.go
@@ -13,18 +13,18 @@ import (
)
const (
- s3DestinationPathInternal = "/backups/s3"
- s3DestinationTagInternal = "S3 Destinations"
- s3ConnectionTestSuccessInternal = "S3 connection test succeeded"
- s3RemoteSyncFailureMessageInternal = "Failed to fan out S3 destination sync to remote environments"
+ s3DestinationPath = "/backups/s3"
+ s3DestinationTag = "S3 Destinations"
+ s3ConnectionTestSuccess = "S3 connection test succeeded"
+ s3RemoteSyncFailureMessage = "Failed to fan out S3 destination sync to remote environments"
)
-type s3DestinationHandlerInternal struct {
+type s3DestinationHandler struct {
service *S3DestinationService
syncRemoteDestinations func(context.Context) error
}
-type listS3DestinationsInputInternal struct {
+type listS3DestinationsInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
Order string `query:"order" default:"asc" doc:"Sort direction"`
@@ -32,57 +32,53 @@ type listS3DestinationsInputInternal struct {
Limit int `query:"limit" default:"20" doc:"Limit"`
}
-type listAllS3DestinationsOutputInternal struct {
+type listAllS3DestinationsOutput struct {
Body []backup.S3Destination
}
-type s3DestinationIDInputInternal struct {
+type s3DestinationIDInput struct {
ID string `path:"id" doc:"S3 destination ID"`
}
-type createS3DestinationInputInternal struct {
+type createS3DestinationInput struct {
Body backup.CreateS3Destination
}
-type updateS3DestinationInputInternal struct {
+type updateS3DestinationInput struct {
ID string `path:"id" doc:"S3 destination ID"`
Body backup.UpdateS3Destination
}
-type s3DestinationOutputInternal struct {
+type s3DestinationOutput struct {
Body backup.S3Destination
}
-type testS3DestinationInputInternal struct {
+type testS3DestinationInput struct {
ID string `path:"id" doc:"S3 destination ID"`
Body *backup.UpdateS3Destination `json:"body,omitempty"`
}
-type testS3DestinationConfigurationInputInternal struct {
+type testS3DestinationConfigurationInput struct {
Body backup.CreateS3Destination
}
-type syncS3DestinationsInputInternal struct {
+type syncS3DestinationsInput struct {
Body backup.S3DestinationSyncRequest
}
-type s3DestinationUsageOutputInternal struct {
- Body struct {
- InUse bool `json:"inUse"`
- }
+type s3DestinationUsageOutput struct {
+ Body backup.S3DestinationUsage
}
-func (h *s3DestinationHandlerInternal) inUseInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*s3DestinationUsageOutputInternal, error) {
+func (h *s3DestinationHandler) inUse(ctx context.Context, input *s3DestinationIDInput) (*s3DestinationUsageOutput, error) {
inUse, err := h.service.DestinationInUse(ctx, input.ID)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- output := &s3DestinationUsageOutputInternal{}
- output.Body.InUse = inUse
- return output, nil
+ return &s3DestinationUsageOutput{Body: backup.S3DestinationUsage{InUse: inUse}}, nil
}
-func (h *s3DestinationHandlerInternal) listInternal(ctx context.Context, input *listS3DestinationsInputInternal) (*handlerutil.Page[backup.S3Destination], error) {
+func (h *s3DestinationHandler) list(ctx context.Context, input *listS3DestinationsInput) (*handlerutil.Page[backup.S3Destination], error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
destinations, paginationResponse, err := h.service.ListS3Destinations(ctx, params)
if err != nil {
@@ -97,15 +93,15 @@ func (h *s3DestinationHandlerInternal) listInternal(ctx context.Context, input *
}, nil
}
-func (h *s3DestinationHandlerInternal) listAllInternal(ctx context.Context, _ *struct{}) (*listAllS3DestinationsOutputInternal, error) {
+func (h *s3DestinationHandler) listAll(ctx context.Context, _ *struct{}) (*listAllS3DestinationsOutput, error) {
destinations, err := h.service.ListAllS3Destinations(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- return &listAllS3DestinationsOutputInternal{Body: destinations}, nil
+ return &listAllS3DestinationsOutput{Body: destinations}, nil
}
-func (h *s3DestinationHandlerInternal) getInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*handlerutil.Out[backup.S3Destination], error) {
+func (h *s3DestinationHandler) get(ctx context.Context, input *s3DestinationIDInput) (*handlerutil.Out[backup.S3Destination], error) {
destination, err := h.service.GetS3Destination(ctx, input.ID)
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
@@ -116,7 +112,7 @@ func (h *s3DestinationHandlerInternal) getInternal(ctx context.Context, input *s
return &handlerutil.Out[backup.S3Destination]{Body: base.ApiResponse[backup.S3Destination]{Success: true, Data: *destination}}, nil
}
-func (h *s3DestinationHandlerInternal) createInternal(ctx context.Context, input *createS3DestinationInputInternal) (*s3DestinationOutputInternal, error) {
+func (h *s3DestinationHandler) create(ctx context.Context, input *createS3DestinationInput) (*s3DestinationOutput, error) {
if err := h.service.TestS3DestinationConfiguration(ctx, input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
@@ -124,11 +120,11 @@ func (h *s3DestinationHandlerInternal) createInternal(ctx context.Context, input
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- h.triggerRemoteSyncInternal(ctx, "S3 destination creation")
- return &s3DestinationOutputInternal{Body: *destination}, nil
+ h.triggerRemoteSync(ctx, "S3 destination creation")
+ return &s3DestinationOutput{Body: *destination}, nil
}
-func (h *s3DestinationHandlerInternal) updateInternal(ctx context.Context, input *updateS3DestinationInputInternal) (*s3DestinationOutputInternal, error) {
+func (h *s3DestinationHandler) update(ctx context.Context, input *updateS3DestinationInput) (*s3DestinationOutput, error) {
if err := h.service.TestS3Destination(ctx, input.ID, &input.Body); err != nil {
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
@@ -142,11 +138,11 @@ func (h *s3DestinationHandlerInternal) updateInternal(ctx context.Context, input
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- h.triggerRemoteSyncInternal(ctx, "S3 destination update")
- return &s3DestinationOutputInternal{Body: *destination}, nil
+ h.triggerRemoteSync(ctx, "S3 destination update")
+ return &s3DestinationOutput{Body: *destination}, nil
}
-func (h *s3DestinationHandlerInternal) deleteInternal(ctx context.Context, input *s3DestinationIDInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
+func (h *s3DestinationHandler) delete(ctx context.Context, input *s3DestinationIDInput) (*handlerutil.Out[base.MessageResponse], error) {
err := h.service.DeleteS3Destination(ctx, input.ID)
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
@@ -157,40 +153,40 @@ func (h *s3DestinationHandlerInternal) deleteInternal(ctx context.Context, input
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
- h.triggerRemoteSyncInternal(ctx, "S3 destination deletion")
+ h.triggerRemoteSync(ctx, "S3 destination deletion")
return handlerutil.MessageOutput("S3 destination deleted successfully", ""), nil
}
-func (h *s3DestinationHandlerInternal) testInternal(ctx context.Context, input *testS3DestinationInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
+func (h *s3DestinationHandler) test(ctx context.Context, input *testS3DestinationInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.TestS3Destination(ctx, input.ID, input.Body); err != nil {
if errors.Is(err, ErrS3DestinationNotFound) {
return nil, huma.Error404NotFound(err.Error())
}
return nil, huma.Error400BadRequest(err.Error())
}
- return handlerutil.MessageOutput(s3ConnectionTestSuccessInternal, ""), nil
+ return handlerutil.MessageOutput(s3ConnectionTestSuccess, ""), nil
}
-func (h *s3DestinationHandlerInternal) triggerRemoteSyncInternal(ctx context.Context, reason string) {
+func (h *s3DestinationHandler) triggerRemoteSync(ctx context.Context, reason string) {
if h.syncRemoteDestinations == nil {
return
}
detachedCtx := context.WithoutCancel(ctx)
go func(syncCtx context.Context, syncReason string) {
if err := h.syncRemoteDestinations(syncCtx); err != nil {
- slog.WarnContext(syncCtx, s3RemoteSyncFailureMessageInternal, "reason", syncReason, "error", err.Error())
+ slog.WarnContext(syncCtx, s3RemoteSyncFailureMessage, "reason", syncReason, "error", err.Error())
}
}(detachedCtx, reason)
}
-func (h *s3DestinationHandlerInternal) testConfigurationInternal(ctx context.Context, input *testS3DestinationConfigurationInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
+func (h *s3DestinationHandler) testConfiguration(ctx context.Context, input *testS3DestinationConfigurationInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.TestS3DestinationConfiguration(ctx, input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
- return handlerutil.MessageOutput(s3ConnectionTestSuccessInternal, ""), nil
+ return handlerutil.MessageOutput(s3ConnectionTestSuccess, ""), nil
}
-func (h *s3DestinationHandlerInternal) syncInternal(ctx context.Context, input *syncS3DestinationsInputInternal) (*handlerutil.Out[base.MessageResponse], error) {
+func (h *s3DestinationHandler) sync(ctx context.Context, input *syncS3DestinationsInput) (*handlerutil.Out[base.MessageResponse], error) {
if err := h.service.SyncS3Destinations(ctx, input.Body.Destinations); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
diff --git a/backend/internal/s3/module.go b/backend/internal/s3/module.go
index 9e86dfde9..827344e55 100644
--- a/backend/internal/s3/module.go
+++ b/backend/internal/s3/module.go
@@ -36,78 +36,78 @@ func (m *Module) RegisterRoutes(api huma.API) {
}
func RegisterS3Destinations(api huma.API, service *S3DestinationService, syncRemoteDestinations func(context.Context) error) {
- handler := &s3DestinationHandlerInternal{service: service, syncRemoteDestinations: syncRemoteDestinations}
+ handler := &s3DestinationHandler{service: service, syncRemoteDestinations: syncRemoteDestinations}
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"list-s3-destinations",
http.MethodGet,
- s3DestinationPathInternal,
+ s3DestinationPath,
"List S3 destinations",
"List saved S3-compatible backup destinations with search, sorting, and pagination",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsList, handler.listInternal)
+ authz.PermS3DestinationsList, handler.list)
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"list-all-s3-destinations",
http.MethodGet,
- s3DestinationPathInternal+"/options",
+ s3DestinationPath+"/options",
"List all S3 destination options",
"List saved S3-compatible destinations for backup configuration selectors",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsList, handler.listAllInternal)
+ authz.PermS3DestinationsList, handler.listAll)
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"sync-s3-destinations",
http.MethodPost,
- s3DestinationPathInternal+"/sync",
+ s3DestinationPath+"/sync",
"Sync S3 destinations",
"Synchronize manager-owned S3 destinations to an agent",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsSync, handler.syncInternal)
+ authz.PermS3DestinationsSync, handler.sync)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("get-s3-destination", http.MethodGet, s3DestinationPathInternal+"/{id}", "Get S3 destination", "", s3DestinationTagInternal),
- authz.PermS3DestinationsRead, handler.getInternal)
+ handlerutil.Operation("get-s3-destination", http.MethodGet, s3DestinationPath+"/{id}", "Get S3 destination", "", s3DestinationTag),
+ authz.PermS3DestinationsRead, handler.get)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("create-s3-destination", http.MethodPost, s3DestinationPathInternal, "Create S3 destination", "", s3DestinationTagInternal),
- authz.PermS3DestinationsCreate, handler.createInternal)
+ handlerutil.Operation("create-s3-destination", http.MethodPost, s3DestinationPath, "Create S3 destination", "", s3DestinationTag),
+ authz.PermS3DestinationsCreate, handler.create)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("update-s3-destination", http.MethodPut, s3DestinationPathInternal+"/{id}", "Update S3 destination", "", s3DestinationTagInternal),
- authz.PermS3DestinationsUpdate, handler.updateInternal)
+ handlerutil.Operation("update-s3-destination", http.MethodPut, s3DestinationPath+"/{id}", "Update S3 destination", "", s3DestinationTag),
+ authz.PermS3DestinationsUpdate, handler.update)
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"test-s3-destination-configuration",
http.MethodPost,
- s3DestinationPathInternal+"/test",
+ s3DestinationPath+"/test",
"Test unsaved S3 destination configuration",
"Verify upload, download, and delete access before saving an S3 destination",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsTest, handler.testConfigurationInternal)
+ authz.PermS3DestinationsTest, handler.testConfiguration)
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"test-s3-destination",
http.MethodPost,
- s3DestinationPathInternal+"/{id}/test",
+ s3DestinationPath+"/{id}/test",
"Test S3 destination",
"Verify upload, download, and delete access using the saved or supplied S3 destination configuration",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsTest, handler.testInternal)
+ authz.PermS3DestinationsTest, handler.test)
handlerutil.RegisterSecured(api,
handlerutil.Operation(
"get-s3-destination-usage",
http.MethodGet,
- s3DestinationPathInternal+"/{id}/in-use",
+ s3DestinationPath+"/{id}/in-use",
"Check S3 destination references",
"Report whether backup records, policies, or settings on this environment still reference the destination",
- s3DestinationTagInternal,
+ s3DestinationTag,
),
- authz.PermS3DestinationsRead, handler.inUseInternal)
+ authz.PermS3DestinationsRead, handler.inUse)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("delete-s3-destination", http.MethodDelete, s3DestinationPathInternal+"/{id}", "Delete S3 destination", "", s3DestinationTagInternal),
- authz.PermS3DestinationsDelete, handler.deleteInternal)
+ handlerutil.Operation("delete-s3-destination", http.MethodDelete, s3DestinationPath+"/{id}", "Delete S3 destination", "", s3DestinationTag),
+ authz.PermS3DestinationsDelete, handler.delete)
}
diff --git a/backend/internal/system/children/upgrade/handler.go b/backend/internal/system/children/upgrade/handler.go
index 12cf3f0ed..b1eaeb365 100644
--- a/backend/internal/system/children/upgrade/handler.go
+++ b/backend/internal/system/children/upgrade/handler.go
@@ -7,6 +7,7 @@ import (
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/system"
kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
@@ -30,15 +31,8 @@ type CheckUpgradeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-// UpgradeCheckResultData is the response for upgrade check.
-type UpgradeCheckResultData struct {
- CanUpgrade bool `json:"canUpgrade"`
- Error bool `json:"error"`
- Message string `json:"message"`
-}
-
type CheckUpgradeOutput struct {
- Body UpgradeCheckResultData
+ Body system.UpgradeCheckResult
}
type TriggerUpgradeInput struct {
@@ -71,7 +65,7 @@ func (h *Handler) CheckUpgradeAvailable(ctx context.Context, input *CheckUpgrade
if err != nil {
slog.DebugContext(ctx, "System upgrade check failed", "error", err)
return &CheckUpgradeOutput{
- Body: UpgradeCheckResultData{
+ Body: system.UpgradeCheckResult{
CanUpgrade: false,
Error: true,
Message: "Failed to check for updates: " + err.Error(),
@@ -80,7 +74,7 @@ func (h *Handler) CheckUpgradeAvailable(ctx context.Context, input *CheckUpgrade
}
return &CheckUpgradeOutput{
- Body: UpgradeCheckResultData{
+ Body: system.UpgradeCheckResult{
CanUpgrade: canUpgrade,
Error: false,
Message: "System can be upgraded",
@@ -129,7 +123,7 @@ func (h *Handler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput
}
// TriggerUpdateAll starts a fleet-wide update: every remote agent in turn, then the manager last.
-func (h *Handler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*handlerutil.Out[EnvironmentUpdateJob], error) {
+func (h *Handler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*handlerutil.Out[system.EnvironmentUpdateJob], error) {
if h.cfg != nil && h.cfg.AgentMode {
return nil, huma.Error400BadRequest("update-all is managed on the Arcane manager")
}
@@ -149,16 +143,17 @@ func (h *Handler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllI
return nil, huma.Error500InternalServerError("Failed to initiate upgrade: " + err.Error())
}
- return &handlerutil.Out[EnvironmentUpdateJob]{
- Body: base.ApiResponse[EnvironmentUpdateJob]{
- Success: true,
- Data: *job,
- },
- }, nil
+ body, err := handlerutil.MapOneAPIResponse[*EnvironmentUpdateJob, system.EnvironmentUpdateJob](job, func(mapErr error) string {
+ return "Failed to initiate upgrade: " + mapErr.Error()
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &handlerutil.Out[system.EnvironmentUpdateJob]{Body: body}, nil
}
// GetUpdateAllStatus returns the latest update-all job for live progress polling.
-func (h *Handler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*handlerutil.Out[EnvironmentUpdateJob], error) {
+func (h *Handler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*handlerutil.Out[system.EnvironmentUpdateJob], error) {
if h.cfg != nil && h.cfg.AgentMode {
return nil, huma.Error400BadRequest("update-all is managed on the Arcane manager")
}
@@ -171,10 +166,11 @@ func (h *Handler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatus
return nil, huma.Error404NotFound("no update-all job found")
}
- return &handlerutil.Out[EnvironmentUpdateJob]{
- Body: base.ApiResponse[EnvironmentUpdateJob]{
- Success: true,
- Data: *job,
- },
- }, nil
+ body, err := handlerutil.MapOneAPIResponse[*EnvironmentUpdateJob, system.EnvironmentUpdateJob](job, func(mapErr error) string {
+ return mapErr.Error()
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &handlerutil.Out[system.EnvironmentUpdateJob]{Body: body}, nil
}
diff --git a/backend/internal/updater/handler.go b/backend/internal/updater/handler.go
index 2c4e50883..a781a1571 100644
--- a/backend/internal/updater/handler.go
+++ b/backend/internal/updater/handler.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/project"
"github.com/getarcaneapp/arcane/types/v2/updater"
+ "go.getarcane.app/kit/pkg/mapping"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
@@ -83,7 +84,7 @@ func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdater
}
// GetUpdaterHistory returns the history of update operations.
-func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*handlerutil.Out[[]AutoUpdateRecord], error) {
+func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*handlerutil.Out[[]updater.AutoUpdateRecord], error) {
limit := input.Limit
if limit <= 0 {
limit = 50
@@ -94,10 +95,15 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
return nil, huma.Error500InternalServerError("Failed to get updater history: " + err.Error())
}
- return &handlerutil.Out[[]AutoUpdateRecord]{
- Body: base.ApiResponse[[]AutoUpdateRecord]{
+ records, err := mapping.MapSlice[AutoUpdateRecord, updater.AutoUpdateRecord](history)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("Failed to get updater history: " + err.Error())
+ }
+
+ return &handlerutil.Out[[]updater.AutoUpdateRecord]{
+ Body: base.ApiResponse[[]updater.AutoUpdateRecord]{
Success: true,
- Data: history,
+ Data: records,
},
}, nil
}
diff --git a/backend/internal/volume/children/backup/handler.go b/backend/internal/volume/children/backup/handler.go
index 3f9bbd1b6..5335f0bae 100644
--- a/backend/internal/volume/children/backup/handler.go
+++ b/backend/internal/volume/children/backup/handler.go
@@ -45,15 +45,8 @@ type ListBackupsInput struct {
Type string `query:"type" doc:"Management origin filter"`
}
-type VolumeBackupPaginatedResponse struct {
- Success bool `json:"success"`
- Data []volume.Backup `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
- Warnings []string `json:"warnings,omitempty"`
-}
-
type ListBackupsOutput struct {
- Body VolumeBackupPaginatedResponse
+ Body base.PaginatedWithWarnings[volume.Backup]
}
type CreateBackupInput struct {
@@ -140,7 +133,7 @@ func (h *Handler) ListBackups(ctx context.Context, input *ListBackupsInput) (*Li
warning := h.service.backupMountWarning(ctx)
return &ListBackupsOutput{
- Body: VolumeBackupPaginatedResponse{
+ Body: base.PaginatedWithWarnings[volume.Backup]{
Success: true,
Data: backups,
Pagination: handlerutil.PaginationResponse(paginationResp),
diff --git a/backend/internal/vulnerability/children/scan/children/trivy/handler.go b/backend/internal/vulnerability/children/scan/children/trivy/handler.go
index e92f27c86..595754c41 100644
--- a/backend/internal/vulnerability/children/scan/children/trivy/handler.go
+++ b/backend/internal/vulnerability/children/scan/children/trivy/handler.go
@@ -4,6 +4,7 @@ import (
"context"
"github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/vulnerability"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)
@@ -21,23 +22,15 @@ type GetScannerStatusInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ScannerStatus struct {
- // Available indicates if the vulnerability scanner (Trivy) is available
- Available bool `json:"available"`
-
- // Version is the version of the scanner if available
- Version string `json:"version,omitempty"`
-}
-
// GetScannerStatus checks if the vulnerability scanner is available.
-func (h *Handler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*handlerutil.Out[ScannerStatus], error) {
+func (h *Handler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*handlerutil.Out[vulnerability.ScannerStatus], error) {
version := h.service.Version(ctx)
available := version != ""
- return &handlerutil.Out[ScannerStatus]{
- Body: base.ApiResponse[ScannerStatus]{
+ return &handlerutil.Out[vulnerability.ScannerStatus]{
+ Body: base.ApiResponse[vulnerability.ScannerStatus]{
Success: true,
- Data: ScannerStatus{
+ Data: vulnerability.ScannerStatus{
Available: available,
Version: version,
},
diff --git a/cli/go.mod b/cli/go.mod
index aa0a2ae2b..4e99e5649 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -13,6 +13,7 @@ require (
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/x/ansi v0.11.9
github.com/charmbracelet/x/term v0.2.2
+ github.com/creack/pty v1.1.24
github.com/docker/go-units v0.5.0
github.com/getarcaneapp/arcane/types/v2 v2.14.0
github.com/mattn/go-runewidth v0.0.31
@@ -22,11 +23,14 @@ require (
github.com/spf13/pflag v1.0.10
github.com/stretchr/testify v1.12.1
go.getarcane.app/acfs v0.6.2
+ go.getarcane.app/builds v0.4.4
+ go.getarcane.app/docker v0.1.0
go.getarcane.app/kit v0.4.0
go.yaml.in/yaml/v4 v4.0.0-rc.6
)
require (
+ github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect
github.com/DmitriyVTitov/size v1.5.0 // indirect
github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
@@ -56,6 +60,7 @@ require (
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/moby/api v1.56.1 // indirect
github.com/moby/moby/client v0.6.2 // indirect
+ github.com/moby/term v0.5.2 // indirect
github.com/muesli/mango v0.2.0 // indirect
github.com/muesli/mango-cobra v1.3.0 // indirect
github.com/muesli/mango-pflag v0.2.0 // indirect
@@ -70,10 +75,10 @@ require (
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sahilm/fuzzy v0.1.3 // indirect
github.com/samber/go-singleflightx v0.3.2 // indirect
+ github.com/samber/mo v1.17.0 // indirect
github.com/sirupsen/logrus v1.10.2 // indirect
github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
github.com/xo/terminfo v1.0.0 // indirect
- go.getarcane.app/builds v0.4.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect
go.opentelemetry.io/otel v1.46.0 // indirect
diff --git a/cli/go.sum b/cli/go.sum
index 8355f1d1b..e7f146250 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -8,6 +8,8 @@ charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
charm.land/log/v2 v2.0.1 h1:uMk+t1hM/fomIqt7vn/Ub0AKo7IHvnDu6NK17nbOVx0=
charm.land/log/v2 v2.0.1/go.mod h1:VXZNB8zoPPEIcvd7bRi2fpQpGCWweCSfWOwczA9dibs=
+github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 h1:m2xcjRABtG288vnlV3U/PKh/HnPURxZp50RKNUwBxM8=
+github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4/go.mod h1:MTUE7ZuZO89FAtAwozGg6AWD83pcdefnEq5gF82MB8s=
github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g=
github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=
github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 h1:0kQAzHq8vLs7Pptv+7TxjdETLf/nIqJpIB4oC6Ba4vY=
@@ -49,6 +51,8 @@ github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc=
@@ -89,6 +93,8 @@ github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c=
github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4=
github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc=
+github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
+github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/mango v0.2.0 h1:iNNc0c5VLQ6fsMgAqGQofByNUBH2Q2nEbD6TaI+5yyQ=
@@ -122,6 +128,8 @@ github.com/samber/go-singleflightx v0.3.2 h1:jXbUU0fvis8Fdv4HGONboX5WdEZcYLoBEcK
github.com/samber/go-singleflightx v0.3.2/go.mod h1:X2BR+oheHIYc73PvxRMlcASg6KYYTQyUYpdVU7t/ux4=
github.com/samber/hot v0.13.1 h1:cTIS9spjhKs3k6QfL1N2m7qdAud8Aiw8oXsjxR58dxo=
github.com/samber/hot v0.13.1/go.mod h1:NB9v5U4NfDx7jmlrP+zHuqCuLUsywgAtCH7XOAkOxAg=
+github.com/samber/mo v1.17.0 h1:EbeLc7nxIdpalstxQQakLOcXxULuMRqo7PJPtY18bQg=
+github.com/samber/mo v1.17.0/go.mod h1:DlgzJ4SYhOh41nP1L9kh9rDNERuf8IqWSAs+gj2Vxag=
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
@@ -139,6 +147,8 @@ go.getarcane.app/acfs v0.6.2 h1:5cO8uWPz16lg+aP/iQe+k5IIDTToccCqoakwoDfUOOE=
go.getarcane.app/acfs v0.6.2/go.mod h1:Z+0Gs4LGNjvGMLq+TKv/oGKh29FRbAH6mcVPwY5KhFI=
go.getarcane.app/builds v0.4.4 h1:r9e97gmG2vic6kZB1UfTp9vSpqb1nPYA6CBlbaCvH64=
go.getarcane.app/builds v0.4.4/go.mod h1:8B6z4dKZqE36Y+Rpudx7AIL3BXeIoqsMgrJQepRKeds=
+go.getarcane.app/docker v0.1.0 h1:iUhl7amZsdAE4p2efVRd0i1tw1Vl9i1VgFqdBAf90S8=
+go.getarcane.app/docker v0.1.0/go.mod h1:uGxT363iZM6n2WLXCz2T0ejCP/8xInuJNzXnySLe+pc=
go.getarcane.app/kit v0.4.0 h1:3PqyAmBfp07ZOK1ztCwS6vuOzQKFtXeMbk+P0oxhIK4=
go.getarcane.app/kit v0.4.0/go.mod h1:KTjbXTEeC3i9e1QxZowDJWjFyABlD6UF3ISVtoIZs10=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.go
index 81562a40c..8a0ce3f93 100644
--- a/cli/internal/ci/ci_detect.go
+++ b/cli/internal/ci/ci_detect.go
@@ -1,6 +1,7 @@
package ci
import (
+ "cmp"
"context"
"encoding/json/v2"
"errors"
@@ -10,8 +11,6 @@ import (
"net/url"
"strings"
"time"
-
- kit "go.getarcane.app/kit/pkg"
)
const (
@@ -23,7 +22,7 @@ const (
// DetectToken resolves a CI-issued OIDC token from the requested provider.
func DetectToken(ctx context.Context, provider, audience string, getenv func(string) string, httpClient *http.Client) (string, string, error) {
- provider = normalizeFederatedProviderInternal(provider)
+ provider = cmp.Or(strings.ToLower(strings.TrimSpace(provider)), ProviderAuto)
if getenv == nil {
getenv = func(string) string { return "" }
}
@@ -33,7 +32,7 @@ func DetectToken(ctx context.Context, provider, audience string, getenv func(str
switch provider {
case ProviderAuto:
- if token, err := mintGitHubActionsTokenInternal(ctx, audience, getenv, httpClient); err == nil {
+ if token, err := mintGitHubActionsToken(ctx, audience, getenv, httpClient); err == nil {
return token, ProviderGitHub, nil
}
if token := strings.TrimSpace(getenv("CI_JOB_JWT_V2")); token != "" {
@@ -41,7 +40,7 @@ func DetectToken(ctx context.Context, provider, audience string, getenv func(str
}
return "", "", errors.New("no supported CI OIDC token source detected")
case ProviderGitHub:
- token, err := mintGitHubActionsTokenInternal(ctx, audience, getenv, httpClient)
+ token, err := mintGitHubActionsToken(ctx, audience, getenv, httpClient)
if err != nil {
return "", "", err
}
@@ -59,7 +58,7 @@ func DetectToken(ctx context.Context, provider, audience string, getenv func(str
}
}
-func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenv func(string) string, httpClient *http.Client) (string, error) {
+func mintGitHubActionsToken(ctx context.Context, audience string, getenv func(string) string, httpClient *http.Client) (string, error) {
requestURL := strings.TrimSpace(getenv("ACTIONS_ID_TOKEN_REQUEST_URL"))
requestToken := strings.TrimSpace(getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN"))
if requestURL == "" || requestToken == "" {
@@ -109,8 +108,3 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenv
}
return token, nil
}
-
-func normalizeFederatedProviderInternal(provider string) string {
- provider = strings.ToLower(strings.TrimSpace(provider))
- return kit.Ternary(provider == "", ProviderAuto, provider)
-}
diff --git a/cli/internal/ci/ci_detect_test.go b/cli/internal/ci/ci_detect_test.go
index 93e2c37c0..f6176d52c 100644
--- a/cli/internal/ci/ci_detect_test.go
+++ b/cli/internal/ci/ci_detect_test.go
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/require"
)
-func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
+func TestDetectFederatedTokenFromGitHubActions(t *testing.T) {
t.Parallel()
var gotAudience string
@@ -26,7 +26,7 @@ func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
"ACTIONS_ID_TOKEN_REQUEST_URL": server.URL + "?api-version=2",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-token",
}
- token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMapInternal(env), server.Client())
+ token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMap(env), server.Client())
require.NoError(t, err)
require.Equal(t, "github.jwt", token)
@@ -35,10 +35,10 @@ func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
require.Equal(t, "Bearer request-token", gotAuth)
}
-func TestDetectFederatedTokenFromGitLabLegacyInternal(t *testing.T) {
+func TestDetectFederatedTokenFromGitLabLegacy(t *testing.T) {
t.Parallel()
- token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMapInternal(map[string]string{
+ token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMap(map[string]string{
"CI_JOB_JWT_V2": "gitlab.jwt",
}), http.DefaultClient)
@@ -47,17 +47,17 @@ func TestDetectFederatedTokenFromGitLabLegacyInternal(t *testing.T) {
require.Equal(t, "gitlab", provider)
}
-func TestDetectFederatedTokenProviderMismatchInternal(t *testing.T) {
+func TestDetectFederatedTokenProviderMismatch(t *testing.T) {
t.Parallel()
- _, _, err := DetectToken(t.Context(), "github", "aud", envGetterFromMapInternal(map[string]string{
+ _, _, err := DetectToken(t.Context(), "github", "aud", envGetterFromMap(map[string]string{
"CI_JOB_JWT_V2": "gitlab.jwt",
}), http.DefaultClient)
require.Error(t, err)
}
-func envGetterFromMapInternal(values map[string]string) func(string) string {
+func envGetterFromMap(values map[string]string) func(string) string {
return func(key string) string {
return values[key]
}
diff --git a/cli/internal/client/client.go b/cli/internal/client/client.go
index ce246000f..92026f272 100644
--- a/cli/internal/client/client.go
+++ b/cli/internal/client/client.go
@@ -68,29 +68,14 @@ func New(cfg *types.Config) (*Client, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
- parsedURL, err := url.Parse(cfg.ServerURL)
+ c, err := NewUnauthenticated(cfg)
if err != nil {
- return nil, fmt.Errorf("invalid server_url: %w", err)
- }
-
- envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)
- httpClient := &http.Client{Timeout: defaultTimeout}
- if transport, ok := http.DefaultTransport.(*http.Transport); ok {
- httpClient.Transport = transport.Clone()
+ return nil, err
}
-
- return &Client{
- baseURL: cfg.ServerURL,
- baseURLParsed: parsedURL,
- apiKey: cfg.APIKey,
- jwtToken: cfg.JWTToken,
- refreshToken: cfg.RefreshToken,
- envID: envID,
- httpClient: httpClient,
- maxAttempts: 3,
- baseBackoff: 150 * time.Millisecond,
- maxBackoff: 2 * time.Second,
- }, nil
+ c.apiKey = cfg.APIKey
+ c.jwtToken = cfg.JWTToken
+ c.refreshToken = cfg.RefreshToken
+ return c, nil
}
// NewUnauthenticated creates a client that can call unauthenticated endpoints
@@ -108,7 +93,6 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {
return nil, fmt.Errorf("invalid server_url: %w", err)
}
- envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)
httpClient := &http.Client{Timeout: defaultTimeout}
if transport, ok := http.DefaultTransport.(*http.Transport); ok {
httpClient.Transport = transport.Clone()
@@ -117,7 +101,7 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {
return &Client{
baseURL: cfg.ServerURL,
baseURLParsed: parsedURL,
- envID: envID,
+ envID: cmp.Or(cfg.DefaultEnvironment, defaultEnvID),
refreshToken: cfg.RefreshToken,
httpClient: httpClient,
maxAttempts: 3,
@@ -178,10 +162,7 @@ func (c *Client) SetTimeout(timeout time.Duration) {
// SetRetryPolicy configures retry behavior for idempotent requests.
func (c *Client) SetRetryPolicy(maxAttempts int, baseBackoff, maxBackoff time.Duration) {
- if maxAttempts < 1 {
- maxAttempts = 1
- }
- c.maxAttempts = maxAttempts
+ c.maxAttempts = max(maxAttempts, 1)
c.baseBackoff = baseBackoff
c.maxBackoff = maxBackoff
}
@@ -192,13 +173,6 @@ func (c *Client) EnvID() string {
return c.envID
}
-// APIResponse wraps the Arcane success, data, and error response fields.
-type APIResponse[T any] struct {
- Success bool `json:"success"`
- Data T `json:"data"`
- Error string `json:"error,omitempty"`
-}
-
// Request sends JSON or raw reader bodies with authentication; streaming bodies skip retries and token refresh.
func (c *Client) Request(ctx context.Context, method, path string, body any, headers ...http.Header) (*http.Response, error) {
loading := output.StartLoading(ctx)
@@ -350,7 +324,8 @@ func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyByte
}
if attempt < attempts && c.shouldRetry(method, resp.StatusCode, nil) {
- logger.GetLogger().Debug("Retrying request after retryable status", "method", method, "url", fullURL, "env_id", c.envID, "attempt", attempt, "max_attempts", attempts, "status", resp.Status)
+ logger.GetLogger().Debug("Retrying request after retryable status",
+ "method", method, "url", fullURL, "env_id", c.envID, "attempt", attempt, "max_attempts", attempts, "status", resp.Status)
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxErrorBody))
_ = resp.Body.Close()
if backoffErr := c.waitRetry(ctx, attempt); backoffErr != nil {
@@ -395,8 +370,8 @@ func (c *Client) waitRetry(ctx context.Context, attempt int) error {
for i := 1; i < attempt; i++ {
delay *= 2
}
- if c.maxBackoff > 0 && delay > c.maxBackoff {
- delay = c.maxBackoff
+ if c.maxBackoff > 0 {
+ delay = min(delay, c.maxBackoff)
}
timer := time.NewTimer(delay)
defer timer.Stop()
@@ -468,10 +443,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
return errors.New("token refresh failed: unexpected response from server")
}
- newRefresh := result.Data.RefreshToken
- if newRefresh == "" {
- newRefresh = c.refreshToken
- }
+ newRefresh := cmp.Or(result.Data.RefreshToken, c.refreshToken)
c.jwtToken = result.Data.Token
c.refreshToken = newRefresh
@@ -542,12 +514,11 @@ func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body an
return out, nil
}
-// GetJSON performs a GET and decodes the standard API envelope, enforcing
-// HTTP and API success.
-func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {
+// DoEnvelope sends a request and decodes the shared envelope, enforcing HTTP and API success.
+func (c *Client) DoEnvelope[T any](ctx context.Context, method, path string, body any) (*base.ApiResponse[T], error) {
loading := output.StartLoading(ctx)
defer loading.Stop()
- resp, err := c.Get(ctx, path)
+ resp, err := c.Request(ctx, method, path, body)
if err != nil {
return nil, err
}
@@ -555,17 +526,16 @@ func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[
return decodeResponseStrict[T](resp)
}
+// GetJSON performs a GET and decodes the standard API envelope, enforcing
+// HTTP and API success.
+func (c *Client) GetJSON[T any](ctx context.Context, path string) (*base.ApiResponse[T], error) {
+ return c.DoEnvelope[T](ctx, http.MethodGet, path, nil)
+}
+
// PostJSON performs a POST with a JSON body and decodes the standard API
// envelope, enforcing HTTP and API success.
-func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {
- loading := output.StartLoading(ctx)
- defer loading.Stop()
- resp, err := c.Post(ctx, path, body)
- if err != nil {
- return nil, err
- }
- defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrict[T](resp)
+func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*base.ApiResponse[T], error) {
+ return c.DoEnvelope[T](ctx, http.MethodPost, path, body)
}
// DoRaw performs a request and returns the response payload when status is 2xx.
@@ -592,32 +562,18 @@ func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]by
// PutJSON performs a PUT with a JSON body and decodes the standard API
// envelope, enforcing HTTP and API success.
-func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {
- loading := output.StartLoading(ctx)
- defer loading.Stop()
- resp, err := c.Put(ctx, path, body)
- if err != nil {
- return nil, err
- }
- defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrict[T](resp)
+func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*base.ApiResponse[T], error) {
+ return c.DoEnvelope[T](ctx, http.MethodPut, path, body)
}
// DeleteJSON performs a DELETE and decodes the standard API envelope,
// enforcing HTTP and API success.
-func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {
- loading := output.StartLoading(ctx)
- defer loading.Stop()
- resp, err := c.Delete(ctx, path)
- if err != nil {
- return nil, err
- }
- defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrict[T](resp)
+func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*base.ApiResponse[T], error) {
+ return c.DoEnvelope[T](ctx, http.MethodDelete, path, nil)
}
// decodeResponseStrict enforces HTTP and API success while decoding the response. The caller owns the response body.
-func decodeResponseStrict[T any](resp *http.Response) (*APIResponse[T], error) {
+func decodeResponseStrict[T any](resp *http.Response) (*base.ApiResponse[T], error) {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
@@ -628,19 +584,22 @@ func decodeResponseStrict[T any](resp *http.Response) (*APIResponse[T], error) {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
- var result APIResponse[T]
+ var result struct {
+ base.ApiResponse[T]
+ base.ErrorResponse
+ }
if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
return nil, fmt.Errorf("failed to decode response (body: %s): %w", string(body), unmarshalErr)
}
if !result.Success {
if strings.TrimSpace(result.Error) != "" {
- return &result, fmt.Errorf("API error: %s", result.Error)
+ return &result.ApiResponse, fmt.Errorf("API error: %s", result.Error)
}
- return &result, errors.New("API error: request was not successful")
+ return &result.ApiResponse, errors.New("API error: request was not successful")
}
- return &result, nil
+ return &result.ApiResponse, nil
}
// TestConnection checks the API version endpoint and returns transport or status failures.
diff --git a/cli/internal/client/client_test.go b/cli/internal/client/client_test.go
index 4ec211666..7523194a6 100644
--- a/cli/internal/client/client_test.go
+++ b/cli/internal/client/client_test.go
@@ -2,8 +2,11 @@ package client
import (
"encoding/json"
+ "fmt"
+ "io"
"net/http"
"net/http/httptest"
+ "strings"
"sync/atomic"
"testing"
"time"
@@ -291,3 +294,63 @@ func TestClient_DoRaw_Success(t *testing.T) {
require.NotEmpty(t, b,
"expected response payload")
}
+
+func TestClientDoEnvelope(t *testing.T) {
+ type record struct {
+ Name string `json:"name"`
+ }
+ for _, tt := range []struct {
+ name, method, response, wantErr string
+ status int
+ body any
+ }{
+ {name: "GET", method: http.MethodGet, status: http.StatusOK, response: `{"success":true,"data":{"name":"arcane"}}`},
+ {
+ name: "POST body", method: http.MethodPost, body: map[string]string{"name": "arcane"}, status: http.StatusCreated,
+ response: `{"success":true,"data":{"name":"arcane"}}`,
+ },
+ {
+ name: "PUT body", method: http.MethodPut, body: map[string]string{"name": "arcane"}, status: http.StatusOK,
+ response: `{"success":true,"data":{"name":"arcane"}}`,
+ },
+ {
+ name: "DELETE body", method: http.MethodDelete, body: map[string]string{"name": "arcane"}, status: http.StatusOK,
+ response: `{"success":true,"data":{"name":"arcane"}}`,
+ },
+ {name: "HTTP failure", method: http.MethodGet, status: http.StatusForbidden, response: `{"error":"denied"}`, wantErr: "request failed with status 403"},
+ {name: "API failure", method: http.MethodGet, status: http.StatusOK, response: `{"success":false,"error":"denied"}`, wantErr: "API error: denied"},
+ {name: "failure without message", method: http.MethodGet, status: http.StatusOK, response: `{"success":false}`, wantErr: "API error: request was not successful"},
+ {name: "missing success", method: http.MethodGet, status: http.StatusOK, response: `{"data":{"name":"arcane"}}`, wantErr: "API error: request was not successful"},
+ {name: "invalid JSON", method: http.MethodGet, status: http.StatusOK, response: `invalid`, wantErr: "failed to decode response"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ requests := make(chan string, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requestBody, readErr := io.ReadAll(r.Body)
+ if readErr != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ requests <- r.Method + " " + r.URL.RequestURI() + " " + string(requestBody)
+ w.WriteHeader(tt.status)
+ _, _ = fmt.Fprint(w, tt.response)
+ }))
+ defer server.Close()
+ c, newErr := NewUnauthenticated(&types.Config{ServerURL: server.URL})
+ require.NoError(t, newErr)
+ result, requestErr := c.DoEnvelope[record](t.Context(), tt.method, "/api/record?full=true", tt.body)
+ if tt.wantErr != "" {
+ require.ErrorContains(t, requestErr, tt.wantErr)
+ } else {
+ require.NoError(t, requestErr)
+ require.True(t, result.Success)
+ require.Equal(t, record{Name: "arcane"}, result.Data)
+ }
+ request := <-requests
+ require.True(t, strings.HasPrefix(request, tt.method+" /api/record?full=true "))
+ if tt.body != nil {
+ require.Contains(t, request, `{"name":"arcane"}`)
+ }
+ })
+ }
+}
diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.go
index da65154b7..fad263fad 100644
--- a/cli/internal/cmdutil/context.go
+++ b/cli/internal/cmdutil/context.go
@@ -2,11 +2,13 @@ package cmdutil
import (
"errors"
+ "fmt"
"github.com/spf13/cobra"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
)
@@ -32,14 +34,15 @@ func UnauthClientFromCommand(cmd *cobra.Command) (*client.Client, error) {
return client.NewFromConfigUnauthenticated()
}
-// JSONOutputEnabled returns true if JSON output is enabled for this command.
+// JSONOutputEnabled reads the parsed local or inherited --json flag, then runtime output mode.
+// Runtime JSON mode includes --output json, even when --json is explicitly false.
func JSONOutputEnabled(cmd *cobra.Command) bool {
if cmd == nil {
return false
}
- if flag := cmd.Flags().Lookup("json"); flag != nil && flag.Changed {
- val, err := cmd.Flags().GetBool("json")
- return err == nil && val
+ jsonMode, _ := cmd.Flags().GetBool("json")
+ if jsonMode {
+ return true
}
if app, ok := runtime.From(cmd.Context()); ok {
return app.IsJSON()
@@ -47,23 +50,39 @@ func JSONOutputEnabled(cmd *cobra.Command) bool {
return false
}
-// AssumeYes returns true when prompts should be skipped.
+// AssumeYes reads the global --yes flag or invocation consent.
func AssumeYes(cmd *cobra.Command) bool {
if cmd == nil {
return false
}
- if app, ok := runtime.From(cmd.Context()); ok {
- return app.AssumeYes
- }
- return false
+ yes, _ := cmd.Flags().GetBool("yes")
+ app, ok := runtime.From(cmd.Context())
+ return yes || ok && app.AssumeYes
+}
+
+// AllowPrompt reports whether interactive prompts are allowed for this command.
+func AllowPrompt(cmd *cobra.Command) bool {
+ return !JSONOutputEnabled(cmd) && prompt.IsInteractive()
}
-// Confirm prompts the user unless --yes is enabled.
-func Confirm(cmd *cobra.Command, prompt string) (bool, error) {
+// ConfirmOrCancel accepts force, --yes, or fleet consent; otherwise it requires text mode and terminal input.
+// Declining prints Cancelled to stderr and returns false without an error.
+func ConfirmOrCancel(cmd *cobra.Command, force bool, label string) (bool, error) {
app, _ := runtime.From(cmd.Context())
- if AssumeYes(cmd) || app != nil && app.FleetConfirmed {
+ if force || AssumeYes(cmd) || app != nil && app.FleetConfirmed {
return true, nil
}
+ if JSONOutputEnabled(cmd) {
+ return false, fmt.Errorf("confirmation required: re-run with --yes (%s)", label)
+ }
+ confirmed, err := output.Confirm(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), label)
+ if err == nil && !confirmed {
+ _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Cancelled")
+ }
+ return confirmed, err
+}
- return output.Confirm(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), prompt)
+// Confirm prompts through ConfirmOrCancel unless invocation consent is already present.
+func Confirm(cmd *cobra.Command, label string) (bool, error) {
+ return ConfirmOrCancel(cmd, false, label)
}
diff --git a/cli/internal/cmdutil/context_test.go b/cli/internal/cmdutil/context_test.go
new file mode 100644
index 000000000..8f3c38165
--- /dev/null
+++ b/cli/internal/cmdutil/context_test.go
@@ -0,0 +1,78 @@
+package cmdutil
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/creack/pty"
+ "github.com/spf13/cobra"
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
+)
+
+type confirmationInput struct {
+ io.Reader
+ terminal *os.File
+}
+
+func (input confirmationInput) Fd() uintptr { return input.terminal.Fd() }
+
+func TestConfirmOrCancel(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ force, yes, json, terminal, fleet, runtimeYes, confirmed bool
+ answer, wantErr string
+ }{
+ {name: "force", force: true, json: true, confirmed: true},
+ {name: "global yes", yes: true, confirmed: true},
+ {name: "global yes in JSON", yes: true, json: true, confirmed: true},
+ {name: "runtime yes", runtimeYes: true, confirmed: true},
+ {name: "fleet consent", fleet: true, confirmed: true},
+ {name: "JSON refuses prompt", json: true, wantErr: "confirmation required: re-run with --yes"},
+ {name: "piped yes is not consent", answer: "yes\n", wantErr: "confirmation required: re-run with --yes"},
+ {name: "terminal yes", terminal: true, answer: "yes\n", confirmed: true},
+ {name: "terminal no", terminal: true, answer: "no\n"},
+ {name: "terminal blank", terminal: true, answer: "\n"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ var stdout, stderr bytes.Buffer
+ input := strings.NewReader(tt.answer)
+ cmd := &cobra.Command{Use: "delete"}
+ cmd.SetContext(context.WithValue(t.Context(), runtime.AppContextKey, &runtime.AppContext{
+ Options: runtime.Options{AssumeYes: tt.runtimeYes}, FleetConfirmed: tt.fleet,
+ }))
+ cmd.SetOut(&stdout)
+ cmd.SetErr(&stderr)
+ cmd.SetIn(input)
+ cmd.Flags().Bool("json", tt.json, "")
+ cmd.Flags().Bool("yes", tt.yes, "")
+ if tt.terminal {
+ master, terminal, terminalErr := pty.Open()
+ require.NoError(t, terminalErr)
+ defer func() { _ = master.Close(); _ = terminal.Close() }()
+ t.Setenv("TERM", "xterm")
+ cmd.SetIn(confirmationInput{Reader: input, terminal: terminal})
+ }
+ confirmed, confirmErr := ConfirmOrCancel(cmd, tt.force, "Delete record?")
+ require.Equal(t, tt.confirmed, confirmed)
+ if tt.wantErr != "" {
+ require.ErrorContains(t, confirmErr, tt.wantErr)
+ } else {
+ require.NoError(t, confirmErr)
+ }
+ require.Empty(t, stdout.String())
+ if !tt.terminal {
+ require.Equal(t, len(tt.answer), input.Len(), "confirmation must not read noninteractive input")
+ require.Empty(t, stderr.String())
+ }
+ if tt.terminal && !tt.confirmed {
+ require.Contains(t, stderr.String(), "Cancelled\n")
+ }
+ })
+ }
+}
diff --git a/cli/internal/cmdutil/flags.go b/cli/internal/cmdutil/flags.go
new file mode 100644
index 000000000..9eb60ad60
--- /dev/null
+++ b/cli/internal/cmdutil/flags.go
@@ -0,0 +1,73 @@
+package cmdutil
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
+)
+
+// EnumValue implements a string flag restricted to the choices registered by EnumVarP.
+type EnumValue[T ~string] struct {
+ value *T
+ allowed []string
+}
+
+// String returns the current flag value.
+func (v *EnumValue[T]) String() string { return string(*v.value) }
+
+// Type keeps enum flags compatible with pflag's GetString accessor.
+func (v *EnumValue[T]) Type() string { return "string" }
+
+// Set matches the allowed choices case-insensitively and rejects others without changing the destination.
+func (v *EnumValue[T]) Set(value string) error {
+ if value == "" {
+ *v.value = ""
+ return nil
+ }
+ idx := slices.IndexFunc(v.allowed, func(choice string) bool { return strings.EqualFold(choice, value) })
+ if idx < 0 {
+ return fmt.Errorf("invalid value %q (allowed: %s)", value, strings.Join(v.allowed, ", "))
+ }
+ *v.value = T(v.allowed[idx])
+ return nil
+}
+
+// EnumVarP registers a validated enum flag with shell completion and appends the choices to usage.
+// The empty value is always allowed as unset; invalid nonempty defaults panic.
+func EnumVarP[T ~string](cmd *cobra.Command, flags *pflag.FlagSet, p *T, name, shorthand string, value T, usage string, allowed ...T) {
+ choices := make([]string, len(allowed))
+ for i, choice := range allowed {
+ choices[i] = string(choice)
+ }
+ enum := &EnumValue[T]{value: p, allowed: choices}
+ if setErr := enum.Set(string(value)); setErr != nil {
+ panic(fmt.Sprintf("flag --%s: default %v", name, setErr))
+ }
+ listed := slices.DeleteFunc(slices.Clone(choices), func(choice string) bool { return choice == "" })
+ flags.VarP(enum, name, shorthand, fmt.Sprintf("%s (%s)", usage, strings.Join(listed, ", ")))
+ if completionErr := cmd.RegisterFlagCompletionFunc(name, cobra.FixedCompletions(listed, cobra.ShellCompDirectiveNoFileComp)); completionErr != nil {
+ panic(fmt.Sprintf("flag --%s: %v", name, completionErr))
+ }
+}
+
+// ExclusiveFlags rejects more than one changed flag set to a non-zero value for its type.
+func ExclusiveFlags(cmd *cobra.Command, names ...string) error {
+ active := make([]string, 0, len(names))
+ for _, name := range names {
+ flag := cmd.Flags().Lookup(name)
+ if flag == nil {
+ return fmt.Errorf("unknown flag --%s", name)
+ }
+ zero := map[string]string{"bool": "false", "int": "0", "stringSlice": "[]", "stringArray": "[]"}[flag.Value.Type()]
+ if flag.Changed && flag.Value.String() != zero {
+ active = append(active, "--"+name)
+ }
+ }
+ if len(active) > 1 {
+ return fmt.Errorf("flags %s cannot be used together", strings.Join(active, " and "))
+ }
+ return nil
+}
diff --git a/cli/internal/cmdutil/flags_test.go b/cli/internal/cmdutil/flags_test.go
new file mode 100644
index 000000000..acf13a215
--- /dev/null
+++ b/cli/internal/cmdutil/flags_test.go
@@ -0,0 +1,162 @@
+package cmdutil
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+ "github.com/stretchr/testify/require"
+)
+
+func TestEnumValue(t *testing.T) {
+ type mode string
+ for _, tt := range []struct {
+ name string
+ input string
+ want mode
+ valid bool
+ }{
+ {name: "allowed", input: "json", want: "json", valid: true},
+ {name: "invalid", input: "xml", want: "text"},
+ {name: "case insensitive", input: "JSON", want: "json", valid: true},
+ {name: "whitespace", input: " json ", want: "text"},
+ {name: "empty", input: "", want: "", valid: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ current := mode("text")
+ value := &EnumValue[mode]{value: &current, allowed: []string{"text", "json"}}
+ setErr := value.Set(tt.input)
+ if tt.valid {
+ require.NoError(t, setErr)
+ } else {
+ require.ErrorContains(t, setErr, "allowed: text, json")
+ }
+ require.Equal(t, tt.want, current)
+ require.Equal(t, string(tt.want), value.String())
+ require.Equal(t, "string", value.Type())
+ })
+ }
+}
+
+func TestEnumVarP(t *testing.T) {
+ type mode string
+ for _, tt := range []struct {
+ name string
+ persistent bool
+ input string
+ valid bool
+ short bool
+ emptyDefault bool
+ }{
+ {name: "local valid", input: "json", valid: true},
+ {name: "local invalid", input: "xml"},
+ {name: "persistent valid", persistent: true, input: "json", valid: true},
+ {name: "persistent invalid", persistent: true, input: "xml"},
+ {name: "local shorthand", input: "json", valid: true, short: true},
+ {name: "persistent shorthand", persistent: true, input: "json", valid: true, short: true},
+ {name: "optional default", input: "json", valid: true, emptyDefault: true},
+ {name: "optional empty", input: "", valid: true, emptyDefault: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ root := &cobra.Command{Use: "root"}
+ child := &cobra.Command{Use: "child"}
+ root.AddCommand(child)
+ owner, flags := child, child.Flags()
+ if tt.persistent {
+ owner, flags = root, root.PersistentFlags()
+ }
+ var current mode
+ allowed := []mode{"text", "json"}
+ defaultValue := mode("text")
+ if tt.emptyDefault {
+ defaultValue = ""
+ }
+ EnumVarP(owner, flags, &current, "mode", "m", defaultValue, "Output mode", allowed...)
+ require.Equal(t, "Output mode (text, json)", flags.Lookup("mode").Usage)
+ require.Equal(t, defaultValue, current)
+ allowed[0] = "changed"
+ completion, ok := owner.GetFlagCompletionFunc("mode")
+ require.True(t, ok)
+ choices, directive := completion(child, nil, "")
+ require.Equal(t, []string{"text", "json"}, choices)
+ require.Equal(t, cobra.ShellCompDirectiveNoFileComp, directive)
+
+ flagName := "--mode"
+ if tt.short {
+ flagName = "-m"
+ }
+ parseErr := child.ParseFlags([]string{flagName, tt.input})
+ if tt.valid {
+ require.NoError(t, parseErr)
+ require.Equal(t, mode(tt.input), current)
+ } else {
+ require.ErrorContains(t, parseErr, "allowed: text, json")
+ require.Equal(t, defaultValue, current)
+ }
+ got, getErr := child.Flags().GetString("mode")
+ require.NoError(t, getErr)
+ require.Equal(t, string(current), got)
+ })
+ }
+}
+
+func TestEnumVarPInvalidDefault(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ allowed []string
+ }{
+ {name: "empty choices"},
+ {name: "invalid default", allowed: []string{"text", "json"}},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ cmd := &cobra.Command{Use: "root"}
+ current := "unchanged"
+ require.PanicsWithValue(t, `flag --mode: default invalid value "xml" (allowed: `+strings.Join(tt.allowed, ", ")+`)`, func() {
+ EnumVarP(cmd, cmd.Flags(), &current, "mode", "", "xml", "Output mode", tt.allowed...)
+ })
+ require.Equal(t, "unchanged", current)
+ require.Nil(t, cmd.Flags().Lookup("mode"))
+ })
+ }
+}
+
+func TestExclusiveFlags(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ args []string
+ wantErr string
+ }{
+ {name: "defaults do not conflict"},
+ {name: "one boolean", args: []string{"--inuse"}},
+ {name: "explicit false", args: []string{"--inuse=false", "--unused"}},
+ {name: "empty string", args: []string{"--filter=", "--unused"}},
+ {name: "zero integer", args: []string{"--limit=0", "--unused"}},
+ {name: "empty slice", args: []string{"--labels=", "--unused"}},
+ {name: "boolean conflict", args: []string{"--inuse", "--unused"}, wantErr: "flags --inuse and --unused cannot be used together"},
+ {name: "string conflict", args: []string{"--filter=0", "--unused"}, wantErr: "flags --unused and --filter cannot be used together"},
+ {name: "integer conflict", args: []string{"--limit=1", "--unused"}, wantErr: "flags --unused and --limit cannot be used together"},
+ {name: "slice conflict", args: []string{"--labels=app", "--unused"}, wantErr: "flags --unused and --labels cannot be used together"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ cmd := &cobra.Command{
+ Use: "list", RunE: func(*cobra.Command, []string) error { return nil },
+ PreRunE: func(cmd *cobra.Command, _ []string) error {
+ return ExclusiveFlags(cmd, "inuse", "unused", "filter", "limit", "labels")
+ },
+ }
+ cmd.SetContext(t.Context())
+ cmd.Flags().Bool("inuse", false, "")
+ cmd.Flags().Bool("unused", false, "")
+ cmd.Flags().String("filter", "default", "")
+ cmd.Flags().Int("limit", 10, "")
+ cmd.Flags().StringSlice("labels", nil, "")
+ require.NoError(t, cmd.ParseFlags(tt.args))
+ checkErr := cmd.PreRunE(cmd, nil)
+ if tt.wantErr != "" {
+ require.EqualError(t, checkErr, tt.wantErr)
+ } else {
+ require.NoError(t, checkErr)
+ }
+ })
+ }
+}
diff --git a/cli/internal/cmdutil/pagination.go b/cli/internal/cmdutil/pagination.go
index ce1cde4e8..83688278a 100644
--- a/cli/internal/cmdutil/pagination.go
+++ b/cli/internal/cmdutil/pagination.go
@@ -11,25 +11,17 @@ import (
kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
- runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
- clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
)
const (
- // ShowAllLimit is the sentinel the Arcane API uses for "return everything".
- // The backend honours it on every list path: DB-backed lists short-circuit to
- // paginateDBAll (bypassing the 100-item clamp), in-memory Docker lists return
- // the full slice, and the handlers that coerce a zero limit to 20 test for
- // exactly 0 so they leave it alone.
+ // ShowAllLimit requests every item without the server pagination clamp.
ShowAllLimit = -1
// AllFlagUsage is the shared help text for the --all flag on list commands.
AllFlagUsage = "Return every item, ignoring pagination"
- // StartFlagUsage is the shared help text for the --start flag on list commands.
- // Database-backed resources (projects, repos, gitops-syncs, environments,
- // registries, users, events, api-keys, roles) derive a page number from
- // start/limit, so an offset that is not a multiple of --limit is rounded down.
+ // StartFlagUsage documents offset rounding for database-backed resources.
StartFlagUsage = "Offset for pagination (rounded down to a multiple of --limit on database-backed resources)"
)
@@ -53,7 +45,7 @@ func AppendQuery(path string, extra url.Values) string {
// ListParams describes how a list command wants its results paginated.
type ListParams struct {
// Resource is the canonical resource name used to look up a configured
- // per-resource limit. See clitypes.KnownPaginatedResources.
+ // per-resource limit.
Resource string
// Limit is the value of the command's --limit flag.
Limit int
@@ -97,10 +89,8 @@ func ApplyPaginationParams(cmd *cobra.Command, path string, p ListParams) (strin
return parsed.String(), nil
}
-// EffectiveLimit resolves the final list limit with precedence:
-// explicit flag > per-resource config > global config > fallback default.
-// A limit of ShowAllLimit is passed straight through so that `--limit -1`
-// reaches the server as the documented "return everything" sentinel.
+// EffectiveLimit resolves explicit flag, resource config, global config, then fallback.
+// ShowAllLimit passes through unchanged.
func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int {
if cmd != nil {
if flag := cmd.Flags().Lookup(flagName); flag != nil && flag.Changed {
@@ -108,13 +98,11 @@ func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fa
}
}
- resource = clitypes.NormalizePaginatedResource(resource)
-
var ctx context.Context
if cmd != nil {
ctx = cmd.Context()
}
- if app, ok := runtimectx.From(ctx); ok {
+ if app, ok := runtime.From(ctx); ok {
if cfg := app.Config(); cfg != nil {
if v := cfg.LimitFor(resource); v != 0 {
return v
diff --git a/cli/internal/cmdutil/resolve.go b/cli/internal/cmdutil/resolve.go
index be9215bc1..6964d2d1d 100644
--- a/cli/internal/cmdutil/resolve.go
+++ b/cli/internal/cmdutil/resolve.go
@@ -12,6 +12,7 @@ import (
"slices"
"strings"
+ "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/environment"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
@@ -74,6 +75,27 @@ type resourceCandidate[D any] struct {
label string
}
+// Fetch resolves an identifier and retrieves full detail when resolution returned only a summary.
+func (ref ResourceRef[D, S]) Fetch(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, error) {
+ resolved, complete, err := ref.Resolve(ctx, c, identifier, allowPrompt)
+ if err != nil || complete {
+ return resolved, err
+ }
+ if ref.GetPath == nil || ref.IdentifierOf == nil {
+ return nil, fmt.Errorf("%s reference requires GetPath and IdentifierOf to fetch detail", ref.Singular)
+ }
+ result, fetchErr := c.GetJSON[D](ctx, ref.GetPath(c.EnvID(), ref.IdentifierOf(*resolved)))
+ if fetchErr != nil {
+ return nil, fetchErr
+ }
+ if ref.Validate != nil {
+ if validateErr := ref.Validate(result.Data, identifier); validateErr != nil {
+ return nil, validateErr
+ }
+ }
+ return &result.Data, nil
+}
+
// Resolve finds one resource and pins its environment for subsequent requests.
func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, bool, error) {
identifier = strings.TrimSpace(identifier)
@@ -226,7 +248,10 @@ func (ref ResourceRef[D, S]) fetchByIdentifier(ctx context.Context, c *client.Cl
}
if resp.StatusCode == http.StatusOK {
- var result client.APIResponse[D]
+ var result struct {
+ base.ApiResponse[D]
+ base.ErrorResponse
+ }
if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
return nil, false, fmt.Errorf("failed to parse %s response: %w", ref.Singular, unmarshalErr)
}
@@ -295,7 +320,10 @@ func (ref ResourceRef[D, S]) listItems(ctx context.Context, c *client.Client, pa
return nil, fmt.Errorf("failed to search %s (status %d): %s", ref.Plural, resp.StatusCode, strings.TrimSpace(string(body)))
}
- var result client.APIResponse[[]S]
+ var result struct {
+ base.ApiResponse[[]S]
+ base.ErrorResponse
+ }
if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
return nil, fmt.Errorf("failed to parse %s response: %w", ref.Plural, unmarshalErr)
}
@@ -308,13 +336,7 @@ func (ref ResourceRef[D, S]) listItems(ctx context.Context, c *client.Client, pa
// LooksLikeIDPrefix reports whether identifier could be a hex ID prefix worth
// scanning the full list for.
func LooksLikeIDPrefix(identifierLower string) bool {
- if len(identifierLower) < 4 {
- return false
- }
- for _, r := range identifierLower {
- if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
- return false
- }
- }
- return true
+ return len(identifierLower) >= 4 && strings.IndexFunc(identifierLower, func(r rune) bool {
+ return (r < '0' || r > '9') && (r < 'a' || r > 'f')
+ }) == -1
}
diff --git a/cli/internal/cmdutil/resolve_test.go b/cli/internal/cmdutil/resolve_test.go
new file mode 100644
index 000000000..8fd0fb136
--- /dev/null
+++ b/cli/internal/cmdutil/resolve_test.go
@@ -0,0 +1,89 @@
+package cmdutil
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+)
+
+func TestResourceRefFetch(t *testing.T) {
+ type detail struct{ ID, Name, Extra string }
+ type summary struct{ ID, Name string }
+ for _, tt := range []struct {
+ name, identifier, detailBody, searchBody, wantErr string
+ noIdentifier bool
+ wantRequests []string
+ }{
+ {name: "complete direct lookup", identifier: "id-1", wantRequests: []string{"/resources/id-1"}},
+ {name: "summary fetches canonical detail", identifier: "arcane", wantRequests: []string{"/resources/arcane", "/resources?search=arcane&limit=-1", "/resources/id-1"}},
+ {
+ name: "detail API failure", identifier: "arcane", detailBody: `{"success":false,"error":"denied"}`, wantErr: "API error: denied",
+ wantRequests: []string{"/resources/arcane", "/resources?search=arcane&limit=-1", "/resources/id-1"},
+ },
+ {
+ name: "not found", identifier: "absent", searchBody: `{"success":true,"data":[]}`, wantErr: `record "absent" not found`,
+ wantRequests: []string{"/resources/absent", "/resources?search=absent&limit=-1"},
+ },
+ {name: "empty identifier", wantErr: "record identifier is required"},
+ {
+ name: "missing detail identifier", identifier: "arcane", noIdentifier: true, wantErr: "requires GetPath and IdentifierOf",
+ wantRequests: []string{"/resources/arcane", "/resources?search=arcane&limit=-1"},
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ requests := make(chan string, 3)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests <- r.URL.RequestURI()
+ switch r.URL.Path {
+ case "/resources/id-1":
+ if tt.detailBody != "" {
+ _, _ = fmt.Fprint(w, tt.detailBody)
+ return
+ }
+ _, _ = fmt.Fprint(w, `{"success":true,"data":{"ID":"id-1","Name":"arcane","Extra":"full detail"}}`)
+ case "/resources":
+ if tt.searchBody != "" {
+ _, _ = fmt.Fprint(w, tt.searchBody)
+ return
+ }
+ _, _ = fmt.Fprint(w, `{"success":true,"data":[{"ID":"id-1","Name":"arcane"}]}`)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer server.Close()
+ c, newErr := client.NewUnauthenticated(&types.Config{ServerURL: server.URL})
+ require.NoError(t, newErr)
+ ref := ResourceRef[detail, summary]{
+ Singular: "record", Plural: "records", IDHint: "the record ID", ListCmd: "records list",
+ GetPath: func(_, identifier string) string { return "/resources/" + identifier },
+ ListPath: func(string) string { return "/resources" },
+ Matches: func(item summary, lower, _ string) bool { return strings.ToLower(item.Name) == lower },
+ Label: func(item summary) string { return item.Name },
+ Promote: func(item summary) *detail { return &detail{ID: item.ID, Name: item.Name} },
+ IdentifierOf: func(item detail) string { return item.ID },
+ }
+ if tt.noIdentifier {
+ ref.IdentifierOf = nil
+ }
+ result, fetchErr := ref.Fetch(t.Context(), c, tt.identifier, false)
+ if tt.wantErr != "" {
+ require.ErrorContains(t, fetchErr, tt.wantErr)
+ } else {
+ require.NoError(t, fetchErr)
+ require.Equal(t, &detail{ID: "id-1", Name: "arcane", Extra: "full detail"}, result)
+ }
+ require.Len(t, requests, len(tt.wantRequests))
+ for _, path := range tt.wantRequests {
+ require.Equal(t, path, <-requests)
+ }
+ })
+ }
+}
diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.go
index fe8e8c945..7f8d85d3e 100644
--- a/cli/internal/cmdutil/response.go
+++ b/cli/internal/cmdutil/response.go
@@ -45,11 +45,8 @@ func EnsureSuccessStatus(resp *http.Response) error {
}
}
-// DecodeJSON decodes JSON into out and enforces a successful HTTP status.
-func DecodeJSON[T any](resp *http.Response, out *T) error {
- if err := EnsureSuccessStatus(resp); err != nil {
- return err
- }
+// DecodeJSON decodes into out; callers must first enforce HTTP success with EnsureSuccessStatus.
+func DecodeJSON(resp *http.Response, out any) error {
if out == nil {
return errors.New("nil decode target")
}
diff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.go
index db7a982ce..0219a0d9e 100644
--- a/cli/internal/cmdutil/run.go
+++ b/cli/internal/cmdutil/run.go
@@ -1,8 +1,11 @@
package cmdutil
import (
+ "encoding/json/jsontext"
"encoding/json/v2"
+ "errors"
"fmt"
+ "net/http"
"net/url"
"time"
@@ -24,8 +27,6 @@ type ListSpec[T any] struct {
Params ListParams
// Query holds extra query parameters, applied after pagination.
Query url.Values
- // JSON selects raw JSON passthrough output.
- JSON bool
Headers []string
Row func(T) []string
@@ -33,7 +34,7 @@ type ListSpec[T any] struct {
// RunList executes one standard list command as described by spec.
func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) error {
- loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !spec.JSON, "Loading "+spec.Resource)
+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !JSONOutputEnabled(cmd), "Loading "+spec.Resource)
loading.NextStep()
defer loading.Stop()
path, err := ApplyPaginationParams(cmd, spec.Endpoint, spec.Params)
@@ -55,7 +56,7 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erro
return fmt.Errorf("failed to list %s: %w", spec.Resource, err)
}
- if spec.JSON {
+ if JSONOutputEnabled(cmd) {
return PrintRawJSON(body)
}
@@ -71,49 +72,72 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erro
rows[i] = spec.Row(item)
}
- if tableErr := PrintTable(cmd, spec.Headers, rows, TableSummary{Resource: spec.Resource, Total: result.Pagination.TotalItems, Paginated: true}); tableErr != nil {
- return tableErr
- }
- return nil
+ return PrintTable(cmd, spec.Headers, rows, TableSummary{Resource: spec.Resource, Total: result.Pagination.TotalItems, Paginated: true})
}
-// PostActionSpec describes one resolve→POST→decode→report action command. T
-// is the API envelope's data payload.
-type PostActionSpec struct {
- // Path is the fully built action path.
- Path string
- // Body is the optional JSON request body.
- Body any
- // FailureMessage wraps transport and status errors.
- FailureMessage string
- // SuccessMessage is the preformatted human-readable success line.
- SuccessMessage string
- // Timeout optionally extends the client timeout for slow actions.
- Timeout time.Duration
- // JSON prints the decoded response data instead of the success line.
- JSON bool
+// Spec describes a request with raw JSON data output or typed text rendering.
+// Render is required in text mode; a nil Render returns a programmer error before requesting.
+type Spec[T any] struct {
+ Method, Path, FailureMessage string
+ Body any
+ Timeout time.Duration
+ Render func(T) error
}
-// RunPostAction executes one POST action command as described by spec.
-func RunPostAction[T any](cmd *cobra.Command, c *client.Client, spec PostActionSpec) error {
+// Run enforces a success envelope and prints raw data in JSON mode or invokes Render in text mode.
+func Run[T any](cmd *cobra.Command, c *client.Client, spec Spec[T]) error {
+ jsonMode := JSONOutputEnabled(cmd)
+ if !jsonMode && spec.Render == nil {
+ return errors.New("request runner requires Render in text mode")
+ }
if spec.Timeout > 0 {
c.SetTimeout(spec.Timeout)
}
-
- loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !spec.JSON, cmd.Short)
+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !jsonMode, cmd.Short)
loading.NextStep()
defer loading.Stop()
- result, err := c.PostJSON[T](cmd.Context(), spec.Path, spec.Body)
+ result, err := c.DoEnvelope[jsontext.Value](cmd.Context(), spec.Method, spec.Path, spec.Body)
if err != nil {
return fmt.Errorf("%s: %w", spec.FailureMessage, err)
}
-
loading.Finish("", nil)
loading.Stop()
- if spec.JSON {
- return PrintJSON(result.Data)
+ if jsonMode {
+ if len(result.Data) == 0 {
+ return PrintJSON(nil)
+ }
+ return PrintRawJSON(result.Data)
+ }
+ var data T
+ if len(result.Data) > 0 {
+ if decodeErr := json.Unmarshal(result.Data, &data); decodeErr != nil {
+ return fmt.Errorf("%s: failed to decode response: %w", spec.FailureMessage, decodeErr)
+ }
}
+ return spec.Render(data)
+}
+
+// DeleteSpec describes a confirmed DELETE with optional body and human-readable success output.
+type DeleteSpec struct {
+ Force bool
+ Prompt, Path, FailureMessage, SuccessMessage string
+ Body any
+}
- output.Success("%s", spec.SuccessMessage)
- return nil
+// RunDelete returns nil on cancellation, otherwise printing raw data in JSON mode or SuccessMessage in text mode.
+func RunDelete(cmd *cobra.Command, c *client.Client, spec DeleteSpec) error {
+ confirmed, err := ConfirmOrCancel(cmd, spec.Force, spec.Prompt)
+ if err != nil || !confirmed {
+ return err
+ }
+ return Run(cmd, c, Spec[jsontext.Value]{
+ Method: http.MethodDelete,
+ Path: spec.Path,
+ Body: spec.Body,
+ FailureMessage: spec.FailureMessage,
+ Render: func(jsontext.Value) error {
+ output.Success("%s", spec.SuccessMessage)
+ return nil
+ },
+ })
}
diff --git a/cli/internal/cmdutil/run_test.go b/cli/internal/cmdutil/run_test.go
new file mode 100644
index 000000000..0f4abe06e
--- /dev/null
+++ b/cli/internal/cmdutil/run_test.go
@@ -0,0 +1,188 @@
+package cmdutil
+
+import (
+ "bytes"
+ "cmp"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/creack/pty"
+ "github.com/spf13/cobra"
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+)
+
+func TestRun(t *testing.T) {
+ type record struct {
+ Name string `json:"name"`
+ }
+ renderFailure := errors.New("render failed")
+ for _, tt := range []struct {
+ name string
+ json bool
+ status int
+ body string
+ renderErr error
+ wantErr string
+ wantText string
+ wantCalls int
+ }{
+ {name: "json data only", json: true, status: http.StatusOK, body: `{"success":true,"data":{"name":"arcane"}}`, wantText: "{\n \"name\": \"arcane\"\n}\n"},
+ {
+ name: "unknown fields retained", json: true, status: http.StatusOK,
+ body: `{"success":true,"data":{"name":"arcane","future":{"number":9007199254740993}}}`,
+ wantText: "{\n \"name\": \"arcane\",\n \"future\": {\n \"number\": 9007199254740993\n }\n}\n",
+ },
+ {name: "JSON skips typed decoding", json: true, status: http.StatusOK, body: `{"success":true,"data":{"name":7}}`, wantText: "{\n \"name\": 7\n}\n"},
+ {name: "null data", json: true, status: http.StatusOK, body: `{"success":true,"data":null}`, wantText: "null\n"},
+ {name: "missing data", json: true, status: http.StatusOK, body: `{"success":true}`, wantText: "null\n"},
+ {name: "typed render", status: http.StatusOK, body: `{"success":true,"data":{"name":"arcane"}}`, wantText: "name: arcane\n", wantCalls: 1},
+ {name: "render failure", status: http.StatusOK, body: `{"success":true,"data":{"name":"arcane"}}`, renderErr: renderFailure, wantErr: "render failed", wantCalls: 1},
+ {name: "http failure", status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`, wantErr: "failed to get record: request failed with status 401"},
+ {name: "api failure", json: true, status: http.StatusOK, body: `{"success":false,"error":"unavailable"}`, wantErr: "failed to get record: API error: unavailable"},
+ {name: "malformed response", status: http.StatusOK, body: `invalid`, wantErr: "failed to get record: failed to decode response"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ requests := make(chan string, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests <- r.Method + " " + r.URL.RequestURI()
+ w.WriteHeader(tt.status)
+ _, _ = fmt.Fprint(w, tt.body)
+ }))
+ defer server.Close()
+ c, newErr := client.New(&types.Config{ServerURL: server.URL, APIKey: "test-key"})
+ require.NoError(t, newErr)
+ var stdout, stderr bytes.Buffer
+ cmd := &cobra.Command{Use: "get", Short: "Get record"}
+ cmd.SetContext(t.Context())
+ cmd.Flags().Bool("json", tt.json, "")
+ cmd.SetOut(&stdout)
+ cmd.SetErr(&stderr)
+ oldOut, oldErr := output.Stdout(), output.Stderr()
+ output.Configure(&stdout, &stderr, tt.json, true, cmd.Short)
+ defer output.Configure(oldOut, oldErr, false, true, "Loading")
+ renderCalls := 0
+ runErr := Run(cmd, c, Spec[record]{
+ Method: http.MethodGet,
+ Path: "/api/record?details=true",
+ FailureMessage: "failed to get record",
+ Render: func(item record) error {
+ renderCalls++
+ require.Equal(t, record{Name: "arcane"}, item)
+ if tt.renderErr != nil {
+ return tt.renderErr
+ }
+ _, printErr := fmt.Fprintf(cmd.OutOrStdout(), "name: %s\n", item.Name)
+ return printErr
+ },
+ })
+ if tt.wantErr == "" {
+ require.NoError(t, runErr)
+ } else {
+ require.ErrorContains(t, runErr, tt.wantErr)
+ }
+ if tt.renderErr != nil {
+ require.ErrorIs(t, runErr, tt.renderErr)
+ }
+ require.Equal(t, "GET /api/record?details=true", <-requests)
+ require.Equal(t, tt.wantCalls, renderCalls)
+ require.Equal(t, tt.wantText, stdout.String())
+ })
+ }
+}
+
+func TestRunRequiresRender(t *testing.T) {
+ cmd := &cobra.Command{Use: "get"}
+ cmd.SetContext(t.Context())
+ require.ErrorContains(t, Run(cmd, nil, Spec[string]{Method: http.MethodGet}), "requires Render in text mode")
+}
+
+func TestRunDelete(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ force, yes, json, terminal bool
+ answer, response, wantErr string
+ body any
+ wantRequests int
+ }{
+ {name: "force", force: true, wantRequests: 1},
+ {name: "yes", yes: true, wantRequests: 1},
+ {name: "cancel", terminal: true, answer: "n\n"},
+ {name: "non TTY", wantErr: "confirmation required: re-run with --yes"},
+ {name: "JSON requires consent", json: true, wantErr: "confirmation required: re-run with --yes"},
+ {name: "JSON raw data", json: true, force: true, wantRequests: 1, body: map[string]bool{"remove": true}},
+ {name: "JSON yes", json: true, yes: true, wantRequests: 1},
+ {name: "API failure", force: true, wantRequests: 1, response: `{"success":false,"error":"denied"}`, wantErr: "failed to delete record: API error: denied"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ requests := make(chan string, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requestBody, readErr := io.ReadAll(r.Body)
+ if readErr != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ requests <- r.Method + " " + r.URL.Path + " " + string(requestBody)
+ _, _ = fmt.Fprint(w, cmp.Or(tt.response, `{"success":true,"data":{"message":"removed","future":9007199254740993}}`))
+ }))
+ defer server.Close()
+ c, newErr := client.NewUnauthenticated(&types.Config{ServerURL: server.URL})
+ require.NoError(t, newErr)
+ var stdout, stderr bytes.Buffer
+ cmd := &cobra.Command{Use: "delete"}
+ cmd.SetContext(t.Context())
+ cmd.SetOut(&stdout)
+ cmd.SetErr(&stderr)
+ cmd.SetIn(strings.NewReader("y\n"))
+ cmd.Flags().Bool("json", tt.json, "")
+ cmd.Flags().Bool("yes", tt.yes, "")
+ if tt.terminal {
+ master, terminal, terminalErr := pty.Open()
+ require.NoError(t, terminalErr)
+ defer func() { _ = master.Close(); _ = terminal.Close() }()
+ t.Setenv("TERM", "xterm")
+ cmd.SetIn(confirmationInput{Reader: strings.NewReader(tt.answer), terminal: terminal})
+ }
+ oldOut, oldErr := output.Stdout(), output.Stderr()
+ output.Configure(&stdout, &stderr, tt.json, true, "Delete record")
+ defer output.Configure(oldOut, oldErr, false, true, "Loading")
+ runErr := RunDelete(cmd, c, DeleteSpec{
+ Force: tt.force, Prompt: "Delete record?", Path: "/api/record", Body: tt.body,
+ FailureMessage: "failed to delete record", SuccessMessage: "Record removed",
+ })
+ if tt.wantErr != "" {
+ require.ErrorContains(t, runErr, tt.wantErr)
+ } else {
+ require.NoError(t, runErr)
+ }
+ require.Len(t, requests, tt.wantRequests)
+ if tt.wantRequests > 0 {
+ request := <-requests
+ require.Contains(t, request, "DELETE /api/record ")
+ if tt.body != nil {
+ require.Contains(t, request, `{"remove":true}`)
+ }
+ }
+ switch {
+ case tt.wantErr != "":
+ require.Empty(t, stdout.String())
+ case tt.wantRequests == 0:
+ require.Empty(t, stdout.String())
+ require.Contains(t, stderr.String(), "Cancelled\n")
+ case tt.json:
+ require.JSONEq(t, `{"message":"removed","future":9007199254740993}`, stdout.String())
+ require.Empty(t, stderr.String())
+ default:
+ require.Contains(t, stdout.String(), "Record removed")
+ }
+ })
+ }
+}
diff --git a/cli/internal/cmdutil/scope.go b/cli/internal/cmdutil/scope.go
index 362115d62..d21337ce8 100644
--- a/cli/internal/cmdutil/scope.go
+++ b/cli/internal/cmdutil/scope.go
@@ -7,6 +7,7 @@ import (
"encoding/json/jsontext"
"errors"
"fmt"
+ "slices"
"strings"
"github.com/spf13/cobra"
@@ -31,25 +32,34 @@ type environmentResult struct {
Error string `json:"error,omitempty"`
}
-var resourceResolvers = make(map[*cobra.Command]func(*cobra.Command, []string) error)
-
-// SetResource binds commands using raw identifiers to the shared resource resolver.
+// SetResource binds raw identifiers through a command-owned closure; call after assigning RunE.
func SetResource[D, S any](ref ResourceRef[D, S], commands ...*cobra.Command) {
SetScope(ScopeResource, commands...)
for _, cmd := range commands {
- resourceResolvers[cmd] = func(command *cobra.Command, args []string) error {
+ if cmd.Annotations["arcane:resource-wrapped"] == "true" {
+ continue
+ }
+ cmd.Annotations["arcane:resource-wrapped"] = "true"
+ run := cmd.RunE
+ cmd.RunE = func(command *cobra.Command, args []string) error {
+ app, _ := runtime.From(command.Context())
+ if !app.PreviewEnabled() {
+ return run(command, args)
+ }
+ defer app.SelectEnvironment("")
c, err := ClientFromCommand(command)
if err != nil {
return err
}
- resolved, _, err := ref.Resolve(command.Context(), c, args[0], false)
- if err != nil {
- return err
+ resolved, _, resolveErr := ref.Resolve(command.Context(), c, args[0], false)
+ if resolveErr != nil {
+ return resolveErr
}
+ resolvedArgs := slices.Clone(args)
if ref.IdentifierOf != nil {
- args[0] = ref.IdentifierOf(*resolved)
+ resolvedArgs[0] = ref.IdentifierOf(*resolved)
}
- return nil
+ return run(command, resolvedArgs)
}
}
}
@@ -86,12 +96,6 @@ func RunScoped(cmd *cobra.Command, args []string, run func(*cobra.Command, []str
return run(cmd, args)
}
if scope == ScopeResource {
- defer app.SelectEnvironment("")
- if resolve := resourceResolvers[cmd]; resolve != nil {
- if resolveErr := resolve(cmd, args); resolveErr != nil {
- return resolveErr
- }
- }
return run(cmd, args)
}
if scope != ScopeDestination {
@@ -137,7 +141,7 @@ func RunEnvironments(cmd *cobra.Command, args []string, run func(*cobra.Command,
if mutation && !skip {
labels := make([]string, len(environments))
for i, env := range environments {
- labels[i] = fmt.Sprintf("%s (%s)", cmp.Or(env.Name, env.ID), env.ID)
+ labels[i] = cmp.Or(env.Name, env.ID)
}
confirmed, confirmErr := Confirm(cmd, fmt.Sprintf("%s across %d environments: %s?", cmd.Short, len(labels), strings.Join(labels, ", ")))
if confirmErr != nil {
diff --git a/cli/internal/cmdutil/table.go b/cli/internal/cmdutil/table.go
index fb85ec57a..bf8625e57 100644
--- a/cli/internal/cmdutil/table.go
+++ b/cli/internal/cmdutil/table.go
@@ -25,7 +25,7 @@ type tableOutput struct {
}
// PrintTable renders rows and an optional summary, collecting them during an environment preview.
-func PrintTable[T ~[]string](cmd *cobra.Command, headers []string, rows []T, summaries ...TableSummary) error {
+func PrintTable(cmd *cobra.Command, headers []string, rows [][]string, summaries ...TableSummary) error {
var summary TableSummary
if len(summaries) > 0 {
summary = summaries[0]
@@ -33,7 +33,7 @@ func PrintTable[T ~[]string](cmd *cobra.Command, headers []string, rows []T, sum
combined, _ := cmd.Context().Value(tableContextKey{}).(*tableOutput)
formatted := make([][]string, len(rows))
for i, row := range rows {
- formatted[i] = []string(row)
+ formatted[i] = row
if combined != nil {
formatted[i] = slices.Concat([]string{combined.environment}, formatted[i])
}
diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.go
index 98bad2e6f..d212fee68 100644
--- a/cli/internal/cmdutil/upload.go
+++ b/cli/internal/cmdutil/upload.go
@@ -10,7 +10,7 @@ import (
"path/filepath"
"strings"
- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+ "github.com/getarcaneapp/arcane/types/v2/upload"
kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
@@ -21,11 +21,8 @@ import (
const uploadChunkAttempts = 3
-// UploadFileInChunks streams a local file to the server through a chunked
-// upload session of the given kind and returns the completed session ID. The
-// file is sent as independently retried chunks so reverse-proxy body limits
-// never see the full size. On failure the session is deleted server-side.
-// When showProgress is true a progress bar is rendered.
+// UploadFileInChunks sends retried chunks with optional progress and aborts the session on failure.
+// It returns the completed upload session ID.
func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath string, showProgress bool) (string, error) {
log := logger.GetLogger()
@@ -42,7 +39,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st
loading := output.StartTracker(ctx, output.Stderr(), showProgress, "Creating upload session", "Uploading chunks")
loading.NextStep()
defer loading.Stop()
- created, err := c.PostJSON[uploadtypes.Session](ctx, types.UploadSessions(c.EnvID(), kind), uploadtypes.CreateSessionRequest{
+ created, err := c.PostJSON[upload.Session](ctx, types.UploadSessions(c.EnvID(), kind), upload.CreateSessionRequest{
Filename: filepath.Base(filePath),
Size: fileInfo.Size(),
})
@@ -57,17 +54,11 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st
loading.SetProgress("", "Uploading", 0, fileInfo.Size(), true)
var uploaded int64
- deleteSession := func() {
- if resp, deleteErr := c.Delete(context.WithoutCancel(ctx), types.UploadSession(c.EnvID(), kind, session.ID)); deleteErr == nil {
- _ = resp.Body.Close()
- }
- }
-
buf := make([]byte, session.ChunkSize)
for index := range session.TotalChunks {
expected := kit.Ternary(index == session.TotalChunks-1, session.Size-int64(index)*session.ChunkSize, session.ChunkSize)
if _, readFullErr := io.ReadFull(file, buf[:expected]); readFullErr != nil {
- deleteSession()
+ AbortUploadSession(ctx, c, kind, session.ID)
return "", fmt.Errorf("failed to read file: %w", readFullErr)
}
@@ -86,7 +77,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st
}
}
if attempt >= uploadChunkAttempts {
- deleteSession()
+ AbortUploadSession(ctx, c, kind, session.ID)
return "", fmt.Errorf("failed to upload file: %w", chunkErr)
}
log.Debugf("Retrying chunk %d after error: %v", index, chunkErr)
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
index c6db58fba..d51bc7f66 100644
--- a/cli/internal/config/config.go
+++ b/cli/internal/config/config.go
@@ -36,22 +36,6 @@ var configCache = hot.NewHotCache[string, *types.Config](hot.LRU, 4).
WithCopyOnWrite((*types.Config).Clone).
Build()
-func normalizeConfig(cfg *types.Config) *types.Config {
- if cfg == nil {
- return DefaultConfig()
- }
- normalized := cfg.Clone()
- if normalized == nil {
- return DefaultConfig()
- }
-
- if normalized.Pagination.Resources == nil {
- normalized.Pagination.Resources = make(map[string]types.PaginationResourceConfig)
- }
-
- return normalized
-}
-
func invalidateCache() {
configCache.Purge()
}
@@ -132,7 +116,10 @@ func Load() (*types.Config, error) {
if parseErr := yaml.Unmarshal(data, cfg); parseErr != nil {
return nil, fmt.Errorf("failed to parse config file: %w", parseErr)
}
- normalized := normalizeConfig(cfg)
+ normalized := cfg.Clone()
+ if normalized.Pagination.Resources == nil {
+ normalized.Pagination.Resources = make(map[string]types.PaginationResourceConfig)
+ }
configCache.Set(path, normalized)
@@ -146,7 +133,10 @@ func Save(c *types.Config) error {
return err
}
- cfg := normalizeConfig(c)
+ cfg := DefaultConfig()
+ if c != nil {
+ cfg = c.Clone()
+ }
cfg.Pagination.Default.Limit = max(0, cfg.Pagination.Default.Limit)
resources := cfg.Pagination.Resources
cfg.Pagination.Resources = make(map[string]types.PaginationResourceConfig, len(resources))
diff --git a/cli/internal/logger/logger.go b/cli/internal/logger/logger.go
index 361b0cb07..030d02b46 100644
--- a/cli/internal/logger/logger.go
+++ b/cli/internal/logger/logger.go
@@ -1,36 +1,16 @@
-// Package logger provides logging configuration and access for the CLI.
-//
-// This package wraps charmbracelet/log to provide consistent logging across
-// the CLI. It supports configurable log levels and JSON output format for
-// machine parsing.
-//
-// # Setup
-//
-// Call Setup early in the application lifecycle:
-//
-// log.Setup(cmd.ErrOrStderr(), "debug", false) // debug level, text format
-// log.Setup(cmd.ErrOrStderr(), "info", true) // info level, JSON format
-//
-// # Usage
-//
-// log := logger.GetLogger()
-// log.Debug("detailed information")
-// log.Info("general information")
-// log.Error("error occurred")
+// Package logger configures shared CLI logging.
package logger
import (
"io"
charmlog "charm.land/log/v2"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
)
-// Setup configures the global logger with the specified level and format.
-// Valid log levels are: debug, info, warn, error, fatal.
-// If an invalid level is provided, it defaults to info.
-// When jsonFormat is true, logs are output as JSON for machine parsing.
+// Setup configures the global logger level and format, defaulting invalid levels to info.
func Setup(w io.Writer, level string, jsonFormat bool) {
lvl, err := charmlog.ParseLevel(level)
if err != nil {
@@ -42,11 +22,7 @@ func Setup(w io.Writer, level string, jsonFormat bool) {
log.SetOutput(output.CoordinatedWriter(w))
log.SetReportTimestamp(true)
- if jsonFormat {
- log.SetFormatter(charmlog.JSONFormatter)
- } else {
- log.SetFormatter(charmlog.TextFormatter)
- }
+ log.SetFormatter(kit.Ternary(jsonFormat, charmlog.JSONFormatter, charmlog.TextFormatter))
}
// GetLogger returns the global logger instance.
diff --git a/cli/internal/output/confirm.go b/cli/internal/output/confirm.go
index 3963ba980..93c3a5bae 100644
--- a/cli/internal/output/confirm.go
+++ b/cli/internal/output/confirm.go
@@ -13,32 +13,37 @@ import (
"github.com/muesli/cancelreader"
)
-// Confirm uses a terminal selector, falling back to line input for scripts.
+// Confirm requires terminal input, using a selector or line input depending on the output terminal.
func Confirm(ctx context.Context, input io.Reader, out io.Writer, label string) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
+ if !IsTerminal(input) {
+ return false, fmt.Errorf("confirmation required: re-run with --yes (%s)", label)
+ }
defer SuspendProgress()()
- if !IsTerminal(input) || !IsTerminal(out) {
+ if !IsTerminal(out) {
if _, err := fmt.Fprintf(out, "%s (y/N): ", strings.TrimSpace(label)); err != nil {
return false, err
}
- answer, err := ReadWithContext(ctx, input, func(r io.Reader) (string, error) {
- var answer string
- _, err := fmt.Fscanln(r, &answer)
- return answer, err
- })
+ answer, err := ReadWithContext(ctx, input, readLine)
if ctxErr := ctx.Err(); ctxErr != nil {
return false, ctxErr
}
if err != nil && !errors.Is(err, io.EOF) {
return false, fmt.Errorf("failed to read confirmation input: %w", err)
}
- return strings.EqualFold(answer, "y") || strings.EqualFold(answer, "yes"), nil
+ return strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes"), nil
}
model, err := tea.NewProgram(confirmModel{label: label, out: out}, tea.WithContext(ctx), tea.WithInput(input), tea.WithOutput(out)).Run()
- if promptErr := programErrInternal(ctx, err, "confirmation prompt"); promptErr != nil {
- return false, promptErr
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return false, ctxErr
+ }
+ if errors.Is(err, tea.ErrInterrupted) {
+ return false, context.Canceled
+ }
+ if err != nil {
+ return false, fmt.Errorf("confirmation prompt: %w", err)
}
result, ok := model.(confirmModel)
if !ok {
@@ -54,7 +59,7 @@ func Secret(ctx context.Context, input io.Reader, out io.Writer, label, flagName
return "", err
}
if !IsTerminal(input) {
- value, err := ReadWithContext(ctx, input, readLineInternal)
+ value, err := ReadWithContext(ctx, input, readLine)
if err != nil {
return "", err
}
@@ -69,8 +74,14 @@ func Secret(ctx context.Context, input io.Reader, out io.Writer, label, flagName
field.EchoMode = textinput.EchoPassword
field.Focus()
model, err := tea.NewProgram(secretModel{input: field}, tea.WithContext(ctx), tea.WithInput(input), tea.WithOutput(out)).Run()
- if promptErr := programErrInternal(ctx, err, "secret prompt"); promptErr != nil {
- return "", promptErr
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return "", ctxErr
+ }
+ if errors.Is(err, tea.ErrInterrupted) {
+ return "", context.Canceled
+ }
+ if err != nil {
+ return "", fmt.Errorf("secret prompt: %w", err)
}
result, ok := model.(secretModel)
if !ok {
@@ -83,24 +94,34 @@ func Secret(ctx context.Context, input io.Reader, out io.Writer, label, flagName
}
// ReadWithContext reads input until read returns or ctx is canceled.
-// Pipes, sockets and terminals are interrupted in place; regular files never
-// block; other readers fall back to readAsyncInternal.
+// Pollable files cancel in place; other blocking readers use an asynchronous read.
func ReadWithContext[T any](ctx context.Context, input io.Reader, read func(io.Reader) (T, error)) (T, error) {
var value T
var err, closeErr error
- mode, isFile := fileModeInternal(input)
- if isFile && mode.IsRegular() {
+ var mode os.FileMode
+ isFile := false
+ if file, ok := input.(interface{ Stat() (os.FileInfo, error) }); ok {
+ if info, statErr := file.Stat(); statErr == nil {
+ mode, isFile = info.Mode(), true
+ }
+ }
+ var reader cancelreader.CancelReader
+ if isFile && !mode.IsRegular() {
+ reader, _ = cancelreader.NewReader(input)
+ }
+ switch {
+ case isFile && mode.IsRegular():
// kqueue never reports a regular file readable at EOF, so poll nothing.
value, err = read(input)
- } else if reader := pollableReaderInternal(input, isFile); reader != nil {
+ case reader != nil:
stop := context.AfterFunc(ctx, func() { reader.Cancel() })
value, err = read(reader)
stop()
if releaseErr := reader.Close(); releaseErr != nil {
closeErr = fmt.Errorf("release input reader: %w", releaseErr)
}
- } else {
- value, err = readAsyncInternal(ctx, input, read)
+ default:
+ value, err = readAsync(ctx, input, read)
}
if ctxErr := ctx.Err(); ctxErr != nil {
var zero T
@@ -109,35 +130,8 @@ func ReadWithContext[T any](ctx context.Context, input io.Reader, read func(io.R
return value, errors.Join(err, closeErr)
}
-func fileModeInternal(input io.Reader) (os.FileMode, bool) {
- file, ok := input.(interface{ Stat() (os.FileInfo, error) })
- if !ok {
- return 0, false
- }
- info, err := file.Stat()
- if err != nil {
- return 0, false
- }
- return info.Mode(), true
-}
-
-// pollableReaderInternal wraps a non-regular file in a reader whose blocked
-// Read can be canceled, or returns nil when the platform cannot poll it.
-func pollableReaderInternal(input io.Reader, isFile bool) cancelreader.CancelReader {
- if !isFile {
- return nil
- }
- reader, err := cancelreader.NewReader(input)
- if err != nil {
- return nil
- }
- return reader
-}
-
-// readAsyncInternal serves readers that cannot be interrupted, such as an
-// embedder's io.Pipe. Cancellation stops waiting; the goroutine exits when the
-// caller-owned reader returns, which closing it forces.
-func readAsyncInternal[T any](ctx context.Context, input io.Reader, read func(io.Reader) (T, error)) (T, error) {
+// readAsync stops waiting on cancellation; its goroutine exits when input returns.
+func readAsync[T any](ctx context.Context, input io.Reader, read func(io.Reader) (T, error)) (T, error) {
type result struct {
value T
err error
@@ -156,9 +150,9 @@ func readAsyncInternal[T any](ctx context.Context, input io.Reader, read func(io
}
}
-// readLineInternal reads byte by byte so input after the newline stays
+// readLine reads byte by byte so input after the newline stays
// available to the next prompt.
-func readLineInternal(r io.Reader) (string, error) {
+func readLine(r io.Reader) (string, error) {
var line []byte
buf := make([]byte, 1)
for {
@@ -179,21 +173,6 @@ func readLineInternal(r io.Reader) (string, error) {
return strings.TrimSuffix(string(line), "\r"), nil
}
-// programErrInternal maps prompt cancellation, including Ctrl+C in raw mode,
-// to a context error.
-func programErrInternal(ctx context.Context, err error, name string) error {
- if ctx.Err() != nil {
- return ctx.Err()
- }
- if errors.Is(err, tea.ErrInterrupted) {
- return context.Canceled
- }
- if err != nil {
- return fmt.Errorf("%s: %w", name, err)
- }
- return nil
-}
-
type secretModel struct {
input textinput.Model
done, submitted bool
@@ -274,6 +253,6 @@ func (m confirmModel) View() tea.View {
} else {
no = "[ No ]"
}
- hint := renderForInternal(m.out, statusMutedStyle, "←/→ or tab: choose · enter: submit · esc: cancel")
- return tea.NewView("\n " + renderForInternal(m.out, headerStyle, m.label) + "\n\n " + no + " " + yes + "\n\n " + hint + "\n")
+ hint := renderFor(m.out, statusMutedStyle, "←/→ or tab: choose · enter: submit · esc: cancel")
+ return tea.NewView("\n " + renderFor(m.out, headerStyle, m.label) + "\n\n " + no + " " + yes + "\n\n " + hint + "\n")
}
diff --git a/cli/internal/output/output.go b/cli/internal/output/output.go
index 5dc6cf92f..7486d51d9 100644
--- a/cli/internal/output/output.go
+++ b/cli/internal/output/output.go
@@ -1,21 +1,11 @@
-// Package output provides formatted terminal output utilities for the CLI.
-//
-// This package offers consistent styling for success messages, errors, warnings,
-// informational text, headers, key-value pairs, and tables. All output includes
-// appropriate color coding for better readability in terminal environments.
-//
-// # Example Usage
-//
-// output.Success("Operation completed")
-// output.Warning("Something looks off: %v", err)
-// output.KeyValue("Status", "Running")
-// output.Table([]string{"ID", "Name"}, rows)
+// Package output provides styled messages and terminal tables for the CLI.
package output
import (
"fmt"
"image/color"
"regexp"
+ "slices"
"strings"
"charm.land/lipgloss/v2"
@@ -32,9 +22,9 @@ var (
tableHeader, tableCell, tableOddRow, tableEvenRow, tableBorder, tablePlainCell, tablePlainHead lipgloss.Style
)
-func init() { setThemeInternal(true) }
+func init() { setTheme(true) }
-func setThemeInternal(dark bool) {
+func setTheme(dark bool) {
c := lipgloss.LightDark(dark)
arcanePurple = c(lipgloss.Color("#6d28d9"), lipgloss.Color("#a78bfa"))
textPrimary = c(lipgloss.Color("#1f2937"), lipgloss.Color("#e5e7eb"))
@@ -67,85 +57,77 @@ var tableWhitespaceReplacer = strings.NewReplacer("\r\n", " ", "\n", " ", "\r",
var colorEnabled = true
-func shouldColorInternal() bool {
- return colorEnabledInternal() && IsTerminal(Stdout())
+func shouldColor() bool {
+ return colorsEnabled() && IsTerminal(Stdout())
}
-func renderInternal(style lipgloss.Style, value string) string {
- return renderForInternal(Stdout(), style, value)
+func render(style lipgloss.Style, value string) string {
+ return renderFor(humanWriter(), style, value)
}
// Success prints a success message in green.
-// The message is prefixed with a newline for visual separation.
-// Format specifiers and arguments work like fmt.Printf.
+// Format specifiers work like fmt.Printf; a leading newline separates messages.
//
//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separately
func Success(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(successStyle, "✓ "+msg))
+ _, _ = fmt.Fprintf(humanWriter(), "\n %s\n", render(successStyle, "✓ "+msg))
}
// Warning prints a warning message in yellow.
-// The message is prefixed with a newline for visual separation.
-// Format specifiers and arguments work like fmt.Printf.
+// Format specifiers work like fmt.Printf; a leading newline separates messages.
//
//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separately
func Warning(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stderr(), "\n %s\n", renderForInternal(Stderr(), warnStyle, msg))
+ _, _ = fmt.Fprintf(Stderr(), "\n %s\n", renderFor(Stderr(), warnStyle, msg))
}
// Info prints an info message in purple.
-// The message is prefixed with a newline for visual separation.
-// Format specifiers and arguments work like fmt.Printf.
+// Format specifiers work like fmt.Printf; a leading newline separates messages.
//
//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separately
func Info(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(infoStyle, msg))
+ _, _ = fmt.Fprintf(humanWriter(), "\n %s\n", render(infoStyle, msg))
}
// Header prints a purple section heading.
-// Use this to introduce sections of output. The message is prefixed
-// with a newline for visual separation.
+// A leading newline separates the heading from previous output.
//
//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separately
func Header(format string, a ...any) {
msg := fmt.Sprintf(format, a...)
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(headerStyle, msg))
+ _, _ = fmt.Fprintf(humanWriter(), "\n %s\n", render(headerStyle, msg))
}
// KeyValue prints a key-value pair with the muted aligned labels and neutral values.
-// This is useful for displaying structured information like image details
-// or configuration values.
+// Use it for structured details and configuration values.
func KeyValue(key string, value any) {
keyText := key
valueText := fmt.Sprint(value)
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stdout(), " %s %s\n", renderInternal(keyStyle, fmt.Sprintf("%-18s", keyText)), renderInternal(valueStyle, valueText))
+ _, _ = fmt.Fprintf(humanWriter(), " %s %s\n", render(keyStyle, fmt.Sprintf("%-18s", keyText)), render(valueStyle, valueText))
}
// Showing prints a pagination summary in the form "Showing: shown/total label".
func Showing(shown int, total int64, label string) {
defer SuspendProgress()()
- _, _ = fmt.Fprintf(Stdout(), "\n Showing: %d/%d %s\n", shown, total, label)
+ _, _ = fmt.Fprintf(humanWriter(), "\n Showing: %d/%d %s\n", shown, total, label)
}
-func hasAnsiInternal(s string) bool {
- if s == "" {
- return false
- }
+func hasAnsi(s string) bool {
return ansiRegexp.MatchString(s)
}
// TintStatus applies semantic status coloring to a value.
func TintStatus(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -166,7 +148,7 @@ func TintStatus(value string) string {
// TintEnabled applies tints for enabled/disabled values.
func TintEnabled(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -183,7 +165,7 @@ func TintEnabled(value string) string {
// TintYesNo applies tints for yes/no style values.
func TintYesNo(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -200,7 +182,7 @@ func TintYesNo(value string) string {
// TintInsecure applies warning tints for insecure values.
func TintInsecure(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -218,7 +200,7 @@ func TintInsecure(value string) string {
// Rendering uses Lip Gloss table styles with zebra-striped rows.
func Table(headers []string, rows [][]string) error {
defer SuspendProgress()()
- if _, spacingErr := fmt.Fprintln(Stdout()); spacingErr != nil {
+ if _, spacingErr := fmt.Fprintln(humanWriter()); spacingErr != nil {
return fmt.Errorf("failed to print table: %w", spacingErr)
}
@@ -227,13 +209,33 @@ func Table(headers []string, rows [][]string) error {
return nil
}
- rows = normalizeTableRowsInternal(rows, n)
- rows = tintTableRowsInternal(headers, rows)
- headers, rows = fitTableToTerminalInternal(headers, rows)
+ displayRows := make([][]string, len(rows))
+ for i, row := range rows {
+ displayRows[i] = make([]string, n)
+ copy(displayRows[i], row)
+ }
+ rows = displayRows
+ if shouldColor() {
+ for _, row := range rows {
+ for col, header := range headers {
+ switch strings.ToUpper(strings.TrimSpace(header)) {
+ case "STATUS", "STATE":
+ row[col] = TintStatus(row[col])
+ case "ENABLED":
+ row[col] = TintEnabled(row[col])
+ case "IN USE":
+ row[col] = TintYesNo(row[col])
+ case "INSECURE":
+ row[col] = TintInsecure(row[col])
+ }
+ }
+ }
+ }
+ headers, rows = fitTableToTerminal(headers, rows)
t := table.New().Border(lipgloss.NormalBorder()).Headers(headers...)
- if shouldColorInternal() {
+ if shouldColor() {
t = t.BorderStyle(tableBorder).
StyleFunc(func(row, col int) lipgloss.Style {
switch {
@@ -255,13 +257,13 @@ func Table(headers []string, rows [][]string) error {
t = t.Rows(rows...)
}
- if _, tableErr := fmt.Fprintln(Stdout(), t.String()); tableErr != nil {
+ if _, tableErr := fmt.Fprintln(humanWriter(), t.String()); tableErr != nil {
return fmt.Errorf("failed to print table: %w", tableErr)
}
return nil
}
-func fitTableToTerminalInternal(headers []string, rows [][]string) ([]string, [][]string) {
+func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]string) {
if len(headers) == 0 {
return headers, rows
}
@@ -269,19 +271,17 @@ func fitTableToTerminalInternal(headers []string, rows [][]string) ([]string, []
columnCount := len(headers)
displayHeaders := make([]string, columnCount)
for i, header := range headers {
- displayHeaders[i] = sanitizeTableCellInternal(header)
+ displayHeaders[i] = strings.TrimSpace(tableWhitespaceReplacer.Replace(header))
}
- displayRows := normalizeTableRowsInternal(rows, columnCount)
- for i, row := range displayRows {
- cleaned := make([]string, columnCount)
+ displayRows := rows
+ for _, row := range displayRows {
for col := range columnCount {
- cleaned[col] = sanitizeTableCellInternal(row[col])
+ row[col] = strings.TrimSpace(tableWhitespaceReplacer.Replace(row[col]))
}
- displayRows[i] = cleaned
}
- fd, ok := Stdout().(interface{ Fd() uintptr })
+ fd, ok := Stdout().(fileDescriptor)
if !ok || !term.IsTerminal(fd.Fd()) {
return displayHeaders, displayRows
}
@@ -293,49 +293,43 @@ func fitTableToTerminalInternal(headers []string, rows [][]string) ([]string, []
columnWidths := make([]int, columnCount)
for i, header := range displayHeaders {
- columnWidths[i] = max(1, visibleWidthInternal(header))
+ columnWidths[i] = max(1, visibleWidth(header))
}
for _, row := range displayRows {
for col := range columnCount {
- columnWidths[col] = max(columnWidths[col], visibleWidthInternal(row[col]))
+ columnWidths[col] = max(columnWidths[col], visibleWidth(row[col]))
}
}
- availableContentWidth := terminalWidth - tableNonContentWidthInternal(columnCount)
+ availableContentWidth := terminalWidth - (3*columnCount + 1)
if availableContentWidth <= 0 {
return displayHeaders, displayRows
}
- fitWidths := fitColumnWidthsInternal(columnWidths, availableContentWidth)
+ fitWidths := fitColumnWidths(columnWidths, availableContentWidth)
for i, header := range displayHeaders {
- displayHeaders[i] = truncateVisibleInternal(header, fitWidths[i])
+ displayHeaders[i] = truncateVisible(header, fitWidths[i])
}
- for i, row := range displayRows {
+ for _, row := range displayRows {
for col := range columnCount {
- row[col] = truncateVisibleInternal(row[col], fitWidths[col])
+ row[col] = truncateVisible(row[col], fitWidths[col])
}
- displayRows[i] = row
}
return displayHeaders, displayRows
}
-func sanitizeTableCellInternal(value string) string {
- cleaned := tableWhitespaceReplacer.Replace(value)
- return strings.TrimSpace(cleaned)
-}
-
-func visibleWidthInternal(value string) int {
+func visibleWidth(value string) int {
return runewidth.StringWidth(ansiRegexp.ReplaceAllString(value, ""))
}
-func truncateVisibleInternal(value string, maxWidth int) string {
+func truncateVisible(value string, maxWidth int) string {
if maxWidth <= 0 {
return ""
}
- if visibleWidthInternal(value) <= maxWidth {
+ if visibleWidth(value) <= maxWidth {
return value
}
@@ -345,10 +339,7 @@ func truncateVisibleInternal(value string, maxWidth int) string {
truncated = runewidth.Truncate(plain, maxWidth, "…")
}
- // Re-apply the cell's styling. Colour is written as a single leading escape
- // sequence plus a trailing reset, so measuring against the stripped text and
- // then returning it bare would leave truncated cells uncoloured while their
- // untruncated neighbours in the same column stay tinted.
+ // Preserve the leading color sequence and reset after truncation.
codes := ansiRegexp.FindAllString(value, -1)
if len(codes) == 0 || !strings.HasPrefix(value, codes[0]) {
return truncated
@@ -356,30 +347,26 @@ func truncateVisibleInternal(value string, maxWidth int) string {
return codes[0] + truncated + ansiReset
}
-func tableNonContentWidthInternal(columnCount int) int {
- const horizontalCellPadding = 2
-
- // For normal border style:
- // - one vertical border per boundary: columnCount + 1
- // - one space of left + right padding per cell: 2 * columnCount
- return (columnCount + 1) + (horizontalCellPadding * columnCount)
-}
-
-func fitColumnWidthsInternal(widths []int, available int) []int {
- fitted := make([]int, len(widths))
- copy(fitted, widths)
+func fitColumnWidths(widths []int, available int) []int {
+ fitted := slices.Clone(widths)
if len(fitted) == 0 {
return fitted
}
- if available < len(fitted) {
- available = len(fitted)
- }
+ available = max(available, len(fitted))
- current := sumIntsInternal(fitted)
+ current := 0
+ for _, width := range fitted {
+ current += width
+ }
for current > available {
- idx := widestShrinkableColumnInternal(fitted)
+ idx, maxWidth := -1, 1
+ for i, width := range fitted {
+ if width > maxWidth {
+ idx, maxWidth = i, width
+ }
+ }
if idx < 0 {
break
}
@@ -389,72 +376,3 @@ func fitColumnWidthsInternal(widths []int, available int) []int {
return fitted
}
-
-func widestShrinkableColumnInternal(widths []int) int {
- idx := -1
- maxWidth := 1
- for i, width := range widths {
- if width > maxWidth {
- idx = i
- maxWidth = width
- }
- }
- return idx
-}
-
-func sumIntsInternal(values []int) int {
- total := 0
- for _, value := range values {
- total += value
- }
- return total
-}
-
-func normalizeTableRowsInternal(rows [][]string, width int) [][]string {
- if width == 0 || len(rows) == 0 {
- return rows
- }
-
- normalized := make([][]string, len(rows))
- for i, row := range rows {
- cells := make([]string, width)
- copy(cells, row)
- normalized[i] = cells
- }
-
- return normalized
-}
-
-func tintTableRowsInternal(headers []string, rows [][]string) [][]string {
- if len(rows) == 0 {
- return rows
- }
- if !shouldColorInternal() {
- return rows
- }
-
- result := make([][]string, len(rows))
- for i, row := range rows {
- if len(row) == 0 {
- result[i] = row
- continue
- }
- styled := make([]string, len(row))
- copy(styled, row)
- for col := 0; col < len(row) && col < len(headers); col++ {
- header := strings.ToUpper(strings.TrimSpace(headers[col]))
- switch header {
- case "STATUS", "STATE":
- styled[col] = TintStatus(row[col])
- case "ENABLED":
- styled[col] = TintEnabled(row[col])
- case "IN USE":
- styled[col] = TintYesNo(row[col])
- case "INSECURE":
- styled[col] = TintInsecure(row[col])
- }
- }
- result[i] = styled
- }
- return result
-}
diff --git a/cli/internal/output/session.go b/cli/internal/output/session.go
index 2db74f421..76fd0b0e8 100644
--- a/cli/internal/output/session.go
+++ b/cli/internal/output/session.go
@@ -12,8 +12,14 @@ import (
"charm.land/lipgloss/v2"
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/x/term"
+ kit "go.getarcane.app/kit/pkg"
)
+// fileDescriptor supplies a writer's descriptor for terminal detection and sizing.
+type fileDescriptor interface {
+ Fd() uintptr
+}
+
var (
sessionMu sync.RWMutex
resultWriter io.Writer
@@ -30,7 +36,7 @@ func Configure(stdout, stderr io.Writer, jsonMode, noColor bool, label string) {
plainMode = jsonMode
colorEnabled = !noColor
commandLabel = label
- setThemeInternal(detectDarkBackgroundInternal(stdout, noColor))
+ setTheme(detectDarkBackground(stdout, noColor))
}
// Stdout returns the current command's result writer.
@@ -53,24 +59,32 @@ func Stderr() io.Writer {
return os.Stderr
}
+// humanWriter routes human-oriented output to stderr when stdout is reserved for JSON.
+func humanWriter() io.Writer {
+ sessionMu.RLock()
+ jsonMode := plainMode
+ sessionMu.RUnlock()
+ return kit.Ternary(jsonMode, Stderr(), Stdout())
+}
+
// IsTerminal checks the actual writer, including terminal capability.
func IsTerminal(value any) bool {
if writer, ok := value.(*colorprofile.Writer); ok {
value = writer.Forward
}
- fd, ok := value.(interface{ Fd() uintptr })
+ fd, ok := value.(fileDescriptor)
return ok && os.Getenv("TERM") != "dumb" && term.IsTerminal(fd.Fd())
}
-func colorEnabledInternal() bool {
+func colorsEnabled() bool {
sessionMu.RLock()
defer sessionMu.RUnlock()
_, noColor := os.LookupEnv("NO_COLOR")
return colorEnabled && !noColor
}
-func renderForInternal(w io.Writer, style lipgloss.Style, value string) string {
- if !colorEnabledInternal() || !IsTerminal(w) {
+func renderFor(w io.Writer, style lipgloss.Style, value string) string {
+ if !colorsEnabled() || !IsTerminal(w) {
return value
}
return style.Render(value)
@@ -102,10 +116,10 @@ func (w coordinatedWriter) Write(p []byte) (int, error) {
// WriteError renders the command error once through Fang's error handler.
func WriteError(w io.Writer, err error) {
defer SuspendProgress()()
- _, _ = fmt.Fprintf(w, "\n %s\n %s\n", renderForInternal(w, headerStyle.Foreground(statusOffline), "Error"), err.Error())
+ _, _ = fmt.Fprintf(w, "\n %s\n %s\n", renderFor(w, headerStyle.Foreground(statusOffline), "Error"), err.Error())
}
-func detectDarkBackgroundInternal(out io.Writer, noColor bool) bool {
+func detectDarkBackground(out io.Writer, noColor bool) bool {
if noColor || !IsTerminal(out) {
return true
}
diff --git a/cli/internal/output/transfer.go b/cli/internal/output/transfer.go
index 4d5a337ca..4fa492bbf 100644
--- a/cli/internal/output/transfer.go
+++ b/cli/internal/output/transfer.go
@@ -10,9 +10,8 @@ func Copy(ctx context.Context, dst io.Writer, src io.Reader, total int64, label
loading := StartTracker(ctx, Stderr(), enabled, label)
loading.NextStep()
defer loading.Stop()
- reader := &transferReader{ctx: ctx, source: src, loading: loading, total: total, label: label}
loading.SetProgress("", label, 0, total, true)
- written, err := io.Copy(dst, reader)
+ written, err := io.Copy(dst, &transferReader{ctx: ctx, source: src, loading: loading, total: total, label: label})
loading.Finish("", err)
return written, err
}
diff --git a/cli/internal/output/tui.go b/cli/internal/output/tui.go
index f55d2a17f..9bc28113d 100644
--- a/cli/internal/output/tui.go
+++ b/cli/internal/output/tui.go
@@ -62,7 +62,7 @@ func StartTracker(ctx context.Context, out io.Writer, enabled bool, labels ...st
if !t.live {
return t
}
- fd, hasFD := t.out.(interface{ Fd() uintptr })
+ fd, hasFD := t.out.(fileDescriptor)
t.stop, t.done = make(chan struct{}), make(chan struct{})
t.resumeOuter = SuspendProgress()
trackersMu.Lock()
@@ -110,7 +110,7 @@ func StartTracker(ctx context.Context, out io.Writer, enabled bool, labels ...st
icons := [...]string{stepPending: "○", stepRunning: spinnerFrames[t.frame%len(spinnerFrames)], stepSucceeded: "✓", stepFailed: "✗"}
styles := [...]lipgloss.Style{stepPending: statusMutedStyle, stepRunning: infoStyle, stepSucceeded: successStyle, stepFailed: statusOfflineStyle}
for _, step := range t.steps[start:] {
- line := " " + renderForInternal(t.out, styles[step.status], icons[step.status]) + " " + renderForInternal(t.out, valueStyle, step.label)
+ line := " " + renderFor(t.out, styles[step.status], icons[step.status]) + " " + renderFor(t.out, valueStyle, step.label)
if step.status == stepRunning && step.total > 0 {
current := min(step.current, step.total)
var count string
@@ -119,13 +119,13 @@ func StartTracker(ctx context.Context, out io.Writer, enabled bool, labels ...st
} else {
count = fmt.Sprintf("%d/%d", current, step.total)
}
- barWidth := min(24, max(width-visibleWidthInternal(step.label)-len(count)-7, 1))
+ barWidth := min(24, max(width-visibleWidth(step.label)-len(count)-7, 1))
bar := progress.New(progress.WithWidth(barWidth), progress.WithColors(arcanePurple))
- showColor := colorEnabledInternal()
+ showColor := colorsEnabled()
bar.FullColor = kit.Ternary(showColor, bar.FullColor, nil)
bar.EmptyColor = kit.Ternary(showColor, bar.EmptyColor, nil)
bar.PercentageStyle = kit.Ternary(showColor, bar.PercentageStyle, tablePlainCell.UnsetPadding())
- line = fmt.Sprintf(" %s %s %s", renderForInternal(t.out, infoStyle, step.label), bar.ViewAs(float64(current)/float64(step.total)), count)
+ line = fmt.Sprintf(" %s %s %s", renderFor(t.out, infoStyle, step.label), bar.ViewAs(float64(current)/float64(step.total)), count)
if !showColor {
line = ansi.Strip(line)
}
@@ -188,10 +188,7 @@ func (t *tracker) Finish(key string, err error) {
defer t.mu.Unlock()
for i := range t.steps {
if (key == "" && i == t.current) || (key != "" && t.steps[i].key == key) {
- t.steps[i].status = stepSucceeded
- if err != nil {
- t.steps[i].status = stepFailed
- }
+ t.steps[i].status = kit.Ternary(err != nil, stepFailed, stepSucceeded)
}
}
}
diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go
index e450c0c82..eae27f556 100644
--- a/cli/internal/prompt/prompt.go
+++ b/cli/internal/prompt/prompt.go
@@ -37,8 +37,7 @@ func Select(label string, options []string) (int, error) {
model.list.SetShowStatusBar(false)
model.list.SetFilteringEnabled(true)
model.list.SetShowHelp(true)
- program := tea.NewProgram(model)
- finalModel, err := program.Run()
+ finalModel, err := tea.NewProgram(model).Run()
if err != nil {
return -1, err
}
@@ -88,12 +87,7 @@ func (m selectModel) Init() tea.Cmd {
func (m selectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
- width := msg.Width
- height := max(msg.Height-4, 6)
- if width < 20 {
- width = 20
- }
- m.list.SetSize(width, height)
+ m.list.SetSize(max(msg.Width, 20), max(msg.Height-4, 6))
return m, nil
case tea.KeyPressMsg:
switch msg.String() {
diff --git a/cli/internal/runtime/context.go b/cli/internal/runtime/context.go
index 09905b257..f04e6e448 100644
--- a/cli/internal/runtime/context.go
+++ b/cli/internal/runtime/context.go
@@ -86,9 +86,6 @@ func (a *AppContext) Config() *types.Config {
return nil
}
copyCfg := a.cfg.Clone()
- if copyCfg == nil {
- return nil
- }
if id := cmp.Or(a.selectedEnv, a.EnvOverride); id != "" {
copyCfg.DefaultEnvironment = id
}
@@ -117,8 +114,7 @@ func (a *AppContext) Client() (*client.Client, error) {
return client.NewFromConfig()
}
a.clientOnce.Do(func() {
- cfg := a.Config()
- a.client, a.clientErr = client.New(cfg)
+ a.client, a.clientErr = client.New(a.Config())
if a.clientErr != nil {
return
}
@@ -134,8 +130,7 @@ func (a *AppContext) UnauthClient() (*client.Client, error) {
return client.NewFromConfigUnauthenticated()
}
a.unauthClientOnce.Do(func() {
- cfg := a.Config()
- a.unauthClient, a.unauthClientErr = client.NewUnauthenticated(cfg)
+ a.unauthClient, a.unauthClientErr = client.NewUnauthenticated(a.Config())
if a.unauthClientErr != nil {
return
}
diff --git a/cli/internal/testutil/cli.go b/cli/internal/testutil/cli.go
index e1c75a72f..e8d284077 100644
--- a/cli/internal/testutil/cli.go
+++ b/cli/internal/testutil/cli.go
@@ -10,8 +10,6 @@ import (
"sync"
"testing"
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
"github.com/stretchr/testify/require"
"github.com/getarcaneapp/arcane/cli/v2/pkg"
@@ -42,12 +40,11 @@ func WriteConfig(t *testing.T, serverURL string, preview ...bool) string {
return configPath
}
-// Execute runs the root command with isolated flags and captures its output.
+// Execute runs a freshly built root command and captures its output.
func Execute(t *testing.T, args []string) (string, string, error) {
t.Helper()
- root := cli.RootCommand()
- resetCommandFlags(t, root)
+ root := cli.NewRootCommand()
errOut := &strings.Builder{}
root.SetErr(errOut)
root.SetArgs(args)
@@ -82,25 +79,3 @@ func Execute(t *testing.T, args []string) (string, string, error) {
return outBuf, errOut.String(), runErr
}
-
-func resetCommandFlags(t *testing.T, root *cobra.Command) {
- t.Helper()
-
- if root == nil {
- return
- }
-
- for _, flagSet := range []*pflag.FlagSet{root.PersistentFlags(), root.Flags()} {
- flagSet.VisitAll(func(flag *pflag.Flag) {
- defValue := flag.DefValue
- if (flag.Value.Type() == "stringSlice" || flag.Value.Type() == "stringArray") && defValue == "[]" {
- defValue = ""
- }
- require.NoError(t, flag.Value.Set(defValue), "reset flag %s", flag.Name)
- flag.Changed = false
- })
- }
- for _, cmd := range root.Commands() {
- resetCommandFlags(t, cmd)
- }
-}
diff --git a/cli/internal/types/config.go b/cli/internal/types/config.go
index 28c9b09ac..6808a836c 100644
--- a/cli/internal/types/config.go
+++ b/cli/internal/types/config.go
@@ -143,10 +143,7 @@ func (c *Config) Clone() *Config {
return nil
}
out := *c
- if c.Pagination.Resources != nil {
- out.Pagination.Resources = make(map[string]PaginationResourceConfig, len(c.Pagination.Resources))
- maps.Copy(out.Pagination.Resources, c.Pagination.Resources)
- }
+ out.Pagination.Resources = maps.Clone(c.Pagination.Resources)
return &out
}
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index a7ee6ee08..fb9f8ead0 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -197,9 +197,7 @@ func UploadSessionChunk(envID, kind, uploadID string, index int) string {
// Image update endpoints
func ImageUpdatesCheck(envID, imageRef string) string {
- query := url.Values{}
- query.Set("imageRef", imageRef)
- return pathf("/api/environments/%s/image-updates/check", envID) + "?" + query.Encode()
+ return pathf("/api/environments/%s/image-updates/check", envID) + "?" + url.Values{"imageRef": {imageRef}}.Encode()
}
func ImageUpdatesCheckAll(envID string) string {
diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.go
index ae3b89e5d..a066ae758 100644
--- a/cli/pkg/activities/cmd.go
+++ b/cli/pkg/activities/cmd.go
@@ -5,295 +5,271 @@ package activities
import (
"cmp"
"fmt"
+ "net/http"
"net/url"
"strconv"
"strings"
"time"
- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
+ "github.com/getarcaneapp/arcane/types/v2/activity"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- statusFlag string
- typeFlag string
- resourceTypeFlag string
- messagesFlag int
-)
-
-// ActivitiesCmd is the parent command for background activity operations.
-var ActivitiesCmd = &cobra.Command{
- Use: "activities",
- Aliases: []string{"activity", "act"},
- Short: "Track background activities",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List background activities",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- query := url.Values{}
- if statusFlag != "" {
- query.Set("status", statusFlag)
- }
- if typeFlag != "" {
- query.Set("type", typeFlag)
- }
- if resourceTypeFlag != "" {
- query.Set("resourceType", resourceTypeFlag)
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[activitytypes.Activity]{
- Resource: "activities",
- Endpoint: types.Activities(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "activities", Limit: limitFlag, FallbackDefault: 50, Start: startFlag, All: allFlag},
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"ID", "TYPE", "STATUS", "RESOURCE", "STARTED", "PROGRESS", "MESSAGE"},
- Row: func(item activitytypes.Activity) []string {
- resource := ""
- if item.ResourceName != nil {
- resource = *item.ResourceName
- }
- if resource == "" && item.ResourceID != nil {
- resource = *item.ResourceID
- }
- if item.ResourceType != nil && *item.ResourceType != "" {
- if resource == "" {
- resource = *item.ResourceType
- } else {
- resource = *item.ResourceType + "/" + resource
- }
- }
- progress := "-"
- if item.Progress != nil {
- progress = strconv.Itoa(*item.Progress) + "%"
- }
- message := cmp.Or(item.LatestMessage, item.Step)
- if message == "" && item.Error != nil {
- message = *item.Error
- }
- return []string{
- item.ID,
- string(item.Type),
- string(item.Status),
- resource,
- item.StartedAt.Format(time.RFC3339),
- progress,
- message,
- }
- },
- })
- },
+// Command is the parent command for background activity operations.
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "activities",
+ Aliases: []string{"activity", "act"},
+ Short: "Track background activities",
+ }
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ cmd.AddCommand(newListCmd(), newGetCmd(), newCancelCmd(), newClearCmd())
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get <activity-id>",
- Short: "Get background activity details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := cmdutil.AppendQuery(
- types.Activity(c.EnvID(), args[0]),
- url.Values{"limit": []string{strconv.Itoa(messagesFlag)}},
- )
- result, err := c.GetJSON[activitytypes.Detail](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get activity: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ status activity.Status
+ activityType activity.Type
+ resourceType string
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List background activities",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- item := result.Data.Activity
- output.Header("Activity Details")
- output.KeyValue("ID", item.ID)
- output.KeyValue("Type", string(item.Type))
- output.KeyValue("Status", string(item.Status))
- resource := ""
- if item.ResourceName != nil {
- resource = *item.ResourceName
- }
- if resource == "" && item.ResourceID != nil {
- resource = *item.ResourceID
- }
- if item.ResourceType != nil && *item.ResourceType != "" {
- if resource == "" {
- resource = *item.ResourceType
- } else {
- resource = *item.ResourceType + "/" + resource
+ query := url.Values{}
+ if opts.status != "" {
+ query.Set("status", string(opts.status))
}
- }
- if resource != "" {
- output.KeyValue("Resource", resource)
- }
- if item.Progress != nil {
- output.KeyValue("Progress", strconv.Itoa(*item.Progress)+"%")
- }
- if item.Step != "" {
- output.KeyValue("Step", item.Step)
- }
- if item.StartedBy != nil {
- startedBy := item.StartedBy.Username
- if item.StartedBy.DisplayName != "" {
- startedBy = item.StartedBy.DisplayName
+ if opts.activityType != "" {
+ query.Set("type", string(opts.activityType))
}
- output.KeyValue("Started By", startedBy)
- }
- output.KeyValue("Started", item.StartedAt.Format(time.RFC3339))
- if item.EndedAt != nil {
- output.KeyValue("Ended", item.EndedAt.Format(time.RFC3339))
- }
- if item.DurationMs != nil {
- output.KeyValue("Duration", (time.Duration(*item.DurationMs) * time.Millisecond).String())
- }
- if item.Error != nil && *item.Error != "" {
- output.KeyValue("Error", *item.Error)
- }
-
- if len(result.Data.Messages) > 0 {
- output.Header("Messages")
- for _, msg := range result.Data.Messages {
- _, _ = fmt.Fprintf(output.Stdout(), "%s [%s] %s\n", msg.CreatedAt.Format(time.RFC3339), msg.Level, msg.Message)
+ if opts.resourceType != "" {
+ query.Set("resourceType", opts.resourceType)
}
- }
- return nil
- },
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[activity.Activity]{
+ Resource: "activities",
+ Endpoint: types.Activities(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "activities", Limit: opts.limit, FallbackDefault: 50, Start: opts.start, All: opts.all},
+ Query: query,
+ Headers: []string{"ID", "TYPE", "STATUS", "RESOURCE", "STARTED", "PROGRESS", "MESSAGE"},
+ Row: func(item activity.Activity) []string {
+ resource := resourceLabel(item)
+ progress := "-"
+ if item.Progress != nil {
+ progress = strconv.Itoa(*item.Progress) + "%"
+ }
+ return []string{
+ item.ID,
+ string(item.Type),
+ string(item.Status),
+ resource,
+ item.StartedAt.Format(time.RFC3339),
+ progress,
+ cmp.Or(item.LatestMessage, item.Step, kit.FromPtr(item.Error)),
+ }
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 50, "Number of activities to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.status, "status", "", "", "Filter by status",
+ activity.StatusQueued, activity.StatusRunning, activity.StatusSuccess, activity.StatusFailed, activity.StatusCancelled)
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.activityType, "type", "", "", "Filter by activity type",
+ activity.TypeJobRun, activity.TypeImagePull, activity.TypeImageBuild, activity.TypeImageUpdateCheck,
+ activity.TypeProjectPull, activity.TypeProjectBuild, activity.TypeProjectDeploy, activity.TypeProjectRedeploy,
+ activity.TypeProjectDown, activity.TypeProjectRestart, activity.TypeProjectDestroy, activity.TypeContainerStart,
+ activity.TypeContainerStop, activity.TypeContainerRestart, activity.TypeContainerRedeploy, activity.TypeContainerEdit,
+ activity.TypeContainerDelete, activity.TypeContainerKill, activity.TypeContainerPause, activity.TypeContainerUnpause,
+ activity.TypeVulnerabilityScan, activity.TypeImagePatch, activity.TypeAutoUpdate, activity.TypeSystemPrune,
+ activity.TypeResourceAction)
+ cmd.Flags().StringVar(&opts.resourceType, "resource-type", "", "Filter by resource type")
+ return cmd
}
-var cancelCmd = &cobra.Command{
- Use: "cancel <activity-id>",
- Short: "Cancel a running background activity",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to cancel activity %s?", args[0]))
+func newGetCmd() *cobra.Command {
+ var opts struct {
+ messages int
+ }
+ cmd := &cobra.Command{
+ Use: "get <activity-id>",
+ Short: "Get background activity details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.PostJSON[activitytypes.Activity](cmd.Context(), types.ActivityCancel(c.EnvID(), args[0]), nil)
- if err != nil {
- return fmt.Errorf("failed to cancel activity: %w", err)
- }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ path := cmdutil.AppendQuery(
+ types.Activity(c.EnvID(), args[0]),
+ url.Values{"limit": []string{strconv.Itoa(opts.messages)}},
+ )
+ return cmdutil.Run(cmd, c, cmdutil.Spec[activity.Detail]{
+ Method: http.MethodGet,
+ Path: path,
+ FailureMessage: "failed to get activity",
+ Render: func(data activity.Detail) error {
+ item := data.Activity
+ output.Header("Activity Details")
+ output.KeyValue("ID", item.ID)
+ output.KeyValue("Type", string(item.Type))
+ output.KeyValue("Status", string(item.Status))
+ resource := resourceLabel(item)
+ if resource != "" {
+ output.KeyValue("Resource", resource)
+ }
+ if item.Progress != nil {
+ output.KeyValue("Progress", strconv.Itoa(*item.Progress)+"%")
+ }
+ if item.Step != "" {
+ output.KeyValue("Step", item.Step)
+ }
+ if item.StartedBy != nil {
+ output.KeyValue("Started By", cmp.Or(item.StartedBy.DisplayName, item.StartedBy.Username))
+ }
+ output.KeyValue("Started", item.StartedAt.Format(time.RFC3339))
+ if item.EndedAt != nil {
+ output.KeyValue("Ended", item.EndedAt.Format(time.RFC3339))
+ }
+ if item.DurationMs != nil {
+ output.KeyValue("Duration", (time.Duration(*item.DurationMs) * time.Millisecond).String())
+ }
+ if item.Error != nil && *item.Error != "" {
+ output.KeyValue("Error", *item.Error)
+ }
- output.Success("Cancellation requested for activity %s (status: %s)", result.Data.ID, result.Data.Status)
- return nil
- },
+ if len(data.Messages) > 0 {
+ output.Header("Messages")
+ for _, msg := range data.Messages {
+ _, _ = fmt.Fprintf(output.Stdout(), "%s [%s] %s\n", msg.CreatedAt.Format(time.RFC3339), msg.Level, msg.Message)
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(activityRef, cmd)
+ cmd.Flags().IntVar(&opts.messages, "messages", 500, "Maximum output messages to return")
+ return cmd
}
-var clearCmd = &cobra.Command{
- Use: "clear",
- Short: "Clear finished activity history",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to clear the finished activity history?")
+func newCancelCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "cancel <activity-id>",
+ Short: "Cancel a running background activity",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ confirmed, confirmErr := cmdutil.ConfirmOrCancel(cmd, opts.force, fmt.Sprintf("Are you sure you want to cancel activity %s?", args[0]))
+ if confirmErr != nil || !confirmed {
+ return confirmErr
+ }
+
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.DeleteJSON[activitytypes.ClearHistoryResult](cmd.Context(), types.ActivitiesHistory(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to clear activity history: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Cleared %d finished activities", result.Data.Deleted)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[activity.Activity]{
+ Method: http.MethodPost,
+ Path: types.ActivityCancel(c.EnvID(), args[0]),
+ FailureMessage: "failed to cancel activity",
+ Render: func(data activity.Activity) error {
+ output.Success("Cancellation requested for activity %s (status: %s)", data.ID, data.Status)
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(activityRef, cmd)
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Cancel without confirmation")
+ return cmd
}
-func init() {
- cmdutil.SetResource(activityRef, getCmd, cancelCmd)
- cmdutil.SetScope(cmdutil.ScopeResource, ActivitiesCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, clearCmd)
- ActivitiesCmd.AddCommand(listCmd)
- ActivitiesCmd.AddCommand(getCmd)
- ActivitiesCmd.AddCommand(cancelCmd)
- ActivitiesCmd.AddCommand(clearCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 50, "Number of activities to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().StringVar(&statusFlag, "status", "", "Filter by status (queued, running, success, failed, cancelled)")
- listCmd.Flags().StringVar(&typeFlag, "type", "", "Filter by activity type (e.g. image_pull, project_deploy)")
- listCmd.Flags().StringVar(&resourceTypeFlag, "resource-type", "", "Filter by resource type")
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Get command flags
- getCmd.Flags().IntVar(&messagesFlag, "messages", 500, "Maximum output messages to return")
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newClearCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "clear",
+ Short: "Clear finished activity history",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ confirmed, confirmErr := cmdutil.ConfirmOrCancel(cmd, opts.force, "Are you sure you want to clear the finished activity history?")
+ if confirmErr != nil || !confirmed {
+ return confirmErr
+ }
- // Cancel command flags
- cancelCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Cancel without confirmation")
- cancelCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- // Clear command flags
- clearCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Clear without confirmation")
- clearCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[activity.ClearHistoryResult]{
+ Method: http.MethodDelete,
+ Path: types.ActivitiesHistory(c.EnvID()),
+ FailureMessage: "failed to clear activity history",
+ Render: func(data activity.ClearHistoryResult) error {
+ output.Success("Cleared %d finished activities", data.Deleted)
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Clear without confirmation")
+ return cmd
}
-var activityRef = cmdutil.ResourceRef[activitytypes.Detail, activitytypes.Activity]{
+var activityRef = cmdutil.ResourceRef[activity.Detail, activity.Activity]{
EnvironmentScoped: true,
Singular: "activity", Plural: "activities",
IDHint: "the identifier", ListCmd: "arcane-cli activities list",
GetPath: types.Activity, ListPath: types.Activities,
- Matches: func(item activitytypes.Activity, lower, original string) bool {
+ Matches: func(item activity.Activity, lower, original string) bool {
return strings.EqualFold(item.ID, original)
},
- Label: func(item activitytypes.Activity) string { return item.ID },
- Promote: func(item activitytypes.Activity) *activitytypes.Detail { return &activitytypes.Detail{Activity: item} },
+ IdentifierOf: func(item activity.Detail) string { return item.Activity.ID },
+ Label: func(item activity.Activity) string { return item.ID },
+ Promote: func(item activity.Activity) *activity.Detail { return &activity.Detail{Activity: item} },
+}
+
+func resourceLabel(item activity.Activity) string {
+ resource := cmp.Or(kit.FromPtr(item.ResourceName), kit.FromPtr(item.ResourceID))
+ resourceType := kit.FromPtr(item.ResourceType)
+ switch {
+ case resourceType == "":
+ return resource
+ case resource == "":
+ return resourceType
+ default:
+ return resourceType + "/" + resource
+ }
}
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index b9304a95e..3fff7a4bd 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -3,350 +3,304 @@ package apikeys
import (
"errors"
"fmt"
+ "net/http"
"strconv"
"strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/apikey"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-)
-
-var apikeyCreatePermissions []string
-
-var (
- apikeyUpdateName string
- apikeyUpdateDescription string
- apikeyUpdateExpiresAt string
- apikeyUpdatePermissions []string
-)
-
-// parsePermissionGrantsInternal turns `--permission` tokens into the wire-format
-// grant list. Each token is either `resource:action` (global grant) or
-// `resource:action:envId` (env-scoped grant). Anything else is an error so the
-// user catches typos before the server rejects them.
-// apiKeyUpdateBody mirrors apikey.UpdateApiKey but holds Permissions behind a
-// pointer. The shared type tags that field omitempty, so encoding/json drops an
-// empty slice — turning `--permission ""` (clear every grant) into a silent
-// no-op even though the server treats a non-nil empty list as "clear".
-type apiKeyUpdateBody struct {
- Name *string `json:"name,omitempty"`
- Description *string `json:"description,omitempty"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty"`
- Permissions *[]apikey.PermissionGrant `json:"permissions,omitempty"`
+// Command is the parent command for API key operations
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "api-keys",
+ Aliases: []string{"apikey", "key"},
+ Short: "Manage API keys",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newGetCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ return command
}
-func parsePermissionGrantsInternal(tokens []string) ([]apikey.PermissionGrant, error) {
- out := make([]apikey.PermissionGrant, 0, len(tokens))
- for _, raw := range tokens {
- token := strings.TrimSpace(raw)
- if token == "" {
- continue
- }
- parts := strings.Split(token, ":")
- switch len(parts) {
- case 2:
- out = append(out, apikey.PermissionGrant{Permission: token})
- case 3:
- env := parts[2]
- if parts[0] == "" || parts[1] == "" || env == "" {
- return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List API keys",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- out = append(out, apikey.PermissionGrant{
- Permission: parts[0] + ":" + parts[1],
- EnvironmentID: &env,
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[apikey.ApiKey]{
+ Resource: "API keys",
+ Endpoint: types.ApiKeys(),
+ Params: cmdutil.ListParams{Resource: "apikeys", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "DESCRIPTION", "PERMISSIONS", "CREATED", "LAST USED"},
+ Row: func(key apikey.ApiKey) []string {
+ lastUsed := "Never"
+ if key.LastUsedAt != nil {
+ lastUsed = key.LastUsedAt.Format("2006-01-02 15:04")
+ }
+ return []string{
+ key.ID,
+ key.Name,
+ kit.FromPtr(key.Description),
+ strconv.Itoa(len(key.Permissions)),
+ key.CreatedAt.Format("2006-01-02 15:04"),
+ lastUsed,
+ }
+ },
})
- default:
- return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)
- }
+ },
}
- return out, nil
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of API keys to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
}
-// ApiKeysCmd is the parent command for API key operations
-var ApiKeysCmd = &cobra.Command{
- Use: "api-keys",
- Aliases: []string{"apikey", "key"},
- Short: "Manage API keys",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List API keys",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ permissions []string
+ description string
+ expiresAt string
+ }
+ command := &cobra.Command{
+ Use: "create <name>",
+ Short: "Create a new API key",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[apikey.ApiKey]{
- Resource: "API keys",
- Endpoint: types.ApiKeys(),
- Params: cmdutil.ListParams{Resource: "apikeys", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "DESCRIPTION", "PERMISSIONS", "CREATED", "LAST USED"},
- Row: func(key apikey.ApiKey) []string {
- description := ""
- if key.Description != nil {
- description = *key.Description
- }
- lastUsed := "Never"
- if key.LastUsedAt != nil {
- lastUsed = key.LastUsedAt.Format("2006-01-02 15:04")
- }
- return []string{
- key.ID,
- key.Name,
- description,
- strconv.Itoa(len(key.Permissions)),
- key.CreatedAt.Format("2006-01-02 15:04"),
- lastUsed,
+ grants, grantsErr := permissionGrants(opts.permissions)
+ if grantsErr != nil {
+ return grantsErr
+ }
+ if len(grants) == 0 {
+ return errors.New("at least one --permission is required (e.g. --permission containers:list)")
+ }
+ var expiresAt *time.Time
+ if opts.expiresAt != "" {
+ parsed, parseErr := time.Parse(time.RFC3339, opts.expiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
}
- },
- })
- },
-}
-
-var createCmd = &cobra.Command{
- Use: "create <name>",
- Short: "Create a new API key",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- description, _ := cmd.Flags().GetString("description")
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- grants, err := parsePermissionGrantsInternal(apikeyCreatePermissions)
- if err != nil {
- return err
- }
- if len(grants) == 0 {
- return errors.New("at least one --permission is required (e.g. --permission containers:list)")
- }
- createReq := apikey.CreateApiKey{
- Name: args[0],
- Permissions: grants,
- }
- if description != "" {
- createReq.Description = &description
- }
- if expiresAtRaw, _ := cmd.Flags().GetString("expires-at"); expiresAtRaw != "" {
- parsed, parseErr := time.Parse(time.RFC3339, expiresAtRaw)
- if parseErr != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ expiresAt = &parsed
}
- createReq.ExpiresAt = &parsed
- }
-
- result, err := c.PostJSON[apikey.ApiKeyCreatedDto](cmd.Context(), types.ApiKeys(), createReq)
- if err != nil {
- return fmt.Errorf("failed to create API key: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("API key created successfully")
- output.Header("API Key Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Key", result.Data.Key)
- output.KeyValue("Created", result.Data.CreatedAt.Format("2006-01-02 15:04"))
- output.Warning("Store the token securely - it will not be shown again!")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[apikey.ApiKeyCreatedDto]{
+ Method: http.MethodPost,
+ Path: types.ApiKeys(),
+ FailureMessage: "failed to create API key",
+ Body: apikey.CreateApiKey{
+ Name: args[0],
+ Permissions: grants,
+ Description: kit.Ternary(opts.description != "", &opts.description, nil),
+ ExpiresAt: expiresAt,
+ },
+ Render: func(data apikey.ApiKeyCreatedDto) error {
+ output.Success("API key created successfully")
+ output.Header("API Key Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("Key", data.Key)
+ output.KeyValue("Created", data.CreatedAt.Format("2006-01-02 15:04"))
+ output.Warning("Store the token securely - it will not be shown again!")
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVarP(&opts.description, "description", "d", "", "Description for the API key")
+ command.Flags().StringVar(&opts.expiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
+ command.Flags().StringArrayVarP(&opts.permissions, "permission", "p", nil,
+ "Permission to grant as `resource:action[:envId]` (repeatable, required). Omit envId for a global grant. Cannot exceed your own permissions.")
+ _ = command.MarkFlagRequired("permission")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete API key",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete API key %s?", args[0]))
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete API key",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.ApiKey(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete API key: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("API key deleted successfully")
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete API key %s?", args[0]),
+ Path: types.ApiKey(args[0]),
+ FailureMessage: "failed to delete API key",
+ SuccessMessage: "API key deleted successfully",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
-var getCmd = &cobra.Command{
- Use: "get <id>",
- Short: "Get API key details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <id>",
+ Short: "Get API key details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.GetJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get API key: %w", err)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[apikey.ApiKey]{
+ Method: http.MethodGet,
+ Path: types.ApiKey(args[0]),
+ FailureMessage: "failed to get API key",
+ Render: func(data apikey.ApiKey) error {
+ output.Header("API Key Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ if data.Description != nil {
+ output.KeyValue("Description", *data.Description)
+ }
+ output.KeyValue("Key Prefix", data.KeyPrefix)
+ output.KeyValue("Created", data.CreatedAt.Format("2006-01-02 15:04"))
+ if data.LastUsedAt != nil {
+ output.KeyValue("Last Used", data.LastUsedAt.Format("2006-01-02 15:04"))
+ }
+ if data.ExpiresAt != nil {
+ output.KeyValue("Expires", data.ExpiresAt.Format("2006-01-02 15:04"))
+ }
+ output.KeyValue("Permissions", strconv.Itoa(len(data.Permissions)))
+ if len(data.Permissions) > 0 {
+ rows := make([][]string, len(data.Permissions))
+ for i, g := range data.Permissions {
+ scope := "global"
+ if g.EnvironmentID != nil {
+ scope = *g.EnvironmentID
+ }
+ rows[i] = []string{g.Permission, scope}
+ }
+ if tableErr := output.Table([]string{"PERMISSION", "SCOPE"}, rows); tableErr != nil {
+ return tableErr
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
+}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ description string
+ expiresAt string
+ permissions []string
+ }
+ command := &cobra.Command{
+ Use: "update <id>",
+ Short: "Update API key",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("API Key Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- if result.Data.Description != nil {
- output.KeyValue("Description", *result.Data.Description)
- }
- output.KeyValue("Key Prefix", result.Data.KeyPrefix)
- output.KeyValue("Created", result.Data.CreatedAt.Format("2006-01-02 15:04"))
- if result.Data.LastUsedAt != nil {
- output.KeyValue("Last Used", result.Data.LastUsedAt.Format("2006-01-02 15:04"))
- }
- if result.Data.ExpiresAt != nil {
- output.KeyValue("Expires", result.Data.ExpiresAt.Format("2006-01-02 15:04"))
- }
- output.KeyValue("Permissions", strconv.Itoa(len(result.Data.Permissions)))
- if len(result.Data.Permissions) > 0 {
- rows := make([][]string, len(result.Data.Permissions))
- for i, g := range result.Data.Permissions {
- scope := "global"
- if g.EnvironmentID != nil {
- scope = *g.EnvironmentID
+ var expiresAt *time.Time
+ var permissions []apikey.PermissionGrant
+ if cmd.Flags().Changed("expires-at") && opts.expiresAt != "" {
+ parsedTime, parseErr := time.Parse(time.RFC3339, opts.expiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid expires-at format (use RFC3339): %w", parseErr)
}
- rows[i] = []string{g.Permission, scope}
+ expiresAt = &parsedTime
}
- if tableErr := output.Table([]string{"PERMISSION", "SCOPE"}, rows); tableErr != nil {
- return tableErr
+ if cmd.Flags().Changed("permission") {
+ var grantsErr error
+ permissions, grantsErr = permissionGrants(opts.permissions)
+ if grantsErr != nil {
+ return grantsErr
+ }
}
- }
- return nil
- },
-}
-var updateCmd = &cobra.Command{
- Use: "update <id>",
- Short: "Update API key",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[apikey.ApiKey]{
+ Method: http.MethodPut,
+ Path: types.ApiKey(args[0]),
+ FailureMessage: "failed to update API key",
+ Body: apikey.UpdateApiKey{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ ExpiresAt: expiresAt,
+ Permissions: permissions,
+ },
+ Render: func(apikey.ApiKey) error {
+ output.Success("API key updated successfully")
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "API key name")
+ command.Flags().StringVarP(&opts.description, "description", "d", "", "API key description")
+ command.Flags().StringVar(&opts.expiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
+ command.Flags().StringArrayVarP(&opts.permissions, "permission", "p", nil,
+ "Replace the key's permission grants. Use `resource:action[:envId]` (repeatable). Pass --permission \"\" once to clear all grants.")
+ return command
+}
- var req apiKeyUpdateBody
- if cmd.Flags().Changed("name") {
- req.Name = &apikeyUpdateName
- }
- if cmd.Flags().Changed("description") {
- req.Description = &apikeyUpdateDescription
- }
- if cmd.Flags().Changed("expires-at") && apikeyUpdateExpiresAt != "" {
- parsedTime, parseErr := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)
- if parseErr != nil {
- return fmt.Errorf("invalid expires-at format (use RFC3339): %w", parseErr)
- }
- req.ExpiresAt = &parsedTime
- }
- if cmd.Flags().Changed("permission") {
- grants, parsePermissionGrantsErr := parsePermissionGrantsInternal(apikeyUpdatePermissions)
- if parsePermissionGrantsErr != nil {
- return parsePermissionGrantsErr
- }
- // Allow `--permission ""` once to clear all grants. Otherwise
- // the parsed slice replaces the key's permission set entirely.
- req.Permissions = &grants
+func permissionGrants(rawPermissions []string) ([]apikey.PermissionGrant, error) {
+ grants := make([]apikey.PermissionGrant, 0, len(rawPermissions))
+ for _, raw := range rawPermissions {
+ token := strings.TrimSpace(raw)
+ if token == "" {
+ continue
}
-
- result, err := c.PutJSON[apikey.ApiKey](cmd.Context(), types.ApiKey(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update API key: %w", err)
+ parts := strings.Split(token, ":")
+ if (len(parts) != 2 && len(parts) != 3) || parts[0] == "" || parts[1] == "" || (len(parts) == 3 && parts[2] == "") {
+ return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)
}
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
+ var environmentID *string
+ if len(parts) == 3 {
+ environmentID = new(parts[2])
}
-
- output.Success("API key updated successfully")
- return nil
- },
-}
-
-func init() {
- ApiKeysCmd.AddCommand(listCmd)
- ApiKeysCmd.AddCommand(createCmd)
- ApiKeysCmd.AddCommand(getCmd)
- ApiKeysCmd.AddCommand(updateCmd)
- ApiKeysCmd.AddCommand(deleteCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of API keys to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringP("description", "d", "", "Description for the API key")
- createCmd.Flags().String("expires-at", "", "Expiration date (RFC3339 format)")
- createCmd.Flags().StringArrayVarP(&apikeyCreatePermissions, "permission", "p", nil,
- "Permission to grant as `resource:action[:envId]` (repeatable, required). Omit envId for a global grant. Cannot exceed your own permissions.")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("permission")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Update command flags
- updateCmd.Flags().StringVar(&apikeyUpdateName, "name", "", "API key name")
- updateCmd.Flags().StringVarP(&apikeyUpdateDescription, "description", "d", "", "API key description")
- updateCmd.Flags().StringVar(&apikeyUpdateExpiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
- updateCmd.Flags().StringArrayVarP(&apikeyUpdatePermissions, "permission", "p", nil,
- "Replace the key's permission grants. Use `resource:action[:envId]` (repeatable). Pass --permission \"\" once to clear all grants.")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ grants = append(grants, apikey.PermissionGrant{
+ Permission: parts[0] + ":" + parts[1],
+ EnvironmentID: environmentID,
+ })
+ }
+ return grants, nil
}
diff --git a/cli/pkg/admin/cmd.go b/cli/pkg/admin/cmd.go
index 7700f2757..c8310e6a7 100644
--- a/cli/pkg/admin/cmd.go
+++ b/cli/pkg/admin/cmd.go
@@ -13,20 +13,20 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/pkg/backups"
)
-// AdminCmd is the parent command for administrative operations.
-var AdminCmd = &cobra.Command{
- Use: "admin",
- Aliases: []string{"adm"},
- Short: "Administration & platform management",
-}
-
-func init() {
- AdminCmd.AddCommand(backups.BackupsCmd)
- AdminCmd.AddCommand(users.UsersCmd)
- AdminCmd.AddCommand(roles.RolesCmd)
- AdminCmd.AddCommand(oidcmappings.OidcMappingsCmd)
- AdminCmd.AddCommand(apikeys.ApiKeysCmd)
- AdminCmd.AddCommand(federatedcredentials.FederatedCredentialsCmd)
- AdminCmd.AddCommand(events.EventsCmd)
- AdminCmd.AddCommand(notifications.NotificationsCmd)
+// Command is the parent command for administrative operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "admin",
+ Aliases: []string{"adm"},
+ Short: "Administration & platform management",
+ }
+ command.AddCommand(backups.Command())
+ command.AddCommand(users.Command())
+ command.AddCommand(roles.Command())
+ command.AddCommand(oidcmappings.Command())
+ command.AddCommand(apikeys.Command())
+ command.AddCommand(federatedcredentials.Command())
+ command.AddCommand(events.Command())
+ command.AddCommand(notifications.Command())
+ return command
}
diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.go
index 84482b709..cfe4cc155 100644
--- a/cli/pkg/admin/events/cmd.go
+++ b/cli/pkg/admin/events/cmd.go
@@ -2,160 +2,138 @@ package events
import (
"fmt"
+ "net/http"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/event"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- envOnlyFlag bool
-)
-
-// EventsCmd is the parent command for event operations
-var EventsCmd = &cobra.Command{
- Use: "events",
- Aliases: []string{"event", "evt"},
- Short: "Manage events",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List events",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- endpoint := types.Events()
- if envOnlyFlag {
- endpoint = types.EventsEnvironment(c.EnvID())
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[event.Event]{
- Resource: "events",
- Endpoint: endpoint,
- Params: cmdutil.ListParams{Resource: "events", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "TYPE", "RESOURCE", "USER", "TIMESTAMP"},
- Row: func(evt event.Event) []string {
- resource := ""
- if evt.ResourceName != nil && evt.ResourceType != nil {
- resource = fmt.Sprintf("%s (%s)", *evt.ResourceName, *evt.ResourceType)
- }
- username := ""
- if evt.Username != nil {
- username = *evt.Username
- }
- return []string{
- evt.ID,
- evt.Type,
- resource,
- username,
- evt.Timestamp.String(),
- }
- },
- })
- },
+// Command is the parent command for event operations
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "events",
+ Aliases: []string{"event", "evt"},
+ Short: "Manage events",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newDeleteCmd())
+ command.AddCommand(newStatsCmd())
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <event-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete event",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete event %s?", args[0]))
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ envOnly bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List events",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- if _, deleteEventErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Event(args[0])); deleteEventErr != nil {
- return fmt.Errorf("failed to delete event: %w", deleteEventErr)
- }
+ endpoint := types.Events()
+ if opts.envOnly {
+ endpoint = types.EventsEnvironment(c.EnvID())
+ }
- output.Success("Event deleted successfully")
- return nil
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[event.Event]{
+ Resource: "events",
+ Endpoint: endpoint,
+ Params: cmdutil.ListParams{Resource: "events", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "TYPE", "RESOURCE", "USER", "TIMESTAMP"},
+ Row: func(evt event.Event) []string {
+ resource := ""
+ if evt.ResourceName != nil && evt.ResourceType != nil {
+ resource = fmt.Sprintf("%s (%s)", *evt.ResourceName, *evt.ResourceType)
+ }
+ return []string{
+ evt.ID,
+ evt.Type,
+ resource,
+ kit.FromPtr(evt.Username),
+ evt.Timestamp.String(),
+ }
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, command)
+ command.Annotations["arcane:scope-flag"] = "environment"
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of events to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ command.Flags().BoolVar(&opts.envOnly, "environment", false, "Only list events for the current environment")
+ return command
}
-var statsCmd = &cobra.Command{
- Use: "stats",
- Short: "Show global event counts by severity",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // The severity counts DTO lives only in the backend's internal event
- // package, so mirror its wire shape here.
- result, err := c.GetJSON[struct {
- Total int64 `json:"total"`
- Info int64 `json:"info"`
- Success int64 `json:"success"`
- Warning int64 `json:"warning"`
- Error int64 `json:"error"`
- }](cmd.Context(), types.EventsStats())
- if err != nil {
- return fmt.Errorf("failed to get event stats: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Event Stats")
- output.KeyValue("Total", result.Data.Total)
- output.KeyValue("Info", result.Data.Info)
- output.KeyValue("Success", result.Data.Success)
- output.KeyValue("Warning", result.Data.Warning)
- output.KeyValue("Error", result.Data.Error)
- return nil
- },
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <event-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete event",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete event %s?", args[0]),
+ Path: types.Event(args[0]),
+ FailureMessage: "failed to delete event",
+ SuccessMessage: "Event deleted successfully",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd)
- listCmd.Annotations["arcane:scope-flag"] = "environment"
- EventsCmd.AddCommand(listCmd)
- EventsCmd.AddCommand(deleteCmd)
- EventsCmd.AddCommand(statsCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of events to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- listCmd.Flags().BoolVar(&envOnlyFlag, "environment", false, "Only list events for the current environment")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newStatsCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "stats",
+ Short: "Show global event counts by severity",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- statsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[event.SeverityCounts]{
+ Method: http.MethodGet,
+ Path: types.EventsStats(),
+ FailureMessage: "failed to get event stats",
+ Render: func(data event.SeverityCounts) error {
+ output.Header("Event Stats")
+ output.KeyValue("Total", data.Total)
+ output.KeyValue("Info", data.Info)
+ output.KeyValue("Success", data.Success)
+ output.KeyValue("Warning", data.Warning)
+ output.KeyValue("Error", data.Error)
+ return nil
+ },
+ })
+ },
+ }
}
diff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.go
index 2efdd1127..07607aa66 100644
--- a/cli/pkg/admin/federatedcredentials/cmd.go
+++ b/cli/pkg/admin/federatedcredentials/cmd.go
@@ -1,298 +1,308 @@
-// Package federatedcredentials provides the `arcane admin federated` command
-// tree. Federated credentials are workload identity federation trust rules:
-// an external OIDC token matching the rule is exchanged for a short-lived
-// Arcane access token backed by a dedicated service user.
+// Package federatedcredentials manages workload identity federation trust rules.
package federatedcredentials
import (
"cmp"
- "errors"
"fmt"
+ "net/http"
+ "strconv"
"time"
- "github.com/getarcaneapp/arcane/types/v2/base"
- federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"
+ "github.com/getarcaneapp/arcane/types/v2/federated"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- createName string
- createDescription string
- createDisabled bool
- createIssuerURL string
- createAudiences []string
- createSubjectClaim string
- createSubjectMatch string
- createMatchType string
- createRoleID string
- createEnvironment string
- createTokenTTL int
- createExpiresAt string
- updateName string
- updateDescription string
- updateEnabled bool
- updateDisabled bool
- updateIssuerURL string
- updateAudiences []string
- updateSubjectClaim string
- updateSubjectMatch string
- updateMatchType string
- updateRoleID string
- updateTokenTTL int
- updateExpiresAt string
-)
-
-// FederatedCredentialsCmd is the parent command for federated credential operations.
-var FederatedCredentialsCmd = &cobra.Command{
- Use: "federated",
- Aliases: []string{"fedcreds", "federated-credentials"},
- Short: "Manage workload identity federation trust rules",
+// Command is the parent command for federated credential operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "federated",
+ Aliases: []string{"fedcreds", "federated-credentials"},
+ Short: "Manage workload identity federation trust rules",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newGetCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ return command
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List federated credentials",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List federated credentials",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[federatedtypes.FederatedCredential]{
- Resource: "federated credentials",
- Endpoint: types.FederatedCredentials(),
- Params: cmdutil.ListParams{Resource: "federated-credentials", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "ISSUER", "SUBJECT", "ROLE", "ENABLED"},
- Row: func(cred federatedtypes.FederatedCredential) []string {
- role := cred.RoleName
- if role == "" {
- role = cred.RoleID
- }
- enabled := "false"
- if cred.Enabled {
- enabled = "true"
- }
- return []string{cred.ID, cred.Name, cred.IssuerURL, cred.SubjectMatch, role, enabled}
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[federated.FederatedCredential]{
+ Resource: "federated credentials",
+ Endpoint: types.FederatedCredentials(),
+ Params: cmdutil.ListParams{Resource: "federated-credentials", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "ISSUER", "SUBJECT", "ROLE", "ENABLED"},
+ Row: func(cred federated.FederatedCredential) []string {
+ return []string{cred.ID, cred.Name, cred.IssuerURL, cred.SubjectMatch, cmp.Or(cred.RoleName, cred.RoleID), strconv.FormatBool(cred.Enabled)}
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of federated credentials to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
}
-var getCmd = &cobra.Command{
- Use: "get <credential-id>",
- Short: "Get federated credential details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get federated credential: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <credential-id>",
+ Short: "Get federated credential details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- printCredentialInternal(result.Data)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[federated.FederatedCredential]{
+ Method: http.MethodGet,
+ Path: types.FederatedCredential(args[0]),
+ FailureMessage: "failed to get federated credential",
+ Render: func(data federated.FederatedCredential) error {
+ printCredential(data)
+ return nil
+ },
+ })
+ },
+ }
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a federated credential",
- Example: ` arcane admin federated create --name github-actions --issuer-url https://token.actions.githubusercontent.com \
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ description string
+ disabled bool
+ issuerURL string
+ audiences []string
+ subjectClaim string
+ subjectMatch string
+ matchType string
+ roleID string
+ environment string
+ tokenTTL int
+ expiresAt string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create a federated credential",
+ Example: ` arcane admin federated create --name github-actions --issuer-url https://token.actions.githubusercontent.com \
--audience arcane --subject-match "repo:myorg/*" --match-type glob --role role_deployer`,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := federatedtypes.CreateFederatedCredential{
- Name: createName,
- Enabled: !createDisabled,
- IssuerURL: createIssuerURL,
- Audiences: createAudiences,
- SubjectClaim: createSubjectClaim,
- SubjectMatch: createSubjectMatch,
- MatchType: createMatchType,
- RoleID: createRoleID,
- }
- if cmd.Flags().Changed("description") {
- req.Description = &createDescription
- }
- if cmd.Flags().Changed("environment") && createEnvironment != "" {
- req.EnvironmentID = new(createEnvironment)
- }
- if cmd.Flags().Changed("token-ttl") {
- req.TokenTTLSeconds = createTokenTTL
- }
- if createExpiresAt != "" {
- parsed, parseErr := time.Parse(time.RFC3339, createExpiresAt)
- if parseErr != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- req.ExpiresAt = &parsed
- }
- result, err := c.PostJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredentials(), req)
- if err != nil {
- return fmt.Errorf("failed to create federated credential: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ var expiresAt *time.Time
+ if opts.expiresAt != "" {
+ parsed, parseErr := time.Parse(time.RFC3339, opts.expiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ }
+ expiresAt = &parsed
+ }
- output.Success("Federated credential created")
- printCredentialInternal(result.Data)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[federated.FederatedCredential]{
+ Method: http.MethodPost,
+ Path: types.FederatedCredentials(),
+ FailureMessage: "failed to create federated credential",
+ Body: federated.CreateFederatedCredential{
+ Name: opts.name,
+ Enabled: !opts.disabled,
+ IssuerURL: opts.issuerURL,
+ Audiences: opts.audiences,
+ SubjectClaim: opts.subjectClaim,
+ SubjectMatch: opts.subjectMatch,
+ MatchType: opts.matchType,
+ RoleID: opts.roleID,
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ EnvironmentID: kit.Ternary(cmd.Flags().Changed("environment") && opts.environment != "", new(opts.environment), nil),
+ TokenTTLSeconds: kit.Ternary(cmd.Flags().Changed("token-ttl"), opts.tokenTTL, 0),
+ ExpiresAt: expiresAt,
+ },
+ Render: func(data federated.FederatedCredential) error {
+ output.Success("Federated credential created")
+ printCredential(data)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "Display name (required)")
+ command.Flags().StringVar(&opts.description, "description", "", "Description")
+ command.Flags().BoolVar(&opts.disabled, "disabled", false, "Create the trust rule in disabled state")
+ command.Flags().StringVar(&opts.issuerURL, "issuer-url", "", "Trusted external OIDC issuer URL (required)")
+ command.Flags().StringArrayVar(&opts.audiences, "audience", nil, "Allowed external token audience (repeatable, required)")
+ command.Flags().StringVar(&opts.subjectClaim, "subject-claim", "", "Claim path to match against (defaults to sub)")
+ command.Flags().StringVar(&opts.subjectMatch, "subject-match", "", "Exact subject or anchored glob pattern (required)")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.matchType, "match-type", "", "", "Subject match strategy",
+ federated.MatchTypeExact, federated.MatchTypeGlob)
+ command.Flags().StringVar(&opts.roleID, "role", "", "Role ID to map exchanged tokens to (required)")
+ command.Flags().StringVar(&opts.environment, "environment", "", "Scope the role assignment to one environment (omit for global)")
+ command.Flags().IntVar(&opts.tokenTTL, "token-ttl", 0, "Issued token lifetime in seconds (60-3600)")
+ command.Flags().StringVar(&opts.expiresAt, "expires-at", "", "Credential expiration (RFC3339 format)")
+ _ = command.MarkFlagRequired("name")
+ _ = command.MarkFlagRequired("issuer-url")
+ _ = command.MarkFlagRequired("audience")
+ _ = command.MarkFlagRequired("subject-match")
+ _ = command.MarkFlagRequired("role")
+ return command
}
-var updateCmd = &cobra.Command{
- Use: "update <credential-id>",
- Short: "Update a federated credential",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if cmd.Flags().Changed("enabled") && cmd.Flags().Changed("disabled") {
- return errors.New("--enabled and --disabled are mutually exclusive")
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ description string
+ enabled bool
+ disabled bool
+ issuerURL string
+ audiences []string
+ subjectClaim string
+ subjectMatch string
+ matchType string
+ roleID string
+ tokenTTL int
+ environment string
+ expiresAt string
+ }
+ command := &cobra.Command{
+ Use: "update <credential-id>",
+ Short: "Update a federated credential",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ PreRunE: func(cmd *cobra.Command, _ []string) error {
+ return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled")
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- var req federatedtypes.UpdateFederatedCredential
- if cmd.Flags().Changed("name") {
- req.Name = &updateName
- }
- if cmd.Flags().Changed("description") {
- req.Description = &updateDescription
- }
- if cmd.Flags().Changed("enabled") {
- req.Enabled = new(true)
- }
- if cmd.Flags().Changed("disabled") {
- req.Enabled = new(false)
- }
- if cmd.Flags().Changed("issuer-url") {
- req.IssuerURL = &updateIssuerURL
- }
- if cmd.Flags().Changed("audience") {
- req.Audiences = updateAudiences
- }
- if cmd.Flags().Changed("subject-claim") {
- req.SubjectClaim = &updateSubjectClaim
- }
- if cmd.Flags().Changed("subject-match") {
- req.SubjectMatch = &updateSubjectMatch
- }
- if cmd.Flags().Changed("match-type") {
- req.MatchType = &updateMatchType
- }
- if cmd.Flags().Changed("role") {
- req.RoleID = &updateRoleID
- }
- if cmd.Flags().Changed("environment") {
- env, _ := cmd.Flags().GetString("environment")
- if env != "" {
- req.EnvironmentID = &env
+ var environmentID *string
+ if cmd.Flags().Changed("environment") {
+ environmentID = kit.Ternary(opts.environment != "", &opts.environment, nil)
}
- }
- if cmd.Flags().Changed("token-ttl") {
- req.TokenTTLSeconds = &updateTokenTTL
- }
- if cmd.Flags().Changed("expires-at") && updateExpiresAt != "" {
- parsed, parseErr := time.Parse(time.RFC3339, updateExpiresAt)
- if parseErr != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ var expiresAt *time.Time
+ if cmd.Flags().Changed("expires-at") && opts.expiresAt != "" {
+ parsed, parseErr := time.Parse(time.RFC3339, opts.expiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ }
+ expiresAt = &parsed
}
- req.ExpiresAt = &parsed
- }
-
- result, err := c.PutJSON[federatedtypes.FederatedCredential](cmd.Context(), types.FederatedCredential(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update federated credential: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Federated credential updated")
- printCredentialInternal(result.Data)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[federated.FederatedCredential]{
+ Method: http.MethodPut,
+ Path: types.FederatedCredential(args[0]),
+ FailureMessage: "failed to update federated credential",
+ Body: federated.UpdateFederatedCredential{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled") || cmd.Flags().Changed("disabled"), new(opts.enabled && !opts.disabled), nil),
+ IssuerURL: kit.Ternary(cmd.Flags().Changed("issuer-url"), &opts.issuerURL, nil),
+ Audiences: kit.Ternary(cmd.Flags().Changed("audience"), opts.audiences, nil),
+ SubjectClaim: kit.Ternary(cmd.Flags().Changed("subject-claim"), &opts.subjectClaim, nil),
+ SubjectMatch: kit.Ternary(cmd.Flags().Changed("subject-match"), &opts.subjectMatch, nil),
+ MatchType: kit.Ternary(cmd.Flags().Changed("match-type"), &opts.matchType, nil),
+ RoleID: kit.Ternary(cmd.Flags().Changed("role"), &opts.roleID, nil),
+ EnvironmentID: environmentID,
+ TokenTTLSeconds: kit.Ternary(cmd.Flags().Changed("token-ttl"), &opts.tokenTTL, nil),
+ ExpiresAt: expiresAt,
+ },
+ Render: func(data federated.FederatedCredential) error {
+ output.Success("Federated credential updated")
+ printCredential(data)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "New display name")
+ command.Flags().StringVar(&opts.description, "description", "", "New description")
+ command.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable the trust rule")
+ command.Flags().BoolVar(&opts.disabled, "disabled", false, "Disable the trust rule")
+ _ = command.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ command.Flags().StringVar(&opts.issuerURL, "issuer-url", "", "New issuer URL")
+ command.Flags().StringArrayVar(&opts.audiences, "audience", nil, "Replace allowed audiences (repeatable)")
+ command.Flags().StringVar(&opts.subjectClaim, "subject-claim", "", "New claim path to match against")
+ command.Flags().StringVar(&opts.subjectMatch, "subject-match", "", "New subject match pattern")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.matchType, "match-type", "", "", "New match strategy",
+ federated.MatchTypeExact, federated.MatchTypeGlob)
+ command.Flags().StringVar(&opts.roleID, "role", "", "New role ID")
+ command.Flags().StringVar(&opts.environment, "environment", "", "New environment scope")
+ command.Flags().IntVar(&opts.tokenTTL, "token-ttl", 0, "New issued token lifetime in seconds (60-3600)")
+ command.Flags().StringVar(&opts.expiresAt, "expires-at", "", "New credential expiration (RFC3339 format)")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <credential-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a federated credential",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Delete federated credential %s and its service user?", args[0]))
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <credential-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a federated credential",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- if _, deleteCredentialErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.FederatedCredential(args[0])); deleteCredentialErr != nil {
- return fmt.Errorf("failed to delete federated credential: %w", deleteCredentialErr)
- }
-
- output.Success("Federated credential deleted")
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Delete federated credential %s and its service user?", args[0]),
+ Path: types.FederatedCredential(args[0]),
+ FailureMessage: "failed to delete federated credential",
+ SuccessMessage: "Federated credential deleted",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
-func printCredentialInternal(cred federatedtypes.FederatedCredential) {
+func printCredential(cred federated.FederatedCredential) {
output.KeyValue("ID", cred.ID)
output.KeyValue("Name", cred.Name)
if cred.Description != nil && *cred.Description != "" {
output.KeyValue("Description", *cred.Description)
}
- output.KeyValue("Enabled", cred.Enabled)
+ output.KeyValue("Enabled", strconv.FormatBool(cred.Enabled))
output.KeyValue("Issuer URL", cred.IssuerURL)
output.KeyValue("Audiences", cred.Audiences)
output.KeyValue("Subject claim", cred.SubjectClaim)
output.KeyValue("Subject match", cred.SubjectMatch)
output.KeyValue("Match type", cred.MatchType)
- role := cmp.Or(cred.RoleName, cred.RoleID)
- output.KeyValue("Role", role)
+ output.KeyValue("Role", cmp.Or(cred.RoleName, cred.RoleID))
scope := "global"
if cred.EnvironmentID != nil {
scope = *cred.EnvironmentID
@@ -312,54 +322,3 @@ func printCredentialInternal(cred federatedtypes.FederatedCredential) {
output.KeyValue("Expires", cred.ExpiresAt.Format("2006-01-02 15:04"))
}
}
-
-func init() {
- FederatedCredentialsCmd.AddCommand(listCmd)
- FederatedCredentialsCmd.AddCommand(getCmd)
- FederatedCredentialsCmd.AddCommand(createCmd)
- FederatedCredentialsCmd.AddCommand(updateCmd)
- FederatedCredentialsCmd.AddCommand(deleteCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of federated credentials to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&createName, "name", "", "Display name (required)")
- createCmd.Flags().StringVar(&createDescription, "description", "", "Description")
- createCmd.Flags().BoolVar(&createDisabled, "disabled", false, "Create the trust rule in disabled state")
- createCmd.Flags().StringVar(&createIssuerURL, "issuer-url", "", "Trusted external OIDC issuer URL (required)")
- createCmd.Flags().StringArrayVar(&createAudiences, "audience", nil, "Allowed external token audience (repeatable, required)")
- createCmd.Flags().StringVar(&createSubjectClaim, "subject-claim", "", "Claim path to match against (defaults to sub)")
- createCmd.Flags().StringVar(&createSubjectMatch, "subject-match", "", "Exact subject or anchored glob pattern (required)")
- createCmd.Flags().StringVar(&createMatchType, "match-type", "", "Subject match strategy: exact or glob")
- createCmd.Flags().StringVar(&createRoleID, "role", "", "Role ID to map exchanged tokens to (required)")
- createCmd.Flags().StringVar(&createEnvironment, "environment", "", "Scope the role assignment to one environment (omit for global)")
- createCmd.Flags().IntVar(&createTokenTTL, "token-ttl", 0, "Issued token lifetime in seconds (60-3600)")
- createCmd.Flags().StringVar(&createExpiresAt, "expires-at", "", "Credential expiration (RFC3339 format)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("issuer-url")
- _ = createCmd.MarkFlagRequired("audience")
- _ = createCmd.MarkFlagRequired("subject-match")
- _ = createCmd.MarkFlagRequired("role")
-
- updateCmd.Flags().StringVar(&updateName, "name", "", "New display name")
- updateCmd.Flags().StringVar(&updateDescription, "description", "", "New description")
- updateCmd.Flags().BoolVar(&updateEnabled, "enabled", false, "Enable the trust rule")
- updateCmd.Flags().BoolVar(&updateDisabled, "disabled", false, "Disable the trust rule")
- updateCmd.Flags().StringVar(&updateIssuerURL, "issuer-url", "", "New issuer URL")
- updateCmd.Flags().StringArrayVar(&updateAudiences, "audience", nil, "Replace allowed audiences (repeatable)")
- updateCmd.Flags().StringVar(&updateSubjectClaim, "subject-claim", "", "New claim path to match against")
- updateCmd.Flags().StringVar(&updateSubjectMatch, "subject-match", "", "New subject match pattern")
- updateCmd.Flags().StringVar(&updateMatchType, "match-type", "", "New match strategy: exact or glob")
- updateCmd.Flags().StringVar(&updateRoleID, "role", "", "New role ID")
- updateCmd.Flags().String("environment", "", "New environment scope")
- updateCmd.Flags().IntVar(&updateTokenTTL, "token-ttl", 0, "New issued token lifetime in seconds (60-3600)")
- updateCmd.Flags().StringVar(&updateExpiresAt, "expires-at", "", "New credential expiration (RFC3339 format)")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
-}
diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.go
index 29ab1e335..71c86d01a 100644
--- a/cli/pkg/admin/notifications/cmd.go
+++ b/cli/pkg/admin/notifications/cmd.go
@@ -9,7 +9,6 @@ import (
"strconv"
"strings"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/notification"
"github.com/spf13/cobra"
@@ -18,200 +17,216 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- jsonOutput bool
- notifForceFlag bool
-)
-
-// NotificationsCmd is the parent command for notification operations
-var NotificationsCmd = &cobra.Command{
- Use: "notifications",
- Aliases: []string{"notif", "notify"},
- Short: "Manage notifications",
-}
-
-var settingsCmd = &cobra.Command{
- Use: "settings",
- Short: "Manage notification settings",
+// Command is the parent command for notification operations
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "notifications",
+ Aliases: []string{"notif", "notify"},
+ Short: "Manage notifications",
+ }
+ cmdutil.SetScope(cmdutil.ScopeResource, command)
+ command.AddCommand(newSettingsCmd())
+ command.AddCommand(newTestProviderCmd())
+ return command
}
-var settingsGetCmd = &cobra.Command{
- Use: "get",
- Short: "Get notification settings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.DoJSON[[]notification.Response](cmd.Context(), http.MethodGet, types.NotificationsSettings(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to get settings: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
-
- headers := []string{"ID", "PROVIDER", "ENABLED"}
- rows := make([][]string, len(result))
- for i, setting := range result {
- rows[i] = []string{
- strconv.FormatUint(uint64(setting.ID), 10),
- string(setting.Provider),
- strconv.FormatBool(setting.Enabled),
- }
- }
-
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "notification settings"}); tableErr != nil {
- return tableErr
- }
- return nil
- },
+func newSettingsCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "settings",
+ Short: "Manage notification settings",
+ }
+ command.AddCommand(newSettingsGetCmd())
+ command.AddCommand(newSettingsSetCmd())
+ command.AddCommand(newSettingsDeleteCmd())
+ return command
}
-var settingsDeleteCmd = &cobra.Command{
- Use: "delete <provider>",
- Short: "Delete notification provider settings",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !notifForceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete notification settings for %s?", args[0]))
+func newSettingsGetCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "get",
+ Short: "Get notification settings",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ body, err := c.DoRaw(cmd.Context(), http.MethodGet, types.NotificationsSettings(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to get settings: %w", err)
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
+ }
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.NotificationSettingsProvider(c.EnvID(), args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete notification settings: %w", err)
- }
+ var result []notification.Response
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to get settings: %w", decodeErr)
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ headers := []string{"ID", "PROVIDER", "ENABLED"}
+ rows := make([][]string, len(result))
+ for i, setting := range result {
+ rows[i] = []string{
+ strconv.FormatUint(uint64(setting.ID), 10),
+ string(setting.Provider),
+ strconv.FormatBool(setting.Enabled),
+ }
+ }
- output.Success("Notification settings for %s deleted successfully", args[0])
- return nil
- },
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "notification settings"}); tableErr != nil {
+ return tableErr
+ }
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, command)
+ return command
}
-var (
- setProvider string
- setEnabled bool
- setConfig string
- setFile string
-)
-
-var settingsSetCmd = &cobra.Command{
- Use: "set",
- Short: "Create or update notification provider settings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- var req notification.Update
- if setFile != "" {
- data, err := os.ReadFile(setFile)
+func newSettingsDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <provider>",
+ Short: "Delete notification provider settings",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
- return fmt.Errorf("failed to read settings file: %w", err)
- }
- if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
- return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
- }
- }
-
- if cmd.Flags().Changed("provider") {
- req.Provider = notification.Provider(setProvider)
- }
- if cmd.Flags().Changed("enabled") {
- req.Enabled = setEnabled
- }
- if cmd.Flags().Changed("config") {
- if err := json.Unmarshal([]byte(setConfig), &req.Config); err != nil {
- return fmt.Errorf("failed to parse --config JSON: %w", err)
- }
- }
-
- if req.Provider == "" {
- return errors.New("provider is required (use --provider or --file)")
- }
- if req.Config == nil {
- return errors.New("config is required (use --config or --file)")
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.DoJSON[notification.Response](cmd.Context(), http.MethodPost, types.NotificationsSettings(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to save notification settings: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
-
- output.Success("Notification settings for %s saved successfully", result.Provider)
- output.KeyValue("ID", strconv.FormatUint(uint64(result.ID), 10))
- output.KeyValue("Enabled", strconv.FormatBool(result.Enabled))
- return nil
- },
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete notification settings for %s?", args[0]),
+ Path: types.NotificationSettingsProvider(c.EnvID(), args[0]),
+ FailureMessage: "failed to delete notification settings",
+ SuccessMessage: fmt.Sprintf("Notification settings for %s deleted successfully", args[0]),
+ })
+ },
+ }
+ cmdutil.SetResource(providerRef, command)
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
-var testProviderCmd = &cobra.Command{
- Use: "test <provider>",
- Short: "Test a notification provider",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- return cmdutil.RunPostAction[notification.TestResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.NotificationsTestProvider(c.EnvID(), args[0]),
- FailureMessage: "failed to test notification provider",
- SuccessMessage: fmt.Sprintf("Notification test for %s successful", args[0]),
- JSON: jsonOutput,
- })
- },
+func newSettingsSetCmd() *cobra.Command {
+ var opts struct {
+ provider notification.Provider
+ enabled bool
+ config string
+ file string
+ }
+ command := &cobra.Command{
+ Use: "set",
+ Short: "Create or update notification provider settings",
+ Example: " arcane admin notifications settings set --file provider.json\n" +
+ " arcane admin notifications settings set --provider generic --enabled --provider-config '{\"webhookUrl\":\"https://example.com/notify\"}'",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ var req notification.Update
+ if opts.file != "" {
+ data, err := os.ReadFile(opts.file)
+ if err != nil {
+ return fmt.Errorf("failed to read settings file: %w", err)
+ }
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
+ }
+ }
+
+ if cmd.Flags().Changed("provider") {
+ req.Provider = opts.provider
+ }
+ if cmd.Flags().Changed("enabled") {
+ req.Enabled = opts.enabled
+ }
+ if cmd.Flags().Changed("provider-config") || cmd.Flags().Changed("config") {
+ configFlag := "--config"
+ if cmd.Flags().Changed("provider-config") {
+ configFlag = "--provider-config"
+ }
+ if configErr := json.Unmarshal([]byte(opts.config), &req.Config); configErr != nil {
+ return fmt.Errorf("failed to parse %s JSON: %w", configFlag, configErr)
+ }
+ }
+
+ if req.Provider == "" {
+ return errors.New("provider is required (use --provider or --file)")
+ }
+ if req.Config == nil {
+ return errors.New("config is required (use --provider-config or --file)")
+ }
+
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ body, err := c.DoRaw(cmd.Context(), http.MethodPost, types.NotificationsSettings(c.EnvID()), req)
+ if err != nil {
+ return fmt.Errorf("failed to save notification settings: %w", err)
+ }
+
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
+ }
+
+ var result notification.Response
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to save notification settings: %w", decodeErr)
+ }
+ output.Success("Notification settings for %s saved successfully", result.Provider)
+ output.KeyValue("ID", strconv.FormatUint(uint64(result.ID), 10))
+ output.KeyValue("Enabled", strconv.FormatBool(result.Enabled))
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, command)
+ cmdutil.EnumVarP(command, command.Flags(), &opts.provider, "provider", "", "", "Notification provider",
+ notification.NotificationProviderDiscord, notification.NotificationProviderEmail, notification.NotificationProviderTelegram,
+ notification.NotificationProviderSignal, notification.NotificationProviderSlack, notification.NotificationProviderNtfy,
+ notification.NotificationProviderPushover, notification.NotificationProviderGotify, notification.NotificationProviderMatrix,
+ notification.NotificationProviderGoogleChat, notification.NotificationProviderGeneric)
+ command.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable the provider")
+ command.Flags().StringVar(&opts.config, "provider-config", "", "Provider configuration as a JSON object")
+ command.Flags().StringVar(&opts.config, "config", "", "Provider configuration as a JSON object")
+ _ = command.Flags().MarkDeprecated("config", "use --provider-config")
+ command.Flags().StringVar(&opts.file, "file", "", "Path to a JSON file with provider, enabled, and config fields")
+ return command
}
-func init() {
- cmdutil.SetResource(providerRef, settingsDeleteCmd, testProviderCmd)
- cmdutil.SetScope(cmdutil.ScopeResource, NotificationsCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, settingsGetCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, settingsSetCmd)
- NotificationsCmd.AddCommand(settingsCmd)
- NotificationsCmd.AddCommand(testProviderCmd)
-
- settingsCmd.AddCommand(settingsGetCmd)
- settingsCmd.AddCommand(settingsSetCmd)
- settingsCmd.AddCommand(settingsDeleteCmd)
-
- settingsGetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- settingsSetCmd.Flags().StringVar(&setProvider, "provider", "", "Notification provider (e.g. discord, email, telegram)")
- settingsSetCmd.Flags().BoolVar(&setEnabled, "enabled", false, "Enable the provider")
- settingsSetCmd.Flags().StringVar(&setConfig, "config", "", "Provider configuration as a JSON object")
- settingsSetCmd.Flags().StringVar(&setFile, "file", "", "Path to a JSON file with provider, enabled, and config fields")
- settingsSetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- settingsDeleteCmd.Flags().BoolVarP(&notifForceFlag, "force", "f", false, "Force deletion without confirmation")
- settingsDeleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- testProviderCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newTestProviderCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "test <provider>",
+ Short: "Test a notification provider",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[notification.TestResponse]{
+ Method: http.MethodPost,
+ Path: types.NotificationsTestProvider(c.EnvID(), args[0]),
+ FailureMessage: "failed to test notification provider",
+ Render: func(notification.TestResponse) error {
+ output.Success("%s", fmt.Sprintf("Notification test for %s successful", args[0]))
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(providerRef, command)
+ return command
}
var providerRef = cmdutil.ResourceRef[notification.Response, notification.Response]{
@@ -222,6 +237,7 @@ var providerRef = cmdutil.ResourceRef[notification.Response, notification.Respon
Matches: func(item notification.Response, lower, original string) bool {
return strings.EqualFold(string(item.Provider), original)
},
- Label: func(item notification.Response) string { return string(item.Provider) },
- Promote: func(item notification.Response) *notification.Response { return &item },
+ Label: func(item notification.Response) string { return string(item.Provider) },
+ Promote: func(item notification.Response) *notification.Response { return &item },
+ IdentifierOf: func(item notification.Response) string { return string(item.Provider) },
}
diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.go
index 49b0f815f..2cf8a7b83 100644
--- a/cli/pkg/admin/oidcmappings/cmd.go
+++ b/cli/pkg/admin/oidcmappings/cmd.go
@@ -1,245 +1,202 @@
-// Package oidcmappings provides the `arcane admin oidc-mappings` command tree.
-// Mappings convert OIDC group/claim values into role assignments on every
-// login — they're the SSO-driven counterpart to manual role assignments.
+// Package oidcmappings manages OIDC claim-to-role mappings.
package oidcmappings
import (
"fmt"
+ "net/http"
+ "slices"
- roletypes "github.com/getarcaneapp/arcane/types/v2/role"
+ "github.com/getarcaneapp/arcane/types/v2/role"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- forceFlag bool
- jsonOutput bool
-)
-
-var (
- createClaim string
- createRoleID string
- createEnvironment string
-)
-
-var (
- updateClaim string
- updateRoleID string
- updateEnvironment string
-)
-
-// OidcMappingsCmd is the parent command for OIDC role mapping operations.
-var OidcMappingsCmd = &cobra.Command{
- Use: "oidc",
- Aliases: []string{"oidc-mappings", "oidc-mapping"},
- Short: "Manage OIDC group → role mappings",
- Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane looks up the user's groups claim and applies " +
- "the matching mappings as source='oidc' role assignments. The groups claim itself is configured via the " +
- "oidcGroupsClaim setting (default `groups`).",
+// Command is the parent command for OIDC role mapping operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "oidc",
+ Aliases: []string{"oidc-mappings", "oidc-mapping"},
+ Short: "Manage OIDC group → role mappings",
+ Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane looks up the user's groups claim and applies " +
+ "the matching mappings as source='oidc' role assignments. The groups claim itself is configured via the " +
+ "oidcGroupsClaim setting (default `groups`).",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ return command
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List OIDC role mappings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())
- if err != nil {
- return fmt.Errorf("failed to list OIDC mappings: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- if len(result.Data) == 0 {
- output.Info("No OIDC role mappings configured")
- return nil
- }
-
- headers := []string{"ID", "CLAIM VALUE", "ROLE", "SCOPE"}
- rows := make([][]string, len(result.Data))
- for i, m := range result.Data {
- scope := "global"
- if m.EnvironmentID != nil {
- scope = *m.EnvironmentID
+func newListCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List OIDC role mappings",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- rows[i] = []string{m.ID, m.ClaimValue, m.RoleID, scope}
- }
- return output.Table(headers, rows)
- },
-}
-
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create an OIDC role mapping",
- Example: ` arcane admin oidc-mappings create --claim docker-admins --role role_admin`,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- req := roletypes.CreateOidcRoleMapping{
- ClaimValue: createClaim,
- RoleID: createRoleID,
- }
- if cmd.Flags().Changed("environment") && createEnvironment != "" {
- req.EnvironmentID = new(createEnvironment)
- }
-
- result, err := c.PostJSON[roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings(), req)
- if err != nil {
- return fmt.Errorf("failed to create OIDC mapping: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("OIDC mapping created")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Claim value", result.Data.ClaimValue)
- output.KeyValue("Role", result.Data.RoleID)
- scope := "global"
- if result.Data.EnvironmentID != nil {
- scope = *result.Data.EnvironmentID
- }
- output.KeyValue("Scope", scope)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]role.OidcRoleMapping]{
+ Method: http.MethodGet,
+ Path: types.OidcRoleMappings(),
+ FailureMessage: "failed to list OIDC mappings",
+ Render: func(data []role.OidcRoleMapping) error {
+ if len(data) == 0 {
+ output.Info("No OIDC role mappings configured")
+ return nil
+ }
+
+ headers := []string{"ID", "CLAIM VALUE", "ROLE", "SCOPE"}
+ rows := make([][]string, len(data))
+ for i, m := range data {
+ scope := "global"
+ if m.EnvironmentID != nil {
+ scope = *m.EnvironmentID
+ }
+ rows[i] = []string{m.ID, m.ClaimValue, m.RoleID, scope}
+ }
+ return output.Table(headers, rows)
+ },
+ })
+ },
+ }
}
-var updateCmd = &cobra.Command{
- Use: "update <mapping-id>",
- Short: "Update an OIDC role mapping",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // The PUT contract requires every field — fetch current and overlay.
- current, err := fetchMappingInternal(cmd, args[0])
- if err != nil {
- return err
- }
-
- req := roletypes.UpdateOidcRoleMapping{
- ClaimValue: current.ClaimValue,
- RoleID: current.RoleID,
- EnvironmentID: current.EnvironmentID,
- }
- if cmd.Flags().Changed("claim") {
- req.ClaimValue = updateClaim
- }
- if cmd.Flags().Changed("role") {
- req.RoleID = updateRoleID
- }
- if cmd.Flags().Changed("environment") {
- if updateEnvironment == "" {
- // Empty value flips an env-scoped mapping back to global.
- req.EnvironmentID = nil
- } else {
- req.EnvironmentID = new(updateEnvironment)
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ claim string
+ roleID string
+ environment string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create an OIDC role mapping",
+ Example: ` arcane admin oidc-mappings create --claim docker-admins --role role_admin`,
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
-
- resp, err := c.Put(cmd.Context(), types.OidcRoleMapping(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update OIDC mapping: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to update OIDC mapping: %w", ensureSuccessStatusErr)
- }
- output.Success("OIDC mapping updated")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.OidcRoleMapping]{
+ Method: http.MethodPost,
+ Path: types.OidcRoleMappings(),
+ FailureMessage: "failed to create OIDC mapping",
+ Body: role.CreateOidcRoleMapping{
+ ClaimValue: opts.claim,
+ RoleID: opts.roleID,
+ EnvironmentID: kit.Ternary(cmd.Flags().Changed("environment") && opts.environment != "", new(opts.environment), nil),
+ },
+ Render: func(data role.OidcRoleMapping) error {
+ output.Success("OIDC mapping created")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Claim value", data.ClaimValue)
+ output.KeyValue("Role", data.RoleID)
+ scope := "global"
+ if data.EnvironmentID != nil {
+ scope = *data.EnvironmentID
+ }
+ output.KeyValue("Scope", scope)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.claim, "claim", "", "OIDC claim value (required)")
+ command.Flags().StringVar(&opts.roleID, "role", "", "Role ID to grant when the claim matches (required)")
+ command.Flags().StringVar(&opts.environment, "environment", "", "Scope the grant to one environment (omit for global)")
+ _ = command.MarkFlagRequired("claim")
+ _ = command.MarkFlagRequired("role")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <mapping-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete an OIDC role mapping",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Delete OIDC mapping %s?", args[0]))
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ claim string
+ roleID string
+ environment string
+ }
+ command := &cobra.Command{
+ Use: "update <mapping-id>",
+ Short: "Update an OIDC role mapping",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ // The PUT contract requires every field — fetch current and overlay.
+ mappings, err := c.GetJSON[[]role.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())
+ if err != nil {
+ return fmt.Errorf("failed to load current mapping: %w", err)
+ }
+ index := slices.IndexFunc(mappings.Data, func(mapping role.OidcRoleMapping) bool { return mapping.ID == args[0] })
+ if index < 0 {
+ return fmt.Errorf("OIDC mapping %q not found", args[0])
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resp, err := c.Delete(cmd.Context(), types.OidcRoleMapping(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete OIDC mapping: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete OIDC mapping: %w", ensureSuccessStatusErr)
- }
- output.Success("OIDC mapping deleted")
- return nil
- },
-}
+ current := mappings.Data[index]
-// fetchMappingInternal looks a mapping up by ID. The API registers only PUT and
-// DELETE on /oidc/role-mappings/{id} — a GET there is a 405 — so this filters
-// the list instead.
-func fetchMappingInternal(cmd *cobra.Command, id string) (*roletypes.OidcRoleMapping, error) {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return nil, err
- }
- result, err := c.GetJSON[[]roletypes.OidcRoleMapping](cmd.Context(), types.OidcRoleMappings())
- if err != nil {
- return nil, fmt.Errorf("failed to load current mapping: %w", err)
- }
- for i := range result.Data {
- if result.Data[i].ID == id {
- return &result.Data[i], nil
- }
+ environmentID := current.EnvironmentID
+ if cmd.Flags().Changed("environment") {
+ environmentID = kit.Ternary(opts.environment == "", nil, new(opts.environment))
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.OidcRoleMapping]{
+ Method: http.MethodPut,
+ Path: types.OidcRoleMapping(args[0]),
+ Body: role.UpdateOidcRoleMapping{
+ ClaimValue: kit.Ternary(cmd.Flags().Changed("claim"), opts.claim, current.ClaimValue),
+ RoleID: kit.Ternary(cmd.Flags().Changed("role"), opts.roleID, current.RoleID),
+ EnvironmentID: environmentID,
+ },
+ FailureMessage: "failed to update OIDC mapping",
+ Render: func(role.OidcRoleMapping) error {
+ output.Success("OIDC mapping updated")
+ return nil
+ },
+ })
+ },
}
- return nil, fmt.Errorf("OIDC mapping %q not found", id)
+ command.Flags().StringVar(&opts.claim, "claim", "", "New claim value")
+ command.Flags().StringVar(&opts.roleID, "role", "", "New role ID")
+ command.Flags().StringVar(&opts.environment, "environment", "", "New environment scope (pass empty to make global)")
+ return command
}
-func init() {
- OidcMappingsCmd.AddCommand(listCmd)
- OidcMappingsCmd.AddCommand(createCmd)
- OidcMappingsCmd.AddCommand(updateCmd)
- OidcMappingsCmd.AddCommand(deleteCmd)
-
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&createClaim, "claim", "", "OIDC claim value (required)")
- createCmd.Flags().StringVar(&createRoleID, "role", "", "Role ID to grant when the claim matches (required)")
- createCmd.Flags().StringVar(&createEnvironment, "environment", "", "Scope the grant to one environment (omit for global)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("claim")
- _ = createCmd.MarkFlagRequired("role")
-
- updateCmd.Flags().StringVar(&updateClaim, "claim", "", "New claim value")
- updateCmd.Flags().StringVar(&updateRoleID, "role", "", "New role ID")
- updateCmd.Flags().StringVar(&updateEnvironment, "environment", "", "New environment scope (pass empty to make global)")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <mapping-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete an OIDC role mapping",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Delete OIDC mapping %s?", args[0]),
+ Path: types.OidcRoleMapping(args[0]),
+ FailureMessage: "failed to delete OIDC mapping",
+ SuccessMessage: "OIDC mapping deleted",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.go
index 17fb03084..cd7f38b3c 100644
--- a/cli/pkg/admin/roles/cmd.go
+++ b/cli/pkg/admin/roles/cmd.go
@@ -1,431 +1,368 @@
-// Package roles provides the `arcane admin roles` command tree for RBAC.
-// Roles are named permission sets that can be granted to users (globally or
-// per-environment) and to API keys. Four built-in roles (Admin, Editor,
-// Deployer, Viewer) ship with Arcane and cannot be modified; everything else
-// is a custom role created via this command.
+// Package roles manages roles and user assignments.
package roles
import (
"errors"
"fmt"
+ "net/http"
"strconv"
"strings"
- roletypes "github.com/getarcaneapp/arcane/types/v2/role"
+ "github.com/getarcaneapp/arcane/types/v2/role"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-)
-
-var (
- roleCreateName string
- roleCreateDescription string
- roleCreatePermissions []string
-)
-
-var (
- roleUpdateName string
- roleUpdateDescription string
- roleUpdatePermissions []string
-)
-
-// `assign` flags. Each --role argument is parsed as `<roleId>[:<envId>]`.
-// Omitting the env id gives a global assignment.
-var (
- assignRoles []string
-)
-
-// RolesCmd is the parent command for role operations.
-var RolesCmd = &cobra.Command{
- Use: "roles",
- Aliases: []string{"role"},
- Short: "Manage roles and per-user role assignments",
+// Command is the parent command for role operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "roles",
+ Aliases: []string{"role"},
+ Short: "Manage roles and per-user role assignments",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newGetCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ command.AddCommand(newPermissionsCmd())
+ command.AddCommand(newAssignmentsCmd())
+ command.AddCommand(newAssignCmd())
+ return command
}
// ---------- Role CRUD ----------
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List roles",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List roles",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[roletypes.Role]{
- Resource: "roles",
- Endpoint: types.Roles(),
- Params: cmdutil.ListParams{Resource: "roles", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "TYPE", "USERS", "PERMISSIONS"},
- Row: func(r roletypes.Role) []string {
- roleType := "custom"
- if r.BuiltIn {
- roleType = "built-in"
- }
- return []string{
- r.ID,
- r.Name,
- roleType,
- strconv.Itoa(r.AssignedUserCount),
- strconv.Itoa(len(r.Permissions)),
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[role.Role]{
+ Resource: "roles",
+ Endpoint: types.Roles(),
+ Params: cmdutil.ListParams{Resource: "roles", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "TYPE", "USERS", "PERMISSIONS"},
+ Row: func(r role.Role) []string {
+ return []string{
+ r.ID,
+ r.Name,
+ kit.Ternary(r.BuiltIn, "built-in", "custom"),
+ strconv.Itoa(r.AssignedUserCount),
+ strconv.Itoa(len(r.Permissions)),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of roles to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
}
-var getCmd = &cobra.Command{
- Use: "get <role-id>",
- Short: "Get role details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get role: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Role Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- if result.Data.Description != nil {
- output.KeyValue("Description", *result.Data.Description)
- }
- output.KeyValue("Built-in", strconv.FormatBool(result.Data.BuiltIn))
- output.KeyValue("Assigned users", strconv.Itoa(result.Data.AssignedUserCount))
- output.KeyValue("Permissions", strconv.Itoa(len(result.Data.Permissions)))
- if len(result.Data.Permissions) > 0 {
- rows := make([][]string, len(result.Data.Permissions))
- for i, p := range result.Data.Permissions {
- rows[i] = []string{p}
- }
- if tableErr := output.Table([]string{"PERMISSION"}, rows); tableErr != nil {
- return tableErr
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <role-id>",
+ Short: "Get role details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.Role]{
+ Method: http.MethodGet,
+ Path: types.Role(args[0]),
+ FailureMessage: "failed to get role",
+ Render: func(data role.Role) error {
+ output.Header("Role Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ if data.Description != nil {
+ output.KeyValue("Description", *data.Description)
+ }
+ output.KeyValue("Built-in", strconv.FormatBool(data.BuiltIn))
+ output.KeyValue("Assigned users", strconv.Itoa(data.AssignedUserCount))
+ output.KeyValue("Permissions", strconv.Itoa(len(data.Permissions)))
+ if len(data.Permissions) > 0 {
+ rows := make([][]string, len(data.Permissions))
+ for i, p := range data.Permissions {
+ rows[i] = []string{p}
+ }
+ if tableErr := output.Table([]string{"PERMISSION"}, rows); tableErr != nil {
+ return tableErr
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a custom role",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if roleCreateName == "" {
- return errors.New("--name is required")
- }
- if len(roleCreatePermissions) == 0 {
- return errors.New("at least one --permission is required")
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := roletypes.CreateRole{
- Name: roleCreateName,
- Permissions: roleCreatePermissions,
- }
- if cmd.Flags().Changed("description") {
- req.Description = &roleCreateDescription
- }
-
- result, err := c.PostJSON[roletypes.Role](cmd.Context(), types.Roles(), req)
- if err != nil {
- return fmt.Errorf("failed to create role: %w", err)
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ description string
+ permissions []string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create a custom role",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if opts.name == "" {
+ return errors.New("--name is required")
+ }
+ if len(opts.permissions) == 0 {
+ return errors.New("at least one --permission is required")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("Role %s created", result.Data.Name)
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Permissions", strconv.Itoa(len(result.Data.Permissions)))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.Role]{
+ Method: http.MethodPost,
+ Path: types.Roles(),
+ FailureMessage: "failed to create role",
+ Body: role.CreateRole{
+ Name: opts.name,
+ Permissions: opts.permissions,
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ },
+ Render: func(data role.Role) error {
+ output.Success("Role %s created", data.Name)
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Permissions", strconv.Itoa(len(data.Permissions)))
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "Role name (required)")
+ command.Flags().StringVarP(&opts.description, "description", "d", "", "Role description")
+ command.Flags().StringArrayVarP(&opts.permissions, "permission", "p", nil, "Permission to grant (repeatable, e.g. containers:start)")
+ return command
}
-var updateCmd = &cobra.Command{
- Use: "update <role-id>",
- Short: "Update a custom role (built-in roles are immutable)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // The PUT contract requires every field — fetch the current state
- // and overlay only the flags the caller set, so partial updates work
- // from the CLI without forcing the user to retype everything.
- current, err := fetchRoleInternal(cmd, args[0])
- if err != nil {
- return err
- }
-
- req := roletypes.UpdateRole{
- Name: current.Name,
- Description: current.Description,
- Permissions: current.Permissions,
- }
- if cmd.Flags().Changed("name") {
- req.Name = roleUpdateName
- }
- if cmd.Flags().Changed("description") {
- req.Description = &roleUpdateDescription
- }
- if cmd.Flags().Changed("permission") {
- req.Permissions = roleUpdatePermissions
- }
-
- resp, err := c.Put(cmd.Context(), types.Role(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update role: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to update role: %w", ensureSuccessStatusErr)
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ description string
+ permissions []string
+ }
+ command := &cobra.Command{
+ Use: "update <role-id>",
+ Short: "Update a custom role (built-in roles are immutable)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Role updated")
- return nil
- },
+ // Fetch required PUT fields, then overlay the changed flags.
+ currentResult, err := c.GetJSON[role.Role](cmd.Context(), types.Role(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to load current role: %w", err)
+ }
+ current := currentResult.Data
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.Role]{
+ Method: http.MethodPut,
+ Path: types.Role(args[0]),
+ Body: role.UpdateRole{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), opts.name, current.Name),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, current.Description),
+ Permissions: kit.Ternary(cmd.Flags().Changed("permission"), opts.permissions, current.Permissions),
+ },
+ FailureMessage: "failed to update role",
+ Render: func(role.Role) error {
+ output.Success("Role updated")
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "New role name")
+ command.Flags().StringVarP(&opts.description, "description", "d", "", "New role description")
+ command.Flags().StringArrayVarP(&opts.permissions, "permission", "p", nil, "Replace the permission set (repeatable)")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <role-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a custom role (built-in roles cannot be deleted)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Delete role %s? This removes every assignment of it.", args[0]))
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <role-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a custom role (built-in roles cannot be deleted)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resp, err := c.Delete(cmd.Context(), types.Role(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete role: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete role: %w", ensureSuccessStatusErr)
- }
- output.Success("Role deleted")
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Delete role %s? This removes every assignment of it.", args[0]),
+ Path: types.Role(args[0]),
+ FailureMessage: "failed to delete role",
+ SuccessMessage: "Role deleted",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
// ---------- Permission manifest ----------
-var permissionsCmd = &cobra.Command{
- Use: "permissions",
- Aliases: []string{"perms"},
- Short: "List every permission the server recognizes (the manifest)",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[roletypes.PermissionsManifest](cmd.Context(), types.RolesAvailablePermissions())
- if err != nil {
- return fmt.Errorf("failed to load permission manifest: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- for _, group := range result.Data.Resources {
- output.Header("%s (%s)", group.Label, group.Scope)
- rows := make([][]string, len(group.Actions))
- for i, a := range group.Actions {
- rows[i] = []string{a.Permission, a.Label, a.Description}
- }
- if tableErr := output.Table([]string{"PERMISSION", "LABEL", "DESCRIPTION"}, rows); tableErr != nil {
- return tableErr
+func newPermissionsCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "permissions",
+ Aliases: []string{"perms"},
+ Short: "List every permission the server recognizes (the manifest)",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[role.PermissionsManifest]{
+ Method: http.MethodGet,
+ Path: types.RolesAvailablePermissions(),
+ FailureMessage: "failed to load permission manifest",
+ Render: func(data role.PermissionsManifest) error {
+ for _, group := range data.Resources {
+ output.Header("%s (%s)", group.Label, group.Scope)
+ rows := make([][]string, len(group.Actions))
+ for i, a := range group.Actions {
+ rows[i] = []string{a.Permission, a.Label, a.Description}
+ }
+ if tableErr := output.Table([]string{"PERMISSION", "LABEL", "DESCRIPTION"}, rows); tableErr != nil {
+ return tableErr
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
}
// ---------- User assignments ----------
-var assignmentsCmd = &cobra.Command{
- Use: "assignments <user-id>",
- Short: "List a user's role assignments",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]))
- if err != nil {
- return fmt.Errorf("failed to list assignments: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- if len(result.Data) == 0 {
- output.Info("No role assignments for user %s", args[0])
- return nil
- }
- rows := make([][]string, len(result.Data))
- for i, a := range result.Data {
- scope := "global"
- if a.EnvironmentID != nil {
- scope = *a.EnvironmentID
+func newAssignmentsCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "assignments <user-id>",
+ Short: "List a user's role assignments",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- rows[i] = []string{a.RoleID, scope, a.Source, a.CreatedAt.Format("2006-01-02 15:04")}
- }
- return output.Table([]string{"ROLE", "SCOPE", "SOURCE", "CREATED"}, rows)
- },
-}
-
-var assignCmd = &cobra.Command{
- Use: "assign <user-id>",
- Short: "Replace a user's manual role assignments",
- Long: "Replace every MANUAL role assignment on the user with the set passed via --role. OIDC-sourced assignments are " +
- "left untouched — manage those via OIDC role mappings.\n\nEach --role flag accepts `<roleId>[:<envId>]`. Omit " +
- "the env id for a global assignment. Pass --role multiple times to assign more than one role. Pass --role \"\" " +
- "(empty) once to clear every manual assignment.",
-
- Example: ` arcane admin roles assign u_123 --role role_editor:env_prod --role role_viewer
- arcane admin roles assign u_123 --role role_admin
- arcane admin roles assign u_123 --role "" # clear all manual assignments`,
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- req := roletypes.SetUserAssignments{
- Assignments: parseAssignmentsInternal(assignRoles),
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.PutJSON[[]roletypes.RoleAssignment](cmd.Context(), types.UserRoleAssignments(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to set assignments: %w", err)
- }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("User %s now has %d role assignment(s)", args[0], len(result.Data))
- return nil
- },
-}
-
-// ---------- helpers ----------
-
-// parseAssignmentsInternal converts CLI --role tokens into the request payload.
-// Format: "<roleId>" (global) or "<roleId>:<envId>" (env-scoped). A single
-// empty token means "clear all assignments".
-func parseAssignmentsInternal(tokens []string) []roletypes.UserAssignmentInput {
- if len(tokens) == 1 && strings.TrimSpace(tokens[0]) == "" {
- return []roletypes.UserAssignmentInput{}
- }
- out := make([]roletypes.UserAssignmentInput, 0, len(tokens))
- for _, raw := range tokens {
- token := strings.TrimSpace(raw)
- if token == "" {
- continue
- }
- roleID, envID, hasEnv := strings.Cut(token, ":")
- entry := roletypes.UserAssignmentInput{RoleID: roleID}
- if hasEnv && envID != "" {
- entry.EnvironmentID = new(envID)
- }
- out = append(out, entry)
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]role.RoleAssignment]{
+ Method: http.MethodGet,
+ Path: types.UserRoleAssignments(args[0]),
+ FailureMessage: "failed to list assignments",
+ Render: func(data []role.RoleAssignment) error {
+ if len(data) == 0 {
+ output.Info("No role assignments for user %s", args[0])
+ return nil
+ }
+ rows := make([][]string, len(data))
+ for i, a := range data {
+ scope := "global"
+ if a.EnvironmentID != nil {
+ scope = *a.EnvironmentID
+ }
+ rows[i] = []string{a.RoleID, scope, a.Source, a.CreatedAt.Format("2006-01-02 15:04")}
+ }
+ return output.Table([]string{"ROLE", "SCOPE", "SOURCE", "CREATED"}, rows)
+ },
+ })
+ },
}
- return out
}
-func fetchRoleInternal(cmd *cobra.Command, id string) (*roletypes.Role, error) {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return nil, err
+func newAssignCmd() *cobra.Command {
+ var opts struct {
+ roles []string
}
- result, err := c.GetJSON[roletypes.Role](cmd.Context(), types.Role(id))
- if err != nil {
- return nil, fmt.Errorf("failed to load current role: %w", err)
+ command := &cobra.Command{
+ Use: "assign <user-id>",
+ Short: "Replace a user's manual role assignments",
+ Long: "Replace every MANUAL role assignment on the user with the set passed via --role. OIDC-sourced assignments are " +
+ "left untouched — manage those via OIDC role mappings.\n\nEach --role flag accepts `<roleId>[:<envId>]`. Omit " +
+ "the env id for a global assignment. Pass --role multiple times to assign more than one role. Pass --role \"\" " +
+ "(empty) once to clear every manual assignment.",
+
+ Example: ` arcane admin roles assign u_123 --role role_editor:env_prod --role role_viewer
+ arcane admin roles assign u_123 --role role_admin
+ arcane admin roles assign u_123 --role "" # clear all manual assignments`,
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ assignments := make([]role.UserAssignmentInput, 0, len(opts.roles))
+ for _, raw := range opts.roles {
+ token := strings.TrimSpace(raw)
+ if token == "" {
+ continue
+ }
+ roleID, envID, hasEnv := strings.Cut(token, ":")
+ assignments = append(assignments, role.UserAssignmentInput{
+ RoleID: roleID,
+ EnvironmentID: kit.Ternary(hasEnv && envID != "", new(envID), nil),
+ })
+ }
+ req := role.SetUserAssignments{
+ Assignments: assignments,
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]role.RoleAssignment]{
+ Method: http.MethodPut,
+ Path: types.UserRoleAssignments(args[0]),
+ FailureMessage: "failed to set assignments",
+ Body: req,
+ Render: func(data []role.RoleAssignment) error {
+ output.Success("User %s now has %d role assignment(s)", args[0], len(data))
+ return nil
+ },
+ })
+ },
}
- return &result.Data, nil
-}
-
-func init() {
- RolesCmd.AddCommand(listCmd)
- RolesCmd.AddCommand(getCmd)
- RolesCmd.AddCommand(createCmd)
- RolesCmd.AddCommand(updateCmd)
- RolesCmd.AddCommand(deleteCmd)
- RolesCmd.AddCommand(permissionsCmd)
- RolesCmd.AddCommand(assignmentsCmd)
- RolesCmd.AddCommand(assignCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of roles to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&roleCreateName, "name", "", "Role name (required)")
- createCmd.Flags().StringVarP(&roleCreateDescription, "description", "d", "", "Role description")
- createCmd.Flags().StringArrayVarP(&roleCreatePermissions, "permission", "p", nil, "Permission to grant (repeatable, e.g. containers:start)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- updateCmd.Flags().StringVar(&roleUpdateName, "name", "", "New role name")
- updateCmd.Flags().StringVarP(&roleUpdateDescription, "description", "d", "", "New role description")
- updateCmd.Flags().StringArrayVarP(&roleUpdatePermissions, "permission", "p", nil, "Replace the permission set (repeatable)")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
-
- permissionsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- assignmentsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- assignCmd.Flags().StringArrayVar(&assignRoles, "role", nil, "Role to grant as `<roleId>[:<envId>]` (repeatable). Pass --role \"\" to clear all manual assignments.")
- assignCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = assignCmd.MarkFlagRequired("role")
+ command.Flags().StringArrayVar(&opts.roles, "role", nil, "Role to grant as `<roleId>[:<envId>]` (repeatable). Pass --role \"\" to clear all manual assignments.")
+ _ = command.MarkFlagRequired("role")
+ return command
}
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index 477b57af9..c8cd58d49 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -1,54 +1,248 @@
package users
import (
+ "cmp"
"fmt"
+ "net/http"
"strings"
"github.com/getarcaneapp/arcane/types/v2/user"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-)
+// Command is the parent command for user operations
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "users",
+ Aliases: []string{"user", "usr"},
+ Short: "Manage users",
+ Long: "Manage users. Role assignments are managed separately via `arcane admin roles assign` — the legacy `--role` flag has been removed alongside the binary admin/user model.",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newGetCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ return command
+}
-var (
- userCreateUsername string
- userCreatePassword string
- userCreateDisplayName string
- userCreateEmail string
-)
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List users",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var (
- userUpdateUsername string
- userUpdateDisplayName string
- userUpdateEmail string
-)
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[user.User]{
+ Resource: "users",
+ Endpoint: types.Users(),
+ Params: cmdutil.ListParams{Resource: "users", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLE ASSIGNMENTS"},
+ Row: func(usr user.User) []string {
+ return []string{
+ usr.ID,
+ usr.Username,
+ kit.FromPtr(usr.DisplayName),
+ kit.FromPtr(usr.Email),
+ roleAssignmentSummary(usr.RoleAssignments),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of users to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
+}
+
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ username string
+ password string
+ displayName string
+ email string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create a new user",
+ Long: "Create a new user. The user is created without any role assignments — grant them via `arcane admin roles assign <userId>` after creation.",
+
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ if opts.password == "" {
+ if opts.password, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Password", "password"); err != nil {
+ return fmt.Errorf("failed to read password: %w", err)
+ }
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[user.User]{
+ Method: http.MethodPost,
+ Path: types.Users(),
+ FailureMessage: "failed to create user",
+ Body: user.CreateUser{
+ Username: opts.username,
+ Password: opts.password,
+ DisplayName: kit.Ternary(cmd.Flags().Changed("display-name"), &opts.displayName, nil),
+ Email: kit.Ternary(cmd.Flags().Changed("email"), &opts.email, nil),
+ },
+ Render: func(data user.User) error {
+ output.Success("User %s created successfully", data.Username)
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Username", data.Username)
+ output.Info("No roles assigned. Use `arcane admin roles assign %s --role <roleId>` to grant access.", data.ID)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.username, "username", "", "Username")
+ command.Flags().StringVar(&opts.password, "password", "", "Password (if omitted, will prompt securely)")
+ command.Flags().StringVar(&opts.displayName, "display-name", "", "Display name")
+ command.Flags().StringVar(&opts.email, "email", "", "Email address")
+ _ = command.MarkFlagRequired("username")
+ return command
+}
-// UsersCmd is the parent command for user operations
-var UsersCmd = &cobra.Command{
- Use: "users",
- Aliases: []string{"user", "usr"},
- Short: "Manage users",
- Long: "Manage users. Role assignments are managed separately via `arcane admin roles assign` — the legacy `--role` flag has been removed alongside the binary admin/user model.",
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <user-id>",
+ Short: "Get user details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[user.User]{
+ Method: http.MethodGet,
+ Path: types.User(args[0]),
+ FailureMessage: "failed to get user",
+ Render: func(data user.User) error {
+ output.Header("User Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Username", data.Username)
+ if data.DisplayName != nil {
+ output.KeyValue("Display Name", *data.DisplayName)
+ }
+ if data.Email != nil {
+ output.KeyValue("Email", *data.Email)
+ }
+ output.KeyValue("Created", data.CreatedAt)
+
+ output.KeyValue("Role Assignments", roleAssignmentSummary(data.RoleAssignments))
+ if len(data.RoleAssignments) > 0 {
+ rows := make([][]string, len(data.RoleAssignments))
+ for i, a := range data.RoleAssignments {
+ env := "global"
+ if a.EnvironmentID != nil {
+ env = *a.EnvironmentID
+ }
+ rows[i] = []string{a.RoleID, env, a.Source}
+ }
+ if tableErr := output.Table([]string{"ROLE", "SCOPE", "SOURCE"}, rows); tableErr != nil {
+ return tableErr
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
}
-// summarizeRoleAssignments turns a user's role-assignment list into a short
-// human label for the list table — e.g. "Admin (global)", "Editor on 2 envs",
-// or "Admin (global) + 1 more". Returns "—" when the user holds none.
-func summarizeRoleAssignments(assignments []user.RoleAssignmentSummary) string {
- if len(assignments) == 0 {
- return "—"
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ username string
+ displayName string
+ email string
}
+ command := &cobra.Command{
+ Use: "update <user-id>",
+ Short: "Update user profile (role assignments managed separately)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[user.User]{
+ Method: http.MethodPut,
+ Path: types.User(args[0]),
+ FailureMessage: "failed to update user",
+ Body: user.UpdateUser{
+ Username: kit.Ternary(cmd.Flags().Changed("username"), &opts.username, nil),
+ DisplayName: kit.Ternary(cmd.Flags().Changed("display-name"), &opts.displayName, nil),
+ Email: kit.Ternary(cmd.Flags().Changed("email"), &opts.email, nil),
+ },
+ Render: func(user.User) error {
+ output.Success("User updated successfully")
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.username, "username", "", "New username")
+ command.Flags().StringVar(&opts.displayName, "display-name", "", "Display name")
+ command.Flags().StringVar(&opts.email, "email", "", "Email address")
+ return command
+}
+
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <user-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete user",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete user %s?", args[0]),
+ Path: types.User(args[0]),
+ FailureMessage: "failed to delete user",
+ SuccessMessage: "User deleted successfully",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
+}
+
+func roleAssignmentSummary(assignments []user.RoleAssignmentSummary) string {
type bucket struct {
envScoped int
hasGlobal bool
@@ -82,240 +276,5 @@ func summarizeRoleAssignments(assignments []user.RoleAssignmentSummary) string {
parts = append(parts, fmt.Sprintf("%s on %d envs", roleID, b.envScoped))
}
}
- return strings.Join(parts, ", ")
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List users",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[user.User]{
- Resource: "users",
- Endpoint: types.Users(),
- Params: cmdutil.ListParams{Resource: "users", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLE ASSIGNMENTS"},
- Row: func(usr user.User) []string {
- displayName := ""
- if usr.DisplayName != nil {
- displayName = *usr.DisplayName
- }
- email := ""
- if usr.Email != nil {
- email = *usr.Email
- }
- return []string{
- usr.ID,
- usr.Username,
- displayName,
- email,
- summarizeRoleAssignments(usr.RoleAssignments),
- }
- },
- })
- },
-}
-
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new user",
- Long: "Create a new user. The user is created without any role assignments — grant them via `arcane admin roles assign <userId>` after creation.",
-
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- if userCreatePassword == "" {
- if userCreatePassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Password", "password"); err != nil {
- return fmt.Errorf("failed to read password: %w", err)
- }
- }
-
- req := user.CreateUser{
- Username: userCreateUsername,
- Password: userCreatePassword,
- }
- if cmd.Flags().Changed("display-name") {
- req.DisplayName = &userCreateDisplayName
- }
- if cmd.Flags().Changed("email") {
- req.Email = &userCreateEmail
- }
-
- result, err := c.PostJSON[user.User](cmd.Context(), types.Users(), req)
- if err != nil {
- return fmt.Errorf("failed to create user: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("User %s created successfully", result.Data.Username)
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Username", result.Data.Username)
- output.Info("No roles assigned. Use `arcane admin roles assign %s --role <roleId>` to grant access.", result.Data.ID)
- return nil
- },
-}
-
-var getCmd = &cobra.Command{
- Use: "get <user-id>",
- Short: "Get user details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[user.User](cmd.Context(), types.User(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get user: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("User Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Username", result.Data.Username)
- if result.Data.DisplayName != nil {
- output.KeyValue("Display Name", *result.Data.DisplayName)
- }
- if result.Data.Email != nil {
- output.KeyValue("Email", *result.Data.Email)
- }
- output.KeyValue("Created", result.Data.CreatedAt)
- output.KeyValue("Role Assignments", summarizeRoleAssignments(result.Data.RoleAssignments))
- if len(result.Data.RoleAssignments) > 0 {
- rows := make([][]string, len(result.Data.RoleAssignments))
- for i, a := range result.Data.RoleAssignments {
- env := "global"
- if a.EnvironmentID != nil {
- env = *a.EnvironmentID
- }
- rows[i] = []string{a.RoleID, env, a.Source}
- }
- if tableErr := output.Table([]string{"ROLE", "SCOPE", "SOURCE"}, rows); tableErr != nil {
- return tableErr
- }
- }
- return nil
- },
-}
-
-var updateCmd = &cobra.Command{
- Use: "update <user-id>",
- Short: "Update user profile (role assignments managed separately)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- var req user.UpdateUser
- if cmd.Flags().Changed("username") {
- req.Username = &userUpdateUsername
- }
- if cmd.Flags().Changed("display-name") {
- req.DisplayName = &userUpdateDisplayName
- }
- if cmd.Flags().Changed("email") {
- req.Email = &userUpdateEmail
- }
-
- result, err := c.PutJSON[user.User](cmd.Context(), types.User(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update user: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("User updated successfully")
- return nil
- },
-}
-
-var deleteCmd = &cobra.Command{
- Use: "delete <user-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete user",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete user %s?", args[0]))
- if err != nil {
- return err
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resp, err := c.Delete(cmd.Context(), types.User(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete user: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete user: %w", ensureSuccessStatusErr)
- }
-
- output.Success("User deleted successfully")
- return nil
- },
-}
-
-func init() {
- UsersCmd.AddCommand(listCmd)
- UsersCmd.AddCommand(createCmd)
- UsersCmd.AddCommand(getCmd)
- UsersCmd.AddCommand(updateCmd)
- UsersCmd.AddCommand(deleteCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of users to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&userCreateUsername, "username", "", "Username")
- createCmd.Flags().StringVar(&userCreatePassword, "password", "", "Password (if omitted, will prompt securely)")
- createCmd.Flags().StringVar(&userCreateDisplayName, "display-name", "", "Display name")
- createCmd.Flags().StringVar(&userCreateEmail, "email", "", "Email address")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("username")
-
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- updateCmd.Flags().StringVar(&userUpdateUsername, "username", "", "New username")
- updateCmd.Flags().StringVar(&userUpdateDisplayName, "display-name", "", "Display name")
- updateCmd.Flags().StringVar(&userUpdateEmail, "email", "", "Email address")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmp.Or(strings.Join(parts, ", "), "—")
}
diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.go
index 26bee253e..6462be41b 100644
--- a/cli/pkg/auth/apikeys.go
+++ b/cli/pkg/auth/apikeys.go
@@ -2,172 +2,150 @@ package auth
import (
"fmt"
+ "net/http"
"time"
- apikeytypes "github.com/getarcaneapp/arcane/types/v2/apikey"
+ "github.com/getarcaneapp/arcane/types/v2/apikey"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- apiKeyForceFlag bool
- apiKeyCreateDescription string
- apiKeyCreateExpiresAt string
-)
-
-// apiKeysCmd is the parent command for the caller's own (personal) API keys.
-// Personal keys inherit the owner's role permissions; scoped keys with
-// granular grants are managed via `arcane admin api-keys`.
-var apiKeysCmd = &cobra.Command{
- Use: "api-keys",
- Aliases: []string{"apikeys", "key"},
- Short: "Manage your own API keys",
- Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and " +
- "deleting them requires a session login (an API key cannot mint or remove other keys).",
-}
-
-var apiKeysListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List your API keys",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[[]apikeytypes.ApiKey](cmd.Context(), types.AuthMeApiKeys())
- if err != nil {
- return fmt.Errorf("failed to list API keys: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- if len(result.Data) == 0 {
- output.Info("No API keys found")
- return nil
- }
-
- headers := []string{"ID", "NAME", "KIND", "PREFIX", "EXPIRES", "LAST USED", "CREATED"}
- rows := make([][]string, len(result.Data))
- for i, key := range result.Data {
- expires := "never"
- if key.ExpiresAt != nil {
- expires = key.ExpiresAt.Format("2006-01-02 15:04")
- }
- lastUsed := "never"
- if key.LastUsedAt != nil {
- lastUsed = key.LastUsedAt.Format("2006-01-02 15:04")
- }
- rows[i] = []string{
- key.ID,
- key.Name,
- key.Kind,
- key.KeyPrefix,
- expires,
- lastUsed,
- key.CreatedAt.Format("2006-01-02 15:04"),
- }
- }
- return output.Table(headers, rows)
- },
+// apiKeysCmd manages personal keys, which inherit the owner's role permissions.
+// Scoped keys are managed through `arcane admin api-keys`.
+func newAPIKeysCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "api-keys",
+ Aliases: []string{"apikeys", "key"},
+ Short: "Manage your own API keys",
+ Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and " +
+ "deleting them requires a session login (an API key cannot mint or remove other keys).",
+ }
+ cmd.AddCommand(newAPIKeysListCmd(), newAPIKeysCreateCmd(), newAPIKeysDeleteCmd())
+ return cmd
}
-var apiKeysCreateCmd = &cobra.Command{
- Use: "create <name>",
- Short: "Create a personal API key",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := apikeytypes.CreateUserApiKey{Name: args[0]}
- if cmd.Flags().Changed("description") {
- req.Description = &apiKeyCreateDescription
- }
- if apiKeyCreateExpiresAt != "" {
- parsed, parseErr := time.Parse(time.RFC3339, apiKeyCreateExpiresAt)
- if parseErr != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+func newAPIKeysListCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List your API keys",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- req.ExpiresAt = &parsed
- }
-
- result, err := c.PostJSON[apikeytypes.ApiKeyCreatedDto](cmd.Context(), types.AuthMeApiKeys(), req)
- if err != nil {
- return fmt.Errorf("failed to create API key: %w", err)
- }
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("API key created")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.Warning("The key secret is shown only once — store it now:")
- output.KeyValue("Key", result.Data.Key)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]apikey.ApiKey]{
+ Method: http.MethodGet,
+ Path: types.AuthMeApiKeys(),
+ FailureMessage: "failed to list API keys",
+ Render: func(data []apikey.ApiKey) error {
+ if len(data) == 0 {
+ output.Info("No API keys found")
+ return nil
+ }
+
+ headers := []string{"ID", "NAME", "KIND", "PREFIX", "EXPIRES", "LAST USED", "CREATED"}
+ rows := make([][]string, len(data))
+ for i, key := range data {
+ rows[i] = []string{
+ key.ID,
+ key.Name,
+ key.Kind,
+ key.KeyPrefix,
+ kit.Ternary(key.ExpiresAt != nil, kit.FromPtr(key.ExpiresAt).Format("2006-01-02 15:04"), "never"),
+ kit.Ternary(key.LastUsedAt != nil, kit.FromPtr(key.LastUsedAt).Format("2006-01-02 15:04"), "never"),
+ key.CreatedAt.Format("2006-01-02 15:04"),
+ }
+ }
+ return output.Table(headers, rows)
+ },
+ })
+ },
+ }
}
-var apiKeysDeleteCmd = &cobra.Command{
- Use: "delete <id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete one of your API keys",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !apiKeyForceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete API key %s?", args[0]))
+func newAPIKeysCreateCmd() *cobra.Command {
+ var opts struct {
+ description string
+ expiresAt string
+ }
+ cmd := &cobra.Command{
+ Use: "create <name>",
+ Short: "Create a personal API key",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resp, err := c.Delete(cmd.Context(), types.AuthMeApiKey(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete API key: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete API key: %w", ensureSuccessStatusErr)
- }
+ var expiresAt *time.Time
+ if opts.expiresAt != "" {
+ parsed, parseErr := time.Parse(time.RFC3339, opts.expiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
+ }
+ expiresAt = &parsed
+ }
- output.Success("API key deleted")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[apikey.ApiKeyCreatedDto]{
+ Method: http.MethodPost,
+ Path: types.AuthMeApiKeys(),
+ Body: apikey.CreateUserApiKey{
+ Name: args[0],
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ ExpiresAt: expiresAt,
+ },
+ FailureMessage: "failed to create API key",
+ Render: func(data apikey.ApiKeyCreatedDto) error {
+ output.Success("API key created")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.Warning("The key secret is shown only once — store it now:")
+ output.KeyValue("Key", data.Key)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.description, "description", "", "Description of the API key")
+ cmd.Flags().StringVar(&opts.expiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
+ return cmd
}
-func init() {
- AuthCmd.AddCommand(apiKeysCmd)
- apiKeysCmd.AddCommand(apiKeysListCmd)
- apiKeysCmd.AddCommand(apiKeysCreateCmd)
- apiKeysCmd.AddCommand(apiKeysDeleteCmd)
-
- apiKeysListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- apiKeysCreateCmd.Flags().StringVar(&apiKeyCreateDescription, "description", "", "Description of the API key")
- apiKeysCreateCmd.Flags().StringVar(&apiKeyCreateExpiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
- apiKeysCreateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newAPIKeysDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete one of your API keys",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- apiKeysDeleteCmd.Flags().BoolVarP(&apiKeyForceFlag, "force", "f", false, "Force deletion without confirmation")
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete API key %s?", args[0]),
+ Path: types.AuthMeApiKey(args[0]),
+ FailureMessage: "failed to delete API key",
+ SuccessMessage: "API key deleted",
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return cmd
}
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index 852b30579..eaccb64bb 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -1,6 +1,7 @@
package auth
import (
+ "cmp"
"encoding/json/v2"
"errors"
"fmt"
@@ -15,142 +16,89 @@ import (
"github.com/getarcaneapp/arcane/types/v2/user"
"github.com/spf13/cobra"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var jsonOutput bool
-
-// AuthCmd is the parent command for authentication operations
-var AuthCmd = &cobra.Command{
- Use: "auth",
- Aliases: []string{"authentication"},
- Short: "Authentication operations",
+// Command is the parent command for authentication operations
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "auth",
+ Aliases: []string{"authentication"},
+ Short: "Authentication operations",
+ }
+ cmd.AddCommand(newFederatedCmd(), newLoginCmd(), newLogoutCmd(), newMeCmd(), newPasswordCmd(), newRefreshCmd(), newOidcStatusCmd(), newAPIKeysCmd())
+ return cmd
}
-var loginCmd = &cobra.Command{
- Use: "login",
- Short: "Login to Arcane using OIDC device authorization",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.UnauthClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- reqBody, err := json.Marshal(auth.OidcDeviceAuthRequest{})
- if err != nil {
- return fmt.Errorf("failed to marshal request: %w", err)
- }
-
- resp, err := c.Post(cmd.Context(), types.OIDCDeviceCode(), reqBody)
- if err != nil {
- return fmt.Errorf("device authorization failed: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- bodyBytes, err := io.ReadAll(resp.Body)
- if err != nil {
- return fmt.Errorf("failed to read response: %w", err)
- }
-
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return fmt.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
- }
-
- var deviceAuth auth.OidcDeviceAuthResponse
- if unmarshalErr := json.Unmarshal(bodyBytes, &deviceAuth); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
-
- output.Header("Device Login")
- output.KeyValue("Verification URL", deviceAuth.VerificationUri)
- if deviceAuth.VerificationUriComplete != "" {
- output.KeyValue("Verification URL (complete)", deviceAuth.VerificationUriComplete)
- }
- output.KeyValue("User code", deviceAuth.UserCode)
- output.Info("Complete authorization in your browser to finish login.")
-
- pollInterval := time.Duration(deviceAuth.Interval) * time.Second
- if pollInterval <= 0 {
- pollInterval = 5 * time.Second
- }
- expiresAt := time.Now().Add(time.Duration(deviceAuth.ExpiresIn) * time.Second)
-
- tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})
- if err != nil {
- return fmt.Errorf("failed to marshal token request: %w", err)
- }
+func newLoginCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "login",
+ Short: "Login to Arcane using OIDC device authorization",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.UnauthClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- ticker := time.NewTicker(pollInterval)
- defer ticker.Stop()
+ reqBody, err := json.Marshal(auth.OidcDeviceAuthRequest{})
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
- for {
- if time.Now().After(expiresAt) {
- return errors.New("device authorization expired; run login again")
+ resp, err := c.Post(cmd.Context(), types.OIDCDeviceCode(), reqBody)
+ if err != nil {
+ return fmt.Errorf("device authorization failed: %w", err)
}
+ defer func() { _ = resp.Body.Close() }()
- select {
- case <-ticker.C:
- case <-cmd.Context().Done():
- return cmd.Context().Err()
+ bodyBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read response: %w", err)
}
- tokenResp, postErr := c.Post(cmd.Context(), types.OIDCDeviceToken(), tokenReqBody)
- if postErr != nil {
- return fmt.Errorf("device token exchange failed: %w", postErr)
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return fmt.Errorf("device authorization failed (status %d): %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
}
- tokenBody, postErr := io.ReadAll(tokenResp.Body)
- _ = tokenResp.Body.Close()
- if postErr != nil {
- return fmt.Errorf("failed to read token response: %w", postErr)
+ var deviceAuth auth.OidcDeviceAuthResponse
+ if unmarshalErr := json.Unmarshal(bodyBytes, &deviceAuth); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
- if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {
- errCode := extractDeviceAuthErrorCode(string(tokenBody))
- switch errCode {
- case "authorization_pending":
- continue
- case "slow_down":
- pollInterval += 5 * time.Second
- ticker.Reset(pollInterval)
- continue
- case "expired_token":
- return errors.New("device authorization expired; run login again")
- case "access_denied":
- return errors.New("device authorization denied")
- case "mfa_required":
- return errors.New("this account has MFA enabled, which browser-based CLI login cannot complete; create a personal API key in " +
- "Arcane (Account -> API keys) and run: arcane config set api-key <key>")
- default:
- return fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))
+ if cmdutil.JSONOutputEnabled(cmd) {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Device Login\nVerification URL: %s\n", deviceAuth.VerificationUri)
+ if deviceAuth.VerificationUriComplete != "" {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Verification URL (complete): %s\n", deviceAuth.VerificationUriComplete)
+ }
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "User code: %s\nComplete authorization in your browser to finish login.\n", deviceAuth.UserCode)
+ } else {
+ output.Header("Device Login")
+ output.KeyValue("Verification URL", deviceAuth.VerificationUri)
+ if deviceAuth.VerificationUriComplete != "" {
+ output.KeyValue("Verification URL (complete)", deviceAuth.VerificationUriComplete)
}
+ output.KeyValue("User code", deviceAuth.UserCode)
+ output.Info("Complete authorization in your browser to finish login.")
}
- var tokenResult auth.AuthenticationResponse
- if decodeTokenResponseErr := json.Unmarshal(tokenBody, &tokenResult); decodeTokenResponseErr != nil {
- return fmt.Errorf("failed to parse token response: %w", decodeTokenResponseErr)
- }
- if !tokenResult.Success || tokenResult.Token == "" {
- return errors.New("device token exchange failed: unexpected response from server")
+ tokenResult, tokenErr := pollDeviceToken(cmd, c, deviceAuth)
+ if tokenErr != nil {
+ return tokenErr
}
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(map[string]any{
- "success": tokenResult.Success,
- "token": tokenResult.Token,
- "refreshToken": tokenResult.RefreshToken,
- "expiresAt": tokenResult.ExpiresAt,
- "user": tokenResult.User,
- })
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(tokenResult)
}
- cfg, postErr := config.Load()
- if postErr != nil {
- return fmt.Errorf("failed to load config: %w", postErr)
+ cfg, loadErr := config.Load()
+ if loadErr != nil {
+ return fmt.Errorf("failed to load config: %w", loadErr)
}
cfg.JWTToken = tokenResult.Token
cfg.RefreshToken = tokenResult.RefreshToken
@@ -163,275 +111,285 @@ var loginCmd = &cobra.Command{
path, _ := config.ConfigPath()
output.KeyValue("JWT token saved to config", path)
return nil
- }
- },
+ },
+ }
}
-var logoutCmd = &cobra.Command{
- Use: "logout",
- Short: "Logout from Arcane",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newLogoutCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "logout",
+ Short: "Logout from Arcane",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthLogout(), nil)
- if err != nil {
- return fmt.Errorf("logout failed: %w", err)
- }
+ result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthLogout(), nil)
+ if err != nil {
+ return fmt.Errorf("logout failed: %w", err)
+ }
- // Clear token from config after successful API logout.
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
- cfg.JWTToken = ""
- cfg.RefreshToken = ""
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to clear token: %w", saveErr)
- }
+ // Clear token from config after successful API logout.
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+ cfg.JWTToken = ""
+ cfg.RefreshToken = ""
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to clear token: %w", saveErr)
+ }
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result.Data)
+ }
- output.Success("Logout successful")
- path, _ := config.ConfigPath()
- output.KeyValue("JWT token cleared from config", path)
- return nil
- },
+ output.Success("Logout successful")
+ path, _ := config.ConfigPath()
+ output.KeyValue("JWT token cleared from config", path)
+ return nil
+ },
+ }
}
-var meCmd = &cobra.Command{
- Use: "me",
- Short: "Get current user information",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[user.User](cmd.Context(), types.AuthMe())
- if err != nil {
- return fmt.Errorf("failed to get user info: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newMeCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "me",
+ Short: "Get current user information",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Current User")
- return cmdutil.PrintJSON(result.Data)
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[user.User]{
+ Method: http.MethodGet,
+ Path: types.AuthMe(),
+ FailureMessage: "failed to get user info",
+ Render: func(data user.User) error {
+ output.Header("Current User")
+ return cmdutil.PrintJSON(data)
+ },
+ })
+ },
+ }
}
-var passwordCmd = &cobra.Command{
- Use: "password",
- Short: "Change password",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- currentPassword, _ := cmd.Flags().GetString("current")
- newPassword, _ := cmd.Flags().GetString("new")
-
- if currentPassword == "" {
- var err error
- if currentPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Current password", "current"); err != nil {
- return fmt.Errorf("failed to read current password: %w", err)
+func newPasswordCmd() *cobra.Command {
+ var opts struct {
+ currentPassword string
+ newPassword string
+ }
+ cmd := &cobra.Command{
+ Use: "password",
+ Short: "Change password",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ currentPassword := opts.currentPassword
+ newPassword := opts.newPassword
+
+ if currentPassword == "" {
+ var err error
+ if currentPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Current password", "current"); err != nil {
+ return fmt.Errorf("failed to read current password: %w", err)
+ }
}
- }
- if newPassword == "" {
- var err error
- if newPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "New password", "new"); err != nil {
- return fmt.Errorf("failed to read new password: %w", err)
+ if newPassword == "" {
+ var err error
+ if newPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "New password", "new"); err != nil {
+ return fmt.Errorf("failed to read new password: %w", err)
+ }
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- changeReq := auth.PasswordChange{
- CurrentPassword: currentPassword,
- NewPassword: newPassword,
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.AuthPassword(),
+ Body: auth.PasswordChange{CurrentPassword: currentPassword, NewPassword: newPassword},
+ FailureMessage: "password change failed",
+ Render: func(base.MessageResponse) error {
+ output.Success("Password changed successfully")
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.currentPassword, "current", "", "Current password")
+ cmd.Flags().StringVar(&opts.newPassword, "new", "", "New password")
+ return cmd
+}
- reqBody, err := json.Marshal(changeReq)
- if err != nil {
- return fmt.Errorf("failed to marshal request: %w", err)
- }
+func newRefreshCmd() *cobra.Command {
+ var opts struct {
+ refreshToken string
+ }
+ cmd := &cobra.Command{
+ Use: "refresh",
+ Short: "Refresh authentication token",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ refreshToken := opts.refreshToken
+
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.AuthPassword(), reqBody)
- if err != nil {
- return fmt.Errorf("password change failed: %w", err)
- }
+ refreshToken = cmp.Or(refreshToken, cfg.RefreshToken)
+ if refreshToken == "" {
+ if refreshToken, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Refresh token", "refresh-token"); err != nil {
+ return fmt.Errorf("failed to read refresh token: %w", err)
+ }
+ }
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Password changed successfully")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[auth.TokenRefreshResponse]{
+ Method: http.MethodPost,
+ Path: types.AuthRefresh(),
+ Body: auth.Refresh{RefreshToken: refreshToken},
+ FailureMessage: "token refresh failed",
+ Render: func(data auth.TokenRefreshResponse) error {
+ cfg.JWTToken = data.Token
+ cfg.APIKey = ""
+ cfg.RefreshToken = cmp.Or(data.RefreshToken, cfg.RefreshToken)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save token: %w", saveErr)
+ }
+ output.Success("Token refreshed successfully")
+ path, _ := config.ConfigPath()
+ output.KeyValue("New JWT token saved to config", path)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.refreshToken, "refresh-token", "", "Refresh token")
+ return cmd
}
-var refreshCmd = &cobra.Command{
- Use: "refresh",
- Short: "Refresh authentication token",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- refreshToken, _ := cmd.Flags().GetString("refresh-token")
+func newOidcStatusCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "oidc",
+ Aliases: []string{"oidc-status"},
+ Short: "Show OIDC configuration status",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
+ result, err := c.DoJSON[auth.OidcStatusInfo](cmd.Context(), http.MethodGet, types.OIDCStatus(), nil)
+ if err != nil {
+ return fmt.Errorf("failed to get OIDC status: %w", err)
+ }
- if refreshToken == "" {
- refreshToken = cfg.RefreshToken
- }
- if refreshToken == "" {
- if refreshToken, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Refresh token", "refresh-token"); err != nil {
- return fmt.Errorf("failed to read refresh token: %w", err)
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ output.Header("OIDC Status")
+ output.KeyValue("Environment Forced", strconv.FormatBool(result.EnvForced))
+ output.KeyValue("Environment Configured", strconv.FormatBool(result.EnvConfigured))
+ output.KeyValue("Merge Accounts", strconv.FormatBool(result.MergeAccounts))
+ return nil
+ },
+ }
+}
- reqBody, err := json.Marshal(map[string]string{"refreshToken": refreshToken})
- if err != nil {
- return fmt.Errorf("failed to marshal request: %w", err)
- }
+func pollDeviceToken(cmd *cobra.Command, c *client.Client, deviceAuth auth.OidcDeviceAuthResponse) (auth.AuthenticationResponse, error) {
+ pollInterval := time.Duration(deviceAuth.Interval) * time.Second
+ if pollInterval <= 0 {
+ pollInterval = 5 * time.Second
+ }
+ expiresAt := time.Now().Add(time.Duration(deviceAuth.ExpiresIn) * time.Second)
- result, err := c.PostJSON[auth.TokenRefreshResponse](cmd.Context(), types.AuthRefresh(), reqBody)
- if err != nil {
- return fmt.Errorf("token refresh failed: %w", err)
- }
+ tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})
+ if err != nil {
+ return auth.AuthenticationResponse{}, fmt.Errorf("failed to marshal token request: %w", err)
+ }
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(map[string]any{
- "token": result.Data.Token,
- "refreshToken": result.Data.RefreshToken,
- "expiresAt": result.Data.ExpiresAt,
- })
- }
+ ticker := time.NewTicker(pollInterval)
+ defer ticker.Stop()
- // Save new JWT token to config
- cfg.JWTToken = result.Data.Token
- cfg.APIKey = ""
- if result.Data.RefreshToken != "" {
- cfg.RefreshToken = result.Data.RefreshToken
- }
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to save token: %w", saveErr)
+ for {
+ if time.Now().After(expiresAt) {
+ return auth.AuthenticationResponse{}, errors.New("device authorization expired; run login again")
}
- output.Success("Token refreshed successfully")
- path, _ := config.ConfigPath()
- output.KeyValue("New JWT token saved to config", path)
- return nil
- },
-}
-
-var oidcStatusCmd = &cobra.Command{
- Use: "oidc",
- Aliases: []string{"oidc-status"},
- Short: "Show OIDC configuration status",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
+ select {
+ case <-ticker.C:
+ case <-cmd.Context().Done():
+ return auth.AuthenticationResponse{}, cmd.Context().Err()
}
- // This endpoint returns its payload directly, not wrapped in an
- // ApiResponse envelope.
- type oidcStatusResult struct {
- EnvForced bool `json:"envForced"`
- EnvConfigured bool `json:"envConfigured"`
- MergeAccounts bool `json:"mergeAccounts"`
- }
- result, err := c.DoJSON[oidcStatusResult](cmd.Context(), http.MethodGet, types.OIDCStatus(), nil)
- if err != nil {
- return fmt.Errorf("failed to get OIDC status: %w", err)
+ tokenResp, postErr := c.Post(cmd.Context(), types.OIDCDeviceToken(), tokenReqBody)
+ if postErr != nil {
+ return auth.AuthenticationResponse{}, fmt.Errorf("device token exchange failed: %w", postErr)
}
- if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
- return cmdutil.PrintJSON(result)
+ tokenBody, postErr := io.ReadAll(tokenResp.Body)
+ _ = tokenResp.Body.Close()
+ if postErr != nil {
+ return auth.AuthenticationResponse{}, fmt.Errorf("failed to read token response: %w", postErr)
}
- output.Header("OIDC Status")
- output.KeyValue("Environment Forced", strconv.FormatBool(result.EnvForced))
- output.KeyValue("Environment Configured", strconv.FormatBool(result.EnvConfigured))
- output.KeyValue("Merge Accounts", strconv.FormatBool(result.MergeAccounts))
- return nil
- },
-}
+ if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {
+ trimmed := strings.TrimSpace(string(tokenBody))
-func init() {
- AuthCmd.AddCommand(loginCmd)
- AuthCmd.AddCommand(logoutCmd)
- AuthCmd.AddCommand(meCmd)
- AuthCmd.AddCommand(passwordCmd)
- AuthCmd.AddCommand(refreshCmd)
- AuthCmd.AddCommand(oidcStatusCmd)
-
- // Login command flags
- loginCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Password command flags
- passwordCmd.Flags().String("current", "", "Current password")
- passwordCmd.Flags().String("new", "", "New password")
- passwordCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Refresh command flags
- refreshCmd.Flags().String("refresh-token", "", "Refresh token")
- refreshCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Global JSON output flags
- logoutCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- meCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- oidcStatusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-}
+ var detail struct {
+ Detail string `json:"detail"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal([]byte(trimmed), &detail) == nil {
+ trimmed = cmp.Or(detail.Detail, detail.Error, trimmed)
+ }
-func extractDeviceAuthErrorCode(body string) string {
- trimmed := strings.TrimSpace(body)
- if trimmed == "" {
- return ""
- }
+ lower := strings.ToLower(trimmed)
+ switch {
+ case strings.Contains(lower, "authorization_pending"):
+ continue
+ case strings.Contains(lower, "slow_down"):
+ pollInterval += 5 * time.Second
+ ticker.Reset(pollInterval)
+ continue
+ case strings.Contains(lower, "expired_token"):
+ return auth.AuthenticationResponse{}, errors.New("device authorization expired; run login again")
+ case strings.Contains(lower, "access_denied"):
+ return auth.AuthenticationResponse{}, errors.New("device authorization denied")
+ case strings.Contains(lower, "mfa_required"):
+ return auth.AuthenticationResponse{}, errors.New("this account has MFA enabled, which browser-based CLI login cannot complete; create a personal API key in " +
+ "Arcane (Account -> API keys) and run: arcane config set api-key <key>")
+ default:
+ return auth.AuthenticationResponse{}, fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))
+ }
+ }
- var detail struct {
- Detail string `json:"detail"`
- Error string `json:"error"`
- }
- if err := json.Unmarshal([]byte(trimmed), &detail); err == nil {
- if detail.Detail != "" {
- trimmed = detail.Detail
- } else if detail.Error != "" {
- trimmed = detail.Error
+ var tokenResult auth.AuthenticationResponse
+ if decodeTokenResponseErr := json.Unmarshal(tokenBody, &tokenResult); decodeTokenResponseErr != nil {
+ return auth.AuthenticationResponse{}, fmt.Errorf("failed to parse token response: %w", decodeTokenResponseErr)
+ }
+ if !tokenResult.Success || tokenResult.Token == "" {
+ return auth.AuthenticationResponse{}, errors.New("device token exchange failed: unexpected response from server")
}
- }
- lower := strings.ToLower(trimmed)
- switch {
- case strings.Contains(lower, "authorization_pending"):
- return "authorization_pending"
- case strings.Contains(lower, "slow_down"):
- return "slow_down"
- case strings.Contains(lower, "expired_token"):
- return "expired_token"
- case strings.Contains(lower, "access_denied"):
- return "access_denied"
- case strings.Contains(lower, "mfa_required"):
- return "mfa_required"
- default:
- return ""
+ return tokenResult, nil
}
}
diff --git a/cli/pkg/auth/cmd_test.go b/cli/pkg/auth/cmd_test.go
deleted file mode 100644
index 539d76c5b..000000000
--- a/cli/pkg/auth/cmd_test.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package auth
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestExtractDeviceAuthErrorCodeClassifiesMFARequired(t *testing.T) {
- // The device-token handler refuses MFA accounts with a huma error, so the
- // code arrives inside "detail"; the bare and "error" forms are covered too
- // because the extractor is the only classifier for this endpoint.
- require.Equal(t, "mfa_required", extractDeviceAuthErrorCode(`{"detail":"mfa_required"}`))
- require.Equal(t, "mfa_required", extractDeviceAuthErrorCode(`{"error":"mfa_required"}`))
- require.Equal(t, "mfa_required", extractDeviceAuthErrorCode("mfa_required"))
- require.Equal(t, "access_denied", extractDeviceAuthErrorCode(`{"detail":"access_denied"}`))
-}
diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.go
index 8ed53cb9a..57e5a31a0 100644
--- a/cli/pkg/auth/federated.go
+++ b/cli/pkg/auth/federated.go
@@ -1,6 +1,7 @@
package auth
import (
+ "cmp"
"encoding/json/v2"
"errors"
"fmt"
@@ -11,9 +12,8 @@ import (
"strings"
"time"
- federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"
+ "github.com/getarcaneapp/arcane/types/v2/federated"
"github.com/spf13/cobra"
- kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/ci"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
@@ -28,11 +28,22 @@ const (
maxFederatedResponseBody = 1 << 20
)
-var federatedCmd = &cobra.Command{
- Use: "federated",
- Short: "Exchange a CI OIDC token for a short-lived Arcane token",
- SilenceUsage: true,
- Long: `Exchange an external OIDC token for a short-lived Arcane bearer token.
+func newFederatedCmd() *cobra.Command {
+ var opts struct {
+ server string
+ audience string
+ provider string
+ token string
+ tokenFile string
+ tokenStdin bool
+ persist bool
+ export bool
+ }
+ cmd := &cobra.Command{
+ Use: "federated",
+ Short: "Exchange a CI OIDC token for a short-lived Arcane token",
+ SilenceUsage: true,
+ Long: `Exchange an external OIDC token for a short-lived Arcane bearer token.
GitHub Actions example:
permissions: { id-token: write, contents: read }
@@ -42,110 +53,110 @@ GitHub Actions example:
--server https://arcane.example.com \
--audience https://arcane.example.com --export)"
- run: arcane-cli projects up my-app`,
- RunE: func(cmd *cobra.Command, args []string) error {
- server, _ := cmd.Flags().GetString("server")
- audience, _ := cmd.Flags().GetString("audience")
- provider, _ := cmd.Flags().GetString("provider")
- persist, _ := cmd.Flags().GetBool("persist")
- exportOutput, _ := cmd.Flags().GetBool("export")
-
- if cmdutil.JSONOutputEnabled(cmd) && exportOutput {
- return errors.New("--json and --export cannot be used together")
- }
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if cmdutil.JSONOutputEnabled(cmd) && opts.export {
+ return errors.New("flags --json and --export cannot be used together")
+ }
+ audience := opts.audience
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
- if strings.TrimSpace(server) != "" {
- cfg.ServerURL = strings.TrimSpace(server)
- }
- if strings.TrimSpace(audience) == "" {
- audience = cfg.FederatedAudience
- }
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+ if strings.TrimSpace(opts.server) != "" {
+ cfg.ServerURL = strings.TrimSpace(opts.server)
+ }
+ if strings.TrimSpace(audience) == "" {
+ audience = cfg.FederatedAudience
+ }
- subjectToken, tokenSource, err := resolveFederatedSubjectTokenInternal(cmd, provider, audience)
- if err != nil {
- return err
- }
+ subjectToken, tokenSource, err := resolveFederatedSubjectToken(cmd, opts.provider, audience, opts.token, opts.tokenFile, opts.tokenStdin)
+ if err != nil {
+ return err
+ }
- c, err := client.NewUnauthenticated(cfg)
- if err != nil {
- return err
- }
+ c, err := client.NewUnauthenticated(cfg)
+ if err != nil {
+ return err
+ }
- tokenResp, err := exchangeFederatedTokenInternal(cmd, c, strings.TrimSpace(subjectToken), strings.TrimSpace(audience))
- if err != nil {
- return err
- }
- if tokenResp.AccessToken == "" {
- return errors.New("federated token exchange failed: empty access token")
- }
+ tokenResp, err := exchangeFederatedToken(cmd, c, strings.TrimSpace(subjectToken), strings.TrimSpace(audience))
+ if err != nil {
+ return err
+ }
+ if tokenResp.AccessToken == "" {
+ return errors.New("federated token exchange failed: empty access token")
+ }
- expiresAt := time.Now().UTC().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
+ expiresAt := time.Now().UTC().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
- if persist {
- cfg.JWTToken = tokenResp.AccessToken
- cfg.APIKey = ""
- cfg.RefreshToken = ""
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to save federated token: %w", saveErr)
+ if opts.persist {
+ cfg.JWTToken = tokenResp.AccessToken
+ cfg.APIKey = ""
+ cfg.RefreshToken = ""
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save federated token: %w", saveErr)
+ }
}
- }
- switch {
- case cmdutil.JSONOutputEnabled(cmd):
- return cmdutil.PrintJSON(map[string]any{
- "token": tokenResp.AccessToken,
- "tokenType": tokenResp.TokenType,
- "expiresIn": tokenResp.ExpiresIn,
- "expiresAt": expiresAt.Format(time.RFC3339),
- "issuedTokenType": tokenResp.IssuedTokenType,
- "source": tokenSource,
- "persisted": persist,
- })
- case exportOutput:
- _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN=%s\n", shellQuoteInternal(tokenResp.AccessToken))
- _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN_EXPIRES_AT=%s\n", shellQuoteInternal(expiresAt.Format(time.RFC3339)))
- default:
- output.Success("Federated token exchange successful")
- output.KeyValue("Token source", tokenSource)
- output.KeyValue("Expires at", expiresAt.Format(time.RFC3339))
- if persist {
- path, _ := config.ConfigPath()
- output.KeyValue("JWT token saved to config", path)
- } else {
- output.Info("Use --export, --json, or --persist to consume the token.")
+ switch {
+ case cmdutil.JSONOutputEnabled(cmd):
+ return cmdutil.PrintJSON(struct {
+ Token string `json:"token"`
+ TokenType string `json:"tokenType"`
+ ExpiresIn int `json:"expiresIn"`
+ ExpiresAt string `json:"expiresAt"`
+ IssuedTokenType string `json:"issuedTokenType"`
+ Source string `json:"source"`
+ Persisted bool `json:"persisted"`
+ }{
+ Token: tokenResp.AccessToken,
+ TokenType: tokenResp.TokenType,
+ ExpiresIn: tokenResp.ExpiresIn,
+ ExpiresAt: expiresAt.Format(time.RFC3339),
+ IssuedTokenType: tokenResp.IssuedTokenType,
+ Source: tokenSource,
+ Persisted: opts.persist,
+ })
+ case opts.export:
+ _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN=%s\n", "'"+strings.ReplaceAll(tokenResp.AccessToken, "'", "'\\''")+"'")
+ _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN_EXPIRES_AT=%s\n", "'"+strings.ReplaceAll(expiresAt.Format(time.RFC3339), "'", "'\\''")+"'")
+ default:
+ output.Success("Federated token exchange successful")
+ output.KeyValue("Token source", tokenSource)
+ output.KeyValue("Expires at", expiresAt.Format(time.RFC3339))
+ if opts.persist {
+ path, _ := config.ConfigPath()
+ output.KeyValue("JWT token saved to config", path)
+ } else {
+ output.Info("Use --export, --json, or --persist to consume the token.")
+ }
}
- }
-
- return nil
- },
-}
-func init() {
- AuthCmd.AddCommand(federatedCmd)
-
- federatedCmd.Flags().String("server", "", "Arcane server URL for this exchange")
- federatedCmd.Flags().String("audience", "", "Audience to request from the external OIDC provider")
- federatedCmd.Flags().String("token", "", "External OIDC token to exchange")
- federatedCmd.Flags().String("token-file", "", "Path to a file containing the external OIDC token")
- federatedCmd.Flags().Bool("token-stdin", false, "Read the external OIDC token from stdin")
- federatedCmd.Flags().String("provider", ci.ProviderAuto, "OIDC token source: auto, github, gitlab, or generic")
- federatedCmd.Flags().Bool("persist", false, "Persist the exchanged Arcane token in CLI config")
- federatedCmd.Flags().Bool("export", false, "Print shell exports for ARCANE_TOKEN and ARCANE_TOKEN_EXPIRES_AT")
- federatedCmd.Flags().Bool("json", false, "Output in JSON format")
+ return nil
+ },
+ }
+ cmd.Flags().StringVar(&opts.server, "server", "", "Arcane server URL for this exchange")
+ cmd.Flags().StringVar(&opts.audience, "audience", "", "Audience to request from the external OIDC provider")
+ cmd.Flags().StringVar(&opts.token, "token", "", "External OIDC token to exchange")
+ cmd.Flags().StringVar(&opts.tokenFile, "token-file", "", "Path to a file containing the external OIDC token")
+ cmd.Flags().BoolVar(&opts.tokenStdin, "token-stdin", false, "Read the external OIDC token from stdin")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.provider, "provider", "", ci.ProviderAuto, "OIDC token source",
+ ci.ProviderAuto, ci.ProviderGitHub, ci.ProviderGitLab, ci.ProviderGeneric)
+ cmd.Flags().BoolVar(&opts.persist, "persist", false, "Persist the exchanged Arcane token in CLI config")
+ cmd.Flags().BoolVar(&opts.export, "export", false, "Print shell exports for ARCANE_TOKEN and ARCANE_TOKEN_EXPIRES_AT")
+ return cmd
}
-func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audience string) (string, string, error) {
- token, _ := cmd.Flags().GetString("token")
+func resolveFederatedSubjectToken(cmd *cobra.Command, provider, audience, federatedToken, federatedTokenFile string, federatedTokenStdin bool) (string, string, error) {
+ token := federatedToken
if strings.TrimSpace(token) != "" {
return strings.TrimSpace(token), "flag", nil
}
- tokenFile, _ := cmd.Flags().GetString("token-file")
- if strings.TrimSpace(tokenFile) != "" {
- data, err := os.ReadFile(strings.TrimSpace(tokenFile))
+ if strings.TrimSpace(federatedTokenFile) != "" {
+ data, err := os.ReadFile(strings.TrimSpace(federatedTokenFile))
if err != nil {
return "", "", fmt.Errorf("failed to read token file: %w", err)
}
@@ -156,9 +167,14 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audience
return token, "file", nil
}
- tokenStdin, _ := cmd.Flags().GetBool("token-stdin")
- if tokenStdin || stdinHasDataInternal() {
- data, err := output.ReadWithContext(cmd.Context(), cmd.InOrStdin(), io.ReadAll)
+ input := cmd.InOrStdin()
+ stdinHasData := false
+ if file, ok := input.(interface{ Stat() (os.FileInfo, error) }); ok {
+ info, err := file.Stat()
+ stdinHasData = err == nil && info.Mode()&os.ModeCharDevice == 0
+ }
+ if federatedTokenStdin || stdinHasData {
+ data, err := output.ReadWithContext(cmd.Context(), input, io.ReadAll)
if err != nil {
return "", "", fmt.Errorf("failed to read token from stdin: %w", err)
}
@@ -172,12 +188,13 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audience
return ci.DetectToken(cmd.Context(), provider, audience, os.Getenv, &http.Client{Timeout: 10 * time.Second})
}
-func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjectToken, audience string) (*federatedtypes.FederatedTokenResponse, error) {
- form := url.Values{}
- form.Set("grant_type", federatedtypes.TokenExchangeGrantType)
- form.Set("subject_token", subjectToken)
- form.Set("subject_token_type", federatedtypes.SubjectTokenTypeJWT)
- form.Set("requested_token_type", federatedtypes.RequestedTokenTypeAccessJWT)
+func exchangeFederatedToken(cmd *cobra.Command, c *client.Client, subjectToken, audience string) (*federated.FederatedTokenResponse, error) {
+ form := url.Values{
+ "grant_type": {federated.TokenExchangeGrantType},
+ "subject_token": {subjectToken},
+ "subject_token_type": {federated.SubjectTokenTypeJWT},
+ "requested_token_type": {federated.RequestedTokenTypeAccessJWT},
+ }
if strings.TrimSpace(audience) != "" {
form.Set("audience", strings.TrimSpace(audience))
}
@@ -192,7 +209,13 @@ func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjec
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFederatedErrorBody))
- return nil, fmt.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, redactedFederatedExchangeMessageInternal(body))
+ var oauthErr struct {
+ Error string `json:"error"`
+ ErrorDescription string `json:"error_description"` //nolint:tagliatelle // RFC 6749 wire shape is snake_case.
+ }
+ _ = json.Unmarshal(body, &oauthErr)
+ message := cmp.Or(strings.TrimSpace(oauthErr.ErrorDescription), strings.TrimSpace(oauthErr.Error), strings.TrimSpace(string(body)), "request rejected")
+ return nil, fmt.Errorf("federated token exchange failed (status %d): %s", resp.StatusCode, message)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFederatedResponseBody))
@@ -200,35 +223,9 @@ func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjec
return nil, fmt.Errorf("failed to read federated token response: %w", err)
}
- var tokenResp federatedtypes.FederatedTokenResponse
+ var tokenResp federated.FederatedTokenResponse
if unmarshalErr := json.Unmarshal(body, &tokenResp); unmarshalErr != nil {
return nil, fmt.Errorf("failed to parse federated token response: %w", unmarshalErr)
}
return &tokenResp, nil
}
-
-func redactedFederatedExchangeMessageInternal(body []byte) string {
- var oauthErr struct {
- Error string `json:"error"`
- ErrorDescription string `json:"error_description"` //nolint:tagliatelle // RFC 6749 wire shape is snake_case.
- }
- if err := json.Unmarshal(body, &oauthErr); err == nil {
- if strings.TrimSpace(oauthErr.ErrorDescription) != "" {
- return strings.TrimSpace(oauthErr.ErrorDescription)
- }
- if strings.TrimSpace(oauthErr.Error) != "" {
- return strings.TrimSpace(oauthErr.Error)
- }
- }
- msg := strings.TrimSpace(string(body))
- return kit.Ternary(msg == "", "request rejected", msg)
-}
-
-func stdinHasDataInternal() bool {
- info, err := os.Stdin.Stat()
- return err == nil && (info.Mode()&os.ModeCharDevice) == 0
-}
-
-func shellQuoteInternal(value string) string {
- return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
-}
diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.go
index 196c36aec..8ca986161 100644
--- a/cli/pkg/backups/cmd.go
+++ b/cli/pkg/backups/cmd.go
@@ -12,364 +12,550 @@ import (
"github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/spf13/cobra"
- kit "go.getarcane.app/kit/pkg"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-
- createDestination string
- createS3Destination string
- createLocal bool
- createRecoveryKey string
- createPolicyID string
-
- deleteRecoveryKey string
-
- restoreRecoveryKey string
-
- uploadS3Destination string
- uploadRecoveryKey string
-
- discoverS3Destination string
- discoverRecoveryKey string
-
- policiesUpdateFile string
- policiesUpdateID string
- policiesUpdateEnabled bool
- policiesUpdateDisabled bool
- policiesUpdateSchedule string
- policiesUpdateRetention int
- policiesUpdateLocal bool
- policiesUpdateS3 bool
- policiesUpdateS3Destination string
-
- generateSave bool
- setRecoveryKey string
-)
-
-// BackupsCmd is the parent command for Arcane system backup operations (admin-only).
-var BackupsCmd = &cobra.Command{
- Use: "backups",
- Aliases: []string{"backup"},
- Short: "Manage Arcane system backups (admin only)",
- Long: `System backups snapshot Arcane's database and configuration, encrypted with the recovery key.
+// Command is the parent command for Arcane system backup operations (admin-only).
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "backups",
+ Aliases: []string{"backup"},
+ Short: "Manage Arcane system backups (admin only)",
+ Long: `System backups snapshot Arcane's database and configuration, encrypted with the recovery key.
Backups are stored in the local repository, a saved S3 destination, or both; policies schedule automatic runs.`,
+ }
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newCreateCmd())
+ cmd.AddCommand(newDeleteCmd())
+ cmd.AddCommand(newRestoreCmd())
+ cmd.AddCommand(newUploadCmd())
+ cmd.AddCommand(newDiscoverCmd())
+ cmd.AddCommand(newPoliciesCmd())
+ cmd.AddCommand(newRecoveryKeyCmd())
+ cmd.AddCommand(newS3Cmd())
+ return cmd
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List Arcane system backups",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List Arcane system backups",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.SystemBackupRun]{
- Resource: "backups",
- Endpoint: types.Backups(),
- Params: cmdutil.ListParams{Resource: "backups", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: cmdutil.JSONOutputEnabled(cmd),
- Headers: []string{"ID", "STATUS", "TRIGGER", "DESTINATION", "SIZE", "S3 DESTINATION", "CREATED"},
- Row: func(run backup.SystemBackupRun) []string {
- size := ""
- if run.Size > 0 {
- size = output.Bytes(run.Size)
- }
- return []string{
- run.ID,
- run.Status,
- run.Trigger,
- string(run.Destination),
- size,
- run.S3DestinationName,
- run.CreatedAt.Format("2006-01-02 15:04"),
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.SystemBackupRun]{
+ Resource: "backups",
+ Endpoint: types.Backups(),
+ Params: cmdutil.ListParams{Resource: "backups", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "STATUS", "TRIGGER", "DESTINATION", "SIZE", "S3 DESTINATION", "CREATED"},
+ Row: func(run backup.SystemBackupRun) []string {
+ return []string{
+ run.ID,
+ run.Status,
+ run.Trigger,
+ string(run.Destination),
+ kit.Ternary(run.Size > 0, output.Bytes(run.Size), ""),
+ run.S3DestinationName,
+ run.CreatedAt.Format("2006-01-02 15:04"),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of backups to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create an Arcane system backup",
- Long: `Create a system backup. With no flags the backup is stored locally; --s3-destination
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ destination backup.SystemBackupDestination
+ s3Destination string
+ local bool
+ recoveryKey string
+ policyID string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create an Arcane system backup",
+ Long: `Create a system backup. With no flags the backup is stored locally; --s3-destination
alone stores it in S3, and --local together with --s3-destination stores it in both.`,
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- s3DestinationID := ""
- if createS3Destination != "" {
- resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, createS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if resolveErr != nil {
- return resolveErr
+ s3DestinationID := ""
+ if opts.s3Destination != "" {
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, opts.s3Destination, cmdutil.AllowPrompt(cmd))
+ if resolveErr != nil {
+ return resolveErr
+ }
+ s3DestinationID = resolved.ID
}
- s3DestinationID = resolved.ID
- }
- destination := backup.SystemBackupDestination(createDestination)
- if cmd.Flags().Changed("destination") {
- switch destination {
- case backup.SystemBackupDestinationLocal, backup.SystemBackupDestinationS3, backup.SystemBackupDestinationLocalS3:
- default:
- return fmt.Errorf("invalid --destination %q: must be local, s3, or local_s3", createDestination)
+ destination := opts.destination
+ if cmd.Flags().Changed("destination") && destination == "" {
+ return fmt.Errorf("invalid --destination %q: must be local, s3, or local_s3", opts.destination)
}
- } else {
- switch {
- case s3DestinationID != "" && createLocal:
- destination = backup.SystemBackupDestinationLocalS3
- case s3DestinationID != "":
- destination = backup.SystemBackupDestinationS3
- default:
- destination = backup.SystemBackupDestinationLocal
+ if !cmd.Flags().Changed("destination") {
+ switch {
+ case s3DestinationID != "" && opts.local:
+ destination = backup.SystemBackupDestinationLocalS3
+ case s3DestinationID != "":
+ destination = backup.SystemBackupDestinationS3
+ default:
+ destination = backup.SystemBackupDestinationLocal
+ }
+ }
+ if (destination == backup.SystemBackupDestinationS3 || destination == backup.SystemBackupDestinationLocalS3) && s3DestinationID == "" {
+ return fmt.Errorf("--destination %s requires --s3-destination", destination)
}
- }
- if (destination == backup.SystemBackupDestinationS3 || destination == backup.SystemBackupDestinationLocalS3) && s3DestinationID == "" {
- return fmt.Errorf("--destination %s requires --s3-destination", destination)
- }
- req := backup.CreateSystemBackupRequest{
- Destination: destination,
- S3DestinationID: s3DestinationID,
- RecoveryKey: createRecoveryKey,
- PolicyID: createPolicyID,
- }
+ req := backup.CreateSystemBackupRequest{
+ Destination: destination,
+ S3DestinationID: s3DestinationID,
+ RecoveryKey: opts.recoveryKey,
+ PolicyID: opts.policyID,
+ }
- run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.Backups(), req)
- if err != nil {
- return fmt.Errorf("failed to create backup: %w", err)
- }
+ run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.Backups(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create backup: %w", err)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(run)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(run)
+ }
- output.Success("Backup %s created successfully", run.ID)
- output.KeyValue("ID", run.ID)
- output.KeyValue("Status", run.Status)
- output.KeyValue("Destination", string(run.Destination))
- if run.Size > 0 {
- output.KeyValue("Size", output.Bytes(run.Size))
- }
- if run.S3DestinationName != "" {
- output.KeyValue("S3 Destination", run.S3DestinationName)
- }
- return nil
- },
+ output.Success("Backup %s created successfully", run.ID)
+ output.KeyValue("ID", run.ID)
+ output.KeyValue("Status", run.Status)
+ output.KeyValue("Destination", string(run.Destination))
+ if run.Size > 0 {
+ output.KeyValue("Size", output.Bytes(run.Size))
+ }
+ if run.S3DestinationName != "" {
+ output.KeyValue("S3 Destination", run.S3DestinationName)
+ }
+ return nil
+ },
+ }
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.destination, "destination", "", "",
+ "Backup destination (inferred from --local/--s3-destination when omitted)",
+ backup.SystemBackupDestinationLocal, backup.SystemBackupDestinationS3, backup.SystemBackupDestinationLocalS3)
+ cmd.Flags().StringVar(&opts.s3Destination, "s3-destination", "", "S3 destination name or ID")
+ cmd.Flags().BoolVar(&opts.local, "local", false, "Also keep a local copy when backing up to S3")
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key used to encrypt the backup")
+ cmd.Flags().StringVar(&opts.policyID, "policy", "", "Backup policy ID to associate with the run")
+ return cmd
}
-var deleteCmd = &cobra.Command{
- Use: "delete <backup-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete an Arcane system backup",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete backup %s?", args[0]))
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ recoveryKey string
+ }
+ cmd := &cobra.Command{
+ Use: "delete <backup-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete an Arcane system backup",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete backup %s?", args[0]),
+ Path: types.Backup(args[0]),
+ Body: backup.DeleteSystemBackupRequest{RecoveryKey: opts.recoveryKey},
+ FailureMessage: "failed to delete backup",
+ SuccessMessage: fmt.Sprintf("Backup %s deleted successfully", args[0]),
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key (required to delete remote snapshots)")
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Delete without confirmation")
+ return cmd
+}
- result, err := c.DoJSON[base.ApiResponse[base.MessageResponse]](cmd.Context(), http.MethodDelete, types.Backup(args[0]), backup.DeleteSystemBackupRequest{RecoveryKey: deleteRecoveryKey})
- if err != nil {
- return fmt.Errorf("failed to delete backup: %w", err)
- }
+func newRestoreCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ recoveryKey string
+ }
+ cmd := &cobra.Command{
+ Use: "restore <backup-id>",
+ Short: "Restore Arcane from a system backup",
+ Long: `Restore overwrites the current Arcane database and configuration with the backup contents, then restarts Arcane.`,
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !opts.force {
+ output.Warning("Restoring backup %s will OVERWRITE the current Arcane database and configuration, then restart Arcane. This cannot be undone.", args[0])
+ }
+ confirmed, confirmErr := cmdutil.ConfirmOrCancel(cmd, opts.force, "Are you absolutely sure you want to restore this backup?")
+ if confirmErr != nil || !confirmed {
+ return confirmErr
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
+ key := opts.recoveryKey
+ if key == "" {
+ var err error
+ if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {
+ return fmt.Errorf("failed to read recovery key: %w", err)
+ }
+ if key == "" {
+ return errors.New("recovery key is required")
+ }
+ }
- output.Success("Backup %s deleted successfully", args[0])
- return nil
- },
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.BackupRestore(args[0]),
+ Body: backup.RestoreSystemBackupRequest{RecoveryKey: key},
+ FailureMessage: "failed to restore backup",
+ Render: func(data base.MessageResponse) error {
+ output.Success("%s", data.Message)
+ output.Warning("Arcane will restart while the restore is applied; the server may be unavailable for a short time.")
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key the backup was encrypted with (prompted for when omitted)")
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Restore without confirmation")
+ return cmd
}
-var restoreCmd = &cobra.Command{
- Use: "restore <backup-id>",
- Short: "Restore Arcane from a system backup",
- Long: `Restore overwrites the current Arcane database and configuration with the backup contents, then restarts Arcane.`,
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- output.Warning("Restoring backup %s will OVERWRITE the current Arcane database and configuration, then restart Arcane. This cannot be undone.", args[0])
- confirmed, err := cmdutil.Confirm(cmd, "Are you absolutely sure you want to restore this backup?")
+func newUploadCmd() *cobra.Command {
+ var opts struct {
+ s3Destination string
+ recoveryKey string
+ }
+ cmd := &cobra.Command{
+ Use: "upload <backup-id>",
+ Short: "Upload an Arcane system backup to an S3 destination",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, opts.s3Destination, cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
}
- }
- key := restoreRecoveryKey
- if key == "" {
- var err error
- if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {
- return fmt.Errorf("failed to read recovery key: %w", err)
+ req := backup.UploadSystemBackupRequest{
+ S3DestinationID: resolved.ID,
+ RecoveryKey: opts.recoveryKey,
}
- if key == "" {
- return errors.New("recovery key is required")
+
+ run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.BackupUpload(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to upload backup: %w", err)
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(run)
+ }
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.BackupRestore(args[0]), backup.RestoreSystemBackupRequest{RecoveryKey: key})
- if err != nil {
- return fmt.Errorf("failed to restore backup: %w", err)
- }
+ output.Success("Backup %s uploaded successfully", run.ID)
+ output.KeyValue("Destination", string(run.Destination))
+ if run.S3DestinationName != "" {
+ output.KeyValue("S3 Destination", run.S3DestinationName)
+ }
+ return nil
+ },
+ }
+ cmd.Flags().StringVar(&opts.s3Destination, "s3-destination", "", "S3 destination name or ID to upload to")
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key the backup was encrypted with")
+ _ = cmd.MarkFlagRequired("s3-destination")
+ return cmd
+}
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
+func newDiscoverCmd() *cobra.Command {
+ var opts struct {
+ s3Destination string
+ recoveryKey string
+ }
+ cmd := &cobra.Command{
+ Use: "discover",
+ Short: "Discover Arcane system backups stored in an S3 destination",
+ Long: `Discover scans an S3 destination for backups and imports records for any not already known to this Arcane instance.`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("%s", result.Data.Message)
- output.Warning("Arcane will restart while the restore is applied; the server may be unavailable for a short time.")
- return nil
- },
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, opts.s3Destination, cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
+
+ req := backup.DiscoverSystemBackupsRequest{
+ S3DestinationID: resolved.ID,
+ RecoveryKey: opts.recoveryKey,
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[int]{
+ Method: http.MethodPost,
+ Path: types.BackupsDiscover(),
+ Body: req,
+ FailureMessage: "failed to discover backups",
+ Render: func(data int) error {
+ output.Success("Discovered %d backup(s)", data)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.s3Destination, "s3-destination", "", "S3 destination name or ID to search")
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key the backups were encrypted with")
+ _ = cmd.MarkFlagRequired("s3-destination")
+ return cmd
}
-var uploadCmd = &cobra.Command{
- Use: "upload <backup-id>",
- Short: "Upload an Arcane system backup to an S3 destination",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newPoliciesCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "policies",
+ Short: "Show Arcane system backup policies",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, uploadS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
- }
+ result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
+ if err != nil {
+ return fmt.Errorf("failed to get backup policies: %w", err)
+ }
- req := backup.UploadSystemBackupRequest{
- S3DestinationID: resolved.ID,
- RecoveryKey: uploadRecoveryKey,
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
+ }
- run, err := c.DoJSON[backup.SystemBackupRun](cmd.Context(), http.MethodPost, types.BackupUpload(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to upload backup: %w", err)
- }
+ return renderSystemPolicies(result)
+ },
+ }
+ cmd.AddCommand(newPoliciesUpdateCmd())
+ return cmd
+}
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(run)
- }
+func newPoliciesUpdateCmd() *cobra.Command {
+ var opts policiesUpdateOptions
+ cmd := &cobra.Command{
+ Use: "update",
+ Short: "Update Arcane system backup policies",
+ Long: `Update a system backup policy with flags: the current policies are fetched, the targeted
+policy is modified, and the whole set is saved back. A new policy is created when none exist.
+Alternatively, --file replaces all policies from a raw JSON payload.`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ req, err := opts.request(cmd, c)
+ if err != nil {
+ return err
+ }
+
+ result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodPut, types.BackupsPolicies(), req)
+ if err != nil {
+ return fmt.Errorf("failed to update backup policies: %w", err)
+ }
- output.Success("Backup %s uploaded successfully", run.ID)
- output.KeyValue("Destination", string(run.Destination))
- if run.S3DestinationName != "" {
- output.KeyValue("S3 Destination", run.S3DestinationName)
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
+ }
+
+ output.Success("Backup policies updated successfully")
+ return renderSystemPolicies(result)
+ },
+ }
+ cmd.Flags().StringVar(&opts.file, "file", "", "JSON file with the full policies payload (use - for stdin); replaces all policies")
+ cmd.Flags().StringVar(&opts.id, "policy-id", "", "Policy ID to update (defaults to the sole policy)")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable the policy")
+ cmd.Flags().BoolVar(&opts.disabled, "disabled", false, "Disable the policy")
+ cmd.Flags().StringVar(&opts.schedule, "schedule", "", "Cron schedule for automatic backups")
+ cmd.Flags().IntVar(&opts.retention, "retention", 0, "Number of backups to retain")
+ cmd.Flags().BoolVar(&opts.local, "local", false, "Store backups in the local repository")
+ cmd.Flags().BoolVar(&opts.s3, "s3", false, "Store backups in the S3 destination")
+ cmd.Flags().StringVar(&opts.s3Destination, "s3-destination", "", "S3 destination name or ID (implies --s3)")
+ _ = cmd.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
+ if conflictErr := cmdutil.ExclusiveFlags(cmd, "enabled", "disabled"); conflictErr != nil {
+ return conflictErr
+ }
+ if !cmd.Flags().Changed("file") {
+ return nil
+ }
+ for _, name := range []string{"policy-id", "enabled", "disabled", "schedule", "retention", "local", "s3", "s3-destination"} {
+ if cmd.Flags().Changed(name) {
+ return fmt.Errorf("--file cannot be combined with --%s", name)
+ }
}
return nil
- },
+ }
+ return cmd
}
-var discoverCmd = &cobra.Command{
- Use: "discover",
- Short: "Discover Arcane system backups stored in an S3 destination",
- Long: `Discover scans an S3 destination for backups and imports records for any not already known to this Arcane instance.`,
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, discoverS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
- }
+func newRecoveryKeyCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "recovery",
+ Short: "Manage the Arcane system backup recovery key",
+ }
+ cmd.AddCommand(newRecoveryKeyGenerateCmd())
+ cmd.AddCommand(newRecoveryKeySetCmd())
+ return cmd
+}
- req := backup.DiscoverSystemBackupsRequest{
- S3DestinationID: resolved.ID,
- RecoveryKey: discoverRecoveryKey,
- }
+func newRecoveryKeyGenerateCmd() *cobra.Command {
+ var opts struct {
+ save bool
+ }
+ cmd := &cobra.Command{
+ Use: "generate",
+ Short: "Generate a new Arcane system backup recovery key",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.PostJSON[int](cmd.Context(), types.BackupsDiscover(), req)
- if err != nil {
- return fmt.Errorf("failed to discover backups: %w", err)
- }
+ result, err := c.DoJSON[backup.SystemBackupRecoveryKey](cmd.Context(), http.MethodPost, types.BackupsRecoveryKeyGenerate(), nil)
+ if err != nil {
+ return fmt.Errorf("failed to generate recovery key: %w", err)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
+ jsonMode := cmdutil.JSONOutputEnabled(cmd)
+ if !jsonMode {
+ output.Header("Generated Recovery Key")
+ _, _ = fmt.Fprintln(output.Stdout(), result.RecoveryKey)
+ output.Warning("Store this recovery key somewhere safe. Backups encrypted with it cannot be restored without it.")
+ }
- output.Success("Discovered %d backup(s)", result.Data)
- return nil
- },
+ save := opts.save
+ if !save && cmdutil.AllowPrompt(cmd) {
+ save, err = cmdutil.Confirm(cmd, "Store this recovery key on the server now?")
+ if err != nil {
+ return err
+ }
+ }
+ if !save {
+ if jsonMode {
+ return cmdutil.PrintJSON(result)
+ }
+ _, _ = fmt.Fprintln(output.Stdout(), "Run `arcane admin backups recovery set` to store it on the server later.")
+ return nil
+ }
+ storeRequest := backup.SystemBackupRecoveryKey{RecoveryKey: result.RecoveryKey}
+ if _, storeErr := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), storeRequest); storeErr != nil {
+ return fmt.Errorf("failed to store recovery key: %w", storeErr)
+ }
+ if jsonMode {
+ return cmdutil.PrintJSON(result)
+ }
+ output.Success("Recovery key stored on the server")
+ return nil
+ },
+ }
+ cmd.Flags().BoolVar(&opts.save, "save", false, "Store the generated recovery key on the server")
+ return cmd
}
-var policiesCmd = &cobra.Command{
- Use: "policies",
- Short: "Show Arcane system backup policies",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newRecoveryKeySetCmd() *cobra.Command {
+ var opts struct {
+ recoveryKey string
+ }
+ cmd := &cobra.Command{
+ Use: "set",
+ Short: "Configure the Arcane system backup recovery key",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ key := opts.recoveryKey
+ if key == "" {
+ var err error
+ if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {
+ return fmt.Errorf("failed to read recovery key: %w", err)
+ }
+ }
+ if key == "" {
+ return errors.New("recovery key is required; use --recovery-key")
+ }
- result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
- if err != nil {
- return fmt.Errorf("failed to get backup policies: %w", err)
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result)
- }
+ status, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
+ if err != nil {
+ return fmt.Errorf("failed to set recovery key: %w", err)
+ }
- return printPolicies(result)
- },
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(status)
+ }
+
+ output.Success("Recovery key configured successfully")
+ return nil
+ },
+ }
+ cmd.Flags().StringVar(&opts.recoveryKey, "recovery-key", "", "Recovery key to store (prompted for when omitted)")
+ return cmd
}
-func printPolicies(result backup.SystemBackupPolicyCollection) error {
+func renderSystemPolicies(policies backup.SystemBackupPolicyCollection) error {
output.Header("System Backup Policies")
- recoveryKey := kit.Ternary(result.RecoveryKeyStored, "Configured", "Not configured")
- output.KeyValue("Recovery Key", recoveryKey)
+ output.KeyValue("Recovery Key", kit.Ternary(policies.RecoveryKeyStored, "Configured", "Not configured"))
headers := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "LOCAL", "S3", "S3 DESTINATION", "LAST RUN"}
- rows := make([][]string, len(result.Policies))
- for i, policy := range result.Policies {
+ rows := make([][]string, len(policies.Policies))
+ for i, policy := range policies.Policies {
lastRun := ""
if policy.LastRun != nil {
lastRun = fmt.Sprintf("%s (%s)", policy.LastRun.CreatedAt.Format("2006-01-02 15:04"), policy.LastRun.Status)
@@ -388,285 +574,103 @@ func printPolicies(result backup.SystemBackupPolicyCollection) error {
return output.Table(headers, rows)
}
-var policiesUpdateCmd = &cobra.Command{
- Use: "update",
- Short: "Update Arcane system backup policies",
- Long: `Update a system backup policy with flags: the current policies are fetched, the targeted
-policy is modified, and the whole set is saved back. A new policy is created when none exist.
-Alternatively, --file replaces all policies from a raw JSON payload.`,
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- var req backup.UpdateSystemBackupPolicies
- if policiesUpdateFile != "" {
- for _, name := range []string{"policy-id", "enabled", "disabled", "schedule", "retention", "local", "s3", "s3-destination"} {
- if cmd.Flags().Changed(name) {
- return fmt.Errorf("--file cannot be combined with --%s", name)
- }
- }
+type policiesUpdateOptions struct {
+ file string
+ id string
+ enabled bool
+ disabled bool
+ schedule string
+ retention int
+ local bool
+ s3 bool
+ s3Destination string
+}
- var data []byte
- if policiesUpdateFile == "-" {
- data, err = io.ReadAll(os.Stdin)
- if err != nil {
- return fmt.Errorf("failed to read policies from stdin: %w", err)
- }
- } else {
- data, err = os.ReadFile(policiesUpdateFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", policiesUpdateFile, err)
- }
- }
- if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
- return fmt.Errorf("failed to parse policies file: %w", unmarshalErr)
+func (opts policiesUpdateOptions) request(cmd *cobra.Command, c *client.Client) (backup.UpdateSystemBackupPolicies, error) {
+ var req backup.UpdateSystemBackupPolicies
+ var err error
+ if opts.file != "" {
+ var data []byte
+ if opts.file == "-" {
+ data, err = io.ReadAll(os.Stdin)
+ if err != nil {
+ return req, fmt.Errorf("failed to read policies from stdin: %w", err)
}
} else {
- current, getPoliciesErr := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
- if getPoliciesErr != nil {
- return fmt.Errorf("failed to get current backup policies: %w", getPoliciesErr)
- }
-
- req.Policies = make([]backup.UpdateSystemBackupPolicy, len(current.Policies))
- targetIndex := -1
- for i, p := range current.Policies {
- req.Policies[i] = backup.UpdateSystemBackupPolicy{
- ID: p.ID,
- Enabled: p.Enabled,
- Schedule: p.Schedule,
- RetentionCount: p.RetentionCount,
- LocalEnabled: p.LocalEnabled,
- S3Enabled: p.S3Enabled,
- S3DestinationID: p.S3DestinationID,
- }
- if policiesUpdateID != "" && p.ID == policiesUpdateID {
- targetIndex = i
- }
- }
-
- switch {
- case policiesUpdateID != "" && targetIndex == -1:
- return fmt.Errorf("policy %q not found; run `arcane admin backups policies`", policiesUpdateID)
- case policiesUpdateID == "" && len(req.Policies) > 1:
- return fmt.Errorf("%d backup policies exist; select one with --policy-id", len(req.Policies))
- case policiesUpdateID == "" && len(req.Policies) == 1:
- targetIndex = 0
- case targetIndex == -1:
- if !cmd.Flags().Changed("schedule") {
- return errors.New("--schedule is required when creating a new backup policy")
- }
- // New policies default to local storage unless --local was set explicitly.
- req.Policies = append(req.Policies, backup.UpdateSystemBackupPolicy{LocalEnabled: !cmd.Flags().Changed("local") || policiesUpdateLocal})
- targetIndex = len(req.Policies) - 1
- }
-
- target := &req.Policies[targetIndex]
- if cmd.Flags().Changed("enabled") {
- target.Enabled = true
- }
- if cmd.Flags().Changed("disabled") {
- target.Enabled = false
- }
- if cmd.Flags().Changed("schedule") {
- target.Schedule = policiesUpdateSchedule
- }
- if cmd.Flags().Changed("retention") {
- target.RetentionCount = policiesUpdateRetention
- }
- if cmd.Flags().Changed("local") {
- target.LocalEnabled = policiesUpdateLocal
+ data, err = os.ReadFile(opts.file)
+ if err != nil {
+ return req, fmt.Errorf("failed to read file %s: %w", opts.file, err)
}
- if cmd.Flags().Changed("s3") {
- target.S3Enabled = policiesUpdateS3
+ }
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return req, fmt.Errorf("failed to parse policies file: %w", unmarshalErr)
+ }
+ } else {
+ current, getPoliciesErr := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
+ if getPoliciesErr != nil {
+ return req, fmt.Errorf("failed to get current backup policies: %w", getPoliciesErr)
+ }
+
+ req.Policies = make([]backup.UpdateSystemBackupPolicy, len(current.Policies))
+ targetIndex := -1
+ for i, p := range current.Policies {
+ req.Policies[i] = backup.UpdateSystemBackupPolicy{
+ ID: p.ID,
+ Enabled: p.Enabled,
+ Schedule: p.Schedule,
+ RetentionCount: p.RetentionCount,
+ LocalEnabled: p.LocalEnabled,
+ S3Enabled: p.S3Enabled,
+ S3DestinationID: p.S3DestinationID,
}
- if cmd.Flags().Changed("s3-destination") {
- resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, policiesUpdateS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if resolveErr != nil {
- return resolveErr
- }
- target.S3DestinationID = resolved.ID
- if !cmd.Flags().Changed("s3") {
- target.S3Enabled = true
- }
+ if opts.id != "" && p.ID == opts.id {
+ targetIndex = i
}
}
- result, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodPut, types.BackupsPolicies(), req)
- if err != nil {
- return fmt.Errorf("failed to update backup policies: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result)
- }
-
- output.Success("Backup policies updated successfully")
- return printPolicies(result)
- },
-}
-
-var recoveryKeyCmd = &cobra.Command{
- Use: "recovery",
- Short: "Manage the Arcane system backup recovery key",
-}
-
-var recoveryKeyGenerateCmd = &cobra.Command{
- Use: "generate",
- Short: "Generate a new Arcane system backup recovery key",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.DoJSON[backup.SystemBackupRecoveryKey](cmd.Context(), http.MethodPost, types.BackupsRecoveryKeyGenerate(), nil)
- if err != nil {
- return fmt.Errorf("failed to generate recovery key: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- if generateSave {
- if storeRecoveryKeyErr := storeRecoveryKey(cmd, c, result.RecoveryKey); storeRecoveryKeyErr != nil {
- return storeRecoveryKeyErr
- }
+ switch {
+ case opts.id != "" && targetIndex == -1:
+ return req, fmt.Errorf("policy %q not found; run `arcane admin backups policies`", opts.id)
+ case opts.id == "" && len(req.Policies) > 1:
+ return req, fmt.Errorf("%d backup policies exist; select one with --policy-id", len(req.Policies))
+ case opts.id == "" && len(req.Policies) == 1:
+ targetIndex = 0
+ case targetIndex == -1:
+ if !cmd.Flags().Changed("schedule") {
+ return req, errors.New("--schedule is required when creating a new backup policy")
}
- return cmdutil.PrintJSON(result)
+ // New policies default to local storage unless --local was set explicitly.
+ req.Policies = append(req.Policies, backup.UpdateSystemBackupPolicy{LocalEnabled: !cmd.Flags().Changed("local") || opts.local})
+ targetIndex = len(req.Policies) - 1
}
- output.Header("Generated Recovery Key")
- _, _ = fmt.Fprintln(output.Stdout(), result.RecoveryKey)
- output.Warning("Store this recovery key somewhere safe. Backups encrypted with it cannot be restored without it.")
-
- save := generateSave
- if !save && prompt.IsInteractive() {
- save, err = cmdutil.Confirm(cmd, "Store this recovery key on the server now?")
- if err != nil {
- return err
- }
+ target := &req.Policies[targetIndex]
+ if cmd.Flags().Changed("enabled") || cmd.Flags().Changed("disabled") {
+ target.Enabled = opts.enabled && !opts.disabled
}
- if !save {
- _, _ = fmt.Fprintln(output.Stdout(), "Run `arcane admin backups recovery set` to store it on the server later.")
- return nil
+ if cmd.Flags().Changed("schedule") {
+ target.Schedule = opts.schedule
}
- if storeRotatedRecoveryKeyErr := storeRecoveryKey(cmd, c, result.RecoveryKey); storeRotatedRecoveryKeyErr != nil {
- return storeRotatedRecoveryKeyErr
+ if cmd.Flags().Changed("retention") {
+ target.RetentionCount = opts.retention
}
- output.Success("Recovery key stored on the server")
- return nil
- },
-}
-
-var recoveryKeySetCmd = &cobra.Command{
- Use: "set",
- Short: "Configure the Arcane system backup recovery key",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- key := setRecoveryKey
- if key == "" {
- var err error
- if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {
- return fmt.Errorf("failed to read recovery key: %w", err)
- }
- }
- if key == "" {
- return errors.New("recovery key is required; use --recovery-key")
+ if cmd.Flags().Changed("local") {
+ target.LocalEnabled = opts.local
}
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
+ if cmd.Flags().Changed("s3") {
+ target.S3Enabled = opts.s3
}
-
- status, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
- if err != nil {
- return fmt.Errorf("failed to set recovery key: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(status)
+ if cmd.Flags().Changed("s3-destination") {
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, opts.s3Destination, cmdutil.AllowPrompt(cmd))
+ if resolveErr != nil {
+ return req, resolveErr
+ }
+ target.S3DestinationID = resolved.ID
+ if !cmd.Flags().Changed("s3") {
+ target.S3Enabled = true
+ }
}
-
- output.Success("Recovery key configured successfully")
- return nil
- },
-}
-
-func storeRecoveryKey(cmd *cobra.Command, c *client.Client, key string) error {
- _, err := c.DoJSON[backup.SystemBackupRecoveryKeyStatus](cmd.Context(), http.MethodPut, types.BackupsRecoveryKey(), backup.SystemBackupRecoveryKey{RecoveryKey: key})
- if err != nil {
- return fmt.Errorf("failed to store recovery key: %w", err)
}
- return nil
-}
-func init() {
- BackupsCmd.AddCommand(listCmd)
- BackupsCmd.AddCommand(createCmd)
- BackupsCmd.AddCommand(deleteCmd)
- BackupsCmd.AddCommand(restoreCmd)
- BackupsCmd.AddCommand(uploadCmd)
- BackupsCmd.AddCommand(discoverCmd)
- BackupsCmd.AddCommand(policiesCmd)
- BackupsCmd.AddCommand(recoveryKeyCmd)
-
- policiesCmd.AddCommand(policiesUpdateCmd)
- recoveryKeyCmd.AddCommand(recoveryKeyGenerateCmd)
- recoveryKeyCmd.AddCommand(recoveryKeySetCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of backups to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&createDestination, "destination", "", "Backup destination: local, s3, or local_s3 (inferred from --local/--s3-destination when omitted)")
- createCmd.Flags().StringVar(&createS3Destination, "s3-destination", "", "S3 destination name or ID")
- createCmd.Flags().BoolVar(&createLocal, "local", false, "Also keep a local copy when backing up to S3")
- createCmd.Flags().StringVar(&createRecoveryKey, "recovery-key", "", "Recovery key used to encrypt the backup")
- createCmd.Flags().StringVar(&createPolicyID, "policy", "", "Backup policy ID to associate with the run")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().StringVar(&deleteRecoveryKey, "recovery-key", "", "Recovery key (required to delete remote snapshots)")
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Delete without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- restoreCmd.Flags().StringVar(&restoreRecoveryKey, "recovery-key", "", "Recovery key the backup was encrypted with (prompted for when omitted)")
- restoreCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Restore without confirmation")
- restoreCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- uploadCmd.Flags().StringVar(&uploadS3Destination, "s3-destination", "", "S3 destination name or ID to upload to")
- uploadCmd.Flags().StringVar(&uploadRecoveryKey, "recovery-key", "", "Recovery key the backup was encrypted with")
- uploadCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = uploadCmd.MarkFlagRequired("s3-destination")
-
- discoverCmd.Flags().StringVar(&discoverS3Destination, "s3-destination", "", "S3 destination name or ID to search")
- discoverCmd.Flags().StringVar(&discoverRecoveryKey, "recovery-key", "", "Recovery key the backups were encrypted with")
- discoverCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = discoverCmd.MarkFlagRequired("s3-destination")
-
- policiesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- policiesUpdateCmd.Flags().StringVar(&policiesUpdateFile, "file", "", "JSON file with the full policies payload (use - for stdin); replaces all policies")
- policiesUpdateCmd.Flags().StringVar(&policiesUpdateID, "policy-id", "", "Policy ID to update (defaults to the sole policy)")
- policiesUpdateCmd.Flags().BoolVar(&policiesUpdateEnabled, "enabled", false, "Enable the policy")
- policiesUpdateCmd.Flags().BoolVar(&policiesUpdateDisabled, "disabled", false, "Disable the policy")
- policiesUpdateCmd.Flags().StringVar(&policiesUpdateSchedule, "schedule", "", "Cron schedule for automatic backups")
- policiesUpdateCmd.Flags().IntVar(&policiesUpdateRetention, "retention", 0, "Number of backups to retain")
- policiesUpdateCmd.Flags().BoolVar(&policiesUpdateLocal, "local", false, "Store backups in the local repository")
- policiesUpdateCmd.Flags().BoolVar(&policiesUpdateS3, "s3", false, "Store backups in the S3 destination")
- policiesUpdateCmd.Flags().StringVar(&policiesUpdateS3Destination, "s3-destination", "", "S3 destination name or ID (implies --s3)")
- policiesUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- policiesUpdateCmd.MarkFlagsMutuallyExclusive("enabled", "disabled")
-
- recoveryKeyGenerateCmd.Flags().BoolVar(&generateSave, "save", false, "Store the generated recovery key on the server")
- recoveryKeyGenerateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- recoveryKeySetCmd.Flags().StringVar(&setRecoveryKey, "recovery-key", "", "Recovery key to store (prompted for when omitted)")
- recoveryKeySetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return req, nil
}
diff --git a/cli/pkg/backups/resolve.go b/cli/pkg/backups/resolve.go
index 2df231731..1ac2317a2 100644
--- a/cli/pkg/backups/resolve.go
+++ b/cli/pkg/backups/resolve.go
@@ -13,9 +13,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-// s3DestinationRef resolves an S3 destination by ID or name: exact ID via the
-// GET endpoint, then exact name (case-insensitive), then substring match over
-// the saved destinations.
+// s3DestinationRef resolves exact IDs, then case-insensitive names and substrings.
var s3DestinationRef = cmdutil.ResourceRef[backup.S3Destination, backup.S3Destination]{
Singular: "S3 destination",
Plural: "S3 destinations",
diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.go
index 85efba631..efce6c187 100644
--- a/cli/pkg/backups/s3.go
+++ b/cli/pkg/backups/s3.go
@@ -4,117 +4,128 @@ import (
"errors"
"fmt"
"net/http"
+ "slices"
"strconv"
"github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- s3Name string
- s3Endpoint string
- s3Bucket string
- s3Region string
- s3AccessKeyID string
- s3SecretAccessKey string
- s3Prefix string
- s3UseSSL bool
- s3ForcePathStyle bool
+func newS3Cmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "s3",
+ Short: "Manage S3 backup destinations",
+ }
+ cmd.AddCommand(newS3ListCmd())
+ cmd.AddCommand(newS3GetCmd())
+ cmd.AddCommand(newS3CreateCmd())
+ cmd.AddCommand(newS3UpdateCmd())
+ cmd.AddCommand(newS3DeleteCmd())
+ cmd.AddCommand(newS3TestCmd())
+ return cmd
+}
- s3GetInUse bool
-)
+func newS3ListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List S3 backup destinations",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var s3Cmd = &cobra.Command{
- Use: "s3",
- Short: "Manage S3 backup destinations",
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.S3Destination]{
+ Resource: "S3 destinations",
+ Endpoint: types.BackupsS3(),
+ Params: cmdutil.ListParams{Resource: "s3 destinations", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "BUCKET", "REGION", "ENDPOINT", "SSL", "SECRET"},
+ Row: func(dest backup.S3Destination) []string {
+ return []string{
+ dest.ID,
+ dest.Name,
+ dest.Bucket,
+ dest.Region,
+ dest.Endpoint,
+ strconv.FormatBool(dest.UseSSL),
+ kit.Ternary(dest.SecretConfigured, "Set", "Not set"),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of destinations to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
}
-var s3ListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List S3 backup destinations",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newS3GetCmd() *cobra.Command {
+ var opts struct {
+ inUse bool
+ }
+ cmd := &cobra.Command{
+ Use: "get <destination>",
+ Short: "Get S3 destination details by name or ID",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[backup.S3Destination]{
- Resource: "S3 destinations",
- Endpoint: types.BackupsS3(),
- Params: cmdutil.ListParams{Resource: "s3 destinations", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: cmdutil.JSONOutputEnabled(cmd),
- Headers: []string{"ID", "NAME", "BUCKET", "REGION", "ENDPOINT", "SSL", "SECRET"},
- Row: func(dest backup.S3Destination) []string {
- secret := "Not set"
- if dest.SecretConfigured {
- secret = "Set"
- }
- return []string{
- dest.ID,
- dest.Name,
- dest.Bucket,
- dest.Region,
- dest.Endpoint,
- strconv.FormatBool(dest.UseSSL),
- secret,
- }
- },
- })
- },
-}
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
+ dest := *resolved
-var s3GetCmd = &cobra.Command{
- Use: "get <destination>",
- Short: "Get S3 destination details by name or ID",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ if !opts.inUse {
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(dest)
+ }
+ printS3Destination(dest)
+ return nil
+ }
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
- }
- dest := *resolved
+ usage, err := c.DoJSON[backup.S3DestinationUsage](cmd.Context(), http.MethodGet, types.BackupsS3DestinationInUse(resolved.ID), nil)
+ if err != nil {
+ return fmt.Errorf("failed to check S3 destination usage: %w", err)
+ }
- if !s3GetInUse {
if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(dest)
+ return cmdutil.PrintJSON(struct {
+ Destination backup.S3Destination `json:"destination"`
+ InUse bool `json:"inUse"`
+ }{Destination: dest, InUse: usage.InUse})
}
+
printS3Destination(dest)
+ if usage.InUse {
+ output.KeyValue("In Use", "Yes (referenced by backups, policies, or settings)")
+ } else {
+ output.KeyValue("In Use", "No")
+ }
return nil
- }
-
- usage, err := c.DoJSON[struct {
- InUse bool `json:"inUse"`
- }](cmd.Context(), http.MethodGet, types.BackupsS3DestinationInUse(resolved.ID), nil)
- if err != nil {
- return fmt.Errorf("failed to check S3 destination usage: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(map[string]any{"destination": dest, "inUse": usage.InUse})
- }
-
- printS3Destination(dest)
- if usage.InUse {
- output.KeyValue("In Use", "Yes (referenced by backups, policies, or settings)")
- } else {
- output.KeyValue("In Use", "No")
- }
- return nil
- },
+ },
+ }
+ cmd.Flags().BoolVar(&opts.inUse, "in-use", false, "Also report whether the destination is still referenced")
+ return cmd
}
func printS3Destination(dest backup.S3Destination) {
@@ -136,217 +147,171 @@ func printS3Destination(dest backup.S3Destination) {
output.KeyValue("Created", dest.CreatedAt.Format("2006-01-02 15:04"))
}
-func s3DestinationFromFlags() backup.CreateS3Destination {
- return backup.CreateS3Destination{
- Name: s3Name,
- Endpoint: s3Endpoint,
- Bucket: s3Bucket,
- Region: s3Region,
- AccessKeyID: s3AccessKeyID,
- SecretAccessKey: s3SecretAccessKey,
- Prefix: s3Prefix,
- UseSSL: s3UseSSL,
- ForcePathStyle: s3ForcePathStyle,
- }
-}
-
-var s3CreateCmd = &cobra.Command{
- Use: "create",
- Short: "Create an S3 backup destination",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newS3CreateCmd() *cobra.Command {
+ var opts backup.CreateS3Destination
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create an S3 backup destination",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPost, types.BackupsS3(), s3DestinationFromFlags())
- if err != nil {
- return fmt.Errorf("failed to create S3 destination: %w", err)
- }
+ dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPost, types.BackupsS3(), opts)
+ if err != nil {
+ return fmt.Errorf("failed to create S3 destination: %w", err)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(dest)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(dest)
+ }
- output.Success("S3 destination %s created successfully", dest.Name)
- printS3Destination(dest)
- return nil
- },
+ output.Success("S3 destination %s created successfully", dest.Name)
+ printS3Destination(dest)
+ return nil
+ },
+ }
+ addS3ConnectionFlags(cmd, &opts)
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("bucket")
+ _ = cmd.MarkFlagRequired("region")
+ _ = cmd.MarkFlagRequired("access-key-id")
+ _ = cmd.MarkFlagRequired("secret-access-key")
+ return cmd
}
-var s3UpdateCmd = &cobra.Command{
- Use: "update <destination>",
- Short: "Update an S3 backup destination by name or ID",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newS3UpdateCmd() *cobra.Command {
+ var opts backup.CreateS3Destination
+ cmd := &cobra.Command{
+ Use: "update <destination>",
+ Short: "Update an S3 backup destination by name or ID",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
- }
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
- dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPut, types.BackupsS3Destination(resolved.ID), s3DestinationFromFlags())
- if err != nil {
- return fmt.Errorf("failed to update S3 destination: %w", err)
- }
+ dest, err := c.DoJSON[backup.S3Destination](cmd.Context(), http.MethodPut, types.BackupsS3Destination(resolved.ID), opts)
+ if err != nil {
+ return fmt.Errorf("failed to update S3 destination: %w", err)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(dest)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(dest)
+ }
- output.Success("S3 destination %s updated successfully", dest.Name)
- printS3Destination(dest)
- return nil
- },
+ output.Success("S3 destination %s updated successfully", dest.Name)
+ printS3Destination(dest)
+ return nil
+ },
+ }
+ addS3ConnectionFlags(cmd, &opts)
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("bucket")
+ _ = cmd.MarkFlagRequired("region")
+ _ = cmd.MarkFlagRequired("access-key-id")
+ return cmd
}
-var s3DeleteCmd = &cobra.Command{
- Use: "delete <destination>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete an S3 backup destination by name or ID",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !forceFlag && !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete S3 destination %s?", resolved.Name))
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+func newS3DeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <destination>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete an S3 backup destination by name or ID",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
-
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.BackupsS3Destination(resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to delete S3 destination: %w", err)
- }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
+ resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !opts.force && cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
- output.Success("S3 destination %s deleted successfully", resolved.Name)
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete S3 destination %s?", resolved.Name),
+ Path: types.BackupsS3Destination(resolved.ID),
+ Body: nil,
+ FailureMessage: "failed to delete S3 destination",
+ SuccessMessage: fmt.Sprintf("S3 destination %s deleted successfully", resolved.Name),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Delete without confirmation")
+ return cmd
}
-var s3TestCmd = &cobra.Command{
- Use: "test [destination]",
- Short: "Test an S3 destination connection",
- Long: `Test a saved S3 destination by name or ID, or an unsaved configuration by
+func newS3TestCmd() *cobra.Command {
+ var opts backup.CreateS3Destination
+ cmd := &cobra.Command{
+ Use: "test [destination]",
+ Short: "Test an S3 destination connection",
+ Long: `Test a saved S3 destination by name or ID, or an unsaved configuration by
passing the connection flags (--name, --bucket, --region, ...) with no argument.`,
- Args: cobra.MaximumNArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- connectionFlagsSet := false
- for _, name := range []string{"name", "endpoint", "bucket", "region", "access-key-id", "secret-access-key", "prefix", "use-ssl", "force-path-style"} {
- if cmd.Flags().Changed(name) {
- connectionFlagsSet = true
- break
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ flagNames := []string{"name", "endpoint", "bucket", "region", "access-key-id", "secret-access-key", "prefix", "use-ssl", "force-path-style"}
+ connectionFlagsSet := slices.ContainsFunc(flagNames, cmd.Flags().Changed)
+
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- testPath := types.BackupsS3Test()
- var testBody any = s3DestinationFromFlags()
- if len(args) == 1 {
- if connectionFlagsSet {
- return errors.New("pass either a saved destination name or ID, or the connection flags, not both")
- }
- resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if resolveErr != nil {
- return resolveErr
+ testPath := types.BackupsS3Test()
+ var testBody any = opts
+ if len(args) == 1 {
+ if connectionFlagsSet {
+ return errors.New("pass either a saved destination name or ID, or the connection flags, not both")
+ }
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if resolveErr != nil {
+ return resolveErr
+ }
+ testPath, testBody = types.BackupsS3DestinationTest(resolved.ID), nil
+ } else if opts.Bucket == "" {
+ return errors.New("either a destination name or ID, or connection flags (--name, --bucket, --region, ...) are required")
}
- testPath, testBody = types.BackupsS3DestinationTest(resolved.ID), nil
- } else if s3Bucket == "" {
- return errors.New("either a destination name or ID, or connection flags (--name, --bucket, --region, ...) are required")
- }
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), testPath, testBody)
- if err != nil {
- return fmt.Errorf("failed to test S3 destination: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("S3 connection test succeeded")
- return nil
- },
-}
-func addS3ConnectionFlags(cmd *cobra.Command) {
- cmd.Flags().StringVar(&s3Name, "name", "", "Destination name")
- cmd.Flags().StringVar(&s3Endpoint, "endpoint", "", "S3 endpoint (empty for AWS S3)")
- cmd.Flags().StringVar(&s3Bucket, "bucket", "", "Bucket name")
- cmd.Flags().StringVar(&s3Region, "region", "", "Region")
- cmd.Flags().StringVar(&s3AccessKeyID, "access-key-id", "", "Access key ID")
- cmd.Flags().StringVar(&s3SecretAccessKey, "secret-access-key", "", "Secret access key")
- cmd.Flags().StringVar(&s3Prefix, "prefix", "", "Object key prefix")
- cmd.Flags().BoolVar(&s3UseSSL, "use-ssl", true, "Use SSL for the connection")
- cmd.Flags().BoolVar(&s3ForcePathStyle, "force-path-style", false, "Use path-style bucket addressing")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: testPath,
+ Body: testBody,
+ FailureMessage: "failed to test S3 destination",
+ Render: func(base.MessageResponse) error { output.Success("%s", "S3 connection test succeeded"); return nil },
+ })
+ },
+ }
+ addS3ConnectionFlags(cmd, &opts)
+ return cmd
}
-func init() {
- BackupsCmd.AddCommand(s3Cmd)
-
- s3Cmd.AddCommand(s3ListCmd)
- s3Cmd.AddCommand(s3GetCmd)
- s3Cmd.AddCommand(s3CreateCmd)
- s3Cmd.AddCommand(s3UpdateCmd)
- s3Cmd.AddCommand(s3DeleteCmd)
- s3Cmd.AddCommand(s3TestCmd)
-
- s3ListCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of destinations to show")
- s3ListCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- s3ListCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- s3ListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- s3GetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- s3GetCmd.Flags().BoolVar(&s3GetInUse, "in-use", false, "Also report whether the destination is still referenced")
-
- addS3ConnectionFlags(s3CreateCmd)
- s3CreateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = s3CreateCmd.MarkFlagRequired("name")
- _ = s3CreateCmd.MarkFlagRequired("bucket")
- _ = s3CreateCmd.MarkFlagRequired("region")
- _ = s3CreateCmd.MarkFlagRequired("access-key-id")
- _ = s3CreateCmd.MarkFlagRequired("secret-access-key")
-
- addS3ConnectionFlags(s3UpdateCmd)
- s3UpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = s3UpdateCmd.MarkFlagRequired("name")
- _ = s3UpdateCmd.MarkFlagRequired("bucket")
- _ = s3UpdateCmd.MarkFlagRequired("region")
- _ = s3UpdateCmd.MarkFlagRequired("access-key-id")
-
- addS3ConnectionFlags(s3TestCmd)
- s3TestCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- s3DeleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Delete without confirmation")
- s3DeleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func addS3ConnectionFlags(cmd *cobra.Command, opts *backup.CreateS3Destination) {
+ cmd.Flags().StringVar(&opts.Name, "name", "", "Destination name")
+ cmd.Flags().StringVar(&opts.Endpoint, "endpoint", "", "S3 endpoint (empty for AWS S3)")
+ cmd.Flags().StringVar(&opts.Bucket, "bucket", "", "Bucket name")
+ cmd.Flags().StringVar(&opts.Region, "region", "", "Region")
+ cmd.Flags().StringVar(&opts.AccessKeyID, "access-key-id", "", "Access key ID")
+ cmd.Flags().StringVar(&opts.SecretAccessKey, "secret-access-key", "", "Secret access key")
+ cmd.Flags().StringVar(&opts.Prefix, "prefix", "", "Object key prefix")
+ cmd.Flags().BoolVar(&opts.UseSSL, "use-ssl", true, "Use SSL for the connection")
+ cmd.Flags().BoolVar(&opts.ForcePathStyle, "force-path-style", false, "Use path-style bucket addressing")
}
diff --git a/cli/pkg/completion/cmd.go b/cli/pkg/completion/cmd.go
index aeee61b83..1432902d2 100644
--- a/cli/pkg/completion/cmd.go
+++ b/cli/pkg/completion/cmd.go
@@ -1,16 +1,18 @@
package completion
import (
+ "bytes"
"fmt"
- "os"
"github.com/spf13/cobra"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
)
// NewCommand returns an explicit shell completion command.
func NewCommand(root *cobra.Command) *cobra.Command {
- cmd := &cobra.Command{
- Use: "completion [bash|zsh|fish|powershell]",
+ return &cobra.Command{
+ Use: "completion <bash|zsh|fish|powershell>",
Short: "Generate shell completion scripts",
Long: "Generate shell completion scripts for bash, zsh, fish, or powershell.",
Args: cobra.ExactArgs(1),
@@ -18,20 +20,31 @@ func NewCommand(root *cobra.Command) *cobra.Command {
SilenceUsage: true,
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ var script bytes.Buffer
+ var generationErr error
switch args[0] {
case "bash":
- return root.GenBashCompletionV2(os.Stdout, true)
+ generationErr = root.GenBashCompletionV2(&script, true)
case "zsh":
- return root.GenZshCompletion(os.Stdout)
+ generationErr = root.GenZshCompletion(&script)
case "fish":
- return root.GenFishCompletion(os.Stdout, true)
+ generationErr = root.GenFishCompletion(&script, true)
case "powershell", "pwsh":
- return root.GenPowerShellCompletionWithDesc(os.Stdout)
+ generationErr = root.GenPowerShellCompletionWithDesc(&script)
default:
return fmt.Errorf("unsupported shell %q", args[0])
}
+ if generationErr != nil {
+ return generationErr
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Shell string `json:"shell"`
+ Script string `json:"script"`
+ }{Shell: args[0], Script: script.String()})
+ }
+ _, writeErr := fmt.Fprint(cmd.OutOrStdout(), script.String())
+ return writeErr
},
}
-
- return cmd
}
diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.go
index de0d761f1..7a6b9a404 100644
--- a/cli/pkg/config/cmd.go
+++ b/cli/pkg/config/cmd.go
@@ -13,101 +13,106 @@ import (
"time"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- setServerURL string
- setAPIKey string
- setJWTToken string
- setEnvironment string
- setFederatedAudience string
- setLogLevel string
- setDefaultLimit int
- setResourceLimit []string
-)
-
-// ConfigCmd is the command for managing API configuration
-var ConfigCmd = &cobra.Command{
- Use: "config",
- Short: "Manage Arcane CLI's Configuration",
+// Command is the command for managing API configuration
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "config",
+ Short: "Manage Arcane CLI's Configuration",
+ }
+ cmd.AddCommand(newConfigShowCmd(), newConfigSetCmd(), newConfigInitCmd(), newConfigBackupCmd(), newConfigPathCmd(), newConfigTestCmd())
+ return cmd
}
-var configShowCmd = &cobra.Command{
- Use: "show",
- Short: "Show current configuration",
- RunE: func(cmd *cobra.Command, args []string) error {
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
+func newConfigShowCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "show",
+ Short: "Show current configuration",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
- path, _ := config.ConfigPath()
- output.Header("CLI configuration")
- output.KeyValue("Config file", path)
- output.KeyValue("Server URL", cmp.Or(cfg.ServerURL, "(not set)"))
- output.KeyValue("API key", maskAPIKey(cfg.APIKey))
- output.KeyValue("JWT token", maskAPIKey(cfg.JWTToken))
- output.KeyValue("Refresh token", maskAPIKey(cfg.RefreshToken))
- output.KeyValue("Previews: all environments", strconv.FormatBool(cfg.Previews.AllEnvironments))
- output.KeyValue("Environment", cmp.Or(cfg.DefaultEnvironment, "0 (local)"))
- output.KeyValue("Federated audience", cmp.Or(cfg.FederatedAudience, "(not set)"))
- output.KeyValue("Log level", cmp.Or(cfg.LogLevel, "info (default)"))
- output.KeyValue("Update channel", cmp.Or(cfg.CLIUpdateChannel, "(auto)"))
- paginationLimit := "(not set)"
- if cfg.Pagination.Default.Limit > 0 {
- paginationLimit = strconv.Itoa(cfg.Pagination.Default.Limit)
- }
- output.KeyValue("Pagination limit", paginationLimit)
- output.Header("Pagination resources")
- printed := 0
- for _, resource := range types.KnownPaginatedResources {
- limit := cfg.LimitFor(resource)
- explicit := cfg.Pagination.Resources != nil && cfg.Pagination.Resources[resource].Limit > 0
- label := "(inherit)"
- if explicit {
- label = strconv.Itoa(limit)
- } else if limit > 0 {
- label = fmt.Sprintf("%d (from global)", limit)
- }
- output.KeyValue(resource, label)
- printed++
- }
- if cfg.Pagination.Resources != nil {
- extras := make([]string, 0)
- for k, v := range cfg.Pagination.Resources {
- known := slices.Contains(types.KnownPaginatedResources, k)
- if !known && v.Limit > 0 {
- extras = append(extras, k)
+ path, _ := config.ConfigPath()
+ if cmdutil.JSONOutputEnabled(cmd) {
+ cfg.APIKey = maskAPIKey(cfg.APIKey)
+ cfg.JWTToken = maskAPIKey(cfg.JWTToken)
+ cfg.RefreshToken = maskAPIKey(cfg.RefreshToken)
+ return cmdutil.PrintJSON(cfg)
+ }
+ output.Header("CLI configuration")
+ output.KeyValue("Config file", path)
+ output.KeyValue("Server URL", cmp.Or(cfg.ServerURL, "(not set)"))
+ output.KeyValue("API key", maskAPIKey(cfg.APIKey))
+ output.KeyValue("JWT token", maskAPIKey(cfg.JWTToken))
+ output.KeyValue("Refresh token", maskAPIKey(cfg.RefreshToken))
+ output.KeyValue("Previews: all environments", strconv.FormatBool(cfg.Previews.AllEnvironments))
+ output.KeyValue("Environment", cmp.Or(cfg.DefaultEnvironment, "0 (local)"))
+ output.KeyValue("Federated audience", cmp.Or(cfg.FederatedAudience, "(not set)"))
+ output.KeyValue("Log level", cmp.Or(cfg.LogLevel, "info (default)"))
+ output.KeyValue("Update channel", cmp.Or(cfg.CLIUpdateChannel, "(auto)"))
+ output.KeyValue("Pagination limit", kit.Ternary(cfg.Pagination.Default.Limit > 0, strconv.Itoa(cfg.Pagination.Default.Limit), "(not set)"))
+ output.Header("Pagination resources")
+ for _, resource := range types.KnownPaginatedResources {
+ limit := cfg.LimitFor(resource)
+ explicit := cfg.Pagination.Resources != nil && cfg.Pagination.Resources[resource].Limit > 0
+ label := "(inherit)"
+ switch {
+ case explicit:
+ label = strconv.Itoa(limit)
+ case limit > 0:
+ label = fmt.Sprintf("%d (from global)", limit)
}
+ output.KeyValue(resource, label)
}
- sort.Strings(extras)
- for _, k := range extras {
- _, _ = fmt.Fprintf(output.Stdout(), " %-14s %d\n", k+":", cfg.Pagination.Resources[k].Limit)
- printed++
+ if cfg.Pagination.Resources != nil {
+ extras := make([]string, 0)
+ for k, v := range cfg.Pagination.Resources {
+ if !slices.Contains(types.KnownPaginatedResources, k) && v.Limit > 0 {
+ extras = append(extras, k)
+ }
+ }
+ sort.Strings(extras)
+ for _, k := range extras {
+ _, _ = fmt.Fprintf(output.Stdout(), " %-14s %d\n", k+":", cfg.Pagination.Resources[k].Limit)
+ }
}
- }
- if printed == 0 {
- _, _ = fmt.Fprintln(output.Stdout(), " (none)")
- }
- if cfg.IsConfigured() {
- _, _ = fmt.Fprintln(output.Stdout(), "\n✓ Configuration is complete")
- } else {
- _, _ = fmt.Fprintln(output.Stdout(), "\n✗ Configuration is incomplete. Run: arcane config set --help")
- }
+ if cfg.IsConfigured() {
+ _, _ = fmt.Fprintln(output.Stdout(), "\n✓ Configuration is complete")
+ } else {
+ _, _ = fmt.Fprintln(output.Stdout(), "\n✗ Configuration is incomplete. Run: arcane config set --help")
+ }
- return nil
- },
+ return nil
+ },
+ }
}
-var configSetCmd = &cobra.Command{
- Use: "set [key value]...",
- Short: "Set configuration values",
- Long: `Set configuration values for connecting to an Arcane server.
+func newConfigSetCmd() *cobra.Command {
+ var opts struct {
+ serverURL string
+ apiKey string
+ jwtToken string
+ environment string
+ federatedAudience string
+ logLevel string
+ defaultLimit int
+ resourceLimits []string
+ }
+ cmd := &cobra.Command{
+ Use: "set [key value]...",
+ Short: "Set configuration values",
+ Long: `Set configuration values for connecting to an Arcane server.
Preferred syntax (key/value pairs):
@@ -124,205 +129,238 @@ Legacy flag syntax (flags shown below) is still supported:
arcane config set --api-key arc_xxxxxxxxxxxxx
arcane auth login
arcane config set --jwt-token eyJhbGciOi...`,
- RunE: func(cmd *cobra.Command, args []string) error {
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
-
- updated := false
- updatedByArgs, err := applyConfigSetArgs(cfg, args)
- if err != nil {
- return err
- }
- updated = updated || updatedByArgs
-
- for _, flag := range []struct{ key, value string }{
- {"server-url", setServerURL},
- {"api-key", setAPIKey},
- {"jwt-token", setJWTToken},
- {"environment", setEnvironment},
- {"federated-audience", setFederatedAudience},
- {"log-level", setLogLevel},
- } {
- if flag.value != "" {
- if _, setErr := applyConfigSetArg(cfg, flag.key, flag.value); setErr != nil {
- return setErr
- }
- updated = true
+ Args: cobra.ArbitraryArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
}
- }
- if cmd.Flags().Changed("default-limit") {
- if setDefaultLimit < 0 {
- return errors.New("--default-limit must be >= 0")
+
+ w := output.Stdout()
+ if cmdutil.JSONOutputEnabled(cmd) {
+ w = io.Discard
}
- if _, setErr := applyConfigSetArg(cfg, "default-limit", strconv.Itoa(setDefaultLimit)); setErr != nil {
+ if setErr := applyConfigSetArgs(cfg, args, w); setErr != nil {
return setErr
}
- updated = true
- }
- for _, pair := range setResourceLimit {
- _, limit, ok := parseResourceLimitPair(pair)
- if !ok {
- return fmt.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(types.KnownPaginatedResources, ", "))
+
+ updatedKeys := make([]string, 0, len(args)/2)
+ for i := 0; i < len(args); i += 2 {
+ updatedKeys = append(updatedKeys, args[i])
}
- if limit < 0 {
- return fmt.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)
+ for _, flag := range []struct{ key, value string }{
+ {"server-url", opts.serverURL},
+ {"api-key", opts.apiKey},
+ {"jwt-token", opts.jwtToken},
+ {"environment", opts.environment},
+ {"federated-audience", opts.federatedAudience},
+ {"log-level", opts.logLevel},
+ } {
+ if flag.value != "" {
+ if setErr := applyConfigSetArg(cfg, flag.key, flag.value, w); setErr != nil {
+ return setErr
+ }
+ updatedKeys = append(updatedKeys, flag.key)
+ }
}
- if _, setErr := applyConfigSetArg(cfg, "resource-limit", pair); setErr != nil {
- return setErr
+ if cmd.Flags().Changed("default-limit") {
+ if opts.defaultLimit < 0 {
+ return errors.New("--default-limit must be >= 0")
+ }
+ if setErr := applyConfigSetArg(cfg, "default-limit", strconv.Itoa(opts.defaultLimit), w); setErr != nil {
+ return setErr
+ }
+ updatedKeys = append(updatedKeys, "default-limit")
+ }
+ for _, pair := range opts.resourceLimits {
+ if setErr := applyConfigSetArg(cfg, "resource-limit", pair, w); setErr != nil {
+ return setErr
+ }
+ resource, _, _ := strings.Cut(pair, "=")
+ updatedKeys = append(updatedKeys, "pagination.resources."+types.NormalizePaginatedResource(resource)+".limit")
}
- updated = true
- }
- if !updated {
- return errors.New("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url " +
- "http://localhost:3552`) or legacy flags (--server-url, --api-key, --jwt-token, --environment, --log-level, " +
- "--default-limit, --resource-limit)")
- }
+ if len(args) == 0 && len(opts.resourceLimits) == 0 && !cmd.Flags().Changed("default-limit") &&
+ cmp.Or(opts.serverURL, opts.apiKey, opts.jwtToken, opts.environment, opts.federatedAudience, opts.logLevel) == "" {
+ return errors.New("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url " +
+ "http://localhost:3552`) or legacy flags (--server-url, --api-key, --jwt-token, --environment, --log-level, " +
+ "--default-limit, --resource-limit)")
+ }
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to save config: %w", saveErr)
- }
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
+ }
- path, _ := config.ConfigPath()
- _, _ = fmt.Fprintf(output.Stdout(), "\nConfiguration saved to %s\n", path)
+ path, _ := config.ConfigPath()
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ UpdatedKeys []string `json:"updatedKeys"`
+ }{Path: path, UpdatedKeys: updatedKeys})
+ }
+ _, _ = fmt.Fprintf(output.Stdout(), "\nConfiguration saved to %s\n", path)
- return nil
- },
+ return nil
+ },
+ }
+ cmd.Flags().StringVar(&opts.serverURL, "server-url", "", "Arcane server URL (e.g., http://localhost:3553)")
+ cmd.Flags().StringVar(&opts.apiKey, "api-key", "", "API key for authentication")
+ cmd.Flags().StringVar(&opts.jwtToken, "jwt-token", "", "JWT access token for authentication (Bearer token)")
+ cmd.Flags().StringVar(&opts.environment, "environment", "", "Default environment ID")
+ cmd.Flags().StringVar(&opts.federatedAudience, "federated-audience", "", "Default audience for federated authentication")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.logLevel, "log-level", "", "", "Default log level", "debug", "info", "warn", "error")
+ cmd.Flags().IntVar(&opts.defaultLimit, "default-limit", 0, "Global default list limit for paginated resources (0 clears)")
+ cmd.Flags().StringSliceVar(&opts.resourceLimits, "resource-limit", nil, "Per-resource list limit in the form resource=limit (repeatable, 0 clears)")
+ return cmd
}
-var configPathCmd = &cobra.Command{
- Use: "path",
- Short: "Print the config file path",
- RunE: func(cmd *cobra.Command, args []string) error {
- path, err := config.ConfigPath()
- if err != nil {
- return err
- }
- _, _ = fmt.Fprintln(output.Stdout(), path)
- return nil
- },
+func newConfigPathCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "path",
+ Short: "Print the config file path",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path, err := config.ConfigPath()
+ if err != nil {
+ return err
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ }{Path: path})
+ }
+ _, _ = fmt.Fprintln(output.Stdout(), path)
+ return nil
+ },
+ }
}
-var configTestCmd = &cobra.Command{
- Use: "test",
- Short: "Test the API connection",
- RunE: func(cmd *cobra.Command, args []string) error {
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
+func newConfigTestCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "test",
+ Short: "Test the API connection",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
- if validateErr := cfg.Validate(); validateErr != nil {
- return validateErr
- }
+ if validateErr := cfg.Validate(); validateErr != nil {
+ return validateErr
+ }
- _, _ = fmt.Fprintf(output.Stdout(), "Testing connection to %s...\n", cfg.ServerURL)
+ if !cmdutil.JSONOutputEnabled(cmd) {
+ _, _ = fmt.Fprintf(output.Stdout(), "Testing connection to %s...\n", cfg.ServerURL)
+ }
- // Test connection directly without importing client to avoid circular import
- httpClient := &http.Client{Timeout: 10 * time.Second}
- req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, cfg.ServerURL+"/api/version", http.NoBody)
- if err != nil {
- return fmt.Errorf("failed to create request: %w", err)
- }
- // Prefer JWT bearer if present, else API key.
- if cfg.JWTToken != "" {
- req.Header.Set("Authorization", "Bearer "+cfg.JWTToken)
- } else {
- req.Header.Set("X-Api-Key", cfg.APIKey)
- }
+ httpClient := &http.Client{Timeout: 10 * time.Second}
+ req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, cfg.ServerURL+"/api/version", http.NoBody)
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+ // Prefer JWT bearer if present, else API key.
+ if cfg.JWTToken != "" {
+ req.Header.Set("Authorization", "Bearer "+cfg.JWTToken)
+ } else {
+ req.Header.Set("X-Api-Key", cfg.APIKey)
+ }
- resp, err := httpClient.Do(req)
- if err != nil {
- return fmt.Errorf("connection test failed: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("connection test failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode != http.StatusOK {
- body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))
- }
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))
+ }
- _, _ = fmt.Fprintln(output.Stdout(), "✓ Connection successful!")
- return nil
- },
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ ServerURL string `json:"serverUrl"`
+ Success bool `json:"success"`
+ }{ServerURL: cfg.ServerURL, Success: true})
+ }
+ _, _ = fmt.Fprintln(output.Stdout(), "✓ Connection successful!")
+ return nil
+ },
+ }
}
-var configInitCmd = &cobra.Command{
- Use: "init",
- Short: "Create a default config file if it does not exist",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- Long: `Create a starter config file with all supported configuration keys.
+func newConfigInitCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "init",
+ Short: "Create a default config file if it does not exist",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ Long: `Create a starter config file with all supported configuration keys.
If the config file already exists, this command is a no-op and does not overwrite it.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- path, err := config.ConfigPath()
- if err != nil {
- return err
- }
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path, err := config.ConfigPath()
+ if err != nil {
+ return err
+ }
- created, err := config.InitDefaultFile()
- if err != nil {
- return fmt.Errorf("failed to initialize config: %w", err)
- }
- if !created {
- _, _ = fmt.Fprintf(output.Stdout(), "Config file already exists at %s (no changes made)\n", path)
- return nil
- }
+ created, err := config.InitDefaultFile()
+ if err != nil {
+ return fmt.Errorf("failed to initialize config: %w", err)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Created bool `json:"created"`
+ }{Path: path, Created: created})
+ }
+ if !created {
+ _, _ = fmt.Fprintf(output.Stdout(), "Config file already exists at %s (no changes made)\n", path)
+ return nil
+ }
- _, _ = fmt.Fprintf(output.Stdout(), "Created default config at %s\n", path)
- _, _ = fmt.Fprintln(output.Stdout(), "Update values with `arcane config set <key> <value>` or run `arcane auth login`.")
- return nil
- },
+ _, _ = fmt.Fprintf(output.Stdout(), "Created default config at %s\n", path)
+ _, _ = fmt.Fprintln(output.Stdout(), "Update values with `arcane config set <key> <value>` or run `arcane auth login`.")
+ return nil
+ },
+ }
}
-var configBackupCmd = &cobra.Command{
- Use: "backup",
- Short: "Move the current config file to a .bak backup",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- Long: `Move the active config file to <config-path>.bak.
+func newConfigBackupCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "backup",
+ Short: "Move the current config file to a .bak backup",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ Long: `Move the active config file to <config-path>.bak.
This removes the original config file from its previous path.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- path, err := config.ConfigPath()
- if err != nil {
- return err
- }
-
- backupPath, moved, err := config.BackupFile()
- if err != nil {
- return fmt.Errorf("failed to backup config: %w", err)
- }
- if !moved {
- _, _ = fmt.Fprintf(output.Stdout(), "No config file found at %s (no changes made)\n", path)
- return nil
- }
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path, err := config.ConfigPath()
+ if err != nil {
+ return err
+ }
- _, _ = fmt.Fprintf(output.Stdout(), "Backed up config to %s\n", backupPath)
- _, _ = fmt.Fprintf(output.Stdout(), "Removed original config at %s\n", path)
- return nil
- },
-}
+ backupPath, moved, err := config.BackupFile()
+ if err != nil {
+ return fmt.Errorf("failed to backup config: %w", err)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Moved bool `json:"moved"`
+ }{Path: cmp.Or(backupPath, path), Moved: moved})
+ }
+ if !moved {
+ _, _ = fmt.Fprintf(output.Stdout(), "No config file found at %s (no changes made)\n", path)
+ return nil
+ }
-func init() {
- ConfigCmd.AddCommand(configShowCmd)
- ConfigCmd.AddCommand(configSetCmd)
- ConfigCmd.AddCommand(configInitCmd)
- ConfigCmd.AddCommand(configBackupCmd)
- ConfigCmd.AddCommand(configPathCmd)
- ConfigCmd.AddCommand(configTestCmd)
-
- configSetCmd.Flags().StringVar(&setServerURL, "server-url", "", "Arcane server URL (e.g., http://localhost:3553)")
- configSetCmd.Flags().StringVar(&setAPIKey, "api-key", "", "API key for authentication")
- configSetCmd.Flags().StringVar(&setJWTToken, "jwt-token", "", "JWT access token for authentication (Bearer token)")
- configSetCmd.Flags().StringVar(&setEnvironment, "environment", "", "Default environment ID")
- configSetCmd.Flags().StringVar(&setFederatedAudience, "federated-audience", "", "Default audience for federated authentication")
- configSetCmd.Flags().StringVar(&setLogLevel, "log-level", "", "Default log level (debug, info, warn, error)")
- configSetCmd.Flags().IntVar(&setDefaultLimit, "default-limit", 0, "Global default list limit for paginated resources (0 clears)")
- configSetCmd.Flags().StringSliceVar(&setResourceLimit, "resource-limit", nil, "Per-resource list limit in the form resource=limit (repeatable, 0 clears)")
+ _, _ = fmt.Fprintf(output.Stdout(), "Backed up config to %s\n", backupPath)
+ _, _ = fmt.Fprintf(output.Stdout(), "Removed original config at %s\n", path)
+ return nil
+ },
+ }
}
func maskAPIKey(key string) string {
@@ -335,161 +373,126 @@ func maskAPIKey(key string) string {
return key[:4] + "..." + key[len(key)-4:]
}
-func parseResourceLimitPair(pair string) (resource string, limit int, ok bool) {
- left, right, found := strings.Cut(pair, "=")
- if !found {
- return "", 0, false
- }
- resource = types.NormalizePaginatedResource(left)
- if resource == "" {
- return "", 0, false
- }
- known := slices.Contains(types.KnownPaginatedResources, resource)
- if !known {
- return "", 0, false
- }
- parsed, err := strconv.Atoi(strings.TrimSpace(right))
- if err != nil {
- return "", 0, false
- }
- return resource, parsed, true
-}
-
-func applyConfigSetArgs(cfg *types.Config, args []string) (bool, error) {
- if len(args) == 0 {
- return false, nil
- }
+func applyConfigSetArgs(cfg *types.Config, args []string, w io.Writer) error {
if len(args)%2 != 0 {
- return false, fmt.Errorf("expected key/value pairs, got odd number of arguments (%d). Example: `arcane config set server-url http://localhost:3552`", len(args))
+ return fmt.Errorf("expected key/value pairs, got odd number of arguments (%d). Example: `arcane config set server-url http://localhost:3552`", len(args))
}
-
- updated := false
for i := 0; i < len(args); i += 2 {
- changed, err := applyConfigSetArg(cfg, args[i], args[i+1])
- if err != nil {
- return false, err
+ if err := applyConfigSetArg(cfg, args[i], args[i+1], w); err != nil {
+ return err
}
- updated = updated || changed
}
- return updated, nil
+ return nil
}
-func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {
+func applyConfigSetArg(cfg *types.Config, key, value string, w io.Writer) error {
normalized := strings.ReplaceAll(strings.ToLower(strings.TrimSpace(key)), " ", "")
switch normalized {
case "server-url", "server", "serverurl", "server_url":
cfg.ServerURL = value
- _, _ = fmt.Fprintf(output.Stdout(), "Set server_url = %s\n", value)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set server_url = %s\n", value)
+ return nil
case "api-key", "apikey", "api_key":
cfg.APIKey = value
// If switching to API key auth, clear any existing JWT token.
cfg.JWTToken = ""
cfg.RefreshToken = ""
- _, _ = fmt.Fprintf(output.Stdout(), "Set api_key = %s\n", maskAPIKey(value))
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set api_key = %s\n", maskAPIKey(value))
+ return nil
case "jwt-token", "jwt", "jwt_token":
cfg.JWTToken = value
// If switching to JWT auth, clear any existing API key.
cfg.APIKey = ""
cfg.RefreshToken = ""
- _, _ = fmt.Fprintf(output.Stdout(), "Set jwt_token = %s\n", maskAPIKey(value))
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set jwt_token = %s\n", maskAPIKey(value))
+ return nil
case "previews.allenvironments":
enabled, err := strconv.ParseBool(value)
if err != nil {
- return false, fmt.Errorf("invalid previews.allEnvironments value %q (expected true or false)", value)
+ return fmt.Errorf("invalid previews.allEnvironments value %q (expected true or false)", value)
}
cfg.Previews.AllEnvironments = enabled
- _, _ = fmt.Fprintf(output.Stdout(), "Set previews.allEnvironments = %t\n", enabled)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set previews.allEnvironments = %t\n", enabled)
+ return nil
case "environment", "default-environment", "default_environment":
cfg.DefaultEnvironment = value
- _, _ = fmt.Fprintf(output.Stdout(), "Set default_environment = %s\n", value)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set default_environment = %s\n", value)
+ return nil
case "federated-audience", "federated_audience", "audience":
cfg.FederatedAudience = value
- _, _ = fmt.Fprintf(output.Stdout(), "Set federated_audience = %s\n", value)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set federated_audience = %s\n", value)
+ return nil
case "log-level", "loglevel", "log_level":
cfg.LogLevel = value
- _, _ = fmt.Fprintf(output.Stdout(), "Set log_level = %s\n", value)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set log_level = %s\n", value)
+ return nil
case "cli-update-channel", "cli_update_channel", "cli-channel", "channel":
channel := strings.ToLower(strings.TrimSpace(value))
if channel != "stable" && channel != "next" {
- return false, fmt.Errorf("invalid cli update channel %q (expected stable or next)", value)
+ return fmt.Errorf("invalid cli update channel %q (expected stable or next)", value)
}
cfg.CLIUpdateChannel = channel
- _, _ = fmt.Fprintf(output.Stdout(), "Set cli_update_channel = %s\n", channel)
- return true, nil
+ _, _ = fmt.Fprintf(w, "Set cli_update_channel = %s\n", channel)
+ return nil
case "default-limit", "default_limit", "pagination.default.limit":
- limit, err := parseLimitValue(normalized, value)
+ limit, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
- return false, err
- }
- cfg.SetDefaultLimit(limit)
- if limit == 0 {
- _, _ = fmt.Fprintln(output.Stdout(), "Cleared pagination.default.limit")
- } else {
- _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.default.limit = %d\n", limit)
- }
- return true, nil
- case "resource-limit", "resource_limit":
- resource, limit, ok := parseResourceLimitPair(value)
- if !ok {
- return false, fmt.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(types.KnownPaginatedResources, ", "))
+ return fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, normalized)
}
if limit < 0 {
- return false, fmt.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)
+ return fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, normalized)
}
- cfg.SetResourceLimit(resource, limit)
+ cfg.SetDefaultLimit(limit)
if limit == 0 {
- _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)
+ _, _ = fmt.Fprintln(w, "Cleared pagination.default.limit")
} else {
- _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)
+ _, _ = fmt.Fprintf(w, "Set pagination.default.limit = %d\n", limit)
}
- return true, nil
- }
-
- if strings.HasPrefix(normalized, "resource-limit.") || strings.HasPrefix(normalized, "resource_limit.") {
- resource := strings.TrimPrefix(strings.TrimPrefix(normalized, "resource-limit."), "resource_limit.")
- return applyResourceLimitByKey(cfg, key, resource, value)
- }
- if strings.HasPrefix(normalized, "pagination.resources.") && strings.HasSuffix(normalized, ".limit") {
- resource := strings.TrimSuffix(strings.TrimPrefix(normalized, "pagination.resources."), ".limit")
- return applyResourceLimitByKey(cfg, key, resource, value)
+ return nil
}
- return false, fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, "+
- "federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)
-}
-
-func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue string) (bool, error) {
- resource := types.NormalizePaginatedResource(resourceValue)
- if resource == "" || !slices.Contains(types.KnownPaginatedResources, resource) {
- return false, fmt.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(types.KnownPaginatedResources, ", "))
- }
- limit, err := parseLimitValue(key, limitValue)
- if err != nil {
- return false, err
+ var resource string
+ var limit int
+ if normalized == "resource-limit" || normalized == "resource_limit" {
+ left, right, found := strings.Cut(value, "=")
+ resource = types.NormalizePaginatedResource(left)
+ parsed, err := strconv.Atoi(strings.TrimSpace(right))
+ if !found || resource == "" || !slices.Contains(types.KnownPaginatedResources, resource) || err != nil {
+ return fmt.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(types.KnownPaginatedResources, ", "))
+ }
+ if parsed < 0 {
+ return fmt.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)
+ }
+ limit = parsed
+ } else {
+ var resourceValue string
+ switch {
+ case strings.HasPrefix(normalized, "resource-limit.") || strings.HasPrefix(normalized, "resource_limit."):
+ resourceValue = strings.TrimPrefix(strings.TrimPrefix(normalized, "resource-limit."), "resource_limit.")
+ case strings.HasPrefix(normalized, "pagination.resources.") && strings.HasSuffix(normalized, ".limit"):
+ resourceValue = strings.TrimSuffix(strings.TrimPrefix(normalized, "pagination.resources."), ".limit")
+ default:
+ return fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, "+
+ "federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)
+ }
+ resource = types.NormalizePaginatedResource(resourceValue)
+ if resource == "" || !slices.Contains(types.KnownPaginatedResources, resource) {
+ return fmt.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(types.KnownPaginatedResources, ", "))
+ }
+ parsed, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil {
+ return fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)
+ }
+ if parsed < 0 {
+ return fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, key)
+ }
+ limit = parsed
}
cfg.SetResourceLimit(resource, limit)
if limit == 0 {
- _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)
+ _, _ = fmt.Fprintf(w, "Cleared pagination.resources.%s.limit\n", resource)
} else {
- _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)
- }
- return true, nil
-}
-
-func parseLimitValue(key, value string) (int, error) {
- parsed, err := strconv.Atoi(strings.TrimSpace(value))
- if err != nil {
- return 0, fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)
- }
- if parsed < 0 {
- return 0, fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, key)
+ _, _ = fmt.Fprintf(w, "Set pagination.resources.%s.limit = %d\n", resource, limit)
}
- return parsed, nil
+ return nil
}
diff --git a/cli/pkg/config/cmd_test.go b/cli/pkg/config/cmd_test.go
index d3a3ffd5e..20cdf047a 100644
--- a/cli/pkg/config/cmd_test.go
+++ b/cli/pkg/config/cmd_test.go
@@ -1,31 +1,29 @@
package config
import (
+ "io"
"testing"
"github.com/stretchr/testify/require"
- clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
func TestApplyConfigSetArgs(t *testing.T) {
- cfg := &clitypes.Config{}
+ cfg := &types.Config{}
- changed, err := applyConfigSetArgs(cfg, []string{
+ err := applyConfigSetArgs(cfg, []string{
"server-url", "http://localhost:3552",
"api-key", "arc_test_12345678",
"previews.allEnvironments", "true",
"default-limit", "25",
"pagination.resources.images.limit", "100",
"resource-limit.volumes", "40",
- })
+ }, io.Discard)
require.NoError(t, err,
"applyConfigSetArgs() error = %v", err)
- require.True(t, changed,
- "applyConfigSetArgs() changed = false, want true")
-
require.Equal(t, "http://localhost:3552", cfg.ServerURL,
"ServerURL = %q, want %q", cfg.ServerURL, "http://localhost:3552")
@@ -37,7 +35,7 @@ func TestApplyConfigSetArgs(t *testing.T) {
require.True(t, cfg.Previews.AllEnvironments)
for _, value := range []string{"false", "true", "invalid"} {
- _, setErr := applyConfigSetArg(cfg, "previews.allEnvironments", value)
+ setErr := applyConfigSetArg(cfg, "previews.allEnvironments", value, io.Discard)
if value == "invalid" {
require.Error(t, setErr)
continue
@@ -62,39 +60,31 @@ func TestApplyConfigSetArgs(t *testing.T) {
}
func TestApplyConfigSetArgs_OddArgs(t *testing.T) {
- cfg := &clitypes.Config{}
- changed, err := applyConfigSetArgs(cfg, []string{"server-url", "http://localhost:3552", "api-key"})
+ cfg := &types.Config{}
+ err := applyConfigSetArgs(cfg, []string{"server-url", "http://localhost:3552", "api-key"}, io.Discard)
require.Error(t, err,
"expected error for odd key/value args, got nil")
-
- require.False(t, changed,
- "changed = true, want false")
}
func TestApplyConfigSetArg_UnknownKey(t *testing.T) {
- cfg := &clitypes.Config{}
- changed, err := applyConfigSetArg(cfg, "not-a-real-key", "value")
+ cfg := &types.Config{}
+ err := applyConfigSetArg(cfg, "not-a-real-key", "value", io.Discard)
require.Error(t, err,
"expected unknown key error, got nil")
- require.False(t, changed,
- "changed = true, want false")
-
require.Contains(t, err.Error(), "unknown config key",
"unexpected error: %v", err)
}
func TestApplyConfigSetArg_ResourceLimitPair(t *testing.T) {
- cfg := &clitypes.Config{}
- changed, err := applyConfigSetArg(cfg, "resource-limit", "containers=55")
+ cfg := &types.Config{}
+ err := applyConfigSetArg(cfg, "resource-limit", "containers=55", io.Discard)
require.NoError(t, err,
"applyConfigSetArg() error = %v", err)
- require.True(t, changed,
- "changed = false, want true")
{
got := cfg.LimitFor("containers")
diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.go
index 52a2fcc5c..a7e80d08b 100644
--- a/cli/pkg/containers/actions.go
+++ b/cli/pkg/containers/actions.go
@@ -1,8 +1,10 @@
package containers
import (
+ "encoding/json/jsontext"
"encoding/json/v2"
"fmt"
+ "net/http"
"net/url"
"os"
"strings"
@@ -11,259 +13,258 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/container"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- killSignal string
-
- commitRepository string
- commitTag string
- commitComment string
- commitAuthor string
- commitChanges []string
- commitNoPause bool
-
- editFile string
-
- autoUpdateEnabled bool
-)
-
-var containersKillCmd = &cobra.Command{
- Use: "kill <container-id|name>",
- Short: "Kill a container (send a signal to its main process)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- path := types.ContainerKill(c.EnvID(), resolved.ID)
- if signal := strings.TrimSpace(killSignal); signal != "" {
- path += "?signal=" + url.QueryEscape(signal)
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: path,
- FailureMessage: "failed to kill container",
- SuccessMessage: fmt.Sprintf("Container %s killed successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
-}
+func newKillCmd() *cobra.Command {
+ var opts struct {
+ signal string
+ }
+ command := &cobra.Command{
+ Use: "kill <container-id|name>",
+ Short: "Kill a container (send a signal to its main process)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
-var containersPauseCmd = &cobra.Command{
- Use: "pause <container-id|name>",
- Short: "Pause a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerPause(c.EnvID(), resolved.ID),
- FailureMessage: "failed to pause container",
- SuccessMessage: fmt.Sprintf("Container %s paused successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
+ path := types.ContainerKill(c.EnvID(), resolved.ID)
+ if signal := strings.TrimSpace(opts.signal); signal != "" {
+ path += "?signal=" + url.QueryEscape(signal)
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: path,
+ FailureMessage: "failed to kill container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s killed successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.signal, "signal", "", "Signal to send (for example SIGTERM, SIGKILL); defaults to SIGKILL")
+ return command
}
-var containersUnpauseCmd = &cobra.Command{
- Use: "unpause <container-id|name>",
- Short: "Unpause a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerUnpause(c.EnvID(), resolved.ID),
- FailureMessage: "failed to unpause container",
- SuccessMessage: fmt.Sprintf("Container %s unpaused successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
+func newPauseCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "pause <container-id|name>",
+ Short: "Pause a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerPause(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to pause container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s paused successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
}
-var containersCommitCmd = &cobra.Command{
- Use: "commit <container-id|name>",
- Short: "Create an image from a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- body := container.CommitRequest{
- Repository: commitRepository,
- Tag: commitTag,
- Comment: commitComment,
- Author: commitAuthor,
- Changes: commitChanges,
- NoPause: commitNoPause,
- }
-
- c.SetTimeout(30 * time.Minute)
-
- result, err := c.PostJSON[container.CommitResult](cmd.Context(), types.ContainerCommit(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to commit container: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Container %s committed successfully", containerDisplayName(resolved))
- output.KeyValue("Image ID", result.Data.ID)
- return nil
- },
+func newUnpauseCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "unpause <container-id|name>",
+ Short: "Unpause a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerUnpause(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to unpause container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s unpaused successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
}
-var containersEditCmd = &cobra.Command{
- Use: "edit <container-id|name>",
- Short: "Edit a container's configuration",
- Long: "Without --file, prints the container's editable configuration as JSON (pipe it to a file, edit it, then re-apply). With --file, applies the edit payload and recreates the container.",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- if editFile == "" {
- result, getEditConfigErr := c.GetJSON[container.EditConfig](cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))
- if getEditConfigErr != nil {
- return fmt.Errorf("failed to get container edit config: %w", getEditConfigErr)
+func newCommitCmd() *cobra.Command {
+ var opts struct {
+ repository string
+ tag string
+ comment string
+ author string
+ changes []string
+ noPause bool
+ }
+ command := &cobra.Command{
+ Use: "commit <container-id|name>",
+ Short: "Create an image from a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- return cmdutil.PrintJSON(result.Data)
- }
-
- data, err := os.ReadFile(editFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", editFile, err)
- }
- var body container.Edit
- if unmarshalErr := json.Unmarshal(data, &body); unmarshalErr != nil {
- return fmt.Errorf("failed to parse edit payload: %w", unmarshalErr)
- }
-
- c.SetTimeout(30 * time.Minute)
-
- result, err := c.PostJSON[container.Details](cmd.Context(), types.ContainerEdit(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to edit container: %w", err)
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ body := container.CommitRequest{
+ Repository: opts.repository,
+ Tag: opts.tag,
+ Comment: opts.comment,
+ Author: opts.author,
+ Changes: opts.changes,
+ NoPause: opts.noPause,
+ }
- output.Success("Container %s edited successfully", containerDisplayName(resolved))
- output.KeyValue("New ID", result.Data.ID)
- return nil
- },
+ c.SetTimeout(30 * time.Minute)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.CommitResult]{
+ Method: http.MethodPost,
+ Path: types.ContainerCommit(c.EnvID(), resolved.ID),
+ Body: body,
+ FailureMessage: "failed to commit container",
+ Render: func(data container.CommitResult) error {
+ output.Success("Container %s committed successfully", containerDisplayName(resolved))
+ output.KeyValue("Image ID", data.ID)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.repository, "repository", "", "Target image repository")
+ command.Flags().StringVar(&opts.tag, "tag", "", "Target image tag")
+ command.Flags().StringVar(&opts.comment, "comment", "", "Commit comment")
+ command.Flags().StringVar(&opts.author, "author", "", "Commit author")
+ command.Flags().StringArrayVar(&opts.changes, "change", nil, "Dockerfile instruction to apply during commit (repeatable)")
+ command.Flags().BoolVar(&opts.noPause, "no-pause", false, "Do not pause the container during commit")
+ return command
}
-var containersAutoUpdateCmd = &cobra.Command{
- Use: "auto-update <container-id|name>",
- Short: "Enable or disable auto-update for a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+func newEditCmd() *cobra.Command {
+ var opts struct {
+ file string
+ }
+ command := &cobra.Command{
+ Use: "edit <container-id|name>",
+ Short: "Edit a container's configuration",
+ Long: "Without --file, prints the container's editable configuration as JSON (pipe it to a file, edit it, then re-apply). With --file, applies the edit payload and recreates the container.",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- body := struct {
- Enabled bool `json:"enabled"`
- }{Enabled: autoUpdateEnabled}
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.ContainerAutoUpdate(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to set container auto-update: %w", err)
- }
+ if opts.file == "" {
+ return cmdutil.Run(cmd, c, cmdutil.Spec[jsontext.Value]{
+ Method: http.MethodGet,
+ Path: types.ContainerEditConfig(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to get container edit config",
+ Render: func(data jsontext.Value) error { return cmdutil.PrintRawJSON(data) },
+ })
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ data, err := os.ReadFile(opts.file)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", opts.file, err)
+ }
+ var body container.Edit
+ if unmarshalErr := json.Unmarshal(data, &body); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse edit payload: %w", unmarshalErr)
+ }
- state := "disabled"
- if autoUpdateEnabled {
- state = "enabled"
- }
- output.Success("Auto-update %s for container %s", state, containerDisplayName(resolved))
- return nil
- },
+ c.SetTimeout(30 * time.Minute)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.Details]{
+ Method: http.MethodPost,
+ Path: types.ContainerEdit(c.EnvID(), resolved.ID),
+ Body: body,
+ FailureMessage: "failed to edit container",
+ Render: func(data container.Details) error {
+ output.Success("Container %s edited successfully", containerDisplayName(resolved))
+ output.KeyValue("New ID", data.ID)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVarP(&opts.file, "file", "f", "", "JSON edit payload to apply (omit to print the current editable configuration)")
+ return command
}
-func init() {
- ContainersCmd.AddCommand(containersKillCmd)
- ContainersCmd.AddCommand(containersPauseCmd)
- ContainersCmd.AddCommand(containersUnpauseCmd)
- ContainersCmd.AddCommand(containersCommitCmd)
- ContainersCmd.AddCommand(containersEditCmd)
- ContainersCmd.AddCommand(containersAutoUpdateCmd)
-
- containersKillCmd.Flags().StringVar(&killSignal, "signal", "", "Signal to send (for example SIGTERM, SIGKILL); defaults to SIGKILL")
-
- containersCommitCmd.Flags().StringVar(&commitRepository, "repository", "", "Target image repository")
- containersCommitCmd.Flags().StringVar(&commitTag, "tag", "", "Target image tag")
- containersCommitCmd.Flags().StringVar(&commitComment, "comment", "", "Commit comment")
- containersCommitCmd.Flags().StringVar(&commitAuthor, "author", "", "Commit author")
- containersCommitCmd.Flags().StringArrayVar(&commitChanges, "change", nil, "Dockerfile instruction to apply during commit (repeatable)")
- containersCommitCmd.Flags().BoolVar(&commitNoPause, "no-pause", false, "Do not pause the container during commit")
-
- containersEditCmd.Flags().StringVarP(&editFile, "file", "f", "", "JSON edit payload to apply (omit to print the current editable configuration)")
+func newAutoUpdateCmd() *cobra.Command {
+ var opts struct {
+ enabled bool
+ }
+ command := &cobra.Command{
+ Use: "auto-update <container-id|name>",
+ Short: "Enable or disable auto-update for a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- containersAutoUpdateCmd.Flags().BoolVar(&autoUpdateEnabled, "enabled", false, "Whether auto-update is enabled for this container")
- _ = containersAutoUpdateCmd.MarkFlagRequired("enabled")
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- containersKillCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersPauseCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersUnpauseCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersCommitCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersEditCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersAutoUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ body := container.SetAutoUpdateRequest{Enabled: opts.enabled}
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPut,
+ Path: types.ContainerAutoUpdate(c.EnvID(), resolved.ID),
+ Body: body,
+ FailureMessage: "failed to set container auto-update",
+ Render: func(data base.MessageResponse) error {
+ output.Success("Auto-update %s for container %s", kit.Ternary(opts.enabled, "enabled", "disabled"), containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().BoolVar(&opts.enabled, "enabled", false, "Whether auto-update is enabled for this container")
+ _ = command.MarkFlagRequired("enabled")
+ return command
}
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index 444a63861..4f097fa54 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -5,8 +5,10 @@ import (
"encoding/json/v2"
"errors"
"fmt"
+ "net/http"
"net/url"
"os"
+ "slices"
"strconv"
"strings"
"time"
@@ -15,578 +17,493 @@ import (
"github.com/getarcaneapp/arcane/types/v2/container"
"github.com/getarcaneapp/arcane/types/v2/updater"
"github.com/spf13/cobra"
+ "go.getarcane.app/docker"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- containersLimit int
- containersStart int
- containersAll bool
- containersUpdatesFilter string
- containersStandalone string
- containersLabelFilter string
- containersInclude bool
- containersIncludeHidden bool
- containersDeleteVolumes bool
- forceFlag bool
- jsonOutput bool
-
- containerCreateFile string
- containerCreateName string
- containerCreateImage string
- containerCreateEnv []string
- containerCreatePort []string
- containerCreateVolume []string
- containerCreateLabel []string
- containerCreateNetwork []string
- containerCreateRestart string
- containerCreateMemory int64
- containerCreateCPUs float64
- containerCreatePrivileged bool
- containerCreateHostname string
- containerCreateUser string
- containerCreateWorkdir string
- containerCreateEntrypoint string
- containerCreateCmd string
-)
-
-// ContainersCmd is the parent command for container operations
-var ContainersCmd = &cobra.Command{
- Use: "containers",
- Aliases: []string{"container", "c"},
- Short: "Manage containers",
+// Command builds the containers command tree.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeResource},
+ Use: "containers",
+ Aliases: []string{"container", "c"},
+ Short: "Manage containers",
+ }
+ command.AddCommand(
+ newListCmd(),
+ newUpdatesCmd(),
+ newGetCmd(),
+ newStartCmd(),
+ newStopCmd(),
+ newRestartCmd(),
+ newUpdateCmd(),
+ newRedeployCmd(),
+ newDeleteCmd(),
+ newCountsCmd(),
+ newCreateCmd(),
+ newKillCmd(),
+ newPauseCmd(),
+ newUnpauseCmd(),
+ newCommitCmd(),
+ newEditCmd(),
+ newAutoUpdateCmd(),
+ )
+ return command
}
-var containersListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List containers",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runContainersList(cmd, false)
- },
+func newListCmd() *cobra.Command {
+ return newContainerListCmd(false)
}
-var containersUpdatesCmd = &cobra.Command{
- Use: "updates",
- Short: "List containers with available updates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runContainersList(cmd, true)
- },
-}
-
-func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- query := url.Values{}
- if containersStandalone != "" {
- query.Set("standalone", containersStandalone)
- }
- if containersIncludeHidden {
- query.Set("includeHidden", "true")
- }
- if containersInclude {
- query.Set("include", "true")
- }
- updatesFilter := strings.TrimSpace(containersUpdatesFilter)
- if forceHasUpdateFilter {
- updatesFilter = "has_update"
- }
- if updatesFilter != "" {
- query.Set("updates", updatesFilter)
- }
- if labelFilter := strings.TrimSpace(containersLabelFilter); labelFilter != "" {
- query.Set("label", labelFilter)
+func newContainerListCmd(updatesOnly bool) *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ updatesFilter string
+ standalone string
+ labelFilter string
+ include bool
+ includeHidden bool
}
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: kit.Ternary(updatesOnly, "updates", "list"),
+ Aliases: kit.Ternary(updatesOnly, []string(nil), []string{"ls"}),
+ Short: kit.Ternary(updatesOnly, "List containers with available updates", "List containers"),
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- spec := cmdutil.ListSpec[container.Summary]{
- Resource: "containers",
- Endpoint: types.Containers(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "containers", Limit: containersLimit, FallbackDefault: 20, Start: containersStart, All: containersAll},
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"},
- Row: func(item container.Summary) []string {
- return []string{
- shortID(item.ID),
- containerSummaryName(item),
- item.Image,
- item.State,
- item.Status,
+ query := url.Values{}
+ if opts.standalone != "" {
+ query.Set("standalone", opts.standalone)
}
- },
- }
- if updatesFilter != "" {
- if !jsonOutput {
- output.Header("Container Updates")
- }
- spec.Headers = []string{"ID", "NAME", "IMAGE", "STATE", "UPDATES", "LATEST"}
- spec.Row = func(item container.Summary) []string {
- status, latest := "unknown", "-"
- if item.UpdateInfo != nil {
- switch {
- case item.UpdateInfo.Error != "":
- status = "error"
- case item.UpdateInfo.HasUpdate:
- status = "has_update"
- default:
- status = "up_to_date"
- }
- if strings.TrimSpace(item.UpdateInfo.LatestVersion) != "" {
- latest = item.UpdateInfo.LatestVersion
- } else if strings.TrimSpace(item.UpdateInfo.LatestDigest) != "" {
- latest = item.UpdateInfo.LatestDigest
- }
+ if opts.includeHidden {
+ query.Set("includeHidden", "true")
}
- return []string{
- shortID(item.ID),
- containerSummaryName(item),
- item.Image,
- item.State,
- status,
- latest,
+ if opts.include {
+ query.Set("include", "true")
+ }
+ updatesFilter := kit.Ternary(cmd.Name() == "updates", "has_update", strings.TrimSpace(opts.updatesFilter))
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
+ }
+ if labelFilter := strings.TrimSpace(opts.labelFilter); labelFilter != "" {
+ query.Set("label", labelFilter)
}
- }
- }
- return cmdutil.RunList(cmd, c, spec)
-}
-
-var containersGetCmd = &cobra.Command{
- Use: "get <container-id|name>",
- Short: "Get detailed container information",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := ContainerRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
- if !complete {
- result, getContainerErr := c.GetJSON[container.Details](cmd.Context(), types.Container(c.EnvID(), resolved.ID))
- if getContainerErr != nil {
- return fmt.Errorf("failed to get container: %w", getContainerErr)
+ if updatesFilter != "" && !cmdutil.JSONOutputEnabled(cmd) {
+ output.Header("Container Updates")
}
- resolved = &result.Data
- }
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[container.Summary]{
+ Resource: "containers",
+ Endpoint: types.Containers(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "containers", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Query: query,
+ Headers: kit.Ternary(updatesFilter != "", []string{"ID", "NAME", "IMAGE", "STATE", "UPDATES", "LATEST"}, []string{"ID", "NAME", "IMAGE", "STATE", "STATUS"}),
+ Row: func(item container.Summary) []string {
+ if updatesFilter == "" {
+ return []string{
+ item.ID[:min(len(item.ID), 12)],
+ docker.ContainerNameFromNames(item.Names),
+ item.Image,
+ item.State,
+ item.Status,
+ }
+ }
+ status, latest := "unknown", "-"
+ if item.UpdateInfo != nil {
+ switch {
+ case item.UpdateInfo.Error != "":
+ status = "error"
+ case item.UpdateInfo.HasUpdate:
+ status = "has_update"
+ default:
+ status = "up_to_date"
+ }
+ switch {
+ case strings.TrimSpace(item.UpdateInfo.LatestVersion) != "":
+ latest = item.UpdateInfo.LatestVersion
+ case strings.TrimSpace(item.UpdateInfo.LatestDigest) != "":
+ latest = item.UpdateInfo.LatestDigest
+ }
+ }
+ return []string{
+ item.ID[:min(len(item.ID), 12)],
+ docker.ContainerNameFromNames(item.Names),
+ item.Image,
+ item.State,
+ status,
+ latest,
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of containers to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ if !updatesOnly {
+ cmdutil.EnumVarP(command, command.Flags(), &opts.updatesFilter, "updates", "", "", "Filter by update status", "has_update", "up_to_date", "error", "unknown")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.standalone, "standalone", "", "", "Filter standalone containers only", "true", "false")
+ command.Flags().StringVar(&opts.labelFilter, "label", "", "Filter by label (key or key=value)")
+ command.Flags().BoolVar(&opts.includeHidden, "include-hidden", false, "Include hidden containers")
+ command.Flags().BoolVar(&opts.include, "include-internal", false, "Include Arcane-internal containers")
+ }
- output.Header("Container Details")
- output.KeyValue("ID", resolved.ID)
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("Image", resolved.Image)
- output.KeyValue("State", fmt.Sprintf("%s (Running: %v)", resolved.State.Status, resolved.State.Running))
- output.KeyValue("Created", resolved.Created)
- return nil
- },
+ return command
}
-var containersStartCmd = &cobra.Command{
- Use: "start <container-id|name>",
- Short: "Start a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerStart(c.EnvID(), resolved.ID),
- FailureMessage: "failed to start container",
- SuccessMessage: fmt.Sprintf("Container %s started successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
+func newUpdatesCmd() *cobra.Command {
+ return newContainerListCmd(true)
}
-var containersStopCmd = &cobra.Command{
- Use: "stop <container-id|name>",
- Short: "Stop a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerStop(c.EnvID(), resolved.ID),
- FailureMessage: "failed to stop container",
- SuccessMessage: fmt.Sprintf("Container %s stopped successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
-}
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <container-id|name>",
+ Short: "Get detailed container information",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var containersRestartCmd = &cobra.Command{
- Use: "restart <container-id|name>",
- Short: "Restart a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ resolved, err := ContainerRef.Fetch(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerRestart(c.EnvID(), resolved.ID),
- FailureMessage: "failed to restart container",
- SuccessMessage: fmt.Sprintf("Container %s restarted successfully", containerDisplayName(resolved)),
- JSON: jsonOutput,
- })
- },
+ output.Header("Container Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Image", resolved.Image)
+ output.KeyValue("State", fmt.Sprintf("%s (Running: %v)", resolved.State.Status, resolved.State.Running))
+ output.KeyValue("Created", resolved.Created)
+ return nil
+ },
+ }
}
-var containersUpdateCmd = &cobra.Command{
- Use: "update <container-id|name>",
- Short: "Update a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newStartCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "start <container-id|name>",
+ Short: "Start a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- // This route is served by the updater handler, so it answers with an
- // updater.Result rather than a container.ActionResult.
- return cmdutil.RunPostAction[updater.Result](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerUpdate(c.EnvID(), resolved.ID),
- FailureMessage: "failed to update container",
- SuccessMessage: fmt.Sprintf("Container %s updated successfully", containerDisplayName(resolved)),
- Timeout: 30 * time.Minute,
- JSON: jsonOutput,
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerStart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to start container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s started successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
}
-var containersRedeployCmd = &cobra.Command{
- Use: "redeploy <container-id|name>",
- Short: "Redeploy a container (pull image and recreate)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newStopCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "stop <container-id|name>",
+ Short: "Stop a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[container.Details](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerRedeploy(c.EnvID(), resolved.ID),
- FailureMessage: "failed to redeploy container",
- SuccessMessage: fmt.Sprintf("Container %s redeployed successfully", containerDisplayName(resolved)),
- Timeout: 30 * time.Minute,
- JSON: jsonOutput,
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerStop(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to stop container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s stopped successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
}
-var containersDeleteCmd = &cobra.Command{
- Use: "delete <container-id|name>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a container",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newRestartCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "restart <container-id|name>",
+ Short: "Restart a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- displayName := containerDisplayName(resolved)
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerRestart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to restart container",
+ Render: func(base.MessageResponse) error {
+ output.Success("Container %s restarted successfully", containerDisplayName(resolved))
+ return nil
+ },
+ })
+ },
+ }
+}
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete container %s?", displayName))
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+func newUpdateCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "update <container-id|name>",
+ Short: "Update a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
-
- query := url.Values{}
- query.Set("force", strconv.FormatBool(forceFlag))
- query.Set("volumes", strconv.FormatBool(containersDeleteVolumes))
- path := types.Container(c.EnvID(), resolved.ID) + "?" + query.Encode()
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to delete container: %w", err)
- }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- output.Success("Container %s deleted successfully", displayName)
- return nil
- },
+ // This route is served by the updater handler, so it answers with an
+ // updater.Result rather than a container.ActionResult.
+ return cmdutil.Run(cmd, c, cmdutil.Spec[updater.Result]{
+ Method: http.MethodPost,
+ Path: types.ContainerUpdate(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to update container",
+ Render: func(updater.Result) error {
+ output.Success("Container %s updated successfully", containerDisplayName(resolved))
+ return nil
+ },
+ Timeout: 30 * time.Minute,
+ })
+ },
+ }
}
-var containersCountsCmd = &cobra.Command{
- Use: "counts",
- Short: "Get container status counts",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[container.StatusCounts](cmd.Context(), types.ContainersCounts(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get container counts: %w", err)
- }
+func newRedeployCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "redeploy <container-id|name>",
+ Short: "Redeploy a container (pull image and recreate)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- output.Header("Container Status Counts")
- output.KeyValue("Running", result.Data.RunningContainers)
- output.KeyValue("Stopped", result.Data.StoppedContainers)
- output.KeyValue("Total", result.Data.TotalContainers)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.Details]{
+ Method: http.MethodPost,
+ Path: types.ContainerRedeploy(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to redeploy container",
+ Render: func(container.Details) error {
+ output.Success("Container %s redeployed successfully", containerDisplayName(resolved))
+ return nil
+ },
+ Timeout: 30 * time.Minute,
+ })
+ },
+ }
}
-var containersCreateCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new container",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ deleteVolumes bool
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <container-id|name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a container",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- c.SetTimeout(30 * time.Minute)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- var req container.Create
+ displayName := containerDisplayName(resolved)
- // File mode: read base config from file
- if containerCreateFile != "" {
- data, readFileErr := os.ReadFile(containerCreateFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read file %s: %w", containerCreateFile, readFileErr)
+ query := url.Values{
+ "force": {strconv.FormatBool(opts.force)},
+ "volumes": {strconv.FormatBool(opts.deleteVolumes)},
}
- if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
- return fmt.Errorf("failed to parse config file: %w", unmarshalErr)
- }
- }
+ path := types.Container(c.EnvID(), resolved.ID) + "?" + query.Encode()
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete container %s?", displayName),
+ Path: path,
+ FailureMessage: "failed to delete container",
+ SuccessMessage: fmt.Sprintf("Container %s deleted successfully", displayName),
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal of a running container and skip the confirmation prompt")
+ command.Flags().BoolVar(&opts.deleteVolumes, "volumes", false, "Remove anonymous volumes associated with the container")
+ return command
+}
- // Flag overrides
- if cmd.Flags().Changed("name") {
- req.Name = containerCreateName
- }
- if cmd.Flags().Changed("image") {
- req.Image = containerCreateImage
- }
- if cmd.Flags().Changed("env") {
- req.Env = containerCreateEnv
- }
- if cmd.Flags().Changed("port") {
- // Parse "HOST:CONTAINER" format into ports map
- req.Ports = make(map[string]string)
- for _, p := range containerCreatePort {
- parts := strings.SplitN(p, ":", 2)
- if len(parts) == 2 {
- req.Ports[parts[1]] = parts[0]
- }
- }
- }
- if cmd.Flags().Changed("volume") {
- req.Volumes = containerCreateVolume
- }
- if cmd.Flags().Changed("label") {
- req.Labels = make(map[string]string)
- for _, l := range containerCreateLabel {
- parts := strings.SplitN(l, "=", 2)
- if len(parts) == 2 {
- req.Labels[parts[0]] = parts[1]
- }
+func newCountsCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "counts",
+ Short: "Get container status counts",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- if cmd.Flags().Changed("network") {
- req.Networks = containerCreateNetwork
- }
- if cmd.Flags().Changed("restart") {
- req.RestartPolicy = containerCreateRestart
- }
- if cmd.Flags().Changed("memory") {
- req.Memory = containerCreateMemory
- }
- if cmd.Flags().Changed("cpus") {
- req.CPUs = containerCreateCPUs
- }
- if cmd.Flags().Changed("privileged") {
- req.Privileged = containerCreatePrivileged
- }
- if cmd.Flags().Changed("hostname") {
- req.Hostname = containerCreateHostname
- }
- if cmd.Flags().Changed("user") {
- req.User = containerCreateUser
- }
- if cmd.Flags().Changed("workdir") {
- req.WorkingDir = containerCreateWorkdir
- }
- if cmd.Flags().Changed("entrypoint") {
- req.Entrypoint = []string{containerCreateEntrypoint}
- }
- if cmd.Flags().Changed("cmd") {
- req.Cmd = []string{containerCreateCmd}
- }
- // Validate required fields
- if req.Name == "" {
- return errors.New("--name is required")
- }
- if req.Image == "" {
- return errors.New("--image is required")
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.StatusCounts]{
+ Method: http.MethodGet,
+ Path: types.ContainersCounts(c.EnvID()),
+ FailureMessage: "failed to get container counts",
+ Render: func(data container.StatusCounts) error {
+ output.Header("Container Status Counts")
+ output.KeyValue("Running", data.RunningContainers)
+ output.KeyValue("Stopped", data.StoppedContainers)
+ output.KeyValue("Total", data.TotalContainers)
+ return nil
+ },
+ })
+ },
+ }
+}
- result, err := c.PostJSON[container.Created](cmd.Context(), types.Containers(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to create container: %w", err)
- }
+type createOptions struct {
+ file string
+ name string
+ image string
+ env []string
+ port []string
+ volume []string
+ label []string
+ network []string
+ restart string
+ memory int64
+ cpus float64
+ privileged bool
+ hostname string
+ user string
+ workdir string
+ entrypoint string
+ cmd string
+}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newCreateCmd() *cobra.Command {
+ opts := &createOptions{}
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeDestination},
+ Use: "create",
+ Short: "Create a new container",
+ Example: " arcane containers create --name web --image nginx --env-var KEY=VALUE\n arcane containers create --name web --image nginx -e KEY=VALUE",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Container %s created successfully", result.Data.Name)
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Image", result.Data.Image)
- output.KeyValue("Status", result.Data.Status)
- return nil
- },
-}
+ c.SetTimeout(30 * time.Minute)
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, ContainersCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, containersListCmd, containersUpdatesCmd, containersCountsCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, containersCreateCmd)
- ContainersCmd.AddCommand(containersListCmd)
- ContainersCmd.AddCommand(containersUpdatesCmd)
- ContainersCmd.AddCommand(containersGetCmd)
- ContainersCmd.AddCommand(containersStartCmd)
- ContainersCmd.AddCommand(containersStopCmd)
- ContainersCmd.AddCommand(containersRestartCmd)
- ContainersCmd.AddCommand(containersUpdateCmd)
- ContainersCmd.AddCommand(containersRedeployCmd)
- ContainersCmd.AddCommand(containersDeleteCmd)
- ContainersCmd.AddCommand(containersCountsCmd)
- ContainersCmd.AddCommand(containersCreateCmd)
-
- // Create command flags
- containersCreateCmd.Flags().StringVarP(&containerCreateFile, "file", "f", "", "JSON config file for container creation")
- containersCreateCmd.Flags().StringVar(&containerCreateName, "name", "", "Container name")
- containersCreateCmd.Flags().StringVar(&containerCreateImage, "image", "", "Docker image")
- containersCreateCmd.Flags().StringArrayVarP(&containerCreateEnv, "env", "e", nil, "Environment variable (KEY=VALUE)")
- containersCreateCmd.Flags().StringArrayVarP(&containerCreatePort, "port", "p", nil, "Port mapping (HOST:CONTAINER)")
- containersCreateCmd.Flags().StringArrayVarP(&containerCreateVolume, "volume", "v", nil, "Volume mount (SRC:DST)")
- containersCreateCmd.Flags().StringArrayVarP(&containerCreateLabel, "label", "l", nil, "Label (KEY=VALUE)")
- containersCreateCmd.Flags().StringArrayVar(&containerCreateNetwork, "network", nil, "Networks to connect to")
- containersCreateCmd.Flags().StringVar(&containerCreateRestart, "restart", "", "Restart policy (no, always, unless-stopped, on-failure)")
- containersCreateCmd.Flags().Int64Var(&containerCreateMemory, "memory", 0, "Memory limit in bytes")
- containersCreateCmd.Flags().Float64Var(&containerCreateCPUs, "cpus", 0, "Number of CPUs")
- containersCreateCmd.Flags().BoolVar(&containerCreatePrivileged, "privileged", false, "Run in privileged mode")
- containersCreateCmd.Flags().StringVar(&containerCreateHostname, "hostname", "", "Container hostname")
- containersCreateCmd.Flags().StringVar(&containerCreateUser, "user", "", "User to run as")
- containersCreateCmd.Flags().StringVar(&containerCreateWorkdir, "workdir", "", "Working directory")
- containersCreateCmd.Flags().StringVar(&containerCreateEntrypoint, "entrypoint", "", "Entrypoint command")
- containersCreateCmd.Flags().StringVar(&containerCreateCmd, "cmd", "", "Command to run")
- containersCreateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // List command flags
- containersListCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
- containersListCmd.Flags().IntVar(&containersStart, "start", 0, cmdutil.StartFlagUsage)
- containersListCmd.Flags().BoolVarP(&containersAll, "all", "a", false, cmdutil.AllFlagUsage)
- containersListCmd.Flags().StringVar(&containersUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
- containersListCmd.Flags().StringVar(&containersStandalone, "standalone", "", "Filter standalone containers only (true/false)")
- containersListCmd.Flags().StringVar(&containersLabelFilter, "label", "", "Filter by label (key or key=value)")
- containersListCmd.Flags().BoolVar(&containersIncludeHidden, "include-hidden", false, "Include hidden containers")
- containersListCmd.Flags().BoolVar(&containersInclude, "include-internal", false, "Include Arcane-internal containers")
- containersListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersUpdatesCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
- containersUpdatesCmd.Flags().IntVar(&containersStart, "start", 0, cmdutil.StartFlagUsage)
- containersUpdatesCmd.Flags().BoolVarP(&containersAll, "all", "a", false, cmdutil.AllFlagUsage)
- containersUpdatesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- containersDeleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force removal of a running container and skip the confirmation prompt")
- containersDeleteCmd.Flags().BoolVar(&containersDeleteVolumes, "volumes", false, "Remove anonymous volumes associated with the container")
-
- // Global JSON output flags
- containersGetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersStartCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersStopCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersRestartCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersRedeployCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersDeleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersCountsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-}
+ req, requestErr := opts.request(cmd)
+ if requestErr != nil {
+ return requestErr
+ }
-func shortID(id string) string {
- if len(id) > 12 {
- return id[:12]
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.Created]{
+ Method: http.MethodPost,
+ Path: types.Containers(c.EnvID()),
+ Body: req,
+ FailureMessage: "failed to create container",
+ Render: func(data container.Created) error {
+ output.Success("Container %s created successfully", data.Name)
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("Image", data.Image)
+ output.KeyValue("Status", data.Status)
+ return nil
+ },
+ })
+ },
}
- return id
+ command.Flags().StringVarP(&opts.file, "file", "f", "", "JSON config file for container creation")
+ command.Flags().StringVar(&opts.name, "name", "", "Container name")
+ command.Flags().StringVar(&opts.image, "image", "", "Docker image")
+ command.Flags().StringArrayVarP(&opts.env, "env-var", "e", nil, "Environment variable (KEY=VALUE)")
+ command.Flags().Var(command.Flags().Lookup("env-var").Value, "env", "Environment variable (KEY=VALUE)")
+ _ = command.Flags().MarkDeprecated("env", "use --env-var or -e")
+ command.Flags().StringArrayVarP(&opts.port, "port", "p", nil, "Port mapping (HOST:CONTAINER)")
+ command.Flags().StringArrayVarP(&opts.volume, "volume", "v", nil, "Volume mount (SRC:DST)")
+ command.Flags().StringArrayVarP(&opts.label, "label", "l", nil, "Label (KEY=VALUE)")
+ command.Flags().StringArrayVar(&opts.network, "network", nil, "Networks to connect to")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.restart, "restart", "", "", "Restart policy", "no", "always", "unless-stopped", "on-failure")
+ command.Flags().Int64Var(&opts.memory, "memory", 0, "Memory limit in bytes")
+ command.Flags().Float64Var(&opts.cpus, "cpus", 0, "Number of CPUs")
+ command.Flags().BoolVar(&opts.privileged, "privileged", false, "Run in privileged mode")
+ command.Flags().StringVar(&opts.hostname, "hostname", "", "Container hostname")
+ command.Flags().StringVar(&opts.user, "user", "", "User to run as")
+ command.Flags().StringVar(&opts.workdir, "workdir", "", "Working directory")
+ command.Flags().StringVar(&opts.entrypoint, "entrypoint", "", "Entrypoint command")
+ command.Flags().StringVar(&opts.cmd, "cmd", "", "Command to run")
+ return command
}
func containerDisplayName(details *container.Details) string {
@@ -596,10 +513,7 @@ func containerDisplayName(details *container.Details) string {
if strings.TrimSpace(details.Name) != "" {
return details.Name
}
- if details.ID != "" {
- return shortID(details.ID)
- }
- return ""
+ return details.ID[:min(len(details.ID), 12)]
}
var ContainerRef = cmdutil.ResourceRef[container.Details, container.Summary]{
@@ -611,48 +525,109 @@ var ContainerRef = cmdutil.ResourceRef[container.Details, container.Summary]{
GetPath: types.Container,
ListPath: types.Containers,
Matches: func(item container.Summary, identifierLower, original string) bool {
- idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
- if strings.Contains(idLower, identifierLower) {
- return true
- }
- if strings.Contains(strings.ToLower(item.Image), identifierLower) {
- return true
- }
- for _, name := range item.Names {
- trimmedName := strings.TrimPrefix(name, "/")
- if strings.Contains(strings.ToLower(trimmedName), identifierLower) {
- return true
- }
- if strings.EqualFold(trimmedName, original) || strings.EqualFold(name, original) {
- return true
- }
- }
- return false
+ return strings.Contains(strings.ToLower(item.ID), identifierLower) ||
+ strings.Contains(strings.ToLower(item.Image), identifierLower) ||
+ slices.ContainsFunc(item.Names, func(name string) bool {
+ trimmedName := strings.TrimPrefix(name, "/")
+ return strings.Contains(strings.ToLower(trimmedName), identifierLower) || strings.EqualFold(trimmedName, original) || strings.EqualFold(name, original)
+ })
},
Label: func(item container.Summary) string {
- name := ""
- if len(item.Names) > 0 {
- name = strings.TrimPrefix(item.Names[0], "/")
- }
- if name == "" {
- name = shortID(item.ID)
- }
+ name := cmp.Or(docker.ContainerNameFromNames(item.Names), item.ID[:min(len(item.ID), 12)])
image := cmp.Or(item.Image, "<unknown>")
state := cmp.Or(item.State, "unknown")
- return fmt.Sprintf("%s (%s, %s)", name, shortID(item.ID), image+" / "+state)
+ return fmt.Sprintf("%s (%s, %s)", name, item.ID[:min(len(item.ID), 12)], image+" / "+state)
},
Promote: func(summary container.Summary) *container.Details {
- return &container.Details{ID: summary.ID, Name: containerSummaryName(summary)}
+ return &container.Details{ID: summary.ID, Name: docker.ContainerNameFromNames(summary.Names)}
},
- IDOf: func(item container.Summary) string { return item.ID },
+ IDOf: func(item container.Summary) string { return item.ID },
+ IdentifierOf: func(details container.Details) string { return details.ID },
}
-func containerSummaryName(summary container.Summary) string {
- if len(summary.Names) == 0 {
- return ""
+func (opts *createOptions) request(cmd *cobra.Command) (container.Create, error) {
+ var req container.Create
+
+ // File mode: read base config from file
+ if opts.file != "" {
+ data, readFileErr := os.ReadFile(opts.file)
+ if readFileErr != nil {
+ return req, fmt.Errorf("failed to read file %s: %w", opts.file, readFileErr)
+ }
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return req, fmt.Errorf("failed to parse config file: %w", unmarshalErr)
+ }
+ }
+
+ // Flag overrides
+ if cmd.Flags().Changed("name") {
+ req.Name = opts.name
+ }
+ if cmd.Flags().Changed("image") {
+ req.Image = opts.image
+ }
+ if cmd.Flags().Changed("env-var") || cmd.Flags().Changed("env") {
+ req.Env = opts.env
+ }
+ if cmd.Flags().Changed("port") {
+ // Parse "HOST:CONTAINER" format into ports map
+ req.Ports = make(map[string]string)
+ for _, p := range opts.port {
+ parts := strings.SplitN(p, ":", 2)
+ if len(parts) == 2 {
+ req.Ports[parts[1]] = parts[0]
+ }
+ }
+ }
+ if cmd.Flags().Changed("volume") {
+ req.Volumes = opts.volume
+ }
+ if cmd.Flags().Changed("label") {
+ req.Labels = make(map[string]string)
+ for _, l := range opts.label {
+ parts := strings.SplitN(l, "=", 2)
+ if len(parts) == 2 {
+ req.Labels[parts[0]] = parts[1]
+ }
+ }
+ }
+ if cmd.Flags().Changed("network") {
+ req.Networks = opts.network
+ }
+ if cmd.Flags().Changed("restart") {
+ req.RestartPolicy = opts.restart
+ }
+ if cmd.Flags().Changed("memory") {
+ req.Memory = opts.memory
+ }
+ if cmd.Flags().Changed("cpus") {
+ req.CPUs = opts.cpus
+ }
+ if cmd.Flags().Changed("privileged") {
+ req.Privileged = opts.privileged
+ }
+ if cmd.Flags().Changed("hostname") {
+ req.Hostname = opts.hostname
+ }
+ if cmd.Flags().Changed("user") {
+ req.User = opts.user
+ }
+ if cmd.Flags().Changed("workdir") {
+ req.WorkingDir = opts.workdir
+ }
+ if cmd.Flags().Changed("entrypoint") {
+ req.Entrypoint = []string{opts.entrypoint}
+ }
+ if cmd.Flags().Changed("cmd") {
+ req.Cmd = []string{opts.cmd}
+ }
+
+ // Validate required fields
+ if req.Name == "" {
+ return req, errors.New("--name is required")
+ }
+ if req.Image == "" {
+ return req, errors.New("--image is required")
}
- return strings.TrimPrefix(summary.Names[0], "/")
+ return req, nil
}
diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.go
index bfe252e44..0bdc7121b 100644
--- a/cli/pkg/doctor/cmd.go
+++ b/cli/pkg/doctor/cmd.go
@@ -1,11 +1,13 @@
package doctor
import (
+ "cmp"
"errors"
- "fmt"
+ "slices"
"strings"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
@@ -24,113 +26,94 @@ type report struct {
Checks []checkResult `json:"checks"`
}
-var jsonOutput bool
-
-// DoctorCmd runs environment and connection diagnostics.
-var DoctorCmd = &cobra.Command{
- Use: "doctor",
- Short: "Run CLI diagnostics",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- app, ok := runtime.From(cmd.Context())
- if !ok {
- created, err := runtime.New(runtime.Options{})
- if err != nil {
- return err
+// Command runs environment and connection diagnostics.
+func Command() *cobra.Command {
+ return &cobra.Command{
+ Use: "doctor",
+ Short: "Run CLI diagnostics",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ app, ok := runtime.From(cmd.Context())
+ if !ok {
+ created, err := runtime.New(runtime.Options{})
+ if err != nil {
+ return err
+ }
+ app = created
}
- app = created
- }
-
- cfg := app.Config()
- if cfg == nil {
- return errors.New("configuration unavailable")
- }
- rep := report{Healthy: true}
- path, _ := config.ConfigPath()
- rep.Checks = append(rep.Checks, checkResult{
- Name: "config_path",
- Status: "ok",
- Details: path,
- })
-
- if strings.TrimSpace(cfg.ServerURL) == "" {
- rep.Healthy = false
- rep.Checks = append(rep.Checks, checkResult{
- Name: "server_url",
- Status: "fail",
- Details: "server_url is not configured (run `arcane config set server-url <url>`)",
- })
- } else {
- rep.Checks = append(rep.Checks, checkResult{Name: "server_url", Status: "ok", Details: cfg.ServerURL})
- }
-
- env := cfg.DefaultEnvironment
- if app.EnvID() != "" {
- env = app.EnvID()
- }
- if strings.TrimSpace(env) == "" {
- env = "0"
- }
- rep.Checks = append(rep.Checks, checkResult{Name: "environment", Status: "ok", Details: env})
+ cfg := app.Config()
+ if cfg == nil {
+ return errors.New("configuration unavailable")
+ }
- if cfg.HasAuth() {
- rep.Checks = append(rep.Checks, checkResult{Name: "auth", Status: "ok", Details: "credentials configured"})
- } else {
- rep.Healthy = false
- rep.Checks = append(rep.Checks, checkResult{
- Name: "auth",
- Status: "fail",
- Details: "authentication is not configured (run `arcane config set api-key ...` or `arcane auth login`)",
- })
- }
+ path, _ := config.ConfigPath()
+ env := cmp.Or(app.EnvID(), cfg.DefaultEnvironment)
+ if strings.TrimSpace(env) == "" {
+ env = "0"
+ }
+ serverConfigured, hasAuth := strings.TrimSpace(cfg.ServerURL) != "", cfg.HasAuth()
+ checks := []checkResult{
+ {Name: "config_path", Status: "ok", Details: path},
+ {
+ Name: "server_url",
+ Status: kit.Ternary(serverConfigured, "ok", "fail"),
+ Details: kit.Ternary(serverConfigured, cfg.ServerURL, "server_url is not configured (run `arcane config set server-url <url>`)"),
+ },
+ {Name: "environment", Status: "ok", Details: env},
+ {
+ Name: "auth",
+ Status: kit.Ternary(hasAuth, "ok", "fail"),
+ Details: kit.Ternary(hasAuth, "credentials configured", "authentication is not configured (run `arcane config set api-key ...` or `arcane auth login`)"),
+ },
+ }
- if strings.TrimSpace(cfg.ServerURL) != "" && cfg.HasAuth() {
- c, err := app.Client()
- if err != nil {
- rep.Healthy = false
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
- } else {
- if testConnectionErr := c.TestConnection(cmd.Context()); testConnectionErr != nil {
- rep.Healthy = false
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: testConnectionErr.Error()})
+ switch {
+ case !serverConfigured:
+ checks = append(checks, checkResult{Name: "api_connection", Status: "skip", Details: "server_url missing"})
+ case !hasAuth:
+ checks = append(checks, checkResult{Name: "api_connection", Status: "skip", Details: "auth missing"})
+ default:
+ c, err := app.Client()
+ if err == nil {
+ err = c.TestConnection(cmd.Context())
+ }
+ if err != nil {
+ checks = append(checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
} else {
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "ok", Details: "connected"})
+ checks = append(checks, checkResult{Name: "api_connection", Status: "ok", Details: "connected"})
}
}
- } else if strings.TrimSpace(cfg.ServerURL) == "" {
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "skip", Details: "server_url missing"})
- } else {
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "skip", Details: "auth missing"})
- }
-
- if jsonOutput || app.IsJSON() {
- if err := cmdutil.PrintJSON(rep); err != nil {
- return fmt.Errorf("failed to marshal doctor output: %w", err)
- }
- } else {
- output.Header("Arcane CLI Diagnostics")
- rows := make([][]string, 0, len(rep.Checks))
- for _, item := range rep.Checks {
- rows = append(rows, []string{item.Name, item.Status, item.Details})
- }
- if tableErr := output.Table([]string{"CHECK", "STATUS", "DETAILS"}, rows); tableErr != nil {
- return tableErr
+ rep := report{
+ Healthy: !slices.ContainsFunc(checks, func(item checkResult) bool { return item.Status == "fail" }),
+ Checks: checks,
}
- if rep.Healthy {
- output.Success("Doctor checks passed")
+
+ if cmdutil.JSONOutputEnabled(cmd) {
+ if printErr := cmdutil.PrintJSON(rep); printErr != nil {
+ return printErr
+ }
} else {
- output.Warning("Doctor found issues")
+ output.Header("Arcane CLI Diagnostics")
+ rows := make([][]string, len(rep.Checks))
+ for i, item := range rep.Checks {
+ rows[i] = []string{item.Name, item.Status, item.Details}
+ }
+ if tableErr := output.Table([]string{"CHECK", "STATUS", "DETAILS"}, rows); tableErr != nil {
+ return tableErr
+ }
+ if rep.Healthy {
+ output.Success("Doctor checks passed")
+ } else {
+ output.Warning("Doctor found issues")
+ }
}
- }
- if !rep.Healthy {
- return errors.New("diagnostics failed")
- }
- return nil
- },
-}
-
-func init() {
- DoctorCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ if !rep.Healthy {
+ return errors.New("diagnostics failed")
+ }
+ return nil
+ },
+ }
}
diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.go
index 8ab7abe88..2d6b3c817 100644
--- a/cli/pkg/environments/cmd.go
+++ b/cli/pkg/environments/cmd.go
@@ -10,12 +10,11 @@ import (
"strings"
"charm.land/lipgloss/v2"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/environment"
"github.com/getarcaneapp/arcane/types/v2/version"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
@@ -23,30 +22,6 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-)
-
-var (
- envUpdateName string
- envUpdateApiUrl string
- envUpdateEnabled bool
- envUpdateDisabled bool
-)
-
-var (
- envCreateName string
- envCreateApiUrl string
- envCreateAccessToken string
- envCreateUseApiKey bool
- envCreateEdge bool
- envCreateDisabled bool
-)
-
var (
statusOnlineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#22c55e"))
statusOfflineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ef4444"))
@@ -54,431 +29,391 @@ var (
enabledStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#6d28d9"))
)
-// EnvironmentsCmd is the parent command for environment operations
-var EnvironmentsCmd = &cobra.Command{
- Use: "environments",
- Aliases: []string{"environment", "env", "e"},
- Short: "Manage environments",
+// Command is the parent command for environment operations
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "environments",
+ Aliases: []string{"environment", "env", "e"},
+ Short: "Manage environments",
+ }
+ command.AddCommand(newListCmd())
+ command.AddCommand(newGetCmd())
+ command.AddCommand(newTestCmd())
+ command.AddCommand(newDeleteCmd())
+ command.AddCommand(newSwitchCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newVersionCmd())
+ command.AddCommand(newCreateCmd())
+ return command
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List environments",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List environments",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[environment.Environment]{
- Resource: "environments",
- Endpoint: types.Environments(),
- Params: cmdutil.ListParams{Resource: "environments", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "API URL", "STATUS", "ENABLED"},
- Row: func(env environment.Environment) []string {
- enabled := "false"
- if env.Enabled {
- enabled = "true"
- }
- return []string{
- env.ID,
- env.Name,
- env.ApiUrl,
- env.Status,
- enabled,
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[environment.Environment]{
+ Resource: "environments",
+ Endpoint: types.Environments(),
+ Params: cmdutil.ListParams{Resource: "environments", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "API URL", "STATUS", "ENABLED"},
+ Row: func(env environment.Environment) []string {
+ return []string{
+ env.ID,
+ env.Name,
+ env.ApiUrl,
+ env.Status,
+ strconv.FormatBool(env.Enabled),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of environments to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete environment",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete environment %s?", args[0]))
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete environment",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- if _, deleteEnvironmentErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Environment(args[0])); deleteEnvironmentErr != nil {
- return fmt.Errorf("failed to delete environment: %w", deleteEnvironmentErr)
- }
-
- output.Success("Environment deleted successfully")
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete environment %s?", args[0]),
+ Path: types.Environment(args[0]),
+ FailureMessage: "failed to delete environment",
+ SuccessMessage: "Environment deleted successfully",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return command
}
-var getCmd = &cobra.Command{
- Use: "get <id>",
- Short: "Get environment details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[environment.Environment](cmd.Context(), types.Environment(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get environment: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
- }
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <id>",
+ Short: "Get environment details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Environment Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("API URL", result.Data.ApiUrl)
- output.KeyValue("Status", result.Data.Status)
- output.KeyValue("Enabled", result.Data.Enabled)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[environment.Environment]{
+ Method: http.MethodGet,
+ Path: types.Environment(args[0]),
+ FailureMessage: "failed to get environment",
+ Body: nil,
+ Render: func(data environment.Environment) error {
+ output.Header("Environment Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("API URL", data.ApiUrl)
+ output.KeyValue("Status", data.Status)
+ output.KeyValue("Enabled", data.Enabled)
+ return nil
+ },
+ })
+ },
+ }
}
-var testCmd = &cobra.Command{
- Use: "test <id>",
- Short: "Test environment connection",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+func newTestCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "test <id>",
+ Short: "Test environment connection",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[environment.Test](cmd, c, cmdutil.PostActionSpec{
- Path: types.EnvironmentTest(args[0]),
- FailureMessage: "failed to test environment",
- SuccessMessage: "Environment connection test successful",
- JSON: jsonOutput,
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[environment.Test]{
+ Method: http.MethodPost,
+ Path: types.EnvironmentTest(args[0]),
+ FailureMessage: "failed to test environment",
+ Render: func(environment.Test) error {
+ output.Success("%s", "Environment connection test successful")
+ return nil
+ },
+ })
+ },
+ }
}
-var switchCmd = &cobra.Command{
- Use: "switch",
- Short: "Switch the default environment (interactive)",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !prompt.IsInteractive() {
- return errors.New("interactive terminal required; run `arcane config set environment <id>` instead")
- }
+func newSwitchCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "switch",
+ Short: "Switch the default environment (interactive)",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !cmdutil.AllowPrompt(cmd) {
+ return errors.New("interactive terminal required; run `arcane config set environment <id>` instead")
+ }
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- path := fmt.Sprintf("%s?limit=%d", types.Environments(), cmdutil.ShowAllLimit)
- result, err := c.DoJSON[base.Paginated[environment.Environment]](cmd.Context(), http.MethodGet, path, nil)
- if err != nil {
- return fmt.Errorf("failed to list environments: %w", err)
- }
+ path := fmt.Sprintf("%s?limit=%d", types.Environments(), cmdutil.ShowAllLimit)
+ result, err := c.GetJSON[[]environment.Environment](cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list environments: %w", err)
+ }
- if len(result.Data) == 0 {
- return errors.New("no environments available")
- }
+ if len(result.Data) == 0 {
+ return errors.New("no environments available")
+ }
- currentEnv := cfg.DefaultEnvironment
- if strings.TrimSpace(currentEnv) == "" {
- currentEnv = "0"
- }
+ currentEnv := cmp.Or(strings.TrimSpace(cfg.DefaultEnvironment), "0")
- envs := result.Data
- sort.SliceStable(envs, func(i, j int) bool {
- left := strings.ToLower(strings.TrimSpace(envs[i].Name))
- right := strings.ToLower(strings.TrimSpace(envs[j].Name))
- if left == "" {
- left = strings.ToLower(envs[i].ID)
- }
- if right == "" {
- right = strings.ToLower(envs[j].ID)
- }
- if left == right {
- return envs[i].ID < envs[j].ID
- }
- return left < right
- })
-
- options := make([]string, len(envs))
- for i, env := range envs {
- displayName := cmp.Or(strings.TrimSpace(env.Name), env.ID)
- status := strings.TrimSpace(env.Status)
- if status == "" {
- status = "unknown"
- }
- var statusLabel string
- switch strings.ToLower(status) {
- case "online":
- statusLabel = statusOnlineStyle.Render(status)
- case "offline":
- statusLabel = statusOfflineStyle.Render(status)
- default:
- statusLabel = statusMutedStyle.Render(status)
- }
+ envs := result.Data
+ sort.SliceStable(envs, func(i, j int) bool {
+ left := strings.ToLower(cmp.Or(strings.TrimSpace(envs[i].Name), envs[i].ID))
+ right := strings.ToLower(cmp.Or(strings.TrimSpace(envs[j].Name), envs[j].ID))
+ if left == right {
+ return envs[i].ID < envs[j].ID
+ }
+ return left < right
+ })
- enabledLabel := statusMutedStyle.Render("disabled")
- if env.Enabled {
- enabledLabel = enabledStyle.Render("enabled")
+ choice, err := prompt.Select("environment", environmentOptions(envs, currentEnv))
+ if err != nil {
+ return err
}
- marker := " "
- if env.ID == currentEnv {
- marker = "* "
+
+ selected := envs[choice]
+ if selected.ID == currentEnv {
+ output.Info("Default environment already set to %s", selected.ID)
+ return nil
}
- options[i] = fmt.Sprintf("%s%s (id: %s, %s, %s)", marker, displayName, env.ID, statusLabel, enabledLabel)
- }
- choice, err := prompt.Select("environment", options)
- if err != nil {
- return err
- }
+ cfg.DefaultEnvironment = selected.ID
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
+ }
- selected := envs[choice]
- if selected.ID == currentEnv {
- output.Info("Default environment already set to %s", selected.ID)
+ output.Success("Default environment set to %s", selected.ID)
+ if strings.TrimSpace(selected.Name) != "" {
+ output.KeyValue("Name", selected.Name)
+ }
+ output.KeyValue("API URL", selected.ApiUrl)
return nil
- }
-
- cfg.DefaultEnvironment = selected.ID
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to save config: %w", saveErr)
- }
-
- output.Success("Default environment set to %s", selected.ID)
- if strings.TrimSpace(selected.Name) != "" {
- output.KeyValue("Name", selected.Name)
- }
- output.KeyValue("API URL", selected.ApiUrl)
- return nil
- },
+ },
+ }
}
-var updateCmd = &cobra.Command{
- Use: "update <id>",
- Short: "Update environment",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- var req environment.Update
- if cmd.Flags().Changed("enabled") && cmd.Flags().Changed("disabled") {
- return errors.New("--enabled and --disabled are mutually exclusive")
- }
- if cmd.Flags().Changed("name") {
- req.Name = &envUpdateName
- }
- if cmd.Flags().Changed("api-url") {
- req.ApiUrl = &envUpdateApiUrl
- }
- if cmd.Flags().Changed("enabled") {
- req.Enabled = new(true)
- }
- if cmd.Flags().Changed("disabled") {
- req.Enabled = new(false)
- }
-
- result, err := c.PutJSON[environment.Environment](cmd.Context(), types.Environment(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update environment: %w", err)
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ apiUrl string
+ enabled bool
+ disabled bool
+ }
+ command := &cobra.Command{
+ Use: "update <id>",
+ Short: "Update environment",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ PreRunE: func(cmd *cobra.Command, _ []string) error {
+ return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled")
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
- }
+ enabled := cmd.Flags().Changed("enabled") && opts.enabled || cmd.Flags().Changed("disabled") && !opts.disabled
+ req := environment.Update{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ ApiUrl: kit.Ternary(cmd.Flags().Changed("api-url"), &opts.apiUrl, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled") || cmd.Flags().Changed("disabled"), &enabled, nil),
+ }
- output.Success("Environment updated successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("API URL", result.Data.ApiUrl)
- output.KeyValue("Enabled", result.Data.Enabled)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[environment.Environment]{
+ Method: http.MethodPut,
+ Path: types.Environment(args[0]),
+ FailureMessage: "failed to update environment",
+ Body: req,
+ Render: func(data environment.Environment) error {
+ output.Success("Environment updated successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("API URL", data.ApiUrl)
+ output.KeyValue("Enabled", data.Enabled)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.name, "name", "", "Environment name")
+ command.Flags().StringVar(&opts.apiUrl, "api-url", "", "API URL")
+ command.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable environment")
+ command.Flags().BoolVar(&opts.disabled, "disabled", false, "Disable environment")
+ _ = command.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ return command
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create environment",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- req := environment.Create{ApiUrl: envCreateApiUrl}
- if cmd.Flags().Changed("name") {
- req.Name = &envCreateName
- }
- if cmd.Flags().Changed("access-token") {
- req.AccessToken = &envCreateAccessToken
- }
- if cmd.Flags().Changed("use-api-key") {
- req.UseApiKey = &envCreateUseApiKey
- }
- if cmd.Flags().Changed("edge") {
- req.IsEdge = &envCreateEdge
- }
- if cmd.Flags().Changed("disabled") {
- req.Enabled = new(!envCreateDisabled)
- }
-
- result, err := c.PostJSON[environment.Environment](cmd.Context(), types.Environments(), req)
- if err != nil {
- return fmt.Errorf("failed to create environment: %w", err)
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ apiUrl string
+ accessToken string
+ useApiKey bool
+ edge bool
+ disabled bool
+ enabled bool
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create environment",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ PreRunE: func(cmd *cobra.Command, _ []string) error {
+ return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled")
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(buildEnvironmentPayloadInternal(result.Data))
- }
+ req := environment.Create{
+ ApiUrl: opts.apiUrl,
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ AccessToken: kit.Ternary(cmd.Flags().Changed("access-token"), &opts.accessToken, nil),
+ UseApiKey: kit.Ternary(cmd.Flags().Changed("use-api-key"), &opts.useApiKey, nil),
+ IsEdge: kit.Ternary(cmd.Flags().Changed("edge"), &opts.edge, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled") || cmd.Flags().Changed("disabled"), new(opts.enabled && !opts.disabled), nil),
+ }
- output.Success("Environment created successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("API URL", result.Data.ApiUrl)
- output.KeyValue("Enabled", result.Data.Enabled)
- if result.Data.ApiKey != nil && *result.Data.ApiKey != "" {
- output.Warning("Pairing API key (shown only once) — store it now:")
- output.KeyValue("API Key", *result.Data.ApiKey)
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[environment.Environment]{
+ Method: http.MethodPost,
+ Path: types.Environments(),
+ FailureMessage: "failed to create environment",
+ Body: req,
+ Render: func(data environment.Environment) error {
+ output.Success("Environment created successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("API URL", data.ApiUrl)
+ output.KeyValue("Enabled", data.Enabled)
+ if data.ApiKey != nil && *data.ApiKey != "" {
+ output.Warning("Pairing API key (shown only once) — store it now:")
+ output.KeyValue("API Key", *data.ApiKey)
+ }
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.apiUrl, "api-url", "", "API URL of the environment (required)")
+ command.Flags().StringVar(&opts.name, "name", "", "Environment name")
+ command.Flags().StringVar(&opts.accessToken, "access-token", "", "Access token for legacy pairing")
+ command.Flags().BoolVar(&opts.useApiKey, "use-api-key", false, "Pair using a generated API key (shown once)")
+ command.Flags().BoolVar(&opts.edge, "edge", false, "Create as an edge environment")
+ command.Flags().BoolVar(&opts.enabled, "enabled", true, "Enable environment")
+ command.Flags().BoolVar(&opts.disabled, "disabled", false, "Create environment in disabled state")
+ _ = command.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ _ = command.MarkFlagRequired("api-url")
+ return command
}
-var versionCmd = &cobra.Command{
- Use: "version <id>",
- Short: "Get environment version",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[version.Info](cmd.Context(), types.EnvironmentVersion(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get environment version: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Environment Version")
- output.KeyValue("Version", result.Data.DisplayVersion)
- output.KeyValue("Full Version", result.Data.CurrentVersion)
- output.KeyValue("Tag", result.Data.CurrentTag)
- output.KeyValue("Revision", result.Data.ShortRevision)
- output.KeyValue("Go Version", result.Data.GoVersion)
- output.KeyValue("Build Time", result.Data.BuildTime)
- output.KeyValue("Update Available", strconv.FormatBool(result.Data.UpdateAvailable))
- return nil
- },
-}
+func newVersionCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "version <id>",
+ Short: "Get environment version",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-func buildEnvironmentPayloadInternal(env environment.Environment) map[string]any {
- payload := map[string]any{
- "id": env.ID,
- "name": env.Name,
- "apiUrl": env.ApiUrl,
- "status": env.Status,
- "enabled": env.Enabled,
- "isEdge": env.IsEdge,
+ return cmdutil.Run(cmd, c, cmdutil.Spec[version.Info]{
+ Method: http.MethodGet,
+ Path: types.EnvironmentVersion(args[0]),
+ FailureMessage: "failed to get environment version",
+ Render: func(data version.Info) error {
+ output.Header("Environment Version")
+ output.KeyValue("Version", data.DisplayVersion)
+ output.KeyValue("Full Version", data.CurrentVersion)
+ output.KeyValue("Tag", data.CurrentTag)
+ output.KeyValue("Revision", data.ShortRevision)
+ output.KeyValue("Go Version", data.GoVersion)
+ output.KeyValue("Build Time", data.BuildTime)
+ output.KeyValue("Update Available", strconv.FormatBool(data.UpdateAvailable))
+ return nil
+ },
+ })
+ },
}
- if env.EdgeTransport != nil {
- payload["edgeTransport"] = *env.EdgeTransport
- }
- if env.Connected != nil {
- payload["connected"] = *env.Connected
- }
- if env.ConnectedAt != nil {
- payload["connectedAt"] = *env.ConnectedAt
- }
- if env.LastHeartbeat != nil {
- payload["lastHeartbeat"] = *env.LastHeartbeat
- }
- if env.ApiKey != nil {
- payload["apiKey"] = *env.ApiKey
- }
-
- return payload
}
-func init() {
- EnvironmentsCmd.AddCommand(listCmd)
- EnvironmentsCmd.AddCommand(getCmd)
- EnvironmentsCmd.AddCommand(testCmd)
- EnvironmentsCmd.AddCommand(deleteCmd)
- EnvironmentsCmd.AddCommand(switchCmd)
- EnvironmentsCmd.AddCommand(updateCmd)
- EnvironmentsCmd.AddCommand(versionCmd)
- EnvironmentsCmd.AddCommand(createCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of environments to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Test command flags
- testCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Update command flags
- updateCmd.Flags().StringVar(&envUpdateName, "name", "", "Environment name")
- updateCmd.Flags().StringVar(&envUpdateApiUrl, "api-url", "", "API URL")
- updateCmd.Flags().BoolVar(&envUpdateEnabled, "enabled", false, "Enable environment")
- updateCmd.Flags().BoolVar(&envUpdateDisabled, "disabled", false, "Disable environment")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Version command flags
- versionCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&envCreateApiUrl, "api-url", "", "API URL of the environment (required)")
- createCmd.Flags().StringVar(&envCreateName, "name", "", "Environment name")
- createCmd.Flags().StringVar(&envCreateAccessToken, "access-token", "", "Access token for legacy pairing")
- createCmd.Flags().BoolVar(&envCreateUseApiKey, "use-api-key", false, "Pair using a generated API key (shown once)")
- createCmd.Flags().BoolVar(&envCreateEdge, "edge", false, "Create as an edge environment")
- createCmd.Flags().BoolVar(&envCreateDisabled, "disabled", false, "Create environment in disabled state")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("api-url")
+func environmentOptions(environments []environment.Environment, currentEnv string) []string {
+ options := make([]string, len(environments))
+ for i, env := range environments {
+ displayName := cmp.Or(strings.TrimSpace(env.Name), env.ID)
+ status := cmp.Or(strings.TrimSpace(env.Status), "unknown")
+ var statusLabel string
+ switch strings.ToLower(status) {
+ case "online":
+ statusLabel = statusOnlineStyle.Render(status)
+ case "offline":
+ statusLabel = statusOfflineStyle.Render(status)
+ default:
+ statusLabel = statusMutedStyle.Render(status)
+ }
+
+ enabledLabel := statusMutedStyle.Render("disabled")
+ if env.Enabled {
+ enabledLabel = enabledStyle.Render("enabled")
+ }
+ marker := " "
+ if env.ID == currentEnv {
+ marker = "* "
+ }
+ options[i] = fmt.Sprintf("%s%s (id: %s, %s, %s)", marker, displayName, env.ID, statusLabel, enabledLabel)
+ }
+ return options
}
diff --git a/cli/pkg/generate/api_key.go b/cli/pkg/generate/api_key.go
index 0f70e5f2d..db8515bf8 100644
--- a/cli/pkg/generate/api_key.go
+++ b/cli/pkg/generate/api_key.go
@@ -4,7 +4,6 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
- "io"
"github.com/spf13/cobra"
)
@@ -14,18 +13,27 @@ const (
apiKeyLength = 32
)
-var apiKeyCmd = &cobra.Command{
- Use: "apikey",
- Aliases: []string{"api-key"},
- Short: "Generate a static admin API key",
- Long: `Generate a static Arcane API key suitable for ADMIN_STATIC_API_KEY. This is just a local generation, nothing is stored to the database with these commands.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- return generateAPIKeyOutputInternal(cmd.OutOrStdout())
- },
-}
-
-func init() {
- GenerateCmd.AddCommand(apiKeyCmd)
+func newAPIKeyCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "apikey",
+ Aliases: []string{"api-key"},
+ Short: "Generate a static admin API key",
+ Long: `Generate a static Arcane API key suitable for ADMIN_STATIC_API_KEY. This is just a local generation, nothing is stored to the database with these commands.`,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ apiKey, err := GenerateAPIKey()
+ if err != nil {
+ return err
+ }
+ if jsonOutput(cmd) {
+ return printJSON(cmd, struct {
+ Key string `json:"key"`
+ }{Key: apiKey})
+ }
+ _, _ = fmt.Fprintln(cmd.OutOrStdout(), apiKey)
+ return nil
+ },
+ }
}
func GenerateAPIKey() (string, error) {
@@ -36,13 +44,3 @@ func GenerateAPIKey() (string, error) {
return apiKeyPrefix + hex.EncodeToString(keyBytes), nil
}
-
-func generateAPIKeyOutputInternal(w io.Writer) error {
- apiKey, err := GenerateAPIKey()
- if err != nil {
- return err
- }
-
- _, _ = fmt.Fprintln(w, apiKey)
- return nil
-}
diff --git a/cli/pkg/generate/api_key_test.go b/cli/pkg/generate/api_key_test.go
index 548d905b2..a2d42e0a6 100644
--- a/cli/pkg/generate/api_key_test.go
+++ b/cli/pkg/generate/api_key_test.go
@@ -6,11 +6,11 @@ import (
"github.com/stretchr/testify/require"
- gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
)
func TestAPIKeyDefaultOutput(t *testing.T) {
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"api-key"})
out, err := captureOutput(func() error {
@@ -32,7 +32,7 @@ func TestAPIKeyDefaultOutput(t *testing.T) {
}
func TestGenerateAPIKeyProducesArcanePrefix(t *testing.T) {
- apiKey, err := gen.GenerateAPIKey()
+ apiKey, err := generate.GenerateAPIKey()
require.NoError(t, err,
"GenerateAPIKey failed: %v", err)
diff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.go
index c9a5099a5..0e3656c9e 100644
--- a/cli/pkg/generate/certs.go
+++ b/cli/pkg/generate/certs.go
@@ -11,7 +11,6 @@ import (
"encoding/pem"
"errors"
"fmt"
- "io"
"math/big"
"net"
"net/url"
@@ -22,67 +21,74 @@ import (
"github.com/spf13/cobra"
"go.getarcane.app/acfs/atomic"
+ kit "go.getarcane.app/kit/pkg"
)
const (
certValidity = 5 * 365 * 24 * time.Hour
)
-var (
- mtlsOutDir string
- mtlsEnvID string
- mtlsAppURL string
- tlsOutDir string
- tlsCommonName string
- tlsHosts []string
- tlsCertName string
- tlsKeyName string
-)
-
-var mtlsCmd = &cobra.Command{
- Use: "mtls",
- Short: "Generate Arcane edge mTLS assets",
- Long: `Generate an Arcane-managed edge mTLS CA and agent client certificate bundle using ML-DSA-87.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- return generateMTLSOutputInternal(cmd.OutOrStdout())
- },
+func newMTLSCmd() *cobra.Command {
+ var opts struct {
+ outDir string
+ envID string
+ appURL string
+ }
+ cmd := &cobra.Command{
+ Use: "mtls",
+ Short: "Generate Arcane edge mTLS assets",
+ Long: `Generate an Arcane-managed edge mTLS CA and agent client certificate bundle using ML-DSA-87.`,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return generateMTLSOutput(cmd, opts.outDir, opts.envID, opts.appURL)
+ },
+ }
+ cmd.Flags().StringVar(&opts.outDir, "out-dir", "./edge-mtls", "directory to write generated edge mTLS assets")
+ cmd.Flags().StringVar(&opts.envID, "env-id", "local-edge", "environment identifier to embed in the generated edge agent certificate")
+ cmd.Flags().StringVar(&opts.appURL, "app-url", "http://localhost:3552", "Arcane manager app URL to embed as the edge mTLS SPIFFE trust domain")
+ return cmd
}
-var tlsCmd = &cobra.Command{
- Use: "tls",
- Short: "Generate Arcane HTTPS TLS assets",
- Long: `Generate a self-signed Arcane HTTPS server certificate bundle using ECDSA P-384.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- return generateTLSOutputInternal(cmd.OutOrStdout())
- },
+func newTLSCmd() *cobra.Command {
+ var opts struct {
+ outDir string
+ commonName string
+ hosts []string
+ certName string
+ keyName string
+ }
+ cmd := &cobra.Command{
+ Use: "tls",
+ Short: "Generate Arcane HTTPS TLS assets",
+ Long: `Generate a self-signed Arcane HTTPS server certificate bundle using ECDSA P-384.`,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return generateTLSOutput(cmd, opts.outDir, opts.commonName, opts.hosts, opts.certName, opts.keyName)
+ },
+ }
+ cmd.Flags().StringVar(&opts.outDir, "out-dir", "./arcane-tls", "directory to write generated Arcane TLS assets")
+ cmd.Flags().StringVar(&opts.commonName, "common-name", "localhost", "certificate common name")
+ cmd.Flags().StringSliceVar(&opts.hosts, "host", []string{"localhost", "127.0.0.1"}, "DNS name or IP SAN to include; repeat flag to add more")
+ cmd.Flags().StringVar(&opts.certName, "cert-name", "server.crt", "certificate file name to write under out-dir")
+ cmd.Flags().StringVar(&opts.keyName, "key-name", "server.key", "private key file name to write under out-dir")
+ return cmd
}
-func init() {
- GenerateCmd.AddCommand(mtlsCmd)
- GenerateCmd.AddCommand(tlsCmd)
-
- mtlsCmd.Flags().StringVar(&mtlsOutDir, "out-dir", "./edge-mtls", "directory to write generated edge mTLS assets")
- mtlsCmd.Flags().StringVar(&mtlsEnvID, "env-id", "local-edge", "environment identifier to embed in the generated edge agent certificate")
- mtlsCmd.Flags().StringVar(&mtlsAppURL, "app-url", "http://localhost:3552", "Arcane manager app URL to embed as the edge mTLS SPIFFE trust domain")
-
- tlsCmd.Flags().StringVar(&tlsOutDir, "out-dir", "./arcane-tls", "directory to write generated Arcane TLS assets")
- tlsCmd.Flags().StringVar(&tlsCommonName, "common-name", "localhost", "certificate common name")
- tlsCmd.Flags().StringSliceVar(&tlsHosts, "host", []string{"localhost", "127.0.0.1"}, "DNS name or IP SAN to include; repeat flag to add more")
- tlsCmd.Flags().StringVar(&tlsCertName, "cert-name", "server.crt", "certificate file name to write under out-dir")
- tlsCmd.Flags().StringVar(&tlsKeyName, "key-name", "server.key", "private key file name to write under out-dir")
-}
-
-func generateMTLSOutputInternal(w io.Writer) error {
+func generateMTLSOutput(cmd *cobra.Command, mtlsOutDir, mtlsEnvID, mtlsAppURL string) error {
+ w := cmd.OutOrStdout()
outDir, err := filepath.Abs(strings.TrimSpace(mtlsOutDir))
if err != nil {
return fmt.Errorf("failed to resolve output directory: %w", err)
}
- paths, err := generateEdgeMTLSBundleInternal(outDir, strings.TrimSpace(mtlsEnvID), strings.TrimSpace(mtlsAppURL))
+ paths, err := generateEdgeMTLSBundle(outDir, strings.TrimSpace(mtlsEnvID), strings.TrimSpace(mtlsAppURL))
if err != nil {
return err
}
+ if jsonOutput(cmd) {
+ return printJSON(cmd, paths)
+ }
_, _ = fmt.Fprintln(w, "Generated Arcane edge mTLS assets (ML-DSA-87)")
_, _ = fmt.Fprintf(w, "CA cert: %s\n", paths.CACertPath)
_, _ = fmt.Fprintf(w, "CA key: %s\n", paths.CAKeyPath)
@@ -97,17 +103,21 @@ func generateMTLSOutputInternal(w io.Writer) error {
return nil
}
-func generateTLSOutputInternal(w io.Writer) error {
+func generateTLSOutput(cmd *cobra.Command, tlsOutDir, tlsCommonName string, tlsHosts []string, tlsCertName, tlsKeyName string) error {
+ w := cmd.OutOrStdout()
outDir, err := filepath.Abs(strings.TrimSpace(tlsOutDir))
if err != nil {
return fmt.Errorf("failed to resolve output directory: %w", err)
}
- paths, err := generateServerTLSBundleInternal(outDir, strings.TrimSpace(tlsCommonName), tlsHosts, strings.TrimSpace(tlsCertName), strings.TrimSpace(tlsKeyName))
+ paths, err := generateServerTLSBundle(outDir, strings.TrimSpace(tlsCommonName), tlsHosts, strings.TrimSpace(tlsCertName), strings.TrimSpace(tlsKeyName))
if err != nil {
return err
}
+ if jsonOutput(cmd) {
+ return printJSON(cmd, paths)
+ }
_, _ = fmt.Fprintln(w, "Generated Arcane TLS assets (ECDSA P-384)")
_, _ = fmt.Fprintf(w, "Server cert: %s\n", paths.CertPath)
_, _ = fmt.Fprintf(w, "Server key: %s\n", paths.KeyPath)
@@ -118,18 +128,18 @@ func generateTLSOutputInternal(w io.Writer) error {
}
type edgeMTLSPaths struct {
- CACertPath string
- CAKeyPath string
- ClientCertPath string
- ClientKeyPath string
+ CACertPath string `json:"cACertPath"`
+ CAKeyPath string `json:"cAKeyPath"`
+ ClientCertPath string `json:"clientCertPath"`
+ ClientKeyPath string `json:"clientKeyPath"`
}
type serverTLSPaths struct {
- CertPath string
- KeyPath string
+ CertPath string `json:"certPath"`
+ KeyPath string `json:"keyPath"`
}
-func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPaths, error) {
+func generateEdgeMTLSBundle(outDir, envID, appURL string) (*edgeMTLSPaths, error) {
if envID == "" {
return nil, errors.New("env ID is required")
}
@@ -180,17 +190,17 @@ func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPath
ClientCertPath: filepath.Join(outDir, "agent.crt"),
ClientKeyPath: filepath.Join(outDir, "agent.key"),
}
- if writeCertificateBundleErr := writeCertificateBundleInternal(paths.CACertPath, paths.CAKeyPath, caDER, caKey); writeCertificateBundleErr != nil {
+ if writeCertificateBundleErr := writeCertificateBundle(paths.CACertPath, paths.CAKeyPath, caDER, caKey); writeCertificateBundleErr != nil {
return nil, writeCertificateBundleErr
}
- if writeClientBundleErr := writeCertificateBundleInternal(paths.ClientCertPath, paths.ClientKeyPath, clientDER, clientKey); writeClientBundleErr != nil {
+ if writeClientBundleErr := writeCertificateBundle(paths.ClientCertPath, paths.ClientKeyPath, clientDER, clientKey); writeClientBundleErr != nil {
return nil, writeClientBundleErr
}
return paths, nil
}
-func generateServerTLSBundleInternal(outDir, commonName string, hosts []string, certName, keyName string) (*serverTLSPaths, error) {
+func generateServerTLSBundle(outDir, commonName string, hosts []string, certName, keyName string) (*serverTLSPaths, error) {
if commonName == "" {
return nil, errors.New("common name is required")
}
@@ -225,7 +235,7 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,
CertPath: filepath.Join(outDir, certName),
KeyPath: filepath.Join(outDir, keyName),
}
- if writeCertificateBundleErr := writeCertificateBundleInternal(paths.CertPath, paths.KeyPath, certDER, privateKey); writeCertificateBundleErr != nil {
+ if writeCertificateBundleErr := writeCertificateBundle(paths.CertPath, paths.KeyPath, certDER, privateKey); writeCertificateBundleErr != nil {
return nil, writeCertificateBundleErr
}
return paths, nil
@@ -243,7 +253,7 @@ func GenerateMLDSA87PrivateKey() (*mldsa.PrivateKey, error) {
// NewEdgeMTLSCATemplate builds Arcane's edge mTLS CA certificate template.
func NewEdgeMTLSCATemplate() (*x509.Certificate, error) {
- template, err := newCertificateTemplateInternal("Arcane Edge mTLS CA")
+ template, err := newCertificateTemplate("Arcane Edge mTLS CA")
if err != nil {
return nil, err
}
@@ -261,7 +271,7 @@ func NewEdgeMTLSClientTemplate(commonName string, uriSAN *url.URL, dnsSANs []str
if commonName == "" {
return nil, errors.New("common name is required")
}
- template, err := newCertificateTemplateInternal(commonName)
+ template, err := newCertificateTemplate(commonName)
if err != nil {
return nil, err
}
@@ -275,12 +285,7 @@ func NewEdgeMTLSClientTemplate(commonName string, uriSAN *url.URL, dnsSANs []str
if uriSAN != nil {
template.URIs = []*url.URL{uriSAN}
}
- for _, dnsSAN := range dnsSANs {
- dnsSAN = strings.TrimSpace(dnsSAN)
- if dnsSAN != "" {
- template.DNSNames = append(template.DNSNames, dnsSAN)
- }
- }
+ template.DNSNames = kit.TrimNonEmpty(dnsSANs)
return template, nil
}
@@ -290,7 +295,7 @@ func NewServerTLSTemplate(commonName string, hosts []string) (*x509.Certificate,
if commonName == "" {
return nil, errors.New("common name is required")
}
- template, err := newCertificateTemplateInternal(commonName)
+ template, err := newCertificateTemplate(commonName)
if err != nil {
return nil, err
}
@@ -298,11 +303,7 @@ func NewServerTLSTemplate(commonName string, hosts []string) (*x509.Certificate,
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
template.KeyUsage = x509.KeyUsageDigitalSignature
- for _, host := range hosts {
- host = strings.TrimSpace(host)
- if host == "" {
- continue
- }
+ for _, host := range kit.TrimNonEmpty(hosts) {
if ip := net.ParseIP(host); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
continue
@@ -344,10 +345,11 @@ func BuildEdgeMTLSURISAN(appURL, envID string) *url.URL {
return &url.URL{Scheme: "spiffe", Host: trustDomain, Path: "/edge/" + envID}
}
-func newCertificateTemplateInternal(commonName string) (*x509.Certificate, error) {
- serial, err := randomSerialInternal()
+func newCertificateTemplate(commonName string) (*x509.Certificate, error) {
+ limit := new(big.Int).Lsh(big.NewInt(1), 128)
+ serial, err := rand.Int(rand.Reader, limit)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to generate certificate serial: %w", err)
}
now := time.Now().UTC()
@@ -359,33 +361,21 @@ func newCertificateTemplateInternal(commonName string) (*x509.Certificate, error
}, nil
}
-func randomSerialInternal() (*big.Int, error) {
- limit := new(big.Int).Lsh(big.NewInt(1), 128)
- serial, err := rand.Int(rand.Reader, limit)
- if err != nil {
- return nil, fmt.Errorf("failed to generate certificate serial: %w", err)
- }
- return serial, nil
-}
-
-func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, privateKey crypto.PrivateKey) error {
+func writeCertificateBundle(certPath, keyPath string, certDER []byte, privateKey crypto.PrivateKey) error {
keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return fmt.Errorf("failed to marshal private key: %w", err)
}
- if writePEMFileErr := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); writePEMFileErr != nil {
- return writePEMFileErr
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
+ if certPEM == nil {
+ return fmt.Errorf("failed to encode PEM file %s", certPath)
}
- if writePrivateKeyErr := writePEMFileInternal(keyPath, "PRIVATE KEY", keyDER, 0o600); writePrivateKeyErr != nil {
- return writePrivateKeyErr
+ keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
+ if keyPEM == nil {
+ return fmt.Errorf("failed to encode PEM file %s", keyPath)
}
- return nil
-}
-
-func writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {
- pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})
- if pemBytes == nil {
- return fmt.Errorf("failed to encode PEM file %s", path)
+ if writeErr := atomic.WriteFile(certPath, certPEM, 0o644); writeErr != nil {
+ return writeErr
}
- return atomic.WriteFile(path, pemBytes, perm)
+ return atomic.WriteFile(keyPath, keyPEM, 0o600)
}
diff --git a/cli/pkg/generate/certs_test.go b/cli/pkg/generate/certs_test.go
index 1795e7f33..d4879508e 100644
--- a/cli/pkg/generate/certs_test.go
+++ b/cli/pkg/generate/certs_test.go
@@ -13,13 +13,13 @@ import (
"github.com/stretchr/testify/require"
- gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
)
func TestGenerateMTLSCommandWritesMLDSA87Assets(t *testing.T) {
outDir := t.TempDir()
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"mtls", "--out-dir", outDir, "--env-id", "env-123", "--app-url", "https://manager.example.com"})
_, err := captureOutput(func() error {
@@ -42,7 +42,7 @@ func TestGenerateMTLSCommandWritesMLDSA87Assets(t *testing.T) {
func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
outDir := t.TempDir()
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--host", "127.0.0.1", "--cert-name", "local-manager.crt", "--key-name", "local-manager.key"})
_, err := captureOutput(func() error {
@@ -56,8 +56,8 @@ func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
assertECDSAP384PrivateKey(t, filepath.Join(outDir, "local-manager.key"))
cert := assertECDSAP384Certificate(t, filepath.Join(outDir, "local-manager.crt"))
- require.False(t, len(cert.DNSNames) == 0 || cert.DNSNames[0] != "localhost",
- "expected localhost DNS SAN, got %v", cert.DNSNames)
+ require.Equal(t, []string{"localhost"}, cert.DNSNames,
+ "expected only localhost DNS SAN, got %v", cert.DNSNames)
require.False(t, len(cert.IPAddresses) == 0 || !cert.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")),
"expected 127.0.0.1 IP SAN, got %v", cert.IPAddresses)
@@ -66,7 +66,7 @@ func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
outDir := t.TempDir()
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
_, err := captureOutput(func() error {
_, err := cmd.ExecuteC()
@@ -78,11 +78,13 @@ func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
certPath := filepath.Join(outDir, "server.crt")
keyPath := filepath.Join(outDir, "server.key")
+ require.Equal(t, []string{"localhost"}, assertECDSAP384Certificate(t, certPath).DNSNames)
firstCert, err := os.ReadFile(certPath)
require.NoError(t, err,
"failed to read first cert: %v", err)
+ cmd = generate.Command()
cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
_, err = captureOutput(func() error {
_, executeCErr := cmd.ExecuteC()
@@ -100,7 +102,7 @@ func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
require.NotEqual(t, string(secondCert), string(firstCert),
"expected certificate to be replaced on second generation")
- assertECDSAP384Certificate(t, certPath)
+ require.Equal(t, []string{"localhost"}, assertECDSAP384Certificate(t, certPath).DNSNames)
assertECDSAP384PrivateKey(t, keyPath)
tmpFiles, err := filepath.Glob(filepath.Join(outDir, "*.tmp-*"))
diff --git a/cli/pkg/generate/generate.go b/cli/pkg/generate/generate.go
index cdaf9dfa0..3f3be7746 100644
--- a/cli/pkg/generate/generate.go
+++ b/cli/pkg/generate/generate.go
@@ -1,11 +1,34 @@
package generate
import (
+ "encoding/json/jsontext"
+ "encoding/json/v2"
+ "fmt"
+
"github.com/spf13/cobra"
)
-var GenerateCmd = &cobra.Command{
- Use: "generate",
- Aliases: []string{"gen", "g"},
- Short: "Generate secrets and bootstrap credentials for Arcane",
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "generate",
+ Aliases: []string{"gen", "g"},
+ Short: "Generate secrets and bootstrap credentials for Arcane",
+ }
+ cmd.AddCommand(newAPIKeyCmd(), newMTLSCmd(), newTLSCmd(), newSecretCmd())
+ return cmd
+}
+
+// The backend embeds this package, so it stays off cmdutil to avoid pulling in the CLI's TUI dependencies.
+func jsonOutput(cmd *cobra.Command) bool {
+ jsonFlag, _ := cmd.Flags().GetBool("json")
+ outputMode, _ := cmd.Flags().GetString("output")
+ return jsonFlag || outputMode == "json"
+}
+
+func printJSON(cmd *cobra.Command, v any) error {
+ if err := json.MarshalWrite(cmd.OutOrStdout(), v, jsontext.WithIndent(" ")); err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ _, err := fmt.Fprintln(cmd.OutOrStdout())
+ return err
}
diff --git a/cli/pkg/generate/secret.go b/cli/pkg/generate/secret.go
index 1f88af55b..6a7099c50 100644
--- a/cli/pkg/generate/secret.go
+++ b/cli/pkg/generate/secret.go
@@ -5,98 +5,93 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
- "io"
+ "slices"
+ "strings"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
)
-var (
- secretFormat string
- secretLength int
-)
-
-var secretCmd = &cobra.Command{
- Use: "secret",
- Short: "Generate cryptographic secrets",
- Long: `Generate a secure cryptographic secret for ENCRYPTION_KEY.`,
- RunE: func(cmd *cobra.Command, args []string) error {
- return generateSecretsInternal(cmd.OutOrStdout())
- },
-}
+var secretFormats = []string{"base64", "hex", "env", "docker", "all"}
-func init() {
- GenerateCmd.AddCommand(secretCmd)
- secretCmd.Flags().StringVarP(&secretFormat, "format", "f", "base64", "output format: base64, hex, env, docker, all")
- secretCmd.Flags().IntVarP(&secretLength, "length", "l", 32, "secret length in bytes (default: 32 for AES-256)")
+func newSecretCmd() *cobra.Command {
+ var opts struct {
+ format string
+ length int
+ }
+ cmd := &cobra.Command{
+ Use: "secret",
+ Short: "Generate cryptographic secrets",
+ Long: `Generate a secure cryptographic secret for ENCRYPTION_KEY.`,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return generateSecrets(cmd, opts.format, opts.length)
+ },
+ }
+ cmd.Flags().StringVarP(&opts.format, "format", "f", "base64", "output format: "+strings.Join(secretFormats, ", "))
+ _ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions(secretFormats, cobra.ShellCompDirectiveNoFileComp))
+ cmd.Flags().IntVarP(&opts.length, "length", "l", 32, "secret length in bytes (default: 32 for AES-256)")
+ return cmd
}
-func generateSecretsInternal(w io.Writer) error {
+func generateSecrets(cmd *cobra.Command, secretFormat string, secretLength int) error {
+ if !slices.Contains(secretFormats, secretFormat) {
+ return fmt.Errorf("unknown format: %s (supported: %s)", secretFormat, strings.Join(secretFormats, ", "))
+ }
+ w := cmd.OutOrStdout()
encryptionKey := make([]byte, secretLength)
if _, err := rand.Read(encryptionKey); err != nil {
return fmt.Errorf("failed to generate encryption key: %w", err)
}
+ if jsonOutput(cmd) {
+ return printJSON(cmd, struct {
+ EncryptionKey string `json:"encryptionKey"`
+ Hex string `json:"hex,omitempty"`
+ }{
+ EncryptionKey: kit.Ternary(secretFormat == "hex", hex.EncodeToString(encryptionKey), base64.StdEncoding.EncodeToString(encryptionKey)),
+ Hex: kit.Ternary(secretFormat == "all", hex.EncodeToString(encryptionKey), ""),
+ })
+ }
switch secretFormat {
case "base64":
- printBase64FormatInternal(w, encryptionKey)
+ _, _ = fmt.Fprintln(w, "BASE64")
+ _, _ = fmt.Fprintln(w, "------")
+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encryptionKey))
case "hex":
- printHexFormatInternal(w, encryptionKey)
+ _, _ = fmt.Fprintln(w, "HEX")
+ _, _ = fmt.Fprintln(w, "---")
+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encryptionKey))
case "env":
- printEnvFormatInternal(w, encryptionKey)
+ _, _ = fmt.Fprintln(w, "ENV (.env) FORMAT")
+ _, _ = fmt.Fprintln(w, "-------------------")
+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encryptionKey))
case "docker":
- printDockerFormatInternal(w, encryptionKey)
+ _, _ = fmt.Fprintln(w, "DOCKER COMPOSE ENVIRONMENT")
+ _, _ = fmt.Fprintln(w, "--------------------------")
+ _, _ = fmt.Fprintln(w, "environment:")
+ _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encryptionKey))
case "all":
- printAllFormatsInternal(w, encryptionKey)
- default:
- return fmt.Errorf("unknown format: %s (supported: base64, hex, env, docker, all)", secretFormat)
+ _, _ = fmt.Fprintln(w, "Arcane cryptographic secrets")
+ _, _ = fmt.Fprintln(w, "===========================")
+ _, _ = fmt.Fprintln(w)
+
+ _, _ = fmt.Fprintln(w, "ENV (.env) - recommended")
+ _, _ = fmt.Fprintln(w, "------------------------")
+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encryptionKey))
+ _, _ = fmt.Fprintln(w)
+
+ _, _ = fmt.Fprintln(w, "Docker Compose (environment block)")
+ _, _ = fmt.Fprintln(w, "-------------------------------")
+ _, _ = fmt.Fprintln(w, "environment:")
+ _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encryptionKey))
+ _, _ = fmt.Fprintln(w)
+
+ _, _ = fmt.Fprintln(w, "HEX")
+ _, _ = fmt.Fprintln(w, "---")
+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encryptionKey))
+ _, _ = fmt.Fprintln(w)
}
return nil
}
-
-func printBase64FormatInternal(w io.Writer, encKey []byte) {
- _, _ = fmt.Fprintln(w, "BASE64")
- _, _ = fmt.Fprintln(w, "------")
- _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))
-}
-
-func printHexFormatInternal(w io.Writer, encKey []byte) {
- _, _ = fmt.Fprintln(w, "HEX")
- _, _ = fmt.Fprintln(w, "---")
- _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))
-}
-
-func printEnvFormatInternal(w io.Writer, encKey []byte) {
- _, _ = fmt.Fprintln(w, "ENV (.env) FORMAT")
- _, _ = fmt.Fprintln(w, "-------------------")
- _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))
-}
-
-func printDockerFormatInternal(w io.Writer, encKey []byte) {
- _, _ = fmt.Fprintln(w, "DOCKER COMPOSE ENVIRONMENT")
- _, _ = fmt.Fprintln(w, "--------------------------")
- _, _ = fmt.Fprintln(w, "environment:")
- _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))
-}
-
-func printAllFormatsInternal(w io.Writer, encKey []byte) {
- _, _ = fmt.Fprintln(w, "Arcane cryptographic secrets")
- _, _ = fmt.Fprintln(w, "===========================")
- _, _ = fmt.Fprintln(w)
-
- _, _ = fmt.Fprintln(w, "ENV (.env) - recommended")
- _, _ = fmt.Fprintln(w, "------------------------")
- _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))
- _, _ = fmt.Fprintln(w)
-
- _, _ = fmt.Fprintln(w, "Docker Compose (environment block)")
- _, _ = fmt.Fprintln(w, "-------------------------------")
- _, _ = fmt.Fprintln(w, "environment:")
- _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))
- _, _ = fmt.Fprintln(w)
-
- _, _ = fmt.Fprintln(w, "HEX")
- _, _ = fmt.Fprintln(w, "---")
- _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))
- _, _ = fmt.Fprintln(w)
-}
diff --git a/cli/pkg/generate/secret_test.go b/cli/pkg/generate/secret_test.go
index a5ba7d41a..a0d34e75b 100644
--- a/cli/pkg/generate/secret_test.go
+++ b/cli/pkg/generate/secret_test.go
@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require"
- gen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
)
// captureOutput captures stdout produced by fn and returns it as a string.
@@ -39,7 +39,7 @@ func captureOutput(fn func() error) (string, error) {
}
func TestSecretDefaultBase64(t *testing.T) {
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"secret"})
out, err := captureOutput(func() error {
@@ -80,7 +80,7 @@ func TestSecretDefaultBase64(t *testing.T) {
}
func TestSecretAllFormatContainsSections(t *testing.T) {
- cmd := gen.GenerateCmd
+ cmd := generate.Command()
cmd.SetArgs([]string{"secret", "-f", "all"})
out, err := captureOutput(func() error {
diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.go
index 2a05999a6..b74fbd3b5 100644
--- a/cli/pkg/gitops/cmd.go
+++ b/cli/pkg/gitops/cmd.go
@@ -1,529 +1,473 @@
package gitops
import (
+ "cmp"
"fmt"
+ "net/http"
"net/url"
+ "strconv"
"strings"
"github.com/getarcaneapp/arcane/types/v2/gitops"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- gitopsFilesPath string
-)
-
-var (
- gitopsUpdateName string
- gitopsUpdateRepoID string
- gitopsUpdateBranch string
- gitopsUpdateComposePath string
- gitopsUpdateProjectName string
- gitopsImportProjectName string
- gitopsUpdateAutoSync bool
- gitopsUpdateInterval int
-)
-
-// GitopsCmd is the parent command for gitops sync operations
-var GitopsCmd = &cobra.Command{
- Use: "gitops",
- Aliases: []string{"gitops-syncs", "gs"},
- Short: "Manage GitOps syncs",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List GitOps syncs",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitOpsSync]{
- Resource: "gitops syncs",
- Endpoint: types.GitOpsSyncs(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "gitops-syncs", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "BRANCH", "AUTO-SYNC", "LAST STATUS", "LAST SYNC"},
- Row: func(sync gitops.GitOpsSync) []string {
- autoSync := "false"
- if sync.AutoSync {
- autoSync = "true"
- }
- lastStatus := "-"
- if sync.LastSyncStatus != nil {
- lastStatus = *sync.LastSyncStatus
- }
- lastSync := "-"
- if sync.LastSyncAt != nil {
- lastSync = sync.LastSyncAt.Format("2006-01-02 15:04:05")
- }
- return []string{
- sync.ID,
- sync.Name,
- sync.Branch,
- autoSync,
- lastStatus,
- lastSync,
- }
- },
- })
- },
+// Command is the parent command for gitops sync operations
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "gitops",
+ Aliases: []string{"gitops-syncs", "gs"},
+ Short: "Manage GitOps syncs",
+ }
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newCreateCmd())
+ cmd.AddCommand(newGetCmd())
+ cmd.AddCommand(newUpdateCmd())
+ cmd.AddCommand(newDeleteCmd())
+ cmd.AddCommand(newStatusCmd())
+ cmd.AddCommand(newSyncCmd())
+ cmd.AddCommand(newFilesCmd())
+ cmd.AddCommand(newImportCmd())
+ return cmd
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new GitOps sync",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- name, _ := cmd.Flags().GetString("name")
- repoID, _ := cmd.Flags().GetString("repo-id")
- branch, _ := cmd.Flags().GetString("branch")
- composePath, _ := cmd.Flags().GetString("compose-path")
- autoSync, _ := cmd.Flags().GetBool("auto-sync")
- interval, _ := cmd.Flags().GetInt("interval")
- projectName, _ := cmd.Flags().GetString("project-name")
-
- req := gitops.CreateSyncRequest{
- Name: name,
- RepositoryID: repoID,
- Branch: branch,
- ComposePath: composePath,
- ProjectName: projectName,
- AutoSync: &autoSync,
- }
- if cmd.Flags().Changed("interval") {
- req.SyncInterval = &interval
- }
-
- result, err := c.PostJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSyncs(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to create gitops sync: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List GitOps syncs",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("GitOps sync %s created successfully (ID: %s)", result.Data.Name, result.Data.ID)
- return nil
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitOpsSync]{
+ Resource: "gitops syncs",
+ Endpoint: types.GitOpsSyncs(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "gitops-syncs", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "BRANCH", "AUTO-SYNC", "LAST STATUS", "LAST SYNC"},
+ Row: func(sync gitops.GitOpsSync) []string {
+ return []string{
+ sync.ID,
+ sync.Name,
+ sync.Branch,
+ strconv.FormatBool(sync.AutoSync),
+ cmp.Or(kit.FromPtr(sync.LastSyncStatus), "-"),
+ kit.Ternary(sync.LastSyncAt != nil, kit.FromPtr(sync.LastSyncAt).Format("2006-01-02 15:04:05"), "-"),
+ }
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of syncs to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get <sync-id|name>",
- Short: "Get GitOps sync details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- if !complete {
- result, getSyncErr := c.GetJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
- if getSyncErr != nil {
- return fmt.Errorf("failed to get gitops sync: %w", getSyncErr)
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ repoID string
+ branch string
+ composePath string
+ projectName string
+ autoSync bool
+ interval int
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a new GitOps sync",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- resolved = &result.Data
- }
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
+ req := gitops.CreateSyncRequest{
+ Name: opts.name,
+ RepositoryID: opts.repoID,
+ Branch: opts.branch,
+ ComposePath: opts.composePath,
+ ProjectName: opts.projectName,
+ AutoSync: &opts.autoSync,
+ SyncInterval: kit.Ternary(cmd.Flags().Changed("interval"), &opts.interval, nil),
+ }
- output.Header("GitOps Sync Details")
- output.KeyValue("ID", resolved.ID)
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("Branch", resolved.Branch)
- output.KeyValue("Compose Path", resolved.ComposePath)
- output.KeyValue("Project Name", resolved.ProjectName)
- output.KeyValue("Auto Sync", resolved.AutoSync)
- output.KeyValue("Sync Interval", fmt.Sprintf("%d min", resolved.SyncInterval))
- if resolved.LastSyncStatus != nil {
- output.KeyValue("Last Status", *resolved.LastSyncStatus)
- }
- if resolved.LastSyncAt != nil {
- output.KeyValue("Last Sync", resolved.LastSyncAt.Format("2006-01-02 15:04:05"))
- }
- if resolved.LastSyncCommit != nil {
- output.KeyValue("Last Commit", *resolved.LastSyncCommit)
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.GitOpsSync]{
+ Method: http.MethodPost,
+ Path: types.GitOpsSyncs(c.EnvID()),
+ Body: req,
+ FailureMessage: "failed to create gitops sync",
+ Render: func(data gitops.GitOpsSync) error {
+ output.Success("GitOps sync %s created successfully (ID: %s)", data.Name, data.ID)
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ cmd.Flags().StringVar(&opts.name, "name", "", "Name of the sync configuration")
+ cmd.Flags().StringVar(&opts.repoID, "repo-id", "", "Repository ID")
+ cmd.Flags().StringVar(&opts.branch, "branch", "", "Branch to sync from")
+ cmd.Flags().StringVar(&opts.composePath, "compose-path", "", "Path to docker-compose file")
+ cmd.Flags().BoolVar(&opts.autoSync, "auto-sync", false, "Enable automatic sync")
+ cmd.Flags().IntVar(&opts.interval, "interval", 0, "Sync interval in minutes")
+ cmd.Flags().StringVar(&opts.projectName, "project-name", "", "Project name for the sync")
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("repo-id")
+ _ = cmd.MarkFlagRequired("branch")
+ _ = cmd.MarkFlagRequired("compose-path")
+ return cmd
}
-var updateCmd = &cobra.Command{
- Use: "update <sync-id|name>",
- Short: "Update a GitOps sync",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- req := gitops.UpdateSyncRequest{}
- if cmd.Flags().Changed("name") {
- req.Name = &gitopsUpdateName
- }
- if cmd.Flags().Changed("repo-id") {
- req.RepositoryID = &gitopsUpdateRepoID
- }
- if cmd.Flags().Changed("branch") {
- req.Branch = &gitopsUpdateBranch
- }
- if cmd.Flags().Changed("compose-path") {
- req.ComposePath = &gitopsUpdateComposePath
- }
- if cmd.Flags().Changed("project-name") {
- req.ProjectName = &gitopsUpdateProjectName
- }
- if cmd.Flags().Changed("auto-sync") {
- req.AutoSync = &gitopsUpdateAutoSync
- }
- if cmd.Flags().Changed("interval") {
- req.SyncInterval = &gitopsUpdateInterval
- }
-
- resp, err := c.Put(cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID), req)
- if err != nil {
- return fmt.Errorf("failed to update gitops sync: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to update gitops sync: %w", ensureSuccessStatusErr)
- }
-
- output.Success("GitOps sync %s updated successfully", resolved.Name)
- return nil
- },
-}
+func newGetCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "get <sync-id|name>",
+ Short: "Get GitOps sync details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var deleteCmd = &cobra.Command{
- Use: "delete <sync-id|name>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a GitOps sync",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ resolved, err := gitopsSyncRef.Fetch(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
- resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
- if !forceFlag {
- display := resolved.Name
- if display == "" {
- display = resolved.ID
+ output.Header("GitOps Sync Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Branch", resolved.Branch)
+ output.KeyValue("Compose Path", resolved.ComposePath)
+ output.KeyValue("Project Name", resolved.ProjectName)
+ output.KeyValue("Auto Sync", resolved.AutoSync)
+ output.KeyValue("Sync Interval", fmt.Sprintf("%d min", resolved.SyncInterval))
+ if resolved.LastSyncStatus != nil {
+ output.KeyValue("Last Status", *resolved.LastSyncStatus)
}
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete gitops sync %s?", display))
- if confirmErr != nil {
- return confirmErr
+ if resolved.LastSyncAt != nil {
+ output.KeyValue("Last Sync", resolved.LastSyncAt.Format("2006-01-02 15:04:05"))
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+ if resolved.LastSyncCommit != nil {
+ output.KeyValue("Last Commit", *resolved.LastSyncCommit)
}
- }
-
- resp, err := c.Delete(cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to delete gitops sync: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete gitops sync: %w", ensureSuccessStatusErr)
- }
-
- output.Success("GitOps sync %s deleted successfully", resolved.Name)
- return nil
- },
+ return nil
+ },
+ }
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
}
-var statusCmd = &cobra.Command{
- Use: "status <sync-id|name>",
- Short: "Get GitOps sync status",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ repoID string
+ branch string
+ composePath string
+ projectName string
+ autoSync bool
+ interval int
+ }
+ cmd := &cobra.Command{
+ Use: "update <sync-id|name>",
+ Short: "Update a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.GetJSON[gitops.SyncStatus](cmd.Context(), types.GitOpsSyncStatus(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get gitops sync status: %w", err)
- }
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ req := gitops.UpdateSyncRequest{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ RepositoryID: kit.Ternary(cmd.Flags().Changed("repo-id"), &opts.repoID, nil),
+ Branch: kit.Ternary(cmd.Flags().Changed("branch"), &opts.branch, nil),
+ ComposePath: kit.Ternary(cmd.Flags().Changed("compose-path"), &opts.composePath, nil),
+ ProjectName: kit.Ternary(cmd.Flags().Changed("project-name"), &opts.projectName, nil),
+ AutoSync: kit.Ternary(cmd.Flags().Changed("auto-sync"), &opts.autoSync, nil),
+ SyncInterval: kit.Ternary(cmd.Flags().Changed("interval"), &opts.interval, nil),
+ }
- output.Header("GitOps Sync Status")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Auto Sync", result.Data.AutoSync)
- if result.Data.NextSyncAt != nil {
- output.KeyValue("Next Sync", result.Data.NextSyncAt.Format("2006-01-02 15:04:05"))
- }
- if result.Data.LastSyncAt != nil {
- output.KeyValue("Last Sync", result.Data.LastSyncAt.Format("2006-01-02 15:04:05"))
- }
- if result.Data.LastSyncStatus != nil {
- output.KeyValue("Last Status", *result.Data.LastSyncStatus)
- }
- if result.Data.LastSyncError != nil {
- output.KeyValue("Last Error", *result.Data.LastSyncError)
- }
- if result.Data.LastSyncCommit != nil {
- output.KeyValue("Last Commit", *result.Data.LastSyncCommit)
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.GitOpsSync]{
+ Method: http.MethodPut,
+ Path: types.GitOpsSync(c.EnvID(), resolved.ID),
+ Body: req,
+ FailureMessage: "failed to update gitops sync",
+ Render: func(gitops.GitOpsSync) error {
+ output.Success("GitOps sync %s updated successfully", resolved.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Name of the sync configuration")
+ cmd.Flags().StringVar(&opts.repoID, "repo-id", "", "Repository ID")
+ cmd.Flags().StringVar(&opts.branch, "branch", "", "Branch to sync from")
+ cmd.Flags().StringVar(&opts.composePath, "compose-path", "", "Path to docker-compose file")
+ cmd.Flags().StringVar(&opts.projectName, "project-name", "", "Project name for the sync")
+ cmd.Flags().BoolVar(&opts.autoSync, "auto-sync", false, "Enable automatic sync")
+ cmd.Flags().IntVar(&opts.interval, "interval", 0, "Sync interval in minutes")
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
}
-var syncCmd = &cobra.Command{
- Use: "sync <sync-id|name>",
- Short: "Trigger a GitOps sync",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <sync-id|name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- result, err := c.PostJSON[gitops.SyncResult](cmd.Context(), types.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)
- if err != nil {
- return fmt.Errorf("failed to trigger gitops sync: %w", err)
- }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete gitops sync %s?", cmp.Or(resolved.Name, resolved.ID)),
+ Path: types.GitOpsSync(c.EnvID(), resolved.ID),
+ Body: nil,
+ FailureMessage: "failed to delete gitops sync",
+ SuccessMessage: fmt.Sprintf("GitOps sync %s deleted successfully", resolved.Name),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force delete without confirmation")
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
+}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newStatusCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "status <sync-id|name>",
+ Short: "Get GitOps sync status",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if result.Data.Success {
- output.Success("Sync triggered successfully: %s", result.Data.Message)
- return nil
- }
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- errMsg := ""
- if result.Data.Error != nil {
- errMsg = *result.Data.Error
- }
- return fmt.Errorf("sync failed: %s %s", result.Data.Message, errMsg)
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.SyncStatus]{
+ Method: http.MethodGet,
+ Path: types.GitOpsSyncStatus(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to get gitops sync status",
+ Render: func(data gitops.SyncStatus) error {
+ output.Header("GitOps Sync Status")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Auto Sync", data.AutoSync)
+ if data.NextSyncAt != nil {
+ output.KeyValue("Next Sync", data.NextSyncAt.Format("2006-01-02 15:04:05"))
+ }
+ if data.LastSyncAt != nil {
+ output.KeyValue("Last Sync", data.LastSyncAt.Format("2006-01-02 15:04:05"))
+ }
+ if data.LastSyncStatus != nil {
+ output.KeyValue("Last Status", *data.LastSyncStatus)
+ }
+ if data.LastSyncError != nil {
+ output.KeyValue("Last Error", *data.LastSyncError)
+ }
+ if data.LastSyncCommit != nil {
+ output.KeyValue("Last Commit", *data.LastSyncCommit)
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
}
-var filesCmd = &cobra.Command{
- Use: "files <sync-id|name>",
- Short: "List files from GitOps sync repository",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newSyncCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "sync <sync-id|name>",
+ Short: "Trigger a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- filesPath := types.GitOpsSyncFiles(c.EnvID(), resolved.ID)
- if gitopsFilesPath != "" {
- filesPath = cmdutil.AppendQuery(filesPath, url.Values{"path": []string{gitopsFilesPath}})
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.SyncResult]{
+ Method: http.MethodPost,
+ Path: types.GitOpsSyncTrigger(c.EnvID(), resolved.ID),
+ Body: nil,
+ FailureMessage: "failed to trigger gitops sync",
+ Render: func(data gitops.SyncResult) error {
+ if data.Success {
+ output.Success("Sync triggered successfully: %s", data.Message)
+ return nil
+ }
+ return fmt.Errorf("sync failed: %s %s", data.Message, kit.FromPtr(data.Error))
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
+}
- result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), filesPath)
- if err != nil {
- return fmt.Errorf("failed to get gitops sync files: %w", err)
- }
+func newFilesCmd() *cobra.Command {
+ var opts struct {
+ path string
+ }
+ cmd := &cobra.Command{
+ Use: "files <sync-id|name>",
+ Short: "List files from GitOps sync repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- files := result.Data.Files
- if jsonOutput {
- return cmdutil.PrintJSON(files)
- }
+ resolved, _, err := gitopsSyncRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
- rows := flattenFileTree(files, 0)
+ filesPath := types.GitOpsSyncFiles(c.EnvID(), resolved.ID)
+ if opts.path != "" {
+ filesPath = cmdutil.AppendQuery(filesPath, url.Values{"path": []string{opts.path}})
+ }
- return output.Table(headers, rows)
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.BrowseResponse]{
+ Method: http.MethodGet,
+ Path: filesPath,
+ FailureMessage: "failed to get gitops sync files",
+ Render: func(data gitops.BrowseResponse) error {
+ headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
+ return output.Table(headers, flattenFileTree(data.Files, 0))
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.path, "path", "", "Path within the repository to browse")
+ cmdutil.SetResource(gitopsSyncRef, cmd)
+ return cmd
}
-var importCmd = &cobra.Command{
- Use: "import",
- Short: "Import a GitOps sync configuration",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- name, _ := cmd.Flags().GetString("name")
- repo, _ := cmd.Flags().GetString("repo-url")
- branch, _ := cmd.Flags().GetString("branch")
- composePath, _ := cmd.Flags().GetString("compose-path")
- autoSync, _ := cmd.Flags().GetBool("auto-sync")
- interval, _ := cmd.Flags().GetInt("interval")
-
- req := gitops.ImportGitOpsSyncRequest{
- SyncName: name,
- GitRepo: repo,
- Branch: branch,
- DockerComposePath: composePath,
- AutoSync: autoSync,
- SyncInterval: interval,
- ProjectName: gitopsImportProjectName,
- }
-
- // The endpoint accepts a batch, so a single sync still has to be wrapped
- // in an array.
- result, err := c.PostJSON[gitops.ImportGitOpsSyncResponse](cmd.Context(), types.GitOpsSyncsImport(c.EnvID()), []gitops.ImportGitOpsSyncRequest{req})
- if err != nil {
- return fmt.Errorf("failed to import gitops sync: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newImportCmd() *cobra.Command {
+ var opts struct {
+ name string
+ repoURL string
+ branch string
+ composePath string
+ autoSync bool
+ interval int
+ projectName string
+ }
+ cmd := &cobra.Command{
+ Use: "import",
+ Short: "Import a GitOps sync configuration",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Import completed: %d succeeded, %d failed", result.Data.SuccessCount, result.Data.FailedCount)
- if len(result.Data.Errors) > 0 {
- output.Warning("Errors:")
- for _, e := range result.Data.Errors {
- _, _ = fmt.Fprintf(output.Stdout(), " - %s\n", e)
+ req := gitops.ImportGitOpsSyncRequest{
+ SyncName: opts.name,
+ GitRepo: opts.repoURL,
+ Branch: opts.branch,
+ DockerComposePath: opts.composePath,
+ AutoSync: opts.autoSync,
+ SyncInterval: opts.interval,
+ ProjectName: opts.projectName,
}
- }
- return nil
- },
-}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, GitopsCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, createCmd, importCmd)
- GitopsCmd.AddCommand(listCmd)
- GitopsCmd.AddCommand(createCmd)
- GitopsCmd.AddCommand(getCmd)
- GitopsCmd.AddCommand(updateCmd)
- GitopsCmd.AddCommand(deleteCmd)
- GitopsCmd.AddCommand(statusCmd)
- GitopsCmd.AddCommand(syncCmd)
- GitopsCmd.AddCommand(filesCmd)
- GitopsCmd.AddCommand(importCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of syncs to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().String("name", "", "Name of the sync configuration")
- createCmd.Flags().String("repo-id", "", "Repository ID")
- createCmd.Flags().String("branch", "", "Branch to sync from")
- createCmd.Flags().String("compose-path", "", "Path to docker-compose file")
- createCmd.Flags().Bool("auto-sync", false, "Enable automatic sync")
- createCmd.Flags().Int("interval", 0, "Sync interval in minutes")
- createCmd.Flags().String("project-name", "", "Project name for the sync")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("repo-id")
- _ = createCmd.MarkFlagRequired("branch")
- _ = createCmd.MarkFlagRequired("compose-path")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Update command flags
- updateCmd.Flags().StringVar(&gitopsUpdateName, "name", "", "Name of the sync configuration")
- updateCmd.Flags().StringVar(&gitopsUpdateRepoID, "repo-id", "", "Repository ID")
- updateCmd.Flags().StringVar(&gitopsUpdateBranch, "branch", "", "Branch to sync from")
- updateCmd.Flags().StringVar(&gitopsUpdateComposePath, "compose-path", "", "Path to docker-compose file")
- updateCmd.Flags().StringVar(&gitopsUpdateProjectName, "project-name", "", "Project name for the sync")
- updateCmd.Flags().BoolVar(&gitopsUpdateAutoSync, "auto-sync", false, "Enable automatic sync")
- updateCmd.Flags().IntVar(&gitopsUpdateInterval, "interval", 0, "Sync interval in minutes")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force delete without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Status command flags
- statusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Sync command flags
- syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Files command flags
- filesCmd.Flags().StringVar(&gitopsFilesPath, "path", "", "Path within the repository to browse")
- filesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Import command flags
- importCmd.Flags().String("name", "", "Name of the sync configuration")
- importCmd.Flags().String("repo-url", "", "Git repository URL")
- importCmd.Flags().String("branch", "", "Branch to sync from")
- importCmd.Flags().String("compose-path", "", "Path to docker-compose file")
- importCmd.Flags().Bool("auto-sync", false, "Enable automatic sync")
- importCmd.Flags().Int("interval", 5, "Sync interval in minutes")
- importCmd.Flags().StringVar(&gitopsImportProjectName, "project-name", "", "Project name for the sync")
- importCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = importCmd.MarkFlagRequired("name")
- _ = importCmd.MarkFlagRequired("repo-url")
- _ = importCmd.MarkFlagRequired("branch")
- _ = importCmd.MarkFlagRequired("compose-path")
+ // The endpoint accepts a batch, so a single sync still has to be wrapped
+ // in an array.
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.ImportGitOpsSyncResponse]{
+ Method: http.MethodPost,
+ Path: types.GitOpsSyncsImport(c.EnvID()),
+ Body: []gitops.ImportGitOpsSyncRequest{req},
+ FailureMessage: "failed to import gitops sync",
+ Render: func(data gitops.ImportGitOpsSyncResponse) error {
+ output.Success("Import completed: %d succeeded, %d failed", data.SuccessCount, data.FailedCount)
+ if len(data.Errors) > 0 {
+ output.Warning("Errors:")
+ for _, e := range data.Errors {
+ _, _ = fmt.Fprintf(output.Stdout(), " - %s\n", e)
+ }
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ cmd.Flags().StringVar(&opts.name, "name", "", "Name of the sync configuration")
+ cmd.Flags().StringVar(&opts.repoURL, "repo-url", "", "Git repository URL")
+ cmd.Flags().StringVar(&opts.branch, "branch", "", "Branch to sync from")
+ cmd.Flags().StringVar(&opts.composePath, "compose-path", "", "Path to docker-compose file")
+ cmd.Flags().BoolVar(&opts.autoSync, "auto-sync", false, "Enable automatic sync")
+ cmd.Flags().IntVar(&opts.interval, "interval", 5, "Sync interval in minutes")
+ cmd.Flags().StringVar(&opts.projectName, "project-name", "", "Project name for the sync")
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("repo-url")
+ _ = cmd.MarkFlagRequired("branch")
+ _ = cmd.MarkFlagRequired("compose-path")
+ return cmd
}
var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
@@ -533,26 +477,14 @@ var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
IDHint: "the sync ID",
ListCmd: "arcane gitops list",
GetPath: types.GitOpsSync,
+ IdentifierOf: func(item gitops.GitOpsSync) string { return item.ID },
ListPath: types.GitOpsSyncs,
Matches: func(item gitops.GitOpsSync, identifierLower, original string) bool {
- idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
- if strings.Contains(idLower, identifierLower) {
- return true
- }
- if strings.Contains(strings.ToLower(item.Name), identifierLower) {
- return true
- }
- return strings.EqualFold(item.Name, original)
+ return strings.Contains(strings.ToLower(item.ID), identifierLower) ||
+ strings.Contains(strings.ToLower(item.Name), identifierLower) || strings.EqualFold(item.Name, original)
},
Label: func(match gitops.GitOpsSync) string {
- lastStatus := "-"
- if match.LastSyncStatus != nil {
- lastStatus = *match.LastSyncStatus
- }
- return fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, lastStatus)
+ return fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, cmp.Or(kit.FromPtr(match.LastSyncStatus), "-"))
},
Promote: func(match gitops.GitOpsSync) *gitops.GitOpsSync { return &match },
}
@@ -560,16 +492,11 @@ var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
func flattenFileTree(nodes []gitops.FileTreeNode, depth int) [][]string {
var rows [][]string
for _, node := range nodes {
- prefix := strings.Repeat(" ", depth)
- size := "-"
- if node.Type == gitops.FileTreeNodeTypeFile {
- size = output.Bytes(node.Size)
- }
rows = append(rows, []string{
- prefix + node.Name,
+ strings.Repeat(" ", depth) + node.Name,
string(node.Type),
node.Path,
- size,
+ kit.Ternary(node.Type == gitops.FileTreeNodeTypeFile, output.Bytes(node.Size), "-"),
})
if len(node.Children) > 0 {
rows = append(rows, flattenFileTree(node.Children, depth+1)...)
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index 909bdbeb9..9cbefd73c 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -7,592 +7,411 @@ import (
"errors"
"fmt"
"io"
+ "maps"
"net/http"
"net/url"
- "sort"
+ "slices"
"strings"
"time"
+ "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/image"
- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+ "github.com/getarcaneapp/arcane/types/v2/upload"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/logger"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/cli/v2/pkg/images/updates"
)
-var (
- imagesLimit int
- imagesStart int
- imagesSort string
- imagesOrder string
- imagesSearch string
- imagesInUseOnly bool
- imagesUnusedOnly bool
- imagesAll bool
-
- imagesUpdatesFilter string
-)
-
-// ImagesCmd is the parent command for image operations
-var ImagesCmd = &cobra.Command{
- Use: "images",
- Aliases: []string{"image", "i"},
- Short: "Manage images",
-}
-
-var imagesListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List images",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- if imagesInUseOnly && imagesUnusedOnly {
- return errors.New("--inuse and --unused cannot be used together")
- }
-
- query := url.Values{}
- if imagesSort != "" {
- query.Set("sort", imagesSort)
- }
- if imagesOrder != "" {
- query.Set("order", imagesOrder)
- }
- if imagesSearch != "" {
- query.Set("search", imagesSearch)
- }
- // Filter server-side so that pagination and the reported totals apply to
- // the matching set rather than to whichever page happened to be fetched.
- if imagesInUseOnly {
- query.Set("inUse", "true")
- }
- if imagesUnusedOnly {
- query.Set("inUse", "false")
- }
- if imagesUpdatesFilter != "" {
- query.Set("updates", imagesUpdatesFilter)
+// Command builds the images command tree.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeResource},
+ Use: "images",
+ Aliases: []string{"image", "i"},
+ Short: "Manage images",
+ }
+ updateCommand := updates.Command()
+ for _, child := range updateCommand.Commands() {
+ if child.Name() == "check-image" {
+ cmdutil.SetResource(ImageRef, child)
}
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.Summary]{
- Resource: "images",
- Endpoint: types.Images(c.EnvID()),
- Params: cmdutil.ListParams{
- Resource: "images",
- Limit: imagesLimit,
- FallbackDefault: 0,
- Start: imagesStart,
- All: imagesAll,
- },
- Query: query,
- JSON: cmdutil.JSONOutputEnabled(cmd),
- Headers: []string{"ID", "REPOSITORY:TAG", "SIZE", "IN USE"},
- Row: func(img image.Summary) []string {
- tag := "<none>"
- if len(img.RepoTags) > 0 {
- tag = img.RepoTags[0]
- }
- inUse := "No"
- if img.InUse {
- inUse = "Yes"
- }
- return []string{img.ID, tag, output.Bytes(img.Size), inUse}
- },
- })
- },
+ }
+ command.AddCommand(
+ newListCmd(), newGetCmd(), newRemoveCmd(), newPullCmd(), newPruneCmd(),
+ newCountsCmd(), newUploadCmd(), newSearchCmd(), newHistoryCmd(), newTagCmd(),
+ newExportCmd(), newAttestationsCmd(), newBuildCmd(), newBuildsCmd(), updateCommand,
+ )
+ return command
}
-var imagesGetCmd = &cobra.Command{
- Use: "get <image-id|name>",
- Short: "Get image details by ID or name",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- allowPrompt := !jsonOutput && prompt.IsInteractive()
-
- resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
- path := types.Image(c.EnvID(), resolved.ID)
-
- log.Debugf("Getting image details from: %s", path)
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return fmt.Errorf("failed to read response: %w", err)
- }
-
- log.Debugf("Response body: %s", string(body))
-
- if jsonOutput {
- _, _ = fmt.Fprintln(output.Stdout(), string(body))
- return nil
- }
-
- var result struct {
- Success bool `json:"success"`
- Data image.DetailSummary `json:"data"`
- }
-
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
-
- output.Header("Image Details")
- output.KeyValue("ID", result.Data.ID)
- if len(result.Data.RepoTags) > 0 {
- output.KeyValue("Tags", strings.Join(result.Data.RepoTags, ", "))
- }
- output.KeyValue("Size", output.Bytes(result.Data.Size))
- output.KeyValue("Architecture", result.Data.Architecture)
- output.KeyValue("OS", result.Data.Os)
- if result.Data.Created != "" {
- output.KeyValue("Created", result.Data.Created)
- }
- if result.Data.Author != "" {
- output.KeyValue("Author", result.Data.Author)
- }
-
- if result.Data.Config.WorkingDir != "" {
- output.KeyValue("Working Dir", result.Data.Config.WorkingDir)
- }
-
- if len(result.Data.Config.Cmd) > 0 {
- output.KeyValue("Cmd", strings.Join(result.Data.Config.Cmd, " "))
- }
-
- if len(result.Data.Config.Env) > 0 {
- output.Header("Environment Variables")
- for _, env := range result.Data.Config.Env {
- _, _ = fmt.Fprintln(output.Stdout(), env)
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ sort string
+ order string
+ search string
+ inUseOnly bool
+ unusedOnly bool
+ all bool
+ updatesFilter string
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List images",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- if len(result.Data.Config.ExposedPorts) > 0 {
- output.Header("Exposed Ports")
- var ports []string
- for p := range result.Data.Config.ExposedPorts {
- ports = append(ports, p)
+ query := url.Values{}
+ if opts.sort != "" {
+ query.Set("sort", opts.sort)
}
- sort.Strings(ports)
- for _, p := range ports {
- _, _ = fmt.Fprintln(output.Stdout(), p)
+ if opts.order != "" {
+ query.Set("order", opts.order)
+ }
+ if opts.search != "" {
+ query.Set("search", opts.search)
+ }
+ // Filter server-side so that pagination and the reported totals apply to
+ // the matching set rather than to whichever page happened to be fetched.
+ if opts.inUseOnly {
+ query.Set("inUse", "true")
+ }
+ if opts.unusedOnly {
+ query.Set("inUse", "false")
+ }
+ if opts.updatesFilter != "" {
+ query.Set("updates", opts.updatesFilter)
}
- }
- return nil
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.Summary]{
+ Resource: "images",
+ Endpoint: types.Images(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "images",
+ Limit: opts.limit,
+ FallbackDefault: 0,
+ Start: opts.start,
+ All: opts.all,
+ },
+ Query: query,
+ Headers: []string{"ID", "REPOSITORY:TAG", "SIZE", "IN USE"},
+ Row: func(img image.Summary) []string {
+ tag := "<none>"
+ if len(img.RepoTags) > 0 {
+ tag = img.RepoTags[0]
+ }
+ return []string{img.ID, tag, output.Bytes(img.Size), kit.Ternary(img.InUse, "Yes", "No")}
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 0, "Number of images to show (server default 20)")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ cmdutil.EnumVarP(command, command.Flags(), &opts.updatesFilter, "updates", "", "", "Filter by update status", "has_update", "up_to_date", "error", "unknown")
+ command.Flags().StringVar(&opts.sort, "sort", "", "Field to sort by")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.order, "order", "", "", "Sort order", "asc", "desc")
+ command.Flags().StringVar(&opts.search, "search", "", "Search query")
+ command.Flags().BoolVar(&opts.inUseOnly, "inuse", false, "Only show images currently in use")
+ command.Flags().BoolVar(&opts.unusedOnly, "unused", false, "Only show images not in use")
+ command.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "inuse", "unused") }
+ return command
}
-var removeForce bool
-
-var imagesRemoveCmd = &cobra.Command{
- Use: "remove <image-id|name>",
- Aliases: []string{"rm", "delete"},
- Short: "Remove an image",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
- path := types.Image(c.EnvID(), resolved.ID)
-
- if removeForce {
- u, parseErr := url.Parse(path)
- if parseErr != nil {
- return fmt.Errorf("failed to parse path: %w", parseErr)
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <image-id|name>",
+ Short: "Get image details by ID or name",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- q := u.Query()
- q.Set("force", "true")
- u.RawQuery = q.Encode()
- path = u.String()
- }
- log.Debugf("Removing image from: %s", path)
+ allowPrompt := cmdutil.AllowPrompt(cmd)
- resp, err := c.Delete(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to remove image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- return fmt.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
- }
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+ path := types.Image(c.EnvID(), resolved.ID)
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return fmt.Errorf("failed to read response: %w", err)
- }
+ log.Debugf("Getting image details from: %s", path)
- log.Debugf("Response body: %s", string(body))
+ return cmdutil.Run(cmd, c, cmdutil.Spec[image.DetailSummary]{
+ Method: http.MethodGet, Path: path, Body: nil, FailureMessage: "failed to get image",
+ Render: func(data image.DetailSummary) error {
+ output.Header("Image Details")
+ output.KeyValue("ID", data.ID)
+ if len(data.RepoTags) > 0 {
+ output.KeyValue("Tags", strings.Join(data.RepoTags, ", "))
+ }
+ output.KeyValue("Size", output.Bytes(data.Size))
+ output.KeyValue("Architecture", data.Architecture)
+ output.KeyValue("OS", data.Os)
+ if data.Created != "" {
+ output.KeyValue("Created", data.Created)
+ }
+ if data.Author != "" {
+ output.KeyValue("Author", data.Author)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- _, _ = fmt.Fprintln(output.Stdout(), string(body))
- return nil
- }
+ if data.Config.WorkingDir != "" {
+ output.KeyValue("Working Dir", data.Config.WorkingDir)
+ }
- var result struct {
- Success bool `json:"success"`
- Data struct {
- Message string `json:"message"`
- } `json:"data"`
- }
+ if len(data.Config.Cmd) > 0 {
+ output.KeyValue("Cmd", strings.Join(data.Config.Cmd, " "))
+ }
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+ if len(data.Config.Env) > 0 {
+ output.Header("Environment Variables")
+ for _, env := range data.Config.Env {
+ _, _ = fmt.Fprintln(output.Stdout(), env)
+ }
+ }
- output.Success("%s", result.Data.Message)
+ if len(data.Config.ExposedPorts) > 0 {
+ output.Header("Exposed Ports")
+ for _, p := range slices.Sorted(maps.Keys(data.Config.ExposedPorts)) {
+ _, _ = fmt.Fprintln(output.Stdout(), p)
+ }
+ }
- return nil
- },
+ return nil
+ },
+ })
+ },
+ }
}
-var imagesPullCmd = &cobra.Command{
- Use: "pull [IMAGE_NAME]",
- Short: "Pull an image from a registry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Pulling large images can take a long time
- c.SetTimeout(30 * time.Minute)
-
- imageName := args[0]
- path := types.ImagesPull(c.EnvID())
-
- log.Debugf("Pulling image from: %s", path)
-
- requestBody := map[string]any{
- "imageName": imageName,
- }
-
- resp, err := c.Post(cmd.Context(), path, requestBody)
- if err != nil {
- return fmt.Errorf("failed to pull image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- return fmt.Errorf("failed to pull image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
- }
-
- // Stream the response
- if cmdutil.JSONOutputEnabled(cmd) {
- _, err = io.Copy(cmd.OutOrStdout(), resp.Body)
+func newRemoveCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "remove <image-id|name>",
+ Aliases: []string{"rm", "delete"},
+ Short: "Remove an image",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
- return fmt.Errorf("failed to read pull stream: %w", err)
+ return err
}
- return nil
- }
- output.Info("Pulling image: %s", imageName)
-
- decoder := jsontext.NewDecoder(resp.Body)
- loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), true)
- defer loading.Stop()
-
- for {
- var event struct {
- Type string `json:"type"`
- Status string `json:"status"`
- Error string `json:"error"`
- ID string `json:"id"`
- ProgressDetail struct {
- Current int64 `json:"current"`
- Total int64 `json:"total"`
- } `json:"progressDetail"`
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
}
+ path := types.Image(c.EnvID(), resolved.ID)
- if unmarshalDecodeErr := json.UnmarshalDecode(decoder, &event); unmarshalDecodeErr != nil {
- if errors.Is(unmarshalDecodeErr, io.EOF) {
- break
+ if opts.force {
+ u, parseErr := url.Parse(path)
+ if parseErr != nil {
+ return fmt.Errorf("failed to parse path: %w", parseErr)
}
- return fmt.Errorf("failed to decode stream: %w", unmarshalDecodeErr)
+ q := u.Query()
+ q.Set("force", "true")
+ u.RawQuery = q.Encode()
+ path = u.String()
}
- // The stream opens with an activity frame that carries no Docker
- // status; printing it would emit a blank line per pull.
- if event.Type != "" && event.Status == "" && event.Error == "" {
- continue
- }
+ log.Debugf("Removing image from: %s", path)
- if event.Error != "" {
- pullErr := fmt.Errorf("pull error: %s", event.Error)
- loading.Finish(event.ID, pullErr)
- return pullErr
- }
- if event.ID != "" {
- label := event.Status + " " + event.ID
- loading.SetProgress(event.ID, label, event.ProgressDetail.Current, event.ProgressDetail.Total, true)
- if event.Status == "Download complete" || event.Status == "Pull complete" || event.Status == "Already exists" {
- loading.Finish(event.ID, nil)
- }
+ confirmed, confirmErr := cmdutil.ConfirmOrCancel(cmd, opts.force, fmt.Sprintf("Are you sure you want to remove image %s?", args[0]))
+ if confirmErr != nil || !confirmed {
+ return confirmErr
}
- if !output.IsTerminal(cmd.ErrOrStderr()) || !output.IsTerminal(cmd.OutOrStdout()) || event.ID == "" {
- if event.Status != "Downloading" && event.Status != "Extracting" {
- deferResume := output.SuspendProgress()
- if event.ID != "" {
- _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", event.ID, event.Status)
- } else {
- _, _ = fmt.Fprintln(cmd.OutOrStdout(), event.Status)
- }
- deferResume()
- }
- }
- }
- loading.Stop()
-
- output.Success("Image pulled successfully")
-
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodDelete, Path: path, FailureMessage: "failed to remove image",
+ Render: func(data base.MessageResponse) error {
+ output.Success("%s", data.Message)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal of image")
+ return command
}
-var pruneDangling bool
-
-var imagesPruneCmd = &cobra.Command{
- Use: "prune",
- Short: "Remove unused images",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := types.ImagesPrune(c.EnvID())
-
- log.Debugf("Pruning images from: %s", path)
-
- requestBody := map[string]any{
- "dangling": pruneDangling,
- }
-
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !jsonOutput, "Pruning images")
- loading.NextStep()
- defer loading.Stop()
- resp, err := c.Post(cmd.Context(), path, requestBody)
- if err != nil {
- return fmt.Errorf("failed to prune images: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- return fmt.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
- }
+func newPullCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeDestination},
+ Use: "pull <image>",
+ Short: "Pull an image from a registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return fmt.Errorf("failed to read response: %w", err)
- }
+ // Pulling large images can take a long time
+ c.SetTimeout(30 * time.Minute)
- log.Debugf("Response body: %s", string(body))
+ imageName := args[0]
+ path := types.ImagesPull(c.EnvID())
- if cmdutil.JSONOutputEnabled(cmd) {
- _, _ = fmt.Fprintln(output.Stdout(), string(body))
- return nil
- }
+ log.Debugf("Pulling image from: %s", path)
- var result struct {
- Success bool `json:"success"`
- Data struct {
- ImagesDeleted []string `json:"imagesDeleted"`
- SpaceReclaimed int64 `json:"spaceReclaimed"`
- } `json:"data"`
- }
+ requestBody := image.PullOptions{ImageName: imageName}
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
-
- output.Success("Pruned %d images, reclaimed %s", len(result.Data.ImagesDeleted), output.Bytes(result.Data.SpaceReclaimed))
+ resp, err := c.Post(cmd.Context(), path, requestBody)
+ if err != nil {
+ return fmt.Errorf("failed to pull image: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if statusErr := cmdutil.EnsureSuccessStatus(resp); statusErr != nil {
+ return fmt.Errorf("failed to pull image: %w", statusErr)
+ }
- return nil
- },
+ if !cmdutil.JSONOutputEnabled(cmd) {
+ output.Info("Pulling image: %s", imageName)
+ }
+ return readPullStream(cmd, resp.Body)
+ },
+ }
}
-var imagesCountsCmd = &cobra.Command{
- Use: "counts",
- Short: "Get image usage counts",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := types.ImagesCounts(c.EnvID())
-
- log.Debugf("Getting image counts from: %s", path)
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get image counts: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return fmt.Errorf("failed to read response: %w", err)
- }
-
- log.Debugf("Response body: %s", string(body))
-
- if cmdutil.JSONOutputEnabled(cmd) {
- _, _ = fmt.Fprintln(output.Stdout(), string(body))
- return nil
- }
+func newPruneCmd() *cobra.Command {
+ var opts struct {
+ dangling bool
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeFleet},
+ Use: "prune",
+ Short: "Remove unused images",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- var result struct {
- Success bool `json:"success"`
- Data image.UsageCounts `json:"data"`
- }
+ path := types.ImagesPrune(c.EnvID())
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+ log.Debugf("Pruning images from: %s", path)
- output.Header("Image Usage Counts")
- output.KeyValue("In Use", result.Data.Inuse)
- output.KeyValue("Unused", result.Data.Unused)
- output.KeyValue("Total", result.Data.Total)
- output.KeyValue("Total Size", output.Bytes(result.Data.TotalSize))
+ requestBody := map[string]any{
+ "dangling": opts.dangling,
+ }
- return nil
- },
+ confirmed, confirmErr := cmdutil.ConfirmOrCancel(cmd, false, "Are you sure you want to remove unused images?")
+ if confirmErr != nil || !confirmed {
+ return confirmErr
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[image.PruneReport]{
+ Method: http.MethodPost, Path: path, Body: requestBody, FailureMessage: "failed to prune images",
+ Render: func(data image.PruneReport) error {
+ output.Success("Pruned %d images, reclaimed %s", len(data.ImagesDeleted), output.Bytes(data.SpaceReclaimed))
+
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().BoolVar(&opts.dangling, "dangling", false, "Only remove dangling images")
+ return command
}
-var imagesUploadCmd = &cobra.Command{
- Use: "upload [FILE]",
- Short: "Upload a Docker image from a tar archive",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Uploading large images can take a long time
- c.SetTimeout(30 * time.Minute)
+func newCountsCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "counts",
+ Short: "Get image usage counts",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- filePath := args[0]
- output.Info("Uploading image: %s", filePath)
+ path := types.ImagesCounts(c.EnvID())
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- sessionID, err := cmdutil.UploadFileInChunks(cmd.Context(), c, uploadtypes.KindImage, filePath, !jsonOutput)
- if err != nil {
- return err
- }
+ log.Debugf("Getting image counts from: %s", path)
- respBody, err := c.DoRaw(cmd.Context(), http.MethodPost, types.ImagesUpload(c.EnvID()), uploadtypes.ConsumeRequest{UploadID: sessionID})
- if err != nil {
- cmdutil.AbortUploadSession(cmd.Context(), c, uploadtypes.KindImage, sessionID)
- return fmt.Errorf("failed to upload image: %w", err)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[image.UsageCounts]{
+ Method: http.MethodGet, Path: path, Body: nil, FailureMessage: "failed to get image counts",
+ Render: func(data image.UsageCounts) error {
+ output.Header("Image Usage Counts")
+ output.KeyValue("In Use", data.Inuse)
+ output.KeyValue("Unused", data.Unused)
+ output.KeyValue("Total", data.Total)
+ output.KeyValue("Total Size", output.Bytes(data.TotalSize))
- log.Debugf("Response body: %s", string(respBody))
-
- if jsonOutput {
- _, _ = fmt.Fprintln(output.Stdout(), string(respBody))
- return nil
- }
-
- var result struct {
- Success bool `json:"success"`
- Data image.LoadResult `json:"data"`
- }
+ return nil
+ },
+ })
+ },
+ }
+}
- if unmarshalErr := json.Unmarshal(respBody, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+func newUploadCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeDestination},
+ Use: "upload <file>",
+ Short: "Upload a Docker image from a tar archive",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if !result.Success {
- return fmt.Errorf("upload failed: %s", string(respBody))
- }
+ // Uploading large images can take a long time
+ c.SetTimeout(30 * time.Minute)
- output.Success("Image uploaded successfully")
+ filePath := args[0]
+ output.Info("Uploading image: %s", filePath)
- return nil
- },
-}
+ jsonOutput := cmdutil.JSONOutputEnabled(cmd)
+ sessionID, err := cmdutil.UploadFileInChunks(cmd.Context(), c, upload.KindImage, filePath, !jsonOutput)
+ if err != nil {
+ return err
+ }
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, ImagesCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, imagesListCmd, imagesCountsCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, imagesPruneCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, imagesPullCmd, imagesUploadCmd)
- ImagesCmd.AddCommand(imagesListCmd)
- imagesListCmd.Flags().IntVarP(&imagesLimit, "limit", "n", 0, "Number of images to show (server default 20)")
- imagesListCmd.Flags().IntVar(&imagesStart, "start", 0, cmdutil.StartFlagUsage)
- imagesListCmd.Flags().BoolVarP(&imagesAll, "all", "a", false, cmdutil.AllFlagUsage)
- imagesListCmd.Flags().StringVar(&imagesUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
- imagesListCmd.Flags().StringVar(&imagesSort, "sort", "", "Field to sort by")
- imagesListCmd.Flags().StringVar(&imagesOrder, "order", "", "Sort order (asc/desc)")
- imagesListCmd.Flags().StringVar(&imagesSearch, "search", "", "Search query")
- imagesListCmd.Flags().BoolVar(&imagesInUseOnly, "inuse", false, "Only show images currently in use")
- imagesListCmd.Flags().BoolVar(&imagesUnusedOnly, "unused", false, "Only show images not in use")
-
- ImagesCmd.AddCommand(imagesGetCmd)
-
- ImagesCmd.AddCommand(imagesRemoveCmd)
- imagesRemoveCmd.Flags().BoolVarP(&removeForce, "force", "f", false, "Force removal of image")
-
- ImagesCmd.AddCommand(imagesPullCmd)
-
- ImagesCmd.AddCommand(imagesPruneCmd)
- imagesPruneCmd.Flags().BoolVar(&pruneDangling, "dangling", false, "Only remove dangling images")
-
- ImagesCmd.AddCommand(imagesCountsCmd)
- ImagesCmd.AddCommand(updates.UpdatesCmd)
- for _, command := range updates.UpdatesCmd.Commands() {
- if command.Name() == "check-image" {
- cmdutil.SetResource(ImageRef, command)
- }
+ uploadErr := cmdutil.Run(cmd, c, cmdutil.Spec[image.LoadResult]{
+ Method: http.MethodPost, Path: types.ImagesUpload(c.EnvID()),
+ Body: upload.ConsumeRequest{UploadID: sessionID}, FailureMessage: "failed to upload image",
+ Render: func(image.LoadResult) error {
+ output.Success("Image uploaded successfully")
+ return nil
+ },
+ })
+ if uploadErr != nil {
+ cmdutil.AbortUploadSession(cmd.Context(), c, upload.KindImage, sessionID)
+ }
+ return uploadErr
+ },
}
-
- ImagesCmd.AddCommand(imagesUploadCmd)
}
var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
@@ -607,9 +426,10 @@ var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
Matches: imageMatches,
Label: func(match image.Summary) string {
label := match.ID
- if len(match.RepoTags) > 0 {
+ switch {
+ case len(match.RepoTags) > 0:
label = match.RepoTags[0]
- } else if match.Repo != "" && match.Tag != "" {
+ case match.Repo != "" && match.Tag != "":
label = match.Repo + ":" + match.Tag
}
return fmt.Sprintf("%s (%s)", label, match.ID)
@@ -635,26 +455,13 @@ var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
func searchImageCandidates(ctx context.Context, c *client.Client, identifier string) ([]image.Summary, error) {
terms := []string{identifier}
- separator := ":"
- if strings.Contains(identifier, "@") {
- separator = "@"
- }
+ separator := kit.Ternary(strings.Contains(identifier, "@"), "@", ":")
if separator == "@" || !strings.HasPrefix(strings.ToLower(identifier), "sha256:") {
if repository, _, ok := strings.Cut(identifier, separator); ok && repository != "" {
terms = append(terms, repository)
}
}
- seenTerms := make(map[string]struct{}, len(terms))
- for _, term := range terms {
- term = strings.TrimSpace(term)
- if term == "" {
- continue
- }
- if _, ok := seenTerms[term]; ok {
- continue
- }
- seenTerms[term] = struct{}{}
-
+ for _, term := range kit.Unique(kit.TrimNonEmpty(terms)) {
searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Images(c.EnvID()), url.QueryEscape(term), cmdutil.ShowAllLimit)
result, err := c.GetJSON[[]image.Summary](ctx, searchPath)
if err != nil {
@@ -678,37 +485,78 @@ func searchImageCandidates(ctx context.Context, c *client.Client, identifier str
func imageMatches(item image.Summary, identifierLower, original string) bool {
hasSeparator := strings.Contains(original, ":") || strings.Contains(original, "@")
-
idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
-
- if !hasSeparator && strings.Contains(strings.ToLower(item.Repo), identifierLower) {
- return true
+ // Qualified refs match exactly or by registry/namespace suffix, so repo:1 never matches repo:10.
+ refMatches := func(ref string) bool {
+ refLower := strings.ToLower(ref)
+ return refLower == identifierLower || (hasSeparator && strings.HasSuffix(refLower, "/"+identifierLower)) ||
+ (!hasSeparator && strings.Contains(refLower, identifierLower))
}
+ return idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) ||
+ (!hasSeparator && strings.Contains(strings.ToLower(item.Repo), identifierLower)) ||
+ slices.ContainsFunc(item.RepoTags, refMatches) ||
+ (item.Repo != "" && item.Tag != "" && refMatches(item.Repo+":"+item.Tag)) ||
+ slices.ContainsFunc(item.RepoDigests, func(digest string) bool { return strings.Contains(strings.ToLower(digest), identifierLower) })
+}
- for _, tag := range item.RepoTags {
- tagLower := strings.ToLower(tag)
- if (!hasSeparator && strings.Contains(tagLower, identifierLower)) || strings.EqualFold(tag, original) {
- return true
+func readPullStream(cmd *cobra.Command, reader io.Reader) error {
+ jsonMode := cmdutil.JSONOutputEnabled(cmd)
+ frames := make([]jsontext.Value, 0)
+ decoder := jsontext.NewDecoder(reader)
+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !jsonMode)
+ defer loading.Stop()
+ for {
+ frame, readErr := decoder.ReadValue()
+ if readErr != nil {
+ if errors.Is(readErr, io.EOF) {
+ break
+ }
+ return fmt.Errorf("failed to decode stream: %w", readErr)
+ }
+ var event struct {
+ Type string `json:"type"`
+ Status string `json:"status"`
+ Error string `json:"error"`
+ ID string `json:"id"`
+ ProgressDetail struct {
+ Current int64 `json:"current"`
+ Total int64 `json:"total"`
+ } `json:"progressDetail"`
+ }
+ if decodeErr := json.Unmarshal(frame, &event); decodeErr != nil {
+ return fmt.Errorf("failed to decode stream: %w", decodeErr)
+ }
+ if jsonMode {
+ frames = append(frames, frame.Clone())
+ }
+ if event.Error != "" {
+ pullErr := fmt.Errorf("pull error: %s", event.Error)
+ loading.Finish(event.ID, pullErr)
+ return pullErr
+ }
+ if jsonMode || event.Type != "" && event.Status == "" {
+ continue
}
- }
-
- if item.Repo != "" && item.Tag != "" {
- combined := item.Repo + ":" + item.Tag
- combinedLower := strings.ToLower(combined)
- if strings.EqualFold(combined, original) || (hasSeparator && strings.Contains(combinedLower, identifierLower)) {
- return true
+ if event.ID != "" {
+ loading.SetProgress(event.ID, event.Status+" "+event.ID, event.ProgressDetail.Current, event.ProgressDetail.Total, true)
+ if slices.Contains([]string{"Download complete", "Pull complete", "Already exists"}, event.Status) {
+ loading.Finish(event.ID, nil)
+ }
}
- }
-
- for _, digest := range item.RepoDigests {
- digestLower := strings.ToLower(digest)
- if strings.EqualFold(digest, original) || strings.Contains(digestLower, identifierLower) {
- return true
+ if (!output.IsTerminal(cmd.ErrOrStderr()) || !output.IsTerminal(cmd.OutOrStdout()) || event.ID == "") && event.Status != "Downloading" && event.Status != "Extracting" {
+ resume := output.SuspendProgress()
+ if event.ID != "" {
+ _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", event.ID, event.Status)
+ } else {
+ _, _ = fmt.Fprintln(cmd.OutOrStdout(), event.Status)
+ }
+ resume()
}
}
-
- return false
+ loading.Stop()
+ if jsonMode {
+ return cmdutil.PrintJSON(frames)
+ }
+ output.Success("Image pulled successfully")
+ return nil
}
diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.go
index 6cf4a3c0b..fe43ce604 100644
--- a/cli/pkg/images/extra.go
+++ b/cli/pkg/images/extra.go
@@ -3,6 +3,8 @@ package images
import (
"bufio"
"cmp"
+ jsonv1 "encoding/json"
+ "encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
@@ -17,620 +19,524 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/image"
"github.com/spf13/cobra"
+ buildtypes "go.getarcane.app/builds/types"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/logger"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var imagesSearchCmd = &cobra.Command{
- Use: "search <term>",
- Short: "Search Docker Hub images",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := types.ImagesSearch(c.EnvID()) + "?term=" + url.QueryEscape(args[0])
-
- log.Debugf("Searching images from: %s", path)
-
- result, err := c.GetJSON[[]image.SearchResult](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to search images: %w", err)
- }
-
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"NAME", "DESCRIPTION", "STARS", "OFFICIAL"}
- var rows [][]string
- for _, item := range result.Data {
- official := ""
- if item.Official {
- official = "Yes"
+func newSearchCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "search <term>",
+ Short: "Search Docker Hub images",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- rows = append(rows, []string{item.Name, truncateCell(item.Description, 60), strconv.Itoa(item.StarCount), official})
- }
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "results", Total: int64(len(result.Data)), Paginated: true}); tableErr != nil {
- return tableErr
- }
-
- return nil
- },
+ path := types.ImagesSearch(c.EnvID()) + "?term=" + url.QueryEscape(args[0])
+
+ log.Debugf("Searching images from: %s", path)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]image.SearchResult]{
+ Method: http.MethodGet,
+ Path: path,
+ FailureMessage: "failed to search images",
+ Render: func(data []image.SearchResult) error {
+ headers := []string{"NAME", "DESCRIPTION", "STARS", "OFFICIAL"}
+ var rows [][]string
+ for _, item := range data {
+ rows = append(rows, []string{item.Name, truncateCell(item.Description, 60), strconv.Itoa(item.StarCount), kit.Ternary(item.Official, "Yes", "")})
+ }
+
+ return cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "results", Total: int64(len(data)), Paginated: true})
+ },
+ })
+ },
+ }
}
-var imagesHistoryCmd = &cobra.Command{
- Use: "history <image-id|name>",
- Short: "Show image layer history",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- allowPrompt := !jsonOutput && prompt.IsInteractive()
-
- resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
- imageID := resolved.ID
- path := types.ImageHistory(c.EnvID(), imageID)
-
- log.Debugf("Getting image history from: %s", path)
-
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get image history: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return fmt.Errorf("failed to get image history: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
+func newHistoryCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "history <image-id|name>",
+ Short: "Show image layer history",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- var result struct {
- Success bool `json:"success"`
- Data []image.HistoryItem `json:"data"`
- }
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
- headers := []string{"CREATED", "CREATED BY", "SIZE", "COMMENT"}
- var rows [][]string
- for _, item := range result.Data {
- created := ""
- if item.Created > 0 {
- created = time.Unix(item.Created, 0).Format(time.RFC3339)
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- rows = append(rows, []string{created, truncateCell(item.CreatedBy, 60), output.Bytes(item.Size), truncateCell(item.Comment, 30)})
- }
-
- return cmdutil.PrintTable(cmd, headers, rows)
- },
+ imageID := resolved.ID
+ path := types.ImageHistory(c.EnvID(), imageID)
+
+ log.Debugf("Getting image history from: %s", path)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]image.HistoryItem]{
+ Method: http.MethodGet, Path: path, Body: nil, FailureMessage: "failed to get image history",
+ Render: func(data []image.HistoryItem) error {
+ headers := []string{"CREATED", "CREATED BY", "SIZE", "COMMENT"}
+ var rows [][]string
+ for _, item := range data {
+ created := ""
+ if item.Created > 0 {
+ created = time.Unix(item.Created, 0).Format(time.RFC3339)
+ }
+ rows = append(rows, []string{created, truncateCell(item.CreatedBy, 60), output.Bytes(item.Size), truncateCell(item.Comment, 30)})
+ }
+
+ return cmdutil.PrintTable(cmd, headers, rows)
+ },
+ })
+ },
+ }
}
-var imagesTagCmd = &cobra.Command{
- Use: "tag <image-id|name> <new-ref>",
- Short: "Add a repository tag to an image",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- allowPrompt := !jsonOutput && prompt.IsInteractive()
-
- resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
- imageID := resolved.ID
-
- repository, tag := strings.TrimSpace(args[1]), ""
- if index := strings.LastIndex(repository, ":"); index > 0 && !strings.Contains(repository[index+1:], "/") {
- repository, tag = repository[:index], repository[index+1:]
- }
- if repository == "" {
- return errors.New("target repository is required")
- }
-
- path := types.ImageTag(c.EnvID(), imageID)
+func newTagCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "tag <image-id|name> <new-ref>",
+ Short: "Add a repository tag to an image",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- log.Debugf("Tagging image via: %s", path)
+ allowPrompt := cmdutil.AllowPrompt(cmd)
- resp, err := c.Post(cmd.Context(), path, image.TagRequest{Repository: repository, Tag: tag})
- if err != nil {
- return fmt.Errorf("failed to tag image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+ imageID := resolved.ID
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return fmt.Errorf("failed to tag image: %w", err)
- }
+ repository, tag := strings.TrimSpace(args[1]), ""
+ if index := strings.LastIndex(repository, ":"); index > 0 && !strings.Contains(repository[index+1:], "/") {
+ repository, tag = repository[:index], repository[index+1:]
+ }
+ if repository == "" {
+ return errors.New("target repository is required")
+ }
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
+ path := types.ImageTag(c.EnvID(), imageID)
- var result struct {
- Success bool `json:"success"`
- Data base.MessageResponse `json:"data"`
- }
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+ log.Debugf("Tagging image via: %s", path)
- output.Success("%s", result.Data.Message)
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost, Path: path, Body: image.TagRequest{Repository: repository, Tag: tag}, FailureMessage: "failed to tag image",
+ Render: func(data base.MessageResponse) error {
+ output.Success("%s", data.Message)
- return nil
- },
+ return nil
+ },
+ })
+ },
+ }
}
-var imagesExportCmd = &cobra.Command{
- Use: "export <image-id|name> [output-file]",
- Short: "Download an image as a tar archive",
- Args: cobra.RangeArgs(1, 2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Exporting large images can take a long time
- c.SetTimeout(30 * time.Minute)
-
- allowPrompt := prompt.IsInteractive()
-
- resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
- imageID := resolved.ID
-
- name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(strings.TrimSpace(args[0]))
- outputFile := cmp.Or(strings.Trim(name, "._-"), "image") + ".tar"
- if len(args) == 2 {
- outputFile = args[1]
- }
-
- path := types.ImageExport(c.EnvID(), imageID)
-
- log.Debugf("Exporting image from: %s", path)
-
- resp, err := c.RequestRaw(cmd.Context(), http.MethodGet, path, nil, nil)
- if err != nil {
- return fmt.Errorf("failed to export image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to export image: %w", ensureSuccessStatusErr)
- }
-
- file, err := os.Create(outputFile)
- if err != nil {
- return fmt.Errorf("failed to create output file: %w", err)
- }
-
- written, err := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Exporting image", !cmdutil.JSONOutputEnabled(cmd))
- if closeErr := file.Close(); closeErr != nil && err == nil {
- err = closeErr
- }
- if err != nil {
- _ = os.Remove(outputFile)
- return fmt.Errorf("failed to write image archive: %w", err)
- }
-
- output.Success("Saved %s (%s)", outputFile, output.Bytes(written))
-
- return nil
- },
-}
+func newExportCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "export <image-id|name> [output-file]",
+ Short: "Download an image as a tar archive",
+ Args: cobra.RangeArgs(1, 2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var (
- attestationsPlatform string
- attestationsPredicateType string
- attestationsStatement bool
- buildTags []string
- buildDockerfile string
- buildInlineFile string
- buildArgs []string
- buildTarget string
- buildPlatforms []string
- buildNetwork string
- buildProvider string
- buildNoCache bool
- buildPull bool
- buildPush bool
- buildLoad bool
- buildsLimit int
- buildsStart int
- buildsAll bool
- buildsStatus string
- buildsProvider string
-)
+ // Exporting large images can take a long time
+ c.SetTimeout(30 * time.Minute)
-var imagesAttestationsCmd = &cobra.Command{
- Use: "attestations <image>",
- Short: "Show in-toto attestations attached to an image",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
- imageName := strings.TrimSpace(args[0])
- if imageName == "" {
- return errors.New("image identifier is required")
- }
+ resolved, _, err := ImageRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+ imageID := resolved.ID
- u, err := url.Parse(types.ImageAttestations(c.EnvID(), imageName))
- if err != nil {
- return fmt.Errorf("failed to parse endpoint path: %w", err)
- }
- q := u.Query()
- if attestationsPlatform != "" {
- q.Set("platform", attestationsPlatform)
- }
- if attestationsPredicateType != "" {
- q.Set("predicateType", attestationsPredicateType)
- }
- if attestationsStatement {
- q.Set("statement", "true")
- }
- u.RawQuery = q.Encode()
- path := u.String()
+ name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(strings.TrimSpace(args[0]))
+ outputFile := cmp.Or(strings.Trim(name, "._-"), "image") + ".tar"
+ if len(args) == 2 {
+ outputFile = args[1]
+ }
- log.Debugf("Getting image attestations from: %s", path)
+ path := types.ImageExport(c.EnvID(), imageID)
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get image attestations: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
+ log.Debugf("Exporting image from: %s", path)
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return fmt.Errorf("failed to get image attestations: %w", err)
- }
+ resp, err := c.RequestRaw(cmd.Context(), http.MethodGet, path, nil, nil)
+ if err != nil {
+ return fmt.Errorf("failed to export image: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to export image: %w", ensureSuccessStatusErr)
+ }
- if cmdutil.JSONOutputEnabled(cmd) || attestationsStatement {
- return cmdutil.PrintRawJSON(body)
- }
+ file, err := os.Create(outputFile)
+ if err != nil {
+ return fmt.Errorf("failed to create output file: %w", err)
+ }
- var result struct {
- Success bool `json:"success"`
- Data image.AttestationList `json:"data"`
- }
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+ written, err := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Exporting image", !cmdutil.JSONOutputEnabled(cmd))
+ if closeErr := file.Close(); closeErr != nil && err == nil {
+ err = closeErr
+ }
+ if err != nil {
+ _ = os.Remove(outputFile)
+ return fmt.Errorf("failed to write image archive: %w", err)
+ }
- output.Header("Image Attestations")
- output.KeyValue("Image", result.Data.ImageRef)
- output.KeyValue("Subject Digest", result.Data.SubjectDigest)
- if result.Data.Platform != "" {
- output.KeyValue("Platform", result.Data.Platform)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ }{Path: outputFile, Bytes: written})
+ }
+ output.Success("Saved %s (%s)", outputFile, output.Bytes(written))
- if len(result.Data.Attestations) == 0 {
- output.Info("No attestations found")
return nil
- }
-
- headers := []string{"PREDICATE TYPE", "PLATFORM", "DIGEST", "SIZE"}
- var rows [][]string
- for _, att := range result.Data.Attestations {
- rows = append(rows, []string{att.PredicateType, att.Platform, truncateCell(att.Digest, 19), output.Bytes(att.Size)})
- }
- _, _ = fmt.Fprintln(output.Stdout())
- if tableErr := cmdutil.PrintTable(cmd, headers, rows); tableErr != nil {
- return tableErr
- }
-
- return nil
- },
+ },
+ }
}
-var imagesBuildCmd = &cobra.Command{
- Use: "build <context-dir|git-url>",
- Short: "Build an image with BuildKit on the server",
- Long: "Build a Docker image using BuildKit with streaming progress output.\n\nThe context argument is a build context directory on the Arcane server or a Git URL.",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Builds can take a long time
- c.SetTimeout(30 * time.Minute)
-
- requestBody := map[string]any{
- "contextDir": args[0],
- }
- if buildDockerfile != "" {
- requestBody["dockerfile"] = buildDockerfile
- }
- if buildInlineFile != "" {
- content, readFileErr := os.ReadFile(buildInlineFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read Dockerfile: %w", readFileErr)
- }
- requestBody["dockerfileInline"] = string(content)
- }
- if len(buildTags) > 0 {
- requestBody["tags"] = buildTags
- }
- if buildTarget != "" {
- requestBody["target"] = buildTarget
- }
- if len(buildArgs) > 0 {
- parsed := make(map[string]string, len(buildArgs))
- for _, arg := range buildArgs {
- key, value, ok := strings.Cut(arg, "=")
- if !ok || key == "" {
- return fmt.Errorf("invalid build arg %q; expected KEY=VALUE", arg)
- }
- parsed[key] = value
+func newAttestationsCmd() *cobra.Command {
+ var opts struct {
+ platform string
+ predicateType string
+ statement bool
+ }
+ command := &cobra.Command{
+ Use: "attestations <image>",
+ Short: "Show in-toto attestations attached to an image",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- requestBody["buildArgs"] = parsed
- }
- if len(buildPlatforms) > 0 {
- requestBody["platforms"] = buildPlatforms
- }
- if buildNetwork != "" {
- requestBody["network"] = buildNetwork
- }
- if buildProvider != "" {
- requestBody["provider"] = buildProvider
- }
- if buildNoCache {
- requestBody["noCache"] = true
- }
- if buildPull {
- requestBody["pull"] = true
- }
- if buildPush {
- requestBody["push"] = true
- }
- if buildLoad {
- requestBody["load"] = true
- }
-
- path := types.ImagesBuild(c.EnvID())
- log.Debugf("Building image via: %s", path)
-
- resp, err := c.Post(cmd.Context(), path, requestBody)
- if err != nil {
- return fmt.Errorf("failed to build image: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to build image: %w", ensureSuccessStatusErr)
- }
+ imageName := strings.TrimSpace(args[0])
+ if imageName == "" {
+ return errors.New("image identifier is required")
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- _, err = io.Copy(cmd.OutOrStdout(), resp.Body)
+ u, err := url.Parse(types.ImageAttestations(c.EnvID(), imageName))
if err != nil {
- return fmt.Errorf("failed to read build stream: %w", err)
+ return fmt.Errorf("failed to parse endpoint path: %w", err)
}
- return nil
- }
-
- if streamBuildOutputErr := streamBuildOutput(resp.Body); streamBuildOutputErr != nil {
- return streamBuildOutputErr
- }
-
- output.Success("Image built successfully")
-
- return nil
- },
-}
-
-// streamBuildOutput prints the build NDJSON stream: control frames (activity,
-// done, error) are interpreted, everything else is raw build output.
-func streamBuildOutput(body io.Reader) error {
- scanner := bufio.NewScanner(body)
- scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
- done := false
- for scanner.Scan() {
- line := scanner.Text()
- trimmed := strings.TrimSpace(line)
- if strings.HasPrefix(trimmed, "{") {
- var frame struct {
- Type string `json:"type"`
- Done bool `json:"done"`
- Error string `json:"error"`
- }
- if json.Unmarshal([]byte(trimmed), &frame) == nil {
- if frame.Error != "" {
- return fmt.Errorf("build error: %s", frame.Error)
- }
- if frame.Done {
- done = true
- continue
- }
- if frame.Type != "" {
- continue
- }
+ q := u.Query()
+ if opts.platform != "" {
+ q.Set("platform", opts.platform)
}
- }
- _, _ = fmt.Fprintln(output.Stdout(), line)
- }
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("failed to read build stream: %w", err)
- }
- if !done {
- return errors.New("build stream ended without completion frame")
+ if opts.predicateType != "" {
+ q.Set("predicateType", opts.predicateType)
+ }
+ if opts.statement {
+ q.Set("statement", "true")
+ }
+ u.RawQuery = q.Encode()
+ path := u.String()
+
+ log.Debugf("Getting image attestations from: %s", path)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[jsontext.Value]{
+ Method: http.MethodGet, Path: path, Body: nil, FailureMessage: "failed to get image attestations",
+ Render: func(raw jsontext.Value) error {
+ if opts.statement {
+ return cmdutil.PrintRawJSON(raw)
+ }
+ var data image.AttestationList
+ if decodeErr := json.Unmarshal(raw, &data); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
+ output.Header("Image Attestations")
+ output.KeyValue("Image", data.ImageRef)
+ output.KeyValue("Subject Digest", data.SubjectDigest)
+ if data.Platform != "" {
+ output.KeyValue("Platform", data.Platform)
+ }
+
+ if len(data.Attestations) == 0 {
+ output.Info("No attestations found")
+ return nil
+ }
+
+ headers := []string{"PREDICATE TYPE", "PLATFORM", "DIGEST", "SIZE"}
+ var rows [][]string
+ for _, att := range data.Attestations {
+ rows = append(rows, []string{att.PredicateType, att.Platform, truncateCell(att.Digest, 19), output.Bytes(att.Size)})
+ }
+ _, _ = fmt.Fprintln(output.Stdout())
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows); tableErr != nil {
+ return tableErr
+ }
+
+ return nil
+ },
+ })
+ },
}
- return nil
+ command.Flags().StringVar(&opts.platform, "platform", "", "OCI platform selector (e.g. linux/amd64)")
+ command.Flags().StringVar(&opts.predicateType, "predicate-type", "", "Exact in-toto predicate type URI to include")
+ command.Flags().BoolVar(&opts.statement, "statement", false, "Include verbatim statement JSON bodies (implies JSON output)")
+ cmdutil.SetResource(ImageRef, command)
+ return command
}
-var imagesBuildsCmd = &cobra.Command{
- Use: "builds",
- Short: "List image build history",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newBuildCmd() *cobra.Command {
+ var opts struct {
+ tags []string
+ dockerfile string
+ inlineFile string
+ args []string
+ target string
+ platforms []string
+ network string
+ provider string
+ noCache bool
+ pull bool
+ push bool
+ load bool
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeDestination},
+ Use: "build <context-dir|git-url>",
+ Short: "Build an image with BuildKit on the server",
+ Long: "Build a Docker image using BuildKit with streaming progress output.\n\nThe context argument is a build context directory on the Arcane server or a Git URL.",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- query := url.Values{}
- if buildsStatus != "" {
- query.Set("status", buildsStatus)
- }
- if buildsProvider != "" {
- query.Set("provider", buildsProvider)
- }
+ // Builds can take a long time
+ c.SetTimeout(30 * time.Minute)
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.BuildRecord]{
- Resource: "builds",
- Endpoint: types.ImageBuilds(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "builds", Limit: buildsLimit, FallbackDefault: 0, Start: buildsStart, All: buildsAll},
- Query: query,
- JSON: cmdutil.JSONOutputEnabled(cmd),
- Headers: []string{"ID", "IMAGE", "STATUS", "STARTED", "DURATION"},
- Row: func(record image.BuildRecord) []string {
- label := truncateCell(record.ContextDir, 40)
- if len(record.Tags) > 0 {
- label = record.Tags[0]
- }
- duration := ""
- if record.DurationMs != nil {
- duration = (time.Duration(*record.DurationMs) * time.Millisecond).Round(time.Second).String()
+ requestBody := buildtypes.BuildRequest{
+ ContextDir: args[0], Dockerfile: opts.dockerfile,
+ Tags: opts.tags, Target: opts.target,
+ Platforms: opts.platforms, Network: opts.network,
+ Provider: opts.provider, NoCache: opts.noCache,
+ Pull: opts.pull, Push: opts.push, Load: opts.load,
+ }
+ if opts.inlineFile != "" {
+ content, readFileErr := os.ReadFile(opts.inlineFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read Dockerfile: %w", readFileErr)
}
- return []string{
- record.ID,
- label,
- output.TintStatus(record.Status),
- record.CreatedAt.Format(time.RFC3339),
- duration,
+ requestBody.DockerfileInline = string(content)
+ }
+ if len(opts.args) > 0 {
+ requestBody.BuildArgs = make(map[string]string, len(opts.args))
+ for _, arg := range opts.args {
+ key, value, valid := strings.Cut(arg, "=")
+ if !valid || key == "" {
+ return fmt.Errorf("invalid build arg %q; expected KEY=VALUE", arg)
+ }
+ requestBody.BuildArgs[key] = value
}
- },
- })
- },
-}
-
-var imagesBuildsGetCmd = &cobra.Command{
- Use: "get <build-id>",
- Short: "Get an image build history entry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- log := logger.GetLogger()
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ }
+ // The build contract uses legacy omitempty semantics for booleans and numbers.
+ payload, marshalErr := jsonv1.Marshal(requestBody)
+ if marshalErr != nil {
+ return fmt.Errorf("failed to build image: %w", marshalErr)
+ }
- path := types.ImageBuild(c.EnvID(), args[0])
+ path := types.ImagesBuild(c.EnvID())
- log.Debugf("Getting image build from: %s", path)
+ log.Debugf("Building image via: %s", path)
- resp, err := c.Get(cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get image build: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
- return fmt.Errorf("failed to get image build: %w", err)
- }
+ resp, err := c.Post(cmd.Context(), path, jsontext.Value(payload))
+ if err != nil {
+ return fmt.Errorf("failed to build image: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to build image: %w", ensureSuccessStatusErr)
+ }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintRawJSON(body)
- }
+ return readBuildStream(cmd, resp.Body)
+ },
+ }
+ command.Flags().StringArrayVarP(&opts.tags, "tag", "t", nil, "Image tag (repeatable)")
+ command.Flags().StringVarP(&opts.dockerfile, "file", "f", "", "Dockerfile path within the build context")
+ command.Flags().StringVar(&opts.inlineFile, "dockerfile-inline", "", "Local Dockerfile whose content is sent as the inline Dockerfile")
+ command.Flags().StringArrayVar(&opts.args, "build-arg", nil, "Build argument KEY=VALUE (repeatable)")
+ command.Flags().StringVar(&opts.target, "target", "", "Target build stage")
+ command.Flags().StringArrayVar(&opts.platforms, "platform", nil, "Target platform (repeatable)")
+ command.Flags().StringVar(&opts.network, "network", "", "Build network mode")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.provider, "provider", "", "", "Build provider override", "local", "depot")
+ command.Flags().BoolVar(&opts.noCache, "no-cache", false, "Disable build cache")
+ command.Flags().BoolVar(&opts.pull, "pull", false, "Always pull referenced base images")
+ command.Flags().BoolVar(&opts.push, "push", false, "Push the image after building")
+ command.Flags().BoolVar(&opts.load, "load", false, "Load the image into the local Docker daemon")
+ return command
+}
- var result struct {
- Success bool `json:"success"`
- Data image.BuildRecord `json:"data"`
- }
- if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
- return fmt.Errorf("failed to parse response: %w", unmarshalErr)
- }
+func newBuildsCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ status string
+ provider string
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "builds",
+ Short: "List image build history",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- record := result.Data
+ query := url.Values{}
+ if opts.status != "" {
+ query.Set("status", opts.status)
+ }
+ if opts.provider != "" {
+ query.Set("provider", opts.provider)
+ }
- output.Header("Build Details")
- output.KeyValue("ID", record.ID)
- output.KeyValue("Status", output.TintStatus(record.Status))
- if record.Provider != "" {
- output.KeyValue("Provider", record.Provider)
- }
- output.KeyValue("Context", record.ContextDir)
- if record.Dockerfile != "" {
- output.KeyValue("Dockerfile", record.Dockerfile)
- }
- if len(record.Tags) > 0 {
- output.KeyValue("Tags", strings.Join(record.Tags, ", "))
- }
- if len(record.Platforms) > 0 {
- output.KeyValue("Platforms", strings.Join(record.Platforms, ", "))
- }
- if record.Username != nil && *record.Username != "" {
- output.KeyValue("User", *record.Username)
- }
- output.KeyValue("Started", record.CreatedAt.Format(time.RFC3339))
- if record.CompletedAt != nil {
- output.KeyValue("Completed", record.CompletedAt.Format(time.RFC3339))
- }
- duration := ""
- if record.DurationMs != nil {
- duration = (time.Duration(*record.DurationMs) * time.Millisecond).Round(time.Second).String()
- }
- output.KeyValue("Duration", duration)
- if record.Digest != nil && *record.Digest != "" {
- output.KeyValue("Digest", *record.Digest)
- }
- if record.ErrorMessage != nil && *record.ErrorMessage != "" {
- output.KeyValue("Error", *record.ErrorMessage)
- }
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[image.BuildRecord]{
+ Resource: "builds",
+ Endpoint: types.ImageBuilds(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "builds", Limit: opts.limit, FallbackDefault: 0, Start: opts.start, All: opts.all},
+ Query: query,
+ Headers: []string{"ID", "IMAGE", "STATUS", "STARTED", "DURATION"},
+ Row: func(record image.BuildRecord) []string {
+ label := truncateCell(record.ContextDir, 40)
+ if len(record.Tags) > 0 {
+ label = record.Tags[0]
+ }
+ duration := ""
+ if record.DurationMs != nil {
+ duration = (time.Duration(*record.DurationMs) * time.Millisecond).Round(time.Second).String()
+ }
+ return []string{
+ record.ID,
+ label,
+ output.TintStatus(record.Status),
+ record.CreatedAt.Format(time.RFC3339),
+ duration,
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 0, "Number of builds to show (server default 20)")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ cmdutil.EnumVarP(command, command.Flags(), &opts.status, "status", "", "", "Filter by status", "running", "success", "failed")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.provider, "provider", "", "", "Filter by provider", "local", "depot")
+ command.AddCommand(newBuildsGetCmd())
+ return command
+}
- if record.Output != nil && *record.Output != "" {
- output.Header("Output")
- _, _ = fmt.Fprintln(output.Stdout(), *record.Output)
- if record.OutputTruncated {
- output.Warning("Output was truncated")
+func newBuildsGetCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "get <build-id>",
+ Short: "Get an image build history entry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ log := logger.GetLogger()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- return nil
- },
+ path := types.ImageBuild(c.EnvID(), args[0])
+
+ log.Debugf("Getting image build from: %s", path)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[image.BuildRecord]{
+ Method: http.MethodGet, Path: path, Body: nil, FailureMessage: "failed to get image build",
+ Render: func(data image.BuildRecord) error {
+ record := data
+
+ output.Header("Build Details")
+ output.KeyValue("ID", record.ID)
+ output.KeyValue("Status", output.TintStatus(record.Status))
+ if record.Provider != "" {
+ output.KeyValue("Provider", record.Provider)
+ }
+ output.KeyValue("Context", record.ContextDir)
+ if record.Dockerfile != "" {
+ output.KeyValue("Dockerfile", record.Dockerfile)
+ }
+ if len(record.Tags) > 0 {
+ output.KeyValue("Tags", strings.Join(record.Tags, ", "))
+ }
+ if len(record.Platforms) > 0 {
+ output.KeyValue("Platforms", strings.Join(record.Platforms, ", "))
+ }
+ if record.Username != nil && *record.Username != "" {
+ output.KeyValue("User", *record.Username)
+ }
+ output.KeyValue("Started", record.CreatedAt.Format(time.RFC3339))
+ if record.CompletedAt != nil {
+ output.KeyValue("Completed", record.CompletedAt.Format(time.RFC3339))
+ }
+ duration := ""
+ if record.DurationMs != nil {
+ duration = (time.Duration(*record.DurationMs) * time.Millisecond).Round(time.Second).String()
+ }
+ output.KeyValue("Duration", duration)
+ if record.Digest != nil && *record.Digest != "" {
+ output.KeyValue("Digest", *record.Digest)
+ }
+ if record.ErrorMessage != nil && *record.ErrorMessage != "" {
+ output.KeyValue("Error", *record.ErrorMessage)
+ }
+
+ if record.Output != nil && *record.Output != "" {
+ output.Header("Output")
+ _, _ = fmt.Fprintln(output.Stdout(), *record.Output)
+ if record.OutputTruncated {
+ output.Warning("Output was truncated")
+ }
+ }
+
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(buildRef, command)
+ return command
}
func truncateCell(value string, limit int) string {
@@ -641,54 +547,62 @@ func truncateCell(value string, limit int) string {
return value
}
-func init() {
- cmdutil.SetResource(buildRef, imagesBuildsGetCmd)
- cmdutil.SetResource(ImageRef, imagesAttestationsCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, imagesSearchCmd, imagesBuildsCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, imagesBuildCmd)
- ImagesCmd.AddCommand(imagesSearchCmd)
-
- ImagesCmd.AddCommand(imagesHistoryCmd)
-
- ImagesCmd.AddCommand(imagesTagCmd)
-
- ImagesCmd.AddCommand(imagesExportCmd)
-
- ImagesCmd.AddCommand(imagesAttestationsCmd)
- imagesAttestationsCmd.Flags().StringVar(&attestationsPlatform, "platform", "", "OCI platform selector (e.g. linux/amd64)")
- imagesAttestationsCmd.Flags().StringVar(&attestationsPredicateType, "predicate-type", "", "Exact in-toto predicate type URI to include")
- imagesAttestationsCmd.Flags().BoolVar(&attestationsStatement, "statement", false, "Include verbatim statement JSON bodies (implies JSON output)")
-
- ImagesCmd.AddCommand(imagesBuildCmd)
- imagesBuildCmd.Flags().StringArrayVarP(&buildTags, "tag", "t", nil, "Image tag (repeatable)")
- imagesBuildCmd.Flags().StringVarP(&buildDockerfile, "file", "f", "", "Dockerfile path within the build context")
- imagesBuildCmd.Flags().StringVar(&buildInlineFile, "dockerfile-inline", "", "Local Dockerfile whose content is sent as the inline Dockerfile")
- imagesBuildCmd.Flags().StringArrayVar(&buildArgs, "build-arg", nil, "Build argument KEY=VALUE (repeatable)")
- imagesBuildCmd.Flags().StringVar(&buildTarget, "target", "", "Target build stage")
- imagesBuildCmd.Flags().StringArrayVar(&buildPlatforms, "platform", nil, "Target platform (repeatable)")
- imagesBuildCmd.Flags().StringVar(&buildNetwork, "network", "", "Build network mode")
- imagesBuildCmd.Flags().StringVar(&buildProvider, "provider", "", "Build provider override")
- imagesBuildCmd.Flags().BoolVar(&buildNoCache, "no-cache", false, "Disable build cache")
- imagesBuildCmd.Flags().BoolVar(&buildPull, "pull", false, "Always pull referenced base images")
- imagesBuildCmd.Flags().BoolVar(&buildPush, "push", false, "Push the image after building")
- imagesBuildCmd.Flags().BoolVar(&buildLoad, "load", false, "Load the image into the local Docker daemon")
-
- ImagesCmd.AddCommand(imagesBuildsCmd)
- imagesBuildsCmd.Flags().IntVarP(&buildsLimit, "limit", "n", 0, "Number of builds to show (server default 20)")
- imagesBuildsCmd.Flags().IntVar(&buildsStart, "start", 0, cmdutil.StartFlagUsage)
- imagesBuildsCmd.Flags().BoolVarP(&buildsAll, "all", "a", false, cmdutil.AllFlagUsage)
- imagesBuildsCmd.Flags().StringVar(&buildsStatus, "status", "", "Filter by status")
- imagesBuildsCmd.Flags().StringVar(&buildsProvider, "provider", "", "Filter by provider")
-
- imagesBuildsCmd.AddCommand(imagesBuildsGetCmd)
-}
-
var buildRef = cmdutil.ResourceRef[image.BuildRecord, image.BuildRecord]{
EnvironmentScoped: true,
Singular: "build", Plural: "builds",
IDHint: "the identifier", ListCmd: "arcane-cli images builds",
GetPath: types.ImageBuild, ListPath: types.ImageBuilds,
- Matches: func(item image.BuildRecord, lower, original string) bool { return strings.EqualFold(item.ID, original) },
- Label: func(item image.BuildRecord) string { return item.ID },
- Promote: func(item image.BuildRecord) *image.BuildRecord { return &item },
+ Matches: func(item image.BuildRecord, lower, original string) bool { return strings.EqualFold(item.ID, original) },
+ Label: func(item image.BuildRecord) string { return item.ID },
+ Promote: func(item image.BuildRecord) *image.BuildRecord { return &item },
+ IdentifierOf: func(item image.BuildRecord) string { return item.ID },
+}
+
+func readBuildStream(cmd *cobra.Command, reader io.Reader) error {
+ jsonMode := cmdutil.JSONOutputEnabled(cmd)
+ frames := make([]jsontext.Value, 0)
+ scanner := bufio.NewScanner(reader)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ done := false
+ for scanner.Scan() {
+ line := scanner.Text()
+ trimmed := strings.TrimSpace(line)
+ var frame struct {
+ Type string `json:"type"`
+ Done bool `json:"done"`
+ Error string `json:"error"`
+ }
+ framed := strings.HasPrefix(trimmed, "{") && json.Unmarshal([]byte(trimmed), &frame) == nil
+ if jsonMode && trimmed != "" {
+ // Plain build log lines become JSON strings so stdout stays one array.
+ value, _ := json.Marshal(line)
+ frames = append(frames, jsontext.Value(kit.Ternary(framed, []byte(trimmed), value)))
+ }
+ if framed {
+ if frame.Error != "" {
+ return fmt.Errorf("build error: %s", frame.Error)
+ }
+ if frame.Done {
+ done = true
+ continue
+ }
+ if frame.Type != "" {
+ continue
+ }
+ }
+ if !jsonMode {
+ _, _ = fmt.Fprintln(output.Stdout(), line)
+ }
+ }
+ if scanErr := scanner.Err(); scanErr != nil {
+ return fmt.Errorf("failed to read build stream: %w", scanErr)
+ }
+ if !done {
+ return errors.New("build stream ended without completion frame")
+ }
+ if jsonMode {
+ return cmdutil.PrintJSON(frames)
+ }
+ output.Success("Image built successfully")
+ return nil
}
diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.go
index 91d923ef5..832478944 100644
--- a/cli/pkg/images/updates/cmd.go
+++ b/cli/pkg/images/updates/cmd.go
@@ -1,9 +1,12 @@
package updates
import (
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"errors"
"fmt"
"maps"
+ "net/http"
"slices"
"strconv"
@@ -16,168 +19,164 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var jsonOutput bool
-
-// UpdatesCmd is the parent command for image update operations.
-var UpdatesCmd = &cobra.Command{
- Use: "updates",
- Short: "Check for image updates",
+// Command builds the updates command tree.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "updates",
+ Short: "Check for image updates",
+ }
+ command.AddCommand(newCheckCmd(), newCheckAllCmd(), newCheckImageCmd(), newSummaryCmd())
+ return command
}
-var checkAll bool
-
-// checkAllBody is an empty JSON object; older servers reject check-all without a body.
-var checkAllBody = struct{}{}
-
-var checkCmd = &cobra.Command{
- Use: "check [image-ref...]",
- Short: "Check image references for updates",
- Long: "Check image references for updates.\n\nWith a single reference the update status is checked directly; with " +
- "multiple references a batch check is performed. With --all every image is checked.",
- Args: cobra.ArbitraryArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- if checkAll {
- if len(args) > 0 {
- return errors.New("--all cannot be combined with image references")
- }
-
- result, checkAllUpdatesErr := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), checkAllBody)
- if checkAllUpdatesErr != nil {
- return fmt.Errorf("failed to check all updates: %w", checkAllUpdatesErr)
+func newCheckCmd() *cobra.Command {
+ var opts struct {
+ all bool
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeFleet},
+ Use: "check [image-ref...]",
+ Short: "Check image references for updates",
+ Long: "Check image references for updates.\n\nWith a single reference the update status is checked directly; with " +
+ "multiple references a batch check is performed. With --all every image is checked.",
+ Args: cobra.ArbitraryArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- return printBatchResults(cmd, result.Data)
- }
- if len(args) == 0 {
- return errors.New("at least one image reference is required (or use --all)")
- }
+ if opts.all {
+ if len(args) > 0 {
+ return errors.New("--all cannot be combined with image references")
+ }
- if len(args) > 1 {
- result, checkBatchUpdatesErr := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
- if checkBatchUpdatesErr != nil {
- return fmt.Errorf("failed to check updates: %w", checkBatchUpdatesErr)
+ result, checkAllUpdatesErr := c.PostJSON[jsontext.Value](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), struct{}{})
+ if checkAllUpdatesErr != nil {
+ return fmt.Errorf("failed to check all updates: %w", checkAllUpdatesErr)
+ }
+ return printBatchResults(cmd, result.Data)
}
- return printBatchResults(cmd, result.Data)
- }
- result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))
- if err != nil {
- return fmt.Errorf("failed to check updates: %w", err)
- }
+ if len(args) == 0 {
+ return errors.New("at least one image reference is required (or use --all)")
+ }
- if app, ok := runtime.From(cmd.Context()); ok && app != nil && app.FleetConfirmed && result.Data.Error != "" {
- return fmt.Errorf("failed to check updates: %s", result.Data.Error)
- }
+ if len(args) > 1 {
+ result, checkBatchUpdatesErr := c.PostJSON[jsontext.Value](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
+ if checkBatchUpdatesErr != nil {
+ return fmt.Errorf("failed to check updates: %w", checkBatchUpdatesErr)
+ }
+ return printBatchResults(cmd, result.Data)
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ result, err := c.GetJSON[jsontext.Value](cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to check updates: %w", err)
+ }
- output.Header("Image Update Status")
- output.KeyValue("Image", args[0])
- output.KeyValue("Has Update", strconv.FormatBool(result.Data.HasUpdate))
- if result.Data.HasUpdate {
- output.KeyValue("Update Type", result.Data.UpdateType)
- output.KeyValue("Current Version", result.Data.CurrentVersion)
- output.KeyValue("Latest Version", result.Data.LatestVersion)
- }
- output.KeyValue("Check Time", result.Data.CheckTime.String())
- output.KeyValue("Response Time", fmt.Sprintf("%dms", result.Data.ResponseTimeMs))
- return nil
- },
+ var data imageupdate.Response
+ if decodeErr := json.Unmarshal(result.Data, &data); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
+ if app, ok := runtime.From(cmd.Context()); ok && app != nil && app.FleetConfirmed && data.Error != "" {
+ return fmt.Errorf("failed to check updates: %s", data.Error)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(result.Data)
+ }
+ return printUpdateStatus(data, args[0])
+ },
+ }
+ command.Flags().BoolVar(&opts.all, "all", false, "Check every image for updates")
+ return command
}
-var checkAllCmd = &cobra.Command{
- Use: "check-all",
- Hidden: true,
- Short: "Check all images for updates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newCheckAllCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeFleet},
+ Use: "check-all",
+ Hidden: true,
+ Short: "Check all images for updates",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), checkAllBody)
- if err != nil {
- return fmt.Errorf("failed to check all updates: %w", err)
- }
+ result, err := c.PostJSON[jsontext.Value](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), struct{}{})
+ if err != nil {
+ return fmt.Errorf("failed to check all updates: %w", err)
+ }
- return printBatchResults(cmd, result.Data)
- },
+ return printBatchResults(cmd, result.Data)
+ },
+ }
}
-var checkImageCmd = &cobra.Command{
- Use: "check-image <image-id>",
- Hidden: true,
- Short: "Check specific image for updates",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheckById(c.EnvID(), args[0]))
- if err != nil {
- return fmt.Errorf("failed to check image update: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newCheckImageCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "check-image <image-id>",
+ Hidden: true,
+ Short: "Check specific image for updates",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Image Update Status")
- output.KeyValue("Has Update", strconv.FormatBool(result.Data.HasUpdate))
- if result.Data.HasUpdate {
- output.KeyValue("Update Type", result.Data.UpdateType)
- output.KeyValue("Current Version", result.Data.CurrentVersion)
- output.KeyValue("Latest Version", result.Data.LatestVersion)
- }
- output.KeyValue("Check Time", result.Data.CheckTime.String())
- output.KeyValue("Response Time", fmt.Sprintf("%dms", result.Data.ResponseTimeMs))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[imageupdate.Response]{
+ Method: http.MethodGet,
+ Path: types.ImageUpdatesCheckById(c.EnvID(), args[0]),
+ FailureMessage: "failed to check image update",
+ Render: func(data imageupdate.Response) error { return printUpdateStatus(data, "") },
+ })
+ },
+ }
}
-var summaryCmd = &cobra.Command{
- Use: "summary",
- Short: "Get image updates summary",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[imageupdate.Summary](cmd.Context(), types.ImageUpdatesSummary(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get summary: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newSummaryCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "summary",
+ Short: "Get image updates summary",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Image Updates Summary")
- output.KeyValue("Total Images", strconv.Itoa(result.Data.TotalImages))
- output.KeyValue("Images with Updates", strconv.Itoa(result.Data.ImagesWithUpdates))
- output.KeyValue("Digest Updates", strconv.Itoa(result.Data.DigestUpdates))
- output.KeyValue("Errors", strconv.Itoa(result.Data.ErrorsCount))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[imageupdate.Summary]{
+ Method: http.MethodGet,
+ Path: types.ImageUpdatesSummary(c.EnvID()),
+ FailureMessage: "failed to get summary",
+ Render: func(data imageupdate.Summary) error {
+ output.Header("Image Updates Summary")
+ output.KeyValue("Total Images", strconv.Itoa(data.TotalImages))
+ output.KeyValue("Images with Updates", strconv.Itoa(data.ImagesWithUpdates))
+ output.KeyValue("Digest Updates", strconv.Itoa(data.DigestUpdates))
+ output.KeyValue("Errors", strconv.Itoa(data.ErrorsCount))
+ return nil
+ },
+ })
+ },
+ }
}
// printBatchResults prints every requested reference, including
// up-to-date and failed checks.
-func printBatchResults(cmd *cobra.Command, result imageupdate.BatchResponse) error {
+func printBatchResults(cmd *cobra.Command, raw jsontext.Value) error {
+ var result imageupdate.BatchResponse
+ if decodeErr := json.Unmarshal(raw, &result); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
if app, ok := runtime.From(cmd.Context()); ok && app != nil && app.FleetConfirmed {
for ref, update := range result {
if update == nil {
@@ -188,8 +187,8 @@ func printBatchResults(cmd *cobra.Command, result imageupdate.BatchResponse) err
}
}
}
- if jsonOutput {
- return cmdutil.PrintJSON(result)
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(raw)
}
refs := slices.Sorted(maps.Keys(result))
@@ -222,17 +221,18 @@ func printBatchResults(cmd *cobra.Command, result imageupdate.BatchResponse) err
return nil
}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeFleet, checkCmd, checkAllCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, summaryCmd)
- UpdatesCmd.AddCommand(checkCmd)
- checkCmd.Flags().BoolVar(&checkAll, "all", false, "Check every image for updates")
- UpdatesCmd.AddCommand(checkAllCmd)
- UpdatesCmd.AddCommand(checkImageCmd)
- UpdatesCmd.AddCommand(summaryCmd)
-
- checkCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- checkAllCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- checkImageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- summaryCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func printUpdateStatus(data imageupdate.Response, imageRef string) error {
+ output.Header("Image Update Status")
+ if imageRef != "" {
+ output.KeyValue("Image", imageRef)
+ }
+ output.KeyValue("Has Update", strconv.FormatBool(data.HasUpdate))
+ if data.HasUpdate {
+ output.KeyValue("Update Type", data.UpdateType)
+ output.KeyValue("Current Version", data.CurrentVersion)
+ output.KeyValue("Latest Version", data.LatestVersion)
+ }
+ output.KeyValue("Check Time", data.CheckTime.String())
+ output.KeyValue("Response Time", fmt.Sprintf("%dms", data.ResponseTimeMs))
+ return nil
}
diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.go
index ec5b40e7b..79f6e1fce 100644
--- a/cli/pkg/jobs/cmd.go
+++ b/cli/pkg/jobs/cmd.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/jobschedule"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
@@ -20,200 +21,197 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- jsonOutput bool
- requestID string
-)
-
-// JobsCmd is the parent command for background jobs and their schedules.
-var JobsCmd = &cobra.Command{
- Use: "jobs",
- Aliases: []string{"job"},
- Short: "Manage background jobs",
+// Command is the parent command for background jobs and their schedules.
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "jobs",
+ Aliases: []string{"job"},
+ Short: "Manage background jobs",
+ }
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ cmd.AddCommand(newSchedulesCmd())
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newRunCmd())
+ return cmd
}
-var schedulesCmd = &cobra.Command{
- Use: "schedules",
- Short: "Manage job schedule intervals",
+func newSchedulesCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "schedules",
+ Short: "Manage job schedule intervals",
+ }
+ cmd.AddCommand(newGetCmd())
+ cmd.AddCommand(newUpdateCmd())
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get",
- Short: "Get configured job schedule intervals",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newGetCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "get",
+ Short: "Get configured job schedule intervals",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- cfg, err := c.DoJSON[jobschedule.Config](cmd.Context(), http.MethodGet, types.JobSchedules(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to get job schedules: %w", err)
- }
+ cfg, err := c.DoJSON[jobschedule.Config](cmd.Context(), http.MethodGet, types.JobSchedules(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to get job schedules: %w", err)
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(cfg)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(cfg)
+ }
- output.Header("Job Schedules")
- output.KeyValue("Environment health interval", cfg.EnvironmentHealthInterval)
- output.KeyValue("Event cleanup interval", cfg.EventCleanupInterval)
- output.KeyValue("Expired sessions cleanup interval", cfg.ExpiredSessionsCleanupInterval)
- return nil
- },
+ output.Header("Job Schedules")
+ output.KeyValue("Environment health interval", cfg.EnvironmentHealthInterval)
+ output.KeyValue("Event cleanup interval", cfg.EventCleanupInterval)
+ output.KeyValue("Expired sessions cleanup interval", cfg.ExpiredSessionsCleanupInterval)
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-var (
- environmentHealthInterval string
- eventCleanupInterval string
- expiredSessionsCleanupInterval string
-)
-
-var updateCmd = &cobra.Command{
- Use: "update",
- Short: "Update job schedule intervals",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- var req jobschedule.Update
- if cmd.Flags().Changed("environment-health-interval") {
- req.EnvironmentHealthInterval = &environmentHealthInterval
- }
- if cmd.Flags().Changed("event-cleanup-interval") {
- req.EventCleanupInterval = &eventCleanupInterval
- }
- if cmd.Flags().Changed("expired-sessions-cleanup-interval") {
- req.ExpiredSessionsCleanupInterval = &expiredSessionsCleanupInterval
- }
-
- if req.EnvironmentHealthInterval == nil && req.EventCleanupInterval == nil && req.ExpiredSessionsCleanupInterval == nil {
- return errors.New("no updates provided (set at least one interval flag)")
- }
-
- result, err := c.PutJSON[jobschedule.Config](cmd.Context(), types.JobSchedules(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to update job schedules: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ environmentHealthInterval string
+ eventCleanupInterval string
+ expiredSessionsCleanupInterval string
+ }
+ cmd := &cobra.Command{
+ Use: "update",
+ Short: "Update job schedule intervals",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !slices.ContainsFunc([]string{"environment-health-interval", "event-cleanup-interval", "expired-sessions-cleanup-interval"}, cmd.Flags().Changed) {
+ return errors.New("no updates provided (set at least one interval flag)")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Job schedules updated")
- output.KeyValue("Environment health interval", result.Data.EnvironmentHealthInterval)
- output.KeyValue("Event cleanup interval", result.Data.EventCleanupInterval)
- output.KeyValue("Expired sessions cleanup interval", result.Data.ExpiredSessionsCleanupInterval)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[jobschedule.Config]{
+ Method: http.MethodPut,
+ Path: types.JobSchedules(c.EnvID()),
+ Body: jobschedule.Update{
+ EnvironmentHealthInterval: kit.Ternary(cmd.Flags().Changed("environment-health-interval"), &opts.environmentHealthInterval, nil),
+ EventCleanupInterval: kit.Ternary(cmd.Flags().Changed("event-cleanup-interval"), &opts.eventCleanupInterval, nil),
+ ExpiredSessionsCleanupInterval: kit.Ternary(cmd.Flags().Changed("expired-sessions-cleanup-interval"), &opts.expiredSessionsCleanupInterval, nil),
+ },
+ FailureMessage: "failed to update job schedules",
+ Render: func(data jobschedule.Config) error {
+ output.Success("Job schedules updated")
+ output.KeyValue("Environment health interval", data.EnvironmentHealthInterval)
+ output.KeyValue("Event cleanup interval", data.EventCleanupInterval)
+ output.KeyValue("Expired sessions cleanup interval", data.ExpiredSessionsCleanupInterval)
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ cmd.Flags().StringVar(&opts.environmentHealthInterval, "environment-health-interval", "", "Environment health job interval (cron expression)")
+ cmd.Flags().StringVar(&opts.eventCleanupInterval, "event-cleanup-interval", "", "Event cleanup job interval (cron expression)")
+ cmd.Flags().StringVar(&opts.expiredSessionsCleanupInterval, "expired-sessions-cleanup-interval", "", "Expired sessions cleanup job interval (cron expression)")
+ return cmd
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List background jobs",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.DoJSON[jobschedule.JobListResponse](cmd.Context(), http.MethodGet, types.Jobs(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to list jobs: %w", err)
- }
+func newListCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List background jobs",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
+ result, err := c.DoJSON[jobschedule.JobListResponse](cmd.Context(), http.MethodGet, types.Jobs(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to list jobs: %w", err)
+ }
- headers := []string{"ID", "NAME", "CATEGORY", "SCHEDULE", "NEXT RUN", "ENABLED"}
- rows := make([][]string, len(result.Jobs))
- for i, job := range result.Jobs {
- nextRun := "-"
- if job.NextRun != nil {
- nextRun = job.NextRun.Format(time.RFC3339)
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
}
- rows[i] = []string{
- job.ID,
- job.Name,
- job.Category,
- job.Schedule,
- nextRun,
- strconv.FormatBool(job.Enabled),
+
+ headers := []string{"ID", "NAME", "CATEGORY", "SCHEDULE", "NEXT RUN", "ENABLED"}
+ rows := make([][]string, len(result.Jobs))
+ for i, job := range result.Jobs {
+ nextRun := "-"
+ if job.NextRun != nil {
+ nextRun = job.NextRun.Format(time.RFC3339)
+ }
+ rows[i] = []string{
+ job.ID,
+ job.Name,
+ job.Category,
+ job.Schedule,
+ nextRun,
+ strconv.FormatBool(job.Enabled),
+ }
}
- }
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "jobs"}); tableErr != nil {
- return tableErr
- }
- return nil
- },
+ return cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "jobs"})
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-var runCmd = &cobra.Command{
- Use: "run <job-id>",
- Short: "Queue a background job now",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- id := requestID
- if id == "" {
- var value [16]byte
- _, _ = rand.Read(value[:])
- value[6] = (value[6] & 0x0f) | 0x40
- value[8] = (value[8] & 0x3f) | 0x80
- id = fmt.Sprintf("%x-%x-%x-%x-%x", value[0:4], value[4:6], value[6:8], value[8:10], value[10:16])
- }
- result, err := c.DoJSON[jobschedule.JobRunResponse](cmd.Context(), http.MethodPost, types.JobRun(c.EnvID(), args[0]), nil, http.Header{"Idempotency-Key": []string{id}})
- if err != nil {
- return fmt.Errorf("failed to queue job (reuse --request-id %s if delivery is uncertain): %w", id, err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
+func newRunCmd() *cobra.Command {
+ var opts struct {
+ requestID string
+ }
+ cmd := &cobra.Command{
+ Use: "run <job-id>",
+ Short: "Queue a background job now",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if !result.Success {
- return fmt.Errorf("job %s failed: %s", args[0], result.Message)
- }
- output.Success("%s", result.Message)
- output.KeyValue("Run ID", result.RunID)
- output.KeyValue("Status", string(result.Status))
- return nil
- },
-}
+ id := opts.requestID
+ if id == "" {
+ var value [16]byte
+ _, _ = rand.Read(value[:])
+ value[6] = (value[6] & 0x0f) | 0x40
+ value[8] = (value[8] & 0x3f) | 0x80
+ id = fmt.Sprintf("%x-%x-%x-%x-%x", value[0:4], value[4:6], value[6:8], value[8:10], value[10:16])
+ }
+ result, err := c.DoJSON[jobschedule.JobRunResponse](cmd.Context(), http.MethodPost, types.JobRun(c.EnvID(), args[0]), nil, http.Header{"Idempotency-Key": []string{id}})
+ if err != nil {
+ return fmt.Errorf("failed to queue job (reuse --request-id %s if delivery is uncertain): %w", id, err)
+ }
-func init() {
- cmdutil.SetResource(jobRef, runCmd)
- cmdutil.SetScope(cmdutil.ScopeResource, JobsCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, getCmd, listCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, updateCmd)
- JobsCmd.AddCommand(schedulesCmd)
- schedulesCmd.AddCommand(getCmd)
- schedulesCmd.AddCommand(updateCmd)
- JobsCmd.AddCommand(listCmd)
- JobsCmd.AddCommand(runCmd)
-
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- runCmd.Flags().StringVar(&requestID, "request-id", "", "Stable request ID to reuse when retrying an uncertain submission")
- runCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- updateCmd.Flags().StringVar(&environmentHealthInterval, "environment-health-interval", "", "Environment health job interval (cron expression)")
- updateCmd.Flags().StringVar(&eventCleanupInterval, "event-cleanup-interval", "", "Event cleanup job interval (cron expression)")
- updateCmd.Flags().StringVar(&expiredSessionsCleanupInterval, "expired-sessions-cleanup-interval", "", "Expired sessions cleanup job interval (cron expression)")
+ if !result.Success {
+ return fmt.Errorf("job %s failed: %s", args[0], result.Message)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
+ }
+ output.Success("%s", result.Message)
+ output.KeyValue("Run ID", result.RunID)
+ output.KeyValue("Status", string(result.Status))
+ return nil
+ },
+ }
+ cmdutil.SetResource(jobRef, cmd)
+ cmd.Flags().StringVar(&opts.requestID, "request-id", "", "Stable request ID to reuse when retrying an uncertain submission")
+ return cmd
}
var jobRef = cmdutil.ResourceRef[jobschedule.JobStatus, jobschedule.JobStatus]{
@@ -225,6 +223,7 @@ var jobRef = cmdutil.ResourceRef[jobschedule.JobStatus, jobschedule.JobStatus]{
}
return slices.DeleteFunc(result.Jobs, func(item jobschedule.JobStatus) bool { return !strings.EqualFold(item.ID, identifier) }), nil
},
- Label: func(item jobschedule.JobStatus) string { return item.Name + " (" + item.ID + ")" },
- Promote: func(item jobschedule.JobStatus) *jobschedule.JobStatus { return &item },
+ IdentifierOf: func(item jobschedule.JobStatus) string { return item.ID },
+ Label: func(item jobschedule.JobStatus) string { return item.Name + " (" + item.ID + ")" },
+ Promote: func(item jobschedule.JobStatus) *jobschedule.JobStatus { return &item },
}
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index 7c5cf2ecb..c8f3ac31a 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -1,574 +1,517 @@
package networks
import (
- "errors"
+ "cmp"
"fmt"
+ "net/http"
"net/url"
"strings"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/network"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
"github.com/getarcaneapp/arcane/cli/v2/pkg/containers"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- inUseOnlyFlag bool
- unusedOnlyFlag bool
-)
-
-var (
- networkCreateName string
- networkCreateDriver string
- networkCreateSubnet string
- networkCreateGateway string
- networkCreateIPRange string
- networkCreate bool
- networkCreateAttachable bool
- networkCreateIPv6 bool
- networkCreateLabels []string
- networkCreateOpts []string
-)
-
-var (
- connectAliases []string
- connectIPv4 string
- connectIPv6 string
-
- disconnectForce bool
-)
-
-// NetworksCmd is the parent command for network operations
-var NetworksCmd = &cobra.Command{
- Use: "networks",
- Aliases: []string{"network", "net", "n"},
- Short: "Manage networks",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List networks",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if inUseOnlyFlag && unusedOnlyFlag {
- return errors.New("--inuse and --unused cannot be used together")
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Filter server-side so that pagination and the reported totals apply to
- // the matching set rather than to whichever page happened to be fetched.
- query := url.Values{}
- if inUseOnlyFlag {
- query.Set("inUse", "true")
- }
- if unusedOnlyFlag {
- query.Set("inUse", "false")
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[network.Summary]{
- Resource: "networks",
- Endpoint: types.Networks(c.EnvID()),
- Params: cmdutil.ListParams{
- Resource: "networks",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- },
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED", "IN USE"},
- Row: func(net network.Summary) []string {
- inUse := "No"
- if net.InUse {
- inUse = "Yes"
- }
- return []string{
- shortID(net.ID),
- net.Name,
- net.Driver,
- net.Scope,
- net.Created.Format("2006-01-02 15:04"),
- inUse,
- }
- },
- })
- },
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "networks",
+ Aliases: []string{"network", "net", "n"},
+ Short: "Manage networks",
+ }
+ cmd.AddCommand(
+ newListCmd(),
+ newGetCmd(),
+ newDeleteCmd(),
+ newCountsCmd(),
+ newPruneCmd(),
+ newCreateCmd(),
+ newConnectCmd(),
+ newDisconnectCmd(),
+ newTopologyCmd(),
+ )
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get <network-id|name>",
- Short: "Get network details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- if !complete {
- result, inspectNetworkErr := c.GetJSON[network.Inspect](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
- if inspectNetworkErr != nil {
- return fmt.Errorf("failed to get network: %w", inspectNetworkErr)
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limitFlag int
+ startFlag int
+ allFlag bool
+ inUseOnlyFlag bool
+ unusedOnlyFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List networks",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- resolved = &result.Data
- }
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
+ // Filter server-side so that pagination and the reported totals apply to
+ // the matching set rather than to whichever page happened to be fetched.
+ query := url.Values{}
+ if opts.inUseOnlyFlag {
+ query.Set("inUse", "true")
+ }
+ if opts.unusedOnlyFlag {
+ query.Set("inUse", "false")
+ }
- output.Header("Network Details")
- output.KeyValue("ID", resolved.ID)
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("Driver", resolved.Driver)
- output.KeyValue("Scope", resolved.Scope)
- output.KeyValue("Created", resolved.Created.Format("2006-01-02 15:04"))
- output.KeyValue("Internal", resolved.Internal)
- output.KeyValue("Attachable", resolved.Attachable)
- output.KeyValue("Ingress", resolved.Ingress)
- output.KeyValue("Containers", len(resolved.ContainersList))
- return nil
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[network.Summary]{
+ Resource: "networks",
+ Endpoint: types.Networks(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "networks",
+ Limit: opts.limitFlag,
+ FallbackDefault: 20,
+ Start: opts.startFlag,
+ All: opts.allFlag,
+ },
+ Query: query,
+ Headers: []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED", "IN USE"},
+ Row: func(net network.Summary) []string {
+ return []string{
+ net.ID[:min(len(net.ID), 12)],
+ net.Name,
+ net.Driver,
+ net.Scope,
+ net.Created.Format("2006-01-02 15:04"),
+ kit.Ternary(net.InUse, "Yes", "No"),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of networks to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage)
+ cmd.Flags().BoolVar(&opts.inUseOnlyFlag, "inuse", false, "Only show networks currently in use")
+ cmd.Flags().BoolVar(&opts.unusedOnlyFlag, "unused", false, "Only show networks not in use")
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "inuse", "unused") }
+ return cmd
}
-var deleteCmd = &cobra.Command{
- Use: "delete <network-id|name>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a network",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- display := resolved.Name
- if display == "" {
- display = shortID(resolved.ID)
- }
-
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete network %s?", display))
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <network-id|name>",
+ Short: "Get network details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to delete network: %w", err)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, err := networkRef.Fetch(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
- output.Success("Network %s deleted successfully", display)
- return nil
- },
+ output.Header("Network Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Driver", resolved.Driver)
+ output.KeyValue("Scope", resolved.Scope)
+ output.KeyValue("Created", resolved.Created.Format("2006-01-02 15:04"))
+ output.KeyValue("Internal", resolved.Internal)
+ output.KeyValue("Attachable", resolved.Attachable)
+ output.KeyValue("Ingress", resolved.Ingress)
+ output.KeyValue("Containers", len(resolved.ContainersList))
+ return nil
+ },
+ }
}
-var countsCmd = &cobra.Command{
- Use: "counts",
- Short: "Get network usage counts",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[network.UsageCounts](cmd.Context(), types.NetworksCounts(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get network counts: %w", err)
- }
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <network-id|name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a network",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- output.Header("Network Usage Counts")
- output.KeyValue("Total networks", result.Data.Total)
- output.KeyValue("In use", result.Data.Inuse)
- output.KeyValue("Unused", result.Data.Unused)
- return nil
- },
+ display := cmp.Or(resolved.Name, resolved.ID[:min(len(resolved.ID), 12)])
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.forceFlag,
+ Prompt: fmt.Sprintf("Are you sure you want to delete network %s?", display),
+ Path: types.Network(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to delete network",
+ SuccessMessage: fmt.Sprintf("Network %s deleted successfully", display),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Force deletion without confirmation")
+ return cmd
}
-var pruneCmd = &cobra.Command{
- Use: "prune",
- Short: "Remove unused networks",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to prune unused networks?")
+func newCountsCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "counts",
+ Short: "Get network usage counts",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[network.UsageCounts]{
+ Method: http.MethodGet,
+ Path: types.NetworksCounts(c.EnvID()),
+ FailureMessage: "failed to get network counts",
+ Render: func(data network.UsageCounts) error {
+ output.Header("Network Usage Counts")
+ output.KeyValue("Total networks", data.Total)
+ output.KeyValue("In use", data.Inuse)
+ output.KeyValue("Unused", data.Unused)
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
+}
- result, err := c.PostJSON[network.PruneReport](cmd.Context(), types.NetworksPrune(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to prune networks: %w", err)
- }
+func newPruneCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "prune",
+ Short: "Remove unused networks",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.forceFlag, "Are you sure you want to prune unused networks?")
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Networks pruned successfully")
- output.KeyValue("Deleted networks", len(result.Data.NetworksDeleted))
- output.KeyValue("Space Reclaimed", output.UnsignedBytes(result.Data.SpaceReclaimed))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[network.PruneReport]{
+ Method: http.MethodPost,
+ Path: types.NetworksPrune(c.EnvID()),
+ Body: nil,
+ FailureMessage: "failed to prune networks",
+ Render: func(data network.PruneReport) error {
+ output.Success("Networks pruned successfully")
+ output.KeyValue("Deleted networks", len(data.NetworksDeleted))
+ output.KeyValue("Space Reclaimed", output.UnsignedBytes(data.SpaceReclaimed))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Force prune without confirmation")
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a network",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ networkCreateName string
+ networkCreateDriver string
+ networkCreateSubnet string
+ networkCreateGateway string
+ networkCreateIPRange string
+ networkCreate bool
+ networkCreateAttachable bool
+ networkCreateIPv6 bool
+ networkCreateLabels []string
+ networkCreateOpts []string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a network",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- req := network.CreateRequest{
- Name: networkCreateName,
- Options: network.CreateOptions{
- Driver: networkCreateDriver,
- Internal: networkCreate,
- Attachable: networkCreateAttachable,
- EnableIPv6: networkCreateIPv6,
- },
- }
+ var ipam *network.IPAM
+ var options, labels map[string]string
- if networkCreateSubnet != "" || networkCreateGateway != "" || networkCreateIPRange != "" {
- req.Options.IPAM = &network.IPAM{
- Config: []network.IPAMConfig{{
- Subnet: networkCreateSubnet,
- Gateway: networkCreateGateway,
- IPRange: networkCreateIPRange,
- }},
+ if opts.networkCreateSubnet != "" || opts.networkCreateGateway != "" || opts.networkCreateIPRange != "" {
+ ipam = &network.IPAM{
+ Config: []network.IPAMConfig{{
+ Subnet: opts.networkCreateSubnet,
+ Gateway: opts.networkCreateGateway,
+ IPRange: opts.networkCreateIPRange,
+ }},
+ }
}
- }
- if len(networkCreateOpts) > 0 {
- req.Options.Options = make(map[string]string)
- for _, opt := range networkCreateOpts {
- parts := strings.SplitN(opt, "=", 2)
- if len(parts) == 2 {
- req.Options.Options[parts[0]] = parts[1]
+ if len(opts.networkCreateOpts) > 0 {
+ options = make(map[string]string)
+ for _, opt := range opts.networkCreateOpts {
+ parts := strings.SplitN(opt, "=", 2)
+ if len(parts) == 2 {
+ options[parts[0]] = parts[1]
+ }
}
}
- }
- if len(networkCreateLabels) > 0 {
- req.Options.Labels = make(map[string]string)
- for _, lbl := range networkCreateLabels {
- parts := strings.SplitN(lbl, "=", 2)
- if len(parts) == 2 {
- req.Options.Labels[parts[0]] = parts[1]
+ if len(opts.networkCreateLabels) > 0 {
+ labels = make(map[string]string)
+ for _, lbl := range opts.networkCreateLabels {
+ parts := strings.SplitN(lbl, "=", 2)
+ if len(parts) == 2 {
+ labels[parts[0]] = parts[1]
+ }
}
}
- }
-
- result, err := c.PostJSON[network.CreateResponse](cmd.Context(), types.Networks(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to create network: %w", err)
- }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Network %s created successfully", networkCreateName)
- output.KeyValue("ID", result.Data.ID)
- if result.Data.Warning != "" {
- output.Warning("%s", result.Data.Warning)
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[network.CreateResponse]{
+ Method: http.MethodPost,
+ Path: types.Networks(c.EnvID()),
+ Body: network.CreateRequest{
+ Name: opts.networkCreateName,
+ Options: network.CreateOptions{
+ Driver: opts.networkCreateDriver,
+ Internal: opts.networkCreate,
+ Attachable: opts.networkCreateAttachable,
+ EnableIPv6: opts.networkCreateIPv6,
+ IPAM: ipam,
+ Options: options,
+ Labels: labels,
+ },
+ },
+ FailureMessage: "failed to create network",
+ Render: func(data network.CreateResponse) error {
+ output.Success("Network %s created successfully", opts.networkCreateName)
+ output.KeyValue("ID", data.ID)
+ if data.Warning != "" {
+ output.Warning("%s", data.Warning)
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.networkCreateName, "name", "", "Network name (required)")
+ cmd.Flags().StringVar(&opts.networkCreateDriver, "driver", "", "Network driver (e.g. bridge, overlay)")
+ cmd.Flags().StringVar(&opts.networkCreateSubnet, "subnet", "", "Subnet in CIDR format")
+ cmd.Flags().StringVar(&opts.networkCreateGateway, "gateway", "", "IPv4 or IPv6 gateway for the subnet")
+ cmd.Flags().StringVar(&opts.networkCreateIPRange, "ip-range", "", "Allocate container IPs from a sub-range")
+ cmd.Flags().BoolVar(&opts.networkCreate, "internal", false, "Restrict external access to the network")
+ cmd.Flags().BoolVar(&opts.networkCreateAttachable, "attachable", false, "Allow manual container attachment")
+ cmd.Flags().BoolVar(&opts.networkCreateIPv6, "ipv6", false, "Enable IPv6 networking")
+ cmd.Flags().StringArrayVar(&opts.networkCreateLabels, "label", nil, "Label (KEY=VALUE)")
+ cmd.Flags().StringArrayVar(&opts.networkCreateOpts, "opt", nil, "Driver option (KEY=VALUE)")
+ _ = cmd.MarkFlagRequired("name")
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ return cmd
}
-var connectCmd = &cobra.Command{
- Use: "connect <network-id|name> <container-id|name>",
- Short: "Connect a container to a network",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- app, _ := runtime.From(cmd.Context())
- preview := app.PreviewEnabled()
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- containerID := args[1]
- if preview {
- dependent, _, resolveErr := containers.ContainerRef.Resolve(cmd.Context(), c, args[1], allowPrompt)
- if resolveErr != nil {
- return resolveErr
+func newConnectCmd() *cobra.Command {
+ var opts struct {
+ connectAliases []string
+ connectIPv4 string
+ connectIPv6 string
+ }
+ cmd := &cobra.Command{
+ Use: "connect <network-id|name> <container-id|name>",
+ Short: "Connect a container to a network",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- containerID = dependent.ID
- }
-
- req := network.ConnectContainerRequest{
- ContainerID: containerID,
- Aliases: connectAliases,
- IPv4Address: connectIPv4,
- IPv6Address: connectIPv6,
- }
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkConnect(c.EnvID(), resolved.ID), req)
- if err != nil {
- return fmt.Errorf("failed to connect container to network: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- display := resolved.Name
- if display == "" {
- display = shortID(resolved.ID)
- }
- output.Success("Container %s connected to network %s", args[1], display)
- return nil
- },
-}
-
-var disconnectCmd = &cobra.Command{
- Use: "disconnect <network-id|name> <container-id|name>",
- Short: "Disconnect a container from a network",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- app, _ := runtime.From(cmd.Context())
- preview := app.PreviewEnabled()
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- containerID := args[1]
- if preview {
- dependent, _, resolveErr := containers.ContainerRef.Resolve(cmd.Context(), c, args[1], allowPrompt)
- if resolveErr != nil {
- return resolveErr
+ app, _ := runtime.From(cmd.Context())
+ preview := app.PreviewEnabled()
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- containerID = dependent.ID
- }
- req := network.DisconnectContainerRequest{
- ContainerID: containerID,
- Force: disconnectForce,
- }
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.NetworkDisconnect(c.EnvID(), resolved.ID), req)
- if err != nil {
- return fmt.Errorf("failed to disconnect container from network: %w", err)
- }
+ containerID := args[1]
+ if preview {
+ dependent, _, resolveErr := containers.ContainerRef.Resolve(cmd.Context(), c, args[1], allowPrompt)
+ if resolveErr != nil {
+ return resolveErr
+ }
+ containerID = dependent.ID
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ req := network.ConnectContainerRequest{
+ ContainerID: containerID,
+ Aliases: opts.connectAliases,
+ IPv4Address: opts.connectIPv4,
+ IPv6Address: opts.connectIPv6,
+ }
- display := resolved.Name
- if display == "" {
- display = shortID(resolved.ID)
- }
- output.Success("Container %s disconnected from network %s", args[1], display)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.NetworkConnect(c.EnvID(), resolved.ID),
+ Body: req,
+ FailureMessage: "failed to connect container to network",
+ Render: func(base.MessageResponse) error {
+ display := cmp.Or(resolved.Name, resolved.ID[:min(len(resolved.ID), 12)])
+ output.Success("Container %s connected to network %s", args[1], display)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringArrayVar(&opts.connectAliases, "alias", nil, "Network-scoped alias for the container")
+ cmd.Flags().StringVar(&opts.connectIPv4, "ip", "", "Static IPv4 address")
+ cmd.Flags().StringVar(&opts.connectIPv6, "ip6", "", "Static IPv6 address")
+ return cmd
}
-var topologyCmd = &cobra.Command{
- Use: "topology",
- Short: "Show the network topology",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[network.Topology](cmd.Context(), types.NetworksTopology(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get network topology: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- nodeNames := make(map[string]string, len(result.Data.Nodes))
- networkCount := 0
- containerCount := 0
- for _, node := range result.Data.Nodes {
- name := node.Name
- if name == "" {
- name = shortID(node.ID)
- }
- nodeNames[node.ID] = name
- switch node.Type {
- case network.TopologyNodeTypeNetwork:
- networkCount++
- case network.TopologyNodeTypeContainer:
- containerCount++
+func newDisconnectCmd() *cobra.Command {
+ var opts struct {
+ disconnectForce bool
+ }
+ cmd := &cobra.Command{
+ Use: "disconnect <network-id|name> <container-id|name>",
+ Short: "Disconnect a container from a network",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
-
- output.Header("Network Topology")
- output.KeyValue("Networks", networkCount)
- output.KeyValue("Containers", containerCount)
- output.KeyValue("Connections", len(result.Data.Edges))
- if len(result.Data.Edges) == 0 {
- return nil
- }
+ app, _ := runtime.From(cmd.Context())
+ preview := app.PreviewEnabled()
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := networkRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- headers := []string{"NETWORK", "CONTAINER", "IPV4", "IPV6"}
- rows := make([][]string, len(result.Data.Edges))
- for i, edge := range result.Data.Edges {
- source := nodeNames[edge.Source]
- if source == "" {
- source = shortID(edge.Source)
+ containerID := args[1]
+ if preview {
+ dependent, _, resolveErr := containers.ContainerRef.Resolve(cmd.Context(), c, args[1], allowPrompt)
+ if resolveErr != nil {
+ return resolveErr
+ }
+ containerID = dependent.ID
}
- target := nodeNames[edge.Target]
- if target == "" {
- target = shortID(edge.Target)
+
+ req := network.DisconnectContainerRequest{
+ ContainerID: containerID,
+ Force: opts.disconnectForce,
}
- rows[i] = []string{source, target, edge.IPv4Address, edge.IPv6Address}
- }
- return cmdutil.PrintTable(cmd, headers, rows)
- },
-}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, NetworksCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd, countsCmd, topologyCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, pruneCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, createCmd)
- NetworksCmd.AddCommand(listCmd)
- NetworksCmd.AddCommand(getCmd)
- NetworksCmd.AddCommand(deleteCmd)
- NetworksCmd.AddCommand(countsCmd)
- NetworksCmd.AddCommand(pruneCmd)
- NetworksCmd.AddCommand(createCmd)
- NetworksCmd.AddCommand(connectCmd)
- NetworksCmd.AddCommand(disconnectCmd)
- NetworksCmd.AddCommand(topologyCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of networks to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- listCmd.Flags().BoolVar(&inUseOnlyFlag, "inuse", false, "Only show networks currently in use")
- listCmd.Flags().BoolVar(&unusedOnlyFlag, "unused", false, "Only show networks not in use")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Prune command flags
- pruneCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force prune without confirmation")
- pruneCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Counts command flags
- countsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&networkCreateName, "name", "", "Network name (required)")
- createCmd.Flags().StringVar(&networkCreateDriver, "driver", "", "Network driver (e.g. bridge, overlay)")
- createCmd.Flags().StringVar(&networkCreateSubnet, "subnet", "", "Subnet in CIDR format")
- createCmd.Flags().StringVar(&networkCreateGateway, "gateway", "", "IPv4 or IPv6 gateway for the subnet")
- createCmd.Flags().StringVar(&networkCreateIPRange, "ip-range", "", "Allocate container IPs from a sub-range")
- createCmd.Flags().BoolVar(&networkCreate, "internal", false, "Restrict external access to the network")
- createCmd.Flags().BoolVar(&networkCreateAttachable, "attachable", false, "Allow manual container attachment")
- createCmd.Flags().BoolVar(&networkCreateIPv6, "ipv6", false, "Enable IPv6 networking")
- createCmd.Flags().StringArrayVar(&networkCreateLabels, "label", nil, "Label (KEY=VALUE)")
- createCmd.Flags().StringArrayVar(&networkCreateOpts, "opt", nil, "Driver option (KEY=VALUE)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
-
- // Connect command flags
- connectCmd.Flags().StringArrayVar(&connectAliases, "alias", nil, "Network-scoped alias for the container")
- connectCmd.Flags().StringVar(&connectIPv4, "ip", "", "Static IPv4 address")
- connectCmd.Flags().StringVar(&connectIPv6, "ip6", "", "Static IPv6 address")
- connectCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Disconnect command flags
- disconnectCmd.Flags().BoolVarP(&disconnectForce, "force", "f", false, "Force the disconnect")
- disconnectCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Topology command flags
- topologyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.NetworkDisconnect(c.EnvID(), resolved.ID),
+ Body: req,
+ FailureMessage: "failed to disconnect container from network",
+ Render: func(base.MessageResponse) error {
+ display := cmp.Or(resolved.Name, resolved.ID[:min(len(resolved.ID), 12)])
+ output.Success("Container %s disconnected from network %s", args[1], display)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.disconnectForce, "force", "f", false, "Force the disconnect")
+ return cmd
}
-func shortID(id string) string {
- if len(id) > 12 {
- return id[:12]
+func newTopologyCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "topology",
+ Short: "Show the network topology",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[network.Topology]{
+ Method: http.MethodGet,
+ Path: types.NetworksTopology(c.EnvID()),
+ FailureMessage: "failed to get network topology",
+ Render: func(data network.Topology) error {
+ nodeNames := make(map[string]string, len(data.Nodes))
+ networkCount := 0
+ containerCount := 0
+ for _, node := range data.Nodes {
+ nodeNames[node.ID] = cmp.Or(node.Name, node.ID[:min(len(node.ID), 12)])
+ switch node.Type {
+ case network.TopologyNodeTypeNetwork:
+ networkCount++
+ case network.TopologyNodeTypeContainer:
+ containerCount++
+ }
+ }
+
+ output.Header("Network Topology")
+ output.KeyValue("Networks", networkCount)
+ output.KeyValue("Containers", containerCount)
+ output.KeyValue("Connections", len(data.Edges))
+
+ if len(data.Edges) == 0 {
+ return nil
+ }
+
+ headers := []string{"NETWORK", "CONTAINER", "IPV4", "IPV6"}
+ rows := make([][]string, len(data.Edges))
+ for i, edge := range data.Edges {
+ source := cmp.Or(nodeNames[edge.Source], edge.Source[:min(len(edge.Source), 12)])
+ target := cmp.Or(nodeNames[edge.Target], edge.Target[:min(len(edge.Target), 12)])
+ rows[i] = []string{source, target, edge.IPv4Address, edge.IPv6Address}
+ }
+ return cmdutil.PrintTable(cmd, headers, rows)
+ },
+ })
+ },
}
- return id
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
var networkRef = cmdutil.ResourceRef[network.Inspect, network.Summary]{
@@ -578,22 +521,14 @@ var networkRef = cmdutil.ResourceRef[network.Inspect, network.Summary]{
IDHint: "the network ID",
ListCmd: "arcane networks list",
GetPath: types.Network,
+ IdentifierOf: func(data network.Inspect) string { return data.ID },
ListPath: types.Networks,
Matches: func(item network.Summary, identifierLower, original string) bool {
- idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
- if strings.Contains(idLower, identifierLower) {
- return true
- }
- if strings.Contains(strings.ToLower(item.Name), identifierLower) {
- return true
- }
- return strings.EqualFold(item.Name, original)
+ return strings.Contains(strings.ToLower(item.ID), identifierLower) ||
+ strings.Contains(strings.ToLower(item.Name), identifierLower) || strings.EqualFold(item.Name, original)
},
Label: func(match network.Summary) string {
- return fmt.Sprintf("%s (%s)", match.Name, shortID(match.ID))
+ return fmt.Sprintf("%s (%s)", match.Name, match.ID[:min(len(match.ID), 12)])
},
Promote: func(match network.Summary) *network.Inspect {
return &network.Inspect{
diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.go
index 878c0075d..c759c0ce5 100644
--- a/cli/pkg/projects/actions.go
+++ b/cli/pkg/projects/actions.go
@@ -1,6 +1,7 @@
package projects
import (
+ "cmp"
"errors"
"fmt"
"net/http"
@@ -12,346 +13,328 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/project"
- workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"
+ "github.com/getarcaneapp/arcane/types/v2/workspace"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- tagAdd string
- tagRemove string
- tagColor string
-
- buildServices []string
- buildProvider string
- buildPush bool
- buildLoad bool
-)
-
-var tagsCmd = &cobra.Command{
- Use: "tags",
- Short: "List project tags for the environment",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[[]project.TagOption](cmd.Context(), types.ProjectsTags(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to list project tags: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"NAME", "COLOR"}
- rows := make([][]string, len(result.Data))
- for i, tag := range result.Data {
- rows[i] = []string{tag.Name, string(tag.Color)}
- }
- return cmdutil.PrintTable(cmd, headers, rows)
- },
+func newTagsCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "tags",
+ Short: "List project tags for the environment",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]project.TagOption]{
+ Method: http.MethodGet,
+ Path: types.ProjectsTags(c.EnvID()),
+ FailureMessage: "failed to list project tags",
+ Render: func(data []project.TagOption) error {
+ headers := []string{"NAME", "COLOR"}
+ rows := make([][]string, len(data))
+ for i, tag := range data {
+ rows[i] = []string{tag.Name, string(tag.Color)}
+ }
+ return cmdutil.PrintTable(cmd, headers, rows)
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-var tagCmd = &cobra.Command{
- Use: "tag <project-id|name>",
- Short: "Attach or detach a project tag",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if (tagAdd == "") == (tagRemove == "") {
- return errors.New("exactly one of --add or --remove is required")
- }
- if tagRemove != "" && tagColor != "" {
- return errors.New("--color can only be used with --add")
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- body := project.UpdateTag{
- Name: tagAdd,
- Attached: tagAdd != "",
- Color: project.TagColor(tagColor),
- }
- if tagRemove != "" {
- body.Name = tagRemove
- }
-
- result, err := c.DoJSON[base.ApiResponse[project.UpdateTagResponse]](cmd.Context(), http.MethodPatch, types.ProjectTags(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to update project tag: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- names := make([]string, len(result.Data.Tags))
- for i, tag := range result.Data.Tags {
- names[i] = tag.Name
- }
- output.Success("Tags updated for project %s", resolved.Name)
- output.KeyValue("Tags", strings.Join(names, ", "))
- return nil
- },
+func newTagCmd() *cobra.Command {
+ var opts struct {
+ tagAdd string
+ tagRemove string
+ tagColor string
+ }
+ cmd := &cobra.Command{
+ Use: "tag <project-id|name>",
+ Short: "Attach or detach a project tag",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if (opts.tagAdd == "") == (opts.tagRemove == "") {
+ return errors.New("exactly one of --add or --remove is required")
+ }
+ if opts.tagRemove != "" && opts.tagColor != "" {
+ return errors.New("--color can only be used with --add")
+ }
+
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ body := project.UpdateTag{
+ Name: cmp.Or(opts.tagRemove, opts.tagAdd),
+ Attached: opts.tagAdd != "",
+ Color: project.TagColor(opts.tagColor),
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[project.UpdateTagResponse]{
+ Method: http.MethodPatch,
+ Path: types.ProjectTags(c.EnvID(), resolved.ID),
+ Body: body,
+ FailureMessage: "failed to update project tag",
+ Render: func(data project.UpdateTagResponse) error {
+ names := make([]string, len(data.Tags))
+ for i, tag := range data.Tags {
+ names[i] = tag.Name
+ }
+ output.Success("Tags updated for project %s", resolved.Name)
+ output.KeyValue("Tags", strings.Join(names, ", "))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.tagAdd, "add", "", "Tag name to attach")
+ cmd.Flags().StringVar(&opts.tagRemove, "remove", "", "Tag name to detach")
+ cmd.Flags().StringVar(&opts.tagColor, "color", "", "Tag color (used with --add)")
+ return cmd
}
-var archiveCmd = &cobra.Command{
- Use: "archive <project-id|name>",
- Short: "Archive a stopped project",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ProjectArchive(c.EnvID(), resolved.ID),
- FailureMessage: "failed to archive project",
- SuccessMessage: fmt.Sprintf("Project %s archived successfully", resolved.Name),
- JSON: jsonOutput,
- })
- },
+func newArchiveCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "archive <project-id|name>",
+ Short: "Archive a stopped project",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ProjectArchive(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to archive project",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", fmt.Sprintf("Project %s archived successfully", resolved.Name))
+ return nil
+ },
+ })
+ },
+ }
}
-var unarchiveCmd = &cobra.Command{
- Use: "unarchive <project-id|name>",
- Short: "Unarchive a project",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ProjectUnarchive(c.EnvID(), resolved.ID),
- FailureMessage: "failed to unarchive project",
- SuccessMessage: fmt.Sprintf("Project %s unarchived successfully", resolved.Name),
- JSON: jsonOutput,
- })
- },
-}
-
-var buildCmd = &cobra.Command{
- Use: "build <project-id|name>",
- Short: "Build project images",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- c.SetTimeout(30 * time.Minute)
-
- body := struct {
- Services []string `json:"services,omitempty"`
- Provider string `json:"provider,omitempty"`
- Push *bool `json:"push,omitempty"`
- Load *bool `json:"load,omitempty"`
- }{Services: buildServices, Provider: buildProvider}
- if cmd.Flags().Changed("push") {
- body.Push = &buildPush
- }
- if cmd.Flags().Changed("load") {
- body.Load = &buildLoad
- }
-
- resp, err := c.Post(cmd.Context(), types.ProjectBuild(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to build project images: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to build project images: %w", ensureSuccessStatusErr)
- }
-
- if printOperationStreamErr := printOperationStream(resp.Body); printOperationStreamErr != nil {
- return fmt.Errorf("failed to build project images: %w", printOperationStreamErr)
- }
-
- output.Success("Images built successfully for project %s", resolved.Name)
- return nil
- },
+func newUnarchiveCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "unarchive <project-id|name>",
+ Short: "Unarchive a project",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ProjectUnarchive(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to unarchive project",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", fmt.Sprintf("Project %s unarchived successfully", resolved.Name))
+ return nil
+ },
+ })
+ },
+ }
}
-var updateServicesCmd = &cobra.Command{
- Use: "upgrade <project-id|name> [services...]",
- Short: "Pull latest images and recreate services (all services when none are given)",
- Args: cobra.MinimumNArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- c.SetTimeout(30 * time.Minute)
-
- body := struct {
- Services []string `json:"services,omitempty"`
- }{Services: args[1:]}
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.ProjectUpdateServices(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to update project services: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Services updated successfully for project %s", resolved.Name)
- return nil
- },
+func newBuildCmd() *cobra.Command {
+ var opts struct {
+ buildServices []string
+ buildProvider string
+ buildPush bool
+ buildLoad bool
+ }
+ cmd := &cobra.Command{
+ Use: "build <project-id|name>",
+ Short: "Build project images",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
+ endpoint: types.ProjectBuild,
+ failureMessage: "failed to build project images",
+ successMessage: "Images built successfully for project %s",
+ body: project.BuildRequest{
+ Services: opts.buildServices,
+ Provider: opts.buildProvider,
+ Push: kit.Ternary(cmd.Flags().Changed("push"), &opts.buildPush, nil),
+ Load: kit.Ternary(cmd.Flags().Changed("load"), &opts.buildLoad, nil),
+ },
+ })
+ },
+ }
+ cmd.Flags().StringArrayVar(&opts.buildServices, "service", nil, "Service to build (repeatable; all services with build directives when omitted)")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.buildProvider, "provider", "", "", "Build provider override", "local", "depot")
+ cmd.Flags().BoolVar(&opts.buildPush, "push", false, "Push built images")
+ cmd.Flags().BoolVar(&opts.buildLoad, "load", false, "Load built images into Docker")
+ return cmd
}
-var workspaceCmd = &cobra.Command{
- Use: "workspace",
- Short: "Work with project workspace files",
+func newUpdateServicesCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "upgrade <project-id|name> [services...]",
+ Short: "Pull latest images and recreate services (all services when none are given)",
+ Args: cobra.MinimumNArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ c.SetTimeout(30 * time.Minute)
+
+ body := project.UpdateServicesRequest{Services: args[1:]}
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ProjectUpdateServices(c.EnvID(), resolved.ID),
+ Body: body,
+ FailureMessage: "failed to update project services",
+ Render: func(base.MessageResponse) error {
+ output.Success("Services updated successfully for project %s", resolved.Name)
+ return nil
+ },
+ })
+ },
+ }
}
-var workspaceCatCmd = &cobra.Command{
- Use: "cat <project-id|name> <path>",
- Short: "Print a project workspace file",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- reqPath := types.ProjectWorkspaceFile(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])
- result, err := c.GetJSON[workspacetypes.FileContent](cmd.Context(), reqPath)
- if err != nil {
- return fmt.Errorf("failed to get workspace file: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {
- return fmt.Errorf("file %s has no inline content (%s); use `arcane projects workspace download` instead", args[1], result.Data.ReadOnlyReason)
- }
- _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)
- return nil
- },
+func newWorkspaceCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "workspace",
+ Short: "Work with project workspace files",
+ }
+ cmd.AddCommand(
+ newWorkspaceCatCmd(),
+ newWorkspaceDownloadCmd(),
+ newUpdateIncludesCmd(),
+ )
+ return cmd
}
-var workspaceDownloadCmd = &cobra.Command{
- Use: "download <project-id|name> <path> [output-file]",
- Short: "Download a project workspace file",
- Args: cobra.RangeArgs(2, 3),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- reqPath := types.ProjectWorkspaceFileDownload(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])
- resp, err := c.Get(cmd.Context(), reqPath)
- if err != nil {
- return fmt.Errorf("failed to download workspace file: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
- }
-
- outputFile := path.Base(args[1])
- if len(args) == 3 {
- outputFile = args[2]
- }
-
- file, err := os.Create(outputFile)
- if err != nil {
- return fmt.Errorf("failed to create file %s: %w", outputFile, err)
- }
- written, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading workspace file", !cmdutil.JSONOutputEnabled(cmd))
- closeErr := file.Close()
- if copyErr != nil {
- return fmt.Errorf("failed to write workspace file: %w", copyErr)
- }
- if closeErr != nil {
- return fmt.Errorf("failed to write workspace file: %w", closeErr)
- }
-
- output.Success("Downloaded %s (%d bytes) to %s", args[1], written, outputFile)
- return nil
- },
+func newWorkspaceCatCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "cat <project-id|name> <path>",
+ Short: "Print a project workspace file",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ reqPath := types.ProjectWorkspaceFile(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])
+ return cmdutil.Run(cmd, c, cmdutil.Spec[workspace.FileContent]{
+ Method: http.MethodGet,
+ Path: reqPath,
+ FailureMessage: "failed to get workspace file",
+ Render: func(data workspace.FileContent) error {
+ if data.Content == "" && data.ReadOnlyReason != "" {
+ return fmt.Errorf("file %s has no inline content (%s); use `arcane projects workspace download` instead", args[1], data.ReadOnlyReason)
+ }
+ _, _ = fmt.Fprint(output.Stdout(), data.Content)
+ return nil
+ },
+ })
+ },
+ }
}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeRead, tagsCmd)
- ProjectsCmd.AddCommand(tagsCmd)
- ProjectsCmd.AddCommand(tagCmd)
- ProjectsCmd.AddCommand(archiveCmd)
- ProjectsCmd.AddCommand(unarchiveCmd)
- ProjectsCmd.AddCommand(buildCmd)
- ProjectsCmd.AddCommand(updateServicesCmd)
- ProjectsCmd.AddCommand(workspaceCmd)
- workspaceCmd.AddCommand(workspaceCatCmd)
- workspaceCmd.AddCommand(workspaceDownloadCmd)
-
- tagCmd.Flags().StringVar(&tagAdd, "add", "", "Tag name to attach")
- tagCmd.Flags().StringVar(&tagRemove, "remove", "", "Tag name to detach")
- tagCmd.Flags().StringVar(&tagColor, "color", "", "Tag color (used with --add)")
-
- buildCmd.Flags().StringArrayVar(&buildServices, "service", nil, "Service to build (repeatable; all services with build directives when omitted)")
- buildCmd.Flags().StringVar(&buildProvider, "provider", "", "Build provider override")
- buildCmd.Flags().BoolVar(&buildPush, "push", false, "Push built images")
- buildCmd.Flags().BoolVar(&buildLoad, "load", false, "Load built images into Docker")
-
- tagsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- tagCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- updateServicesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- workspaceCatCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newWorkspaceDownloadCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "download <project-id|name> <path> [output-file]",
+ Short: "Download a project workspace file",
+ Args: cobra.RangeArgs(2, 3),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ reqPath := types.ProjectWorkspaceFileDownload(c.EnvID(), resolved.ID) + "?relativePath=" + url.QueryEscape(args[1])
+ resp, err := c.Get(cmd.Context(), reqPath)
+ if err != nil {
+ return fmt.Errorf("failed to download workspace file: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
+ }
+
+ outputFile := path.Base(args[1])
+ if len(args) == 3 {
+ outputFile = args[2]
+ }
+
+ file, err := os.Create(outputFile)
+ if err != nil {
+ return fmt.Errorf("failed to create file %s: %w", outputFile, err)
+ }
+ written, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading workspace file", !cmdutil.JSONOutputEnabled(cmd))
+ closeErr := file.Close()
+ if copyErr != nil {
+ return fmt.Errorf("failed to write workspace file: %w", copyErr)
+ }
+ if closeErr != nil {
+ return fmt.Errorf("failed to write workspace file: %w", closeErr)
+ }
+
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ }{outputFile, written})
+ }
+ output.Success("Downloaded %s (%d bytes) to %s", args[1], written, outputFile)
+ return nil
+ },
+ }
}
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index f0007893e..da7bcfce6 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -3,334 +3,287 @@ package projects
import (
"bufio"
"bytes"
+ "cmp"
+ "encoding/json/jsontext"
"encoding/json/v2"
- "errors"
"fmt"
- "io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
+ "slices"
"strconv"
"strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/project"
- workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"
+ "github.com/getarcaneapp/arcane/types/v2/workspace"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- projectsUpdatesFilter string
- projectsStatusFilter string
- projectsArchivedFilter string
- projectsLabelFilter string
- forceFlag bool
- jsonOutput bool
- destroyRemoveFiles bool
- destroyRemoveVolumes bool
-
- createName string
- createFile string
- createEnvFile string
- updateName string
- updateFile string
- updateEnvFile string
- includesFile string
-)
-
-// ProjectsCmd is the parent command for project operations
-var ProjectsCmd = &cobra.Command{
- Use: "projects",
- Aliases: []string{"project", "proj", "p"},
- Short: "Manage projects",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List projects",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectsList(cmd, false)
- },
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "projects",
+ Aliases: []string{"project", "proj", "p"},
+ Short: "Manage projects",
+ }
+ cmd.AddCommand(
+ newTagsCmd(),
+ newTagCmd(),
+ newArchiveCmd(),
+ newUnarchiveCmd(),
+ newBuildCmd(),
+ newUpdateServicesCmd(),
+ newWorkspaceCmd(),
+ newListCmd(),
+ newUpdatesCmd(),
+ newGetCmd(),
+ newUpCmd(),
+ newDownCmd(),
+ newRestartCmd(),
+ newRedeployCmd(),
+ newPullCmd(),
+ newCountsCmd(),
+ newDestroyCmd(),
+ newCreateCmd(),
+ newUpdateCmd(),
+ )
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ return cmd
}
-var updatesCmd = &cobra.Command{
- Use: "updates",
- Short: "List projects with available updates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectsList(cmd, true)
- },
+func newListCmd() *cobra.Command {
+ var opts projectListOptions
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List projects",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error { return runProjectList(cmd, opts) },
+ }
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of projects to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage+", including archived projects")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.projectsUpdatesFilter, "updates", "", "", "Filter by update status", "has_update", "up_to_date", "error", "unknown")
+ cmd.Flags().StringVar(&opts.projectsStatusFilter, "status", "", "Filter by status (comma-separated: running, stopped, partially running)")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.projectsArchivedFilter, "archived", "", "", "Archived filter", "true", "false", "all")
+ cmd.Flags().StringVar(&opts.projectsLabelFilter, "label", "", "Filter by container label (key or key=value)")
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
+func newUpdatesCmd() *cobra.Command {
+ var opts projectListOptions
+ cmd := &cobra.Command{
+ Use: "updates",
+ Short: "List projects with available updates",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error { return runProjectList(cmd, opts) },
}
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of projects to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage)
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
+}
- query := url.Values{}
- updatesFilter := strings.TrimSpace(projectsUpdatesFilter)
- if forceHasUpdateFilter {
- updatesFilter = "has_update"
- }
- if updatesFilter != "" {
- query.Set("updates", updatesFilter)
- }
- if projectsStatusFilter != "" {
- query.Set("status", projectsStatusFilter)
- }
- if labelFilter := strings.TrimSpace(projectsLabelFilter); labelFilter != "" {
- query.Set("label", labelFilter)
- }
- // The server excludes archived projects unless asked, so --all has to opt
- // into them explicitly to actually mean "everything".
- switch {
- case projectsArchivedFilter != "":
- query.Set("archived", projectsArchivedFilter)
- case allFlag:
- query.Set("archived", "all")
+func newDestroyCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ destroyRemoveFiles bool
+ destroyRemoveVolumes bool
}
+ cmd := &cobra.Command{
+ Use: "destroy <project-id|name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Destroy project and remove all containers",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- spec := cmdutil.ListSpec[project.Details]{
- Resource: "projects",
- Endpoint: types.Projects(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "projects", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"},
- Row: func(proj project.Details) []string {
- return []string{
- proj.ID,
- proj.Name,
- proj.Status,
- strconv.Itoa(proj.ServiceCount),
- strconv.Itoa(proj.RunningCount),
- proj.CreatedAt,
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
}
+
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.forceFlag,
+ Prompt: fmt.Sprintf("Are you sure you want to destroy project %s? This will remove all containers!", cmp.Or(resolved.Name, resolved.ID)),
+ Path: types.ProjectDestroy(c.EnvID(), resolved.ID),
+ Body: project.Destroy{RemoveFiles: &opts.destroyRemoveFiles, RemoveVolumes: opts.destroyRemoveVolumes},
+ FailureMessage: "failed to destroy project",
+ SuccessMessage: fmt.Sprintf("Project %s destroyed successfully", resolved.Name),
+ })
},
}
- if updatesFilter != "" {
- if !jsonOutput {
- output.Header("Project Updates")
- }
- spec.Headers = []string{"ID", "NAME", "STATUS", "UPDATES", "IMAGES", "UPDATED"}
- spec.Row = func(proj project.Details) []string {
- imageCount := 0
- updatedCount := 0
- if proj.UpdateInfo != nil {
- imageCount = proj.UpdateInfo.ImageCount
- updatedCount = proj.UpdateInfo.ImagesWithUpdates
- }
- status := "unknown"
- if proj.UpdateInfo != nil && strings.TrimSpace(proj.UpdateInfo.Status) != "" {
- status = proj.UpdateInfo.Status
- }
- return []string{
- proj.ID,
- proj.Name,
- proj.Status,
- status,
- strconv.Itoa(imageCount),
- strconv.Itoa(updatedCount),
- }
- }
- }
- return cmdutil.RunList(cmd, c, spec)
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Force destroy without confirmation")
+ cmd.Flags().BoolVar(&opts.destroyRemoveFiles, "remove-files", true, "Remove the project's files from disk")
+ cmd.Flags().BoolVar(&opts.destroyRemoveVolumes, "remove-volumes", false, "Remove the project's volumes")
+ return cmd
}
-var destroyCmd = &cobra.Command{
- Use: "destroy <project-id|name>",
- Aliases: []string{"rm", "remove"},
- Short: "Destroy project and remove all containers",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- if !forceFlag {
- display := resolved.Name
- if display == "" {
- display = resolved.ID
- }
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to destroy project %s? This will remove all containers!", display))
- if confirmErr != nil {
- return confirmErr
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <project-id|name>",
+ Short: "Get project details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, err := projectRef.Fetch(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- }
- resp, err := c.DeleteWithBody(cmd.Context(), types.ProjectDestroy(c.EnvID(), resolved.ID), project.Destroy{
- RemoveFiles: &destroyRemoveFiles,
- RemoveVolumes: destroyRemoveVolumes,
- })
- if err != nil {
- return fmt.Errorf("failed to destroy project: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to destroy project: %w", ensureSuccessStatusErr)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
- output.Success("Project %s destroyed successfully", resolved.Name)
- return nil
- },
+ output.Header("Project Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Status", resolved.Status)
+ output.KeyValue("Services", resolved.ServiceCount)
+ output.KeyValue("Running", resolved.RunningCount)
+ return nil
+ },
+ }
}
-var getCmd = &cobra.Command{
- Use: "get <project-id|name>",
- Short: "Get project details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, complete, err := projectRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+func newUpCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "up <project-id|name>",
+ Short: "Start project services",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
+ endpoint: types.ProjectUp,
+ failureMessage: "failed to start project",
+ successMessage: "Project %s started successfully",
+ })
+ },
+ }
+}
- if !complete {
- result, getProjectErr := c.GetJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID))
- if getProjectErr != nil {
- return fmt.Errorf("failed to get project: %w", getProjectErr)
+func newDownCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "down <project-id|name>",
+ Short: "Stop project services",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- resolved = &result.Data
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
- output.Header("Project Details")
- output.KeyValue("ID", resolved.ID)
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("Status", resolved.Status)
- output.KeyValue("Services", resolved.ServiceCount)
- output.KeyValue("Running", resolved.RunningCount)
- return nil
- },
-}
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
-var upCmd = &cobra.Command{
- Use: "up <project-id|name>",
- Short: "Start project services",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
- endpoint: types.ProjectUp,
- failureMessage: "failed to start project",
- successMessage: "Project %s started successfully",
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ProjectDown(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to stop project",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", fmt.Sprintf("Project %s stopped successfully", resolved.Name))
+ return nil
+ },
+ })
+ },
+ }
}
-var downCmd = &cobra.Command{
- Use: "down <project-id|name>",
- Short: "Stop project services",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newRestartCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "restart <project-id|name>",
+ Short: "Restart project services",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ProjectDown(c.EnvID(), resolved.ID),
- FailureMessage: "failed to stop project",
- SuccessMessage: fmt.Sprintf("Project %s stopped successfully", resolved.Name),
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ProjectRestart(c.EnvID(), resolved.ID),
+ FailureMessage: "failed to restart project",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", fmt.Sprintf("Project %s restarted successfully", resolved.Name))
+ return nil
+ },
+ })
+ },
+ }
}
-var restartCmd = &cobra.Command{
- Use: "restart <project-id|name>",
- Short: "Restart project services",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
-
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ProjectRestart(c.EnvID(), resolved.ID),
- FailureMessage: "failed to restart project",
- SuccessMessage: fmt.Sprintf("Project %s restarted successfully", resolved.Name),
- })
- },
+func newRedeployCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "redeploy <project-id|name>",
+ Short: "Redeploy project (pull images and restart)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
+ endpoint: types.ProjectRedeploy,
+ failureMessage: "failed to redeploy project",
+ successMessage: "Project %s redeployed successfully",
+ })
+ },
+ }
}
-var redeployCmd = &cobra.Command{
- Use: "redeploy <project-id|name>",
- Short: "Redeploy project (pull images and restart)",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
- endpoint: types.ProjectRedeploy,
- failureMessage: "failed to redeploy project",
- successMessage: "Project %s redeployed successfully",
- })
- },
+func newPullCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "pull <project-id|name>",
+ Short: "Pull latest images for project",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
+ endpoint: types.ProjectPull,
+ failureMessage: "failed to pull images",
+ successMessage: "Images pulled successfully for project %s",
+ })
+ },
+ }
}
-var pullCmd = &cobra.Command{
- Use: "pull <project-id|name>",
- Short: "Pull latest images for project",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runProjectStreamAction(cmd, args[0], projectStreamActionConfig{
- endpoint: types.ProjectPull,
- failureMessage: "failed to pull images",
- successMessage: "Images pulled successfully for project %s",
- })
- },
+type projectStreamFrame struct {
+ Log string `json:"log"`
+ Error string `json:"error"`
+ Done bool `json:"done"`
}
-// projectStreamActionConfig defines an NDJSON action that prints raw logs and returns terminal errors.
type projectStreamActionConfig struct {
+ body any
endpoint func(string, string) string
failureMessage string
successMessage string
@@ -350,7 +303,7 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectSt
// Streamed actions can take a long time as they may pull images.
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), cfg.endpoint(c.EnvID(), resolved.ID), nil)
+ resp, err := c.Post(cmd.Context(), cfg.endpoint(c.EnvID(), resolved.ID), cfg.body)
if err != nil {
return fmt.Errorf("%s: %w", cfg.failureMessage, err)
}
@@ -359,17 +312,9 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectSt
return fmt.Errorf("%s: %w", cfg.failureMessage, ensureSuccessStatusErr)
}
- if printOperationStreamErr := printOperationStream(resp.Body); printOperationStreamErr != nil {
- return fmt.Errorf("%s: %w", cfg.failureMessage, printOperationStreamErr)
- }
-
- output.Success(cfg.successMessage, resolved.Name)
- return nil
-}
-
-// printOperationStream prints NDJSON Docker logs and returns terminal errors, ignoring unknown frames.
-func printOperationStream(body io.Reader) error {
- scanner := bufio.NewScanner(body)
+ jsonMode := cmdutil.JSONOutputEnabled(cmd)
+ frames := make([]jsontext.Value, 0)
+ scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for scanner.Scan() {
@@ -378,330 +323,311 @@ func printOperationStream(body io.Reader) error {
continue
}
- var frame struct {
- Log string `json:"log"`
- Error string `json:"error"`
- Done bool `json:"done"`
- }
- if err := json.Unmarshal([]byte(line), &frame); err != nil {
+ var frame projectStreamFrame
+ if json.Unmarshal([]byte(line), &frame) != nil {
continue
}
+ if jsonMode {
+ frames = append(frames, jsontext.Value(line))
+ }
if frame.Error != "" {
- return errors.New(frame.Error)
+ return fmt.Errorf("%s: %s", cfg.failureMessage, frame.Error)
}
if frame.Done {
- return nil
+ break
}
- if frame.Log != "" {
+ if !jsonMode && frame.Log != "" {
_, _ = fmt.Fprintln(output.Stdout(), frame.Log)
}
}
- return scanner.Err()
-}
-
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new project from a Docker Compose file",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ if scanErr := scanner.Err(); scanErr != nil {
+ return fmt.Errorf("%s: %w", cfg.failureMessage, scanErr)
+ }
- composeBytes, err := os.ReadFile(createFile)
- if err != nil {
- return fmt.Errorf("failed to read compose file: %w", err)
- }
+ if jsonMode {
+ return cmdutil.PrintJSON(frames)
+ }
+ output.Success(cfg.successMessage, resolved.Name)
+ return nil
+}
- body := project.CreateProject{
- Name: createName,
- ComposeContent: string(composeBytes),
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ createName string
+ createFile string
+ createEnvFile string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a new project from a Docker Compose file",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if createEnvFile != "" {
- envBytes, readFileErr := os.ReadFile(createEnvFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read env file: %w", readFileErr)
+ composeBytes, err := os.ReadFile(opts.createFile)
+ if err != nil {
+ return fmt.Errorf("failed to read compose file: %w", err)
}
- body.EnvContent = new(string(envBytes))
- }
- // Creating can take a long time as it may pull images
- c.SetTimeout(30 * time.Minute)
+ body := project.CreateProject{
+ Name: opts.createName,
+ ComposeContent: string(composeBytes),
+ }
- projectJSON, err := json.Marshal(body)
- if err != nil {
- return fmt.Errorf("failed to encode project configuration: %w", err)
- }
- manifestJSON, err := json.Marshal(project.CreateProjectWorkspaceManifest{FileChanges: []project.WorkspaceFileChange{}})
- if err != nil {
- return fmt.Errorf("failed to encode project workspace manifest: %w", err)
- }
- var requestBody bytes.Buffer
- writer := multipart.NewWriter(&requestBody)
- if writeFieldErr := writer.WriteField("project", string(projectJSON)); writeFieldErr != nil {
- return fmt.Errorf("failed to write project configuration: %w", writeFieldErr)
- }
- if writeManifestErr := writer.WriteField("manifest", string(manifestJSON)); writeManifestErr != nil {
- return fmt.Errorf("failed to write project workspace manifest: %w", writeManifestErr)
- }
- if closeErr := writer.Close(); closeErr != nil {
- return fmt.Errorf("failed to finalize project request: %w", closeErr)
- }
+ if opts.createEnvFile != "" {
+ envBytes, readFileErr := os.ReadFile(opts.createEnvFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file: %w", readFileErr)
+ }
+ body.EnvContent = new(string(envBytes))
+ }
- resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, types.Projects(c.EnvID()), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
- if err != nil {
- return fmt.Errorf("failed to create project: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to create project: %w", ensureSuccessStatusErr)
- }
+ // Creating can take a long time as it may pull images
+ c.SetTimeout(30 * time.Minute)
- var result base.ApiResponse[project.CreateReponse]
- if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
- return decodeJSONErr
- }
+ projectJSON, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("failed to encode project configuration: %w", err)
+ }
+ manifestJSON, err := json.Marshal(project.CreateProjectWorkspaceManifest{FileChanges: []project.WorkspaceFileChange{}})
+ if err != nil {
+ return fmt.Errorf("failed to encode project workspace manifest: %w", err)
+ }
+ var requestBody bytes.Buffer
+ writer := multipart.NewWriter(&requestBody)
+ if writeFieldErr := writer.WriteField("project", string(projectJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write project configuration: %w", writeFieldErr)
+ }
+ if writeManifestErr := writer.WriteField("manifest", string(manifestJSON)); writeManifestErr != nil {
+ return fmt.Errorf("failed to write project workspace manifest: %w", writeManifestErr)
+ }
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize project request: %w", closeErr)
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, types.Projects(c.EnvID()), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
+ if err != nil {
+ return fmt.Errorf("failed to create project: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ responseBody, readErr := cmdutil.ReadJSONBody(resp)
+ if readErr != nil {
+ return fmt.Errorf("failed to create project: %w", readErr)
+ }
+ var result base.ApiResponse[jsontext.Value]
+ if decodeErr := json.Unmarshal(responseBody, &result); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result.Data)
+ }
+ var data project.CreateReponse
+ if decodeErr := json.Unmarshal(result.Data, &data); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
- output.Success("Project %s created successfully", result.Data.Name)
- output.Header("Project Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Status", result.Data.Status)
- output.KeyValue("Path", result.Data.Path)
- return nil
- },
+ output.Success("Project %s created successfully", data.Name)
+ output.Header("Project Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("Status", data.Status)
+ output.KeyValue("Path", data.Path)
+ return nil
+ },
+ }
+ cmd.Flags().StringVar(&opts.createName, "name", "", "Project name")
+ cmd.Flags().StringVarP(&opts.createFile, "file", "f", "", "Docker Compose file")
+ cmd.Flags().StringVar(&opts.createEnvFile, "env-file", "", "Environment file")
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("file")
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ return cmd
}
-var updateCmd = &cobra.Command{
- Use: "update <project-id|name>",
- Short: "Update an existing project",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ updateName string
+ updateFile string
+ updateEnvFile string
+ }
+ cmd := &cobra.Command{
+ Use: "update <project-id|name>",
+ Short: "Update an existing project",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- body := project.UpdateProject{}
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- if cmd.Flags().Changed("name") {
- body.Name = &updateName
- }
+ var composeContent, envContent *string
- if cmd.Flags().Changed("file") {
- composeBytes, readFileErr := os.ReadFile(updateFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read compose file: %w", readFileErr)
+ if cmd.Flags().Changed("file") {
+ composeBytes, readFileErr := os.ReadFile(opts.updateFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read compose file: %w", readFileErr)
+ }
+ composeContent = new(string(composeBytes))
}
- body.ComposeContent = new(string(composeBytes))
- }
- if cmd.Flags().Changed("env-file") {
- envBytes, readEnvFileErr := os.ReadFile(updateEnvFile)
- if readEnvFileErr != nil {
- return fmt.Errorf("failed to read env file: %w", readEnvFileErr)
+ if cmd.Flags().Changed("env-file") {
+ envBytes, readEnvFileErr := os.ReadFile(opts.updateEnvFile)
+ if readEnvFileErr != nil {
+ return fmt.Errorf("failed to read env file: %w", readEnvFileErr)
+ }
+ envContent = new(string(envBytes))
}
- body.EnvContent = new(string(envBytes))
- }
-
- result, err := c.PutJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID), body)
- if err != nil {
- return fmt.Errorf("failed to update project: %w", err)
- }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Project %s updated successfully", resolved.Name)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[project.Details]{
+ Method: http.MethodPut,
+ Path: types.Project(c.EnvID(), resolved.ID),
+ Body: project.UpdateProject{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.updateName, nil),
+ ComposeContent: composeContent,
+ EnvContent: envContent,
+ },
+ FailureMessage: "failed to update project",
+ Render: func(project.Details) error {
+ output.Success("Project %s updated successfully", resolved.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.updateName, "name", "", "New project name")
+ cmd.Flags().StringVarP(&opts.updateFile, "file", "f", "", "Docker Compose file")
+ cmd.Flags().StringVar(&opts.updateEnvFile, "env-file", "", "Environment file")
+ return cmd
}
-var updateIncludesCmd = &cobra.Command{
- Use: "update <project-id|name>",
- Aliases: []string{"update-includes"},
- Short: "Update an include file in a project workspace",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newUpdateIncludesCmd() *cobra.Command {
+ var opts struct {
+ includesFile string
+ }
+ cmd := &cobra.Command{
+ Use: "update <project-id|name>",
+ Aliases: []string{"update-includes"},
+ Short: "Update an include file in a project workspace",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
- if err != nil {
- return err
- }
+ resolved, _, err := projectRef.Resolve(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
- content, err := os.ReadFile(includesFile)
- if err != nil {
- return fmt.Errorf("failed to read include file: %w", err)
- }
+ content, err := os.ReadFile(opts.includesFile)
+ if err != nil {
+ return fmt.Errorf("failed to read include file: %w", err)
+ }
- current, err := c.GetJSON[workspacetypes.Workspace](cmd.Context(), types.ProjectWorkspace(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get project workspace: %w", err)
- }
+ current, err := c.GetJSON[workspace.Workspace](cmd.Context(), types.ProjectWorkspace(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to get project workspace: %w", err)
+ }
- relativePath := filepath.ToSlash(filepath.Base(includesFile))
- operation := project.FileOpCreateFile
- for _, entry := range current.Data.Files {
- if entry.RelativePath == relativePath && !entry.IsDirectory {
+ relativePath := filepath.ToSlash(filepath.Base(opts.includesFile))
+ operation := project.FileOpCreateFile
+ if slices.ContainsFunc(current.Data.Files, func(entry workspace.FileEntry) bool {
+ return entry.RelativePath == relativePath && !entry.IsDirectory
+ }) {
operation = project.FileOpUpdateFile
- break
}
- }
- uploadIndex := 0
- manifest := project.WorkspaceUpdateManifest{
- FileTreeRevision: current.Data.FileTreeRevision,
- FileChanges: []project.WorkspaceFileChange{{Operation: operation, RelativePath: relativePath, UploadIndex: &uploadIndex}},
- }
- manifestJSON, err := json.Marshal(manifest)
- if err != nil {
- return fmt.Errorf("failed to encode workspace manifest: %w", err)
- }
- var requestBody bytes.Buffer
- writer := multipart.NewWriter(&requestBody)
- if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
- return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
- }
- filePart, err := writer.CreateFormFile("files", filepath.Base(includesFile))
- if err != nil {
- return fmt.Errorf("failed to create workspace upload: %w", err)
- }
- if _, writeErr := filePart.Write(content); writeErr != nil {
- return fmt.Errorf("failed to write workspace upload: %w", writeErr)
- }
- if closeErr := writer.Close(); closeErr != nil {
- return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
- }
-
- resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.ProjectWorkspace(c.EnvID(), resolved.ID), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
- if err != nil {
- return fmt.Errorf("failed to update include file: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to update include file: %w", ensureSuccessStatusErr)
- }
+ uploadIndex := 0
+ manifest := project.WorkspaceUpdateManifest{
+ FileTreeRevision: current.Data.FileTreeRevision,
+ FileChanges: []project.WorkspaceFileChange{{Operation: operation, RelativePath: relativePath, UploadIndex: &uploadIndex}},
+ }
+ manifestJSON, err := json.Marshal(manifest)
+ if err != nil {
+ return fmt.Errorf("failed to encode workspace manifest: %w", err)
+ }
+ var requestBody bytes.Buffer
+ writer := multipart.NewWriter(&requestBody)
+ if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
+ }
+ filePart, err := writer.CreateFormFile("files", filepath.Base(opts.includesFile))
+ if err != nil {
+ return fmt.Errorf("failed to create workspace upload: %w", err)
+ }
+ if _, writeErr := filePart.Write(content); writeErr != nil {
+ return fmt.Errorf("failed to write workspace upload: %w", writeErr)
+ }
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
+ }
- if jsonOutput {
- var result base.ApiResponse[workspacetypes.Workspace]
- if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
- return decodeJSONErr
+ resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.ProjectWorkspace(c.EnvID(), resolved.ID), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
+ if err != nil {
+ return fmt.Errorf("failed to update include file: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ responseBody, readErr := cmdutil.ReadJSONBody(resp)
+ if readErr != nil {
+ return fmt.Errorf("failed to update include file: %w", readErr)
+ }
+ var result base.ApiResponse[jsontext.Value]
+ if decodeErr := json.Unmarshal(responseBody, &result); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result.Data)
}
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("Include file %s updated successfully for project %s", filepath.Base(includesFile), resolved.Name)
- return nil
- },
+ output.Success("Include file %s updated successfully for project %s", filepath.Base(opts.includesFile), resolved.Name)
+ return nil
+ },
+ }
+ cmd.Flags().StringVarP(&opts.includesFile, "file", "f", "", "Include file")
+ _ = cmd.MarkFlagRequired("file")
+ return cmd
}
-var countsCmd = &cobra.Command{
- Use: "counts",
- Short: "Get project counts",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[map[string]any](cmd.Context(), types.ProjectsCounts(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get project counts: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Project Counts")
- for k, v := range result.Data {
- output.KeyValue(k, v)
- }
- return nil
- },
-}
+func newCountsCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "counts",
+ Short: "Get project counts",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, ProjectsCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd, updatesCmd, countsCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, createCmd)
- ProjectsCmd.AddCommand(listCmd)
- ProjectsCmd.AddCommand(updatesCmd)
- ProjectsCmd.AddCommand(getCmd)
- ProjectsCmd.AddCommand(upCmd)
- ProjectsCmd.AddCommand(downCmd)
- ProjectsCmd.AddCommand(restartCmd)
- ProjectsCmd.AddCommand(redeployCmd)
- ProjectsCmd.AddCommand(pullCmd)
- ProjectsCmd.AddCommand(countsCmd)
- ProjectsCmd.AddCommand(destroyCmd)
- ProjectsCmd.AddCommand(createCmd)
- ProjectsCmd.AddCommand(updateCmd)
- workspaceCmd.AddCommand(updateIncludesCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage+", including archived projects")
- listCmd.Flags().StringVar(&projectsUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
- listCmd.Flags().StringVar(&projectsStatusFilter, "status", "", "Filter by status (comma-separated: running, stopped, partially running)")
- listCmd.Flags().StringVar(&projectsArchivedFilter, "archived", "", "Archived filter: 'true' for archived only, 'all' to include archived")
- listCmd.Flags().StringVar(&projectsLabelFilter, "label", "", "Filter by container label (key or key=value)")
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- updatesCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
- updatesCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- updatesCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- updatesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Counts command flags
- countsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Destroy command flags
- destroyCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force destroy without confirmation")
- destroyCmd.Flags().BoolVar(&destroyRemoveFiles, "remove-files", true, "Remove the project's files from disk")
- destroyCmd.Flags().BoolVar(&destroyRemoveVolumes, "remove-volumes", false, "Remove the project's volumes")
- destroyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&createName, "name", "", "Project name")
- createCmd.Flags().StringVarP(&createFile, "file", "f", "", "Docker Compose file")
- createCmd.Flags().StringVar(&createEnvFile, "env-file", "", "Environment file")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("file")
-
- // Update command flags
- updateCmd.Flags().StringVar(&updateName, "name", "", "New project name")
- updateCmd.Flags().StringVarP(&updateFile, "file", "f", "", "Docker Compose file")
- updateCmd.Flags().StringVar(&updateEnvFile, "env-file", "", "Environment file")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Update includes command flags
- updateIncludesCmd.Flags().StringVarP(&includesFile, "file", "f", "", "Include file")
- updateIncludesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = updateIncludesCmd.MarkFlagRequired("file")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[map[string]any]{
+ Method: http.MethodGet,
+ Path: types.ProjectsCounts(c.EnvID()),
+ FailureMessage: "failed to get project counts",
+ Render: func(data map[string]any) error {
+ output.Header("Project Counts")
+ for k, v := range data {
+ output.KeyValue(k, v)
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
var projectRef = cmdutil.ResourceRef[project.Details, project.Details]{
@@ -711,25 +637,94 @@ var projectRef = cmdutil.ResourceRef[project.Details, project.Details]{
IDHint: "the project ID",
ListCmd: "arcane projects list",
GetPath: types.Project,
+ IdentifierOf: func(data project.Details) string { return data.ID },
ListPath: types.Projects,
Matches: func(item project.Details, identifierLower, original string) bool {
- idLower := strings.ToLower(item.ID)
- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
- return true
- }
- if strings.Contains(idLower, identifierLower) {
- return true
- }
- if strings.Contains(strings.ToLower(item.Name), identifierLower) {
- return true
- }
- if strings.EqualFold(item.Name, original) {
- return true
- }
- return strings.Contains(strings.ToLower(item.Path), identifierLower)
+ return strings.Contains(strings.ToLower(item.ID), identifierLower) ||
+ strings.Contains(strings.ToLower(item.Name), identifierLower) || strings.EqualFold(item.Name, original) ||
+ strings.Contains(strings.ToLower(item.Path), identifierLower)
},
Label: func(match project.Details) string {
return fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, match.Status)
},
Promote: func(match project.Details) *project.Details { return &match },
}
+
+type projectListOptions struct {
+ limitFlag int
+ startFlag int
+ allFlag bool
+ projectsUpdatesFilter string
+ projectsStatusFilter string
+ projectsArchivedFilter string
+ projectsLabelFilter string
+}
+
+func runProjectList(cmd *cobra.Command, opts projectListOptions) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ query := url.Values{}
+ updatesFilter := kit.Ternary(cmd.Name() == "updates", "has_update", strings.TrimSpace(opts.projectsUpdatesFilter))
+ if updatesFilter != "" {
+ query.Set("updates", updatesFilter)
+ }
+ if opts.projectsStatusFilter != "" {
+ query.Set("status", opts.projectsStatusFilter)
+ }
+ if labelFilter := strings.TrimSpace(opts.projectsLabelFilter); labelFilter != "" {
+ query.Set("label", labelFilter)
+ }
+ // The server excludes archived projects unless asked, so --all has to opt
+ // into them explicitly to actually mean "everything".
+ switch {
+ case opts.projectsArchivedFilter != "":
+ query.Set("archived", opts.projectsArchivedFilter)
+ case opts.allFlag:
+ query.Set("archived", "all")
+ }
+
+ if updatesFilter != "" && !cmdutil.JSONOutputEnabled(cmd) {
+ output.Header("Project Updates")
+ }
+
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[project.Details]{
+ Resource: "projects",
+ Endpoint: types.Projects(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "projects", Limit: opts.limitFlag, FallbackDefault: 20, Start: opts.startFlag, All: opts.allFlag},
+ Query: query,
+ Headers: kit.Ternary(updatesFilter != "", []string{"ID", "NAME", "STATUS", "UPDATES", "IMAGES", "UPDATED"}, []string{"ID", "NAME", "STATUS", "SERVICES", "RUNNING", "CREATED"}),
+ Row: func(proj project.Details) []string {
+ if updatesFilter == "" {
+ return []string{
+ proj.ID,
+ proj.Name,
+ proj.Status,
+ strconv.Itoa(proj.ServiceCount),
+ strconv.Itoa(proj.RunningCount),
+ proj.CreatedAt,
+ }
+ }
+ imageCount := 0
+ updatedCount := 0
+ status := "unknown"
+ if proj.UpdateInfo != nil {
+ imageCount = proj.UpdateInfo.ImageCount
+ updatedCount = proj.UpdateInfo.ImagesWithUpdates
+ if strings.TrimSpace(proj.UpdateInfo.Status) != "" {
+ status = proj.UpdateInfo.Status
+ }
+ }
+ return []string{
+ proj.ID,
+ proj.Name,
+ proj.Status,
+ status,
+ strconv.Itoa(imageCount),
+ strconv.Itoa(updatedCount),
+ }
+ },
+ })
+}
diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.go
index 897a44499..a399acdfe 100644
--- a/cli/pkg/registries/cmd.go
+++ b/cli/pkg/registries/cmd.go
@@ -3,11 +3,13 @@ package registries
import (
"errors"
"fmt"
+ "net/http"
"strconv"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
@@ -15,379 +17,328 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-
- registryCreateURL string
- registryCreateUsername string
- registryCreateToken string
- registryCreateDescription string
- registryCreateInsecure bool
- registryCreateDisabled bool
- registryCreateType string
- registryCreateAWSKeyID string
- registryCreateAWSSecret string
- registryCreateAWSRegion string
-
- registryUpdateURL string
- registryUpdateUsername string
- registryUpdatePassword string
- registryUpdateEnabled bool
- registryUpdateDisabled bool
-)
-
-var RegistriesCmd = &cobra.Command{
- Use: "registries",
- Aliases: []string{"registry", "reg"},
- Short: "Manage container registries",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List container registries",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[containerregistry.ContainerRegistry]{
- Resource: "registries",
- Endpoint: types.ContainerRegistries(),
- Params: cmdutil.ListParams{
- Resource: "registries",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- },
- JSON: jsonOutput,
- Headers: []string{"ID", "URL", "USERNAME", "ENABLED", "INSECURE"},
- Row: func(reg containerregistry.ContainerRegistry) []string {
- enabled := "false"
- if reg.Enabled {
- enabled = "true"
- }
- insecure := "false"
- if reg.Insecure {
- insecure = "true"
- }
- return []string{
- reg.ID,
- reg.URL,
- reg.Username,
- enabled,
- insecure,
- }
- },
- })
- },
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "registries",
+ Aliases: []string{"registry", "reg"},
+ Short: "Manage container registries",
+ }
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newGetCmd())
+ cmd.AddCommand(newCreateCmd())
+ cmd.AddCommand(newTestCmd())
+ cmd.AddCommand(newUpdateCmd())
+ cmd.AddCommand(newDeleteCmd())
+ cmd.AddCommand(newUsageCmd())
+ return cmd
}
-var testCmd = &cobra.Command{
- Use: "test <registry-id>",
- Short: "Test container registry connection",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List container registries",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.ContainerRegistryTest(args[0]),
- FailureMessage: "failed to test registry",
- SuccessMessage: "Registry connection test successful",
- JSON: jsonOutput,
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[containerregistry.ContainerRegistry]{
+ Resource: "registries",
+ Endpoint: types.ContainerRegistries(),
+ Params: cmdutil.ListParams{
+ Resource: "registries",
+ Limit: opts.limit,
+ FallbackDefault: 20,
+ Start: opts.start,
+ All: opts.all,
+ },
+ Headers: []string{"ID", "URL", "USERNAME", "ENABLED", "INSECURE"},
+ Row: func(reg containerregistry.ContainerRegistry) []string {
+ return []string{
+ reg.ID,
+ reg.URL,
+ reg.Username,
+ strconv.FormatBool(reg.Enabled),
+ strconv.FormatBool(reg.Insecure),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of registries to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get <registry-id>",
- Short: "Get container registry details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get registry: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newTestCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "test <registry-id>",
+ Short: "Test container registry connection",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- output.Header("Registry Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("URL", result.Data.URL)
- output.KeyValue("Username", result.Data.Username)
- output.KeyValue("Enabled", result.Data.Enabled)
- output.KeyValue("Insecure", result.Data.Insecure)
- output.KeyValue("Created", result.Data.CreatedAt.Format("2006-01-02 15:04"))
- output.KeyValue("Updated", result.Data.UpdatedAt.Format("2006-01-02 15:04"))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.ContainerRegistryTest(args[0]),
+ FailureMessage: "failed to test registry",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", "Registry connection test successful")
+ return nil
+ },
+ })
+ },
+ }
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a container registry",
- SilenceUsage: true,
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- // No field on CreateContainerRegistryRequest carries omitempty, so Huma
- // marks all of them required — every key has to be present, including
- // description.
- req := map[string]any{
- "url": registryCreateURL,
- "registryType": registryCreateType,
- "username": registryCreateUsername,
- "token": registryCreateToken,
- "description": registryCreateDescription,
- "insecure": registryCreateInsecure,
- "enabled": !registryCreateDisabled,
- "awsAccessKeyId": registryCreateAWSKeyID,
- "awsSecretAccessKey": registryCreateAWSSecret,
- "awsRegion": registryCreateAWSRegion,
- }
-
- result, err := c.PostJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistries(), req)
- if err != nil {
- return fmt.Errorf("failed to create registry: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <registry-id>",
+ Short: "Get container registry details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- output.Success("Registry created successfully")
- output.Header("Registry Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("URL", result.Data.URL)
- output.KeyValue("Username", result.Data.Username)
- output.KeyValue("Type", result.Data.RegistryType)
- output.KeyValue("Enabled", result.Data.Enabled)
- output.KeyValue("Insecure", result.Data.Insecure)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[containerregistry.ContainerRegistry]{
+ Method: http.MethodGet,
+ Path: types.ContainerRegistry(args[0]),
+ FailureMessage: "failed to get registry",
+ Render: func(data containerregistry.ContainerRegistry) error {
+ output.Header("Registry Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("URL", data.URL)
+ output.KeyValue("Username", data.Username)
+ output.KeyValue("Enabled", data.Enabled)
+ output.KeyValue("Insecure", data.Insecure)
+ output.KeyValue("Created", data.CreatedAt.Format("2006-01-02 15:04"))
+ output.KeyValue("Updated", data.UpdatedAt.Format("2006-01-02 15:04"))
+ return nil
+ },
+ })
+ },
+ }
}
-var updateCmd = &cobra.Command{
- Use: "update <registry-id>",
- Short: "Update container registry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- if cmd.Flags().Changed("enabled") && cmd.Flags().Changed("disabled") {
- return errors.New("--enabled and --disabled are mutually exclusive")
- }
-
- // Every field on UpdateContainerRegistryRequest lacks omitempty, so Huma
- // requires all of them. They are all pointers though, so an explicit null
- // is valid and the service leaves those fields untouched.
- req := map[string]any{
- "url": nil,
- "username": nil,
- "token": nil,
- "description": nil,
- "insecure": nil,
- "enabled": nil,
- "registryType": nil,
- "awsAccessKeyId": nil,
- "awsSecretAccessKey": nil,
- "awsRegion": nil,
- }
-
- changed := false
- setField := func(key string, value any) {
- req[key] = value
- changed = true
- }
- if cmd.Flags().Changed("url") {
- setField("url", registryUpdateURL)
- }
- if cmd.Flags().Changed("username") {
- setField("username", registryUpdateUsername)
- }
- if cmd.Flags().Changed("password") {
- setField("token", registryUpdatePassword)
- }
- if cmd.Flags().Changed("enabled") {
- setField("enabled", registryUpdateEnabled)
- }
- if cmd.Flags().Changed("disabled") {
- setField("enabled", !registryUpdateDisabled)
- }
-
- if !changed {
- return errors.New("no updates provided; use --url, --username, --password, --enabled, or --disabled")
- }
-
- result, err := c.PutJSON[containerregistry.ContainerRegistry](cmd.Context(), types.ContainerRegistry(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update registry: %w", err)
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ url string
+ username string
+ token string
+ description string
+ insecure bool
+ disabled bool
+ enabled bool
+ registryType string
+ awsKeyID string
+ awsSecret string
+ awsRegion string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a container registry",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ req := containerregistry.CreateContainerRegistryRequest{
+ URL: opts.url,
+ RegistryType: opts.registryType,
+ Username: opts.username,
+ Token: opts.token,
+ Description: &opts.description,
+ Insecure: &opts.insecure,
+ Enabled: new(opts.enabled && !opts.disabled),
+ AWSAccessKeyID: opts.awsKeyID,
+ AWSSecretAccessKey: opts.awsSecret,
+ AWSRegion: opts.awsRegion,
+ }
- output.Success("Registry updated successfully")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[containerregistry.ContainerRegistry]{
+ Method: http.MethodPost,
+ Path: types.ContainerRegistries(),
+ Body: req,
+ FailureMessage: "failed to create registry",
+ Render: func(data containerregistry.ContainerRegistry) error {
+ output.Success("Registry created successfully")
+ output.Header("Registry Details")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("URL", data.URL)
+ output.KeyValue("Username", data.Username)
+ output.KeyValue("Type", data.RegistryType)
+ output.KeyValue("Enabled", data.Enabled)
+ output.KeyValue("Insecure", data.Insecure)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.url, "url", "", "Registry URL (e.g. ghcr.io, docker.io, registry.example.com)")
+ cmd.Flags().StringVar(&opts.username, "username", "", "Username")
+ cmd.Flags().StringVar(&opts.token, "token", "", "Access token or password")
+ cmd.Flags().StringVar(&opts.description, "description", "", "Description")
+ cmd.Flags().BoolVar(&opts.insecure, "insecure", false, "Allow insecure (HTTP) connections")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", true, "Enable registry")
+ cmd.Flags().BoolVar(&opts.disabled, "disabled", false, "Create registry in disabled state")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.registryType, "registry-type", "", "generic", "Registry type", "generic", "ecr")
+ cmd.Flags().StringVar(&opts.awsKeyID, "aws-access-key-id", "", "AWS Access Key ID (ECR only; omit both keys to use the host's IAM role)")
+ cmd.Flags().StringVar(&opts.awsSecret, "aws-secret-access-key", "", "AWS Secret Access Key (ECR only; omit both keys to use the host's IAM role)")
+ cmd.Flags().StringVar(&opts.awsRegion, "aws-region", "", "AWS region (ECR only)")
+ _ = cmd.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled") }
+ _ = cmd.MarkFlagRequired("url")
+ return cmd
}
-var deleteCmd = &cobra.Command{
- Use: "delete <registry-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete container registry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete registry %s?", args[0]))
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ url string
+ username string
+ password string
+ enabled bool
+ disabled bool
+ }
+ cmd := &cobra.Command{
+ Use: "update <registry-id>",
+ Short: "Update container registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ req := containerregistry.UpdateContainerRegistryRequest{
+ URL: kit.Ternary(cmd.Flags().Changed("url"), &opts.url, nil),
+ Username: kit.Ternary(cmd.Flags().Changed("username"), &opts.username, nil),
+ Token: kit.Ternary(cmd.Flags().Changed("password"), &opts.password, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled") || cmd.Flags().Changed("disabled"),
+ new(cmd.Flags().Changed("enabled") && opts.enabled || cmd.Flags().Changed("disabled") && !opts.disabled), nil),
+ }
- resp, err := c.Delete(cmd.Context(), types.ContainerRegistry(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete registry: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete registry: %w", ensureSuccessStatusErr)
- }
+ if req.URL == nil && req.Username == nil && req.Token == nil && req.Enabled == nil {
+ return errors.New("no updates provided; use --url, --username, --password, --enabled, or --disabled")
+ }
- output.Success("Registry deleted successfully")
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[containerregistry.ContainerRegistry]{
+ Method: http.MethodPut,
+ Path: types.ContainerRegistry(args[0]),
+ Body: req,
+ FailureMessage: "failed to update registry",
+ Render: func(data containerregistry.ContainerRegistry) error {
+ output.Success("Registry updated successfully")
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.url, "url", "", "Registry URL")
+ cmd.Flags().StringVar(&opts.username, "username", "", "Username")
+ cmd.Flags().StringVar(&opts.password, "password", "", "Password")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable registry")
+ cmd.Flags().BoolVar(&opts.disabled, "disabled", false, "Disable registry")
+ _ = cmd.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled") }
+ return cmd
}
-var usageCmd = &cobra.Command{
- Use: "usage",
- Aliases: []string{"pull-usage"},
- Short: "Show pull usage and rate limits for configured registries",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[containerregistry.PullUsageResponse](cmd.Context(), types.ContainerRegistriesPullUsage())
- if err != nil {
- return fmt.Errorf("failed to get registry pull usage: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- if len(result.Data.Registries) == 0 {
- output.Info("No registries configured")
- return nil
- }
-
- formatCount := func(value *int) string {
- if value == nil {
- return "-"
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <registry-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete container registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- return strconv.Itoa(*value)
- }
- headers := []string{"NAME", "REGISTRY", "PROVIDER", "LIMIT", "REMAINING", "USED", "OBSERVED", "CHECKED", "ERROR"}
- rows := make([][]string, len(result.Data.Registries))
- for i, usage := range result.Data.Registries {
- rows[i] = []string{
- usage.DisplayName,
- usage.Registry,
- usage.Provider,
- formatCount(usage.Limit),
- formatCount(usage.Remaining),
- formatCount(usage.Used),
- strconv.FormatInt(usage.ObservedPulls, 10),
- usage.CheckedAt.Format("2006-01-02 15:04"),
- usage.Error,
- }
- }
- return output.Table(headers, rows)
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete registry %s?", args[0]),
+ Path: types.ContainerRegistry(args[0]),
+ Body: nil,
+ FailureMessage: "failed to delete registry",
+ SuccessMessage: "Registry deleted successfully",
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return cmd
}
-func init() {
- RegistriesCmd.AddCommand(listCmd)
- RegistriesCmd.AddCommand(getCmd)
- RegistriesCmd.AddCommand(createCmd)
- RegistriesCmd.AddCommand(testCmd)
- RegistriesCmd.AddCommand(updateCmd)
- RegistriesCmd.AddCommand(deleteCmd)
- RegistriesCmd.AddCommand(usageCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of registries to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- testCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&registryCreateURL, "url", "", "Registry URL (e.g. ghcr.io, docker.io, registry.example.com)")
- createCmd.Flags().StringVar(&registryCreateUsername, "username", "", "Username")
- createCmd.Flags().StringVar(&registryCreateToken, "token", "", "Access token or password")
- createCmd.Flags().StringVar(&registryCreateDescription, "description", "", "Description")
- createCmd.Flags().BoolVar(&registryCreateInsecure, "insecure", false, "Allow insecure (HTTP) connections")
- createCmd.Flags().BoolVar(&registryCreateDisabled, "disabled", false, "Create registry in disabled state")
- createCmd.Flags().StringVar(&registryCreateType, "registry-type", "generic", "Registry type: generic or ecr")
- createCmd.Flags().StringVar(&registryCreateAWSKeyID, "aws-access-key-id", "", "AWS Access Key ID (ECR only; omit both keys to use the host's IAM role)")
- createCmd.Flags().StringVar(&registryCreateAWSSecret, "aws-secret-access-key", "", "AWS Secret Access Key (ECR only; omit both keys to use the host's IAM role)")
- createCmd.Flags().StringVar(&registryCreateAWSRegion, "aws-region", "", "AWS region (ECR only)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("url")
-
- updateCmd.Flags().StringVar(&registryUpdateURL, "url", "", "Registry URL")
- updateCmd.Flags().StringVar(&registryUpdateUsername, "username", "", "Username")
- updateCmd.Flags().StringVar(&registryUpdatePassword, "password", "", "Password")
- updateCmd.Flags().BoolVar(&registryUpdateEnabled, "enabled", false, "Enable registry")
- updateCmd.Flags().BoolVar(&registryUpdateDisabled, "disabled", false, "Disable registry")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newUsageCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "usage",
+ Aliases: []string{"pull-usage"},
+ Short: "Show pull usage and rate limits for configured registries",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- usageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[containerregistry.PullUsageResponse]{
+ Method: http.MethodGet,
+ Path: types.ContainerRegistriesPullUsage(),
+ FailureMessage: "failed to get registry pull usage",
+ Render: func(data containerregistry.PullUsageResponse) error {
+ if len(data.Registries) == 0 {
+ output.Info("No registries configured")
+ return nil
+ }
+
+ formatCount := func(value *int) string {
+ return kit.Ternary(value == nil, "-", strconv.Itoa(kit.FromPtr(value)))
+ }
+
+ headers := []string{"NAME", "REGISTRY", "PROVIDER", "LIMIT", "REMAINING", "USED", "OBSERVED", "CHECKED", "ERROR"}
+ rows := make([][]string, len(data.Registries))
+ for i, usage := range data.Registries {
+ rows[i] = []string{
+ usage.DisplayName,
+ usage.Registry,
+ usage.Provider,
+ formatCount(usage.Limit),
+ formatCount(usage.Remaining),
+ formatCount(usage.Used),
+ strconv.FormatInt(usage.ObservedPulls, 10),
+ usage.CheckedAt.Format("2006-01-02 15:04"),
+ usage.Error,
+ }
+ }
+ return output.Table(headers, rows)
+ },
+ })
+ },
+ }
}
diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.go
index 8e96a20b8..79489562a 100644
--- a/cli/pkg/repos/cmd.go
+++ b/cli/pkg/repos/cmd.go
@@ -2,6 +2,7 @@ package repos
import (
"fmt"
+ "net/http"
"net/url"
"os"
"strconv"
@@ -10,484 +11,497 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/gitops"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
-)
-
-// ReposCmd is the parent command for git repository operations.
-var ReposCmd = &cobra.Command{
- Use: "repos",
- Aliases: []string{"repo", "git-repositories", "git-repos"},
- Short: "Manage git repositories",
+// Command is the parent command for git repository operations.
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "repos",
+ Aliases: []string{"repo", "git-repositories", "git-repos"},
+ Short: "Manage git repositories",
+ }
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newCreateCmd())
+ cmd.AddCommand(newGetCmd())
+ cmd.AddCommand(newUpdateCmd())
+ cmd.AddCommand(newDeleteCmd())
+ cmd.AddCommand(newTestCmd())
+ cmd.AddCommand(newBranchesCmd())
+ cmd.AddCommand(newFilesCmd())
+ return cmd
}
-// --- create flags ---
-var (
- repoCreateName string
- repoCreateURL string
- repoCreateAuthType string
- repoCreateToken string
- repoCreateUsername string
- repoCreateSSHKey string
- repoCreateSSHHostKeyVerify string
- repoCreateAuthorName string
- repoCreateAuthorEmail string
- repoCreateSigningKey string
- repoCreateSigningKeyPass string
- repoCreateDescription string
- repoCreateEnabled bool
-)
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List git repositories",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
-// --- update flags ---
-var (
- repoUpdateName string
- repoUpdateURL string
- repoUpdateAuthType string
- repoUpdateToken string
- repoUpdateUsername string
- repoUpdateSSHKey string
- repoUpdateSSHHostKeyVerify string
- repoUpdateAuthorName string
- repoUpdateAuthorEmail string
- repoUpdateSigningKey string
- repoUpdateSigningKeyPass string
- repoUpdateDescription string
- repoUpdateEnabled bool
-)
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitRepository]{
+ Resource: "repositories",
+ Endpoint: types.GitRepositories(),
+ Params: cmdutil.ListParams{Resource: "repos", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "NAME", "URL", "AUTH TYPE", "ENABLED", "CREATED"},
+ Row: func(repo gitops.GitRepository) []string {
+ return []string{
+ repo.ID,
+ repo.Name,
+ repo.URL,
+ repo.AuthType,
+ strconv.FormatBool(repo.Enabled),
+ repo.CreatedAt.Format("2006-01-02 15:04:05"),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of repositories to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
+}
-// --- files flags ---
-var (
- filesBranch string
- filesPath string
-)
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ url string
+ authType string
+ token string
+ username string
+ sshKey string
+ sshHostKeyVerify string
+ authorName string
+ authorEmail string
+ signingKey string
+ signingKeyPass string
+ description string
+ enabled bool
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a git repository",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List git repositories",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[gitops.GitRepository]{
- Resource: "repositories",
- Endpoint: types.GitRepositories(),
- Params: cmdutil.ListParams{Resource: "repos", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "NAME", "URL", "AUTH TYPE", "ENABLED", "CREATED"},
- Row: func(repo gitops.GitRepository) []string {
- enabled := "false"
- if repo.Enabled {
- enabled = "true"
+ var sshKey string
+ if cmd.Flags().Changed("ssh-key") {
+ sshKeyData, readFileErr := os.ReadFile(opts.sshKey)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
}
- return []string{
- repo.ID,
- repo.Name,
- repo.URL,
- repo.AuthType,
- enabled,
- repo.CreatedAt.Format("2006-01-02 15:04:05"),
+ sshKey = string(sshKeyData)
+ }
+ var signingKey string
+ if cmd.Flags().Changed("signing-key") {
+ signingKeyData, readSigningKeyErr := os.ReadFile(opts.signingKey)
+ if readSigningKeyErr != nil {
+ return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
}
- },
- })
- },
+ signingKey = string(signingKeyData)
+ }
+
+ req := gitops.CreateRepositoryRequest{
+ Name: opts.name,
+ URL: opts.url,
+ AuthType: opts.authType,
+ Token: opts.token,
+ Username: opts.username,
+ SSHHostKeyVerification: opts.sshHostKeyVerify,
+ CommitAuthorName: opts.authorName,
+ CommitAuthorEmail: opts.authorEmail,
+ SigningKeyPassphrase: opts.signingKeyPass,
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled"), &opts.enabled, nil),
+ SSHKey: sshKey,
+ SigningKey: signingKey,
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.GitRepository]{
+ Method: http.MethodPost,
+ Path: types.GitRepositories(),
+ Body: req,
+ FailureMessage: "failed to create repository",
+ Render: func(data gitops.GitRepository) error {
+ output.Success("Repository created successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("URL", data.URL)
+ output.KeyValue("Auth Type", data.AuthType)
+ output.KeyValue("Enabled", data.Enabled)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Repository name")
+ cmd.Flags().StringVar(&opts.url, "url", "", "Repository URL")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.authType, "auth-type", "", "", "Authentication type", "none", "http", "ssh")
+ cmd.Flags().StringVar(&opts.token, "token", "", "Token for HTTP authentication")
+ cmd.Flags().StringVar(&opts.username, "username", "", "Username for HTTP authentication")
+ cmd.Flags().StringVar(&opts.sshKey, "ssh-key", "", "Path to SSH key file")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.sshHostKeyVerify, "ssh-host-key-verification", "", "", "SSH host key verification", "strict", "accept_new", "skip")
+ cmd.Flags().StringVar(&opts.authorName, "author-name", "", "Author name for commits Arcane pushes")
+ cmd.Flags().StringVar(&opts.authorEmail, "author-email", "", "Author email for commits Arcane pushes")
+ cmd.Flags().StringVar(&opts.signingKey, "signing-key", "", "Path to an armored OpenPGP private key used to sign commits")
+ cmd.Flags().StringVar(&opts.signingKeyPass, "signing-key-passphrase", "", "Passphrase for the signing key")
+ cmd.Flags().StringVar(&opts.description, "description", "", "Repository description")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", true, "Enable the repository")
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("url")
+ _ = cmd.MarkFlagRequired("auth-type")
+ return cmd
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a git repository",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- req := gitops.CreateRepositoryRequest{
- Name: repoCreateName,
- URL: repoCreateURL,
- AuthType: repoCreateAuthType,
- }
-
- if cmd.Flags().Changed("token") {
- req.Token = repoCreateToken
- }
- if cmd.Flags().Changed("username") {
- req.Username = repoCreateUsername
- }
- if cmd.Flags().Changed("ssh-key") {
- sshKeyData, readFileErr := os.ReadFile(repoCreateSSHKey)
- if readFileErr != nil {
- return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <repository>",
+ Short: "Get git repository details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- req.SSHKey = string(sshKeyData)
- }
- if cmd.Flags().Changed("ssh-host-key-verification") {
- req.SSHHostKeyVerification = repoCreateSSHHostKeyVerify
- }
- if cmd.Flags().Changed("author-name") {
- req.CommitAuthorName = repoCreateAuthorName
- }
- if cmd.Flags().Changed("author-email") {
- req.CommitAuthorEmail = repoCreateAuthorEmail
- }
- if cmd.Flags().Changed("signing-key") {
- signingKeyData, readSigningKeyErr := os.ReadFile(repoCreateSigningKey)
- if readSigningKeyErr != nil {
- return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
}
- req.SigningKey = string(signingKeyData)
- }
- if cmd.Flags().Changed("signing-key-passphrase") {
- req.SigningKeyPassphrase = repoCreateSigningKeyPass
- }
- if cmd.Flags().Changed("description") {
- req.Description = &repoCreateDescription
- }
- if cmd.Flags().Changed("enabled") {
- req.Enabled = &repoCreateEnabled
- }
-
- result, err := c.PostJSON[gitops.GitRepository](cmd.Context(), types.GitRepositories(), req)
- if err != nil {
- return fmt.Errorf("failed to create repository: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Repository created successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("URL", result.Data.URL)
- output.KeyValue("Auth Type", result.Data.AuthType)
- output.KeyValue("Enabled", result.Data.Enabled)
- return nil
- },
-}
-var getCmd = &cobra.Command{
- Use: "get <repository>",
- Short: "Get git repository details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
-
- output.Header("Repository Details")
- output.KeyValue("ID", resolved.ID)
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("URL", resolved.URL)
- output.KeyValue("Auth Type", resolved.AuthType)
- if resolved.Username != "" {
- output.KeyValue("Username", resolved.Username)
- }
- if resolved.SSHHostKeyVerification != "" {
- output.KeyValue("SSH Host Key Verification", resolved.SSHHostKeyVerification)
- }
- if resolved.CommitAuthorName != "" || resolved.CommitAuthorEmail != "" {
- output.KeyValue("Commit Author", strings.TrimSpace(resolved.CommitAuthorName+" <"+resolved.CommitAuthorEmail+">"))
- }
- output.KeyValue("Signing Key", resolved.HasSigningKey)
- if resolved.Description != nil {
- output.KeyValue("Description", *resolved.Description)
- }
- output.KeyValue("Enabled", resolved.Enabled)
- output.KeyValue("Created", resolved.CreatedAt.Format("2006-01-02 15:04:05"))
- output.KeyValue("Updated", resolved.UpdatedAt.Format("2006-01-02 15:04:05"))
- return nil
- },
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
+
+ output.Header("Repository Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("URL", resolved.URL)
+ output.KeyValue("Auth Type", resolved.AuthType)
+ if resolved.Username != "" {
+ output.KeyValue("Username", resolved.Username)
+ }
+ if resolved.SSHHostKeyVerification != "" {
+ output.KeyValue("SSH Host Key Verification", resolved.SSHHostKeyVerification)
+ }
+ if resolved.CommitAuthorName != "" || resolved.CommitAuthorEmail != "" {
+ output.KeyValue("Commit Author", strings.TrimSpace(resolved.CommitAuthorName+" <"+resolved.CommitAuthorEmail+">"))
+ }
+ output.KeyValue("Signing Key", resolved.HasSigningKey)
+ if resolved.Description != nil {
+ output.KeyValue("Description", *resolved.Description)
+ }
+ output.KeyValue("Enabled", resolved.Enabled)
+ output.KeyValue("Created", resolved.CreatedAt.Format("2006-01-02 15:04:05"))
+ output.KeyValue("Updated", resolved.UpdatedAt.Format("2006-01-02 15:04:05"))
+ return nil
+ },
+ }
}
-var updateCmd = &cobra.Command{
- Use: "update <repository>",
- Short: "Update a git repository",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- req := gitops.UpdateRepositoryRequest{}
-
- if cmd.Flags().Changed("name") {
- req.Name = &repoUpdateName
- }
- if cmd.Flags().Changed("url") {
- req.URL = &repoUpdateURL
- }
- if cmd.Flags().Changed("auth-type") {
- req.AuthType = &repoUpdateAuthType
- }
- if cmd.Flags().Changed("token") {
- req.Token = &repoUpdateToken
- }
- if cmd.Flags().Changed("username") {
- req.Username = &repoUpdateUsername
- }
- if cmd.Flags().Changed("ssh-key") {
- sshKeyData, readFileErr := os.ReadFile(repoUpdateSSHKey)
- if readFileErr != nil {
- return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ url string
+ authType string
+ token string
+ username string
+ sshKey string
+ sshHostKeyVerify string
+ authorName string
+ authorEmail string
+ signingKey string
+ signingKeyPass string
+ description string
+ enabled bool
+ }
+ cmd := &cobra.Command{
+ Use: "update <repository>",
+ Short: "Update a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- req.SSHKey = new(string(sshKeyData))
- }
- if cmd.Flags().Changed("ssh-host-key-verification") {
- req.SSHHostKeyVerification = &repoUpdateSSHHostKeyVerify
- }
- if cmd.Flags().Changed("author-name") {
- req.CommitAuthorName = &repoUpdateAuthorName
- }
- if cmd.Flags().Changed("author-email") {
- req.CommitAuthorEmail = &repoUpdateAuthorEmail
- }
- if cmd.Flags().Changed("signing-key") {
- signingKey := ""
- if repoUpdateSigningKey != "" {
- signingKeyData, readSigningKeyErr := os.ReadFile(repoUpdateSigningKey)
- if readSigningKeyErr != nil {
- return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
+
+ var sshKey *string
+ if cmd.Flags().Changed("ssh-key") {
+ sshKeyData, readFileErr := os.ReadFile(opts.sshKey)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
}
- signingKey = string(signingKeyData)
+ sshKey = new(string(sshKeyData))
}
- req.SigningKey = &signingKey
- }
- if cmd.Flags().Changed("signing-key-passphrase") {
- req.SigningKeyPassphrase = &repoUpdateSigningKeyPass
- }
- if cmd.Flags().Changed("description") {
- req.Description = &repoUpdateDescription
- }
- if cmd.Flags().Changed("enabled") {
- req.Enabled = &repoUpdateEnabled
- }
-
- result, err := c.PutJSON[gitops.GitRepository](cmd.Context(), types.GitRepository(resolved.ID), req)
- if err != nil {
- return fmt.Errorf("failed to update repository: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Repository updated successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("URL", result.Data.URL)
- output.KeyValue("Auth Type", result.Data.AuthType)
- output.KeyValue("Enabled", result.Data.Enabled)
- return nil
- },
+ var signingKey *string
+ if cmd.Flags().Changed("signing-key") {
+ signingKeyValue := ""
+ if opts.signingKey != "" {
+ signingKeyData, readSigningKeyErr := os.ReadFile(opts.signingKey)
+ if readSigningKeyErr != nil {
+ return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
+ }
+ signingKeyValue = string(signingKeyData)
+ }
+ signingKey = &signingKeyValue
+ }
+
+ req := gitops.UpdateRepositoryRequest{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), &opts.name, nil),
+ URL: kit.Ternary(cmd.Flags().Changed("url"), &opts.url, nil),
+ AuthType: kit.Ternary(cmd.Flags().Changed("auth-type"), &opts.authType, nil),
+ Token: kit.Ternary(cmd.Flags().Changed("token"), &opts.token, nil),
+ Username: kit.Ternary(cmd.Flags().Changed("username"), &opts.username, nil),
+ SSHHostKeyVerification: kit.Ternary(cmd.Flags().Changed("ssh-host-key-verification"), &opts.sshHostKeyVerify, nil),
+ CommitAuthorName: kit.Ternary(cmd.Flags().Changed("author-name"), &opts.authorName, nil),
+ CommitAuthorEmail: kit.Ternary(cmd.Flags().Changed("author-email"), &opts.authorEmail, nil),
+ SigningKeyPassphrase: kit.Ternary(cmd.Flags().Changed("signing-key-passphrase"), &opts.signingKeyPass, nil),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), &opts.description, nil),
+ Enabled: kit.Ternary(cmd.Flags().Changed("enabled"), &opts.enabled, nil),
+ SSHKey: sshKey,
+ SigningKey: signingKey,
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.GitRepository]{
+ Method: http.MethodPut,
+ Path: types.GitRepository(resolved.ID),
+ Body: req,
+ FailureMessage: "failed to update repository",
+ Render: func(data gitops.GitRepository) error {
+ output.Success("Repository updated successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("URL", data.URL)
+ output.KeyValue("Auth Type", data.AuthType)
+ output.KeyValue("Enabled", data.Enabled)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Repository name")
+ cmd.Flags().StringVar(&opts.url, "url", "", "Repository URL")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.authType, "auth-type", "", "", "Authentication type", "none", "http", "ssh")
+ cmd.Flags().StringVar(&opts.token, "token", "", "Token for HTTP authentication")
+ cmd.Flags().StringVar(&opts.username, "username", "", "Username for HTTP authentication")
+ cmd.Flags().StringVar(&opts.sshKey, "ssh-key", "", "Path to SSH key file")
+ cmdutil.EnumVarP(cmd, cmd.Flags(), &opts.sshHostKeyVerify, "ssh-host-key-verification", "", "", "SSH host key verification", "strict", "accept_new", "skip")
+ cmd.Flags().StringVar(&opts.authorName, "author-name", "", "Author name for commits Arcane pushes")
+ cmd.Flags().StringVar(&opts.authorEmail, "author-email", "", "Author email for commits Arcane pushes")
+ cmd.Flags().StringVar(&opts.signingKey, "signing-key", "", "Path to an armored OpenPGP private key used to sign commits (empty clears it)")
+ cmd.Flags().StringVar(&opts.signingKeyPass, "signing-key-passphrase", "", "Passphrase for the signing key")
+ cmd.Flags().StringVar(&opts.description, "description", "", "Repository description")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", true, "Enable the repository")
+ return cmd
}
-var deleteCmd = &cobra.Command{
- Use: "delete <repository>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a git repository",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete repository %s (%s)?", resolved.Name, resolved.ID))
- if confirmErr != nil {
- return confirmErr
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <repository>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
}
- }
-
- resp, err := c.Delete(cmd.Context(), types.GitRepository(resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to delete repository: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete repository: %w", ensureSuccessStatusErr)
- }
-
- output.Success("Repository deleted successfully")
- return nil
- },
+
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete repository %s (%s)?", resolved.Name, resolved.ID),
+ Path: types.GitRepository(resolved.ID),
+ Body: nil,
+ FailureMessage: "failed to delete repository",
+ SuccessMessage: "Repository deleted successfully",
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return cmd
}
-var testCmd = &cobra.Command{
- Use: "test <repository>",
- Short: "Test git repository connection",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.GitRepositoryTest(resolved.ID),
- FailureMessage: "repository connection test failed",
- SuccessMessage: "Repository connection test successful",
- JSON: jsonOutput,
- })
- },
+func newTestCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "test <repository>",
+ Short: "Test git repository connection",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.GitRepositoryTest(resolved.ID),
+ FailureMessage: "repository connection test failed",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", "Repository connection test successful")
+ return nil
+ },
+ })
+ },
+ }
}
-var branchesCmd = &cobra.Command{
- Use: "branches <repository>",
- Short: "List branches for a git repository",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[gitops.BranchesResponse](cmd.Context(), types.GitRepositoryBranches(resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to list branches: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"BRANCH", "DEFAULT"}
- rows := make([][]string, len(result.Data.Branches))
- for i, branch := range result.Data.Branches {
- isDefault := ""
- if branch.IsDefault {
- isDefault = "*"
+func newBranchesCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "branches <repository>",
+ Short: "List branches for a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- rows[i] = []string{
- branch.Name,
- isDefault,
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
}
- }
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
- }
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d branches\n", len(result.Data.Branches))
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.BranchesResponse]{
+ Method: http.MethodGet,
+ Path: types.GitRepositoryBranches(resolved.ID),
+ FailureMessage: "failed to list branches",
+ Render: func(data gitops.BranchesResponse) error {
+ headers := []string{"BRANCH", "DEFAULT"}
+ rows := make([][]string, len(data.Branches))
+ for i, branch := range data.Branches {
+ isDefault := ""
+ if branch.IsDefault {
+ isDefault = "*"
+ }
+ rows[i] = []string{
+ branch.Name,
+ isDefault,
+ }
+ }
+
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d branches\n", len(data.Branches))
+ return nil
+ },
+ })
+ },
+ }
}
-var filesCmd = &cobra.Command{
- Use: "files <repository>",
- Short: "List files in a git repository",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], prompt.IsInteractive())
- if err != nil {
- return err
- }
-
- path := types.GitRepositoryFiles(resolved.ID)
- params := url.Values{}
- if filesBranch != "" {
- params.Set("branch", filesBranch)
- }
- if filesPath != "" {
- params.Set("path", filesPath)
- }
- if len(params) > 0 {
- path = path + "?" + params.Encode()
- }
-
- result, err := c.GetJSON[gitops.BrowseResponse](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to list files: %w", err)
- }
-
- files := result.Data.Files
- if jsonOutput {
- return cmdutil.PrintJSON(files)
- }
-
- headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
- rows := make([][]string, len(files))
- for i, node := range files {
- size := ""
- if node.Type == gitops.FileTreeNodeTypeFile {
- size = strconv.FormatInt(node.Size, 10)
+func newFilesCmd() *cobra.Command {
+ var opts struct {
+ branch string
+ path string
+ }
+ cmd := &cobra.Command{
+ Use: "files <repository>",
+ Short: "List files in a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- rows[i] = []string{
- node.Name,
- string(node.Type),
- node.Path,
- size,
+
+ resolved, _, err := repoRef.Resolve(cmd.Context(), c, args[0], cmdutil.AllowPrompt(cmd))
+ if err != nil {
+ return err
}
- }
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
- }
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d entries\n", len(files))
- return nil
- },
+ path := types.GitRepositoryFiles(resolved.ID)
+ params := url.Values{}
+ if opts.branch != "" {
+ params.Set("branch", opts.branch)
+ }
+ if opts.path != "" {
+ params.Set("path", opts.path)
+ }
+ if len(params) > 0 {
+ path = cmdutil.AppendQuery(path, params)
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[gitops.BrowseResponse]{
+ Method: http.MethodGet,
+ Path: path,
+ FailureMessage: "failed to list files",
+ Render: func(data gitops.BrowseResponse) error {
+ files := data.Files
+ headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
+ rows := make([][]string, len(files))
+ for i, node := range files {
+ size := ""
+ if node.Type == gitops.FileTreeNodeTypeFile {
+ size = strconv.FormatInt(node.Size, 10)
+ }
+ rows[i] = []string{
+ node.Name,
+ string(node.Type),
+ node.Path,
+ size,
+ }
+ }
+
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d entries\n", len(files))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.branch, "branch", "", "Branch to browse (required)")
+ _ = cmd.MarkFlagRequired("branch")
+ cmd.Flags().StringVar(&opts.path, "path", "", "Path within repository")
+ return cmd
}
var repoRef = cmdutil.ResourceRef[gitops.GitRepository, gitops.GitRepository]{
@@ -497,7 +511,10 @@ var repoRef = cmdutil.ResourceRef[gitops.GitRepository, gitops.GitRepository]{
ListCmd: "arcane repos list",
GetPath: func(_, identifier string) string { return types.GitRepository(identifier) },
ListPath: func(string) string { return types.GitRepositories() },
- Matches: repoMatches,
+ Matches: func(item gitops.GitRepository, identifierLower, original string) bool {
+ return strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original) ||
+ strings.HasPrefix(strings.ToLower(item.ID), identifierLower) || strings.Contains(strings.ToLower(item.Name), identifierLower)
+ },
Label: func(match gitops.GitRepository) string {
return fmt.Sprintf("%s (%s)", match.Name, match.ID)
},
@@ -506,86 +523,3 @@ var repoRef = cmdutil.ResourceRef[gitops.GitRepository, gitops.GitRepository]{
return strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original)
},
}
-
-func repoMatches(item gitops.GitRepository, identifierLower, original string) bool {
- if strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original) {
- return true
- }
- if strings.HasPrefix(strings.ToLower(item.ID), identifierLower) {
- return true
- }
- return strings.Contains(strings.ToLower(item.Name), identifierLower)
-}
-
-func init() {
- ReposCmd.AddCommand(listCmd)
- ReposCmd.AddCommand(createCmd)
- ReposCmd.AddCommand(getCmd)
- ReposCmd.AddCommand(updateCmd)
- ReposCmd.AddCommand(deleteCmd)
- ReposCmd.AddCommand(testCmd)
- ReposCmd.AddCommand(branchesCmd)
- ReposCmd.AddCommand(filesCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of repositories to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&repoCreateName, "name", "", "Repository name")
- createCmd.Flags().StringVar(&repoCreateURL, "url", "", "Repository URL")
- createCmd.Flags().StringVar(&repoCreateAuthType, "auth-type", "", "Authentication type (none, http, ssh)")
- createCmd.Flags().StringVar(&repoCreateToken, "token", "", "Token for HTTP authentication")
- createCmd.Flags().StringVar(&repoCreateUsername, "username", "", "Username for HTTP authentication")
- createCmd.Flags().StringVar(&repoCreateSSHKey, "ssh-key", "", "Path to SSH key file")
- createCmd.Flags().StringVar(&repoCreateSSHHostKeyVerify, "ssh-host-key-verification", "", "SSH host key verification (strict, accept_new, skip)")
- createCmd.Flags().StringVar(&repoCreateAuthorName, "author-name", "", "Author name for commits Arcane pushes")
- createCmd.Flags().StringVar(&repoCreateAuthorEmail, "author-email", "", "Author email for commits Arcane pushes")
- createCmd.Flags().StringVar(&repoCreateSigningKey, "signing-key", "", "Path to an armored OpenPGP private key used to sign commits")
- createCmd.Flags().StringVar(&repoCreateSigningKeyPass, "signing-key-passphrase", "", "Passphrase for the signing key")
- createCmd.Flags().StringVar(&repoCreateDescription, "description", "", "Repository description")
- createCmd.Flags().BoolVar(&repoCreateEnabled, "enabled", true, "Enable the repository")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("url")
- _ = createCmd.MarkFlagRequired("auth-type")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Update command flags
- updateCmd.Flags().StringVar(&repoUpdateName, "name", "", "Repository name")
- updateCmd.Flags().StringVar(&repoUpdateURL, "url", "", "Repository URL")
- updateCmd.Flags().StringVar(&repoUpdateAuthType, "auth-type", "", "Authentication type (none, http, ssh)")
- updateCmd.Flags().StringVar(&repoUpdateToken, "token", "", "Token for HTTP authentication")
- updateCmd.Flags().StringVar(&repoUpdateUsername, "username", "", "Username for HTTP authentication")
- updateCmd.Flags().StringVar(&repoUpdateSSHKey, "ssh-key", "", "Path to SSH key file")
- updateCmd.Flags().StringVar(&repoUpdateSSHHostKeyVerify, "ssh-host-key-verification", "", "SSH host key verification (strict, accept_new, skip)")
- updateCmd.Flags().StringVar(&repoUpdateAuthorName, "author-name", "", "Author name for commits Arcane pushes")
- updateCmd.Flags().StringVar(&repoUpdateAuthorEmail, "author-email", "", "Author email for commits Arcane pushes")
- updateCmd.Flags().StringVar(&repoUpdateSigningKey, "signing-key", "", "Path to an armored OpenPGP private key used to sign commits (empty clears it)")
- updateCmd.Flags().StringVar(&repoUpdateSigningKeyPass, "signing-key-passphrase", "", "Passphrase for the signing key")
- updateCmd.Flags().StringVar(&repoUpdateDescription, "description", "", "Repository description")
- updateCmd.Flags().BoolVar(&repoUpdateEnabled, "enabled", true, "Enable the repository")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Test command flags
- testCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Branches command flags
- branchesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Files command flags
- filesCmd.Flags().StringVar(&filesBranch, "branch", "", "Branch to browse (required)")
- _ = filesCmd.MarkFlagRequired("branch")
- filesCmd.Flags().StringVar(&filesPath, "path", "", "Path within repository")
- filesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Sync command flags
-}
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index dfc74b270..62b3d788f 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -15,6 +15,7 @@ import (
"charm.land/fang/v2"
"charm.land/lipgloss/v2"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
@@ -50,89 +51,89 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/pkg/webhooks"
)
-var (
- logLevel string
- logJSONOutput bool
- showVersion bool
- configPath string
- outputMode string
- envOverride string
- assumeYes bool
- noColorOutput bool
- requestTimeout time.Duration
- globalJSON bool
-)
+type rootOptions struct {
+ logLevel, configPath, outputMode, envOverride string
+ logJSON, showVersion, assumeYes, noColor, json bool
+ requestTimeout time.Duration
+}
-var rootCmd = &cobra.Command{
- Use: "arcane-cli",
- Long: "Arcane CLI - The official command line interface for Arcane",
- PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
- if configPath != "" {
- if err := config.SetConfigPath(configPath); err != nil {
- return err
+// NewRootCommand builds a fresh Arcane CLI command tree.
+func NewRootCommand() *cobra.Command {
+ opts := &rootOptions{}
+ root := &cobra.Command{
+ Use: "arcane-cli",
+ Long: "Arcane CLI - The official command line interface for Arcane",
+ PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
+ if opts.configPath != "" {
+ if err := config.SetConfigPath(opts.configPath); err != nil {
+ return err
+ }
}
- }
- outputMode = cmp.Or(strings.ToLower(strings.TrimSpace(outputMode)), string(runtimectx.OutputModeText))
- if globalJSON && !cmd.Flags().Changed("output") {
- outputMode = string(runtimectx.OutputModeJSON)
- }
- runtimeMode := runtimectx.OutputMode(outputMode)
- switch runtimeMode {
- case runtimectx.OutputModeJSON:
- if flag := cmd.Flags().Lookup("json"); flag != nil && !flag.Changed {
- _ = cmd.Flags().Set("json", "true")
+ jsonMode := opts.json || opts.outputMode == "json"
+ runtimeMode := kit.Ternary(jsonMode, runtimectx.OutputModeJSON, runtimectx.OutputModeText)
+ output.Configure(cmd.OutOrStdout(), cmd.ErrOrStderr(), jsonMode, opts.noColor, cmd.Short)
+
+ app, err := runtimectx.New(runtimectx.Options{
+ EnvOverride: opts.envOverride,
+ OutputMode: runtimeMode,
+ AssumeYes: opts.assumeYes,
+ NoColor: opts.noColor,
+ RequestTimeout: opts.requestTimeout,
+ })
+ if err != nil {
+ return err
+ }
+ if cfg := app.Config(); !cmd.Flags().Changed("log-level") && cfg != nil && cfg.LogLevel != "" {
+ opts.logLevel = cfg.LogLevel
+ }
+ logger.Setup(cmd.ErrOrStderr(), opts.logLevel, opts.logJSON)
+ cmd.SetContext(context.WithValue(cmd.Context(), runtimectx.AppContextKey, app))
+ runstate.Set(runstate.State{
+ EnvOverride: opts.envOverride,
+ OutputMode: string(runtimeMode),
+ AssumeYes: opts.assumeYes,
+ NoColor: opts.noColor,
+ RequestTimeout: opts.requestTimeout,
+ })
+ return nil
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !opts.showVersion {
+ return cmd.Help()
}
- case runtimectx.OutputModeText:
- default:
- return fmt.Errorf("invalid --output value %q (expected text or json)", outputMode)
- }
-
- // Load config to check for log level setting
- cfg, _ := config.Load()
-
- // If flag is not explicitly set, try to use config value
- if !cmd.Flags().Changed("log-level") && cfg != nil && cfg.LogLevel != "" {
- logLevel = cfg.LogLevel
- }
-
- if localJSON, _ := cmd.Flags().GetBool("json"); localJSON {
- runtimeMode = runtimectx.OutputModeJSON
- }
- output.Configure(cmd.OutOrStdout(), cmd.ErrOrStderr(), runtimeMode == runtimectx.OutputModeJSON, noColorOutput, cmd.Short)
- logger.Setup(cmd.ErrOrStderr(), logLevel, logJSONOutput)
-
- app, err := runtimectx.New(runtimectx.Options{
- EnvOverride: envOverride,
- OutputMode: runtimeMode,
- AssumeYes: assumeYes,
- NoColor: noColorOutput,
- RequestTimeout: requestTimeout,
- })
- if err != nil {
- return err
- }
- cmd.SetContext(context.WithValue(cmd.Context(), runtimectx.AppContextKey, app))
- runstate.Set(runstate.State{
- EnvOverride: envOverride,
- OutputMode: outputMode,
- AssumeYes: assumeYes,
- NoColor: noColorOutput,
- RequestTimeout: requestTimeout,
- })
- return nil
- },
- RunE: func(cmd *cobra.Command, args []string) error {
- if showVersion {
_, _ = fmt.Fprintf(output.Stdout(), "Arcane CLI version: %s\n", config.Version)
_, _ = fmt.Fprintf(output.Stdout(), "Git revision: %s\n", config.Revision)
_, _ = fmt.Fprintf(output.Stdout(), "Go version: %s\n", runtime.Version())
_, _ = fmt.Fprintf(output.Stdout(), "OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
return nil
- }
- return cmd.Help()
- },
- CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
+ },
+ CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
+ }
+
+ flags := root.PersistentFlags()
+ cmdutil.EnumVarP(root, flags, &opts.logLevel, "log-level", "", "info", "Log level", "debug", "info", "warn", "error", "fatal")
+ flags.StringVarP(&opts.configPath, "config", "c", "", "Path to config file (default ~/.config/arcanecli.yml)")
+ cmdutil.EnumVarP(root, flags, &opts.outputMode, "output", "", "text", "Output mode", "text", "json")
+ flags.StringVar(&opts.envOverride, "env", "", "Override default environment ID for this invocation")
+ flags.BoolVarP(&opts.assumeYes, "yes", "y", false, "Automatic yes to prompts")
+ flags.BoolVar(&opts.noColor, "no-color", false, "Disable colored output")
+ flags.DurationVar(&opts.requestTimeout, "request-timeout", 0, "HTTP request timeout override (e.g. 30s, 2m)")
+ flags.BoolVar(&opts.json, "json", false, "Alias for --output json")
+ flags.BoolVar(&opts.logJSON, "log-json", false, "Log in JSON format")
+ root.Flags().BoolVarP(&opts.showVersion, "version", "v", false, "Print version information")
+
+ imagesCmd := images.Command()
+ imagesCmd.AddCommand(vulnerabilities.Command())
+ root.AddCommand(
+ configClient.Command(), completion.NewCommand(root), doctor.Command(), generate.Command(), version.Command(), auth.Command(),
+ containers.Command(), imagesCmd, volumes.Command(), networks.Command(), projects.Command(), environments.Command(),
+ registries.Command(), repos.Command(), templates.Command(), settings.Command(), jobs.Command(), system.Command(),
+ updater.Command(), selfupdate.Command(), admin.Command(), gitops.Command(), variables.Command(), activities.Command(),
+ webhooks.Command(),
+ )
+ instrumentCommandTree(root)
+ return root
}
func Execute() {
@@ -141,23 +142,29 @@ func Execute() {
context.AfterFunc(ctx, cancel)
if err := fang.Execute(
ctx,
- rootCmd,
+ NewRootCommand(),
fang.WithColorSchemeFunc(func(c lipgloss.LightDarkFunc) fang.ColorScheme {
- scheme := fang.DefaultColorScheme(c)
- scheme.Base = c(lipgloss.Color("#1f2937"), lipgloss.Color("#e5e7eb"))
- scheme.Title = c(lipgloss.Color("#6d28d9"), lipgloss.Color("#a78bfa"))
- scheme.Description = scheme.Base
- scheme.Codeblock = c(lipgloss.Color("#f5f3ff"), lipgloss.Color("#241b35"))
- scheme.Program = scheme.Title
- scheme.Command = c(lipgloss.Color("#7c3aed"), lipgloss.Color("#c4b5fd"))
- scheme.DimmedArgument = c(lipgloss.Color("#64748b"), lipgloss.Color("#94a3b8"))
- scheme.Comment = c(lipgloss.Color("#64748b"), lipgloss.Color("#cbd5e1"))
- scheme.Flag = scheme.Title
- scheme.FlagDefault = c(lipgloss.Color("#64748b"), lipgloss.Color("#cbd5e1"))
- scheme.Argument = scheme.Base
- scheme.Help = scheme.Base
- scheme.Dash = scheme.Base
- return scheme
+ defaults := fang.DefaultColorScheme(c)
+ base := c(lipgloss.Color("#1f2937"), lipgloss.Color("#e5e7eb"))
+ title := c(lipgloss.Color("#6d28d9"), lipgloss.Color("#a78bfa"))
+ return fang.ColorScheme{
+ Base: base,
+ Title: title,
+ Description: base,
+ Codeblock: c(lipgloss.Color("#f5f3ff"), lipgloss.Color("#241b35")),
+ Program: title,
+ Command: c(lipgloss.Color("#7c3aed"), lipgloss.Color("#c4b5fd")),
+ DimmedArgument: c(lipgloss.Color("#64748b"), lipgloss.Color("#94a3b8")),
+ Comment: c(lipgloss.Color("#64748b"), lipgloss.Color("#cbd5e1")),
+ Flag: title,
+ FlagDefault: c(lipgloss.Color("#64748b"), lipgloss.Color("#cbd5e1")),
+ Argument: base,
+ Help: base,
+ Dash: base,
+ QuotedString: defaults.QuotedString,
+ ErrorHeader: defaults.ErrorHeader,
+ ErrorDetails: defaults.ErrorDetails,
+ }
}),
fang.WithErrorHandler(func(w io.Writer, _ fang.Styles, err error) { output.WriteError(w, err) }),
fang.WithVersion(config.Version),
@@ -169,12 +176,6 @@ func Execute() {
cancel()
}
-// RootCommand returns the configured root command.
-// Intended for integration tests and embedding.
-func RootCommand() *cobra.Command {
- return rootCmd
-}
-
func instrumentCommandTree(cmd *cobra.Command) {
for _, child := range cmd.Commands() {
instrumentCommandTree(child)
@@ -210,45 +211,3 @@ func instrumentCommandTree(cmd *cobra.Command) {
}
}
}
-
-func init() {
- rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error, fatal)")
- rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "Path to config file (default ~/.config/arcanecli.yml)")
- rootCmd.PersistentFlags().StringVar(&outputMode, "output", "text", "Output mode (text, json)")
- rootCmd.PersistentFlags().StringVar(&envOverride, "env", "", "Override default environment ID for this invocation")
- rootCmd.PersistentFlags().BoolVarP(&assumeYes, "yes", "y", false, "Automatic yes to prompts")
- rootCmd.PersistentFlags().BoolVar(&noColorOutput, "no-color", false, "Disable colored output")
- rootCmd.PersistentFlags().DurationVar(&requestTimeout, "request-timeout", 0, "HTTP request timeout override (e.g. 30s, 2m)")
- rootCmd.PersistentFlags().BoolVar(&globalJSON, "json", false, "Alias for --output json")
- rootCmd.PersistentFlags().BoolVar(&logJSONOutput, "log-json", false, "Log in JSON format")
- rootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "Print version information")
-
- rootCmd.AddCommand(configClient.ConfigCmd)
- rootCmd.AddCommand(completion.NewCommand(rootCmd))
- rootCmd.AddCommand(doctor.DoctorCmd)
- rootCmd.AddCommand(generate.GenerateCmd)
- rootCmd.AddCommand(version.VersionCmd)
- rootCmd.AddCommand(auth.AuthCmd)
- rootCmd.AddCommand(containers.ContainersCmd)
- images.ImagesCmd.AddCommand(vulnerabilities.VulnerabilitiesCmd)
- rootCmd.AddCommand(images.ImagesCmd)
- rootCmd.AddCommand(volumes.VolumesCmd)
- rootCmd.AddCommand(networks.NetworksCmd)
- rootCmd.AddCommand(projects.ProjectsCmd)
- rootCmd.AddCommand(environments.EnvironmentsCmd)
- rootCmd.AddCommand(registries.RegistriesCmd)
- rootCmd.AddCommand(repos.ReposCmd)
- rootCmd.AddCommand(templates.TemplatesCmd)
- rootCmd.AddCommand(settings.SettingsCmd)
- rootCmd.AddCommand(jobs.JobsCmd)
- rootCmd.AddCommand(system.SystemCmd)
- rootCmd.AddCommand(updater.UpdaterCmd)
- rootCmd.AddCommand(selfupdate.Cmd)
- rootCmd.AddCommand(admin.AdminCmd)
- rootCmd.AddCommand(gitops.GitopsCmd)
- rootCmd.AddCommand(variables.VariablesCmd)
- rootCmd.AddCommand(activities.ActivitiesCmd)
- rootCmd.AddCommand(webhooks.WebhooksCmd)
-
- instrumentCommandTree(rootCmd)
-}
diff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.go
index 99ae3279e..beb0c24c7 100644
--- a/cli/pkg/selfupdate/cmd.go
+++ b/cli/pkg/selfupdate/cmd.go
@@ -20,6 +20,7 @@ import (
"time"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
@@ -35,13 +36,10 @@ const (
maxCLIExtractSize = 128 * 1024 * 1024
)
-var (
- cliUpdateVersion string
- cliUpdateTarget string
- cliUpdateDryRun bool
- cliUpdateVerbose bool
- jsonOutput bool
-)
+type cliUpdateOptions struct {
+ version, target string
+ dryRun, verbose bool
+}
type cliUpdatePlan struct {
Channel string `json:"channel"`
@@ -60,97 +58,94 @@ type githubLatestRelease struct {
TagName string `json:"tag_name"`
}
-// Cmd updates the arcane-cli executable.
-var Cmd = &cobra.Command{
- Use: "self-update",
- Aliases: []string{"self", "cli"},
- Short: "Update arcane-cli",
- SilenceUsage: true,
- RunE: runCLIUpdateCommandInternal,
-}
-
-var selfUpdateRunCmd = &cobra.Command{
- Use: "run",
- Short: "Update arcane-cli using the configured channel",
- SilenceUsage: true,
- RunE: runCLIUpdateCommandInternal,
+// Command updates the arcane-cli executable.
+func Command() *cobra.Command {
+ var opts cliUpdateOptions
+ cmd := &cobra.Command{
+ Use: "self-update", Aliases: []string{"self", "cli"}, Short: "Update arcane-cli",
+ Args: cobra.NoArgs, SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, _ []string) error { return opts.runCLIUpdate(cmd, "") },
+ }
+ cmd.AddCommand(newSelfUpdateRunCmd(), newSelfUpdateChannelCmd())
+ registerCLIUpdateFlags(cmd, &opts)
+ return cmd
}
-var selfUpdateChannelCmd = &cobra.Command{
- Use: "channel [stable|next]",
- Short: "Set the CLI update channel and update arcane-cli",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return setCLIUpdateChannelAndRunInternal(cmd, args[0])
- },
+func newSelfUpdateRunCmd() *cobra.Command {
+ var opts cliUpdateOptions
+ cmd := &cobra.Command{
+ Use: "run", Short: "Update arcane-cli using the configured channel",
+ Args: cobra.NoArgs, SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, _ []string) error { return opts.runCLIUpdate(cmd, "") },
+ }
+ registerCLIUpdateFlags(cmd, &opts)
+ return cmd
}
-func init() {
- Cmd.AddCommand(selfUpdateRunCmd)
- Cmd.AddCommand(selfUpdateChannelCmd)
- stableCmd := newSelfUpdateChannelValueCmdInternal(cliUpdateChannelStable)
- nextCmd := newSelfUpdateChannelValueCmdInternal(cliUpdateChannelNext)
- selfUpdateChannelCmd.AddCommand(stableCmd)
- selfUpdateChannelCmd.AddCommand(nextCmd)
-
- registerCLIUpdateFlagsInternal(Cmd)
- registerCLIUpdateFlagsInternal(selfUpdateRunCmd)
- registerCLIUpdateFlagsInternal(selfUpdateChannelCmd)
- registerCLIUpdateFlagsInternal(stableCmd)
- registerCLIUpdateFlagsInternal(nextCmd)
+func newSelfUpdateChannelCmd() *cobra.Command {
+ var opts cliUpdateOptions
+ cmd := &cobra.Command{
+ Use: "channel <stable|next>", Short: "Set the CLI update channel and update arcane-cli",
+ Args: cobra.ExactArgs(1), SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error { return opts.setCLIUpdateChannelAndRun(cmd, args[0]) },
+ }
+ cmd.AddCommand(newSelfUpdateChannelValueCmd(cliUpdateChannelStable), newSelfUpdateChannelValueCmd(cliUpdateChannelNext))
+ registerCLIUpdateFlags(cmd, &opts)
+ return cmd
}
-func registerCLIUpdateFlagsInternal(cmd *cobra.Command) {
- cmd.Flags().StringVar(&cliUpdateVersion, "version", "", "Stable release tag to install (default: latest)")
- cmd.Flags().StringVar(&cliUpdateTarget, "target", "", "Binary path to replace (default: current executable)")
- cmd.Flags().BoolVar(&cliUpdateDryRun, "dry-run", false, "Check for an update without installing it")
- cmd.Flags().BoolVar(&cliUpdateVerbose, "verbose", false, "Print self-update resolution details")
- cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newSelfUpdateChannelValueCmd(channel string) *cobra.Command {
+ var opts cliUpdateOptions
+ cmd := &cobra.Command{
+ Use: channel, Short: fmt.Sprintf("Set the CLI update channel to %s and update arcane-cli", channel),
+ Args: cobra.NoArgs, SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, _ []string) error { return opts.setCLIUpdateChannelAndRun(cmd, channel) },
+ }
+ registerCLIUpdateFlags(cmd, &opts)
+ return cmd
}
-func newSelfUpdateChannelValueCmdInternal(channel string) *cobra.Command {
- return &cobra.Command{
- Use: channel,
- Short: fmt.Sprintf("Set the CLI update channel to %s and update arcane-cli", channel),
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return setCLIUpdateChannelAndRunInternal(cmd, channel)
- },
- }
+func registerCLIUpdateFlags(cmd *cobra.Command, opts *cliUpdateOptions) {
+ cmd.Flags().StringVar(&opts.version, "version", "", "Stable release tag to install (default: latest)")
+ cmd.Flags().StringVar(&opts.target, "target", "", "Binary path to replace (default: current executable)")
+ cmd.Flags().BoolVar(&opts.dryRun, "dry-run", false, "Check for an update without installing it")
+ cmd.Flags().BoolVar(&opts.verbose, "verbose", false, "Print self-update resolution details")
}
-func setCLIUpdateChannelAndRunInternal(cmd *cobra.Command, channel string) error {
+func (opts cliUpdateOptions) setCLIUpdateChannelAndRun(cmd *cobra.Command, channel string) error {
channel = strings.ToLower(strings.TrimSpace(channel))
if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {
return fmt.Errorf("invalid update channel %q (expected stable or next)", channel)
}
- if err := saveCLIUpdateChannelInternal(channel); err != nil {
- return err
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
}
- if !jsonOutput {
- output.Success("Set CLI update channel to %s", channel)
+ cfg.CLIUpdateChannel = channel
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
}
- return runCLIUpdateInternal(cmd.Context(), channel)
-}
-func runCLIUpdateCommandInternal(cmd *cobra.Command, args []string) error {
- return runCLIUpdateInternal(cmd.Context(), "")
+ if !cmdutil.JSONOutputEnabled(cmd) {
+ output.Success("Set CLI update channel to %s", channel)
+ }
+ return opts.runCLIUpdate(cmd, channel)
}
-func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {
- loading := output.StartTracker(ctx, output.Stderr(), !jsonOutput, "Resolving update")
+func (opts cliUpdateOptions) runCLIUpdate(cmd *cobra.Command, overrideChannel string) error {
+ ctx := cmd.Context()
+ jsonMode := cmdutil.JSONOutputEnabled(cmd)
+ loading := output.StartTracker(ctx, output.Stderr(), !jsonMode, "Resolving update")
loading.NextStep()
defer loading.Stop()
- plan, err := buildCLIUpdatePlanInternal(ctx, overrideChannel)
+ plan, err := opts.buildCLIUpdatePlan(ctx, overrideChannel)
if err != nil {
return err
}
loading.Finish("", err)
loading.Stop()
- if jsonOutput {
+ if jsonMode {
return cmdutil.PrintJSON(plan)
}
@@ -168,56 +163,62 @@ func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {
return nil
}
- if cliUpdateDryRun {
+ if opts.dryRun {
output.Info("Update available: %s", plan.ArtifactURL)
return nil
}
- if installCLIUpdateErr := installCLIUpdateInternal(ctx, plan); installCLIUpdateErr != nil {
+ if installCLIUpdateErr := opts.installCLIUpdate(ctx, plan, jsonMode); installCLIUpdateErr != nil {
return installCLIUpdateErr
}
output.Success("arcane-cli updated successfully")
return nil
}
-func buildCLIUpdatePlanInternal(ctx context.Context, overrideChannel string) (*cliUpdatePlan, error) {
- targetPath, err := resolveCLIUpdateTargetInternal()
+func (opts cliUpdateOptions) buildCLIUpdatePlan(ctx context.Context, overrideChannel string) (*cliUpdatePlan, error) {
+ targetPath, err := opts.resolveCLIUpdateTarget()
if err != nil {
return nil, err
}
channel := strings.ToLower(strings.TrimSpace(overrideChannel))
if channel == "" {
- channel, err = configuredCLIUpdateChannelInternal()
+ channel, err = configuredCLIUpdateChannel()
if err != nil {
return nil, err
}
}
if channel == "" {
- channel = inferCLIUpdateChannelInternal(config.Version)
+ normalized := strings.ToLower(strings.TrimSpace(config.Version))
+ channel = kit.Ternary(strings.Contains(normalized, "next") || strings.Contains(normalized, "beta"), cliUpdateChannelNext, cliUpdateChannelStable)
}
if channel != cliUpdateChannelNext && channel != cliUpdateChannelStable {
return nil, fmt.Errorf("invalid update channel %q (expected next or stable)", channel)
}
- verboseCLIUpdateInternal("channel=%s target=%s platform=%s/%s", channel, targetPath, runtime.GOOS, runtime.GOARCH)
+ opts.verboseCLIUpdate("channel=%s target=%s platform=%s/%s", channel, targetPath, runtime.GOOS, runtime.GOARCH)
- currentSHA, err := sha256FileInternal(targetPath)
+ currentSHA, err := sha256File(targetPath)
if err != nil {
return nil, err
}
- plan, err := resolveRemoteCLIUpdateInternal(ctx, channel)
+ var plan *cliUpdatePlan
+ if channel == cliUpdateChannelNext {
+ plan, err = opts.resolveNextCLIUpdate(ctx)
+ } else {
+ plan, err = opts.resolveStableCLIUpdate(ctx)
+ }
if err != nil {
return nil, err
}
plan.Channel = channel
plan.TargetPath = targetPath
plan.CurrentSHA = currentSHA
- plan.UpdateNeeded = cliUpdateNeededInternal(channel, currentSHA, plan.ExpectedSHA, plan.Version)
+ plan.UpdateNeeded = cliUpdateNeeded(channel, currentSHA, plan.ExpectedSHA, plan.Version)
return plan, nil
}
-func configuredCLIUpdateChannelInternal() (string, error) {
+func configuredCLIUpdateChannel() (string, error) {
cfg, err := config.Load()
if err != nil {
return "", fmt.Errorf("failed to load config: %w", err)
@@ -232,21 +233,9 @@ func configuredCLIUpdateChannelInternal() (string, error) {
return channel, nil
}
-func saveCLIUpdateChannelInternal(channel string) error {
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
- }
- cfg.CLIUpdateChannel = channel
- if saveErr := config.Save(cfg); saveErr != nil {
- return fmt.Errorf("failed to save config: %w", saveErr)
- }
- return nil
-}
-
-func resolveCLIUpdateTargetInternal() (string, error) {
- if strings.TrimSpace(cliUpdateTarget) != "" {
- return filepath.Abs(strings.TrimSpace(cliUpdateTarget))
+func (opts cliUpdateOptions) resolveCLIUpdateTarget() (string, error) {
+ if strings.TrimSpace(opts.target) != "" {
+ return filepath.Abs(strings.TrimSpace(opts.target))
}
if pathTarget, err := exec.LookPath("arcane-cli"); err == nil {
absTarget, absErr := filepath.Abs(pathTarget)
@@ -262,48 +251,30 @@ func resolveCLIUpdateTargetInternal() (string, error) {
return filepath.EvalSymlinks(exe)
}
-func inferCLIUpdateChannelInternal(version string) string {
- normalized := strings.ToLower(strings.TrimSpace(version))
- if strings.Contains(normalized, "next") || strings.Contains(normalized, "beta") {
- return cliUpdateChannelNext
- }
- return cliUpdateChannelStable
-}
-
-func resolveRemoteCLIUpdateInternal(ctx context.Context, channel string) (*cliUpdatePlan, error) {
- if channel == cliUpdateChannelNext {
- return resolveNextCLIUpdateInternal(ctx)
- }
- return resolveStableCLIUpdateInternal(ctx)
-}
-
-func resolveNextCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error) {
+func (opts cliUpdateOptions) resolveNextCLIUpdate(ctx context.Context) (*cliUpdatePlan, error) {
baseURL := strings.TrimSpace(config.CLINextBaseURL)
if baseURL == "" {
return nil, errors.New("next CLI update base URL is empty")
}
- artifactName, err := cliRawArtifactNameInternal()
+ platformName, err := cliPlatformName()
if err != nil {
return nil, err
}
- platformName, err := cliPlatformNameInternal()
- if err != nil {
- return nil, err
- }
- checksumURL := joinURLPathInternal(baseURL, "arcane-cli_checksums.txt")
- artifactURL := joinURLPathInternal(baseURL, artifactName)
- verboseCLIUpdateInternal("next base URL: %s", baseURL)
- verboseCLIUpdateInternal("next artifact URL: %s", artifactURL)
- verboseCLIUpdateInternal("next checksum URL: %s", checksumURL)
- verboseCLIUpdateInternal("next checksum candidates: %s", artifactName+", "+platformName)
+ artifactName := "arcane-cli_" + platformName
+ checksumURL := joinURLPath(baseURL, "arcane-cli_checksums.txt")
+ artifactURL := joinURLPath(baseURL, artifactName)
+ opts.verboseCLIUpdate("next base URL: %s", baseURL)
+ opts.verboseCLIUpdate("next artifact URL: %s", artifactURL)
+ opts.verboseCLIUpdate("next checksum URL: %s", checksumURL)
+ opts.verboseCLIUpdate("next checksum candidates: %s", artifactName+", "+platformName)
- checksums, err := fetchTextInternal(ctx, checksumURL)
+ checksums, err := fetchText(ctx, checksumURL)
if err != nil {
return nil, err
}
- verboseCLIUpdateInternal("next checksum entries: %s", strings.Join(checksumEntryNamesInternal(checksums), ", "))
- expectedSHA, err := findChecksumInternal(checksums, artifactName, platformName)
+ opts.verboseCLIUpdate("next checksum entries: %s", strings.Join(checksumEntryNames(checksums), ", "))
+ expectedSHA, err := findChecksum(checksums, artifactName, platformName)
if err != nil {
return nil, err
}
@@ -318,10 +289,10 @@ func resolveNextCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error) {
}, nil
}
-func resolveStableCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error) {
- version := strings.TrimSpace(cliUpdateVersion)
+func (opts cliUpdateOptions) resolveStableCLIUpdate(ctx context.Context) (*cliUpdatePlan, error) {
+ version := strings.TrimSpace(opts.version)
if version == "" {
- latest, err := fetchLatestGitHubReleaseInternal(ctx)
+ latest, err := fetchLatestGitHubRelease(ctx)
if err != nil {
return nil, err
}
@@ -336,25 +307,26 @@ func resolveStableCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error)
return nil, errors.New("stable CLI update base URL is empty")
}
- artifactName, err := cliArchiveArtifactNameInternal()
+ arch, err := cliArtifactArch()
if err != nil {
return nil, err
}
+ artifactName := fmt.Sprintf("arcane-cli_%s_%s.tar.gz", runtime.GOOS, arch)
checksumName := fmt.Sprintf("arcane_%s_checksums.txt", strings.TrimPrefix(version, "v"))
- versionBaseURL := joinURLPathInternal(baseURL, version)
- checksumURL := joinURLPathInternal(versionBaseURL, checksumName)
- artifactURL := joinURLPathInternal(versionBaseURL, artifactName)
- verboseCLIUpdateInternal("stable version: %s", version)
- verboseCLIUpdateInternal("stable artifact URL: %s", artifactURL)
- verboseCLIUpdateInternal("stable checksum URL: %s", checksumURL)
- verboseCLIUpdateInternal("stable checksum candidates: %s", artifactName)
-
- checksums, err := fetchTextInternal(ctx, checksumURL)
+ versionBaseURL := joinURLPath(baseURL, version)
+ checksumURL := joinURLPath(versionBaseURL, checksumName)
+ artifactURL := joinURLPath(versionBaseURL, artifactName)
+ opts.verboseCLIUpdate("stable version: %s", version)
+ opts.verboseCLIUpdate("stable artifact URL: %s", artifactURL)
+ opts.verboseCLIUpdate("stable checksum URL: %s", checksumURL)
+ opts.verboseCLIUpdate("stable checksum candidates: %s", artifactName)
+
+ checksums, err := fetchText(ctx, checksumURL)
if err != nil {
return nil, err
}
- verboseCLIUpdateInternal("stable checksum entries: %s", strings.Join(checksumEntryNamesInternal(checksums), ", "))
- artifactSHA, err := findChecksumInternal(checksums, artifactName)
+ opts.verboseCLIUpdate("stable checksum entries: %s", strings.Join(checksumEntryNames(checksums), ", "))
+ artifactSHA, err := findChecksum(checksums, artifactName)
if err != nil {
return nil, err
}
@@ -368,19 +340,16 @@ func resolveStableCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error)
}, nil
}
-func cliUpdateNeededInternal(channel, currentSHA, expectedSHA, remoteVersion string) bool {
+func cliUpdateNeeded(channel, currentSHA, expectedSHA, remoteVersion string) bool {
if channel == cliUpdateChannelStable {
current := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(config.Version)), "v")
remote := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(remoteVersion)), "v")
return current != remote
}
- if strings.TrimSpace(expectedSHA) == "" {
- return true
- }
- return !strings.EqualFold(currentSHA, expectedSHA)
+ return strings.TrimSpace(expectedSHA) == "" || !strings.EqualFold(currentSHA, expectedSHA)
}
-func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {
+func fetchLatestGitHubRelease(ctx context.Context) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/getarcaneapp/arcane/releases/latest", http.NoBody)
if err != nil {
return "", err
@@ -404,31 +373,15 @@ func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {
return strings.TrimSpace(latest.TagName), nil
}
-func cliRawArtifactNameInternal() (string, error) {
- platformName, err := cliPlatformNameInternal()
- if err != nil {
- return "", err
- }
- return "arcane-cli_" + platformName, nil
-}
-
-func cliPlatformNameInternal() (string, error) {
- arch, err := cliArtifactArchInternal()
+func cliPlatformName() (string, error) {
+ arch, err := cliArtifactArch()
if err != nil {
return "", err
}
return fmt.Sprintf("%s_%s", runtime.GOOS, arch), nil
}
-func cliArchiveArtifactNameInternal() (string, error) {
- arch, err := cliArtifactArchInternal()
- if err != nil {
- return "", err
- }
- return fmt.Sprintf("arcane-cli_%s_%s.tar.gz", runtime.GOOS, arch), nil
-}
-
-func cliArtifactArchInternal() (string, error) {
+func cliArtifactArch() (string, error) {
switch runtime.GOARCH {
case "amd64", "arm64", "386", "riscv64":
return runtime.GOARCH, nil
@@ -439,22 +392,22 @@ func cliArtifactArchInternal() (string, error) {
}
}
-func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {
+func (opts cliUpdateOptions) installCLIUpdate(ctx context.Context, plan *cliUpdatePlan, jsonMode bool) error {
tmpDir, err := os.MkdirTemp("", "arcane-cli-update-*")
if err != nil {
return fmt.Errorf("failed to create update temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
- loading := output.StartTracker(ctx, output.Stderr(), !jsonOutput, "Downloading artifact", "Verifying artifact", "Installing executable")
+ loading := output.StartTracker(ctx, output.Stderr(), !jsonMode, "Downloading artifact", "Verifying artifact", "Installing executable")
loading.NextStep()
defer loading.Stop()
downloadPath := filepath.Join(tmpDir, plan.ArtifactName)
- if downloadFileErr := downloadFileInternal(ctx, plan.ArtifactURL, downloadPath); downloadFileErr != nil {
+ if downloadFileErr := opts.downloadFile(ctx, plan.ArtifactURL, downloadPath, jsonMode); downloadFileErr != nil {
return downloadFileErr
}
loading.NextStep()
- if gotSHA, sha256FileErr := sha256FileInternal(downloadPath); sha256FileErr != nil {
+ if gotSHA, sha256FileErr := sha256File(downloadPath); sha256FileErr != nil {
return sha256FileErr
} else if !strings.EqualFold(gotSHA, plan.ArtifactSHA) {
return fmt.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)
@@ -464,7 +417,7 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {
binaryPath := downloadPath
if strings.HasSuffix(plan.ArtifactName, ".tar.gz") {
extractedPath := filepath.Join(tmpDir, "arcane-cli")
- if extractCLIFromTarGzErr := extractCLIFromTarGzInternal(downloadPath, extractedPath); extractCLIFromTarGzErr != nil {
+ if extractCLIFromTarGzErr := extractCLIFromTarGz(downloadPath, extractedPath); extractCLIFromTarGzErr != nil {
return extractCLIFromTarGzErr
}
binaryPath = extractedPath
@@ -473,10 +426,10 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {
if chmodErr := os.Chmod(binaryPath, 0o755); chmodErr != nil {
return fmt.Errorf("failed to make downloaded binary executable: %w", chmodErr)
}
- return replaceExecutableInternal(binaryPath, plan.TargetPath)
+ return replaceExecutable(binaryPath, plan.TargetPath)
}
-func replaceExecutableInternal(sourcePath, targetPath string) error {
+func replaceExecutable(sourcePath, targetPath string) error {
targetDir := filepath.Dir(targetPath)
tmpTarget, err := os.CreateTemp(targetDir, filepath.Base(targetPath)+".update-*")
if err != nil {
@@ -528,7 +481,7 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {
return nil
}
-func extractCLIFromTarGzInternal(archivePath, outputPath string) error {
+func extractCLIFromTarGz(archivePath, outputPath string) error {
file, err := os.Open(archivePath)
if err != nil {
return fmt.Errorf("failed to open archive: %w", err)
@@ -576,7 +529,7 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {
return errors.New("archive did not contain arcane-cli")
}
-func fetchTextInternal(ctx context.Context, url string) (string, error) {
+func fetchText(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return "", err
@@ -603,8 +556,8 @@ func fetchTextInternal(ctx context.Context, url string) (string, error) {
return string(body), nil
}
-func downloadFileInternal(ctx context.Context, url, outputPath string) error {
- verboseCLIUpdateInternal("downloading %s to %s", url, outputPath)
+func (opts cliUpdateOptions) downloadFile(ctx context.Context, url, outputPath string, jsonMode bool) error {
+ opts.verboseCLIUpdate("downloading %s to %s", url, outputPath)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return err
@@ -624,7 +577,7 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {
return fmt.Errorf("failed to create download file: %w", err)
}
limitedBody := &io.LimitedReader{R: resp.Body, N: maxCLIDownloadSize + 1}
- written, err := output.Copy(ctx, out, limitedBody, resp.ContentLength, "Downloading artifact", !jsonOutput)
+ written, err := output.Copy(ctx, out, limitedBody, resp.ContentLength, "Downloading artifact", !jsonMode)
if err != nil {
_ = out.Close()
return fmt.Errorf("failed to write download file: %w", err)
@@ -640,14 +593,14 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {
}
//nolint:goprintffuncname // internal verbose-logging helper; printf-style by design
-func verboseCLIUpdateInternal(format string, args ...any) {
- if !cliUpdateVerbose {
+func (opts cliUpdateOptions) verboseCLIUpdate(format string, args ...any) {
+ if !opts.verbose {
return
}
_, _ = fmt.Fprintf(output.CoordinatedWriter(output.Stderr()), "self-update: "+format+"\n", args...)
}
-func sha256FileInternal(filePath string) (string, error) {
+func sha256File(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open %s for SHA-256: %w", filePath, err)
@@ -661,7 +614,7 @@ func sha256FileInternal(filePath string) (string, error) {
return hex.EncodeToString(hash.Sum(nil)), nil
}
-func findChecksumInternal(checksums string, artifactNames ...string) (string, error) {
+func findChecksum(checksums string, artifactNames ...string) (string, error) {
wanted := make(map[string]struct{}, len(artifactNames))
for _, artifactName := range artifactNames {
artifactName = strings.TrimPrefix(path.Clean(strings.TrimSpace(artifactName)), "./")
@@ -671,22 +624,30 @@ func findChecksumInternal(checksums string, artifactNames ...string) (string, er
}
for line := range strings.SplitSeq(checksums, "\n") {
- fields := strings.Fields(strings.TrimSpace(line))
+ fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
checksumPath := strings.TrimPrefix(path.Clean(strings.TrimSpace(fields[len(fields)-1])), "./")
- if checksumPathMatchesInternal(checksumPath, wanted) {
+ if _, ok := wanted[checksumPath]; ok {
+ return strings.ToLower(fields[0]), nil
+ }
+ if _, ok := wanted[path.Base(checksumPath)]; ok {
return strings.ToLower(fields[0]), nil
}
+ for wantedPath := range wanted {
+ if strings.HasSuffix(checksumPath, "/"+wantedPath) {
+ return strings.ToLower(fields[0]), nil
+ }
+ }
}
return "", fmt.Errorf("checksum for %s not found", strings.Join(artifactNames, " or "))
}
-func checksumEntryNamesInternal(checksums string) []string {
+func checksumEntryNames(checksums string) []string {
names := make([]string, 0)
for line := range strings.SplitSeq(checksums, "\n") {
- fields := strings.Fields(strings.TrimSpace(line))
+ fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
@@ -695,22 +656,7 @@ func checksumEntryNamesInternal(checksums string) []string {
return names
}
-func checksumPathMatchesInternal(checksumPath string, wanted map[string]struct{}) bool {
- if _, ok := wanted[checksumPath]; ok {
- return true
- }
- if _, ok := wanted[path.Base(checksumPath)]; ok {
- return true
- }
- for wantedPath := range wanted {
- if strings.HasSuffix(checksumPath, "/"+wantedPath) {
- return true
- }
- }
- return false
-}
-
-func joinURLPathInternal(baseURL string, parts ...string) string {
+func joinURLPath(baseURL string, parts ...string) string {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
joined := path.Join(parts...)
if joined == "." || joined == "" {
diff --git a/cli/pkg/selfupdate/cmd_test.go b/cli/pkg/selfupdate/cmd_test.go
index 8ee0acb2c..9692c7468 100644
--- a/cli/pkg/selfupdate/cmd_test.go
+++ b/cli/pkg/selfupdate/cmd_test.go
@@ -10,7 +10,7 @@ import (
func TestFindChecksumMatchesNextDistPath(t *testing.T) {
checksums := "abc123 dist/arcane-cli_darwin_arm64_v8.0/arcane-cli\n"
- got, err := findChecksumInternal(checksums, "arcane-cli_darwin_arm64_v8.0/arcane-cli", "arcane-cli_darwin_arm64")
+ got, err := findChecksum(checksums, "arcane-cli_darwin_arm64_v8.0/arcane-cli", "arcane-cli_darwin_arm64")
require.NoError(t, err,
"findChecksum returned error: %v", err)
@@ -22,7 +22,7 @@ func TestFindChecksumMatchesNextDistPath(t *testing.T) {
func TestFindChecksumMatchesArchiveBasename(t *testing.T) {
checksums := "def456 dist/arcane-cli_linux_amd64.tar.gz\n"
- got, err := findChecksumInternal(checksums, "arcane-cli_linux_amd64.tar.gz")
+ got, err := findChecksum(checksums, "arcane-cli_linux_amd64.tar.gz")
require.NoError(t, err,
"findChecksum returned error: %v", err)
@@ -34,7 +34,7 @@ func TestFindChecksumMatchesArchiveBasename(t *testing.T) {
func TestChecksumEntryNames(t *testing.T) {
checksums := "abc123 ./arcane-cli_darwin_arm64\n\nbad-line\ndef456 dist/arcane-cli_linux_amd64.tar.gz\n"
- got := checksumEntryNamesInternal(checksums)
+ got := checksumEntryNames(checksums)
want := []string{"arcane-cli_darwin_arm64", "dist/arcane-cli_linux_amd64.tar.gz"}
if len(got) != len(want) {
require.Len(t, got, len(want),
@@ -47,19 +47,11 @@ func TestChecksumEntryNames(t *testing.T) {
}
func TestCLIArtifactNamesUseFlatR2BinaryNames(t *testing.T) {
- platformName, err := cliPlatformNameInternal()
+ platformName, err := cliPlatformName()
require.NoError(t, err,
"cliPlatformName returned error: %v", err)
require.False(t, strings.HasPrefix(platformName, "arcane-cli_") || strings.Contains(platformName, "/") || strings.HasSuffix(platformName, ".tar.gz"),
"platformName = %q, want bare platform name", platformName)
-
- artifactName, err := cliRawArtifactNameInternal()
-
- require.NoError(t, err,
- "cliRawArtifactName returned error: %v", err)
-
- require.Equal(t, "arcane-cli_"+platformName, artifactName,
- "artifactName = %q, want %q", artifactName, "arcane-cli_"+platformName)
}
diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.go
index e8b826be6..d7a622882 100644
--- a/cli/pkg/settings/cmd.go
+++ b/cli/pkg/settings/cmd.go
@@ -14,76 +14,92 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var jsonOutput bool
-
-// SettingsCmd is the parent command for settings operations
-var SettingsCmd = &cobra.Command{
- Use: "settings",
- Aliases: []string{"setting"},
- Short: "Manage settings",
+// Command is the parent command for settings operations
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "settings",
+ Aliases: []string{"setting"},
+ Short: "Manage settings",
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.AddCommand(newListCmd(), newUpdateCmd(), newPublicCmd())
+ return cmd
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List environment settings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runSettingsList(cmd, settingsListConfig{
- endpoint: types.Settings,
- failureMessage: "failed to get settings",
- totalLabel: "settings",
- })
- },
+func newListCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List environment settings",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runSettingsList(cmd, settingsListConfig{
+ endpoint: types.Settings,
+ failureMessage: "failed to get settings",
+ totalLabel: "settings",
+ })
+ },
+ }
}
-var settingsUpdateFile string
-
-var updateCmd = &cobra.Command{
- Use: "update",
- Short: "Update environment settings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- data, err := os.ReadFile(settingsUpdateFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", settingsUpdateFile, err)
- }
-
- var req settings.Update
- if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
- return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
- }
-
- result, err := c.PutJSON[[]settings.SettingDto](cmd.Context(), types.Settings(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to update settings: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Settings updated successfully")
- return nil
- },
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ file string
+ }
+ cmd := &cobra.Command{
+ Use: "update",
+ Short: "Update environment settings",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ data, err := os.ReadFile(opts.file)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", opts.file, err)
+ }
+
+ var req settings.Update
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]settings.SettingDto]{
+ Method: http.MethodPut,
+ Path: types.Settings(c.EnvID()),
+ Body: req,
+ FailureMessage: "failed to update settings",
+ Render: func([]settings.SettingDto) error {
+ output.Success("Settings updated successfully")
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ cmd.Flags().StringVarP(&opts.file, "file", "f", "", "Settings JSON file")
+ _ = cmd.MarkFlagRequired("file")
+ return cmd
}
-var publicCmd = &cobra.Command{
- Use: "public",
- Short: "List public settings",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runSettingsList(cmd, settingsListConfig{
- endpoint: types.SettingsPublic,
- failureMessage: "failed to get public settings",
- totalLabel: "public settings",
- })
- },
+func newPublicCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "public",
+ Short: "List public settings",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runSettingsList(cmd, settingsListConfig{
+ endpoint: types.SettingsPublic,
+ failureMessage: "failed to get public settings",
+ totalLabel: "public settings",
+ })
+ },
+ }
}
type settingsListConfig struct {
@@ -103,7 +119,7 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
return fmt.Errorf("%s: %w", cfg.failureMessage, err)
}
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) {
return cmdutil.PrintJSON(result)
}
@@ -113,24 +129,5 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
rows[i] = []string{s.Key, s.Type, s.Value}
}
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: cfg.totalLabel}); tableErr != nil {
- return tableErr
- }
- return nil
-}
-
-func init() {
- cmdutil.SetScope(cmdutil.ScopeRead, SettingsCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, updateCmd)
- SettingsCmd.AddCommand(listCmd)
- SettingsCmd.AddCommand(updateCmd)
- SettingsCmd.AddCommand(publicCmd)
-
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- updateCmd.Flags().StringVarP(&settingsUpdateFile, "file", "f", "", "Settings JSON file")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = updateCmd.MarkFlagRequired("file")
-
- publicCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: cfg.totalLabel})
}
diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.go
index 6992b354c..d229bd7cc 100644
--- a/cli/pkg/system/cmd.go
+++ b/cli/pkg/system/cmd.go
@@ -2,6 +2,7 @@ package system
import (
"cmp"
+ "encoding/json/v2"
"errors"
"fmt"
"net/http"
@@ -12,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/dockerinfo"
"github.com/getarcaneapp/arcane/types/v2/system"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
@@ -19,267 +21,276 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var jsonOutput bool
-
-// SystemCmd is the parent command for system operations
-var SystemCmd = &cobra.Command{
- Use: "system",
- Aliases: []string{"sys"},
- Short: "System operations",
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "system",
+ Aliases: []string{"sys"},
+ Short: "System operations",
+ }
+ cmd.AddCommand(
+ newPruneCmd(),
+ newDockerInfoCmd(),
+ newSystemContainersCmd(),
+ newConvertCmd(),
+ newUpgradeCmd(),
+ )
+ return cmd
}
-var pruneCmd = &cobra.Command{
- Use: "prune",
- Short: "Prune all unused resources",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := system.PruneAllRequest{
- Containers: &system.PruneContainersOptions{Mode: system.PruneContainerModeStopped},
- Images: &system.PruneImagesOptions{Mode: system.PruneImageModeDangling},
- Networks: &system.PruneNetworksOptions{Mode: system.PruneNetworkModeUnused},
- }
-
- result, err := c.PostJSON[system.PruneAllResult](cmd.Context(), types.SystemPrune(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to prune: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("System Prune Results")
- output.KeyValue("Space Reclaimed", output.UnsignedBytes(result.Data.SpaceReclaimed))
- return nil
- },
+func newPruneCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "prune",
+ Short: "Prune all unused resources",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, false, "Are you sure you want to prune all unused resources?")
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[system.PruneAllResult]{
+ Method: http.MethodPost,
+ Path: types.SystemPrune(c.EnvID()),
+ FailureMessage: "failed to prune",
+ Body: system.PruneAllRequest{
+ Containers: &system.PruneContainersOptions{Mode: system.PruneContainerModeStopped},
+ Images: &system.PruneImagesOptions{Mode: system.PruneImageModeDangling},
+ Networks: &system.PruneNetworksOptions{Mode: system.PruneNetworkModeUnused},
+ },
+ Render: func(data system.PruneAllResult) error {
+ output.Header("System Prune Results")
+ output.KeyValue("Space Reclaimed", output.UnsignedBytes(data.SpaceReclaimed))
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-var dockerInfoCmd = &cobra.Command{
- Use: "info",
- Aliases: []string{"docker-info"},
- Short: "Get Docker daemon information",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // This endpoint returns dockerinfo.Info directly, not wrapped in an
- // ApiResponse envelope.
- result, err := c.DoJSON[dockerinfo.Info](cmd.Context(), http.MethodGet, types.SystemDockerInfo(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to get docker info: %w", err)
- }
+func newDockerInfoCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "info",
+ Aliases: []string{"docker-info"},
+ Short: "Get Docker daemon information",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
+ // This endpoint returns dockerinfo.Info directly, not wrapped in an
+ // ApiResponse envelope.
+ body, err := c.DoRaw(cmd.Context(), http.MethodGet, types.SystemDockerInfo(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to get docker info: %w", err)
+ }
- output.Header("Docker Info")
- output.KeyValue("API Version", result.APIVersion)
- output.KeyValue("OS", result.Os)
- output.KeyValue("Architecture", result.Arch)
- output.KeyValue("Go Version", result.GoVersion)
- return nil
- },
-}
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
+ }
+ var result dockerinfo.Info
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to get docker info: failed to decode response: %w", decodeErr)
+ }
-var systemContainersCmd = &cobra.Command{
- Use: "containers",
- Short: "Bulk container operations",
+ output.Header("Docker Info")
+ output.KeyValue("API Version", result.APIVersion)
+ output.KeyValue("OS", result.Os)
+ output.KeyValue("Architecture", result.Arch)
+ output.KeyValue("Go Version", result.GoVersion)
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-var startStoppedOnlyFlag bool
-
-var containersStartCmd = &cobra.Command{
- Use: "start",
- Short: "Start all containers",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := types.SystemContainersStartAll(c.EnvID())
- successMessage := "Started all containers"
- if startStoppedOnlyFlag {
- path = types.SystemStartStopped(c.EnvID())
- successMessage = "Started all stopped containers"
- }
-
- return cmdutil.RunPostAction[container.ActionResult](cmd, c, cmdutil.PostActionSpec{
- Path: path,
- FailureMessage: "failed to start containers",
- SuccessMessage: successMessage,
- JSON: jsonOutput,
- })
- },
+func newSystemContainersCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "containers",
+ Short: "Bulk container operations",
+ }
+ cmd.AddCommand(
+ newContainersStartCmd(),
+ newContainersStopCmd(),
+ )
+ return cmd
}
-var containersStopCmd = &cobra.Command{
- Use: "stop",
- Short: "Stop all containers",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newContainersStartCmd() *cobra.Command {
+ var opts struct {
+ startStoppedOnlyFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "start",
+ Short: "Start all containers",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[container.ActionResult](cmd, c, cmdutil.PostActionSpec{
- Path: types.SystemContainersStopAll(c.EnvID()),
- FailureMessage: "failed to stop all containers",
- SuccessMessage: "Stopped all containers",
- JSON: jsonOutput,
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.ActionResult]{
+ Method: http.MethodPost,
+ Path: kit.Ternary(opts.startStoppedOnlyFlag, types.SystemStartStopped(c.EnvID()), types.SystemContainersStartAll(c.EnvID())),
+ FailureMessage: "failed to start containers",
+ Render: func(container.ActionResult) error {
+ output.Success("%s", kit.Ternary(opts.startStoppedOnlyFlag, "Started all stopped containers", "Started all containers"))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().BoolVar(&opts.startStoppedOnlyFlag, "stopped", false, "Only start containers that are currently stopped")
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-var convertCmd = &cobra.Command{
- Use: "convert <docker-run-command>",
- Short: "Convert docker run command to compose",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // This endpoint returns its payload directly, not wrapped in an
- // ApiResponse envelope.
- type convertResult struct {
- Success bool `json:"success"`
- DockerCompose string `json:"dockerCompose"`
- EnvVars string `json:"envVars"`
- ServiceName string `json:"serviceName"`
- }
- req := map[string]string{"dockerRunCommand": args[0]}
- result, err := c.DoJSON[convertResult](cmd.Context(), http.MethodPost, types.SystemConvert(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to convert command: %w", err)
- }
+func newContainersStopCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "stop",
+ Short: "Stop all containers",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(map[string]string{
- "dockerCompose": result.DockerCompose,
- "envVars": result.EnvVars,
- "serviceName": result.ServiceName,
+ return cmdutil.Run(cmd, c, cmdutil.Spec[container.ActionResult]{
+ Method: http.MethodPost,
+ Path: types.SystemContainersStopAll(c.EnvID()),
+ FailureMessage: "failed to stop all containers",
+ Render: func(container.ActionResult) error { output.Success("%s", "Stopped all containers"); return nil },
})
- }
-
- output.Header("Conversion Result")
- if result.ServiceName != "" {
- _, _ = fmt.Fprintf(output.Stdout(), "Service: %s\n\n", result.ServiceName)
- }
- if result.DockerCompose != "" {
- _, _ = fmt.Fprintln(output.Stdout(), "Docker Compose:")
- _, _ = fmt.Fprintln(output.Stdout(), result.DockerCompose)
- }
- if result.EnvVars != "" {
- _, _ = fmt.Fprintln(output.Stdout(), "Environment Variables:")
- _, _ = fmt.Fprintln(output.Stdout(), result.EnvVars)
- }
- return nil
- },
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-var forceFlag bool
+func newConvertCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "convert <docker-run-command>",
+ Short: "Convert docker run command to compose",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var upgradeCmd = &cobra.Command{
- Use: "upgrade",
- Short: "Trigger system upgrade",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if upgradeAllStatusFlag && !upgradeAllFlag {
- return errors.New("--status requires --all")
- }
- if upgradeCheckFlag && upgradeAllFlag {
- return errors.New("--check cannot be combined with --all")
- }
- if app, ok := runtime.From(cmd.Context()); ok && app.PreviewEnabled() {
- if upgradeCheckFlag {
- return cmdutil.RunEnvironments(cmd, args, func(command *cobra.Command, _ []string) error { return runUpgradeCheck(command) }, false)
+ resp, err := c.Post(cmd.Context(), types.SystemConvert(c.EnvID()), system.ConvertDockerRunRequest{DockerRunCommand: args[0]})
+ if err != nil {
+ return fmt.Errorf("failed to convert command: %w", err)
}
- environments, discoveryErr := app.Environments(cmd.Context())
- if discoveryErr != nil {
- return discoveryErr
+ defer func() { _ = resp.Body.Close() }()
+ body, readErr := cmdutil.ReadJSONBody(resp)
+ if readErr != nil {
+ return fmt.Errorf("failed to convert command: %w", readErr)
}
- if len(environments) == 0 {
- return errors.New("no enabled environments available")
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
}
- for _, env := range environments {
- _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Upgrade environment: %s (%s)\n", cmp.Or(env.Name, env.ID), env.ID)
+ var result system.ConvertDockerRunResponse
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to convert command: failed to decode response: %w", decodeErr)
}
- app.SelectEnvironment("0")
- defer app.SelectEnvironment("")
- return runUpgradeAll(cmd)
- }
- if upgradeAllFlag {
- return runUpgradeAll(cmd)
- }
- if upgradeCheckFlag {
- return runUpgradeCheck(cmd)
- }
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to upgrade the system?")
- if err != nil {
- return err
+ output.Header("Conversion Result")
+ if result.ServiceName != "" {
+ _, _ = fmt.Fprintf(output.Stdout(), "Service: %s\n\n", result.ServiceName)
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+ if result.DockerCompose != "" {
+ _, _ = fmt.Fprintln(output.Stdout(), "Docker Compose:")
+ _, _ = fmt.Fprintln(output.Stdout(), result.DockerCompose)
}
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // The upgrade payload type is backend-internal, so the envelope stays
- // untyped to keep --json output complete.
- return cmdutil.RunPostAction[any](cmd, c, cmdutil.PostActionSpec{
- Path: types.SystemUpgrade(c.EnvID()),
- FailureMessage: "failed to upgrade system",
- SuccessMessage: "System upgrade initiated",
- JSON: jsonOutput,
- })
- },
+ if result.EnvVars != "" {
+ _, _ = fmt.Fprintln(output.Stdout(), "Environment Variables:")
+ _, _ = fmt.Fprintln(output.Stdout(), result.EnvVars)
+ }
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ return cmd
}
-var upgradeCheckFlag bool
+func newUpgradeCmd() *cobra.Command {
+ var opts struct{ force, all, status, check bool }
+ cmd := &cobra.Command{
+ Use: "upgrade",
+ Short: "Trigger system upgrade",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ PreRunE: func(cmd *cobra.Command, _ []string) error {
+ if opts.status && !opts.all {
+ return errors.New("--status requires --all")
+ }
+ return cmdutil.ExclusiveFlags(cmd, "check", "all")
+ },
+ RunE: func(cmd *cobra.Command, args []string) error {
+ app, _ := runtime.From(cmd.Context())
+ switch {
+ case opts.check:
+ return cmdutil.RunEnvironments(cmd, args, runUpgradeCheck, false)
+ case app.PreviewEnabled() || opts.all:
+ return runUpgradeAll(cmd, opts.force, opts.status)
+ default:
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.force, "Are you sure you want to upgrade the system?")
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[any]{
+ Method: http.MethodPost,
+ Path: types.SystemUpgrade(c.EnvID()),
+ FailureMessage: "failed to upgrade system",
+ Render: func(any) error { output.Success("System upgrade initiated"); return nil },
+ })
+ }
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Skip confirmation")
+ cmd.Flags().BoolVar(&opts.all, "all", false, "Update all environments with available updates")
+ cmd.Flags().BoolVar(&opts.status, "status", false, "Show the status of the latest update-all job (requires --all)")
+ cmd.Flags().BoolVar(&opts.check, "check", false, "Only check whether an upgrade is available")
+ cmdutil.SetScope(cmdutil.ScopeGlobal, cmd)
+ return cmd
+}
-func runUpgradeCheck(cmd *cobra.Command) error {
+func runUpgradeCheck(cmd *cobra.Command, _ []string) error {
c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
-
- // This endpoint returns its payload directly, not wrapped in an
- // ApiResponse envelope.
- type upgradeCheckResult struct {
- CanUpgrade bool `json:"canUpgrade"`
- Error bool `json:"error"`
- Message string `json:"message"`
- }
- result, err := c.DoJSON[upgradeCheckResult](cmd.Context(), http.MethodGet, types.SystemUpgradeCheck(c.EnvID()), nil)
+ // Upgrade checks return a direct payload rather than an API envelope.
+ body, err := c.DoRaw(cmd.Context(), http.MethodGet, types.SystemUpgradeCheck(c.EnvID()), nil)
if err != nil {
return fmt.Errorf("failed to check for upgrades: %w", err)
}
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
+ }
+ var result system.UpgradeCheckResult
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to check for upgrades: failed to decode response: %w", decodeErr)
}
-
output.Header("Upgrade Check")
output.KeyValue("Can Upgrade", strconv.FormatBool(result.CanUpgrade))
output.KeyValue("Message", result.Message)
@@ -289,26 +300,53 @@ func runUpgradeCheck(cmd *cobra.Command) error {
return nil
}
-// environmentUpdateJob mirrors the backend fleet update payload, which has no shared public DTO.
-type environmentUpdateJob struct {
- ID string `json:"id"`
- Status string `json:"status"`
- Username string `json:"username"`
- ManagerVersionAtStart string `json:"managerVersionAtStart"`
- ManagerTargetVersion string `json:"managerTargetVersion"`
- Results []struct {
- EnvironmentID string `json:"environmentId"`
- EnvironmentName string `json:"environmentName"`
- Status string `json:"status"`
- FromVersion string `json:"fromVersion,omitempty"`
- ToVersion string `json:"toVersion,omitempty"`
- Error string `json:"error,omitempty"`
- } `json:"results,omitempty"`
- Error *string `json:"error,omitempty"`
- CompletedAt *time.Time `json:"completedAt,omitempty"`
+func runUpgradeAll(cmd *cobra.Command, force, status bool) error {
+ app, _ := runtime.From(cmd.Context())
+ if app.PreviewEnabled() {
+ environments, discoveryErr := app.Environments(cmd.Context())
+ if discoveryErr != nil {
+ return discoveryErr
+ }
+ if len(environments) == 0 {
+ return errors.New("no enabled environments available")
+ }
+ for _, env := range environments {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Upgrade environment: %s (%s)\n", cmp.Or(env.Name, env.ID), env.ID)
+ }
+ app.SelectEnvironment("0")
+ defer app.SelectEnvironment("")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ if status {
+ return cmdutil.Run(cmd, c, cmdutil.Spec[system.EnvironmentUpdateJob]{
+ Method: http.MethodGet,
+ Path: types.SystemUpgradeAllStatus(c.EnvID()),
+ FailureMessage: "failed to get update-all status",
+ Render: func(data system.EnvironmentUpdateJob) error {
+ output.Header("Update-All Status")
+ return renderUpgradeResults(data)
+ },
+ })
+ }
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, force, "Are you sure you want to update all environments?")
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[system.EnvironmentUpdateJob]{
+ Method: http.MethodPost,
+ Path: types.SystemUpgradeAll(c.EnvID()),
+ FailureMessage: "failed to trigger update-all",
+ Render: func(data system.EnvironmentUpdateJob) error {
+ output.Success("Update-all started")
+ return renderUpgradeResults(data)
+ },
+ })
}
-func printUpdateAllJob(job environmentUpdateJob) error {
+func renderUpgradeResults(job system.EnvironmentUpdateJob) error {
output.KeyValue("Status", job.Status)
if job.Username != "" {
output.KeyValue("Triggered By", job.Username)
@@ -328,91 +366,12 @@ func printUpdateAllJob(job environmentUpdateJob) error {
if len(job.Results) == 0 {
return nil
}
-
- headers := []string{"ENVIRONMENT", "STATUS", "FROM", "TO", "ERROR"}
rows := make([][]string, len(job.Results))
for i, res := range job.Results {
- name := cmp.Or(res.EnvironmentName, res.EnvironmentID)
- resErr := cmp.Or(res.Error, "-")
- rows[i] = []string{name, res.Status, res.FromVersion, res.ToVersion, resErr}
+ rows[i] = []string{cmp.Or(res.EnvironmentName, res.EnvironmentID), res.Status, res.FromVersion, res.ToVersion, cmp.Or(res.Error, "-")}
}
if _, spacingErr := fmt.Fprintln(output.Stdout()); spacingErr != nil {
return fmt.Errorf("failed to print update status: %w", spacingErr)
}
- return output.Table(headers, rows)
-}
-
-var (
- upgradeAllFlag bool
- upgradeAllStatusFlag bool
-)
-
-func runUpgradeAll(cmd *cobra.Command) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- if upgradeAllStatusFlag {
- result, getUpgradeStatusErr := c.GetJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))
- if getUpgradeStatusErr != nil {
- return fmt.Errorf("failed to get update-all status: %w", getUpgradeStatusErr)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Update-All Status")
- return printUpdateAllJob(result.Data)
- }
-
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, "Are you sure you want to update all environments?")
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- result, err := c.PostJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAll(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to trigger update-all: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Update-all started")
- return printUpdateAllJob(result.Data)
-}
-
-func init() {
- cmdutil.SetScope(cmdutil.ScopeRead, dockerInfoCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, pruneCmd, containersStartCmd, containersStopCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, convertCmd)
- cmdutil.SetScope(cmdutil.ScopeGlobal, upgradeCmd)
- SystemCmd.AddCommand(pruneCmd)
- SystemCmd.AddCommand(dockerInfoCmd)
- SystemCmd.AddCommand(systemContainersCmd)
- SystemCmd.AddCommand(convertCmd)
- SystemCmd.AddCommand(upgradeCmd)
- systemContainersCmd.AddCommand(containersStartCmd)
- systemContainersCmd.AddCommand(containersStopCmd)
-
- pruneCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- dockerInfoCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersStartCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- containersStartCmd.Flags().BoolVar(&startStoppedOnlyFlag, "stopped", false, "Only start containers that are currently stopped")
- containersStopCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- convertCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- upgradeCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Skip confirmation")
- upgradeCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- upgradeCmd.Flags().BoolVar(&upgradeAllFlag, "all", false, "Update all environments with available updates")
- upgradeCmd.Flags().BoolVar(&upgradeAllStatusFlag, "status", false, "Show the status of the latest update-all job (requires --all)")
- upgradeCmd.Flags().BoolVar(&upgradeCheckFlag, "check", false, "Only check whether an upgrade is available")
+ return output.Table([]string{"ENVIRONMENT", "STATUS", "FROM", "TO", "ERROR"}, rows)
}
diff --git a/cli/pkg/system/cmd_test.go b/cli/pkg/system/cmd_test.go
index 33cfaf2df..1524c6edc 100644
--- a/cli/pkg/system/cmd_test.go
+++ b/cli/pkg/system/cmd_test.go
@@ -44,7 +44,7 @@ func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {
partial bool
cancel bool
}{
- {name: "fleet succeeds"}, {name: "fleet continues after failure", partial: true}, {name: "fleet confirmation cancelled", cancel: true},
+ {name: "fleet succeeds"}, {name: "fleet continues after failure", partial: true}, {name: "fleet requires consent without a terminal", cancel: true},
} {
t.Run(tc.name, func(t *testing.T) {
var mu sync.Mutex
@@ -76,10 +76,10 @@ func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {
paths := append([]string(nil), mutations...)
mu.Unlock()
if tc.cancel {
- require.NoError(t, runErr)
+ require.ErrorContains(t, runErr, "re-run with --yes")
require.Empty(t, paths)
require.Empty(t, out)
- require.Contains(t, diagnostics, "Local (0), Remote (remote)")
+ require.Contains(t, diagnostics, "Local, Remote")
return
}
require.Equal(t, []string{"/api/environments/0/system/containers/start-all", "/api/environments/remote/system/containers/start-all"}, paths)
diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.go
index 383be00c7..28f7f36e9 100644
--- a/cli/pkg/templates/cmd.go
+++ b/cli/pkg/templates/cmd.go
@@ -1,9 +1,12 @@
package templates
import (
+ "cmp"
"context"
- "errors"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"fmt"
+ "net/http"
"net/url"
"os"
"path/filepath"
@@ -16,7 +19,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/template"
"github.com/spf13/cobra"
- kit "go.getarcane.app/kit/pkg"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
@@ -25,297 +28,302 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- templateListAll bool
- forceFlag bool
- jsonOutput bool
-
- templateUpdateName string
- templateUpdateFile string
- templateUpdateDescription string
- templateUpdateEnvFile string
- templateCreateName string
- templateCreateFile string
- templateCreateDescription string
- templateCreateEnvFile string
- templateDownloadOutput string
- templateDefaultsSaveFile string
- templateDefaultsEnvFile string
- templateFetchURL string
- templateRegUpdateName string
- templateRegUpdateURL string
- templateRegUpdateDesc string
- templateRegUpdateEnabled bool
- templateRegUpdateDisabled bool
-)
-
-// TemplatesCmd is the parent command for template operations
-var TemplatesCmd = &cobra.Command{
- Use: "templates",
- Aliases: []string{"template", "tpl"},
- Short: "Manage Docker Compose templates",
-}
-
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List local templates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- headers := []string{"NAME", "CUSTOM", "REMOTE", "DESCRIPTION"}
- row := func(tpl template.Template) []string {
- custom := "no"
- if tpl.IsCustom {
- custom = "yes"
- }
- remote := "no"
- if tpl.IsRemote {
- remote = "yes"
+// Command is the parent command for template operations
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "templates",
+ Aliases: []string{"template", "tpl"},
+ Short: "Manage Docker Compose templates",
+ }
+ cmd.AddCommand(newListCmd())
+ cmd.AddCommand(newDefaultCmd())
+ cmd.AddCommand(newContentCmd())
+ cmd.AddCommand(newRegistriesCmd())
+ cmd.AddCommand(newDeleteCmd())
+ cmd.AddCommand(newGetCmd())
+ cmd.AddCommand(newCreateCmd())
+ cmd.AddCommand(newUpdateCmd())
+ cmd.AddCommand(newDownloadCmd())
+ cmd.AddCommand(newFetchCmd())
+ return cmd
+}
+
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ templateListAll bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List local templates",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- return []string{
- tpl.Name,
- custom,
- remote,
- tpl.Description,
- }
- }
- if templateListAll {
- if cmd.Flags().Changed("limit") || cmd.Flags().Changed("start") {
- return errors.New("--all cannot be combined with explicit pagination flags")
+ headers := []string{"NAME", "CUSTOM", "REMOTE", "DESCRIPTION"}
+
+ if opts.templateListAll {
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]template.Template]{
+ Method: http.MethodGet,
+ Path: types.TemplatesAll(),
+ FailureMessage: "failed to list templates",
+ Render: func(data []template.Template) error {
+ rows := make([][]string, len(data))
+ for i, tpl := range data {
+ rows[i] = []string{
+ tpl.Name,
+ kit.Ternary(tpl.IsCustom, "yes", "no"),
+ kit.Ternary(tpl.IsRemote, "yes", "no"),
+ tpl.Description,
+ }
+ }
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ output.Showing(len(data), int64(len(data)), "templates")
+ return nil
+ },
+ })
}
- result, listTemplatesErr := c.GetJSON[[]template.Template](cmd.Context(), types.TemplatesAll())
- if listTemplatesErr != nil {
- return fmt.Errorf("failed to list templates: %w", listTemplatesErr)
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[template.Template]{
+ Resource: "templates",
+ Endpoint: types.Templates(),
+ Params: cmdutil.ListParams{Resource: "templates", Limit: opts.limit, FallbackDefault: 20, Start: opts.start},
+ Headers: headers,
+ Row: func(tpl template.Template) []string {
+ return []string{
+ tpl.Name,
+ kit.Ternary(tpl.IsCustom, "yes", "no"),
+ kit.Ternary(tpl.IsRemote, "yes", "no"),
+ tpl.Description,
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of templates to show")
+ cmd.Flags().IntVar(&opts.start, "start", 0, "Offset for pagination")
+ cmd.Flags().BoolVarP(&opts.templateListAll, "all", "a", false, "List all templates (including remote)")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
+ if conflictErr := cmdutil.ExclusiveFlags(cmd, "all", "limit"); conflictErr != nil {
+ return conflictErr
+ }
+ return cmdutil.ExclusiveFlags(cmd, "all", "start")
+ }
+ return cmd
+}
+
+func newDefaultCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "default",
+ Short: "Get default templates",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
+ return cmdutil.Run(cmd, c, cmdutil.Spec[template.DefaultTemplatesResponse]{
+ Method: http.MethodGet,
+ Path: types.TemplatesDefault(),
+ FailureMessage: "failed to get default templates",
+ Render: func(data template.DefaultTemplatesResponse) error {
+ output.Header("Default Templates")
+ output.KeyValue("Compose Template", fmt.Sprintf("%d bytes", len(data.ComposeTemplate)))
+ output.KeyValue("Env Template", fmt.Sprintf("%d bytes", len(data.EnvTemplate)))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.AddCommand(newDefaultsSaveCmd())
+ return cmd
+}
+
+func newContentCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "content <template-id>",
+ Short: "Get template content",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- rows := make([][]string, len(result.Data))
- for i, tpl := range result.Data {
- rows[i] = row(tpl)
- }
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
+ return cmdutil.Run(cmd, c, cmdutil.Spec[template.TemplateContent]{
+ Method: http.MethodGet,
+ Path: types.TemplateContent(args[0]),
+ FailureMessage: "failed to get template content",
+ Render: func(data template.TemplateContent) error {
+ output.Header("Template Content")
+ output.KeyValue("Name", data.Template.Name)
+ output.KeyValue("Description", data.Template.Description)
+ output.KeyValue("Services", strconv.Itoa(len(data.Services)))
+ output.KeyValue("Env Variables", strconv.Itoa(len(data.EnvVariables)))
+ _, _ = fmt.Fprintln(output.Stdout(), "\n--- Compose Content ---")
+ _, _ = fmt.Fprintln(output.Stdout(), data.Content)
+ if data.EnvContent != "" {
+ _, _ = fmt.Fprintln(output.Stdout(), "\n--- Environment Content ---")
+ _, _ = fmt.Fprintln(output.Stdout(), data.EnvContent)
+ }
+ return nil
+ },
+ })
+ },
+ }
+}
+
+func newRegistriesCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "registries",
+ Aliases: []string{"reg"},
+ Short: "List template registries",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- output.Showing(len(result.Data), int64(len(result.Data)), "templates")
- return nil
- }
-
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[template.Template]{
- Resource: "templates",
- Endpoint: types.Templates(),
- Params: cmdutil.ListParams{Resource: "templates", Limit: limitFlag, FallbackDefault: 20, Start: startFlag},
- JSON: jsonOutput,
- Headers: headers,
- Row: row,
- })
- },
-}
-
-var defaultCmd = &cobra.Command{
- Use: "default",
- Short: "Get default templates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[template.DefaultTemplatesResponse](cmd.Context(), types.TemplatesDefault())
- if err != nil {
- return fmt.Errorf("failed to get default templates: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Default Templates")
- output.KeyValue("Compose Template", fmt.Sprintf("%d bytes", len(result.Data.ComposeTemplate)))
- output.KeyValue("Env Template", fmt.Sprintf("%d bytes", len(result.Data.EnvTemplate)))
- return nil
- },
-}
-
-var contentCmd = &cobra.Command{
- Use: "content <template-id>",
- Short: "Get template content",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
- result, err := c.GetJSON[template.TemplateContent](cmd.Context(), types.TemplateContent(args[0]))
- if err != nil {
- return fmt.Errorf("failed to get template content: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Template Content")
- output.KeyValue("Name", result.Data.Template.Name)
- output.KeyValue("Description", result.Data.Template.Description)
- output.KeyValue("Services", strconv.Itoa(len(result.Data.Services)))
- output.KeyValue("Env Variables", strconv.Itoa(len(result.Data.EnvVariables)))
- _, _ = fmt.Fprintln(output.Stdout(), "\n--- Compose Content ---")
- _, _ = fmt.Fprintln(output.Stdout(), result.Data.Content)
- if result.Data.EnvContent != "" {
- _, _ = fmt.Fprintln(output.Stdout(), "\n--- Environment Content ---")
- _, _ = fmt.Fprintln(output.Stdout(), result.Data.EnvContent)
- }
- return nil
- },
-}
-
-var registriesCmd = &cobra.Command{
- Use: "registries",
- Aliases: []string{"reg"},
- Short: "List template registries",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())
- if err != nil {
- return fmt.Errorf("failed to list registries: %w", err)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]template.TemplateRegistry]{
+ Method: http.MethodGet,
+ Path: types.TemplatesRegistries(),
+ FailureMessage: "failed to list registries",
+ Render: func(data []template.TemplateRegistry) error {
+ headers := []string{"ID", "NAME", "URL", "ENABLED"}
+ rows := make([][]string, len(data))
+ for i, reg := range data {
+ enabled := kit.Ternary(reg.Enabled, "yes", "no")
+ rows[i] = []string{
+ reg.ID,
+ reg.Name,
+ reg.URL,
+ enabled,
+ }
+ }
+
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d registries\n", len(data))
+ return nil
+ },
+ })
+ },
+ }
+ cmd.AddCommand(newRegistriesUpdateCmd())
+ cmd.AddCommand(newDeleteRegistryCmd())
+ return cmd
+}
+
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <template-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete template",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ label := "template " + args[0]
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete %s?", label),
+ Path: types.Template(args[0]),
+ Body: nil,
+ FailureMessage: "failed to delete " + label,
+ SuccessMessage: fmt.Sprintf("Deleted %s successfully", label),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return cmd
+}
+
+func newDeleteRegistryCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <registry-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete template registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ label := "template registry " + args[0]
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- headers := []string{"ID", "NAME", "URL", "ENABLED"}
- rows := make([][]string, len(result.Data))
- for i, reg := range result.Data {
- enabled := "no"
- if reg.Enabled {
- enabled = "yes"
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete %s?", label),
+ Path: types.TemplateRegistry(args[0]),
+ Body: nil,
+ FailureMessage: "failed to delete " + label,
+ SuccessMessage: fmt.Sprintf("Deleted %s successfully", label),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force deletion without confirmation")
+ return cmd
+}
+
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <template>",
+ Short: "Get a template by ID or name",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
}
- rows[i] = []string{
- reg.ID,
- reg.Name,
- reg.URL,
- enabled,
+
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := templateRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- }
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
- }
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d registries\n", len(result.Data))
- return nil
- },
-}
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
-func runTemplateDeleteInternal(cmd *cobra.Command, label, path string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete %s?", label))
- if err != nil {
- return err
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
+ tpl := *resolved
+ output.Header("Template")
+ output.KeyValue("ID", tpl.ID)
+ output.KeyValue("Name", tpl.Name)
+ output.KeyValue("Description", tpl.Description)
+ custom := kit.Ternary(tpl.IsCustom, "yes", "no")
+ remote := kit.Ternary(tpl.IsRemote, "yes", "no")
+ output.KeyValue("Custom", custom)
+ output.KeyValue("Remote", remote)
return nil
- }
- }
-
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to delete %s: %w", label, err)
+ },
}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Deleted %s successfully", label)
- return nil
-}
-
-var deleteCmd = &cobra.Command{
- Use: "delete <template-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete template",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runTemplateDeleteInternal(cmd, "template "+args[0], types.Template(args[0]))
- },
-}
-
-var deleteRegistryCmd = &cobra.Command{
- Use: "delete <registry-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete template registry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- return runTemplateDeleteInternal(cmd, "template registry "+args[0], types.TemplateRegistry(args[0]))
- },
-}
-
-var getCmd = &cobra.Command{
- Use: "get <template>",
- Short: "Get a template by ID or name",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := templateRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
-
- tpl := *resolved
- output.Header("Template")
- output.KeyValue("ID", tpl.ID)
- output.KeyValue("Name", tpl.Name)
- output.KeyValue("Description", tpl.Description)
- custom := "no"
- if tpl.IsCustom {
- custom = "yes"
- }
- remote := "no"
- if tpl.IsRemote {
- remote = "yes"
- }
- output.KeyValue("Custom", custom)
- output.KeyValue("Remote", remote)
- return nil
- },
}
var templateRef = cmdutil.ResourceRef[template.Template, template.Template]{
@@ -324,12 +332,12 @@ var templateRef = cmdutil.ResourceRef[template.Template, template.Template]{
IDHint: "the template ID",
ListCmd: "arcane templates list",
GetPath: func(_, identifier string) string { return types.Template(identifier) },
- SearchCandidates: searchTemplateCandidatesInternal,
- SelectCandidate: selectTemplateCandidateInternal,
+ SearchCandidates: searchTemplateCandidates,
+ SelectCandidate: selectTemplateCandidate,
Promote: func(match template.Template) *template.Template { return &match },
}
-func searchTemplateCandidatesInternal(ctx context.Context, c *client.Client, identifier string) ([]template.Template, error) {
+func searchTemplateCandidates(ctx context.Context, c *client.Client, identifier string) ([]template.Template, error) {
result, err := c.GetJSON[[]template.Template](ctx, types.TemplatesAll())
if err != nil {
return nil, fmt.Errorf("failed to search templates: %w", err)
@@ -358,22 +366,27 @@ func searchTemplateCandidatesInternal(ctx context.Context, c *client.Client, ide
if len(partialMatches) == 1 {
return partialMatches, nil
}
- if len(partialMatches) > 1 {
- ranked := rankFuzzyTemplateMatchesInternal(identifier, partialMatches)
- if isConfidentBestFuzzyMatchInternal(ranked) {
- return []template.Template{ranked[0].template}, nil
- }
- return topTemplatesFromRankedMatchesInternal(ranked, cmdutil.MaxPromptOptions), nil
+ candidates := result.Data
+ if len(partialMatches) > 0 {
+ candidates = partialMatches
}
-
- ranked := rankFuzzyTemplateMatchesInternal(identifier, result.Data)
- if isConfidentBestFuzzyMatchInternal(ranked) {
+ ranked := rankFuzzyTemplateMatches(identifier, candidates)
+ if len(ranked) == 0 {
+ return nil, nil
+ }
+ best := ranked[0].score
+ if best <= 110 && (len(ranked) == 1 || ranked[1].score-best >= 8) {
return []template.Template{ranked[0].template}, nil
}
- return topTemplatesFromRankedMatchesInternal(ranked, cmdutil.MaxPromptOptions), nil
+ limit := min(cmdutil.MaxPromptOptions, len(ranked))
+ selected := make([]template.Template, 0, limit)
+ for i := range limit {
+ selected = append(selected, ranked[i].template)
+ }
+ return selected, nil
}
-func selectTemplateCandidateInternal(matches []template.Template, identifier string, allowPrompt bool) (*template.Template, error) {
+func selectTemplateCandidate(matches []template.Template, identifier string, allowPrompt bool) (*template.Template, error) {
if len(matches) == 0 {
return nil, nil
}
@@ -381,7 +394,16 @@ func selectTemplateCandidateInternal(matches []template.Template, identifier str
return &matches[0], nil
}
if !allowPrompt || len(matches) > cmdutil.MaxPromptOptions {
- return nil, fmt.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidatesInternal(matches))
+ const previewLimit = 5
+ limit := min(len(matches), previewLimit)
+ parts := make([]string, 0, limit+1)
+ for i := range limit {
+ parts = append(parts, fmt.Sprintf("%s (%s)", matches[i].Name, matches[i].ID))
+ }
+ if len(matches) > limit {
+ parts = append(parts, fmt.Sprintf("and %d more", len(matches)-limit))
+ }
+ return nil, fmt.Errorf("ambiguous template %q: %s", identifier, strings.Join(parts, ", "))
}
ordered := slices.Clone(matches)
@@ -396,7 +418,9 @@ func selectTemplateCandidateInternal(matches []template.Template, identifier str
options := make([]string, len(ordered))
for i, candidate := range ordered {
- options[i] = templateOptionLabelInternal(candidate)
+ source := kit.Ternary(candidate.IsRemote, "remote", "local")
+ custom := kit.Ternary(candidate.IsCustom, "custom", "builtin")
+ options[i] = fmt.Sprintf("%s (id: %s, %s, %s)", candidate.Name, candidate.ID, source, custom)
}
choice, err := prompt.Select("template", options)
if err != nil {
@@ -405,32 +429,26 @@ func selectTemplateCandidateInternal(matches []template.Template, identifier str
return &ordered[choice], nil
}
-func templateOptionLabelInternal(candidate template.Template) string {
- source := kit.Ternary(candidate.IsRemote, "remote", "local")
- custom := kit.Ternary(candidate.IsCustom, "custom", "builtin")
- return fmt.Sprintf("%s (id: %s, %s, %s)", candidate.Name, candidate.ID, source, custom)
-}
-
-type rankedTemplateMatchInternal struct {
+type rankedTemplateMatch struct {
template template.Template
score int
}
-func rankFuzzyTemplateMatchesInternal(query string, candidates []template.Template) []rankedTemplateMatchInternal {
- normalizedQuery := normalizeSearchTokenInternal(query)
+func rankFuzzyTemplateMatches(query string, candidates []template.Template) []rankedTemplateMatch {
+ normalizedQuery := normalizeSearchToken(query)
if normalizedQuery == "" {
return nil
}
- ranked := make([]rankedTemplateMatchInternal, 0, len(candidates))
+ ranked := make([]rankedTemplateMatch, 0, len(candidates))
for _, candidate := range candidates {
- nameScore, nameMatches := fuzzyScoreInternal(normalizedQuery, normalizeSearchTokenInternal(candidate.Name))
- idScore, idMatches := fuzzyScoreInternal(normalizedQuery, normalizeSearchTokenInternal(candidate.ID))
+ nameScore, nameMatches := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.Name))
+ idScore, idMatches := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.ID))
score := 0
matched := false
switch {
case nameMatches && idMatches:
- score = kit.Ternary(idScore < nameScore, idScore+10, nameScore)
+ score = min(nameScore, idScore+10)
matched = true
case nameMatches:
score = nameScore
@@ -440,7 +458,7 @@ func rankFuzzyTemplateMatchesInternal(query string, candidates []template.Templa
matched = true
}
if matched {
- ranked = append(ranked, rankedTemplateMatchInternal{template: candidate, score: score})
+ ranked = append(ranked, rankedTemplateMatch{template: candidate, score: score})
}
}
@@ -456,7 +474,7 @@ func rankFuzzyTemplateMatchesInternal(query string, candidates []template.Templa
return ranked
}
-func normalizeSearchTokenInternal(value string) string {
+func normalizeSearchToken(value string) string {
var builder strings.Builder
builder.Grow(len(value))
for _, r := range strings.ToLower(strings.TrimSpace(value)) {
@@ -467,7 +485,7 @@ func normalizeSearchTokenInternal(value string) string {
return builder.String()
}
-func fuzzyScoreInternal(query, target string) (int, bool) {
+func fuzzyScore(query, target string) (int, bool) {
if query == "" || target == "" {
return 0, false
}
@@ -475,20 +493,20 @@ func fuzzyScoreInternal(query, target string) (int, bool) {
return 0, true
}
if strings.Contains(target, query) {
- return 10 + absIntInternal(len(target)-len(query)), true
+ return 10 + absInt(len(target)-len(query)), true
}
- if gap, ok := subsequenceGapPenaltyInternal(query, target); ok {
+ if gap, ok := subsequenceGapPenalty(query, target); ok {
return 40 + gap, true
}
- distance := levenshteinDistanceInternal(query, target)
+ distance := levenshteinDistance(query, target)
if distance <= max(2, len(query)/3) {
- return 80 + (distance * 8) + absIntInternal(len(target)-len(query)), true
+ return 80 + (distance * 8) + absInt(len(target)-len(query)), true
}
return 0, false
}
-func subsequenceGapPenaltyInternal(query, target string) (int, bool) {
+func subsequenceGapPenalty(query, target string) (int, bool) {
queryRunes := []rune(query)
targetRunes := []rune(target)
if len(queryRunes) == 0 {
@@ -506,15 +524,13 @@ func subsequenceGapPenaltyInternal(query, target string) (int, bool) {
}
queryIndex++
if queryIndex == len(queryRunes) {
- span := (index - start) + 1
- gaps := span - len(queryRunes)
- return gaps + absIntInternal(len(targetRunes)-len(queryRunes)), true
+ return index - start + 1 - len(queryRunes) + absInt(len(targetRunes)-len(queryRunes)), true
}
}
return 0, false
}
-func levenshteinDistanceInternal(left, right string) int {
+func levenshteinDistance(left, right string) int {
leftRunes := []rune(left)
rightRunes := []rune(right)
if len(leftRunes) == 0 {
@@ -544,410 +560,344 @@ func levenshteinDistanceInternal(left, right string) int {
return previous[len(rightRunes)]
}
-func isConfidentBestFuzzyMatchInternal(matches []rankedTemplateMatchInternal) bool {
- if len(matches) == 0 {
- return false
- }
- best := matches[0].score
- if len(matches) == 1 {
- return best <= 110
- }
- return best <= 110 && matches[1].score-best >= 8
-}
-
-func topTemplatesFromRankedMatchesInternal(matches []rankedTemplateMatchInternal, limit int) []template.Template {
- if limit <= 0 || len(matches) == 0 {
- return nil
- }
- limit = min(limit, len(matches))
- result := make([]template.Template, 0, limit)
- for i := range limit {
- result = append(result, matches[i].template)
- }
- return result
-}
-
-func absIntInternal(value int) int {
+func absInt(value int) int {
return kit.Ternary(value < 0, -value, value)
}
-func formatTemplateCandidatesInternal(matches []template.Template) string {
- if len(matches) == 0 {
- return "no matches"
- }
- const previewLimit = 5
- limit := min(len(matches), previewLimit)
- parts := make([]string, 0, limit+1)
- for i := range limit {
- parts = append(parts, fmt.Sprintf("%s (%s)", matches[i].Name, matches[i].ID))
- }
- if len(matches) > limit {
- parts = append(parts, fmt.Sprintf("and %d more", len(matches)-limit))
- }
- return strings.Join(parts, ", ")
-}
-
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new template",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- content, err := os.ReadFile(templateCreateFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", templateCreateFile, err)
- }
-
- req := template.CreateRequest{
- Name: templateCreateName,
- Description: templateCreateDescription,
- Content: string(content),
- }
-
- if templateCreateEnvFile != "" {
- envContent, readFileErr := os.ReadFile(templateCreateEnvFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, readFileErr)
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ file string
+ description string
+ envFile string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a new template",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ content, err := os.ReadFile(opts.file)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", opts.file, err)
}
- req.EnvContent = string(envContent)
- }
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.PostJSON[template.Template](cmd.Context(), types.Templates(), req)
- if err != nil {
- return fmt.Errorf("failed to create template: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Template created successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- return nil
- },
-}
-
-var updateCmd = &cobra.Command{
- Use: "update <template-id>",
- Short: "Update a template",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- // UpdateRequest has no omitempty fields and the handler replaces the whole
- // record, so an unset --file would otherwise wipe the compose content.
- // Start from the stored template and overlay only what was passed.
- current, err := fetchTemplateInternal(cmd, c, args[0])
- if err != nil {
- return err
- }
-
- req := template.UpdateRequest{
- Name: current.Name,
- Description: current.Description,
- Content: current.Content,
- }
- if current.EnvContent != nil {
- req.EnvContent = *current.EnvContent
- }
- if cmd.Flags().Changed("name") {
- req.Name = templateUpdateName
- }
- if cmd.Flags().Changed("description") {
- req.Description = templateUpdateDescription
- }
-
- if templateUpdateFile != "" {
- content, readFileErr := os.ReadFile(templateUpdateFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, readFileErr)
+ var envContent string
+ if opts.envFile != "" {
+ envData, readFileErr := os.ReadFile(opts.envFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", opts.envFile, readFileErr)
+ }
+ envContent = string(envData)
}
- req.Content = string(content)
- }
- if templateUpdateEnvFile != "" {
- envContent, readEnvFileErr := os.ReadFile(templateUpdateEnvFile)
- if readEnvFileErr != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, readEnvFileErr)
+ req := template.CreateRequest{
+ Name: opts.name,
+ Description: opts.description,
+ Content: string(content),
+ EnvContent: envContent,
}
- req.EnvContent = string(envContent)
- }
-
- result, err := c.PutJSON[template.Template](cmd.Context(), types.Template(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update template: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Template updated successfully")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- return nil
- },
-}
-var downloadCmd = &cobra.Command{
- Use: "download <template-id>",
- Short: "Download template compose file",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- result, err := c.PostJSON[template.Template](cmd.Context(), types.TemplateDownload(args[0]), nil)
- if err != nil {
- return fmt.Errorf("failed to download template: %w", err)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[template.Template]{
+ Method: http.MethodPost,
+ Path: types.Templates(),
+ Body: req,
+ FailureMessage: "failed to create template",
+ Render: func(data template.Template) error {
+ output.Success("Template created successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Template name")
+ cmd.Flags().StringVar(&opts.file, "file", "", "Path to Docker Compose file")
+ cmd.Flags().StringVar(&opts.description, "description", "", "Template description")
+ cmd.Flags().StringVar(&opts.envFile, "env-file", "", "Path to environment file")
+ _ = cmd.MarkFlagRequired("name")
+ _ = cmd.MarkFlagRequired("file")
+ return cmd
+}
+
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ file string
+ description string
+ envFile string
+ }
+ cmd := &cobra.Command{
+ Use: "update <template-id>",
+ Short: "Update a template",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- if templateDownloadOutput != "" {
- dir := filepath.Dir(templateDownloadOutput)
- if mkdirAllErr := os.MkdirAll(dir, 0o755); mkdirAllErr != nil {
- return fmt.Errorf("failed to create directory %s: %w", dir, mkdirAllErr)
+ // Preserve stored content and overlay only the changed flags.
+ currentResult, err := c.GetJSON[template.Template](cmd.Context(), types.Template(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to load template: %w", err)
}
- if writeFileErr := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); writeFileErr != nil {
- return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, writeFileErr)
+ current := currentResult.Data
+
+ content := current.Content
+ envContent := kit.FromPtr(current.EnvContent)
+ if opts.file != "" {
+ contentData, readFileErr := os.ReadFile(opts.file)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read file %s: %w", opts.file, readFileErr)
+ }
+ content = string(contentData)
}
- output.Success("Template downloaded to %s", templateDownloadOutput)
- return nil
- }
-
- _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)
- return nil
- },
-}
-
-var defaultsSaveCmd = &cobra.Command{
- Use: "save",
- Short: "Save default templates",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- content, err := os.ReadFile(templateDefaultsSaveFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", templateDefaultsSaveFile, err)
- }
-
- req := template.SaveDefaultTemplatesRequest{
- ComposeContent: string(content),
- }
- if templateDefaultsEnvFile != "" {
- envContent, readFileErr := os.ReadFile(templateDefaultsEnvFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, readFileErr)
+ if opts.envFile != "" {
+ envData, readEnvFileErr := os.ReadFile(opts.envFile)
+ if readEnvFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", opts.envFile, readEnvFileErr)
+ }
+ envContent = string(envData)
}
- req.EnvContent = string(envContent)
- }
-
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, cmdutil.PostActionSpec{
- Path: types.TemplatesDefault(),
- Body: req,
- FailureMessage: "failed to save default templates",
- SuccessMessage: "Default templates saved successfully",
- JSON: jsonOutput,
- })
- },
-}
-
-var registriesUpdateCmd = &cobra.Command{
- Use: "update <registry-id>",
- Short: "Update a template registry",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if templateRegUpdateEnabled && templateRegUpdateDisabled {
- return errors.New("--enabled and --disabled cannot be used together")
- }
-
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- // Every field on UpdateRegistryRequest is required and the handler does a
- // full replace, so start from the current registry and overlay only the
- // flags that were actually passed.
- current, err := fetchTemplateRegistryInternal(cmd, c, args[0])
- if err != nil {
- return err
- }
-
- req := template.UpdateRegistryRequest{
- Name: current.Name,
- URL: current.URL,
- Description: current.Description,
- Enabled: current.Enabled,
- }
- if cmd.Flags().Changed("name") {
- req.Name = templateRegUpdateName
- }
- if cmd.Flags().Changed("url") {
- req.URL = templateRegUpdateURL
- }
- if cmd.Flags().Changed("description") {
- req.Description = templateRegUpdateDesc
- }
- if templateRegUpdateEnabled {
- req.Enabled = true
- }
- if templateRegUpdateDisabled {
- req.Enabled = false
- }
-
- // The handler answers with a plain message, not the updated registry.
- result, err := c.PutJSON[base.MessageResponse](cmd.Context(), types.TemplateRegistry(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update registry: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Template registry updated successfully")
- output.KeyValue("ID", current.ID)
- output.KeyValue("Name", req.Name)
- return nil
- },
-}
+ req := template.UpdateRequest{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), opts.name, current.Name),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), opts.description, current.Description),
+ Content: content,
+ EnvContent: envContent,
+ }
-// fetchTemplateInternal loads a single template, including its content.
-func fetchTemplateInternal(cmd *cobra.Command, c *client.Client, id string) (template.Template, error) {
- result, err := c.GetJSON[template.Template](cmd.Context(), types.Template(id))
- if err != nil {
- return template.Template{}, fmt.Errorf("failed to load template: %w", err)
- }
- return result.Data, nil
-}
+ return cmdutil.Run(cmd, c, cmdutil.Spec[template.Template]{
+ Method: http.MethodPut,
+ Path: types.Template(args[0]),
+ Body: req,
+ FailureMessage: "failed to update template",
+ Render: func(data template.Template) error {
+ output.Success("Template updated successfully")
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Name", data.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Template name")
+ cmd.Flags().StringVar(&opts.file, "file", "", "Path to Docker Compose file")
+ cmd.Flags().StringVar(&opts.description, "description", "", "Template description")
+ cmd.Flags().StringVar(&opts.envFile, "env-file", "", "Path to environment file")
+ return cmd
+}
+
+func newDownloadCmd() *cobra.Command {
+ var opts struct{ outputFile, legacyOutput string }
+ cmd := &cobra.Command{
+ Use: "download <template-id>",
+ Short: "Download template compose file",
+ Example: " arcane templates download <template-id> --output-file compose.yaml\n arcane templates download <template-id> -o compose.yaml",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+ result, err := c.PostJSON[jsontext.Value](cmd.Context(), types.TemplateDownload(args[0]), nil)
+ if err != nil {
+ return fmt.Errorf("failed to download template: %w", err)
+ }
+ jsonMode := cmdutil.JSONOutputEnabled(cmd) || opts.legacyOutput == "json"
+ outputFile := cmp.Or(opts.outputFile, kit.Ternary(slices.Contains([]string{"text", "json"}, opts.legacyOutput), "", opts.legacyOutput))
+ if jsonMode && outputFile == "" {
+ if len(result.Data) == 0 {
+ return cmdutil.PrintJSON(nil)
+ }
+ return cmdutil.PrintRawJSON(result.Data)
+ }
+ var data template.Template
+ if decodeErr := json.Unmarshal(result.Data, &data); decodeErr != nil {
+ return fmt.Errorf("failed to download template: failed to decode response: %w", decodeErr)
+ }
+ if outputFile != "" {
+ dir := filepath.Dir(outputFile)
+ if mkdirErr := os.MkdirAll(dir, 0o755); mkdirErr != nil {
+ return fmt.Errorf("failed to create directory %s: %w", dir, mkdirErr)
+ }
+ if writeErr := os.WriteFile(outputFile, []byte(data.Content), 0o600); writeErr != nil {
+ return fmt.Errorf("failed to write file %s: %w", outputFile, writeErr)
+ }
+ if jsonMode {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Bytes int `json:"bytes"`
+ }{Path: outputFile, Bytes: len(data.Content)})
+ }
+ output.Success("Template downloaded to %s", outputFile)
+ return nil
+ }
+ _, writeErr := fmt.Fprint(output.Stdout(), data.Content)
+ return writeErr
+ },
+ }
+ cmd.Flags().StringVarP(&opts.outputFile, "output-file", "o", "", "Output file path")
+ cmd.Flags().StringVar(&opts.legacyOutput, "output", "", "Output file path")
+ _ = cmd.Flags().MarkDeprecated("output", "use --output-file or -o")
+ return cmd
+}
+
+func newDefaultsSaveCmd() *cobra.Command {
+ var opts struct {
+ saveFile string
+ envFile string
+ }
+ cmd := &cobra.Command{
+ Use: "save",
+ Short: "Save default templates",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ content, err := os.ReadFile(opts.saveFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", opts.saveFile, err)
+ }
-// fetchTemplateRegistryInternal looks a registry up by ID. The API exposes no
-// get-by-id route for template registries, so this filters the list.
-func fetchTemplateRegistryInternal(cmd *cobra.Command, c *client.Client, id string) (template.TemplateRegistry, error) {
- listed, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())
- if err != nil {
- return template.TemplateRegistry{}, fmt.Errorf("failed to load registry: %w", err)
- }
+ var envContent string
+ if opts.envFile != "" {
+ envData, readFileErr := os.ReadFile(opts.envFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", opts.envFile, readFileErr)
+ }
+ envContent = string(envData)
+ }
- for _, registry := range listed.Data {
- if registry.ID == id {
- return registry, nil
- }
- }
- return template.TemplateRegistry{}, fmt.Errorf("template registry %q not found", id)
-}
+ req := template.SaveDefaultTemplatesRequest{
+ ComposeContent: string(content),
+ EnvContent: envContent,
+ }
-var fetchCmd = &cobra.Command{
- Use: "fetch",
- Short: "Fetch remote template registries",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- path := cmdutil.AppendQuery(types.TemplateFetch(), url.Values{"url": []string{templateFetchURL}})
- result, err := c.GetJSON[template.RemoteRegistry](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to fetch templates: %w", err)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.TemplatesDefault(),
+ Body: req,
+ FailureMessage: "failed to save default templates",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", "Default templates saved successfully")
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.saveFile, "file", "", "Path to compose content file")
+ cmd.Flags().StringVar(&opts.envFile, "env-file", "", "Path to environment content file")
+ _ = cmd.MarkFlagRequired("file")
+ return cmd
+}
+
+func newRegistriesUpdateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ url string
+ desc string
+ enabled bool
+ disabled bool
+ }
+ cmd := &cobra.Command{
+ Use: "update <registry-id>",
+ Short: "Update a template registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ // Preserve required registry fields and overlay only the changed flags.
+ listed, err := c.GetJSON[[]template.TemplateRegistry](cmd.Context(), types.TemplatesRegistries())
+ if err != nil {
+ return fmt.Errorf("failed to load registry: %w", err)
+ }
+ index := slices.IndexFunc(listed.Data, func(registry template.TemplateRegistry) bool { return registry.ID == args[0] })
+ if index < 0 {
+ return fmt.Errorf("template registry %q not found", args[0])
+ }
+ current := listed.Data[index]
+
+ req := template.UpdateRegistryRequest{
+ Name: kit.Ternary(cmd.Flags().Changed("name"), opts.name, current.Name),
+ URL: kit.Ternary(cmd.Flags().Changed("url"), opts.url, current.URL),
+ Description: kit.Ternary(cmd.Flags().Changed("description"), opts.desc, current.Description),
+ Enabled: cmd.Flags().Changed("enabled") && opts.enabled ||
+ cmd.Flags().Changed("disabled") && !opts.disabled ||
+ !cmd.Flags().Changed("enabled") && !cmd.Flags().Changed("disabled") && current.Enabled,
+ }
- output.Success("Remote templates fetched successfully")
- return nil
- },
-}
+ // The handler answers with a plain message, not the updated registry.
+ return cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPut,
+ Path: types.TemplateRegistry(args[0]),
+ Body: req,
+ FailureMessage: "failed to update registry",
+ Render: func(base.MessageResponse) error {
+ output.Success("Template registry updated successfully")
+ output.KeyValue("ID", current.ID)
+ output.KeyValue("Name", req.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.name, "name", "", "Registry name")
+ cmd.Flags().StringVar(&opts.url, "url", "", "Registry URL")
+ cmd.Flags().StringVar(&opts.desc, "description", "", "Registry description")
+ cmd.Flags().BoolVar(&opts.enabled, "enabled", false, "Enable registry")
+ cmd.Flags().BoolVar(&opts.disabled, "disabled", false, "Disable registry")
+ _ = cmd.Flags().MarkDeprecated("disabled", "use --enabled=false")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "enabled", "disabled") }
+ return cmd
+}
+
+func newFetchCmd() *cobra.Command {
+ var opts struct {
+ url string
+ }
+ cmd := &cobra.Command{
+ Use: "fetch",
+ Short: "Fetch remote template registries",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
-func init() {
- TemplatesCmd.AddCommand(listCmd)
- TemplatesCmd.AddCommand(defaultCmd)
- TemplatesCmd.AddCommand(contentCmd)
- TemplatesCmd.AddCommand(registriesCmd)
- TemplatesCmd.AddCommand(deleteCmd)
- TemplatesCmd.AddCommand(getCmd)
- TemplatesCmd.AddCommand(createCmd)
- TemplatesCmd.AddCommand(updateCmd)
- TemplatesCmd.AddCommand(downloadCmd)
- TemplatesCmd.AddCommand(fetchCmd)
- defaultCmd.AddCommand(defaultsSaveCmd)
- registriesCmd.AddCommand(registriesUpdateCmd)
- registriesCmd.AddCommand(deleteRegistryCmd)
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of templates to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, "Offset for pagination")
- listCmd.Flags().BoolVarP(&templateListAll, "all", "a", false, "List all templates (including remote)")
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- defaultCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- contentCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- registriesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteRegistryCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
- deleteRegistryCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // create command flags
- createCmd.Flags().StringVar(&templateCreateName, "name", "", "Template name")
- createCmd.Flags().StringVar(&templateCreateFile, "file", "", "Path to Docker Compose file")
- createCmd.Flags().StringVar(&templateCreateDescription, "description", "", "Template description")
- createCmd.Flags().StringVar(&templateCreateEnvFile, "env-file", "", "Path to environment file")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("file")
-
- // update command flags
- updateCmd.Flags().StringVar(&templateUpdateName, "name", "", "Template name")
- updateCmd.Flags().StringVar(&templateUpdateFile, "file", "", "Path to Docker Compose file")
- updateCmd.Flags().StringVar(&templateUpdateDescription, "description", "", "Template description")
- updateCmd.Flags().StringVar(&templateUpdateEnvFile, "env-file", "", "Path to environment file")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // download command flags
- downloadCmd.Flags().StringVarP(&templateDownloadOutput, "output", "o", "", "Output file path")
- downloadCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // defaults-save command flags
- defaultsSaveCmd.Flags().StringVar(&templateDefaultsSaveFile, "file", "", "Path to compose content file")
- defaultsSaveCmd.Flags().StringVar(&templateDefaultsEnvFile, "env-file", "", "Path to environment content file")
- defaultsSaveCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = defaultsSaveCmd.MarkFlagRequired("file")
-
- // registries update command flags
- registriesUpdateCmd.Flags().StringVar(&templateRegUpdateName, "name", "", "Registry name")
- registriesUpdateCmd.Flags().StringVar(&templateRegUpdateURL, "url", "", "Registry URL")
- registriesUpdateCmd.Flags().StringVar(&templateRegUpdateDesc, "description", "", "Registry description")
- registriesUpdateCmd.Flags().BoolVar(&templateRegUpdateEnabled, "enabled", false, "Enable registry")
- registriesUpdateCmd.Flags().BoolVar(&templateRegUpdateDisabled, "disabled", false, "Disable registry")
- registriesUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // fetch command flags
- fetchCmd.Flags().StringVar(&templateFetchURL, "url", "", "Registry URL to fetch templates from (required)")
- _ = fetchCmd.MarkFlagRequired("url")
- fetchCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ path := cmdutil.AppendQuery(types.TemplateFetch(), url.Values{"url": []string{opts.url}})
+ return cmdutil.Run(cmd, c, cmdutil.Spec[template.RemoteRegistry]{
+ Method: http.MethodGet,
+ Path: path,
+ FailureMessage: "failed to fetch templates",
+ Render: func(data template.RemoteRegistry) error {
+ output.Success("Remote templates fetched successfully")
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.url, "url", "", "Registry URL to fetch templates from (required)")
+ _ = cmd.MarkFlagRequired("url")
+ return cmd
}
diff --git a/cli/pkg/templates/cmd_test.go b/cli/pkg/templates/cmd_test.go
index bf319db82..7ed5e3ff4 100644
--- a/cli/pkg/templates/cmd_test.go
+++ b/cli/pkg/templates/cmd_test.go
@@ -107,10 +107,10 @@ func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {
require.Error(t, err,
"expected command error, got nil")
- require.Contains(t, err.Error(), "--all cannot be combined with explicit pagination flags",
+ require.Contains(t, err.Error(), "flags --all and --limit cannot be used together",
"unexpected error: %v", err)
- require.Contains(t, errOut, "--all cannot be combined with explicit pagination flags",
+ require.Contains(t, errOut, "flags --all and --limit cannot be used together",
"unexpected stderr output: %s", errOut)
mu.Lock()
diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.go
index a74a5853c..8abf0ff10 100644
--- a/cli/pkg/updater/cmd.go
+++ b/cli/pkg/updater/cmd.go
@@ -1,7 +1,9 @@
package updater
import (
+ "cmp"
"fmt"
+ "net/http"
"net/url"
"strconv"
"time"
@@ -15,153 +17,128 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- jsonOutput bool
- historyLimit int
-)
-
-// UpdaterCmd is the parent command for updater operations
-var UpdaterCmd = &cobra.Command{
- Use: "updater",
- Aliases: []string{"upd"},
- Short: "Auto-updater operations",
+// Command is the parent command for updater operations
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "updater",
+ Aliases: []string{"upd"},
+ Short: "Auto-updater operations",
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.AddCommand(newStatusCmd(), newRunCmd(), newHistoryCmd())
+ return cmd
}
-var statusCmd = &cobra.Command{
- Use: "status",
- Short: "Get updater status",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[updater.Status](cmd.Context(), types.UpdaterStatus(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get updater status: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Updater Status")
- output.KeyValue("Updating Containers", strconv.Itoa(result.Data.UpdatingContainers))
- output.KeyValue("Updating Projects", strconv.Itoa(result.Data.UpdatingProjects))
- return nil
- },
-}
+func newStatusCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "status",
+ Short: "Get updater status",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
-var runCmd = &cobra.Command{
- Use: "run",
- Short: "Run updater",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Updater run can take a long time as it pulls images and restarts containers
- c.SetTimeout(30 * time.Minute)
-
- result, err := c.PostJSON[updater.Result](cmd.Context(), types.UpdaterRun(c.EnvID()), nil)
- if err != nil {
- return fmt.Errorf("failed to run updater: %w", err)
- }
-
- if app, ok := runtime.From(cmd.Context()); ok && app != nil && app.FleetConfirmed && result.Data.Failed > 0 {
- return fmt.Errorf("updater failed for %d resources", result.Data.Failed)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Updater Results")
- output.KeyValue("Checked", strconv.Itoa(result.Data.Checked))
- output.KeyValue("Updated", strconv.Itoa(result.Data.Updated))
- output.KeyValue("Skipped", strconv.Itoa(result.Data.Skipped))
- output.KeyValue("Failed", strconv.Itoa(result.Data.Failed))
- output.KeyValue("Duration", result.Data.Duration)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[updater.Status]{
+ Method: http.MethodGet,
+ Path: types.UpdaterStatus(c.EnvID()),
+ FailureMessage: "failed to get updater status",
+ Render: func(data updater.Status) error {
+ output.Header("Updater Status")
+ output.KeyValue("Updating Containers", strconv.Itoa(data.UpdatingContainers))
+ output.KeyValue("Updating Projects", strconv.Itoa(data.UpdatingProjects))
+ return nil
+ },
+ })
+ },
+ }
}
-// autoUpdateRecord mirrors the backend's models.AutoUpdateRecord, which is not
-// exported through the shared types module.
-type autoUpdateRecord struct {
- ID string `json:"id"`
- ResourceID string `json:"resourceId"`
- ResourceType string `json:"resourceType"`
- ResourceName string `json:"resourceName"`
- Status string `json:"status"`
- StartTime time.Time `json:"startTime"`
- EndTime *time.Time `json:"endTime,omitempty"`
- UpdateAvailable bool `json:"updateAvailable"`
- UpdateApplied bool `json:"updateApplied"`
- Error *string `json:"error,omitempty"`
- OldImages map[string]string `json:"oldImageVersions,omitempty"`
- NewImages map[string]string `json:"newImageVersions,omitempty"`
-}
+func newRunCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "run",
+ Short: "Run updater",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ // Updater run can take a long time as it pulls images and restarts containers
+ c.SetTimeout(30 * time.Minute)
-var historyCmd = &cobra.Command{
- Use: "history",
- Short: "Get updater history",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- path := types.UpdaterHistory(c.EnvID())
- if cmd.Flags().Changed("limit") {
- path = cmdutil.AppendQuery(path, url.Values{"limit": []string{strconv.Itoa(historyLimit)}})
- }
-
- result, err := c.GetJSON[[]autoUpdateRecord](cmd.Context(), path)
- if err != nil {
- return fmt.Errorf("failed to get updater history: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"RESOURCE", "TYPE", "STATUS", "APPLIED", "STARTED"}
- rows := make([][]string, len(result.Data))
- for i, h := range result.Data {
- name := h.ResourceName
- if name == "" {
- name = h.ResourceID
+ result, err := c.PostJSON[updater.Result](cmd.Context(), types.UpdaterRun(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to run updater: %w", err)
}
- rows[i] = []string{
- name,
- h.ResourceType,
- h.Status,
- strconv.FormatBool(h.UpdateApplied),
- h.StartTime.Format("2006-01-02 15:04"),
+
+ if app, ok := runtime.From(cmd.Context()); ok && app.FleetConfirmed && result.Data.Failed > 0 {
+ return fmt.Errorf("updater failed for %d resources", result.Data.Failed)
+ }
+
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result.Data)
}
- }
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "history entries"}); tableErr != nil {
- return tableErr
- }
- return nil
- },
+ output.Header("Updater Results")
+ output.KeyValue("Checked", strconv.Itoa(result.Data.Checked))
+ output.KeyValue("Updated", strconv.Itoa(result.Data.Updated))
+ output.KeyValue("Skipped", strconv.Itoa(result.Data.Skipped))
+ output.KeyValue("Failed", strconv.Itoa(result.Data.Failed))
+ output.KeyValue("Duration", result.Data.Duration)
+ return nil
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-func init() {
- cmdutil.SetScope(cmdutil.ScopeRead, UpdaterCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, runCmd)
- UpdaterCmd.AddCommand(statusCmd)
- UpdaterCmd.AddCommand(runCmd)
- UpdaterCmd.AddCommand(historyCmd)
-
- statusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- runCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- historyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- historyCmd.Flags().IntVarP(&historyLimit, "limit", "n", 50, "Number of history entries to show")
+func newHistoryCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ }
+ cmd := &cobra.Command{
+ Use: "history",
+ Short: "Get updater history",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ path := types.UpdaterHistory(c.EnvID())
+ if cmd.Flags().Changed("limit") {
+ path = cmdutil.AppendQuery(path, url.Values{"limit": []string{strconv.Itoa(opts.limit)}})
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]updater.AutoUpdateRecord]{
+ Method: http.MethodGet,
+ Path: path,
+ FailureMessage: "failed to get updater history",
+ Render: func(data []updater.AutoUpdateRecord) error {
+ headers := []string{"RESOURCE", "TYPE", "STATUS", "APPLIED", "STARTED"}
+ rows := make([][]string, len(data))
+ for i, h := range data {
+ rows[i] = []string{
+ cmp.Or(h.ResourceName, h.ResourceID),
+ h.ResourceType,
+ h.Status,
+ strconv.FormatBool(h.UpdateApplied),
+ h.StartTime.Format("2006-01-02 15:04"),
+ }
+ }
+
+ return cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "history entries"})
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limit, "limit", "n", 50, "Number of history entries to show")
+ return cmd
}
diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.go
index b532587f7..66a126c92 100644
--- a/cli/pkg/variables/cmd.go
+++ b/cli/pkg/variables/cmd.go
@@ -4,290 +4,277 @@ import (
"cmp"
"errors"
"fmt"
+ "net/http"
+ "slices"
"strconv"
"strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/env"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
- "github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- jsonOutput bool
- forceFlag bool
- createKey string
- createValue string
- createSecret bool
- createAllEnvs bool
- createEnvIDs []string
- updateKey string
- updateValue string
- updateSecret bool
- updateAllEnvs bool
- updateEnvIDs []string
- syncStatusFlag bool
-)
-
-// VariablesCmd is the parent command for global variable operations.
-var VariablesCmd = &cobra.Command{
- Use: "variables",
- Aliases: []string{"variable", "vars"},
- Short: "Manage global variables",
-}
-
-const secretMask = "********"
-
-func variableScope(allEnvironments bool, environmentIDs []string) string {
- if allEnvironments {
- return "all environments"
+// Command is the parent command for global variable operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "variables",
+ Aliases: []string{"variable", "vars"},
+ Short: "Manage global variables",
}
- if len(environmentIDs) == 0 {
- return "-"
- }
- return strings.Join(environmentIDs, ",")
+ command.AddCommand(newListCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ command.AddCommand(newSyncCmd())
+ return command
}
-func printSyncStatuses(statuses []env.EnvironmentSyncStatus) error {
- headers := []string{"ENVIRONMENT ID", "NAME", "STATUS", "LAST SYNCED", "ERROR"}
- rows := make([][]string, len(statuses))
- for i, status := range statuses {
- lastSynced := "-"
- if status.LastSyncedAt != nil {
- lastSynced = status.LastSyncedAt.Format(time.RFC3339)
- }
- syncError := cmp.Or(status.Error, "-")
- rows[i] = []string{
- status.EnvironmentID,
- status.EnvironmentName,
- status.Status,
- lastSynced,
- syncError,
- }
- }
- return output.Table(headers, rows)
-}
+const secretMask = "********"
func printMutationResult(result env.GlobalVariableMutationResponse, message string) error {
- if jsonOutput {
- return cmdutil.PrintJSON(result)
- }
-
output.Success("%s", message)
if result.Variable != nil {
output.KeyValue("ID", result.Variable.ID)
output.KeyValue("Key", result.Variable.Key)
output.KeyValue("Secret", strconv.FormatBool(result.Variable.IsSecret))
- output.KeyValue("Scope", variableScope(result.Variable.AllEnvironments, result.Variable.EnvironmentIDs))
+ scope := "-"
+ switch {
+ case result.Variable.AllEnvironments:
+ scope = "all environments"
+ case len(result.Variable.EnvironmentIDs) > 0:
+ scope = strings.Join(result.Variable.EnvironmentIDs, ",")
+ }
+ output.KeyValue("Scope", scope)
}
return nil
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List global variables",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[[]env.GlobalVariable](cmd.Context(), types.Variables())
- if err != nil {
- return fmt.Errorf("failed to list variables: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"ID", "KEY", "SCOPE", "SECRET", "VALUE"}
- rows := make([][]string, len(result.Data))
- for i, variable := range result.Data {
- value := variable.Value
- if variable.IsSecret {
- value = secretMask
- }
- rows[i] = []string{
- variable.ID,
- variable.Key,
- variableScope(variable.AllEnvironments, variable.EnvironmentIDs),
- strconv.FormatBool(variable.IsSecret),
- value,
+func newListCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List global variables",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
-
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
- }
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d variables\n", len(result.Data))
- return nil
- },
-}
-
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a global variable",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := env.CreateGlobalVariableRequest{
- Key: createKey,
- Value: createValue,
- IsSecret: createSecret,
- AllEnvironments: createAllEnvs,
- EnvironmentIDs: createEnvIDs,
- }
-
- result, err := c.PostJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variables(), req)
- if err != nil {
- return fmt.Errorf("failed to create variable: %w", err)
- }
- return printMutationResult(result.Data, fmt.Sprintf("Variable %s created successfully", createKey))
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]env.GlobalVariable]{
+ Method: http.MethodGet,
+ Path: types.Variables(),
+ FailureMessage: "failed to list variables",
+ Render: func(data []env.GlobalVariable) error {
+ headers := []string{"ID", "KEY", "SCOPE", "SECRET", "VALUE"}
+ rows := make([][]string, len(data))
+ for i, variable := range data {
+ value := variable.Value
+ if variable.IsSecret {
+ value = secretMask
+ }
+ scope := "-"
+ switch {
+ case variable.AllEnvironments:
+ scope = "all environments"
+ case len(variable.EnvironmentIDs) > 0:
+ scope = strings.Join(variable.EnvironmentIDs, ",")
+ }
+ rows[i] = []string{
+ variable.ID,
+ variable.Key,
+ scope,
+ strconv.FormatBool(variable.IsSecret),
+ value,
+ }
+ }
+
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d variables\n", len(data))
+ return nil
+ },
+ })
+ },
+ }
}
-var updateCmd = &cobra.Command{
- Use: "update <id>",
- Short: "Update a global variable",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- var req env.UpdateGlobalVariableRequest
- if cmd.Flags().Changed("key") {
- req.Key = &updateKey
- }
- if cmd.Flags().Changed("value") {
- req.Value = &updateValue
- }
- if cmd.Flags().Changed("secret") {
- req.IsSecret = &updateSecret
- }
- if cmd.Flags().Changed("all-environments") {
- req.AllEnvironments = &updateAllEnvs
- }
- if cmd.Flags().Changed("environment") {
- req.EnvironmentIDs = &updateEnvIDs
- }
-
- if req.Key == nil && req.Value == nil && req.IsSecret == nil && req.AllEnvironments == nil && req.EnvironmentIDs == nil {
- return errors.New("no updates provided (set at least one flag)")
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ key string
+ value string
+ secret bool
+ allEnvs bool
+ envIDs []string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create a global variable",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.PutJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to update variable: %w", err)
- }
+ req := env.CreateGlobalVariableRequest{
+ Key: opts.key,
+ Value: opts.value,
+ IsSecret: opts.secret,
+ AllEnvironments: opts.allEnvs,
+ EnvironmentIDs: opts.envIDs,
+ }
- return printMutationResult(result.Data, "Variable updated successfully")
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[env.GlobalVariableMutationResponse]{
+ Method: http.MethodPost,
+ Path: types.Variables(),
+ FailureMessage: "failed to create variable",
+ Body: req,
+ Render: func(data env.GlobalVariableMutationResponse) error {
+ return printMutationResult(data, fmt.Sprintf("Variable %s created successfully", opts.key))
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.key, "key", "", "Variable key")
+ command.Flags().StringVar(&opts.value, "value", "", "Variable value")
+ command.Flags().BoolVar(&opts.secret, "secret", false, "Store the value as a secret")
+ command.Flags().BoolVar(&opts.allEnvs, "all-environments", false, "Scope the variable to all environments")
+ command.Flags().StringArrayVar(&opts.envIDs, "environment", nil, "Environment ID to scope the variable to (repeatable)")
+ _ = command.MarkFlagRequired("key")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a global variable",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete variable %s?", args[0]))
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ key string
+ value string
+ secret bool
+ allEnvs bool
+ envIDs []string
+ }
+ command := &cobra.Command{
+ Use: "update <id>",
+ Short: "Update a global variable",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !slices.ContainsFunc([]string{"key", "value", "secret", "all-environments", "environment"}, cmd.Flags().Changed) {
+ return errors.New("no updates provided (set at least one flag)")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.DeleteJSON[env.GlobalVariableMutationResponse](cmd.Context(), types.Variable(args[0]))
- if err != nil {
- return fmt.Errorf("failed to delete variable: %w", err)
- }
+ req := env.UpdateGlobalVariableRequest{
+ Key: kit.Ternary(cmd.Flags().Changed("key"), &opts.key, nil),
+ Value: kit.Ternary(cmd.Flags().Changed("value"), &opts.value, nil),
+ IsSecret: kit.Ternary(cmd.Flags().Changed("secret"), &opts.secret, nil),
+ AllEnvironments: kit.Ternary(cmd.Flags().Changed("all-environments"), &opts.allEnvs, nil),
+ EnvironmentIDs: kit.Ternary(cmd.Flags().Changed("environment"), &opts.envIDs, nil),
+ }
- return printMutationResult(result.Data, "Variable deleted successfully")
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[env.GlobalVariableMutationResponse]{
+ Method: http.MethodPut,
+ Path: types.Variable(args[0]),
+ FailureMessage: "failed to update variable",
+ Body: req,
+ Render: func(data env.GlobalVariableMutationResponse) error {
+ return printMutationResult(data, "Variable updated successfully")
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.key, "key", "", "Variable key")
+ command.Flags().StringVar(&opts.value, "value", "", "Variable value")
+ command.Flags().BoolVar(&opts.secret, "secret", false, "Store the value as a secret")
+ command.Flags().BoolVar(&opts.allEnvs, "all-environments", false, "Scope the variable to all environments")
+ command.Flags().StringArrayVar(&opts.envIDs, "environment", nil, "Environment ID to scope the variable to (repeatable)")
+ return command
}
-var syncCmd = &cobra.Command{
- Use: "sync",
- Short: "Sync global variables to every environment (--status shows the last sync result per environment)",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- var result *client.APIResponse[[]env.EnvironmentSyncStatus]
- failureMessage := "failed to sync variables"
- if syncStatusFlag {
- failureMessage = "failed to get variable sync status"
- result, err = c.GetJSON[[]env.EnvironmentSyncStatus](cmd.Context(), types.VariablesSyncStatus())
- } else {
- result, err = c.PostJSON[[]env.EnvironmentSyncStatus](cmd.Context(), types.VariablesSync(), nil)
- }
- if err != nil {
- return fmt.Errorf("%s: %w", failureMessage, err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- return printSyncStatuses(result.Data)
- },
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a global variable",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete variable %s?", args[0]),
+ Path: types.Variable(args[0]),
+ FailureMessage: "failed to delete variable",
+ SuccessMessage: "Variable deleted successfully",
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Skip the confirmation prompt")
+ return command
}
-func init() {
- VariablesCmd.AddCommand(listCmd)
- VariablesCmd.AddCommand(createCmd)
- VariablesCmd.AddCommand(updateCmd)
- VariablesCmd.AddCommand(deleteCmd)
- VariablesCmd.AddCommand(syncCmd)
-
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- createCmd.Flags().StringVar(&createKey, "key", "", "Variable key")
- createCmd.Flags().StringVar(&createValue, "value", "", "Variable value")
- createCmd.Flags().BoolVar(&createSecret, "secret", false, "Store the value as a secret")
- createCmd.Flags().BoolVar(&createAllEnvs, "all-environments", false, "Scope the variable to all environments")
- createCmd.Flags().StringArrayVar(&createEnvIDs, "environment", nil, "Environment ID to scope the variable to (repeatable)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("key")
-
- updateCmd.Flags().StringVar(&updateKey, "key", "", "Variable key")
- updateCmd.Flags().StringVar(&updateValue, "value", "", "Variable value")
- updateCmd.Flags().BoolVar(&updateSecret, "secret", false, "Store the value as a secret")
- updateCmd.Flags().BoolVar(&updateAllEnvs, "all-environments", false, "Scope the variable to all environments")
- updateCmd.Flags().StringArrayVar(&updateEnvIDs, "environment", nil, "Environment ID to scope the variable to (repeatable)")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Skip the confirmation prompt")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newSyncCmd() *cobra.Command {
+ var opts struct {
+ syncStatus bool
+ }
+ command := &cobra.Command{
+ Use: "sync",
+ Short: "Sync global variables to every environment (--status shows the last sync result per environment)",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- syncCmd.Flags().BoolVar(&syncStatusFlag, "status", false, "Show the last sync result per environment instead of triggering a sync")
- syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ method, path, failureMessage := http.MethodPost, types.VariablesSync(), "failed to sync variables"
+ if opts.syncStatus {
+ method, path, failureMessage = http.MethodGet, types.VariablesSyncStatus(), "failed to get variable sync status"
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]env.EnvironmentSyncStatus]{
+ Method: method,
+ Path: path,
+ FailureMessage: failureMessage,
+ Render: func(data []env.EnvironmentSyncStatus) error {
+ headers := []string{"ENVIRONMENT ID", "NAME", "STATUS", "LAST SYNCED", "ERROR"}
+ rows := make([][]string, len(data))
+ for i, status := range data {
+ lastSynced := "-"
+ if status.LastSyncedAt != nil {
+ lastSynced = status.LastSyncedAt.Format(time.RFC3339)
+ }
+ syncError := cmp.Or(status.Error, "-")
+ rows[i] = []string{
+ status.EnvironmentID,
+ status.EnvironmentName,
+ status.Status,
+ lastSynced,
+ syncError,
+ }
+ }
+ return output.Table(headers, rows)
+ },
+ })
+ },
+ }
+ command.Flags().BoolVar(&opts.syncStatus, "status", false, "Show the last sync result per environment instead of triggering a sync")
+ return command
}
diff --git a/cli/pkg/version/cmd.go b/cli/pkg/version/cmd.go
index 4214d542d..6e27cd73d 100644
--- a/cli/pkg/version/cmd.go
+++ b/cli/pkg/version/cmd.go
@@ -12,59 +12,60 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/logger"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-// VersionCmd displays CLI and server versions.
-var VersionCmd = &cobra.Command{
- Use: "version",
- Short: "Show CLI and Arcane server versions",
- Args: cobra.NoArgs,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- jsonOutput := cmdutil.JSONOutputEnabled(cmd)
- if !jsonOutput {
- output.Header("Arcane CLI")
- output.KeyValue("Version", config.Version)
- output.KeyValue("Revision", config.Revision)
- }
+// Command displays CLI and server versions.
+func Command() *cobra.Command {
+ return &cobra.Command{
+ Use: "version",
+ Short: "Show CLI and Arcane server versions",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !cmdutil.JSONOutputEnabled(cmd) {
+ output.Header("Arcane CLI")
+ output.KeyValue("Version", config.Version)
+ output.KeyValue("Revision", config.Revision)
+ }
- c, err := cmdutil.ClientFromCommand(cmd)
- var result version.Info
- if err == nil {
- logger.GetLogger().Debug("Fetching server version", "endpoint", clitypes.AppVersionEndpoint)
- result, err = c.DoJSON[version.Info](cmd.Context(), http.MethodGet, clitypes.AppVersionEndpoint, nil)
- }
- if err != nil {
- if cmd.Context().Err() != nil {
- return cmd.Context().Err()
+ c, err := cmdutil.ClientFromCommand(cmd)
+ var result version.Info
+ if err == nil {
+ logger.GetLogger().Debug("Fetching server version", "endpoint", types.AppVersionEndpoint)
+ result, err = c.DoJSON[version.Info](cmd.Context(), http.MethodGet, types.AppVersionEndpoint, nil)
}
- if jsonOutput {
- return fmt.Errorf("failed to get server version: %w", err)
+ if err != nil {
+ if cmd.Context().Err() != nil {
+ return cmd.Context().Err()
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return fmt.Errorf("failed to get server version: %w", err)
+ }
+ output.Header("Arcane Server")
+ output.KeyValue("Status", "Unavailable")
+ output.Warning("Could not get server version: %s", err)
+ return nil
}
- output.Header("Arcane Server")
- output.KeyValue("Status", "Unavailable")
- output.Warning("Could not get server version: %s", err)
- return nil
- }
- if cmdutil.JSONOutputEnabled(cmd) {
- return cmdutil.PrintJSON(result)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result)
+ }
- output.Header("Arcane Server")
+ output.Header("Arcane Server")
- output.KeyValue("Version", cmp.Or(result.DisplayVersion, result.CurrentVersion))
- if result.Revision != "" {
- output.KeyValue("Revision", result.Revision)
- }
- if result.UpdateAvailable {
- output.Warning("Update available! New version: %s", result.NewestVersion)
- if result.ReleaseURL != "" {
- output.Info("Download at: %s", result.ReleaseURL)
+ output.KeyValue("Version", cmp.Or(result.DisplayVersion, result.CurrentVersion))
+ if result.Revision != "" {
+ output.KeyValue("Revision", result.Revision)
+ }
+ if result.UpdateAvailable {
+ output.Warning("Update available! New version: %s", result.NewestVersion)
+ if result.ReleaseURL != "" {
+ output.Info("Download at: %s", result.ReleaseURL)
+ }
}
- }
- return nil
- },
+ return nil
+ },
+ }
}
diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.go
index d99ee0b8e..8fad8e17d 100644
--- a/cli/pkg/volumes/backup.go
+++ b/cli/pkg/volumes/backup.go
@@ -13,272 +13,525 @@ import (
"strconv"
"time"
+ "github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/base"
- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+ "github.com/getarcaneapp/arcane/types/v2/upload"
"github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/spf13/cobra"
- kit "go.getarcane.app/kit/pkg"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- backupCreateDestination string
- backupCreateS3Destination string
- backupCreatePolicyID string
- backupUploadS3Destination string
- restorePaths []string
- restoreArchiveFile string
- policyEnabled bool
- policySchedule string
- policyRetention int
- policyStopContainers bool
- policyLocal bool
- policyS3 bool
- policyS3Destination string
- policyID string
- policyFile string
-)
+func newRenameCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "rename <volume-name> <new-name>",
+ Short: "Rename an unused volume",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ allowPrompt := !opts.forceFlag && cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
-// backupsListResponse mirrors the backend's paginated volume backup response,
-// which carries warnings alongside the standard pagination envelope.
-type backupsListResponse struct {
- Success bool `json:"success"`
- Data []volume.BackupEntry `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
- Warnings []string `json:"warnings,omitempty"`
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.forceFlag, fmt.Sprintf("Rename volume %s to %s? The volume is copied and the source is removed.", resolved.Name, args[1]))
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.Volume]{
+ Method: http.MethodPost,
+ Path: types.VolumeRename(c.EnvID(), resolved.Name),
+ Body: volume.Rename{Name: args[1]},
+ FailureMessage: "failed to rename volume",
+ Render: func(data volume.Volume) error {
+ output.Success("Volume %s renamed to %s", resolved.Name, data.Name)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Rename without confirmation")
+ return cmd
}
-var renameCmd = &cobra.Command{
- Use: "rename <volume-name> <new-name>",
- Short: "Rename an unused volume",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newBackupsPolicyCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "policy <volume-name>",
+ Short: "Show volume backup policies",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- allowPrompt := !forceFlag && !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Rename volume %s to %s? The volume is copied and the source is removed.", resolved.Name, args[1]))
- if confirmErr != nil {
- return confirmErr
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.BackupPolicyCollection]{
+ Method: http.MethodGet,
+ Path: types.VolumeBackupPolicy(c.EnvID(), resolved.Name),
+ FailureMessage: "failed to get backup policies",
+ Render: func(data volume.BackupPolicyCollection) error {
+ return renderVolumePolicies(resolved.Name, data)
+ },
+ })
+ },
+ }
+ cmd.AddCommand(newBackupsPolicyUpdateCmd())
+ return cmd
+}
+
+func newBackupsPolicyUpdateCmd() *cobra.Command {
+ var opts backupPolicyOptions
+ cmd := &cobra.Command{
+ Use: "update <volume-name>",
+ Short: "Update volume backup policies",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- }
- result, err := c.PostJSON[volume.Volume](cmd.Context(), types.VolumeRename(c.EnvID(), resolved.Name), volume.Rename{Name: args[1]})
- if err != nil {
- return fmt.Errorf("failed to rename volume: %w", err)
- }
+ payload, policyErr := volumeBackupPolicies(cmd, c, resolved.Name, opts)
+ if policyErr != nil {
+ return policyErr
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.BackupPolicyCollection]{
+ Method: http.MethodPut,
+ Path: types.VolumeBackupPolicy(c.EnvID(), resolved.Name),
+ Body: payload,
+ FailureMessage: "failed to update backup policies",
+ Render: func(data volume.BackupPolicyCollection) error {
+ output.Success("Backup policies for volume %s saved successfully", resolved.Name)
+ return renderVolumePolicies(resolved.Name, data)
+ },
+ })
+ },
+ }
+ cmd.Flags().BoolVar(&opts.policyEnabled, "enabled", false, "Enable or disable the policy")
+ cmd.Flags().StringVar(&opts.policySchedule, "schedule", "", "Backup schedule (cron expression)")
+ cmd.Flags().IntVar(&opts.policyRetention, "retention", 0, "Number of backups to retain")
+ cmd.Flags().BoolVar(&opts.policyStopContainers, "stop-containers", false, "Stop containers using the volume during backup")
+ cmd.Flags().BoolVar(&opts.policyLocal, "local", false, "Store backups locally")
+ cmd.Flags().BoolVar(&opts.policyS3, "s3", false, "Store backups in S3")
+ cmd.Flags().StringVar(&opts.policyS3Destination, "s3-destination", "", "Saved S3 destination ID")
+ cmd.Flags().StringVar(&opts.policyID, "policy-id", "", "Policy to update when the volume has multiple policies")
+ cmd.Flags().StringVar(&opts.policyFile, "file", "", "JSON file with the full policy collection to PUT")
+ return cmd
+}
- output.Success("Volume %s renamed to %s", resolved.Name, result.Data.Name)
- return nil
- },
+func newBackupsCmd() *cobra.Command {
+ var opts backupListOptions
+ cmd := &cobra.Command{
+ Use: "backups <volume-name>",
+ Short: "Manage volume backups",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error { return runBackupList(cmd, args, opts) },
+ }
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of backups to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage)
+ cmd.AddCommand(
+ newBackupsListCmd(),
+ newBackupsPolicyCmd(),
+ newBackupsCreateCmd(),
+ newBackupsRestoreCmd(),
+ newBackupsDeleteCmd(),
+ newBackupsUploadCmd(),
+ newBackupsDownloadCmd(),
+ newBackupsFilesCmd(),
+ )
+ return cmd
}
-var backupsPolicyCmd = &cobra.Command{
- Use: "policy <volume-name>",
- Short: "Show volume backup policies",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newBackupsListCmd() *cobra.Command {
+ var opts backupListOptions
+ cmd := &cobra.Command{
+ Use: "list <volume-name>",
+ Aliases: []string{"ls"},
+ Short: "List volume backups",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error { return runBackupList(cmd, args, opts) },
+ }
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of backups to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage)
+ return cmd
+}
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+func newBackupsCreateCmd() *cobra.Command {
+ var opts struct {
+ backupCreateDestination string
+ backupCreateS3Destination string
+ backupCreatePolicyID string
+ }
+ cmd := &cobra.Command{
+ Use: "create <volume-name>",
+ Short: "Create a volume backup",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- result, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name))
- if err != nil {
- return fmt.Errorf("failed to get backup policies: %w", err)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ req := volume.CreateBackupRequest{
+ Destination: volume.BackupDestination(opts.backupCreateDestination),
+ PolicyID: opts.backupCreatePolicyID,
+ S3DestinationID: opts.backupCreateS3Destination,
+ }
- return printBackupPolicies(resolved.Name, result.Data)
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.BackupEntry]{
+ Method: http.MethodPost,
+ Path: types.VolumeBackups(c.EnvID(), resolved.Name),
+ Body: req,
+ FailureMessage: "failed to create backup",
+ Render: func(data volume.BackupEntry) error {
+ output.Success("Backup started for volume %s", resolved.Name)
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Status", data.Status)
+ output.KeyValue("Destination", string(data.Destination))
+ if data.Size > 0 {
+ output.KeyValue("Size", output.Bytes(data.Size))
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.backupCreateDestination, "destination", "", "Backup destination (local, s3, local_s3)")
+ cmd.Flags().StringVar(&opts.backupCreateS3Destination, "s3-destination", "", "Saved S3 destination ID for a remote backup")
+ cmd.Flags().StringVar(&opts.backupCreatePolicyID, "policy-id", "", "Backup policy whose settings should be used")
+ return cmd
}
-var backupsPolicyUpdateCmd = &cobra.Command{
- Use: "update <volume-name>",
- Short: "Update volume backup policies",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newBackupsRestoreCmd() *cobra.Command {
+ var opts struct {
+ restorePaths []string
+ restoreArchiveFile string
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "restore <volume-name> [backup-id]",
+ Short: "Restore a volume from a backup",
+ Long: `Restore a volume from an existing backup, or from a local tar.gz archive.
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+With a backup ID the whole backup is restored; add one or more --path flags to
+restore only those paths. With --file a local tar.gz backup archive is uploaded
+and restored instead (no backup ID).`,
+ Args: cobra.RangeArgs(1, 2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if opts.restoreArchiveFile != "" && len(args) == 2 {
+ return errors.New("--file and a backup ID are mutually exclusive")
+ }
+ if opts.restoreArchiveFile == "" && len(args) < 2 {
+ return errors.New("a backup ID or --file is required")
+ }
- var payload volume.UpdateBackupPolicies
- if policyFile != "" {
- raw, readFileErr := os.ReadFile(policyFile)
- if readFileErr != nil {
- return fmt.Errorf("failed to read policy file: %w", readFileErr)
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if unmarshalErr := json.Unmarshal(raw, &payload); unmarshalErr != nil {
- return fmt.Errorf("failed to parse policy file: %w", unmarshalErr)
+
+ allowPrompt := !opts.forceFlag && cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
}
- } else {
- current, policyErr := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name))
- if policyErr != nil {
- return fmt.Errorf("failed to get current backup policies: %w", policyErr)
- }
-
- payload.Policies = make([]volume.UpdateBackupPolicy, len(current.Data.Policies))
- targetIndex := -1
- for i, p := range current.Data.Policies {
- payload.Policies[i] = volume.UpdateBackupPolicy{
- ID: p.ID,
- Enabled: p.Enabled,
- Schedule: p.Schedule,
- RetentionCount: p.RetentionCount,
- StopContainers: p.StopContainers,
- LocalEnabled: p.LocalEnabled,
- S3Enabled: p.S3Enabled,
- S3DestinationID: p.S3DestinationID,
+
+ backupID := ""
+ confirmation := fmt.Sprintf("Restore volume %s from %s? Current volume contents will be replaced.", resolved.Name, opts.restoreArchiveFile)
+ if opts.restoreArchiveFile == "" {
+ backupID = args[1]
+ confirmation = fmt.Sprintf("Restore volume %s from backup %s? Current volume contents will be replaced.", resolved.Name, backupID)
+ if len(opts.restorePaths) > 0 {
+ confirmation = fmt.Sprintf("Restore %d path(s) into volume %s from backup %s?", len(opts.restorePaths), resolved.Name, backupID)
}
- if policyID != "" && p.ID == policyID {
- targetIndex = i
+ }
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.forceFlag, confirmation)
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
+ }
+ if opts.restoreArchiveFile != "" {
+ c.SetTimeout(30 * time.Minute)
+ sessionID, uploadErr := cmdutil.UploadFileInChunks(cmd.Context(), c, upload.KindVolumeBackup, opts.restoreArchiveFile, !cmdutil.JSONOutputEnabled(cmd))
+ if uploadErr != nil {
+ return uploadErr
+ }
+ restoreErr := cmdutil.Run(cmd, c, cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.VolumeBackupUploadRestore(c.EnvID(), resolved.Name),
+ Body: upload.ConsumeRequest{UploadID: sessionID},
+ FailureMessage: "failed to upload and restore backup",
+ Render: func(base.MessageResponse) error {
+ output.Success("Backup uploaded and restored into volume %s successfully", resolved.Name)
+ return nil
+ },
+ })
+ if restoreErr != nil {
+ cmdutil.AbortUploadSession(cmd.Context(), c, upload.KindVolumeBackup, sessionID)
}
+ return restoreErr
}
-
- switch {
- case policyID != "" && targetIndex == -1:
- return fmt.Errorf("policy %q not found for volume %q", policyID, resolved.Name)
- case policyID == "" && len(payload.Policies) > 1:
- return fmt.Errorf("volume %q has %d backup policies; select one with --policy-id", resolved.Name, len(payload.Policies))
- case policyID == "" && len(payload.Policies) == 1:
- targetIndex = 0
- case targetIndex == -1:
- if policySchedule == "" {
- return errors.New("--schedule is required when creating a new backup policy")
+ spec := cmdutil.Spec[base.MessageResponse]{
+ Method: http.MethodPost,
+ Path: types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID),
+ FailureMessage: "failed to restore backup",
+ Render: func(base.MessageResponse) error {
+ output.Success("%s", fmt.Sprintf("Restore of volume %s from backup %s initiated", resolved.Name, backupID))
+ return nil
+ },
+ }
+ if len(opts.restorePaths) > 0 {
+ spec.Path = types.VolumeBackupRestoreFiles(c.EnvID(), resolved.Name, backupID)
+ spec.Body = backup.RestoreSelection{Paths: opts.restorePaths}
+ spec.FailureMessage = "failed to restore backup files"
+ spec.Render = func(base.MessageResponse) error {
+ output.Success("Restore of %d path(s) into volume %s initiated", len(opts.restorePaths), resolved.Name)
+ return nil
}
- // New policies default to local storage unless --local was set explicitly.
- payload.Policies = append(payload.Policies, volume.UpdateBackupPolicy{LocalEnabled: !cmd.Flags().Changed("local") || policyLocal})
- targetIndex = len(payload.Policies) - 1
}
+ return cmdutil.Run(cmd, c, spec)
+ },
+ }
+ cmd.Flags().StringArrayVar(&opts.restorePaths, "path", nil, "Restore only this path from the backup (repeatable)")
+ cmd.Flags().StringVar(&opts.restoreArchiveFile, "file", "", "Local tar.gz backup archive to upload and restore")
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Restore without confirmation")
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "file", "path") }
+ return cmd
+}
- target := &payload.Policies[targetIndex]
- if cmd.Flags().Changed("enabled") {
- target.Enabled = policyEnabled
+func newBackupsDeleteCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <backup-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a volume backup",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if cmd.Flags().Changed("schedule") {
- target.Schedule = policySchedule
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.forceFlag,
+ Prompt: fmt.Sprintf("Are you sure you want to delete backup %s?", args[0]),
+ Path: types.VolumeBackup(c.EnvID(), args[0]),
+ FailureMessage: "failed to delete backup",
+ SuccessMessage: fmt.Sprintf("Backup %s deleted successfully", args[0]),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Delete without confirmation")
+ cmdutil.SetResource(backupRef, cmd)
+ return cmd
+}
+
+func newBackupsUploadCmd() *cobra.Command {
+ var opts struct {
+ backupUploadS3Destination string
+ }
+ cmd := &cobra.Command{
+ Use: "upload <backup-id>",
+ Short: "Upload an existing local backup to an S3 destination",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if cmd.Flags().Changed("retention") {
- target.RetentionCount = policyRetention
+
+ // Uploading large backups can take a long time
+ c.SetTimeout(30 * time.Minute)
+
+ req := volume.UploadBackupRequest{S3DestinationID: opts.backupUploadS3Destination}
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.BackupEntry]{
+ Method: http.MethodPost,
+ Path: types.VolumeBackupUpload(c.EnvID(), args[0]),
+ Body: req,
+ FailureMessage: "failed to upload backup",
+ Render: func(volume.BackupEntry) error {
+ output.Success("Backup %s uploaded to S3 successfully", args[0])
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.backupUploadS3Destination, "s3-destination", "", "S3 destination for the uploaded backup")
+ _ = cmd.MarkFlagRequired("s3-destination")
+ cmdutil.SetResource(backupRef, cmd)
+ return cmd
+}
+
+func newBackupsDownloadCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "download <backup-id> [output-file]",
+ Short: "Download a volume backup archive",
+ Args: cobra.RangeArgs(1, 2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if cmd.Flags().Changed("stop-containers") {
- target.StopContainers = policyStopContainers
+
+ // Downloading large backups can take a long time
+ c.SetTimeout(30 * time.Minute)
+
+ resp, err := c.Get(cmd.Context(), types.VolumeBackupDownload(c.EnvID(), args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to download backup: %w", err)
}
- if cmd.Flags().Changed("local") {
- target.LocalEnabled = policyLocal
+ defer func() { _ = resp.Body.Close() }()
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download backup: %w", ensureSuccessStatusErr)
}
- if cmd.Flags().Changed("s3") {
- target.S3Enabled = policyS3
+
+ outputFile := ""
+ if len(args) == 2 {
+ outputFile = args[1]
}
- if cmd.Flags().Changed("s3-destination") {
- target.S3DestinationID = policyS3Destination
+ if outputFile == "" {
+ outputFile = args[0] + ".tar.gz"
+ if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
+ outputFile = cmp.Or(params["filename"], outputFile)
+ }
}
- }
- result, err := c.PutJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), resolved.Name), payload)
- if err != nil {
- return fmt.Errorf("failed to update backup policies: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ file, openErr := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+ if openErr != nil {
+ return fmt.Errorf("failed to create file %s: %w", outputFile, openErr)
+ }
+ written, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading backup", !cmdutil.JSONOutputEnabled(cmd))
+ if copyErr != nil {
+ _ = file.Close()
+ return fmt.Errorf("failed to write file %s: %w", outputFile, copyErr)
+ }
+ if closeErr := file.Close(); closeErr != nil {
+ return fmt.Errorf("failed to write file %s: %w", outputFile, closeErr)
+ }
- output.Success("Backup policies for volume %s saved successfully", resolved.Name)
- return printBackupPolicies(resolved.Name, result.Data)
- },
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ }{outputFile, written})
+ }
+ output.Success("Backup downloaded to %s", outputFile)
+ return nil
+ },
+ }
+ cmdutil.SetResource(backupRef, cmd)
+ return cmd
}
-func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollection) error {
- output.Header("Backup Policies: %s", volumeName)
- output.KeyValue("S3 Available", collection.S3Available)
- if len(collection.Policies) == 0 {
- _, writeErr := fmt.Fprintln(output.Stdout(), "No backup policies configured")
- return writeErr
- }
+func newBackupsFilesCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "files <backup-id>",
+ Short: "List files in a volume backup",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- headers := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "STOP CONTAINERS", "LOCAL", "S3", "S3 DESTINATION"}
- rows := make([][]string, len(collection.Policies))
- for i, p := range collection.Policies {
- s3Destination := cmp.Or(p.S3DestinationName, p.S3DestinationID)
- rows[i] = []string{
- p.ID,
- output.TintEnabled(kit.Ternary(p.Enabled, "Yes", "No")),
- p.Schedule,
- strconv.Itoa(p.RetentionCount),
- kit.Ternary(p.StopContainers, "Yes", "No"),
- kit.Ternary(p.LocalEnabled, "Yes", "No"),
- kit.Ternary(p.S3Enabled, "Yes", "No"),
- s3Destination,
- }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]string]{
+ Method: http.MethodGet,
+ Path: types.VolumeBackupFiles(c.EnvID(), args[0]),
+ FailureMessage: "failed to list backup files",
+ Render: func(data []string) error {
+ for _, file := range data {
+ _, _ = fmt.Fprintln(output.Stdout(), file)
+ }
+ return nil
+ },
+ })
+ },
}
- return output.Table(headers, rows)
+ cmdutil.SetResource(backupRef, cmd)
+ return cmd
}
-var backupsCmd = &cobra.Command{
- Use: "backups <volume-name>",
- Short: "Manage volume backups",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: runListBackups,
+var backupRef = cmdutil.ResourceRef[volume.BackupEntry, volume.BackupEntry]{
+ EnvironmentScoped: true, Singular: "backup", Plural: "backups", IDHint: "the backup ID", ListCmd: "arcane-cli volumes backups list <volume-name>",
+ SearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]volume.BackupEntry, error) {
+ volumes, err := c.GetJSON[[]volume.Volume](ctx, types.Volumes(c.EnvID())+"?limit=-1")
+ if err != nil {
+ return nil, err
+ }
+ var matches []volume.BackupEntry
+ var failures []error
+ for _, item := range volumes.Data {
+ backups, listErr := c.GetJSON[[]volume.BackupEntry](ctx, types.VolumeBackups(c.EnvID(), item.Name)+"?limit=-1")
+ if listErr != nil {
+ failures = append(failures, fmt.Errorf("%s: %w", item.Name, listErr))
+ continue
+ }
+ matches = append(matches, slices.DeleteFunc(backups.Data, func(entry volume.BackupEntry) bool { return entry.ID != identifier })...)
+ }
+ return matches, errors.Join(failures...)
+ },
+ Label: func(item volume.BackupEntry) string { return item.VolumeName + " (" + item.ID + ")" },
+ Promote: func(item volume.BackupEntry) *volume.BackupEntry { return &item },
}
-var backupsListCmd = &cobra.Command{
- Use: "list <volume-name>",
- Aliases: []string{"ls"},
- Short: "List volume backups",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: runListBackups,
+type backupListOptions struct {
+ limitFlag int
+ startFlag int
+ allFlag bool
}
-func runListBackups(cmd *cobra.Command, args []string) error {
+func runBackupList(cmd *cobra.Command, args []string, opts backupListOptions) error {
c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- allowPrompt := !jsonOutput && prompt.IsInteractive()
+ allowPrompt := cmdutil.AllowPrompt(cmd)
resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
@@ -286,22 +539,30 @@ func runListBackups(cmd *cobra.Command, args []string) error {
path, err := cmdutil.ApplyPaginationParams(cmd, types.VolumeBackups(c.EnvID(), resolved.Name), cmdutil.ListParams{
Resource: "backups",
- Limit: limitFlag,
+ Limit: opts.limitFlag,
FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
+ Start: opts.startFlag,
+ All: opts.allFlag,
})
if err != nil {
return fmt.Errorf("failed to build pagination query: %w", err)
}
- result, err := c.DoJSON[backupsListResponse](cmd.Context(), http.MethodGet, path, nil)
+ resp, err := c.Get(cmd.Context(), path)
if err != nil {
return fmt.Errorf("failed to list backups: %w", err)
}
-
- if jsonOutput {
- return cmdutil.PrintJSON(result)
+ defer func() { _ = resp.Body.Close() }()
+ body, readErr := cmdutil.ReadJSONBody(resp)
+ if readErr != nil {
+ return fmt.Errorf("failed to list backups: %w", readErr)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintRawJSON(body)
+ }
+ var result base.PaginatedWithWarnings[volume.Backup]
+ if decodeErr := json.Unmarshal(body, &result); decodeErr != nil {
+ return fmt.Errorf("failed to list backups: failed to decode response: %w", decodeErr)
}
headers := []string{"ID", "SIZE", "CREATED", "STATUS", "TRIGGER", "DESTINATION", "FORMAT"}
@@ -310,7 +571,7 @@ func runListBackups(cmd *cobra.Command, args []string) error {
rows[i] = []string{
backup.ID,
output.Bytes(backup.Size),
- backup.CreatedAt,
+ backup.CreatedAt.Format(time.RFC3339Nano),
output.TintStatus(backup.Status),
backup.Trigger,
string(backup.Destination),
@@ -328,351 +589,113 @@ func runListBackups(cmd *cobra.Command, args []string) error {
return nil
}
-var backupsCreateCmd = &cobra.Command{
- Use: "create <volume-name>",
- Short: "Create a volume backup",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- req := volume.CreateBackupRequest{
- Destination: volume.BackupDestination(backupCreateDestination),
- PolicyID: backupCreatePolicyID,
- S3DestinationID: backupCreateS3Destination,
- }
-
- result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackups(c.EnvID(), resolved.Name), req)
- if err != nil {
- return fmt.Errorf("failed to create backup: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func renderVolumePolicies(name string, data volume.BackupPolicyCollection) error {
+ output.Header("Backup Policies: %s", name)
+ output.KeyValue("S3 Available", data.S3Available)
+ if len(data.Policies) == 0 {
+ _, writeErr := fmt.Fprintln(output.Stdout(), "No backup policies configured")
+ return writeErr
+ }
- output.Success("Backup started for volume %s", resolved.Name)
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Status", result.Data.Status)
- output.KeyValue("Destination", string(result.Data.Destination))
- if result.Data.Size > 0 {
- output.KeyValue("Size", output.Bytes(result.Data.Size))
+ headers := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "STOP CONTAINERS", "LOCAL", "S3", "S3 DESTINATION"}
+ rows := make([][]string, len(data.Policies))
+ for i, p := range data.Policies {
+ rows[i] = []string{
+ p.ID,
+ output.TintEnabled(kit.Ternary(p.Enabled, "Yes", "No")),
+ p.Schedule,
+ strconv.Itoa(p.RetentionCount),
+ kit.Ternary(p.StopContainers, "Yes", "No"),
+ kit.Ternary(p.LocalEnabled, "Yes", "No"),
+ kit.Ternary(p.S3Enabled, "Yes", "No"),
+ cmp.Or(p.S3DestinationName, p.S3DestinationID),
}
- return nil
- },
+ }
+ return output.Table(headers, rows)
}
-var backupsRestoreCmd = &cobra.Command{
- Use: "restore <volume-name> [backup-id]",
- Short: "Restore a volume from a backup",
- Long: `Restore a volume from an existing backup, or from a local tar.gz archive.
-
-With a backup ID the whole backup is restored; add one or more --path flags to
-restore only those paths. With --file a local tar.gz backup archive is uploaded
-and restored instead (no backup ID).`,
- Args: cobra.RangeArgs(1, 2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if restoreArchiveFile != "" && len(args) == 2 {
- return errors.New("--file and a backup ID are mutually exclusive")
- }
- if restoreArchiveFile == "" && len(args) < 2 {
- return errors.New("a backup ID or --file is required")
- }
- if restoreArchiveFile != "" && len(restorePaths) > 0 {
- return errors.New("--path cannot be used with --file")
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- backupID := ""
- confirmation := fmt.Sprintf("Restore volume %s from %s? Current volume contents will be replaced.", resolved.Name, restoreArchiveFile)
- if restoreArchiveFile == "" {
- backupID = args[1]
- confirmation = fmt.Sprintf("Restore volume %s from backup %s? Current volume contents will be replaced.", resolved.Name, backupID)
- if len(restorePaths) > 0 {
- confirmation = fmt.Sprintf("Restore %d path(s) into volume %s from backup %s?", len(restorePaths), resolved.Name, backupID)
- }
- }
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, confirmation)
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- if restoreArchiveFile != "" {
- c.SetTimeout(30 * time.Minute)
- sessionID, uploadErr := cmdutil.UploadFileInChunks(cmd.Context(), c, uploadtypes.KindVolumeBackup, restoreArchiveFile, !jsonOutput)
- if uploadErr != nil {
- return uploadErr
- }
- respBody, restoreErr := c.DoRaw(cmd.Context(), http.MethodPost, types.VolumeBackupUploadRestore(c.EnvID(), resolved.Name), uploadtypes.ConsumeRequest{UploadID: sessionID})
- if restoreErr != nil {
- cmdutil.AbortUploadSession(cmd.Context(), c, uploadtypes.KindVolumeBackup, sessionID)
- return fmt.Errorf("failed to upload and restore backup: %w", restoreErr)
- }
- if jsonOutput {
- return cmdutil.PrintRawJSON(respBody)
- }
- output.Success("Backup uploaded and restored into volume %s successfully", resolved.Name)
- return nil
- }
- spec := cmdutil.PostActionSpec{
- Path: types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID),
- FailureMessage: "failed to restore backup",
- SuccessMessage: fmt.Sprintf("Restore of volume %s from backup %s initiated", resolved.Name, backupID),
- JSON: jsonOutput,
- }
- if len(restorePaths) > 0 {
- spec.Path = types.VolumeBackupRestoreFiles(c.EnvID(), resolved.Name, backupID)
- spec.Body = struct {
- Paths []string `json:"paths"`
- }{Paths: restorePaths}
- spec.FailureMessage = "failed to restore backup files"
- spec.SuccessMessage = fmt.Sprintf("Restore of %d path(s) into volume %s initiated", len(restorePaths), resolved.Name)
- }
- return cmdutil.RunPostAction[base.MessageResponse](cmd, c, spec)
- },
+type backupPolicyOptions struct {
+ policyEnabled bool
+ policySchedule string
+ policyRetention int
+ policyStopContainers bool
+ policyLocal bool
+ policyS3 bool
+ policyS3Destination string
+ policyID string
+ policyFile string
}
-var backupsDeleteCmd = &cobra.Command{
- Use: "delete <backup-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a volume backup",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete backup %s?", args[0]))
- if err != nil {
- return err
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+func volumeBackupPolicies(cmd *cobra.Command, c *client.Client, name string, opts backupPolicyOptions) (volume.UpdateBackupPolicies, error) {
+ var payload volume.UpdateBackupPolicies
+ if opts.policyFile != "" {
+ raw, readFileErr := os.ReadFile(opts.policyFile)
+ if readFileErr != nil {
+ return payload, fmt.Errorf("failed to read policy file: %w", readFileErr)
+ }
+ if unmarshalErr := json.Unmarshal(raw, &payload); unmarshalErr != nil {
+ return payload, fmt.Errorf("failed to parse policy file: %w", unmarshalErr)
+ }
+ } else {
+ current, policyErr := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), name))
+ if policyErr != nil {
+ return payload, fmt.Errorf("failed to get current backup policies: %w", policyErr)
+ }
+
+ payload.Policies = make([]volume.UpdateBackupPolicy, len(current.Data.Policies))
+ for i, p := range current.Data.Policies {
+ payload.Policies[i] = volume.UpdateBackupPolicy{
+ ID: p.ID,
+ Enabled: p.Enabled,
+ Schedule: p.Schedule,
+ RetentionCount: p.RetentionCount,
+ StopContainers: p.StopContainers,
+ LocalEnabled: p.LocalEnabled,
+ S3Enabled: p.S3Enabled,
+ S3DestinationID: p.S3DestinationID,
}
}
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- if _, deleteBackupErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.VolumeBackup(c.EnvID(), args[0])); deleteBackupErr != nil {
- return fmt.Errorf("failed to delete backup: %w", deleteBackupErr)
- }
-
- output.Success("Backup %s deleted successfully", args[0])
- return nil
- },
-}
-
-var backupsUploadCmd = &cobra.Command{
- Use: "upload <backup-id>",
- Short: "Upload an existing local backup to an S3 destination",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Uploading large backups can take a long time
- c.SetTimeout(30 * time.Minute)
-
- req := volume.UploadBackupRequest{S3DestinationID: backupUploadS3Destination}
- result, err := c.PostJSON[volume.BackupEntry](cmd.Context(), types.VolumeBackupUpload(c.EnvID(), args[0]), req)
- if err != nil {
- return fmt.Errorf("failed to upload backup: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Backup %s uploaded to S3 successfully", args[0])
- return nil
- },
-}
-
-var backupsDownloadCmd = &cobra.Command{
- Use: "download <backup-id> [output-file]",
- Short: "Download a volume backup archive",
- Args: cobra.RangeArgs(1, 2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- // Downloading large backups can take a long time
- c.SetTimeout(30 * time.Minute)
-
- resp, err := c.Get(cmd.Context(), types.VolumeBackupDownload(c.EnvID(), args[0]))
- if err != nil {
- return fmt.Errorf("failed to download backup: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to download backup: %w", ensureSuccessStatusErr)
- }
-
- outputFile := ""
- if len(args) == 2 {
- outputFile = args[1]
- }
- if outputFile == "" {
- outputFile = args[0] + ".tar.gz"
- if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
- outputFile = cmp.Or(params["filename"], outputFile)
+ targetIndex := slices.IndexFunc(payload.Policies, func(policy volume.UpdateBackupPolicy) bool { return opts.policyID != "" && policy.ID == opts.policyID })
+ switch {
+ case opts.policyID != "" && targetIndex == -1:
+ return payload, fmt.Errorf("policy %q not found for volume %q", opts.policyID, name)
+ case opts.policyID == "" && len(payload.Policies) > 1:
+ return payload, fmt.Errorf("volume %q has %d backup policies; select one with --policy-id", name, len(payload.Policies))
+ case opts.policyID == "" && len(payload.Policies) == 1:
+ targetIndex = 0
+ case targetIndex == -1:
+ if opts.policySchedule == "" {
+ return payload, errors.New("--schedule is required when creating a new backup policy")
}
+ // New policies default to local storage unless --local was set explicitly.
+ payload.Policies = append(payload.Policies, volume.UpdateBackupPolicy{LocalEnabled: !cmd.Flags().Changed("local") || opts.policyLocal})
+ targetIndex = len(payload.Policies) - 1
}
- file, openErr := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
- if openErr != nil {
- return fmt.Errorf("failed to create file %s: %w", outputFile, openErr)
+ target := &payload.Policies[targetIndex]
+ if cmd.Flags().Changed("enabled") {
+ target.Enabled = opts.policyEnabled
}
- if _, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading backup", !cmdutil.JSONOutputEnabled(cmd)); copyErr != nil {
- _ = file.Close()
- return fmt.Errorf("failed to write file %s: %w", outputFile, copyErr)
+ if cmd.Flags().Changed("schedule") {
+ target.Schedule = opts.policySchedule
}
- if closeErr := file.Close(); closeErr != nil {
- return fmt.Errorf("failed to write file %s: %w", outputFile, closeErr)
+ if cmd.Flags().Changed("retention") {
+ target.RetentionCount = opts.policyRetention
}
-
- output.Success("Backup downloaded to %s", outputFile)
- return nil
- },
-}
-
-var backupsFilesCmd = &cobra.Command{
- Use: "files <backup-id>",
- Short: "List files in a volume backup",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
+ if cmd.Flags().Changed("stop-containers") {
+ target.StopContainers = opts.policyStopContainers
}
-
- result, err := c.GetJSON[[]string](cmd.Context(), types.VolumeBackupFiles(c.EnvID(), args[0]))
- if err != nil {
- return fmt.Errorf("failed to list backup files: %w", err)
+ if cmd.Flags().Changed("local") {
+ target.LocalEnabled = opts.policyLocal
}
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
+ if cmd.Flags().Changed("s3") {
+ target.S3Enabled = opts.policyS3
}
-
- for _, file := range result.Data {
- _, _ = fmt.Fprintln(output.Stdout(), file)
+ if cmd.Flags().Changed("s3-destination") {
+ target.S3DestinationID = opts.policyS3Destination
}
- return nil
- },
-}
-
-func init() {
- cmdutil.SetResource(backupRef, backupsDeleteCmd, backupsUploadCmd, backupsDownloadCmd, backupsFilesCmd)
- VolumesCmd.AddCommand(renameCmd)
- VolumesCmd.AddCommand(backupsCmd)
-
- backupsCmd.AddCommand(backupsListCmd)
- backupsCmd.AddCommand(backupsPolicyCmd)
- backupsCmd.AddCommand(backupsCreateCmd)
- backupsCmd.AddCommand(backupsRestoreCmd)
- backupsCmd.AddCommand(backupsDeleteCmd)
- backupsCmd.AddCommand(backupsUploadCmd)
- backupsCmd.AddCommand(backupsDownloadCmd)
- backupsCmd.AddCommand(backupsFilesCmd)
-
- backupsPolicyCmd.AddCommand(backupsPolicyUpdateCmd)
-
- renameCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Rename without confirmation")
- renameCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- backupsPolicyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- backupsPolicyUpdateCmd.Flags().BoolVar(&policyEnabled, "enabled", false, "Enable or disable the policy")
- backupsPolicyUpdateCmd.Flags().StringVar(&policySchedule, "schedule", "", "Backup schedule (cron expression)")
- backupsPolicyUpdateCmd.Flags().IntVar(&policyRetention, "retention", 0, "Number of backups to retain")
- backupsPolicyUpdateCmd.Flags().BoolVar(&policyStopContainers, "stop-containers", false, "Stop containers using the volume during backup")
- backupsPolicyUpdateCmd.Flags().BoolVar(&policyLocal, "local", false, "Store backups locally")
- backupsPolicyUpdateCmd.Flags().BoolVar(&policyS3, "s3", false, "Store backups in S3")
- backupsPolicyUpdateCmd.Flags().StringVar(&policyS3Destination, "s3-destination", "", "Saved S3 destination ID")
- backupsPolicyUpdateCmd.Flags().StringVar(&policyID, "policy-id", "", "Policy to update when the volume has multiple policies")
- backupsPolicyUpdateCmd.Flags().StringVar(&policyFile, "file", "", "JSON file with the full policy collection to PUT")
- backupsPolicyUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- for _, listLike := range []*cobra.Command{backupsCmd, backupsListCmd} {
- listLike.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of backups to show")
- listLike.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listLike.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listLike.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
- backupsCreateCmd.Flags().StringVar(&backupCreateDestination, "destination", "", "Backup destination (local, s3, local_s3)")
- backupsCreateCmd.Flags().StringVar(&backupCreateS3Destination, "s3-destination", "", "Saved S3 destination ID for a remote backup")
- backupsCreateCmd.Flags().StringVar(&backupCreatePolicyID, "policy-id", "", "Backup policy whose settings should be used")
- backupsCreateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- backupsRestoreCmd.Flags().StringArrayVar(&restorePaths, "path", nil, "Restore only this path from the backup (repeatable)")
- backupsRestoreCmd.Flags().StringVar(&restoreArchiveFile, "file", "", "Local tar.gz backup archive to upload and restore")
- backupsRestoreCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Restore without confirmation")
- backupsRestoreCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- backupsDeleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Delete without confirmation")
-
- backupsUploadCmd.Flags().StringVar(&backupUploadS3Destination, "s3-destination", "", "S3 destination for the uploaded backup")
- backupsUploadCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = backupsUploadCmd.MarkFlagRequired("s3-destination")
-
- backupsFilesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-}
-
-var backupRef = cmdutil.ResourceRef[volume.BackupEntry, volume.BackupEntry]{
- EnvironmentScoped: true, Singular: "backup", Plural: "backups", IDHint: "the backup ID", ListCmd: "arcane-cli volumes backups list <volume-name>",
- SearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]volume.BackupEntry, error) {
- volumes, err := c.GetJSON[[]volume.Volume](ctx, types.Volumes(c.EnvID())+"?limit=-1")
- if err != nil {
- return nil, err
- }
- var matches []volume.BackupEntry
- var failures []error
- for _, item := range volumes.Data {
- backups, listErr := c.GetJSON[[]volume.BackupEntry](ctx, types.VolumeBackups(c.EnvID(), item.Name)+"?limit=-1")
- if listErr != nil {
- failures = append(failures, fmt.Errorf("%s: %w", item.Name, listErr))
- continue
- }
- matches = append(matches, slices.DeleteFunc(backups.Data, func(entry volume.BackupEntry) bool { return entry.ID != identifier })...)
- }
- return matches, errors.Join(failures...)
- },
- Label: func(item volume.BackupEntry) string { return item.VolumeName + " (" + item.ID + ")" },
- Promote: func(item volume.BackupEntry) *volume.BackupEntry { return &item },
+ return payload, nil
}
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index 31db59878..7e15e1999 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -1,390 +1,368 @@
package volumes
import (
- "errors"
"fmt"
+ "net/http"
"net/url"
"strconv"
"strings"
"github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- jsonOutput bool
- inUseOnlyFlag bool
- unusedOnlyFlag bool
- includeInternalFlag bool
-)
-
-var (
- volumeCreateName string
- volumeCreateDriver string
- volumeCreateOpts []string
- volumeCreateLabels []string
-)
-
-// VolumesCmd is the parent command for volume operations
-var VolumesCmd = &cobra.Command{
- Use: "volumes",
- Aliases: []string{"volume", "vol", "v"},
- Short: "Manage volumes",
+func Command() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "volumes",
+ Aliases: []string{"volume", "vol", "v"},
+ Short: "Manage volumes",
+ }
+ cmd.AddCommand(
+ newWorkspaceCmd(),
+ newRenameCmd(),
+ newBackupsCmd(),
+ newListCmd(),
+ newGetCmd(),
+ newDeleteCmd(),
+ newCountsCmd(),
+ newPruneCmd(),
+ newSizesCmd(),
+ newUsageCmd(),
+ newCreateCmd(),
+ )
+ cmdutil.SetScope(cmdutil.ScopeResource, cmd)
+ return cmd
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List volumes",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if inUseOnlyFlag && unusedOnlyFlag {
- return errors.New("--inuse and --unused cannot be used together")
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limitFlag int
+ startFlag int
+ allFlag bool
+ inUseOnlyFlag bool
+ unusedOnlyFlag bool
+ includeFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List volumes",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- // Filter server-side so that pagination and the reported totals apply to
- // the matching set rather than to whichever page happened to be fetched.
- query := url.Values{}
- if inUseOnlyFlag {
- query.Set("inUse", "true")
- }
- if unusedOnlyFlag {
- query.Set("inUse", "false")
- }
- if includeInternalFlag {
- query.Set("include", "true")
- }
+ // Filter server-side so that pagination and the reported totals apply to
+ // the matching set rather than to whichever page happened to be fetched.
+ query := url.Values{}
+ if opts.inUseOnlyFlag {
+ query.Set("inUse", "true")
+ }
+ if opts.unusedOnlyFlag {
+ query.Set("inUse", "false")
+ }
+ if opts.includeFlag {
+ query.Set("include", "true")
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[volume.Volume]{
- Resource: "volumes",
- Endpoint: types.Volumes(c.EnvID()),
- Params: cmdutil.ListParams{
- Resource: "volumes",
- Limit: limitFlag,
- FallbackDefault: 20,
- Start: startFlag,
- All: allFlag,
- },
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED", "IN USE"},
- Row: func(vol volume.Volume) []string {
- inUse := "No"
- if vol.InUse {
- inUse = "Yes"
- }
- return []string{
- vol.Name,
- vol.Driver,
- vol.Mountpoint,
- vol.CreatedAt,
- inUse,
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[volume.Volume]{
+ Resource: "volumes",
+ Endpoint: types.Volumes(c.EnvID()),
+ Params: cmdutil.ListParams{
+ Resource: "volumes",
+ Limit: opts.limitFlag,
+ FallbackDefault: 20,
+ Start: opts.startFlag,
+ All: opts.allFlag,
+ },
+ Query: query,
+ Headers: []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED", "IN USE"},
+ Row: func(vol volume.Volume) []string {
+ return []string{
+ vol.Name,
+ vol.Driver,
+ vol.Mountpoint,
+ vol.CreatedAt,
+ kit.Ternary(vol.InUse, "Yes", "No"),
+ }
+ },
+ })
+ },
+ }
+ cmd.Flags().IntVarP(&opts.limitFlag, "limit", "n", 20, "Number of volumes to show")
+ cmd.Flags().IntVar(&opts.startFlag, "start", 0, cmdutil.StartFlagUsage)
+ cmd.Flags().BoolVarP(&opts.allFlag, "all", "a", false, cmdutil.AllFlagUsage)
+ cmd.Flags().BoolVar(&opts.inUseOnlyFlag, "inuse", false, "Only show volumes currently in use")
+ cmd.Flags().BoolVar(&opts.unusedOnlyFlag, "unused", false, "Only show volumes not in use")
+ cmd.Flags().BoolVar(&opts.includeFlag, "include-internal", false, "Include Arcane-internal volumes")
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ cmd.PreRunE = func(cmd *cobra.Command, _ []string) error { return cmdutil.ExclusiveFlags(cmd, "inuse", "unused") }
+ return cmd
}
-var getCmd = &cobra.Command{
- Use: "get <volume-name>",
- Short: "Get volume details",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newGetCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "get <volume-name>",
+ Short: "Get volume details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, err := volumeRef.Fetch(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(resolved)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(resolved)
+ }
- output.Header("Volume Details")
- output.KeyValue("Name", resolved.Name)
- output.KeyValue("Driver", resolved.Driver)
- output.KeyValue("Mountpoint", resolved.Mountpoint)
- output.KeyValue("Scope", resolved.Scope)
- output.KeyValue("Created", resolved.CreatedAt)
- output.KeyValue("In Use", resolved.InUse)
- if resolved.Size > 0 {
- output.KeyValue("Size", output.Bytes(resolved.Size))
- }
- return nil
- },
+ output.Header("Volume Details")
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Driver", resolved.Driver)
+ output.KeyValue("Mountpoint", resolved.Mountpoint)
+ output.KeyValue("Scope", resolved.Scope)
+ output.KeyValue("Created", resolved.CreatedAt)
+ output.KeyValue("In Use", resolved.InUse)
+ if resolved.Size > 0 {
+ output.KeyValue("Size", output.Bytes(resolved.Size))
+ }
+ return nil
+ },
+ }
}
-var deleteCmd = &cobra.Command{
- Use: "delete <volume-name>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a volume",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete volume %s?", resolved.Name))
- if confirmErr != nil {
- return confirmErr
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "delete <volume-name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a volume",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- deletePath := cmdutil.AppendQuery(
- types.Volume(c.EnvID(), resolved.Name),
- url.Values{"force": []string{strconv.FormatBool(forceFlag)}},
- )
- resp, err := c.Delete(cmd.Context(), deletePath)
- if err != nil {
- return fmt.Errorf("failed to delete volume: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to delete volume: %w", ensureSuccessStatusErr)
- }
-
- output.Success("Volume %s deleted successfully", resolved.Name)
- return nil
- },
-}
+ allowPrompt := !opts.forceFlag && cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
-var countsCmd = &cobra.Command{
- Use: "counts",
- Short: "Get volume usage counts",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[any](cmd.Context(), types.VolumesCounts(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get volume counts: %w", err)
- }
- if !jsonOutput {
- output.Header("Volume Usage Counts")
- }
- if printErr := cmdutil.PrintJSON(result.Data); printErr != nil {
- return fmt.Errorf("failed to marshal volume counts: %w", printErr)
- }
- return nil
- },
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.forceFlag,
+ Prompt: fmt.Sprintf("Are you sure you want to delete volume %s?", resolved.Name),
+ Path: cmdutil.AppendQuery(types.Volume(c.EnvID(), resolved.Name), url.Values{"force": []string{strconv.FormatBool(opts.forceFlag)}}),
+ FailureMessage: "failed to delete volume",
+ SuccessMessage: fmt.Sprintf("Volume %s deleted successfully", resolved.Name),
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Force removal of a volume that is in use and skip the confirmation prompt")
+ return cmd
}
-var pruneCmd = &cobra.Command{
- Use: "prune",
- Short: "Remove unused volumes",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to prune unused volumes?")
+func newCountsCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "counts",
+ Short: "Get volume usage counts",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+ return cmdutil.Run(cmd, c, cmdutil.Spec[any]{
+ Method: http.MethodGet,
+ Path: types.VolumesCounts(c.EnvID()),
+ FailureMessage: "failed to get volume counts",
+ Render: func(data any) error {
+ output.Header("Volume Usage Counts")
+ return cmdutil.PrintJSON(data)
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
+}
+
+func newPruneCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "prune",
+ Short: "Remove unused volumes",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.forceFlag, "Are you sure you want to prune unused volumes?")
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
}
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- return cmdutil.RunPostAction[any](cmd, c, cmdutil.PostActionSpec{
- Path: types.VolumesPrune(c.EnvID()),
- FailureMessage: "failed to prune volumes",
- SuccessMessage: "Volumes pruned successfully",
- JSON: jsonOutput,
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[any]{
+ Method: http.MethodPost,
+ Path: types.VolumesPrune(c.EnvID()),
+ FailureMessage: "failed to prune volumes",
+ Render: func(any) error { output.Success("%s", "Volumes pruned successfully"); return nil },
+ })
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Force prune without confirmation")
+ cmdutil.SetScope(cmdutil.ScopeFleet, cmd)
+ return cmd
}
-var sizesCmd = &cobra.Command{
- Use: "sizes",
- Short: "Get volume sizes",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- result, err := c.GetJSON[any](cmd.Context(), types.VolumesSizes(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get volume sizes: %w", err)
- }
- if !jsonOutput {
- output.Header("Volume Sizes")
- }
- if printErr := cmdutil.PrintJSON(result.Data); printErr != nil {
- return fmt.Errorf("failed to marshal volume sizes: %w", printErr)
- }
- return nil
- },
+func newSizesCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "sizes",
+ Short: "Get volume sizes",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.Run(cmd, c, cmdutil.Spec[any]{
+ Method: http.MethodGet,
+ Path: types.VolumesSizes(c.EnvID()),
+ FailureMessage: "failed to get volume sizes",
+ Render: func(data any) error {
+ output.Header("Volume Sizes")
+ return cmdutil.PrintJSON(data)
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, cmd)
+ return cmd
}
-var usageCmd = &cobra.Command{
- Use: "usage <volume-name>",
- Short: "Get specific volume usage",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[any](cmd.Context(), types.VolumeUsage(c.EnvID(), resolved.Name))
- if err != nil {
- return fmt.Errorf("failed to get volume usage: %w", err)
- }
+func newUsageCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "usage <volume-name>",
+ Short: "Get specific volume usage",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- output.Header("Volume Usage: %s", resolved.Name)
- return cmdutil.PrintJSON(result.Data)
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[any]{
+ Method: http.MethodGet,
+ Path: types.VolumeUsage(c.EnvID(), resolved.Name),
+ FailureMessage: "failed to get volume usage",
+ Render: func(data any) error {
+ output.Header("Volume Usage: %s", resolved.Name)
+ return cmdutil.PrintJSON(data)
+ },
+ })
+ },
+ }
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a volume",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ volumeCreateName string
+ volumeCreateDriver string
+ volumeCreateOpts []string
+ volumeCreateLabels []string
+ }
+ cmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a volume",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- req := volume.Create{
- Name: volumeCreateName,
- Driver: volumeCreateDriver,
- }
+ var driverOpts, labels map[string]string
- if len(volumeCreateOpts) > 0 {
- req.DriverOpts = make(map[string]string)
- for _, opt := range volumeCreateOpts {
- parts := strings.SplitN(opt, "=", 2)
- if len(parts) == 2 {
- req.DriverOpts[parts[0]] = parts[1]
+ if len(opts.volumeCreateOpts) > 0 {
+ driverOpts = make(map[string]string)
+ for _, opt := range opts.volumeCreateOpts {
+ parts := strings.SplitN(opt, "=", 2)
+ if len(parts) == 2 {
+ driverOpts[parts[0]] = parts[1]
+ }
}
}
- }
- if len(volumeCreateLabels) > 0 {
- req.Labels = make(map[string]string)
- for _, lbl := range volumeCreateLabels {
- parts := strings.SplitN(lbl, "=", 2)
- if len(parts) == 2 {
- req.Labels[parts[0]] = parts[1]
+ if len(opts.volumeCreateLabels) > 0 {
+ labels = make(map[string]string)
+ for _, lbl := range opts.volumeCreateLabels {
+ parts := strings.SplitN(lbl, "=", 2)
+ if len(parts) == 2 {
+ labels[parts[0]] = parts[1]
+ }
}
}
- }
- result, err := c.PostJSON[volume.Volume](cmd.Context(), types.Volumes(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to create volume: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Volume %s created successfully", result.Data.Name)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Driver", result.Data.Driver)
- output.KeyValue("Mountpoint", result.Data.Mountpoint)
- return nil
- },
-}
-
-func init() {
- cmdutil.SetScope(cmdutil.ScopeResource, VolumesCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd, countsCmd, sizesCmd)
- cmdutil.SetScope(cmdutil.ScopeFleet, pruneCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, createCmd)
- VolumesCmd.AddCommand(listCmd)
- VolumesCmd.AddCommand(getCmd)
- VolumesCmd.AddCommand(deleteCmd)
- VolumesCmd.AddCommand(countsCmd)
- VolumesCmd.AddCommand(pruneCmd)
- VolumesCmd.AddCommand(sizesCmd)
- VolumesCmd.AddCommand(usageCmd)
- VolumesCmd.AddCommand(createCmd)
-
- // List command flags
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of volumes to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- listCmd.Flags().BoolVar(&inUseOnlyFlag, "inuse", false, "Only show volumes currently in use")
- listCmd.Flags().BoolVar(&unusedOnlyFlag, "unused", false, "Only show volumes not in use")
- listCmd.Flags().BoolVar(&includeInternalFlag, "include-internal", false, "Include Arcane-internal volumes")
-
- // Get command flags
- getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force removal of a volume that is in use and skip the confirmation prompt")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Prune command flags
- pruneCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force prune without confirmation")
- pruneCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Other command flags
- countsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- sizesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- usageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&volumeCreateName, "name", "", "Volume name")
- createCmd.Flags().StringVar(&volumeCreateDriver, "driver", "", "Volume driver")
- createCmd.Flags().StringArrayVar(&volumeCreateOpts, "opt", nil, "Driver option (KEY=VALUE)")
- createCmd.Flags().StringArrayVar(&volumeCreateLabels, "label", nil, "Label (KEY=VALUE)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[volume.Volume]{
+ Method: http.MethodPost,
+ Path: types.Volumes(c.EnvID()),
+ Body: volume.Create{
+ Name: opts.volumeCreateName,
+ Driver: opts.volumeCreateDriver,
+ DriverOpts: driverOpts,
+ Labels: labels,
+ },
+ FailureMessage: "failed to create volume",
+ Render: func(data volume.Volume) error {
+ output.Success("Volume %s created successfully", data.Name)
+ output.KeyValue("Name", data.Name)
+ output.KeyValue("Driver", data.Driver)
+ output.KeyValue("Mountpoint", data.Mountpoint)
+ return nil
+ },
+ })
+ },
+ }
+ cmd.Flags().StringVar(&opts.volumeCreateName, "name", "", "Volume name")
+ cmd.Flags().StringVar(&opts.volumeCreateDriver, "driver", "", "Volume driver")
+ cmd.Flags().StringArrayVar(&opts.volumeCreateOpts, "opt", nil, "Driver option (KEY=VALUE)")
+ cmd.Flags().StringArrayVar(&opts.volumeCreateLabels, "label", nil, "Label (KEY=VALUE)")
+ _ = cmd.MarkFlagRequired("name")
+ cmdutil.SetScope(cmdutil.ScopeDestination, cmd)
+ return cmd
}
var volumeRef = cmdutil.ResourceRef[volume.Volume, volume.Volume]{
@@ -394,16 +372,12 @@ var volumeRef = cmdutil.ResourceRef[volume.Volume, volume.Volume]{
IDHint: "the volume name",
ListCmd: "arcane volumes list",
GetPath: types.Volume,
+ IdentifierOf: func(data volume.Volume) string { return data.Name },
ListPath: types.Volumes,
Matches: func(item volume.Volume, identifierLower, original string) bool {
- if strings.EqualFold(item.Name, original) {
- return true
- }
- if strings.Contains(strings.ToLower(item.Name), identifierLower) {
- return true
- }
idLower := strings.ToLower(item.ID)
- return idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower))
+ return strings.EqualFold(item.Name, original) || strings.Contains(strings.ToLower(item.Name), identifierLower) ||
+ idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower))
},
Label: func(match volume.Volume) string {
if match.Driver != "" {
diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.go
index 0a4c426df..f3dd5f138 100644
--- a/cli/pkg/volumes/workspace.go
+++ b/cli/pkg/volumes/workspace.go
@@ -3,6 +3,7 @@ package volumes
import (
"bytes"
"cmp"
+ "encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
@@ -13,328 +14,303 @@ import (
"os"
"path"
"path/filepath"
+ "slices"
"strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/volume"
- workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"
+ "github.com/getarcaneapp/arcane/types/v2/workspace"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var workspaceCmd = &cobra.Command{
- Use: "workspace <volume-name> [path]",
- Short: "Browse volume workspace files",
- Args: cobra.RangeArgs(1, 2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+func newWorkspaceCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "workspace <volume-name> [path]",
+ Short: "Browse volume workspace files",
+ Args: cobra.RangeArgs(1, 2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- resp, err := c.Get(cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))
- if err != nil {
- return fmt.Errorf("failed to get volume workspace: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to get volume workspace: %w", ensureSuccessStatusErr)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- var result base.ApiResponse[workspacetypes.Workspace]
- if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
- return decodeJSONErr
- }
+ result, err := c.GetJSON[workspace.Workspace](cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))
+ if err != nil {
+ return fmt.Errorf("failed to get volume workspace: %w", err)
+ }
- // The endpoint returns the full tree; an optional path argument
- // narrows the listing to that subtree.
- entries := result.Data.Files
- if len(args) == 2 {
- prefix := strings.Trim(args[1], "/")
- filtered := entries[:0:0]
- for _, entry := range entries {
- if entry.RelativePath == prefix || strings.HasPrefix(entry.RelativePath, prefix+"/") {
- filtered = append(filtered, entry)
+ // The endpoint returns the full tree; an optional path argument
+ // narrows the listing to that subtree.
+ entries := result.Data.Files
+ if len(args) == 2 {
+ prefix := strings.Trim(args[1], "/")
+ filtered := entries[:0:0]
+ for _, entry := range entries {
+ if entry.RelativePath == prefix || strings.HasPrefix(entry.RelativePath, prefix+"/") {
+ filtered = append(filtered, entry)
+ }
}
+ entries = filtered
}
- entries = filtered
- }
- if jsonOutput {
- return cmdutil.PrintJSON(entries)
- }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(entries)
+ }
- headers := []string{"PATH", "TYPE", "SIZE", "MODIFIED"}
- rows := make([][]string, len(entries))
- for i, entry := range entries {
- entryType := "file"
- switch {
- case entry.IsDirectory:
- entryType = "dir"
- case entry.IsSymlink:
- entryType = "symlink"
- }
- size := ""
- if !entry.IsDirectory {
- size = output.Bytes(entry.Size)
- }
- rows[i] = []string{
- entry.RelativePath,
- entryType,
- size,
- entry.ModTime.Format(time.RFC3339),
- }
- }
- if tableErr := output.Table(headers, rows); tableErr != nil {
- return tableErr
- }
- if result.Data.FileTreeTruncated {
- output.Warning("File listing was truncated by the server")
- }
- return nil
- },
+ headers := []string{"PATH", "TYPE", "SIZE", "MODIFIED"}
+ rows := make([][]string, len(entries))
+ for i, entry := range entries {
+ entryType := "file"
+ switch {
+ case entry.IsDirectory:
+ entryType = "dir"
+ case entry.IsSymlink:
+ entryType = "symlink"
+ }
+ rows[i] = []string{
+ entry.RelativePath,
+ entryType,
+ kit.Ternary(entry.IsDirectory, "", output.Bytes(entry.Size)),
+ entry.ModTime.Format(time.RFC3339),
+ }
+ }
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
+ if result.Data.FileTreeTruncated {
+ output.Warning("File listing was truncated by the server")
+ }
+ return nil
+ },
+ }
+ cmd.AddCommand(
+ newWorkspaceCatCmd(),
+ newWorkspaceDownloadCmd(),
+ newWorkspacePutCmd(),
+ )
+ return cmd
}
-var workspaceCatCmd = &cobra.Command{
- Use: "cat <volume-name> <path>",
- Short: "Print a volume workspace file",
- Args: cobra.ExactArgs(2),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !jsonOutput && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
-
- filePath := cmdutil.AppendQuery(
- types.VolumeWorkspaceFile(c.EnvID(), resolved.Name),
- url.Values{"relativePath": []string{args[1]}},
- )
- resp, err := c.Get(cmd.Context(), filePath)
- if err != nil {
- return fmt.Errorf("failed to get workspace file: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to get workspace file: %w", ensureSuccessStatusErr)
- }
-
- var result base.ApiResponse[workspacetypes.FileContent]
- if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
- return decodeJSONErr
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newWorkspaceCatCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "cat <volume-name> <path>",
+ Short: "Print a volume workspace file",
+ Args: cobra.ExactArgs(2),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {
- return fmt.Errorf("file %s has no printable content (%s); use `arcane volumes workspace download` instead", args[1], result.Data.ReadOnlyReason)
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)
- return nil
- },
+ filePath := cmdutil.AppendQuery(
+ types.VolumeWorkspaceFile(c.EnvID(), resolved.Name),
+ url.Values{"relativePath": []string{args[1]}},
+ )
+ return cmdutil.Run(cmd, c, cmdutil.Spec[workspace.FileContent]{
+ Method: http.MethodGet,
+ Path: filePath,
+ FailureMessage: "failed to get workspace file",
+ Render: func(data workspace.FileContent) error {
+ if data.Content == "" && data.ReadOnlyReason != "" {
+ return fmt.Errorf("file %s has no printable content (%s); use `arcane volumes workspace download` instead", args[1], data.ReadOnlyReason)
+ }
+ _, _ = fmt.Fprint(output.Stdout(), data.Content)
+ return nil
+ },
+ })
+ },
+ }
}
-var workspaceDownloadCmd = &cobra.Command{
- Use: "download <volume-name> <path> [output-file]",
- Short: "Download a volume workspace file",
- Args: cobra.RangeArgs(2, 3),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newWorkspaceDownloadCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "download <volume-name> <path> [output-file]",
+ Short: "Download a volume workspace file",
+ Args: cobra.RangeArgs(2, 3),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- allowPrompt := prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+ allowPrompt := cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- // Downloading large files can take a long time
- c.SetTimeout(30 * time.Minute)
+ // Downloading large files can take a long time
+ c.SetTimeout(30 * time.Minute)
- downloadPath := cmdutil.AppendQuery(
- types.VolumeWorkspaceFileDownload(c.EnvID(), resolved.Name),
- url.Values{"relativePath": []string{args[1]}},
- )
- resp, err := c.Get(cmd.Context(), downloadPath)
- if err != nil {
- return fmt.Errorf("failed to download workspace file: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
- }
+ downloadPath := cmdutil.AppendQuery(
+ types.VolumeWorkspaceFileDownload(c.EnvID(), resolved.Name),
+ url.Values{"relativePath": []string{args[1]}},
+ )
+ resp, err := c.Get(cmd.Context(), downloadPath)
+ if err != nil {
+ return fmt.Errorf("failed to download workspace file: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
+ }
- outputFile := ""
- if len(args) == 3 {
- outputFile = args[2]
- }
- if outputFile == "" {
- outputFile = path.Base(args[1])
- if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
- outputFile = cmp.Or(params["filename"], outputFile)
- }
- }
+ outputFile := ""
+ if len(args) == 3 {
+ outputFile = args[2]
+ }
+ if outputFile == "" {
+ outputFile = path.Base(args[1])
+ if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
+ outputFile = cmp.Or(params["filename"], outputFile)
+ }
+ }
- file, openErr := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
- if openErr != nil {
- return fmt.Errorf("failed to create file %s: %w", outputFile, openErr)
- }
- if _, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading backup", !cmdutil.JSONOutputEnabled(cmd)); copyErr != nil {
- _ = file.Close()
- return fmt.Errorf("failed to write file %s: %w", outputFile, copyErr)
- }
- if closeErr := file.Close(); closeErr != nil {
- return fmt.Errorf("failed to write file %s: %w", outputFile, closeErr)
- }
+ file, openErr := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+ if openErr != nil {
+ return fmt.Errorf("failed to create file %s: %w", outputFile, openErr)
+ }
+ written, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading workspace file", !cmdutil.JSONOutputEnabled(cmd))
+ if copyErr != nil {
+ _ = file.Close()
+ return fmt.Errorf("failed to write file %s: %w", outputFile, copyErr)
+ }
+ if closeErr := file.Close(); closeErr != nil {
+ return fmt.Errorf("failed to write file %s: %w", outputFile, closeErr)
+ }
- output.Success("File downloaded to %s", outputFile)
- return nil
- },
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(struct {
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ }{outputFile, written})
+ }
+ output.Success("File downloaded to %s", outputFile)
+ return nil
+ },
+ }
}
-var workspacePutCmd = &cobra.Command{
- Use: "put <volume-name> <local-file> <path>",
- Short: "Write a local file into a volume workspace",
- Args: cobra.ExactArgs(3),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- allowPrompt := !forceFlag && prompt.IsInteractive()
- resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
- if err != nil {
- return err
- }
+func newWorkspacePutCmd() *cobra.Command {
+ var opts struct {
+ forceFlag bool
+ }
+ cmd := &cobra.Command{
+ Use: "put <volume-name> <local-file> <path>",
+ Short: "Write a local file into a volume workspace",
+ Args: cobra.ExactArgs(3),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- content, err := os.ReadFile(args[1])
- if err != nil {
- return fmt.Errorf("failed to read local file: %w", err)
- }
+ allowPrompt := !opts.forceFlag && cmdutil.AllowPrompt(cmd)
+ resolved, _, err := volumeRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
- relativePath := strings.Trim(filepath.ToSlash(args[2]), "/")
- if relativePath == "" {
- return errors.New("destination path is required")
- }
+ content, err := os.ReadFile(args[1])
+ if err != nil {
+ return fmt.Errorf("failed to read local file: %w", err)
+ }
- if !forceFlag {
- confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Write %s to %s in volume %s?", args[1], relativePath, resolved.Name))
- if confirmErr != nil {
- return confirmErr
+ relativePath := strings.Trim(filepath.ToSlash(args[2]), "/")
+ if relativePath == "" {
+ return errors.New("destination path is required")
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
+
+ confirmed, confirmationErr := cmdutil.ConfirmOrCancel(cmd, opts.forceFlag, fmt.Sprintf("Write %s to %s in volume %s?", args[1], relativePath, resolved.Name))
+ if confirmationErr != nil || !confirmed {
+ return confirmationErr
}
- }
- workspaceResp, err := c.Get(cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))
- if err != nil {
- return fmt.Errorf("failed to get volume workspace: %w", err)
- }
- defer func() { _ = workspaceResp.Body.Close() }()
- if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(workspaceResp); ensureSuccessStatusErr != nil {
- return fmt.Errorf("failed to get volume workspace: %w", ensureSuccessStatusErr)
- }
- var current base.ApiResponse[workspacetypes.Workspace]
- if decodeJSONErr := cmdutil.DecodeJSON(workspaceResp, &current); decodeJSONErr != nil {
- return decodeJSONErr
- }
+ current, err := c.GetJSON[workspace.Workspace](cmd.Context(), types.VolumeWorkspace(c.EnvID(), resolved.Name))
+ if err != nil {
+ return fmt.Errorf("failed to get volume workspace: %w", err)
+ }
- operation := volume.FileOpCreateFile
- for _, entry := range current.Data.Files {
- if entry.RelativePath == relativePath && !entry.IsDirectory {
+ operation := volume.FileOpCreateFile
+ if slices.ContainsFunc(current.Data.Files, func(entry workspace.FileEntry) bool {
+ return entry.RelativePath == relativePath && !entry.IsDirectory
+ }) {
operation = volume.FileOpUpdateFile
- break
}
- }
-
- uploadIndex := 0
- manifest := volume.WorkspaceUpdateManifest{
- FileTreeRevision: current.Data.FileTreeRevision,
- FileChanges: []volume.WorkspaceFileChange{{
- Operation: operation,
- RelativePath: relativePath,
- UploadIndex: &uploadIndex,
- }},
- }
- manifestJSON, err := json.Marshal(manifest)
- if err != nil {
- return fmt.Errorf("failed to encode workspace manifest: %w", err)
- }
-
- var requestBody bytes.Buffer
- writer := multipart.NewWriter(&requestBody)
- if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
- return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
- }
- filePart, err := writer.CreateFormFile("files", path.Base(relativePath))
- if err != nil {
- return fmt.Errorf("failed to create workspace upload: %w", err)
- }
- if _, writeErr := filePart.Write(content); writeErr != nil {
- return fmt.Errorf("failed to write workspace upload: %w", writeErr)
- }
- if closeErr := writer.Close(); closeErr != nil {
- return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
- }
- resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.VolumeWorkspace(c.EnvID(), resolved.Name), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
- if err != nil {
- return fmt.Errorf("failed to update volume workspace: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
- if updateStatusErr := cmdutil.EnsureSuccessStatus(resp); updateStatusErr != nil {
- return fmt.Errorf("failed to update volume workspace: %w", updateStatusErr)
- }
-
- if jsonOutput {
- var result base.ApiResponse[workspacetypes.Workspace]
- if decodeUpdateErr := cmdutil.DecodeJSON(resp, &result); decodeUpdateErr != nil {
- return decodeUpdateErr
+ uploadIndex := 0
+ manifest := volume.WorkspaceUpdateManifest{
+ FileTreeRevision: current.Data.FileTreeRevision,
+ FileChanges: []volume.WorkspaceFileChange{{
+ Operation: operation,
+ RelativePath: relativePath,
+ UploadIndex: &uploadIndex,
+ }},
+ }
+ manifestJSON, err := json.Marshal(manifest)
+ if err != nil {
+ return fmt.Errorf("failed to encode workspace manifest: %w", err)
}
- return cmdutil.PrintJSON(result.Data)
- }
- output.Success("File %s written to volume %s", relativePath, resolved.Name)
- return nil
- },
-}
+ var requestBody bytes.Buffer
+ writer := multipart.NewWriter(&requestBody)
+ if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
+ }
+ filePart, err := writer.CreateFormFile("files", path.Base(relativePath))
+ if err != nil {
+ return fmt.Errorf("failed to create workspace upload: %w", err)
+ }
+ if _, writeErr := filePart.Write(content); writeErr != nil {
+ return fmt.Errorf("failed to write workspace upload: %w", writeErr)
+ }
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
+ }
-func init() {
- VolumesCmd.AddCommand(workspaceCmd)
- workspaceCmd.AddCommand(workspaceCatCmd)
- workspaceCmd.AddCommand(workspaceDownloadCmd)
- workspaceCmd.AddCommand(workspacePutCmd)
+ resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.VolumeWorkspace(c.EnvID(), resolved.Name), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
+ if err != nil {
+ return fmt.Errorf("failed to update volume workspace: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ responseBody, readErr := cmdutil.ReadJSONBody(resp)
+ if readErr != nil {
+ return fmt.Errorf("failed to update volume workspace: %w", readErr)
+ }
+ var result base.ApiResponse[jsontext.Value]
+ if decodeErr := json.Unmarshal(responseBody, &result); decodeErr != nil {
+ return fmt.Errorf("failed to parse response: %w", decodeErr)
+ }
+ if cmdutil.JSONOutputEnabled(cmd) {
+ return cmdutil.PrintJSON(result.Data)
+ }
- workspaceCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- workspaceCatCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- workspacePutCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Write without confirmation")
- workspacePutCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ output.Success("File %s written to volume %s", relativePath, resolved.Name)
+ return nil
+ },
+ }
+ cmd.Flags().BoolVarP(&opts.forceFlag, "force", "f", false, "Write without confirmation")
+ return cmd
}
diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.go
index c6a7fa313..5db20ba70 100644
--- a/cli/pkg/vulnerabilities/cmd.go
+++ b/cli/pkg/vulnerabilities/cmd.go
@@ -5,12 +5,14 @@ import (
"cmp"
"context"
"fmt"
+ "net/http"
"net/url"
"strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
"github.com/spf13/cobra"
+ kit "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
@@ -19,391 +21,380 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/pkg/images"
)
-var (
- jsonOutput bool
- limitFlag int
- startFlag int
- allFlag bool
- forceFlag bool
- severityFlag string
- imageFlag string
- summaryFlag bool
-
- ignoreImageFlag string
- ignorePkgFlag string
- ignoreVersionFlag string
- ignoreReasonFlag string
-)
-
-// VulnerabilitiesCmd is the parent command for vulnerability operations
-var VulnerabilitiesCmd = &cobra.Command{
- Use: "vulnerabilities",
- Aliases: []string{"vulns", "vuln", "cve"},
- Short: "Manage image vulnerability scans",
+// Command builds the vulnerabilities command tree.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeResource},
+ Use: "vulnerabilities",
+ Aliases: []string{"vulns", "vuln", "cve"},
+ Short: "Manage image vulnerability scans",
+ }
+ command.AddCommand(newStatusCmd(), newSummaryCmd(), newListCmd(), newScanCmd(), newImageCmd(), newIgnoreCmd(), newIgnoredCmd(), newUnignoreCmd())
+ return command
}
-var statusCmd = &cobra.Command{
- Use: "status",
- Short: "Show vulnerability scanner status",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[struct {
- Available bool `json:"available"`
- Version string `json:"version,omitempty"`
- }](cmd.Context(), types.VulnerabilitiesScannerStatus(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get scanner status: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newStatusCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "status",
+ Short: "Show vulnerability scanner status",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Vulnerability Scanner")
- output.KeyValue("Available", result.Data.Available)
- if result.Data.Version != "" {
- output.KeyValue("Version", result.Data.Version)
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[vulnerability.ScannerStatus]{
+ Method: http.MethodGet,
+ Path: types.VulnerabilitiesScannerStatus(c.EnvID()),
+ FailureMessage: "failed to get scanner status",
+ Render: func(data vulnerability.ScannerStatus) error {
+ output.Header("Vulnerability Scanner")
+ output.KeyValue("Available", data.Available)
+ if data.Version != "" {
+ output.KeyValue("Version", data.Version)
+ }
+ return nil
+ },
+ })
+ },
+ }
}
-var summaryCmd = &cobra.Command{
- Use: "summary",
- Short: "Show environment-wide vulnerability summary",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[vulnerability.EnvironmentVulnerabilitySummary](cmd.Context(), types.VulnerabilitiesSummary(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get vulnerability summary: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newSummaryCmd() *cobra.Command {
+ return &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "summary",
+ Short: "Show environment-wide vulnerability summary",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Header("Vulnerability Summary")
- output.KeyValue("Total Images", result.Data.TotalImages)
- output.KeyValue("Scanned Images", result.Data.ScannedImages)
- printSeveritySummary(result.Data.Summary)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[vulnerability.EnvironmentVulnerabilitySummary]{
+ Method: http.MethodGet,
+ Path: types.VulnerabilitiesSummary(c.EnvID()),
+ FailureMessage: "failed to get vulnerability summary",
+ Render: func(data vulnerability.EnvironmentVulnerabilitySummary) error {
+ output.Header("Vulnerability Summary")
+ output.KeyValue("Total Images", data.TotalImages)
+ output.KeyValue("Scanned Images", data.ScannedImages)
+ printSeveritySummary(data.Summary)
+ return nil
+ },
+ })
+ },
+ }
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List vulnerabilities across all scanned images",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+func newListCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ severity string
+ image string
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List vulnerabilities across all scanned images",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- query := url.Values{}
- if severityFlag != "" {
- query.Set("severity", strings.ToUpper(severityFlag))
- }
- if imageFlag != "" {
- query.Set("imageName", imageFlag)
- }
+ query := url.Values{}
+ if opts.severity != "" {
+ query.Set("severity", strings.ToUpper(opts.severity))
+ }
+ if opts.image != "" {
+ query.Set("imageName", opts.image)
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.VulnerabilityWithImage]{
- Resource: "vulnerabilities",
- Endpoint: types.VulnerabilitiesAll(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"CVE ID", "SEVERITY", "IMAGE", "PACKAGE", "VERSION", "FIXED IN"},
- Row: func(item vulnerability.VulnerabilityWithImage) []string {
- return []string{
- item.VulnerabilityID,
- string(item.Severity),
- item.ImageName,
- item.PkgName,
- item.InstalledVersion,
- cmp.Or(item.FixedVersion, "-"),
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.VulnerabilityWithImage]{
+ Resource: "vulnerabilities",
+ Endpoint: types.VulnerabilitiesAll(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Query: query,
+ Headers: []string{"CVE ID", "SEVERITY", "IMAGE", "PACKAGE", "VERSION", "FIXED IN"},
+ Row: func(item vulnerability.VulnerabilityWithImage) []string {
+ return []string{
+ item.VulnerabilityID,
+ string(item.Severity),
+ item.ImageName,
+ item.PkgName,
+ item.InstalledVersion,
+ cmp.Or(item.FixedVersion, "-"),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of vulnerabilities to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ command.Flags().StringVar(&opts.severity, "severity", "", "Comma-separated severity filter (critical,high,medium,low,unknown)")
+ command.Flags().StringVar(&opts.image, "image", "", "Filter by image name (substring)")
+ return command
}
-var scanCmd = &cobra.Command{
- Use: "scan <image>",
- Short: "Scan an image for vulnerabilities",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- imageID, err := resolveImageID(cmd.Context(), c, args[0])
- if err != nil {
- return err
- }
-
- // Scans can take a long time on large images.
- c.SetTimeout(30 * time.Minute)
-
- result, err := c.PostJSON[vulnerability.ScanResult](cmd.Context(), types.ImageVulnerabilitiesScan(c.EnvID(), imageID), nil)
- if err != nil {
- return fmt.Errorf("failed to scan image: %w", err)
- }
+func newScanCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "scan <image>",
+ Short: "Scan an image for vulnerabilities",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+ imageID, err := resolveImageID(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
- output.Header("Vulnerability Scan")
- output.KeyValue("Image", result.Data.ImageName)
- output.KeyValue("Status", string(result.Data.Status))
- if result.Data.ScanPhase != "" {
- output.KeyValue("Phase", string(result.Data.ScanPhase))
- }
- if result.Data.Error != "" {
- output.KeyValue("Error", result.Data.Error)
- }
- if result.Data.ScannerVersion != "" {
- output.KeyValue("Scanner", result.Data.ScannerVersion)
- }
- printSeveritySummary(result.Data.Summary)
- return nil
- },
+ // Scans can take a long time on large images.
+ c.SetTimeout(30 * time.Minute)
+
+ return cmdutil.Run(cmd, c, cmdutil.Spec[vulnerability.ScanResult]{
+ Method: http.MethodPost,
+ Path: types.ImageVulnerabilitiesScan(c.EnvID(), imageID),
+ Body: nil,
+ FailureMessage: "failed to scan image",
+ Render: func(data vulnerability.ScanResult) error {
+ output.Header("Vulnerability Scan")
+ output.KeyValue("Image", data.ImageName)
+ output.KeyValue("Status", string(data.Status))
+ if data.ScanPhase != "" {
+ output.KeyValue("Phase", string(data.ScanPhase))
+ }
+ if data.Error != "" {
+ output.KeyValue("Error", data.Error)
+ }
+ if data.ScannerVersion != "" {
+ output.KeyValue("Scanner", data.ScannerVersion)
+ }
+ printSeveritySummary(data.Summary)
+ return nil
+ },
+ })
+ },
+ }
}
-var imageCmd = &cobra.Command{
- Use: "image <image>",
- Short: "List vulnerabilities for an image",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- imageID, err := resolveImageID(cmd.Context(), c, args[0])
- if err != nil {
- return err
- }
-
- if summaryFlag {
- result, summaryErr := c.GetJSON[vulnerability.ScanSummary](cmd.Context(), types.ImageVulnerabilitiesSummary(c.EnvID(), imageID))
- if summaryErr != nil {
- return fmt.Errorf("failed to get image vulnerability summary: %w", summaryErr)
+func newImageCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ severity string
+ summary bool
+ }
+ command := &cobra.Command{
+ Use: "image <image>",
+ Short: "List vulnerabilities for an image",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
+ imageID, err := resolveImageID(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
}
- output.Header("Image Vulnerability Summary")
- output.KeyValue("Image ID", result.Data.ImageID)
- output.KeyValue("Status", string(result.Data.Status))
- output.KeyValue("Scan Time", result.Data.ScanTime.Format(time.RFC3339))
- if result.Data.ScanPhase != "" {
- output.KeyValue("Phase", string(result.Data.ScanPhase))
+ if opts.summary {
+ return cmdutil.Run(cmd, c, cmdutil.Spec[vulnerability.ScanSummary]{
+ Method: http.MethodGet,
+ Path: types.ImageVulnerabilitiesSummary(c.EnvID(), imageID),
+ FailureMessage: "failed to get image vulnerability summary",
+ Render: func(data vulnerability.ScanSummary) error {
+ output.Header("Image Vulnerability Summary")
+ output.KeyValue("Image ID", data.ImageID)
+ output.KeyValue("Status", string(data.Status))
+ output.KeyValue("Scan Time", data.ScanTime.Format(time.RFC3339))
+ if data.ScanPhase != "" {
+ output.KeyValue("Phase", string(data.ScanPhase))
+ }
+ if data.Error != "" {
+ output.KeyValue("Error", data.Error)
+ }
+ printSeveritySummary(data.Summary)
+ return nil
+ },
+ })
}
- if result.Data.Error != "" {
- output.KeyValue("Error", result.Data.Error)
- }
- printSeveritySummary(result.Data.Summary)
- return nil
- }
- query := url.Values{}
- if severityFlag != "" {
- query.Set("severity", strings.ToUpper(severityFlag))
- }
+ query := url.Values{}
+ if opts.severity != "" {
+ query.Set("severity", strings.ToUpper(opts.severity))
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.Vulnerability]{
- Resource: "vulnerabilities",
- Endpoint: types.ImageVulnerabilitiesList(c.EnvID(), imageID),
- Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- Query: query,
- JSON: jsonOutput,
- Headers: []string{"CVE ID", "SEVERITY", "PACKAGE", "VERSION", "FIXED IN"},
- Row: func(item vulnerability.Vulnerability) []string {
- return []string{
- item.VulnerabilityID,
- string(item.Severity),
- item.PkgName,
- item.InstalledVersion,
- cmp.Or(item.FixedVersion, "-"),
- }
- },
- })
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.Vulnerability]{
+ Resource: "vulnerabilities",
+ Endpoint: types.ImageVulnerabilitiesList(c.EnvID(), imageID),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Query: query,
+ Headers: []string{"CVE ID", "SEVERITY", "PACKAGE", "VERSION", "FIXED IN"},
+ Row: func(item vulnerability.Vulnerability) []string {
+ return []string{
+ item.VulnerabilityID,
+ string(item.Severity),
+ item.PkgName,
+ item.InstalledVersion,
+ cmp.Or(item.FixedVersion, "-"),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().BoolVar(&opts.summary, "summary", false, "Show the scan summary instead of the detailed list")
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of vulnerabilities to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ command.Flags().StringVar(&opts.severity, "severity", "", "Comma-separated severity filter (critical,high,medium,low,unknown)")
+ return command
}
-var ignoreCmd = &cobra.Command{
- Use: "ignore <cve-id>",
- Short: "Ignore a vulnerability for an image",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- imageID, err := resolveImageID(cmd.Context(), c, ignoreImageFlag)
- if err != nil {
- return err
- }
-
- payload := vulnerability.IgnorePayload{
- ImageID: imageID,
- VulnerabilityID: args[0],
- PkgName: ignorePkgFlag,
- InstalledVersion: ignoreVersionFlag,
- }
- if ignoreReasonFlag != "" {
- payload.Reason = &ignoreReasonFlag
- }
-
- result, err := c.PostJSON[vulnerability.IgnoredVulnerability](cmd.Context(), types.VulnerabilitiesIgnore(c.EnvID()), payload)
- if err != nil {
- return fmt.Errorf("failed to ignore vulnerability: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
+func newIgnoreCmd() *cobra.Command {
+ var opts struct {
+ image string
+ pkg string
+ version string
+ reason string
+ }
+ command := &cobra.Command{
+ Use: "ignore <cve-id>",
+ Short: "Ignore a vulnerability for an image",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- output.Success("Vulnerability %s ignored", result.Data.VulnerabilityID)
- output.KeyValue("Ignore ID", result.Data.ID)
- return nil
- },
-}
+ imageID, err := resolveImageID(cmd.Context(), c, opts.image)
+ if err != nil {
+ return err
+ }
-var ignoredCmd = &cobra.Command{
- Use: "ignored",
- Short: "List ignored vulnerabilities",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
+ payload := vulnerability.IgnorePayload{
+ ImageID: imageID,
+ VulnerabilityID: args[0],
+ PkgName: opts.pkg,
+ InstalledVersion: opts.version,
+ Reason: kit.Ternary(cmd.Flags().Changed("reason"), &opts.reason, nil),
+ }
- return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.IgnoredVulnerability]{
- Resource: "ignored vulnerabilities",
- Endpoint: types.VulnerabilitiesIgnored(c.EnvID()),
- Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: limitFlag, FallbackDefault: 20, Start: startFlag, All: allFlag},
- JSON: jsonOutput,
- Headers: []string{"ID", "CVE ID", "IMAGE ID", "PACKAGE", "REASON", "CREATED"},
- Row: func(item vulnerability.IgnoredVulnerability) []string {
- reason := ""
- if item.Reason != nil {
- reason = *item.Reason
- }
- imageID := strings.TrimPrefix(item.ImageID, "sha256:")
- imageID = imageID[:min(len(imageID), 12)]
- return []string{
- item.ID,
- item.VulnerabilityID,
- imageID,
- item.PkgName,
- cmp.Or(reason, "-"),
- item.CreatedAt.Format(time.RFC3339),
- }
- },
- })
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[vulnerability.IgnoredVulnerability]{
+ Method: http.MethodPost,
+ Path: types.VulnerabilitiesIgnore(c.EnvID()),
+ Body: payload,
+ FailureMessage: "failed to ignore vulnerability",
+ Render: func(data vulnerability.IgnoredVulnerability) error {
+ output.Success("Vulnerability %s ignored", data.VulnerabilityID)
+ output.KeyValue("Ignore ID", data.ID)
+ return nil
+ },
+ })
+ },
+ }
+ command.Flags().StringVar(&opts.image, "image", "", "Image containing the vulnerability")
+ command.Flags().StringVar(&opts.pkg, "package", "", "Package name containing the vulnerability")
+ command.Flags().StringVar(&opts.version, "version", "", "Installed version of the vulnerable package")
+ command.Flags().StringVar(&opts.reason, "reason", "", "Reason for ignoring this vulnerability")
+ _ = command.MarkFlagRequired("image")
+ _ = command.MarkFlagRequired("package")
+ return command
}
-var unignoreCmd = &cobra.Command{
- Use: "unignore <ignore-id>",
- Short: "Remove a vulnerability ignore record",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to remove ignore record %s?", args[0]))
+func newIgnoredCmd() *cobra.Command {
+ var opts struct {
+ limit int
+ start int
+ all bool
+ }
+ command := &cobra.Command{
+ Annotations: map[string]string{"arcane:scope": cmdutil.ScopeRead},
+ Use: "ignored",
+ Short: "List ignored vulnerabilities",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- if _, deleteIgnoreErr := c.DeleteJSON[struct{}](cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0])); deleteIgnoreErr != nil {
- return fmt.Errorf("failed to remove ignore record: %w", deleteIgnoreErr)
- }
-
- output.Success("Ignore record %s removed", args[0])
- return nil
- },
+ return cmdutil.RunList(cmd, c, cmdutil.ListSpec[vulnerability.IgnoredVulnerability]{
+ Resource: "ignored vulnerabilities",
+ Endpoint: types.VulnerabilitiesIgnored(c.EnvID()),
+ Params: cmdutil.ListParams{Resource: "vulnerabilities", Limit: opts.limit, FallbackDefault: 20, Start: opts.start, All: opts.all},
+ Headers: []string{"ID", "CVE ID", "IMAGE ID", "PACKAGE", "REASON", "CREATED"},
+ Row: func(item vulnerability.IgnoredVulnerability) []string {
+ imageID := strings.TrimPrefix(item.ImageID, "sha256:")
+ imageID = imageID[:min(len(imageID), 12)]
+ return []string{
+ item.ID,
+ item.VulnerabilityID,
+ imageID,
+ item.PkgName,
+ cmp.Or(kit.FromPtr(item.Reason), "-"),
+ item.CreatedAt.Format(time.RFC3339),
+ }
+ },
+ })
+ },
+ }
+ command.Flags().IntVarP(&opts.limit, "limit", "n", 20, "Number of ignore records to show")
+ command.Flags().IntVar(&opts.start, "start", 0, cmdutil.StartFlagUsage)
+ command.Flags().BoolVarP(&opts.all, "all", "a", false, cmdutil.AllFlagUsage)
+ return command
}
-func init() {
- cmdutil.SetResource(ignoreRef, unignoreCmd)
- cmdutil.SetScope(cmdutil.ScopeResource, VulnerabilitiesCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, statusCmd, summaryCmd, listCmd, ignoredCmd)
- VulnerabilitiesCmd.AddCommand(statusCmd)
- VulnerabilitiesCmd.AddCommand(summaryCmd)
- VulnerabilitiesCmd.AddCommand(listCmd)
- VulnerabilitiesCmd.AddCommand(scanCmd)
- VulnerabilitiesCmd.AddCommand(imageCmd)
- VulnerabilitiesCmd.AddCommand(ignoreCmd)
- VulnerabilitiesCmd.AddCommand(ignoredCmd)
- VulnerabilitiesCmd.AddCommand(unignoreCmd)
-
- statusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- summaryCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of vulnerabilities to show")
- listCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- listCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- listCmd.Flags().StringVar(&severityFlag, "severity", "", "Comma-separated severity filter (critical,high,medium,low,unknown)")
- listCmd.Flags().StringVar(&imageFlag, "image", "", "Filter by image name (substring)")
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- scanCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- imageCmd.Flags().BoolVar(&summaryFlag, "summary", false, "Show the scan summary instead of the detailed list")
- imageCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of vulnerabilities to show")
- imageCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- imageCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- imageCmd.Flags().StringVar(&severityFlag, "severity", "", "Comma-separated severity filter (critical,high,medium,low,unknown)")
- imageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- ignoreCmd.Flags().StringVar(&ignoreImageFlag, "image", "", "Image containing the vulnerability")
- ignoreCmd.Flags().StringVar(&ignorePkgFlag, "package", "", "Package name containing the vulnerability")
- ignoreCmd.Flags().StringVar(&ignoreVersionFlag, "version", "", "Installed version of the vulnerable package")
- ignoreCmd.Flags().StringVar(&ignoreReasonFlag, "reason", "", "Reason for ignoring this vulnerability")
- ignoreCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = ignoreCmd.MarkFlagRequired("image")
- _ = ignoreCmd.MarkFlagRequired("package")
-
- ignoredCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of ignore records to show")
- ignoredCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
- ignoredCmd.Flags().BoolVarP(&allFlag, "all", "a", false, cmdutil.AllFlagUsage)
- ignoredCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newUnignoreCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "unignore <ignore-id>",
+ Short: "Remove a vulnerability ignore record",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- unignoreCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Skip the confirmation prompt")
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to remove ignore record %s?", args[0]),
+ Path: types.VulnerabilityIgnore(c.EnvID(), args[0]),
+ FailureMessage: "failed to remove ignore record",
+ SuccessMessage: fmt.Sprintf("Ignore record %s removed", args[0]),
+ })
+ },
+ }
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Skip the confirmation prompt")
+ cmdutil.SetResource(ignoreRef, command)
+ return command
}
func printSeveritySummary(s *vulnerability.SeveritySummary) {
@@ -440,5 +431,6 @@ var ignoreRef = cmdutil.ResourceRef[vulnerability.IgnoredVulnerability, vulnerab
Label: func(item vulnerability.IgnoredVulnerability) string {
return item.VulnerabilityID + " (" + item.ID + ")"
},
- Promote: func(item vulnerability.IgnoredVulnerability) *vulnerability.IgnoredVulnerability { return &item },
+ Promote: func(item vulnerability.IgnoredVulnerability) *vulnerability.IgnoredVulnerability { return &item },
+ IdentifierOf: func(item vulnerability.IgnoredVulnerability) string { return item.ID },
}
diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.go
index 54c49dce4..fe49b8c7f 100644
--- a/cli/pkg/webhooks/cmd.go
+++ b/cli/pkg/webhooks/cmd.go
@@ -4,258 +4,233 @@ package webhooks
import (
"cmp"
+ "encoding/json/jsontext"
"errors"
"fmt"
"net/http"
"strings"
"time"
- "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/webhook"
"github.com/spf13/cobra"
+ "go.getarcane.app/kit/pkg"
"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-var (
- forceFlag bool
- jsonOutput bool
- createName string
- createTarget string
- createAction string
- createTargetID string
- updateEnabled bool
-)
-
-// WebhooksCmd is the parent command for webhook operations.
-var WebhooksCmd = &cobra.Command{
- Use: "webhooks",
- Aliases: []string{"webhook", "wh"},
- Short: "Manage inbound webhooks",
+// Command is the parent command for webhook operations.
+func Command() *cobra.Command {
+ command := &cobra.Command{
+ Use: "webhooks",
+ Aliases: []string{"webhook", "wh"},
+ Short: "Manage inbound webhooks",
+ }
+ cmdutil.SetScope(cmdutil.ScopeResource, command)
+ command.AddCommand(newListCmd())
+ command.AddCommand(newCreateCmd())
+ command.AddCommand(newUpdateCmd())
+ command.AddCommand(newDeleteCmd())
+ command.AddCommand(newTriggerCmd())
+ return command
}
-var listCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List webhooks",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[[]webhook.Summary](cmd.Context(), types.Webhooks(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to list webhooks: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- headers := []string{"ID", "NAME", "ACTION", "TARGET", "TOKEN", "ENABLED", "LAST TRIGGERED"}
- rows := make([][]string, len(result.Data))
- for i, item := range result.Data {
- enabled := "No"
- if item.Enabled {
- enabled = "Yes"
- }
- lastTriggered := "-"
- if item.LastTriggeredAt != nil {
- lastTriggered = item.LastTriggeredAt.Format(time.RFC3339)
- }
- target := item.TargetType
- if name := cmp.Or(item.TargetName, item.TargetID); name != "" {
- target += "/" + name
- }
- rows[i] = []string{
- item.ID,
- item.Name,
- item.ActionType,
- target,
- item.TokenPrefix,
- enabled,
- lastTriggered,
+func newListCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List webhooks",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
}
- }
- if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "webhooks", Total: int64(len(result.Data)), Paginated: true}); tableErr != nil {
- return tableErr
- }
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[[]webhook.Summary]{
+ Method: http.MethodGet,
+ Path: types.Webhooks(c.EnvID()),
+ FailureMessage: "failed to list webhooks",
+ Render: func(data []webhook.Summary) error {
+ headers := []string{"ID", "NAME", "ACTION", "TARGET", "TOKEN", "ENABLED", "LAST TRIGGERED"}
+ rows := make([][]string, len(data))
+ for i, item := range data {
+ lastTriggered := "-"
+ if item.LastTriggeredAt != nil {
+ lastTriggered = item.LastTriggeredAt.Format(time.RFC3339)
+ }
+ target := item.TargetType
+ if name := cmp.Or(item.TargetName, item.TargetID); name != "" {
+ target += "/" + name
+ }
+ rows[i] = []string{
+ item.ID,
+ item.Name,
+ item.ActionType,
+ target,
+ item.TokenPrefix,
+ kit.Ternary(item.Enabled, "Yes", "No"),
+ lastTriggered,
+ }
+ }
+
+ return cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "webhooks", Total: int64(len(data)), Paginated: true})
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeRead, command)
+ return command
}
-var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a webhook",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := webhook.CreateInput{
- Name: createName,
- TargetType: createTarget,
- ActionType: createAction,
- TargetID: createTargetID,
- }
-
- result, err := c.PostJSON[webhook.Created](cmd.Context(), types.Webhooks(c.EnvID()), req)
- if err != nil {
- return fmt.Errorf("failed to create webhook: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Webhook %s created successfully", result.Data.Name)
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Target Type", result.Data.TargetType)
- output.KeyValue("Action", result.Data.ActionType)
- if result.Data.TargetID != "" {
- output.KeyValue("Target ID", result.Data.TargetID)
- }
- if result.Data.Token != "" {
- output.Warning("Store this token securely — it will not be shown again")
- output.KeyValue("Token", result.Data.Token)
- }
- return nil
- },
-}
-
-var updateCmd = &cobra.Command{
- Use: "update <webhook-id>",
- Short: "Update a webhook",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !cmd.Flags().Changed("enabled") {
- return errors.New("no fields to update: specify --enabled")
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- req := webhook.UpdateInput{Enabled: updateEnabled}
- if _, updateWebhookErr := c.DoJSON[base.ApiResponse[any]](cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req); updateWebhookErr != nil {
- return fmt.Errorf("failed to update webhook: %w", updateWebhookErr)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(map[string]bool{"enabled": updateEnabled})
- }
+func newCreateCmd() *cobra.Command {
+ var opts struct {
+ name string
+ target string
+ action string
+ targetID string
+ }
+ command := &cobra.Command{
+ Use: "create",
+ Short: "Create a webhook",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- state := "disabled"
- if updateEnabled {
- state = "enabled"
- }
- output.Success("Webhook %s %s", args[0], state)
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[webhook.Created]{
+ Method: http.MethodPost,
+ Path: types.Webhooks(c.EnvID()),
+ FailureMessage: "failed to create webhook",
+ Body: webhook.CreateInput{
+ Name: opts.name,
+ TargetType: opts.target,
+ ActionType: opts.action,
+ TargetID: opts.targetID,
+ },
+ Render: func(data webhook.Created) error {
+ output.Success("Webhook %s created successfully", data.Name)
+ output.KeyValue("ID", data.ID)
+ output.KeyValue("Target Type", data.TargetType)
+ output.KeyValue("Action", data.ActionType)
+ if data.TargetID != "" {
+ output.KeyValue("Target ID", data.TargetID)
+ }
+ if data.Token != "" {
+ output.Warning("Store this token securely — it will not be shown again")
+ output.KeyValue("Token", data.Token)
+ }
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeDestination, command)
+ command.Flags().StringVar(&opts.name, "name", "", "Webhook name")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.target, "target", "", "", "Target type", "container", "project", "updater", "gitops")
+ cmdutil.EnumVarP(command, command.Flags(), &opts.action, "action", "", "", "Action to run", "update", "start", "stop", "restart", "redeploy", "up", "down", "run", "sync")
+ command.Flags().StringVar(&opts.targetID, "target-id", "", "Container ID, project ID, or GitOps sync ID to target (not needed for updater webhooks)")
+ _ = command.MarkFlagRequired("name")
+ _ = command.MarkFlagRequired("target")
+ _ = command.MarkFlagRequired("action")
+ return command
}
-var deleteCmd = &cobra.Command{
- Use: "delete <webhook-id>",
- Aliases: []string{"rm", "remove"},
- Short: "Delete a webhook",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete webhook %s?", args[0]))
+func newUpdateCmd() *cobra.Command {
+ var opts struct {
+ enabled bool
+ }
+ command := &cobra.Command{
+ Use: "update <webhook-id>",
+ Short: "Update a webhook",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !cmd.Flags().Changed("enabled") {
+ return errors.New("no fields to update: specify --enabled")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- return nil
- }
- }
-
- c, err := cmdutil.ClientFromCommand(cmd)
- if err != nil {
- return err
- }
- if _, deleteWebhookErr := c.DeleteJSON[any](cmd.Context(), types.Webhook(c.EnvID(), args[0])); deleteWebhookErr != nil {
- return fmt.Errorf("failed to delete webhook: %w", deleteWebhookErr)
- }
-
- output.Success("Webhook %s deleted successfully", args[0])
- return nil
- },
+ return cmdutil.Run(cmd, c, cmdutil.Spec[jsontext.Value]{
+ Method: http.MethodPatch,
+ Path: types.Webhook(c.EnvID(), args[0]),
+ Body: webhook.UpdateInput{Enabled: opts.enabled},
+ FailureMessage: "failed to update webhook",
+ Render: func(jsontext.Value) error {
+ output.Success("Webhook %s %s", args[0], kit.Ternary(opts.enabled, "enabled", "disabled"))
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetResource(webhookRef, command)
+ command.Flags().BoolVar(&opts.enabled, "enabled", true, "Whether the webhook is active")
+ return command
}
-var triggerCmd = &cobra.Command{
- Use: "trigger <token>",
- Short: "Trigger a webhook by token",
- Long: "Trigger a webhook by its token. The token is the sole authentication mechanism; no login is required. The server accepts the trigger and runs the action in the background.",
- Args: cobra.ExactArgs(1),
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := cmdutil.UnauthClientFromCommand(cmd)
- if err != nil {
- return err
- }
-
- body, err := c.DoRaw(cmd.Context(), http.MethodPost, types.WebhookTrigger(args[0]), nil)
- if err != nil {
- return fmt.Errorf("failed to trigger webhook: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- output.Success("Webhook trigger accepted; the action is running in the background")
- return nil
- },
+func newDeleteCmd() *cobra.Command {
+ var opts struct {
+ force bool
+ }
+ command := &cobra.Command{
+ Use: "delete <webhook-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a webhook",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ return cmdutil.RunDelete(cmd, c, cmdutil.DeleteSpec{
+ Force: opts.force,
+ Prompt: fmt.Sprintf("Are you sure you want to delete webhook %s?", args[0]),
+ Path: types.Webhook(c.EnvID(), args[0]),
+ FailureMessage: "failed to delete webhook",
+ SuccessMessage: fmt.Sprintf("Webhook %s deleted successfully", args[0]),
+ })
+ },
+ }
+ cmdutil.SetResource(webhookRef, command)
+ command.Flags().BoolVarP(&opts.force, "force", "f", false, "Delete without confirmation")
+ return command
}
-func init() {
- cmdutil.SetResource(webhookRef, updateCmd, deleteCmd)
- cmdutil.SetScope(cmdutil.ScopeResource, WebhooksCmd)
- cmdutil.SetScope(cmdutil.ScopeRead, listCmd)
- cmdutil.SetScope(cmdutil.ScopeDestination, createCmd)
- cmdutil.SetScope(cmdutil.ScopeGlobal, triggerCmd)
- WebhooksCmd.AddCommand(listCmd)
- WebhooksCmd.AddCommand(createCmd)
- WebhooksCmd.AddCommand(updateCmd)
- WebhooksCmd.AddCommand(deleteCmd)
- WebhooksCmd.AddCommand(triggerCmd)
-
- // List command flags
- listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Create command flags
- createCmd.Flags().StringVar(&createName, "name", "", "Webhook name")
- createCmd.Flags().StringVar(&createTarget, "target", "", "Target type: container, project, updater, or gitops")
- createCmd.Flags().StringVar(&createAction, "action", "", "Action to run: update, start, stop, restart, redeploy, up, down, run, or sync")
- createCmd.Flags().StringVar(&createTargetID, "target-id", "", "Container ID, project ID, or GitOps sync ID to target (not needed for updater webhooks)")
- createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
- _ = createCmd.MarkFlagRequired("name")
- _ = createCmd.MarkFlagRequired("target")
- _ = createCmd.MarkFlagRequired("action")
-
- // Update command flags
- updateCmd.Flags().BoolVar(&updateEnabled, "enabled", true, "Whether the webhook is active")
- updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- // Delete command flags
- deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Delete without confirmation")
- deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+func newTriggerCmd() *cobra.Command {
+ command := &cobra.Command{
+ Use: "trigger <token>",
+ Short: "Trigger a webhook by token",
+ Long: "Trigger a webhook by its token. The token is the sole authentication mechanism; no login is required. The server accepts the trigger and runs the action in the background.",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.UnauthClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
- // Trigger command flags
- triggerCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ return cmdutil.Run(cmd, c, cmdutil.Spec[jsontext.Value]{
+ Method: http.MethodPost,
+ Path: types.WebhookTrigger(args[0]),
+ FailureMessage: "failed to trigger webhook",
+ Render: func(jsontext.Value) error {
+ output.Success("Webhook trigger accepted; the action is running in the background")
+ return nil
+ },
+ })
+ },
+ }
+ cmdutil.SetScope(cmdutil.ScopeGlobal, command)
+ return command
}
var webhookRef = cmdutil.ResourceRef[webhook.Summary, webhook.Summary]{
@@ -263,7 +238,8 @@ var webhookRef = cmdutil.ResourceRef[webhook.Summary, webhook.Summary]{
Singular: "webhook", Plural: "webhooks",
IDHint: "the identifier", ListCmd: "arcane-cli webhooks list",
GetPath: nil, ListPath: types.Webhooks,
- Matches: func(item webhook.Summary, lower, original string) bool { return strings.EqualFold(item.ID, original) },
- Label: func(item webhook.Summary) string { return item.Name + " (" + item.ID + ")" },
- Promote: func(item webhook.Summary) *webhook.Summary { return &item },
+ Matches: func(item webhook.Summary, lower, original string) bool { return strings.EqualFold(item.ID, original) },
+ Label: func(item webhook.Summary) string { return item.Name + " (" + item.ID + ")" },
+ Promote: func(item webhook.Summary) *webhook.Summary { return &item },
+ IdentifierOf: func(item webhook.Summary) string { return item.ID },
}
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index d1ff89d6e..472aa496f 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -56,5 +56,5 @@ type UpdateApiKey struct {
Name *string `json:"name,omitzero" maxLength:"255" doc:"New name for the API key" unorm:"nfc" trim:"true"`
Description *string `json:"description,omitzero" maxLength:"1000" doc:"New description for the API key" unorm:"nfc" trim:"true"`
ExpiresAt *time.Time `json:"expiresAt,omitzero" doc:"New expiration date for the API key"`
- Permissions []PermissionGrant `json:"permissions,omitempty" doc:"Replace the key's permission grants. Omit to leave unchanged. Cannot exceed the updater's own permissions."`
+ Permissions []PermissionGrant `json:"permissions,omitzero" doc:"Replace the key's permission grants. Omit to leave unchanged. Cannot exceed the updater's own permissions."`
}
diff --git a/types/backup/s3.go b/types/backup/s3.go
index 143925335..334661d79 100644
--- a/types/backup/s3.go
+++ b/types/backup/s3.go
@@ -2,6 +2,11 @@ package backup
import "time"
+// S3DestinationUsage reports whether a destination is referenced by backups.
+type S3DestinationUsage struct {
+ InUse bool `json:"inUse"`
+}
+
type S3Destination struct {
ID string `json:"id"`
Name string `json:"name"`
diff --git a/types/base/response.go b/types/base/response.go
index 5fcbff543..780e88135 100644
--- a/types/base/response.go
+++ b/types/base/response.go
@@ -33,6 +33,14 @@ type Paginated[T any] struct {
Pagination PaginationResponse `json:"pagination" doc:"Pagination metadata"`
}
+// PaginatedWithWarnings is a generic wrapper for paginated responses with warnings.
+type PaginatedWithWarnings[T any] struct {
+ Success bool `json:"success"`
+ Data []T `json:"data"`
+ Pagination PaginationResponse `json:"pagination"`
+ Warnings []string `json:"warnings,omitempty"`
+}
+
// PaginatedWithCounts is a generic wrapper for paginated responses with aggregate counts.
type PaginatedWithCounts[T, C any] struct {
Success bool `json:"success" doc:"Whether the request was successful"`
diff --git a/types/container/container.go b/types/container/container.go
index 8f767c07c..83b035f2a 100644
--- a/types/container/container.go
+++ b/types/container/container.go
@@ -13,6 +13,11 @@ import (
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
)
+// SetAutoUpdateRequest configures container auto-update.
+type SetAutoUpdateRequest struct {
+ Enabled bool `json:"enabled" doc:"Whether auto-update is enabled for this container"`
+}
+
// RestartPolicyCreate represents restart policy options for container creation.
type RestartPolicyCreate struct {
// Name of the restart policy.
diff --git a/types/event/event.go b/types/event/event.go
index 95dee70b5..79cbdb09f 100644
--- a/types/event/event.go
+++ b/types/event/event.go
@@ -2,6 +2,15 @@ package event
import "time"
+// SeverityCounts holds global event counts per severity.
+type SeverityCounts struct {
+ Total int64 `json:"total"`
+ Info int64 `json:"info"`
+ Success int64 `json:"success"`
+ Warning int64 `json:"warning"`
+ Error int64 `json:"error"`
+}
+
// Event represents an event in API responses.
type Event struct {
// ID of the event.
diff --git a/types/project/project.go b/types/project/project.go
index fec7c4ae3..29831b178 100644
--- a/types/project/project.go
+++ b/types/project/project.go
@@ -144,6 +144,19 @@ type UpdateProject struct {
OverrideContent *string `json:"overrideContent,omitzero"`
}
+// BuildRequest configures a project's image build.
+type BuildRequest struct {
+ Services []string `json:"services,omitempty" doc:"Service names to build"`
+ Provider string `json:"provider,omitempty" doc:"Build provider override"`
+ Push *bool `json:"push,omitempty" doc:"Push images"`
+ Load *bool `json:"load,omitempty" doc:"Load images into Docker"`
+}
+
+// UpdateServicesRequest selects project services to update.
+type UpdateServicesRequest struct {
+ Services []string `json:"services,omitempty" doc:"Service names to update; empty updates all services"`
+}
+
// DeployOptions configures project deploy behavior.
type DeployOptions struct {
// PullPolicy overrides the image pull policy used during deploy.
diff --git a/types/system/upgrade.go b/types/system/upgrade.go
new file mode 100644
index 000000000..c9246fec0
--- /dev/null
+++ b/types/system/upgrade.go
@@ -0,0 +1,39 @@
+package system
+
+import "time"
+
+// UpgradeCheckResult reports whether the system can be upgraded.
+type UpgradeCheckResult struct {
+ CanUpgrade bool `json:"canUpgrade"`
+ Error bool `json:"error"`
+ Message string `json:"message"`
+}
+
+// EnvironmentUpdateResult reports an environment's outcome within an update job.
+type EnvironmentUpdateResult struct {
+ EnvironmentID string `json:"environmentId"`
+ EnvironmentName string `json:"environmentName"`
+ Status string `json:"status"`
+ FromVersion string `json:"fromVersion,omitempty"`
+ FromDigest string `json:"fromDigest,omitempty"`
+ ToVersion string `json:"toVersion,omitempty"`
+ Stage string `json:"stage,omitempty"`
+ StageStartedAt *time.Time `json:"stageStartedAt,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// EnvironmentUpdateJob reports a persisted fleet-wide update job.
+type EnvironmentUpdateJob struct {
+ ID string `json:"id"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+ Status string `json:"status"`
+ UserID string `json:"userId"`
+ Username string `json:"username"`
+ ManagerVersionAtStart string `json:"managerVersionAtStart"`
+ ManagerDigestAtStart string `json:"managerDigestAtStart"`
+ ManagerTargetVersion string `json:"managerTargetVersion"`
+ Results []EnvironmentUpdateResult `json:"results,omitempty"`
+ Error *string `json:"error,omitempty"`
+ CompletedAt *time.Time `json:"completedAt,omitempty"`
+}
diff --git a/types/updater/updater.go b/types/updater/updater.go
index f0c438485..44f7bb2b9 100644
--- a/types/updater/updater.go
+++ b/types/updater/updater.go
@@ -1,5 +1,26 @@
package updater
+import "time"
+
+// AutoUpdateRecord reports a persisted resource auto-update operation.
+type AutoUpdateRecord struct {
+ ID string `json:"id"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+ ResourceID string `json:"resourceId"`
+ ResourceType string `json:"resourceType"`
+ ResourceName string `json:"resourceName"`
+ Status string `json:"status"`
+ StartTime time.Time `json:"startTime"`
+ EndTime *time.Time `json:"endTime,omitempty"`
+ UpdateAvailable bool `json:"updateAvailable"`
+ UpdateApplied bool `json:"updateApplied"`
+ OldImageVersions map[string]any `json:"oldImageVersions,omitempty"`
+ NewImageVersions map[string]any `json:"newImageVersions,omitempty"`
+ Error *string `json:"error,omitempty"`
+ Details map[string]any `json:"details,omitempty"`
+}
+
const (
// StatusChecked indicates a resource was checked.
StatusChecked = "checked"
diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.go
index 4f5fe1b4a..3a3b3640c 100644
--- a/types/vulnerability/vulnerability.go
+++ b/types/vulnerability/vulnerability.go
@@ -4,6 +4,12 @@ import (
"time"
)
+// ScannerStatus reports vulnerability scanner availability and version.
+type ScannerStatus struct {
+ Available bool `json:"available"`
+ Version string `json:"version,omitempty"`
+}
+
// Severity represents the severity level of a vulnerability
type Severity string