Skip to content

Modern Docker Management, Designed for Everyone

feat(cli): add all environment preview to cli

Kyle Mendellc8ec32417078
diff --git a/cli/internal/client/client.go b/cli/internal/client/client.go
index 9201f8883..ce246000f 100644
--- a/cli/internal/client/client.go
+++ b/cli/internal/client/client.go
@@ -1,25 +1,4 @@
-// Package client provides an HTTP client for communicating with the Arcane API.
-//
-// The client handles authentication, request construction, and response parsing
-// for all API calls. It supports JSON request/response bodies as well as raw
-// multipart uploads.
-//
-// # Creating a Client
-//
-// The recommended way to create a client is from the CLI configuration:
-//
-// c, err := client.NewFromConfig()
-// if err != nil {
-// return err
-// }
-//
-// # Making Requests
-//
-// The client provides convenience methods for common HTTP methods:
-//
-// resp, err := c.Get(ctx, "/api/images")
-// resp, err := c.Post(ctx, "/api/images/pull", body)
-// resp, err := c.Delete(ctx, "/api/images/abc123")
+// Package client provides authenticated HTTP transport for the Arcane API.
package client
import (
@@ -36,6 +15,7 @@ import (
"net/http"
"net/url"
"os"
+ "slices"
"strings"
"time"
@@ -63,10 +43,7 @@ var retryableStatusCodes = map[int]struct{}{
http.StatusGatewayTimeout: {},
}
-// Client is an HTTP client for the Arcane API.
-// It handles authentication via API tokens and provides methods for making
-// HTTP requests to various API endpoints. The client automatically includes
-// authentication headers and handles JSON serialization.
+// Client provides authenticated requests, token refresh, and response decoding for the Arcane API.
type Client struct {
baseURL string
baseURLParsed *url.URL
@@ -80,11 +57,14 @@ type Client struct {
maxBackoff time.Duration
}
-// New creates a new API client from the provided configuration.
-// It validates the configuration and returns an error if required fields
-// (ServerURL, APIKey) are missing. The client is initialized with a default
-// 30-second timeout and the configured environment ID.
+// New validates configuration and creates an authenticated client with the configured environment and a ten-minute timeout.
func New(cfg *types.Config) (*Client, error) {
+ cfg = cfg.Clone()
+ if token := strings.TrimSpace(os.Getenv("ARCANE_TOKEN")); token != "" {
+ cfg.JWTToken = token
+ cfg.APIKey = ""
+ cfg.RefreshToken = ""
+ }
if err := cfg.Validate(); err != nil {
return nil, err
}
@@ -94,6 +74,10 @@ func New(cfg *types.Config) (*Client, error) {
}
envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)
+ httpClient := &http.Client{Timeout: defaultTimeout}
+ if transport, ok := http.DefaultTransport.(*http.Transport); ok {
+ httpClient.Transport = transport.Clone()
+ }
return &Client{
baseURL: cfg.ServerURL,
@@ -102,7 +86,7 @@ func New(cfg *types.Config) (*Client, error) {
jwtToken: cfg.JWTToken,
refreshToken: cfg.RefreshToken,
envID: envID,
- httpClient: newHTTPClientInternal(),
+ httpClient: httpClient,
maxAttempts: 3,
baseBackoff: 150 * time.Millisecond,
maxBackoff: 2 * time.Second,
@@ -112,6 +96,10 @@ func New(cfg *types.Config) (*Client, error) {
// NewUnauthenticated creates a client that can call unauthenticated endpoints
// (e.g. /api/auth/login). It only validates that server_url is configured.
func NewUnauthenticated(cfg *types.Config) (*Client, error) {
+ cfg = cfg.Clone()
+ if strings.TrimSpace(os.Getenv("ARCANE_TOKEN")) != "" {
+ cfg.RefreshToken = ""
+ }
if err := cfg.ValidateServerURL(); err != nil {
return nil, err
}
@@ -121,36 +109,24 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {
}
envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)
+ httpClient := &http.Client{Timeout: defaultTimeout}
+ if transport, ok := http.DefaultTransport.(*http.Transport); ok {
+ httpClient.Transport = transport.Clone()
+ }
return &Client{
baseURL: cfg.ServerURL,
baseURLParsed: parsedURL,
envID: envID,
refreshToken: cfg.RefreshToken,
- httpClient: newHTTPClientInternal(),
+ httpClient: httpClient,
maxAttempts: 3,
baseBackoff: 150 * time.Millisecond,
maxBackoff: 2 * time.Second,
}, nil
}
-func newHTTPClientInternal() *http.Client {
- transport, ok := http.DefaultTransport.(*http.Transport)
- if ok {
- return &http.Client{
- Timeout: defaultTimeout,
- Transport: transport.Clone(),
- }
- }
-
- return &http.Client{
- Timeout: defaultTimeout,
- }
-}
-
-// NewFromConfig loads the CLI configuration from disk and creates a new client.
-// This is the recommended way to create a client in CLI commands.
-// It returns an error if the configuration cannot be loaded or is invalid.
+// NewFromConfig loads persisted configuration and applies invocation overrides before creating a client.
func NewFromConfig() (*Client, error) {
cfg, err := config.Load()
if err != nil {
@@ -160,11 +136,6 @@ func NewFromConfig() (*Client, error) {
if strings.TrimSpace(state.EnvOverride) != "" {
cfg.DefaultEnvironment = strings.TrimSpace(state.EnvOverride)
}
- if token := strings.TrimSpace(os.Getenv("ARCANE_TOKEN")); token != "" {
- cfg.JWTToken = token
- cfg.APIKey = ""
- cfg.RefreshToken = ""
- }
c, err := New(cfg)
if err != nil {
return nil, err
@@ -185,11 +156,6 @@ func NewFromConfigUnauthenticated() (*Client, error) {
if strings.TrimSpace(state.EnvOverride) != "" {
cfg.DefaultEnvironment = strings.TrimSpace(state.EnvOverride)
}
- if token := strings.TrimSpace(os.Getenv("ARCANE_TOKEN")); token != "" {
- cfg.JWTToken = token
- cfg.APIKey = ""
- cfg.RefreshToken = ""
- }
c, err := NewUnauthenticated(cfg)
if err != nil {
return nil, err
@@ -200,9 +166,7 @@ func NewFromConfigUnauthenticated() (*Client, error) {
return c, nil
}
-// SetEnvironment changes the environment ID for subsequent requests.
-// This allows switching between different Arcane environments without
-// creating a new client instance.
+// SetEnvironment changes the environment ID for subsequent requests on this client.
func (c *Client) SetEnvironment(envID string) {
c.envID = envID
}
@@ -228,20 +192,14 @@ func (c *Client) EnvID() string {
return c.envID
}
-// APIResponse wraps the standard Arcane API response format.
-// All API responses include a Success field indicating whether the request
-// succeeded, a Data field containing the response payload, and an optional
-// Error field with error details on failure.
+// 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 makes an HTTP request to the API with JSON body serialization.
-// It constructs the full URL from the base URL and path, serializes the body
-// as JSON (if provided), and includes authentication headers. The caller is
-// responsible for closing the response body.
+// 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)
defer loading.Stop()
@@ -288,13 +246,10 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hea
}
}
- return c.doRequestInternal(ctx, method, fullURL, bodyBytes, true, headers...)
+ return c.doRequest(ctx, method, fullURL, bodyBytes, true, headers...)
}
-// RequestRaw makes an HTTP request with a raw body and custom headers.
-// Unlike Request, this method does not serialize the body as JSON, making it
-// suitable for multipart form uploads and other non-JSON content types.
-// Custom headers can be provided to set Content-Type and other headers.
+// RequestRaw sends a streaming body with custom headers, without JSON encoding or automatic replay.
func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Reader, headers map[string]string) (*http.Response, error) {
loading := output.StartLoading(ctx)
defer loading.Stop()
@@ -347,7 +302,7 @@ func (c *Client) resolveURL(path string) (string, error) {
return c.baseURLParsed.ResolveReference(rel).String(), nil
}
-func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string, bodyBytes []byte, allowRefresh bool, headers ...http.Header) (*http.Response, error) {
+func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyBytes []byte, allowRefresh bool, headers ...http.Header) (*http.Response, error) {
attempts := max(c.maxAttempts, 1)
for attempt := 1; attempt <= attempts; attempt++ {
@@ -411,7 +366,7 @@ func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string,
}
func (c *Client) shouldRetry(method string, status int, err error) bool {
- if !isIdempotentMethod(method) {
+ if !slices.Contains([]string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete}, method) {
return false
}
if err != nil {
@@ -453,15 +408,6 @@ func (c *Client) waitRetry(ctx context.Context, attempt int) error {
}
}
-func isIdempotentMethod(method string) bool {
- switch method {
- case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
- return true
- default:
- return false
- }
-}
-
func (c *Client) applyAuth(req *http.Request) {
// Prefer JWT bearer token if present.
if c.jwtToken != "" {
@@ -569,16 +515,12 @@ func (c *Client) Delete(ctx context.Context, path string) (*http.Response, error
return c.Request(ctx, http.MethodDelete, path, nil)
}
-// DeleteWithBody makes a DELETE request to the specified path with a JSON body.
-// A handful of Arcane delete endpoints — project destroy, for one — take options
-// in the request body rather than as query parameters.
+// DeleteWithBody sends a DELETE request with a JSON options body.
func (c *Client) DeleteWithBody(ctx context.Context, path string, body any) (*http.Response, error) {
return c.Request(ctx, http.MethodDelete, path, body)
}
-// DoJSON performs a request and decodes the response JSON, enforcing a
-// successful HTTP status. Unlike GetJSON/PostJSON it does not require the
-// standard API envelope or its Success flag.
+// DoJSON enforces HTTP success and decodes a response without requiring the standard API envelope.
func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body any, headers ...http.Header) (T, error) {
loading := output.StartLoading(ctx)
defer loading.Stop()
@@ -610,7 +552,7 @@ func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[
return nil, err
}
defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrictInternal[T](resp)
+ return decodeResponseStrict[T](resp)
}
// PostJSON performs a POST with a JSON body and decodes the standard API
@@ -623,7 +565,7 @@ func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*A
return nil, err
}
defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrictInternal[T](resp)
+ return decodeResponseStrict[T](resp)
}
// DoRaw performs a request and returns the response payload when status is 2xx.
@@ -658,7 +600,7 @@ func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*AP
return nil, err
}
defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrictInternal[T](resp)
+ return decodeResponseStrict[T](resp)
}
// DeleteJSON performs a DELETE and decodes the standard API envelope,
@@ -671,14 +613,11 @@ func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*APIRespon
return nil, err
}
defer func() { _ = resp.Body.Close() }()
- return decodeResponseStrictInternal[T](resp)
+ return decodeResponseStrict[T](resp)
}
-// decodeResponseStrictInternal decodes an API response into the given type and
-// enforces HTTP and API success. If the response indicates failure
-// (Success=false) or carries a non-2xx status code, an error is returned with
-// the message from the API. The caller owns the response body.
-func decodeResponseStrictInternal[T any](resp *http.Response) (*APIResponse[T], error) {
+// 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) {
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)))
@@ -704,9 +643,7 @@ func decodeResponseStrictInternal[T any](resp *http.Response) (*APIResponse[T],
return &result, nil
}
-// TestConnection tests the API connection by making a request to the version endpoint.
-// It returns nil if the connection is successful, or an error describing the failure.
-// This is useful for verifying configuration before making other API calls.
+// TestConnection checks the API version endpoint and returns transport or status failures.
func (c *Client) TestConnection(ctx context.Context) error {
resp, err := c.Get(ctx, "/api/version")
if err != nil {
diff --git a/cli/internal/client/client_test.go b/cli/internal/client/client_test.go
index 7494c825b..4ec211666 100644
--- a/cli/internal/client/client_test.go
+++ b/cli/internal/client/client_test.go
@@ -4,7 +4,9 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "sync/atomic"
"testing"
+ "time"
"github.com/stretchr/testify/require"
@@ -45,8 +47,6 @@ func TestClient_UsesAPIKeyHeader(t *testing.T) {
}
func TestClient_UsesBearerTokenHeader(t *testing.T) {
- t.Parallel()
-
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Bearer header.payload.sig" {
w.WriteHeader(http.StatusUnauthorized)
@@ -60,21 +60,33 @@ func TestClient_UsesBearerTokenHeader(t *testing.T) {
}))
defer srv.Close()
- cfg := &types.Config{ServerURL: srv.URL, JWTToken: "header.payload.sig"}
- c, err := New(cfg)
+ for _, source := range []string{"config", "environment"} {
+ t.Run(source, func(t *testing.T) {
+ cfg := &types.Config{ServerURL: srv.URL, JWTToken: "header.payload.sig"}
+ if source == "environment" {
+ t.Setenv("ARCANE_TOKEN", "header.payload.sig")
+ cfg.APIKey, cfg.JWTToken, cfg.RefreshToken = "arc_test_key", "", "saved-refresh"
+ }
+ c, err := New(cfg)
- require.NoError(t, err,
- "New() error: %v", err)
+ require.NoError(t, err,
+ "New() error: %v", err)
- resp, err := c.Get(t.Context(), "/api/version")
+ resp, err := c.Get(t.Context(), "/api/version")
- require.NoError(t, err,
- "Get() error: %v", err)
+ require.NoError(t, err,
+ "Get() error: %v", err)
- _ = resp.Body.Close()
+ _ = resp.Body.Close()
- require.Equal(t, http.StatusOK, resp.StatusCode,
- "unexpected status: %d", resp.StatusCode)
+ require.Equal(t, http.StatusOK, resp.StatusCode,
+ "unexpected status: %d", resp.StatusCode)
+ if source == "environment" {
+ require.Equal(t, "saved-refresh", cfg.RefreshToken)
+ require.Empty(t, c.refreshToken)
+ }
+ })
+ }
}
func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {
@@ -149,3 +161,133 @@ func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {
require.Equal(t, http.StatusOK, resp.StatusCode,
"unexpected status: %d", resp.StatusCode)
}
+
+func TestClient_RetriesIdempotentRequests(t *testing.T) {
+ t.Parallel()
+
+ var attempts atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ current := attempts.Add(1)
+ if current == 1 {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = w.Write([]byte(`{"error":"temporary"}`))
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"success":true,"data":{"value":"ok"}}`))
+ }))
+ defer srv.Close()
+
+ cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
+ c, err := New(cfg)
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
+ c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
+
+ resp, err := c.Get(t.Context(), "/api/version")
+
+ require.NoError(t, err,
+ "Get() error: %v", err)
+
+ _ = resp.Body.Close()
+ {
+ got := attempts.Load()
+ require.Equal(t, int32(2), got,
+ "expected 2 attempts, got %d", got)
+ }
+}
+
+func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
+ t.Parallel()
+
+ var attempts atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ attempts.Add(1)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = w.Write([]byte(`{"error":"temporary"}`))
+ }))
+ defer srv.Close()
+
+ cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
+ c, err := New(cfg)
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
+ c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
+
+ resp, err := c.Post(t.Context(), "/api/version", map[string]any{"a": 1})
+
+ require.NoError(t, err,
+ "Post() returned transport error: %v", err)
+
+ _ = resp.Body.Close()
+ {
+ got := attempts.Load()
+ require.Equal(t, int32(1), got,
+ "expected 1 attempt, got %d", got)
+ }
+}
+
+func TestClient_DoJSON_StrictStatus(t *testing.T) {
+ t.Parallel()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"success":false,"error":"unauthorized"}`))
+ }))
+ defer srv.Close()
+
+ cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
+ c, err := New(cfg)
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
+ {
+ _, requestErr := c.DoJSON[map[string]any](t.Context(), http.MethodGet, "/api/version", nil)
+ require.Error(t, requestErr,
+ "expected strict status error")
+ }
+}
+
+func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {
+ t.Parallel()
+
+ rec := httptest.NewRecorder()
+ rec.Code = http.StatusOK
+ rec.Body.WriteString(`{"success":false,"error":"not ok"}`)
+
+ resp := rec.Result()
+ {
+ _, err := decodeResponseStrict[map[string]any](resp)
+ require.Error(t, err,
+ "expected envelope failure")
+ }
+}
+
+func TestClient_DoRaw_Success(t *testing.T) {
+ t.Parallel()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
+ }))
+ defer srv.Close()
+
+ cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
+ c, err := New(cfg)
+
+ require.NoError(t, err,
+ "New() error: %v", err)
+
+ b, err := c.DoRaw(t.Context(), http.MethodGet, "/api/version", nil)
+
+ require.NoError(t, err,
+ "DoRaw() error: %v", err)
+
+ require.NotEmpty(t, b,
+ "expected response payload")
+}
diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.go
deleted file mode 100644
index 85f2a1f19..000000000
--- a/cli/internal/client/retry_test.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package client
-
-import (
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/stretchr/testify/require"
-
- "github.com/getarcaneapp/arcane/cli/v2/internal/types"
-)
-
-func TestClient_RetriesIdempotentRequests(t *testing.T) {
- t.Parallel()
-
- var attempts atomic.Int32
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- current := attempts.Add(1)
- if current == 1 {
- w.WriteHeader(http.StatusServiceUnavailable)
- _, _ = w.Write([]byte(`{"error":"temporary"}`))
- return
- }
- w.WriteHeader(http.StatusOK)
- _, _ = w.Write([]byte(`{"success":true,"data":{"value":"ok"}}`))
- }))
- defer srv.Close()
-
- cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
- c, err := New(cfg)
-
- require.NoError(t, err,
- "New() error: %v", err)
-
- c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
-
- resp, err := c.Get(t.Context(), "/api/version")
-
- require.NoError(t, err,
- "Get() error: %v", err)
-
- _ = resp.Body.Close()
- {
- got := attempts.Load()
- require.Equal(t, int32(2), got,
- "expected 2 attempts, got %d", got)
- }
-}
-
-func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
- t.Parallel()
-
- var attempts atomic.Int32
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- attempts.Add(1)
- w.WriteHeader(http.StatusServiceUnavailable)
- _, _ = w.Write([]byte(`{"error":"temporary"}`))
- }))
- defer srv.Close()
-
- cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
- c, err := New(cfg)
-
- require.NoError(t, err,
- "New() error: %v", err)
-
- c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
-
- resp, err := c.Post(t.Context(), "/api/version", map[string]any{"a": 1})
-
- require.NoError(t, err,
- "Post() returned transport error: %v", err)
-
- _ = resp.Body.Close()
- {
- got := attempts.Load()
- require.Equal(t, int32(1), got,
- "expected 1 attempt, got %d", got)
- }
-}
-
-func TestClient_DoJSON_StrictStatus(t *testing.T) {
- t.Parallel()
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusUnauthorized)
- _, _ = w.Write([]byte(`{"success":false,"error":"unauthorized"}`))
- }))
- defer srv.Close()
-
- cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
- c, err := New(cfg)
-
- require.NoError(t, err,
- "New() error: %v", err)
-
- {
- _, requestErr := c.DoJSON[map[string]any](t.Context(), http.MethodGet, "/api/version", nil)
- require.Error(t, requestErr,
- "expected strict status error")
- }
-}
-
-func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {
- t.Parallel()
-
- rec := httptest.NewRecorder()
- rec.Code = http.StatusOK
- rec.Body.WriteString(`{"success":false,"error":"not ok"}`)
-
- resp := rec.Result()
- {
- _, err := decodeResponseStrictInternal[map[string]any](resp)
- require.Error(t, err,
- "expected envelope failure")
- }
-}
-
-func TestClient_DoRaw_Success(t *testing.T) {
- t.Parallel()
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
- _ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
- }))
- defer srv.Close()
-
- cfg := &types.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
- c, err := New(cfg)
-
- require.NoError(t, err,
- "New() error: %v", err)
-
- b, err := c.DoRaw(t.Context(), http.MethodGet, "/api/version", nil)
-
- require.NoError(t, err,
- "DoRaw() error: %v", err)
-
- require.NotEmpty(t, b,
- "expected response payload")
-}
diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.go
index e6d679f1a..da65154b7 100644
--- a/cli/internal/cmdutil/context.go
+++ b/cli/internal/cmdutil/context.go
@@ -7,7 +7,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
- runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
)
// ClientFromCommand returns a configured authenticated client for the command.
@@ -15,7 +15,7 @@ func ClientFromCommand(cmd *cobra.Command) (*client.Client, error) {
if cmd == nil {
return nil, errors.New("nil command")
}
- if app, ok := runtimectx.From(cmd.Context()); ok {
+ if app, ok := runtime.From(cmd.Context()); ok {
return app.Client()
}
return client.NewFromConfig()
@@ -26,7 +26,7 @@ func UnauthClientFromCommand(cmd *cobra.Command) (*client.Client, error) {
if cmd == nil {
return nil, errors.New("nil command")
}
- if app, ok := runtimectx.From(cmd.Context()); ok {
+ if app, ok := runtime.From(cmd.Context()); ok {
return app.UnauthClient()
}
return client.NewFromConfigUnauthenticated()
@@ -41,7 +41,7 @@ func JSONOutputEnabled(cmd *cobra.Command) bool {
val, err := cmd.Flags().GetBool("json")
return err == nil && val
}
- if app, ok := runtimectx.From(cmd.Context()); ok {
+ if app, ok := runtime.From(cmd.Context()); ok {
return app.IsJSON()
}
return false
@@ -52,15 +52,16 @@ func AssumeYes(cmd *cobra.Command) bool {
if cmd == nil {
return false
}
- if app, ok := runtimectx.From(cmd.Context()); ok {
- return app.AssumeYes()
+ if app, ok := runtime.From(cmd.Context()); ok {
+ return app.AssumeYes
}
return false
}
// Confirm prompts the user unless --yes is enabled.
func Confirm(cmd *cobra.Command, prompt string) (bool, error) {
- if AssumeYes(cmd) {
+ app, _ := runtime.From(cmd.Context())
+ if AssumeYes(cmd) || app != nil && app.FleetConfirmed {
return true, nil
}
diff --git a/cli/internal/cmdutil/resolve.go b/cli/internal/cmdutil/resolve.go
index 49893e28b..be9215bc1 100644
--- a/cli/internal/cmdutil/resolve.go
+++ b/cli/internal/cmdutil/resolve.go
@@ -1,28 +1,33 @@
package cmdutil
import (
+ "cmp"
"context"
"encoding/json/v2"
+ "errors"
"fmt"
"io"
"net/http"
"net/url"
+ "slices"
"strings"
- "github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/environment"
"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"
)
// MaxPromptOptions caps how many search matches the resolver offers
// interactively before asking the user to refine the query instead.
const MaxPromptOptions = 20
-// ResourceRef describes how one resource kind is resolved from a name, ID, or
-// prefix. D is the detail type returned by the GET-by-identifier endpoint and
-// S the summary type returned by the list endpoint.
+// ResourceRef resolves a resource from a name, ID, or prefix.
+// D is the detail shape and S is the list summary.
type ResourceRef[D any, S any] struct {
+ EnvironmentScoped bool
// Singular and Plural name the resource in prompts and error messages
// ("container", "containers").
Singular string
@@ -52,86 +57,163 @@ type ResourceRef[D any, S any] struct {
// Promote converts a selected summary into the detail shape.
Promote func(S) *D
- // IDOf enables the last-resort ID-prefix scan over the full list for
- // resources addressed by opaque IDs (containers, images). Leave nil to
- // skip that fallback.
+ // IDOf enables an ID-prefix scan over the full list. Leave nil for resources without opaque IDs.
IDOf func(S) string
+ // IdentifierOf supplies the canonical identifier for commands accepting raw IDs.
+ IdentifierOf func(D) string
- // Exact optionally reports an exact identifier match. When set and
- // exactly one search match is exact, it wins without prompting even if
- // broader substring matches exist.
+ // Exact identifies exact matches so a unique exact search result wins over substring matches.
Exact func(item S, identifierLower, original string) bool
}
-// Resolve finds one resource by exact identifier or search. The bool result
-// reports whether the returned details are complete (fetched from the
-// GET-by-identifier endpoint) rather than promoted from a list row.
+type resourceCandidate[D any] struct {
+ details *D
+ complete bool
+ exact bool
+ envID string
+ label string
+}
+
+// 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) {
- trimmed := strings.TrimSpace(identifier)
- if trimmed == "" {
+ identifier = strings.TrimSpace(identifier)
+ if identifier == "" {
return nil, false, fmt.Errorf("%s identifier is required", ref.Singular)
}
+ app, _ := runtime.From(ctx)
+ preview := app.PreviewEnabled() && ref.EnvironmentScoped
+ environments := []environment.Environment{{ID: c.EnvID()}}
+ if preview {
+ var discoveryErr error
+ environments, discoveryErr = app.Environments(ctx)
+ if discoveryErr != nil {
+ return nil, false, discoveryErr
+ }
+ allowPrompt = !app.IsJSON() && prompt.IsInteractive()
+ }
+ originalEnv := c.EnvID()
+ defer func() {
+ if preview && app.PreviewEnabled() {
+ c.SetEnvironment(originalEnv)
+ }
+ }()
+ var candidates []resourceCandidate[D]
+ var failures []error
+ for _, env := range environments {
+ if cancelErr := ctx.Err(); cancelErr != nil {
+ return nil, false, cancelErr
+ }
+ c.SetEnvironment(env.ID)
+ matches, lookupErr := ref.candidates(ctx, c, identifier, allowPrompt, preview)
+ switch {
+ case lookupErr != nil && !preview:
+ return nil, false, lookupErr
+ case lookupErr != nil:
+ failures = append(failures, fmt.Errorf("%s (%s): %w", cmp.Or(env.Name, env.ID), env.ID, lookupErr))
+ }
+ for i := range matches {
+ matches[i].envID = env.ID
+ if preview {
+ matches[i].label = fmt.Sprintf("%s — %s (%s)", matches[i].label, cmp.Or(env.Name, env.ID), env.ID)
+ }
+ }
+ candidates = append(candidates, matches...)
+ }
+ if slices.ContainsFunc(candidates, func(item resourceCandidate[D]) bool { return item.exact }) {
+ candidates = slices.DeleteFunc(candidates, func(item resourceCandidate[D]) bool { return !item.exact })
+ }
+ for _, failure := range failures {
+ output.Warning("%v", failure)
+ }
+ if len(candidates) == 0 {
+ return nil, false, errors.Join(append(failures, fmt.Errorf("%s %q not found; use %s or run `%s`", ref.Singular, identifier, ref.IDHint, ref.ListCmd))...)
+ }
+ choice := 0
+ prompted := false
+ if len(candidates) > 1 || len(failures) > 0 {
+ if !allowPrompt {
+ if preview {
+ return nil, false, fmt.Errorf("%s %q requires an environment selection; pass --env <id> or run `%s`", ref.Singular, identifier, ref.ListCmd)
+ }
+ return nil, false, fmt.Errorf("multiple %s match %q; use %s or run `%s`", ref.Plural, identifier, ref.IDHint, ref.ListCmd)
+ }
+ if len(candidates) > MaxPromptOptions {
+ return nil, false, fmt.Errorf("multiple %s match %q (%d results); refine your query or use %s", ref.Plural, identifier, len(candidates), ref.IDHint)
+ }
+ options := make([]string, len(candidates))
+ for i, item := range candidates {
+ options[i] = item.label
+ }
+ var selectErr error
+ choice, selectErr = prompt.Select(ref.Singular, options)
+ prompted = true
+ if selectErr != nil {
+ return nil, false, selectErr
+ }
+ }
+ selected := candidates[choice]
+ if preview {
+ app.SelectEnvironment(selected.envID)
+ c.SetEnvironment(selected.envID)
+ }
+ if preview && !prompted {
+ _, _ = fmt.Fprintf(output.Stderr(), "Selected %s: %s\n", ref.Singular, selected.label)
+ }
+ return selected.details, selected.complete, nil
+}
- details, found, err := ref.fetchByIdentifierInternal(ctx, c, trimmed)
+func (ref ResourceRef[D, S]) candidates(ctx context.Context, c *client.Client, identifier string, allowPrompt, collect bool) ([]resourceCandidate[D], error) {
+ details, found, err := ref.fetchByIdentifier(ctx, c, identifier)
if err != nil {
- return nil, false, err
+ return nil, err
}
if found {
- return details, true, nil
+ return []resourceCandidate[D]{{details: details, complete: true, exact: true, label: identifier}}, nil
}
-
var matches []S
if ref.SearchCandidates != nil {
- matches, err = ref.SearchCandidates(ctx, c, trimmed)
+ matches, err = ref.SearchCandidates(ctx, c, identifier)
} else {
- matches, err = ref.searchMatchesInternal(ctx, c, trimmed)
+ matches, err = ref.searchMatches(ctx, c, identifier)
}
- if err != nil {
- return nil, false, err
+ if err != nil && len(matches) == 0 {
+ return nil, err
}
-
- if ref.Exact != nil && len(matches) > 1 {
- identifierLower := strings.ToLower(trimmed)
- exact := make([]S, 0, 1)
- for _, match := range matches {
- if ref.Exact(match, identifierLower, trimmed) {
- exact = append(exact, match)
- }
- }
+ identifierLower := strings.ToLower(identifier)
+ if ref.Exact != nil && !collect {
+ exact := slices.Clone(matches)
+ exact = slices.DeleteFunc(exact, func(item S) bool { return !ref.Exact(item, identifierLower, identifier) })
if len(exact) == 1 {
matches = exact
}
}
-
- selected, err := ref.selectCandidateInternal(matches, trimmed, allowPrompt)
- if err != nil {
- return nil, false, err
- }
- if selected != nil {
- return ref.Promote(*selected), false, nil
+ if ref.SelectCandidate != nil && !collect {
+ selected, selectErr := ref.SelectCandidate(matches, identifier, allowPrompt)
+ if selectErr != nil {
+ return nil, selectErr
+ }
+ matches = nil
+ if selected != nil {
+ matches = []S{*selected}
+ }
}
-
- if ref.IDOf != nil {
- identifierLower := strings.ToLower(trimmed)
- if LooksLikeIDPrefix(identifierLower) {
- fallbackMatches, fallbackByIDPrefixErr := ref.fallbackByIDPrefixInternal(ctx, c, identifierLower)
- if fallbackByIDPrefixErr != nil {
- return nil, false, fallbackByIDPrefixErr
- }
- fallbackCandidate, fallbackByIDPrefixErr := ref.selectCandidateInternal(fallbackMatches, trimmed, allowPrompt)
- if fallbackByIDPrefixErr != nil {
- return nil, false, fallbackByIDPrefixErr
- }
- if fallbackCandidate != nil {
- return ref.Promote(*fallbackCandidate), false, nil
- }
+ if len(matches) == 0 && ref.IDOf != nil && LooksLikeIDPrefix(identifierLower) {
+ matches, err = ref.fallbackByIDPrefix(ctx, c, identifierLower)
+ if err != nil {
+ return nil, err
}
}
-
- return nil, false, fmt.Errorf("%s %q not found; use %s or run `%s`", ref.Singular, trimmed, ref.IDHint, ref.ListCmd)
+ result := make([]resourceCandidate[D], len(matches))
+ for i, item := range matches {
+ result[i] = resourceCandidate[D]{details: ref.Promote(item), label: ref.Label(item), exact: collect && ref.Exact != nil && ref.Exact(item, identifierLower, identifier)}
+ }
+ return result, err
}
-func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *client.Client, identifier string) (*D, bool, error) {
+func (ref ResourceRef[D, S]) fetchByIdentifier(ctx context.Context, c *client.Client, identifier string) (*D, bool, error) {
+ if ref.GetPath == nil {
+ return nil, false, nil
+ }
resp, err := c.Get(ctx, ref.GetPath(c.EnvID(), identifier))
if err != nil {
return nil, false, fmt.Errorf("failed to resolve %s %q: %w", ref.Singular, identifier, err)
@@ -144,10 +226,13 @@ func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *c
}
if resp.StatusCode == http.StatusOK {
- var result base.ApiResponse[D]
+ var result client.APIResponse[D]
if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
return nil, false, fmt.Errorf("failed to parse %s response: %w", ref.Singular, unmarshalErr)
}
+ if !result.Success {
+ return nil, false, fmt.Errorf("API error: %s", cmp.Or(result.Error, "request was not successful"))
+ }
if ref.Validate != nil {
if validateErr := ref.Validate(result.Data, identifier); validateErr != nil {
return nil, false, validateErr
@@ -163,9 +248,9 @@ func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *c
return nil, false, nil
}
-func (ref ResourceRef[D, S]) searchMatchesInternal(ctx context.Context, c *client.Client, identifier string) ([]S, error) {
+func (ref ResourceRef[D, S]) searchMatches(ctx context.Context, c *client.Client, identifier string) ([]S, error) {
searchPath := fmt.Sprintf("%s?search=%s&limit=%d", ref.ListPath(c.EnvID()), url.QueryEscape(identifier), ShowAllLimit)
- items, err := ref.listItemsInternal(ctx, c, searchPath)
+ items, err := ref.listItems(ctx, c, searchPath)
if err != nil {
return nil, err
}
@@ -180,41 +265,8 @@ func (ref ResourceRef[D, S]) searchMatchesInternal(ctx context.Context, c *clien
return matches, nil
}
-func (ref ResourceRef[D, S]) selectCandidateInternal(matches []S, identifier string, allowPrompt bool) (*S, error) {
- if ref.SelectCandidate != nil {
- return ref.SelectCandidate(matches, identifier, allowPrompt)
- }
- return ref.selectMatchInternal(matches, identifier, allowPrompt)
-}
-
-func (ref ResourceRef[D, S]) selectMatchInternal(matches []S, identifier string, allowPrompt bool) (*S, error) {
- if len(matches) == 1 {
- return &matches[0], nil
- }
- if len(matches) == 0 {
- return nil, nil
- }
-
- if !allowPrompt {
- return nil, fmt.Errorf("multiple %s match %q; use %s or run `%s`", ref.Plural, identifier, ref.IDHint, ref.ListCmd)
- }
- if len(matches) > MaxPromptOptions {
- return nil, fmt.Errorf("multiple %s match %q (%d results); refine your query or use %s", ref.Plural, identifier, len(matches), ref.IDHint)
- }
-
- options := make([]string, 0, len(matches))
- for _, match := range matches {
- options = append(options, ref.Label(match))
- }
- choice, err := prompt.Select(ref.Singular, options)
- if err != nil {
- return nil, err
- }
- return &matches[choice], nil
-}
-
-func (ref ResourceRef[D, S]) fallbackByIDPrefixInternal(ctx context.Context, c *client.Client, identifierLower string) ([]S, error) {
- items, err := ref.listItemsInternal(ctx, c, fmt.Sprintf("%s?limit=%d", ref.ListPath(c.EnvID()), ShowAllLimit))
+func (ref ResourceRef[D, S]) fallbackByIDPrefix(ctx context.Context, c *client.Client, identifierLower string) ([]S, error) {
+ items, err := ref.listItems(ctx, c, fmt.Sprintf("%s?limit=%d", ref.ListPath(c.EnvID()), ShowAllLimit))
if err != nil {
return nil, err
}
@@ -227,7 +279,7 @@ func (ref ResourceRef[D, S]) fallbackByIDPrefixInternal(ctx context.Context, c *
return matches, nil
}
-func (ref ResourceRef[D, S]) listItemsInternal(ctx context.Context, c *client.Client, path string) ([]S, error) {
+func (ref ResourceRef[D, S]) listItems(ctx context.Context, c *client.Client, path string) ([]S, error) {
resp, err := c.Get(ctx, path)
if err != nil {
return nil, fmt.Errorf("failed to search %s: %w", ref.Plural, err)
@@ -243,10 +295,13 @@ func (ref ResourceRef[D, S]) listItemsInternal(ctx context.Context, c *client.Cl
return nil, fmt.Errorf("failed to search %s (status %d): %s", ref.Plural, resp.StatusCode, strings.TrimSpace(string(body)))
}
- var result base.Paginated[S]
+ var result client.APIResponse[[]S]
if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
return nil, fmt.Errorf("failed to parse %s response: %w", ref.Plural, unmarshalErr)
}
+ if !result.Success {
+ return nil, fmt.Errorf("API error: %s", cmp.Or(result.Error, "request was not successful"))
+ }
return result.Data, nil
}
diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.go
index fd68c882c..fe8e8c945 100644
--- a/cli/internal/cmdutil/response.go
+++ b/cli/internal/cmdutil/response.go
@@ -2,6 +2,7 @@ package cmdutil
import (
"bytes"
+ "cmp"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
@@ -58,11 +59,7 @@ func DecodeJSON[T any](resp *http.Response, out *T) error {
return nil
}
-// ReadJSONBody enforces a successful HTTP status and returns the raw response body.
-// Use it when a command needs both to decode a response and to echo it verbatim,
-// so that fields the CLI does not model — such as the counts and groups objects
-// on the container, volume, network and gitops-sync list endpoints — survive
-// --json output instead of being dropped by a re-marshal.
+// ReadJSONBody enforces HTTP and API success while retaining every response field.
func ReadJSONBody(resp *http.Response) ([]byte, error) {
if err := EnsureSuccessStatus(resp); err != nil {
return nil, err
@@ -71,6 +68,13 @@ func ReadJSONBody(resp *http.Response) ([]byte, error) {
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
+ var status struct {
+ Success *bool `json:"success"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(body, &status) == nil && status.Success != nil && !*status.Success {
+ return nil, fmt.Errorf("API error: %s", cmp.Or(status.Error, "request was not successful"))
+ }
return body, nil
}
diff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.go
index 2e185c3e7..db7a982ce 100644
--- a/cli/internal/cmdutil/run.go
+++ b/cli/internal/cmdutil/run.go
@@ -13,9 +13,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
)
-// ListSpec describes one standard list command: fetch a paginated endpoint,
-// echo the raw body for --json (so unmodeled fields like counts and groups
-// survive, see ReadJSONBody), otherwise render a table.
+// ListSpec describes a paginated list with raw JSON passthrough or table rendering.
type ListSpec[T any] struct {
// Resource names the collection in error messages and the trailing
// "Showing x of y <resource>" line.
@@ -73,10 +71,9 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erro
rows[i] = spec.Row(item)
}
- if tableErr := output.Table(spec.Headers, rows); tableErr != nil {
+ if tableErr := PrintTable(cmd, spec.Headers, rows, TableSummary{Resource: spec.Resource, Total: result.Pagination.TotalItems, Paginated: true}); tableErr != nil {
return tableErr
}
- output.Showing(len(result.Data), result.Pagination.TotalItems, spec.Resource)
return nil
}
diff --git a/cli/internal/cmdutil/scope.go b/cli/internal/cmdutil/scope.go
new file mode 100644
index 000000000..362115d62
--- /dev/null
+++ b/cli/internal/cmdutil/scope.go
@@ -0,0 +1,225 @@
+package cmdutil
+
+import (
+ "bytes"
+ "cmp"
+ "context"
+ "encoding/json/jsontext"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
+)
+
+const (
+ ScopeRead = "read"
+ ScopeFleet = "fleet"
+ ScopeDestination = "destination"
+ ScopeResource = "resource"
+ ScopeGlobal = "global"
+)
+
+type environmentResult struct {
+ EnvironmentID string `json:"environmentId"`
+ EnvironmentName string `json:"environmentName"`
+ Result jsontext.Value `json:"result,omitempty"`
+ 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.
+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 {
+ c, err := ClientFromCommand(command)
+ if err != nil {
+ return err
+ }
+ resolved, _, err := ref.Resolve(command.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+ if ref.IdentifierOf != nil {
+ args[0] = ref.IdentifierOf(*resolved)
+ }
+ return nil
+ }
+ }
+}
+
+// SetScope declares how commands behave when all-environments preview is enabled.
+func SetScope(scope string, commands ...*cobra.Command) {
+ for _, cmd := range commands {
+ if cmd.Annotations == nil {
+ cmd.Annotations = make(map[string]string)
+ }
+ cmd.Annotations["arcane:scope"] = scope
+ }
+}
+
+// RunScoped reuses the command's requests and rendering for each selected environment.
+func RunScoped(cmd *cobra.Command, args []string, run func(*cobra.Command, []string) error) error {
+ app, ok := runtime.From(cmd.Context())
+ if !ok || !app.PreviewEnabled() {
+ return run(cmd, args)
+ }
+ var scope string
+ for current := cmd; current != nil; current = current.Parent() {
+ if scope = current.Annotations["arcane:scope"]; scope != "" {
+ break
+ }
+ }
+ if flag := cmd.Annotations["arcane:scope-flag"]; flag != "" {
+ enabled, _ := cmd.Flags().GetBool(flag)
+ if !enabled {
+ return run(cmd, args)
+ }
+ }
+ if scope == "" || scope == ScopeGlobal {
+ 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 {
+ return RunEnvironments(cmd, args, run, scope == ScopeFleet)
+ }
+ environments, err := app.Environments(cmd.Context())
+ if err != nil {
+ return err
+ }
+ if len(environments) == 0 {
+ return errors.New("no enabled environments available")
+ }
+ if JSONOutputEnabled(cmd) || !prompt.IsInteractive() {
+ return errors.New("an environment destination is required; pass --env <id>")
+ }
+ options := make([]string, len(environments))
+ for i, env := range environments {
+ options[i] = fmt.Sprintf("%s (%s)", cmp.Or(env.Name, env.ID), env.ID)
+ }
+ choice, selectErr := prompt.Select("environment", options)
+ if selectErr != nil {
+ return selectErr
+ }
+ app.SelectEnvironment(environments[choice].ID)
+ defer app.SelectEnvironment("")
+ return run(cmd, args)
+}
+
+// RunEnvironments executes a command sequentially and reports each environment's result.
+func RunEnvironments(cmd *cobra.Command, args []string, run func(*cobra.Command, []string) error, mutation bool) error {
+ app, _ := runtime.From(cmd.Context())
+ if !app.PreviewEnabled() {
+ return run(cmd, args)
+ }
+ environments, discoveryErr := app.Environments(cmd.Context())
+ if discoveryErr != nil {
+ return discoveryErr
+ }
+ if mutation && len(environments) == 0 {
+ return errors.New("no enabled environments available")
+ }
+ skip, _ := cmd.Flags().GetBool("force")
+ 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)
+ }
+ confirmed, confirmErr := Confirm(cmd, fmt.Sprintf("%s across %d environments: %s?", cmd.Short, len(labels), strings.Join(labels, ", ")))
+ if confirmErr != nil {
+ return confirmErr
+ }
+ if !confirmed {
+ return nil
+ }
+ }
+ if mutation {
+ app.FleetConfirmed = true
+ defer func() { app.FleetConfirmed = false }()
+ }
+ jsonMode := JSONOutputEnabled(cmd)
+ combined := &tableOutput{}
+ commandContext := cmd.Context()
+ if !jsonMode {
+ cmd.SetContext(context.WithValue(commandContext, tableContextKey{}, combined))
+ defer cmd.SetContext(commandContext)
+ }
+ stdout, stderr := output.Stdout(), output.Stderr()
+ defer output.Configure(stdout, stderr, jsonMode, app.NoColor, cmd.Short)
+ defer app.SelectEnvironment("")
+ result := struct {
+ Success bool `json:"success"`
+ Environments []environmentResult `json:"environments"`
+ }{Success: true, Environments: make([]environmentResult, len(environments))}
+ var failures []error
+ var details []struct{ environment, body string }
+ for i, env := range environments {
+ entry := &result.Environments[i]
+ entry.EnvironmentID, entry.EnvironmentName = env.ID, cmp.Or(env.Name, env.ID)
+ if err := cmd.Context().Err(); err != nil {
+ entry.Error = "not started: " + err.Error()
+ failures = append(failures, fmt.Errorf("%s (%s): %w", entry.EnvironmentName, env.ID, err))
+ continue
+ }
+ app.SelectEnvironment(env.ID)
+ var buffer bytes.Buffer
+ combined.environment = entry.EnvironmentName
+ output.Configure(&buffer, stderr, jsonMode, app.NoColor, cmd.Short)
+ runErr := run(cmd, args)
+ if !jsonMode && buffer.Len() > 0 {
+ details = append(details, struct{ environment, body string }{fmt.Sprintf("%s (%s)", entry.EnvironmentName, env.ID), buffer.String()})
+ }
+ if jsonMode {
+ entry.Result = bytes.Clone(bytes.TrimSpace(buffer.Bytes()))
+ if !entry.Result.IsValid() {
+ runErr = cmp.Or(runErr, errors.New("command did not produce a valid JSON result"))
+ }
+ }
+ if runErr != nil {
+ entry.Result = nil
+ entry.Error = runErr.Error()
+ failures = append(failures, fmt.Errorf("%s (%s): %w", entry.EnvironmentName, env.ID, runErr))
+ if !jsonMode {
+ _, _ = fmt.Fprintf(stderr, "%s (%s): %v\n", entry.EnvironmentName, env.ID, runErr)
+ }
+ }
+ }
+ result.Success = len(failures) == 0
+ output.Configure(stdout, stderr, jsonMode, app.NoColor, cmd.Short)
+ cmd.SetContext(commandContext)
+ if jsonMode {
+ if err := PrintJSON(result); err != nil {
+ failures = append(failures, err)
+ }
+ return errors.Join(failures...)
+ }
+ if combined.headers != nil {
+ if err := PrintTable(cmd, combined.headers, combined.rows, combined.summary); err != nil {
+ failures = append(failures, err)
+ }
+ }
+ for _, detail := range details {
+ output.Header("%s", detail.environment)
+ if _, err := fmt.Fprint(stdout, detail.body); err != nil {
+ failures = append(failures, err)
+ }
+ }
+ if len(environments) == 0 {
+ output.Info("No enabled environments")
+ }
+ return errors.Join(failures...)
+}
diff --git a/cli/internal/cmdutil/table.go b/cli/internal/cmdutil/table.go
new file mode 100644
index 000000000..fb85ec57a
--- /dev/null
+++ b/cli/internal/cmdutil/table.go
@@ -0,0 +1,61 @@
+package cmdutil
+
+import (
+ "fmt"
+ "slices"
+
+ "github.com/spf13/cobra"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"
+)
+
+type tableContextKey struct{}
+
+type TableSummary struct {
+ Resource string
+ Total int64
+ Paginated bool
+}
+
+type tableOutput struct {
+ environment string
+ headers []string
+ rows [][]string
+ summary TableSummary
+}
+
+// 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 {
+ var summary TableSummary
+ if len(summaries) > 0 {
+ summary = summaries[0]
+ }
+ combined, _ := cmd.Context().Value(tableContextKey{}).(*tableOutput)
+ formatted := make([][]string, len(rows))
+ for i, row := range rows {
+ formatted[i] = []string(row)
+ if combined != nil {
+ formatted[i] = slices.Concat([]string{combined.environment}, formatted[i])
+ }
+ }
+ if combined != nil {
+ if combined.headers == nil {
+ combined.headers = slices.Concat([]string{"ENVIRONMENT"}, headers)
+ }
+ combined.rows = append(combined.rows, formatted...)
+ combined.summary.Total += summary.Total
+ combined.summary.Resource, combined.summary.Paginated = summary.Resource, summary.Paginated
+ return nil
+ }
+ if err := output.Table(headers, formatted); err != nil {
+ return err
+ }
+ switch {
+ case summary.Resource == "":
+ case summary.Paginated:
+ output.Showing(len(rows), summary.Total, summary.Resource)
+ default:
+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d %s\n", len(rows), summary.Resource)
+ }
+ return nil
+}
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
index 99dfd7867..c6db58fba 100644
--- a/cli/internal/config/config.go
+++ b/cli/internal/config/config.go
@@ -1,23 +1,4 @@
-// Package config handles CLI configuration loading and persistence.
-//
-// Configuration is stored in a YAML file at ~/.config/arcanecli.yml.
-// This package provides functions to load, save, and access configuration
-// values including the server URL, API key, and default environment.
-//
-// # Configuration File
-//
-// The configuration file uses the following format:
-//
-// server_url: https://your-server.com
-// api_key: your-api-key
-// default_environment: "0"
-// log_level: info
-//
-// # Version Information
-//
-// Version and Revision variables are set at build time via ldflags:
-//
-// go build -ldflags "-X github.com/getarcaneapp/arcane/cli/v2/internal/config.Version=1.0.0"
+// Package config loads and persists CLI configuration in ~/.config/arcanecli.yml.
package config
import (
@@ -55,7 +36,7 @@ var configCache = hot.NewHotCache[string, *types.Config](hot.LRU, 4).
WithCopyOnWrite((*types.Config).Clone).
Build()
-func normalizeConfigInternal(cfg *types.Config) *types.Config {
+func normalizeConfig(cfg *types.Config) *types.Config {
if cfg == nil {
return DefaultConfig()
}
@@ -71,15 +52,11 @@ func normalizeConfigInternal(cfg *types.Config) *types.Config {
return normalized
}
-func invalidateCacheInternal() {
+func invalidateCache() {
configCache.Purge()
}
-// DefaultConfig returns a Config with sensible default values.
-// The defaults are:
-// - ServerURL: http://localhost:3552
-// - DefaultEnvironment: "0"
-// - LogLevel: "info"
+// DefaultConfig uses localhost:3552, local environment "0", and info logging.
func DefaultConfig() *types.Config {
return &types.Config{
ServerURL: "http://localhost:3552",
@@ -88,9 +65,7 @@ func DefaultConfig() *types.Config {
}
}
-// ConfigPath returns the absolute path to the configuration file.
-// The config file is located at ~/.config/arcanecli.yml.
-// Returns an error if the user's home directory cannot be determined.
+// ConfigPath resolves the active config path, defaulting to ~/.config/arcanecli.yml.
func ConfigPath() (string, error) {
if customConfigPath != "" {
return customConfigPath, nil
@@ -109,7 +84,7 @@ func ConfigPath() (string, error) {
func SetConfigPath(path string) error {
if strings.TrimSpace(path) == "" {
customConfigPath = ""
- invalidateCacheInternal()
+ invalidateCache()
return nil
}
@@ -129,13 +104,11 @@ func SetConfigPath(path string) error {
}
customConfigPath = absPath
- invalidateCacheInternal()
+ invalidateCache()
return nil
}
-// Load reads the configuration from disk and returns it.
-// If the config file does not exist, default values are returned.
-// Returns an error if the file exists but cannot be read or parsed.
+// Load reads configuration, using defaults when the file does not exist.
func Load() (*types.Config, error) {
path, err := ConfigPath()
if err != nil {
@@ -159,23 +132,21 @@ 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 := normalizeConfigInternal(cfg)
+ normalized := normalizeConfig(cfg)
configCache.Set(path, normalized)
return normalized, nil
}
-// Save writes the configuration to disk.
-// The config directory is created if it does not exist.
-// The file is created with 0600 permissions for security.
+// Save writes configuration with mode 0600, creating its directory when needed.
func Save(c *types.Config) error {
path, err := ConfigPath()
if err != nil {
return err
}
- cfg := normalizeConfigInternal(c)
+ cfg := normalizeConfig(c)
cfg.Pagination.Default.Limit = max(0, cfg.Pagination.Default.Limit)
resources := cfg.Pagination.Resources
cfg.Pagination.Resources = make(map[string]types.PaginationResourceConfig, len(resources))
@@ -185,7 +156,7 @@ func Save(c *types.Config) error {
}
}
- if writeErr := writeConfigInternal(path, cfg, false); writeErr != nil {
+ if writeErr := writeConfig(path, cfg, false); writeErr != nil {
return writeErr
}
@@ -194,9 +165,7 @@ func Save(c *types.Config) error {
return nil
}
-// InitDefaultFile creates a default config file with credential placeholders.
-// It returns true when a file is created, or false when an
-// existing file is left unchanged.
+// InitDefaultFile creates a template with credential placeholders and returns false if the file already exists.
func InitDefaultFile() (bool, error) {
path, err := ConfigPath()
if err != nil {
@@ -233,18 +202,18 @@ func InitDefaultFile() (bool, error) {
)
}
- if writeErr := writeConfigInternal(path, &template, true); writeErr != nil {
+ if writeErr := writeConfig(path, &template, true); writeErr != nil {
if errors.Is(writeErr, os.ErrExist) {
return false, nil
}
return false, writeErr
}
- invalidateCacheInternal()
+ invalidateCache()
return true, nil
}
-func writeConfigInternal(path string, cfg any, exclusive bool) (err error) {
+func writeConfig(path string, cfg any, exclusive bool) (err error) {
data, marshalErr := yaml.Marshal(cfg)
if marshalErr != nil {
return fmt.Errorf("failed to marshal config: %w", marshalErr)
@@ -277,9 +246,7 @@ func writeConfigInternal(path string, cfg any, exclusive bool) (err error) {
return nil
}
-// BackupFile moves the active config file to a .bak path and removes the
-// original file from its previous location. If no config file exists, it
-// returns moved=false and no error.
+// BackupFile moves the active config to .bak, returning moved=false when no config exists.
func BackupFile() (backupPath string, moved bool, err error) {
path, err := ConfigPath()
if err != nil {
@@ -315,6 +282,6 @@ func BackupFile() (backupPath string, moved bool, err error) {
return "", false, fmt.Errorf("failed to move config to backup: %w", backupConfigErr)
}
- invalidateCacheInternal()
+ invalidateCache()
return backupPath, true, nil
}
diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go
index 5bb10bc23..32cb0c432 100644
--- a/cli/internal/config/config_test.go
+++ b/cli/internal/config/config_test.go
@@ -12,7 +12,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
-func setTempConfigPathInternal(t *testing.T) string {
+func setTempConfigPath(t *testing.T) string {
t.Helper()
path := filepath.Join(t.TempDir(), "arcanecli.yml")
@@ -33,7 +33,7 @@ func setTempConfigPathInternal(t *testing.T) string {
}
func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
{
_, err := os.Stat(path)
require.True(t, os.IsNotExist(err),
@@ -48,6 +48,7 @@ func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {
require.Equal(t, "http://localhost:3552", cfg.ServerURL,
"ServerURL=%q, want %q", cfg.ServerURL, "http://localhost:3552")
+ require.False(t, cfg.Previews.AllEnvironments)
require.Equal(t, "0", cfg.DefaultEnvironment,
"DefaultEnvironment=%q, want %q", cfg.DefaultEnvironment, "0")
@@ -68,10 +69,11 @@ func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {
func TestSaveAndLoadRoundTripPagination(t *testing.T) {
for _, filename := range []string{"arcanecli.yml", "custom.json", "config"} {
t.Run(filename, func(t *testing.T) {
- path := filepath.Join(filepath.Dir(setTempConfigPathInternal(t)), "nested", filename)
+ path := filepath.Join(filepath.Dir(setTempConfigPath(t)), "nested", filename)
require.NoError(t, SetConfigPath(path))
cfg := DefaultConfig()
+ cfg.Previews.AllEnvironments = true
cfg.APIKey = "k_test"
cfg.JWTToken = "jwt_test"
cfg.RefreshToken = "refresh_test"
@@ -100,6 +102,7 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
require.Contains(t, text, "gitops-syncs:")
require.NotContains(t, text, "GitOps:")
+ require.Contains(t, text, "previews:\n allEnvironments: true")
require.Contains(t, text, "pagination:",
"expected saved YAML to include pagination block:\n%s", text)
@@ -124,12 +127,13 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
cfg.SetResourceLimit("images", 99)
cached, cacheErr := Load()
require.NoError(t, cacheErr)
+ require.True(t, cached.Previews.AllEnvironments)
require.Equal(t, "k_test", cached.APIKey)
require.Equal(t, 17, cached.LimitFor("images"))
require.Equal(t, 8, cached.LimitFor("gitops-syncs"))
require.NotContains(t, cached.Pagination.Resources, "GitOps")
require.NotContains(t, cached.Pagination.Resources, "volumes")
- invalidateCacheInternal()
+ invalidateCache()
loaded, err := Load()
require.NoError(t, err,
@@ -152,6 +156,7 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
require.Equal(t, "next", loaded.CLIUpdateChannel,
"CLIUpdateChannel=%q, want next", loaded.CLIUpdateChannel)
+ require.True(t, loaded.Previews.AllEnvironments)
require.Equal(t, "k_test", loaded.APIKey)
require.Equal(t, "jwt_test", loaded.JWTToken)
require.Equal(t, "refresh_test", loaded.RefreshToken)
@@ -169,7 +174,7 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
}))
omittedRaw, omittedErr := os.ReadFile(path)
require.NoError(t, omittedErr)
- require.Equal(t, "server_url: https://short.test\n", string(omittedRaw))
+ require.Equal(t, "server_url: https://short.test\npreviews:\n allEnvironments: false\n", string(omittedRaw))
securedInfo, securedErr := os.Stat(path)
require.NoError(t, securedErr)
require.Equal(t, os.FileMode(0o600), securedInfo.Mode().Perm())
@@ -178,7 +183,7 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {
}
func TestLoadCanonicalPaginationBlock(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
content := `
server_url: https://api.arcane.test
api_key: k_123
@@ -284,7 +289,7 @@ pagination:
{name: "quoted limit", content: "pagination:\n default:\n limit: \"13\"\n", errorText: "failed to parse config file"},
} {
t.Run(tc.name, func(t *testing.T) {
- fixturePath := setTempConfigPathInternal(t)
+ fixturePath := setTempConfigPath(t)
require.NoError(t, os.WriteFile(fixturePath, []byte(tc.content), 0o600))
loaded, loadErr := Load()
if tc.errorText != "" {
@@ -308,7 +313,7 @@ pagination:
}
func TestInitDefaultFileCreatesTemplate(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
path = filepath.Join(filepath.Dir(path), "template.json")
require.NoError(t, SetConfigPath(path))
_, initialErr := Load()
@@ -328,6 +333,7 @@ func TestInitDefaultFileCreatesTemplate(t *testing.T) {
"failed to read config file: %v", err)
text := string(raw)
+ require.Contains(t, text, "previews:\n allEnvironments: false")
var values map[string]any
require.NoError(t, yaml.Unmarshal(raw, &values))
for _, key := range []string{"api_key", "jwt_token", "refresh_token", "federated_audience"} {
@@ -378,7 +384,7 @@ func TestInitDefaultFileCreatesTemplate(t *testing.T) {
}
func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
original := "server_url: https://custom.arcane.example\napi_key: custom\n"
{
err := os.WriteFile(path, []byte(original), 0o600)
@@ -394,7 +400,7 @@ func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {
require.False(t, created,
"InitDefaultFile() created = true, want false")
// The writer must also refuse an existing file after the initial path check.
- require.ErrorIs(t, writeConfigInternal(path, DefaultConfig(), true), os.ErrExist)
+ require.ErrorIs(t, writeConfig(path, DefaultConfig(), true), os.ErrExist)
entries, readDirErr := os.ReadDir(filepath.Dir(path))
require.NoError(t, readDirErr)
require.Len(t, entries, 1)
@@ -409,7 +415,7 @@ func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {
}
func TestBackupFileMovesConfig(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
original := "server_url: https://backup.arcane.example\napi_key: abc123\n"
{
err := os.WriteFile(path, []byte(original), 0o600)
@@ -444,7 +450,7 @@ func TestBackupFileMovesConfig(t *testing.T) {
}
func TestBackupFileNoConfig(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
{
_, err := os.Stat(path)
require.True(t, os.IsNotExist(err),
@@ -464,7 +470,7 @@ func TestBackupFileNoConfig(t *testing.T) {
}
func TestBackupFileRotatesExistingBak(t *testing.T) {
- path := setTempConfigPathInternal(t)
+ path := setTempConfigPath(t)
backupPath := path + ".bak"
{
diff --git a/cli/internal/integrationtest/action_error_handling_test.go b/cli/internal/integrationtest/action_error_handling_test.go
deleted file mode 100644
index fdcb32ce7..000000000
--- a/cli/internal/integrationtest/action_error_handling_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package integrationtest
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-// TestContainerStartSurfacesServerError verifies that `containers start` reports
-// a non-2xx response from the action endpoint as an error instead of printing a
-// false success. This is a regression guard: the manager's remote-environment
-// proxy returns 403 when the caller lacks the required per-environment
-// permission, and the CLI must not swallow that and exit 0.
-
-func TestContainerStartSurfacesServerError(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch {
- case r.Method == http.MethodGet && r.URL.Path == "/api/environments/0/containers/abc123":
- // Resolution succeeds so the action POST below is reached.
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{"success":true,"data":{"id":"abc123","name":"nginx"}}`))
- case r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/containers/abc123/start":
- w.WriteHeader(http.StatusForbidden)
- _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))
- default:
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- }
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "start", "abc123"},
- )
-
- require.Error(t, err,
- "expected an error for a 403 start response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
-
- require.Contains(t, err.Error(), "403",
- "expected the error to mention status 403, got: %v", err)
-
- require.NotContains(t, outBuf, "successfully",
- "expected no success message on a denied start, got stdout=%s", outBuf)
-}
-
-// TestSystemContainersStartAllSurfacesServerError verifies the same guard for a
-// system command that does not resolve a resource first: it must report the
-// server's error rather than claiming success.
-func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/system/containers/start-all" {
- w.WriteHeader(http.StatusForbidden)
- _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))
- return
- }
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "system", "containers", "start"},
- )
-
- require.Error(t, err,
- "expected an error for a 403 response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
-
- require.Contains(t, err.Error(), "403",
- "expected the error to mention status 403, got: %v", err)
-
- require.NotContains(t, outBuf, "Started all containers",
- "expected no success message on a denied start-all, got stdout=%s", outBuf)
-}
diff --git a/cli/internal/integrationtest/command_naming_test.go b/cli/internal/integrationtest/command_naming_test.go
deleted file mode 100644
index 86afdb803..000000000
--- a/cli/internal/integrationtest/command_naming_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package integrationtest
-
-import (
- "strings"
- "testing"
-
- "github.com/spf13/cobra"
- "github.com/stretchr/testify/require"
-
- clipkg "github.com/getarcaneapp/arcane/cli/v2/pkg"
-)
-
-// Multi-word actions use flags or nested commands, except the explicit
-// self-update, auto-update, and api-keys names. Hidden commands are exempt.
-func TestNoHyphenatedCommandNames(t *testing.T) {
- var walk func(cmd *cobra.Command, path string)
- walk = func(cmd *cobra.Command, path string) {
- for _, child := range cmd.Commands() {
- if child.Hidden || child.Name() == "self-update" || child.Name() == "auto-update" || child.Name() == "api-keys" {
- continue
- }
- childPath := path + " " + child.Name()
- if strings.Contains(child.Name(), "-") {
- t.Errorf("command %q has a hyphenated name; use a flag or nested subcommand instead", childPath)
- }
- walk(child, childPath)
- }
- }
- root := clipkg.RootCommand()
- walk(root, root.Name())
- for _, path := range [][]string{
- {"images", "vulnerabilities", "scan"},
- {"admin", "backups", "list"},
- {"volumes", "backups", "list"},
- {"jobs", "schedules", "get"},
- {"jobs", "schedules", "update"},
- {"jobs", "list"},
- {"jobs", "run"},
- {"containers", "auto-update"},
- {"auth", "api-keys", "list"},
- {"admin", "api-keys", "list"},
- } {
- cmd, remaining, err := root.Find(path)
- require.NoError(t, err)
- require.Empty(t, remaining, "command %s was not fully resolved", strings.Join(path, " "))
- require.Equal(t, root.Name()+" "+strings.Join(path, " "), cmd.CommandPath())
- }
- for _, path := range [][]string{
- {"backups"},
- {"vulnerabilities"},
- {"jobs", "get"},
- {"jobs", "update"},
- {"containers", "autoupdate"},
- {"auth", "keys"},
- {"admin", "keys"},
- } {
- cmd, remaining, err := root.Find(path)
- require.True(t, err != nil || len(remaining) > 0 || cmd.CommandPath() != root.Name()+" "+strings.Join(path, " "),
- "old command %s is still registered", strings.Join(path, " "))
- }
-}
diff --git a/cli/internal/integrationtest/pagination_test.go b/cli/internal/integrationtest/pagination_test.go
deleted file mode 100644
index 0a4abce1d..000000000
--- a/cli/internal/integrationtest/pagination_test.go
+++ /dev/null
@@ -1,376 +0,0 @@
-package integrationtest
-
-import (
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "strings"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestContainersListSendsLimitAndStart(t *testing.T) {
- var (
- mu sync.Mutex
- gotPath string
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotPath = r.URL.Path
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {"id":"abc123","names":["/nginx"],"image":"nginx:latest","state":"running","status":"Up 1 hour"}
- ],
- "pagination": {"totalPages":4,"totalItems":20,"currentPage":3,"itemsPerPage":5}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "list", "--json", "--limit", "5", "--start", "10"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.Equal(t, "/api/environments/0/containers", gotPath,
- "path = %q, want %q", gotPath, "/api/environments/0/containers")
-
- require.True(t, strings.Contains(gotQuery, "limit=5") && strings.Contains(gotQuery, "start=10"),
- "query = %q, want limit=5 and start=10", gotQuery)
-
- var got map[string]any
- {
- unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, unmarshalErr,
- "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
- }
- {
-
- _, ok := got["pagination"]
- require.True(t, ok,
- "expected pagination in output: %v", got)
- }
-}
-
-func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {
- var (
- mu sync.Mutex
- gotPath string
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotPath = r.URL.Path
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [],
- "pagination": {"totalPages":2,"totalItems":26,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- _, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "list", "--json", "--start", "0"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.Equal(t, "/api/environments/0/containers", gotPath,
- "path = %q, want %q", gotPath, "/api/environments/0/containers")
-
- require.True(t, strings.Contains(gotQuery, "start=0") && strings.Contains(gotQuery, "limit=20"),
- "query = %q, want start=0 and limit=20", gotQuery)
-}
-
-func TestContainersListTextShowsShowingSummary(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {"id":"abc123","names":["/nginx"],"image":"nginx:latest","state":"running","status":"Up 1 hour"}
- ],
- "pagination": {"totalPages":2,"totalItems":26,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "list", "--json=false"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Contains(t, outBuf, "Showing: 1/26 containers",
- "expected showing summary in output, got:\n%s", outBuf)
-}
-
-// TestContainersListAllRequestsEveryItem pins the wire form of --all. The API
-// has no "all" query parameter — it silently ignores unknown ones — so sending
-// all=true without a limit left Huma applying its default of 20. limit=-1 is the
-// documented "return everything" sentinel.
-func TestContainersListAllRequestsEveryItem(t *testing.T) {
- var (
- mu sync.Mutex
- gotPath string
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotPath = r.URL.Path
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [],
- "pagination": {"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":0}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- _, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "list", "--json", "--all"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.Equal(t, "/api/environments/0/containers", gotPath,
- "path = %q, want %q", gotPath, "/api/environments/0/containers")
-
- require.Equal(t, "limit=-1", gotQuery,
- "query = %q, want %q", gotQuery, "limit=-1")
-}
-
-// TestProjectsListAllIncludesArchived covers the one resource where "everything"
-// takes a second parameter: the projects list filters archived rows out by
-// default, so --all has to opt back into them.
-func TestProjectsListAllIncludesArchived(t *testing.T) {
- var (
- mu sync.Mutex
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [],
- "pagination": {"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":0}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- _, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "projects", "list", "--json", "--all"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.Equal(t, "archived=all&limit=-1", gotQuery,
- "query = %q, want %q", gotQuery, "archived=all&limit=-1")
-}
-
-func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {
- var (
- mu sync.Mutex
- gotPath string
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotPath = r.URL.Path
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {
- "id":"evt-1",
- "type":"container.start",
- "severity":"info",
- "title":"Container started",
- "timestamp":"2026-04-08T12:00:00Z",
- "createdAt":"2026-04-08T12:00:00Z"
- }
- ],
- "pagination": {"totalPages":5,"totalItems":15,"currentPage":3,"itemsPerPage":3}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- _, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "admin", "events", "list", "--environment", "--json", "--limit", "3", "--start", "6"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.Equal(t, "/api/events/environment/0", gotPath,
- "path = %q, want %q", gotPath, "/api/events/environment/0")
-
- require.True(t, strings.Contains(gotQuery, "limit=3") && strings.Contains(gotQuery, "start=6"),
- "query = %q, want limit=3 and start=6", gotQuery)
-}
-
-func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
- var (
- mu sync.Mutex
- gotPath string
- gotQuery string
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- gotPath = r.URL.Path
- gotQuery = r.URL.RawQuery
- mu.Unlock()
-
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {"name":"nginx","isCustom":false,"isRemote":false,"description":"Nginx template"}
- ],
- "pagination": {"totalPages":3,"totalItems":15,"currentPage":3,"itemsPerPage":7}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "templates", "list", "--json", "--limit", "7", "--start", "14"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- mu.Lock()
- if gotPath != "/api/templates" {
- mu.Unlock()
- require.FailNowf(t, "unexpected failure", "path = %q, want %q", gotPath, "/api/templates")
- }
- if !strings.Contains(gotQuery, "limit=7") || !strings.Contains(gotQuery, "start=14") {
- mu.Unlock()
- require.FailNowf(t, "unexpected failure", "query = %q, want limit=7 and start=14", gotQuery)
- }
- mu.Unlock()
-
- var got map[string]any
- {
- unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, unmarshalErr,
- "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
- }
- {
-
- _, ok := got["success"]
- require.True(t, ok,
- "expected success key in output: %v", got)
- }
- {
-
- _, ok := got["data"]
- require.True(t, ok,
- "expected data key in output: %v", got)
- }
- {
-
- _, ok := got["pagination"]
- require.True(t, ok,
- "expected pagination key in output: %v", got)
- }
-}
-
-func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {
- var (
- mu sync.Mutex
- called bool
- )
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mu.Lock()
- called = true
- mu.Unlock()
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{"success":true,"data":[]}`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- _, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "templates", "list", "--all", "--limit", "50"},
- )
-
- require.Error(t, err,
- "expected command error, got nil")
-
- require.Contains(t, err.Error(), "--all cannot be combined with explicit pagination flags",
- "unexpected error: %v", err)
-
- require.Contains(t, errOut, "--all cannot be combined with explicit pagination flags",
- "unexpected stderr output: %s", errOut)
-
- mu.Lock()
- defer mu.Unlock()
-
- require.False(t, called,
- "expected command to fail before issuing HTTP request")
-}
diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go
index d2ad5773c..e450c0c82 100644
--- a/cli/internal/prompt/prompt.go
+++ b/cli/internal/prompt/prompt.go
@@ -32,7 +32,11 @@ func Select(label string, options []string) (int, error) {
items[i] = selectItem{index: i, title: option}
}
- model := newSelectModel(items)
+ model := selectModel{list: list.New(items, list.NewDefaultDelegate(), 0, 0), choice: -1}
+ model.list.Title = ""
+ model.list.SetShowStatusBar(false)
+ model.list.SetFilteringEnabled(true)
+ model.list.SetShowHelp(true)
program := tea.NewProgram(model)
finalModel, err := program.Run()
if err != nil {
@@ -53,20 +57,13 @@ func Select(label string, options []string) (int, error) {
return -1, errors.New("selection out of range")
}
- clearScreenAndShowSelection(label, options[result.choice])
- return result.choice, nil
-}
-
-func clearScreenAndShowSelection(label, selected string) {
- // Clear visible terminal content and place cursor at top-left.
- fmt.Print("\033[H\033[2J")
-
+ _, _ = fmt.Fprint(output.Stderr(), "\033[H\033[2J")
if label == "" {
- fmt.Printf("Selected: %s\n\n", selected)
- return
+ _, _ = fmt.Fprintf(output.Stderr(), "Selected: %s\n\n", options[result.choice])
+ } else {
+ _, _ = fmt.Fprintf(output.Stderr(), "Selected %s: %s\n\n", label, options[result.choice])
}
-
- fmt.Printf("Selected %s: %s\n\n", label, selected)
+ return result.choice, nil
}
type selectItem struct {
@@ -84,16 +81,6 @@ type selectModel struct {
canceled bool
}
-func newSelectModel(items []list.Item) selectModel {
- delegate := list.NewDefaultDelegate()
- model := selectModel{list: list.New(items, delegate, 0, 0), choice: -1}
- model.list.Title = ""
- model.list.SetShowStatusBar(false)
- model.list.SetFilteringEnabled(true)
- model.list.SetShowHelp(true)
- return model
-}
-
func (m selectModel) Init() tea.Cmd {
return nil
}
diff --git a/cli/internal/runtime/context.go b/cli/internal/runtime/context.go
index b2504a7cd..09905b257 100644
--- a/cli/internal/runtime/context.go
+++ b/cli/internal/runtime/context.go
@@ -4,13 +4,16 @@ import (
"cmp"
"context"
"fmt"
+ "slices"
"strings"
"sync"
"time"
+ "github.com/getarcaneapp/arcane/types/v2/environment"
+
"github.com/getarcaneapp/arcane/cli/v2/internal/client"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
- clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
type contextKey string
@@ -35,12 +38,13 @@ type Options struct {
}
type AppContext struct {
- cfg *clitypes.Config
- envOverride string
- outputMode OutputMode
- assumeYes bool
- noColor bool
- requestTimeout time.Duration
+ Options
+ FleetConfirmed bool
+ cfg *types.Config
+ selectedEnv string
+ environmentsOnce sync.Once
+ environments []environment.Environment
+ environmentsErr error
clientOnce sync.Once
clientErr error
@@ -64,14 +68,9 @@ func New(opts Options) (*AppContext, error) {
return nil, fmt.Errorf("invalid output mode %q (expected text or json)", mode)
}
- return &AppContext{
- cfg: cfg,
- envOverride: strings.TrimSpace(opts.EnvOverride),
- outputMode: mode,
- assumeYes: opts.AssumeYes,
- noColor: opts.NoColor,
- requestTimeout: opts.RequestTimeout,
- }, nil
+ opts.OutputMode = mode
+ opts.EnvOverride = strings.TrimSpace(opts.EnvOverride)
+ return &AppContext{Options: opts, cfg: cfg}, nil
}
func From(ctx context.Context) (*AppContext, bool) {
@@ -82,7 +81,7 @@ func From(ctx context.Context) (*AppContext, bool) {
return app, ok && app != nil
}
-func (a *AppContext) Config() *clitypes.Config {
+func (a *AppContext) Config() *types.Config {
if a == nil || a.cfg == nil {
return nil
}
@@ -90,8 +89,8 @@ func (a *AppContext) Config() *clitypes.Config {
if copyCfg == nil {
return nil
}
- if a.envOverride != "" {
- copyCfg.DefaultEnvironment = a.envOverride
+ if id := cmp.Or(a.selectedEnv, a.EnvOverride); id != "" {
+ copyCfg.DefaultEnvironment = id
}
return copyCfg
}
@@ -100,8 +99,8 @@ func (a *AppContext) EnvID() string {
if a == nil {
return ""
}
- if a.envOverride != "" {
- return a.envOverride
+ if id := cmp.Or(a.selectedEnv, a.EnvOverride); id != "" {
+ return id
}
if a.cfg != nil {
return a.cfg.DefaultEnvironment
@@ -109,30 +108,8 @@ func (a *AppContext) EnvID() string {
return ""
}
-func (a *AppContext) OutputMode() OutputMode {
- if a == nil {
- return OutputModeText
- }
- return a.outputMode
-}
-
func (a *AppContext) IsJSON() bool {
- return a.OutputMode() == OutputModeJSON
-}
-
-func (a *AppContext) AssumeYes() bool {
- return a != nil && a.assumeYes
-}
-
-func (a *AppContext) NoColor() bool {
- return a != nil && a.noColor
-}
-
-func (a *AppContext) RequestTimeout() time.Duration {
- if a == nil {
- return 0
- }
- return a.requestTimeout
+ return a != nil && a.OutputMode == OutputModeJSON
}
func (a *AppContext) Client() (*client.Client, error) {
@@ -145,8 +122,8 @@ func (a *AppContext) Client() (*client.Client, error) {
if a.clientErr != nil {
return
}
- if a.requestTimeout > 0 {
- a.client.SetTimeout(a.requestTimeout)
+ if a.RequestTimeout > 0 {
+ a.client.SetTimeout(a.RequestTimeout)
}
})
return a.client, a.clientErr
@@ -162,9 +139,43 @@ func (a *AppContext) UnauthClient() (*client.Client, error) {
if a.unauthClientErr != nil {
return
}
- if a.requestTimeout > 0 {
- a.unauthClient.SetTimeout(a.requestTimeout)
+ if a.RequestTimeout > 0 {
+ a.unauthClient.SetTimeout(a.RequestTimeout)
}
})
return a.unauthClient, a.unauthClientErr
}
+
+// PreviewEnabled reports whether this command still needs an environment scope.
+func (a *AppContext) PreviewEnabled() bool {
+ return a != nil && a.cfg.Previews.AllEnvironments && a.EnvOverride == "" && a.selectedEnv == ""
+}
+
+// SelectEnvironment pins subsequent requests without changing persisted configuration.
+func (a *AppContext) SelectEnvironment(id string) {
+ a.selectedEnv = id
+ if a.client != nil {
+ a.client.SetEnvironment(cmp.Or(id, a.EnvOverride, a.cfg.DefaultEnvironment, "0"))
+ }
+}
+
+// Environments loads the complete visible, enabled environment list once per invocation.
+func (a *AppContext) Environments(ctx context.Context) ([]environment.Environment, error) {
+ a.environmentsOnce.Do(func() {
+ c, err := a.Client()
+ if err != nil {
+ a.environmentsErr = err
+ return
+ }
+ response, err := c.GetJSON[[]environment.Environment](ctx, types.Environments()+"?limit=-1")
+ if err != nil {
+ a.environmentsErr = fmt.Errorf("failed to discover environments: %w", err)
+ return
+ }
+ a.environments = slices.DeleteFunc(response.Data, func(env environment.Environment) bool { return !env.Enabled })
+ slices.SortFunc(a.environments, func(left, right environment.Environment) int {
+ return cmp.Or(cmp.Compare(strings.ToLower(cmp.Or(left.Name, left.ID)), strings.ToLower(cmp.Or(right.Name, right.ID))), cmp.Compare(left.ID, right.ID))
+ })
+ })
+ return a.environments, a.environmentsErr
+}
diff --git a/cli/internal/integrationtest/command_helpers_test.go b/cli/internal/testutil/cli.go
similarity index 55%
rename from cli/internal/integrationtest/command_helpers_test.go
rename to cli/internal/testutil/cli.go
index 75122ea91..e1c75a72f 100644
--- a/cli/internal/integrationtest/command_helpers_test.go
+++ b/cli/internal/testutil/cli.go
@@ -1,10 +1,11 @@
-package integrationtest
+package testutil
import (
"io"
"os"
"path/filepath"
"runtime"
+ "strconv"
"strings"
"sync"
"testing"
@@ -13,12 +14,13 @@ import (
"github.com/spf13/pflag"
"github.com/stretchr/testify/require"
- clipkg "github.com/getarcaneapp/arcane/cli/v2/pkg"
+ "github.com/getarcaneapp/arcane/cli/v2/pkg"
)
-var stdoutCaptureMuInternal sync.Mutex
+var stdoutCaptureMu sync.Mutex
-func writeCLIIntegrationConfigInternal(t *testing.T, serverURL string) string {
+// WriteConfig writes isolated configuration for command tests.
+func WriteConfig(t *testing.T, serverURL string, preview ...bool) string {
t.Helper()
tempDir := t.TempDir()
@@ -27,6 +29,7 @@ func writeCLIIntegrationConfigInternal(t *testing.T, serverURL string) string {
"server_url: " + serverURL,
"api_key: arc_test_key",
"default_environment: \"0\"",
+ "previews:\n allEnvironments: " + strconv.FormatBool(len(preview) > 0 && preview[0]),
"log_level: info",
"",
}, "\n")
@@ -39,17 +42,18 @@ func writeCLIIntegrationConfigInternal(t *testing.T, serverURL string) string {
return configPath
}
-func executeCLIIntegrationCommandInternal(t *testing.T, args []string) (string, string, error) {
+// Execute runs the root command with isolated flags and captures its output.
+func Execute(t *testing.T, args []string) (string, string, error) {
t.Helper()
- root := clipkg.RootCommand()
- resetCommandFlagsInternal(t, root)
+ root := cli.RootCommand()
+ resetCommandFlags(t, root)
errOut := &strings.Builder{}
root.SetErr(errOut)
root.SetArgs(args)
- stdoutCaptureMuInternal.Lock()
- defer stdoutCaptureMuInternal.Unlock()
+ stdoutCaptureMu.Lock()
+ defer stdoutCaptureMu.Unlock()
stdout := os.Stdout
reader, writer, err := os.Pipe()
@@ -79,42 +83,24 @@ func executeCLIIntegrationCommandInternal(t *testing.T, args []string) (string,
return outBuf, errOut.String(), runErr
}
-func resetCommandFlagsInternal(t *testing.T, root *cobra.Command) {
+func resetCommandFlags(t *testing.T, root *cobra.Command) {
t.Helper()
if root == nil {
return
}
- resetFlagSetInternal(t, root.PersistentFlags())
- resetFlagSetInternal(t, root.Flags())
- for _, cmd := range root.Commands() {
- resetCommandFlagsInternal(t, cmd)
- }
-}
-
-func resetFlagSetInternal(t *testing.T, flagSet *pflag.FlagSet) {
- t.Helper()
-
- if flagSet == nil {
- return
- }
-
- flagSet.VisitAll(func(flag *pflag.Flag) {
- defValue := flag.DefValue
- switch flag.Value.Type() {
- case "stringSlice", "stringArray":
- if defValue == "[]" {
+ 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 = ""
}
- }
- {
-
- err := flag.Value.Set(defValue)
- require.NoError(t, err,
- "reset flag %s: %v", flag.Name, err)
- }
-
- flag.Changed = false
- })
+ 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 7685c637f..28c9b09ac 100644
--- a/cli/internal/types/config.go
+++ b/cli/internal/types/config.go
@@ -78,6 +78,11 @@ func NormalizePaginatedResource(resource string) string {
}
// Config holds the CLI configuration for connecting to an Arcane server.
+// PreviewsConfig contains optional CLI preview features.
+type PreviewsConfig struct {
+ AllEnvironments bool `yaml:"allEnvironments"`
+}
+
// It is persisted to disk as YAML and loaded on each CLI invocation.
type Config struct {
// ServerURL is the base URL of the Arcane server (e.g., http://localhost:3552)
@@ -88,6 +93,8 @@ type Config struct {
JWTToken string `yaml:"jwt_token,omitempty"`
// RefreshToken is the refresh token for obtaining new access tokens
RefreshToken string `yaml:"refresh_token,omitempty"`
+ // Previews contains optional CLI preview features.
+ Previews PreviewsConfig `yaml:"previews"`
// DefaultEnvironment is the default environment ID to use
DefaultEnvironment string `yaml:"default_environment,omitempty"`
// FederatedAudience is the default token audience for `arcane-cli auth federated`
@@ -114,9 +121,7 @@ func (c *Config) ValidateServerURL() error {
return nil
}
-// Validate checks if the configuration has all required fields set.
-// It returns an error with instructions if ServerURL or APIKey is missing.
-// This should be called before using the config to make API requests.
+// Validate requires a configured server URL and either an API key or JWT token.
func (c *Config) Validate() error {
if err := c.ValidateServerURL(); err != nil {
return err
@@ -127,9 +132,7 @@ func (c *Config) Validate() error {
return nil
}
-// IsConfigured returns true if both ServerURL and APIKey are set.
-// This is a quick check to determine if the CLI has been configured
-// without triggering validation errors.
+// IsConfigured reports whether the server URL and authentication are configured.
func (c *Config) IsConfigured() bool {
return c.ServerURL != "" && c.HasAuth()
}
diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.go
index 08d07e0e3..ae3b89e5d 100644
--- a/cli/pkg/activities/cmd.go
+++ b/cli/pkg/activities/cmd.go
@@ -3,9 +3,11 @@
package activities
import (
+ "cmp"
"fmt"
"net/url"
"strconv"
+ "strings"
"time"
activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"
@@ -65,14 +67,36 @@ var listCmd = &cobra.Command{
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),
- activityResource(item),
+ resource,
item.StartedAt.Format(time.RFC3339),
- activityProgress(item),
- activityMessage(item),
+ progress,
+ message,
}
},
})
@@ -108,11 +132,25 @@ var getCmd = &cobra.Command{
output.KeyValue("ID", item.ID)
output.KeyValue("Type", string(item.Type))
output.KeyValue("Status", string(item.Status))
- if resource := activityResource(item); resource != "" {
+ 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
+ }
+ }
+ if resource != "" {
output.KeyValue("Resource", resource)
}
if item.Progress != nil {
- output.KeyValue("Progress", activityProgress(item))
+ output.KeyValue("Progress", strconv.Itoa(*item.Progress)+"%")
}
if item.Step != "" {
output.KeyValue("Step", item.Step)
@@ -217,6 +255,10 @@ var clearCmd = &cobra.Command{
}
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)
@@ -244,39 +286,14 @@ func init() {
clearCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
-func activityResource(item activitytypes.Activity) string {
- name := ""
- if item.ResourceName != nil {
- name = *item.ResourceName
- }
- if name == "" && item.ResourceID != nil {
- name = *item.ResourceID
- }
- if item.ResourceType != nil && *item.ResourceType != "" {
- if name == "" {
- return *item.ResourceType
- }
- return fmt.Sprintf("%s/%s", *item.ResourceType, name)
- }
- return name
-}
-
-func activityProgress(item activitytypes.Activity) string {
- if item.Progress == nil {
- return "-"
- }
- return strconv.Itoa(*item.Progress) + "%"
-}
-
-func activityMessage(item activitytypes.Activity) string {
- if item.LatestMessage != "" {
- return item.LatestMessage
- }
- if item.Step != "" {
- return item.Step
- }
- if item.Error != nil {
- return *item.Error
- }
- return ""
+var activityRef = cmdutil.ResourceRef[activitytypes.Detail, activitytypes.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 {
+ 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} },
}
diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.go
index 4e025d5f6..84482b709 100644
--- a/cli/pkg/admin/events/cmd.go
+++ b/cli/pkg/admin/events/cmd.go
@@ -7,7 +7,6 @@ import (
"github.com/getarcaneapp/arcane/types/v2/event"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -35,7 +34,7 @@ var listCmd = &cobra.Command{
Short: "List events",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -45,39 +44,33 @@ var listCmd = &cobra.Command{
endpoint = types.EventsEnvironment(c.EnvID())
}
- return cmdutil.RunList(cmd, c, eventListSpecInternal(endpoint))
+ 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(),
+ }
+ },
+ })
},
}
-// eventListSpecInternal builds the shared list spec for the global and
-// per-environment event list commands, which render identically.
-func eventListSpecInternal(endpoint string) cmdutil.ListSpec[event.Event] {
- return 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(),
- }
- },
- }
-}
-
var deleteCmd = &cobra.Command{
Use: "delete <event-id>",
Aliases: []string{"rm", "remove"},
@@ -96,7 +89,7 @@ var deleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -115,7 +108,7 @@ var statsCmd = &cobra.Command{
Short: "Show global event counts by severity",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -148,6 +141,8 @@ var statsCmd = &cobra.Command{
}
func init() {
+ cmdutil.SetScope(cmdutil.ScopeRead, listCmd)
+ listCmd.Annotations["arcane:scope-flag"] = "environment"
EventsCmd.AddCommand(listCmd)
EventsCmd.AddCommand(deleteCmd)
EventsCmd.AddCommand(statsCmd)
diff --git a/cli/pkg/admin/events/cmd_test.go b/cli/pkg/admin/events/cmd_test.go
new file mode 100644
index 000000000..3a405ec00
--- /dev/null
+++ b/cli/pkg/admin/events/cmd_test.go
@@ -0,0 +1,63 @@
+package events_test
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
+
+func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {
+ var (
+ mu sync.Mutex
+ gotPath string
+ gotQuery string
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ gotPath = r.URL.Path
+ gotQuery = r.URL.RawQuery
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"evt-1",
+ "type":"container.start",
+ "severity":"info",
+ "title":"Container started",
+ "timestamp":"2026-04-08T12:00:00Z",
+ "createdAt":"2026-04-08T12:00:00Z"
+ }
+ ],
+ "pagination": {"totalPages":5,"totalItems":15,"currentPage":3,"itemsPerPage":3}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ _, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "admin", "events", "list", "--environment", "--json", "--limit", "3", "--start", "6"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ require.Equal(t, "/api/events/environment/0", gotPath,
+ "path = %q, want %q", gotPath, "/api/events/environment/0")
+
+ require.True(t, strings.Contains(gotQuery, "limit=3") && strings.Contains(gotQuery, "start=6"),
+ "query = %q, want limit=3 and start=6", gotQuery)
+}
diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.go
index ecd5ff055..29ab1e335 100644
--- a/cli/pkg/admin/notifications/cmd.go
+++ b/cli/pkg/admin/notifications/cmd.go
@@ -7,12 +7,12 @@ import (
"net/http"
"os"
"strconv"
+ "strings"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/notification"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -40,7 +40,7 @@ var settingsGetCmd = &cobra.Command{
Short: "Get notification settings",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -64,10 +64,9 @@ var settingsGetCmd = &cobra.Command{
}
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "notification settings"}); tableErr != nil {
return tableErr
}
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d notification settings\n", len(result))
return nil
},
}
@@ -89,7 +88,7 @@ var settingsDeleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -177,7 +176,7 @@ var testProviderCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -192,6 +191,10 @@ var testProviderCmd = &cobra.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)
@@ -210,3 +213,15 @@ func init() {
settingsDeleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
testProviderCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
+
+var providerRef = cmdutil.ResourceRef[notification.Response, notification.Response]{
+ EnvironmentScoped: true,
+ Singular: "provider", Plural: "providers",
+ IDHint: "the identifier", ListCmd: "arcane-cli admin notifications settings get",
+ GetPath: types.NotificationSettingsProvider, ListPath: types.NotificationsSettings,
+ 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 },
+}
diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.go
index 4b0b33b95..de0d761f1 100644
--- a/cli/pkg/config/cmd.go
+++ b/cli/pkg/config/cmd.go
@@ -52,11 +52,16 @@ var configShowCmd = &cobra.Command{
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", cmp.Or(intToString(cfg.Pagination.Default.Limit), "(not set)"))
+ 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 {
@@ -109,6 +114,7 @@ Preferred syntax (key/value pairs):
Examples:
arcane config set server-url http://localhost:3553
arcane config set api-key arc_xxxxxxxxxxxxx
+ arcane config set previews.allEnvironments true
arcane config set pagination.default.limit 25
arcane config set pagination.resources.images.limit 100
arcane config set server-url http://localhost:3553 api-key arc_xxxxxxxxxxxxx
@@ -131,11 +137,43 @@ Legacy flag syntax (flags shown below) is still supported:
}
updated = updated || updatedByArgs
- updatedByFlags, err := applyConfigSetFlags(cmd, cfg)
- if err != nil {
- return err
+ 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
+ }
+ }
+ if cmd.Flags().Changed("default-limit") {
+ if setDefaultLimit < 0 {
+ return errors.New("--default-limit must be >= 0")
+ }
+ if _, setErr := applyConfigSetArg(cfg, "default-limit", strconv.Itoa(setDefaultLimit)); 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, ", "))
+ }
+ if limit < 0 {
+ return fmt.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)
+ }
+ if _, setErr := applyConfigSetArg(cfg, "resource-limit", pair); setErr != nil {
+ return setErr
+ }
+ updated = true
}
- updated = updated || updatedByFlags
if !updated {
return errors.New("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url " +
@@ -317,84 +355,6 @@ func parseResourceLimitPair(pair string) (resource string, limit int, ok bool) {
return resource, parsed, true
}
-func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {
- updated := false
-
- if setServerURL != "" {
- cfg.ServerURL = setServerURL
- _, _ = fmt.Fprintf(output.Stdout(), "Set server_url = %s\n", setServerURL)
- updated = true
- }
-
- if setAPIKey != "" {
- cfg.APIKey = setAPIKey
- // 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(setAPIKey))
- updated = true
- }
-
- if setJWTToken != "" {
- cfg.JWTToken = setJWTToken
- // If switching to JWT auth, clear any existing API key.
- cfg.APIKey = ""
- cfg.RefreshToken = ""
- _, _ = fmt.Fprintf(output.Stdout(), "Set jwt_token = %s\n", maskAPIKey(setJWTToken))
- updated = true
- }
-
- if setEnvironment != "" {
- cfg.DefaultEnvironment = setEnvironment
- _, _ = fmt.Fprintf(output.Stdout(), "Set default_environment = %s\n", setEnvironment)
- updated = true
- }
-
- if setFederatedAudience != "" {
- cfg.FederatedAudience = setFederatedAudience
- _, _ = fmt.Fprintf(output.Stdout(), "Set federated_audience = %s\n", setFederatedAudience)
- updated = true
- }
-
- if setLogLevel != "" {
- cfg.LogLevel = setLogLevel
- _, _ = fmt.Fprintf(output.Stdout(), "Set log_level = %s\n", setLogLevel)
- updated = true
- }
-
- if cmd.Flags().Changed("default-limit") {
- if setDefaultLimit < 0 {
- return false, errors.New("--default-limit must be >= 0")
- }
- cfg.SetDefaultLimit(setDefaultLimit)
- if setDefaultLimit == 0 {
- _, _ = fmt.Fprintln(output.Stdout(), "Cleared pagination.default.limit")
- } else {
- _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.default.limit = %d\n", setDefaultLimit)
- }
- updated = true
- }
-
- for _, pair := range setResourceLimit {
- resource, limit, ok := parseResourceLimitPair(pair)
- if !ok {
- return false, fmt.Errorf("invalid --resource-limit %q (expected resource=number, resources: %s)", pair, strings.Join(types.KnownPaginatedResources, ", "))
- }
- if limit < 0 {
- return false, fmt.Errorf("invalid --resource-limit %q (limit must be >= 0)", pair)
- }
- cfg.SetResourceLimit(resource, limit)
- if limit == 0 {
- _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)
- } else {
- _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)
- }
- updated = true
- }
-
- return updated, nil
-}
-
func applyConfigSetArgs(cfg *types.Config, args []string) (bool, error) {
if len(args) == 0 {
return false, nil
@@ -415,7 +375,7 @@ func applyConfigSetArgs(cfg *types.Config, args []string) (bool, error) {
}
func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {
- normalized := normalizeConfigKey(key)
+ normalized := strings.ReplaceAll(strings.ToLower(strings.TrimSpace(key)), " ", "")
switch normalized {
case "server-url", "server", "serverurl", "server_url":
cfg.ServerURL = value
@@ -435,6 +395,14 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {
cfg.RefreshToken = ""
_, _ = fmt.Fprintf(output.Stdout(), "Set jwt_token = %s\n", maskAPIKey(value))
return true, 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)
+ }
+ cfg.Previews.AllEnvironments = enabled
+ _, _ = fmt.Fprintf(output.Stdout(), "Set previews.allEnvironments = %t\n", enabled)
+ return true, nil
case "environment", "default-environment", "default_environment":
cfg.DefaultEnvironment = value
_, _ = fmt.Fprintf(output.Stdout(), "Set default_environment = %s\n", value)
@@ -499,7 +467,7 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {
func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue string) (bool, error) {
resource := types.NormalizePaginatedResource(resourceValue)
- if resource == "" || !isKnownPaginatedResource(resource) {
+ 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)
@@ -515,10 +483,6 @@ func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue s
return true, nil
}
-func isKnownPaginatedResource(resource string) bool {
- return slices.Contains(types.KnownPaginatedResources, resource)
-}
-
func parseLimitValue(key, value string) (int, error) {
parsed, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
@@ -529,16 +493,3 @@ func parseLimitValue(key, value string) (int, error) {
}
return parsed, nil
}
-
-func normalizeConfigKey(key string) string {
- k := strings.ToLower(strings.TrimSpace(key))
- k = strings.ReplaceAll(k, " ", "")
- return k
-}
-
-func intToString(v int) string {
- if v <= 0 {
- return ""
- }
- return strconv.Itoa(v)
-}
diff --git a/cli/pkg/config/cmd_test.go b/cli/pkg/config/cmd_test.go
index 1bb9bb5ca..d3a3ffd5e 100644
--- a/cli/pkg/config/cmd_test.go
+++ b/cli/pkg/config/cmd_test.go
@@ -14,6 +14,7 @@ func TestApplyConfigSetArgs(t *testing.T) {
changed, 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",
@@ -34,6 +35,16 @@ func TestApplyConfigSetArgs(t *testing.T) {
require.Empty(t, cfg.JWTToken,
"JWTToken = %q, want empty", cfg.JWTToken)
+ require.True(t, cfg.Previews.AllEnvironments)
+ for _, value := range []string{"false", "true", "invalid"} {
+ _, setErr := applyConfigSetArg(cfg, "previews.allEnvironments", value)
+ if value == "invalid" {
+ require.Error(t, setErr)
+ continue
+ }
+ require.NoError(t, setErr)
+ require.Equal(t, value == "true", cfg.Previews.AllEnvironments)
+ }
require.Equal(t, 25, cfg.Pagination.Default.Limit,
"Pagination.Default.Limit = %d, want 25", cfg.Pagination.Default.Limit)
{
diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.go
index 82c71b4f5..52a2fcc5c 100644
--- a/cli/pkg/containers/actions.go
+++ b/cli/pkg/containers/actions.go
@@ -42,7 +42,7 @@ var containersKillCmd = &cobra.Command{
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -70,7 +70,7 @@ var containersPauseCmd = &cobra.Command{
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -93,7 +93,7 @@ var containersUnpauseCmd = &cobra.Command{
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -117,7 +117,7 @@ var containersCommitCmd = &cobra.Command{
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -160,7 +160,7 @@ var containersEditCmd = &cobra.Command{
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -211,7 +211,7 @@ var containersAutoUpdateCmd = &cobra.Command{
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index eaa016012..444a63861 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -16,7 +16,6 @@ import (
"github.com/getarcaneapp/arcane/types/v2/updater"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
@@ -24,17 +23,17 @@ import (
)
var (
- containersLimit int
- containersStart int
- containersAll bool
- containersUpdatesFilter string
- containersStandalone string
- containersLabelFilter string
- containersIncludeInternal bool
- containersIncludeHidden bool
- containersDeleteVolumes bool
- forceFlag bool
- jsonOutput bool
+ 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
@@ -82,7 +81,7 @@ var containersUpdatesCmd = &cobra.Command{
}
func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -94,8 +93,8 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
if containersIncludeHidden {
query.Set("includeHidden", "true")
}
- if containersIncludeInternal {
- query.Set("includeInternal", "true")
+ if containersInclude {
+ query.Set("include", "true")
}
updatesFilter := strings.TrimSpace(containersUpdatesFilter)
if forceHasUpdateFilter {
@@ -131,58 +130,48 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
}
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
+ }
+ }
return []string{
shortID(item.ID),
containerSummaryName(item),
item.Image,
item.State,
- containerUpdateStatus(item),
- containerUpdateLatest(item),
+ status,
+ latest,
}
}
}
return cmdutil.RunList(cmd, c, spec)
}
-func containerUpdateStatus(item container.Summary) string {
- switch {
- case item.UpdateInfo == nil:
- return "unknown"
- case item.UpdateInfo.Error != "":
- return "error"
- case item.UpdateInfo.HasUpdate:
- return "has_update"
- default:
- return "up_to_date"
- }
-}
-
-func containerUpdateLatest(item container.Summary) string {
- if item.UpdateInfo == nil {
- return "-"
- }
- if strings.TrimSpace(item.UpdateInfo.LatestVersion) != "" {
- return item.UpdateInfo.LatestVersion
- }
- if strings.TrimSpace(item.UpdateInfo.LatestDigest) != "" {
- return item.UpdateInfo.LatestDigest
- }
- return "-"
-}
-
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 := client.NewFromConfig()
+ 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)
+ resolved, complete, err := ContainerRef.Resolve(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
return err
}
@@ -215,12 +204,12 @@ var containersStartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -240,12 +229,12 @@ var containersStopCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -265,12 +254,12 @@ var containersRestartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -290,12 +279,12 @@ var containersUpdateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -318,12 +307,12 @@ var containersRedeployCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -345,12 +334,12 @@ var containersDeleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- resolved, _, err := containerRef.Resolve(cmd.Context(), c, args[0], false)
+ resolved, _, err := ContainerRef.Resolve(cmd.Context(), c, args[0], false)
if err != nil {
return err
}
@@ -391,7 +380,7 @@ var containersCountsCmd = &cobra.Command{
Short: "Get container status counts",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -418,7 +407,7 @@ var containersCreateCmd = &cobra.Command{
Short: "Create a new container",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -528,6 +517,9 @@ var containersCreateCmd = &cobra.Command{
}
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)
@@ -568,7 +560,7 @@ func init() {
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(&containersIncludeInternal, "include-internal", false, "Include Arcane-internal 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)
@@ -610,62 +602,57 @@ func containerDisplayName(details *container.Details) string {
return ""
}
-var containerRef = cmdutil.ResourceRef[container.Details, container.Summary]{
- Singular: "container",
- Plural: "containers",
- IDHint: "the container ID",
- ListCmd: "arcane containers list",
- GetPath: types.Container,
- ListPath: types.Containers,
- Matches: containerMatches,
- Label: formatContainerOption,
- Promote: containerDetailsFromSummary,
- IDOf: func(item container.Summary) string { return item.ID },
-}
-
-func containerSummaryName(summary container.Summary) string {
- if len(summary.Names) == 0 {
- return ""
- }
- return strings.TrimPrefix(summary.Names[0], "/")
-}
-
-func containerDetailsFromSummary(summary container.Summary) *container.Details {
- return &container.Details{ID: summary.ID, Name: containerSummaryName(summary)}
-}
-
-func containerMatches(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) {
+var ContainerRef = cmdutil.ResourceRef[container.Details, container.Summary]{
+ EnvironmentScoped: true,
+ Singular: "container",
+ Plural: "containers",
+ IDHint: "the container ID",
+ ListCmd: "arcane containers list",
+ 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.EqualFold(trimmedName, original) || strings.EqualFold(name, original) {
+ if strings.Contains(idLower, identifierLower) {
return true
}
- }
- return false
+ 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
+ },
+ Label: func(item container.Summary) string {
+ name := ""
+ if len(item.Names) > 0 {
+ name = strings.TrimPrefix(item.Names[0], "/")
+ }
+ if name == "" {
+ name = shortID(item.ID)
+ }
+ image := cmp.Or(item.Image, "<unknown>")
+ state := cmp.Or(item.State, "unknown")
+ return fmt.Sprintf("%s (%s, %s)", name, shortID(item.ID), image+" / "+state)
+ },
+ Promote: func(summary container.Summary) *container.Details {
+ return &container.Details{ID: summary.ID, Name: containerSummaryName(summary)}
+ },
+ IDOf: func(item container.Summary) string { return item.ID },
}
-func formatContainerOption(item container.Summary) string {
- name := ""
- if len(item.Names) > 0 {
- name = strings.TrimPrefix(item.Names[0], "/")
- }
- if name == "" {
- name = shortID(item.ID)
+func containerSummaryName(summary container.Summary) string {
+ if len(summary.Names) == 0 {
+ return ""
}
- 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 strings.TrimPrefix(summary.Names[0], "/")
}
diff --git a/cli/pkg/containers/cmd_test.go b/cli/pkg/containers/cmd_test.go
new file mode 100644
index 000000000..935244c17
--- /dev/null
+++ b/cli/pkg/containers/cmd_test.go
@@ -0,0 +1,587 @@
+package containers_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
+
+func TestContainerStartSurfacesServerError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments/0/containers/abc123":
+ // Resolution succeeds so the action POST below is reached.
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"abc123","name":"nginx"}}`))
+ case r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/containers/abc123/start":
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ }
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "containers", "start", "abc123"},
+ )
+
+ require.Error(t, err,
+ "expected an error for a 403 start response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
+
+ require.Contains(t, err.Error(), "403",
+ "expected the error to mention status 403, got: %v", err)
+
+ require.NotContains(t, outBuf, "successfully",
+ "expected no success message on a denied start, got stdout=%s", outBuf)
+ for _, tc := range []struct {
+ name string
+ identifier string
+ duplicate bool
+ unavailable bool
+ search bool
+ prefix bool
+ explicit bool
+ }{
+ {name: "unique environment", identifier: "abc123"},
+ {name: "duplicate ID", identifier: "abc123", duplicate: true},
+ {name: "partial search", identifier: "abc123", unavailable: true},
+ {name: "name search", identifier: "nginx", search: true},
+ {name: "ID prefix fallback", identifier: "abcd", prefix: true},
+ {name: "explicit environment", identifier: "abc123", duplicate: true, explicit: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var mu sync.Mutex
+ var mutations []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/api/environments" {
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"0","name":"Local","enabled":true},{"id":"remote","name":"Remote","enabled":true}]}`))
+ return
+ }
+ if r.Method == http.MethodPost {
+ mu.Lock()
+ mutations = append(mutations, r.URL.Path)
+ mu.Unlock()
+ _, _ = w.Write([]byte(`{"success":true,"data":{"message":"started"}}`))
+ return
+ }
+ local := strings.Contains(r.URL.Path, "/0/")
+ if local && tc.unavailable {
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"error":"search denied"}`))
+ return
+ }
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/containers") && !local && (tc.search || tc.prefix && r.URL.Query().Get("search") == ""):
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"abcd1234","names":["/nginx"]}]}`))
+ return
+ case strings.HasSuffix(r.URL.Path, "/containers"):
+ _, _ = w.Write([]byte(`{"success":true,"data":[]}`))
+ return
+ case (!local || tc.duplicate) && !tc.search && !tc.prefix:
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"abc123","name":"nginx"}}`))
+ return
+ }
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ }))
+ defer server.Close()
+ path := testutil.WriteConfig(t, server.URL, true)
+ args := []string{"--config", path, "--json", "--yes"}
+ if tc.explicit {
+ args = append(args, "--env", "remote")
+ }
+ out, diagnostics, runErr := testutil.Execute(t, append(args, "containers", "start", tc.identifier))
+ mu.Lock()
+ paths := append([]string(nil), mutations...)
+ mu.Unlock()
+ if !tc.explicit && (tc.duplicate || tc.unavailable) {
+ require.ErrorContains(t, runErr, "pass --env")
+ require.Empty(t, paths)
+ require.Empty(t, out)
+ return
+ }
+ require.NoError(t, runErr, diagnostics)
+ resourceID := "abc123"
+ if tc.search || tc.prefix {
+ resourceID = "abcd1234"
+ }
+ require.Equal(t, []string{"/api/environments/remote/containers/" + resourceID + "/start"}, paths)
+ var result map[string]any
+ require.NoError(t, json.Unmarshal([]byte(out), &result), out)
+ require.NotContains(t, result, "environments")
+ })
+ }
+}
+
+func TestContainersListSendsLimitAndStart(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ preview, all bool
+ }{
+ {name: "saved environment"}, {name: "preview pagination", preview: true}, {name: "preview all", preview: true, all: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var mu sync.Mutex
+ queries := make(map[string]string)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/api/environments" {
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"0","name":"Local","enabled":true},{"id":"remote","name":"Remote","enabled":true}]}`))
+ return
+ }
+ mu.Lock()
+ queries[r.URL.Path] = r.URL.RawQuery
+ mu.Unlock()
+ _, _ = w.Write([]byte(`{"success":true,"data":[],"pagination":{"totalPages":4,"totalItems":20,"currentPage":3,"itemsPerPage":5}}`))
+ }))
+ defer server.Close()
+ args := []string{"--config", testutil.WriteConfig(t, server.URL, tc.preview), "containers", "list", "--json"}
+ if tc.all {
+ args = append(args, "--all")
+ } else {
+ args = append(args, "--limit", "5", "--start", "10")
+ }
+ out, diagnostics, err := testutil.Execute(t, args)
+ require.NoError(t, err, diagnostics)
+ mu.Lock()
+ defer mu.Unlock()
+ wantQuery := "limit=5&start=10"
+ if tc.all {
+ wantQuery = "limit=-1"
+ }
+ require.Equal(t, wantQuery, queries["/api/environments/0/containers"])
+ if tc.preview {
+ require.Len(t, queries, 2)
+ require.Equal(t, wantQuery, queries["/api/environments/remote/containers"])
+ } else {
+ require.Len(t, queries, 1)
+ }
+ require.True(t, json.Valid([]byte(out)))
+ require.Contains(t, out, "pagination")
+ })
+ }
+}
+
+func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {
+ var (
+ mu sync.Mutex
+ gotPath string
+ gotQuery string
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ gotPath = r.URL.Path
+ gotQuery = r.URL.RawQuery
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [],
+ "pagination": {"totalPages":2,"totalItems":26,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ _, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "containers", "list", "--json", "--start", "0"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ require.Equal(t, "/api/environments/0/containers", gotPath,
+ "path = %q, want %q", gotPath, "/api/environments/0/containers")
+
+ require.True(t, strings.Contains(gotQuery, "start=0") && strings.Contains(gotQuery, "limit=20"),
+ "query = %q, want start=0 and limit=20", gotQuery)
+}
+
+func TestContainersListTextShowsShowingSummary(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ command []string
+ preview, unavailable, empty, explicit bool
+ summary string
+ }{
+ {name: "single environment", summary: "Showing: 1/26 containers"},
+ {name: "combined environments", preview: true, summary: "Showing: 2/52 containers"},
+ {name: "partial failure", preview: true, unavailable: true, summary: "Showing: 1/26 containers"},
+ {name: "empty resources", preview: true, empty: true, summary: "Showing: 0/0 containers"},
+ {name: "explicit override", preview: true, explicit: true, summary: "Showing: 1/26 containers"},
+ {name: "custom jobs", preview: true, command: []string{"jobs", "list"}, summary: "Total: 2 jobs"},
+ {name: "custom settings", preview: true, command: []string{"settings", "list"}, summary: "Total: 2 settings"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.URL.Path == "/api/environments":
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"remote","name":"Remote","enabled":true},{"id":"0","name":"Local","enabled":true}]}`))
+ case tc.unavailable && strings.Contains(r.URL.Path, "/remote/"):
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"error":"resource denied"}`))
+ case tc.empty:
+ _, _ = w.Write([]byte(`{"success":true,"data":[],"pagination":{"totalItems":0}}`))
+ case strings.HasSuffix(r.URL.Path, "/jobs"):
+ _, _ = w.Write([]byte(`{"jobs":[{"id":"same-id","name":"nginx"}],"isAgent":false,"durableRuns":true}`))
+ case strings.HasSuffix(r.URL.Path, "/settings"):
+ _, _ = w.Write([]byte(`[{"key":"nginx","value":"dark","type":"string"}]`))
+ default:
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"same-id","names":["/nginx"],"image":"nginx:latest","state":"running","status":"Up 1 hour"}],"pagination":{"totalItems":26}}`))
+ }
+ }))
+ defer srv.Close()
+ configPath := testutil.WriteConfig(t, srv.URL, tc.preview)
+ args := []string{"--config", configPath, "--no-color"}
+ if tc.explicit {
+ args = append(args, "--env", "remote")
+ }
+ command := tc.command
+ if command == nil {
+ command = []string{"containers", "list"}
+ }
+ out, diagnostics, err := testutil.Execute(t, append(args, command...))
+ if tc.unavailable {
+ require.ErrorContains(t, err, "resource denied")
+ } else {
+ require.NoError(t, err, diagnostics)
+ }
+ require.Contains(t, out, tc.summary)
+ require.Equal(t, 1, strings.Count(out, tc.summary))
+ require.NotContains(t, out, "\x1b")
+ if !tc.preview || tc.explicit {
+ require.NotContains(t, out, "ENVIRONMENT")
+ return
+ }
+ require.Equal(t, 1, strings.Count(out, "ENVIRONMENT"), out)
+ require.Equal(t, 1, strings.Count(out, "TYPE")+strings.Count(out, "NAME"), out)
+ if tc.empty {
+ require.NotContains(t, out, "nginx")
+ return
+ }
+ require.Contains(t, out, "Local")
+ require.NotContains(t, out, "(0)")
+ require.NotContains(t, out, "(remote)")
+ if tc.unavailable {
+ require.NotContains(t, out, "Remote")
+ return
+ }
+ require.Contains(t, out, "Remote")
+ require.Equal(t, 2, strings.Count(out, "Local")+strings.Count(out, "Remote"))
+ })
+ }
+}
+
+func TestContainersListAllRequestsEveryItem(t *testing.T) {
+ var (
+ mu sync.Mutex
+ gotPath string
+ gotQuery string
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ gotPath = r.URL.Path
+ gotQuery = r.URL.RawQuery
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [],
+ "pagination": {"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":0}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ _, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "containers", "list", "--json", "--all"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ require.Equal(t, "/api/environments/0/containers", gotPath,
+ "path = %q, want %q", gotPath, "/api/environments/0/containers")
+
+ require.Equal(t, "limit=-1", gotQuery,
+ "query = %q, want %q", gotQuery, "limit=-1")
+}
+
+func TestContainersListJSONContract(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasPrefix(r.URL.Path, "/api/environments/0/containers") {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {"id":"abc123","names":["/nginx"],"image":"nginx:latest","state":"running","status":"Up 1 hour"}
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "--log-level", "debug", "containers", "list", "--json"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Contains(t, errOut, "Sending request")
+ require.NotContains(t, outBuf, "Sending request")
+ require.NotContains(t, outBuf, "\x1b")
+ var got map[string]any
+ {
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
+ }
+
+ for _, key := range []string{"success", "data", "pagination"} {
+ require.Contains(t, got, key)
+ }
+ for _, tc := range []struct {
+ name string
+ args []string
+ unavailable bool
+ empty bool
+ discoveryFailure bool
+ explicit bool
+ }{
+ {name: "preview retains envelopes"},
+ {name: "preview partial failure", unavailable: true},
+ {name: "preview empty", empty: true},
+ {name: "preview discovery failure", discoveryFailure: true},
+ {name: "preview explicit override", explicit: true},
+ {name: "preview custom job response", args: []string{"jobs", "list"}},
+ {name: "preview settings response", args: []string{"settings", "list"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var mu sync.Mutex
+ var requested []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ requested = append(requested, r.URL.Path)
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.URL.Path == "/api/environments" && tc.discoveryFailure:
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"error":"discovery denied"}`))
+ return
+ case r.URL.Path == "/api/environments" && tc.empty:
+ _, _ = w.Write([]byte(`{"success":true,"data":[]}`))
+ return
+ case r.URL.Path == "/api/environments":
+ assert.Equal(t, "-1", r.URL.Query().Get("limit"))
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"remote","name":"Remote","enabled":true},{"id":"disabled","name":"Disabled","enabled":false},{"id":"0","name":"Local","enabled":true}]}`))
+ return
+ case tc.unavailable && strings.Contains(r.URL.Path, "/remote/"):
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"error":"resource denied"}`))
+ return
+ case strings.HasSuffix(r.URL.Path, "/jobs"):
+ _, _ = w.Write([]byte(`{"jobs":[],"isAgent":false,"durableRuns":true}`))
+ case strings.HasSuffix(r.URL.Path, "/settings"):
+ _, _ = w.Write([]byte(`[{"key":"theme","value":"dark","type":"string"}]`))
+ default:
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"same-id","names":["/nginx"]}],"pagination":{"totalItems":1},"counts":{"running":1},"groups":["preserved"]}`))
+ }
+ }))
+ defer server.Close()
+ path := testutil.WriteConfig(t, server.URL, true)
+ args := []string{"--config", path, "--json"}
+ if tc.explicit {
+ args = append(args, "--env", "remote")
+ }
+ command := tc.args
+ if command == nil {
+ command = []string{"containers", "list"}
+ }
+ out, diagnostics, runErr := testutil.Execute(t, append(args, command...))
+ if tc.discoveryFailure {
+ require.ErrorContains(t, runErr, "discovery denied")
+ require.Empty(t, out)
+ return
+ }
+ if tc.unavailable {
+ require.ErrorContains(t, runErr, "resource denied")
+ } else {
+ require.NoError(t, runErr, diagnostics)
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Environments []struct {
+ ID string `json:"environmentId"`
+ Result json.RawMessage `json:"result"`
+ Error string `json:"error"`
+ } `json:"environments"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(out), &result), out)
+ mu.Lock()
+ paths := append([]string(nil), requested...)
+ mu.Unlock()
+ if tc.explicit {
+ require.NotContains(t, paths, "/api/environments")
+ require.Empty(t, result.Environments)
+ require.Contains(t, out, "counts")
+ return
+ }
+ require.Equal(t, !tc.unavailable, result.Success)
+ require.NotContains(t, strings.Join(paths, ","), "disabled")
+ if tc.empty {
+ require.Empty(t, result.Environments)
+ require.Len(t, paths, 1)
+ return
+ }
+ require.Len(t, result.Environments, 2)
+ require.Equal(t, "0", result.Environments[0].ID)
+ require.Equal(t, "remote", result.Environments[1].ID)
+ if tc.unavailable {
+ require.NotEmpty(t, result.Environments[1].Error)
+ require.Empty(t, result.Environments[1].Result)
+ }
+ if tc.args == nil {
+ require.Contains(t, string(result.Environments[0].Result), "counts")
+ require.Contains(t, string(result.Environments[0].Result), "groups")
+ }
+ require.NotContains(t, out, "Selected")
+ })
+ }
+}
+
+func TestContainersListUpdatesJSONContract(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/containers" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"abc123",
+ "names":["/nginx"],
+ "image":"nginx:latest",
+ "state":"running",
+ "status":"Up 1 hour",
+ "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "containers", "list", "--updates", "has_update", "--json"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ var got map[string]any
+ {
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
+ }
+
+ for _, key := range []string{"success", "data", "pagination"} {
+ {
+ _, ok := got[key]
+ require.True(t, ok,
+ "missing key %q in output: %v", key, got)
+ }
+ }
+}
+
+func TestContainersUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/containers" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"abc123",
+ "names":["/nginx"],
+ "image":"nginx:latest",
+ "state":"running",
+ "status":"Up 1 hour",
+ "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "--output", "text", "containers", "updates"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ require.NotEmpty(t, strings.TrimSpace(outBuf),
+ "expected output from containers updates command")
+}
diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.go
index 8cce2cde2..2a05999a6 100644
--- a/cli/pkg/gitops/cmd.go
+++ b/cli/pkg/gitops/cmd.go
@@ -8,7 +8,6 @@ import (
"github.com/getarcaneapp/arcane/types/v2/gitops"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
@@ -48,7 +47,7 @@ var listCmd = &cobra.Command{
Short: "List GitOps syncs",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -90,7 +89,7 @@ var createCmd = &cobra.Command{
Short: "Create a new GitOps sync",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -135,7 +134,7 @@ var getCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -185,7 +184,7 @@ var updateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -240,7 +239,7 @@ var deleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -285,7 +284,7 @@ var statusCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -332,7 +331,7 @@ var syncCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -370,7 +369,7 @@ var filesCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -407,7 +406,7 @@ var importCmd = &cobra.Command{
Short: "Import a GitOps sync configuration",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -452,6 +451,9 @@ var importCmd = &cobra.Command{
}
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)
@@ -525,13 +527,26 @@ func init() {
}
var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
- Singular: "gitops sync",
- Plural: "gitops syncs",
- IDHint: "the sync ID",
- ListCmd: "arcane gitops list",
- GetPath: types.GitOpsSync,
- ListPath: types.GitOpsSyncs,
- Matches: gitOpsSyncMatches,
+ EnvironmentScoped: true,
+ Singular: "gitops sync",
+ Plural: "gitops syncs",
+ IDHint: "the sync ID",
+ ListCmd: "arcane gitops list",
+ GetPath: types.GitOpsSync,
+ 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)
+ },
Label: func(match gitops.GitOpsSync) string {
lastStatus := "-"
if match.LastSyncStatus != nil {
@@ -542,20 +557,6 @@ var gitopsSyncRef = cmdutil.ResourceRef[gitops.GitOpsSync, gitops.GitOpsSync]{
Promote: func(match gitops.GitOpsSync) *gitops.GitOpsSync { return &match },
}
-func gitOpsSyncMatches(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)
-}
-
func flattenFileTree(nodes []gitops.FileTreeNode, depth int) [][]string {
var rows [][]string
for _, node := range nodes {
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index ddcfa763c..909bdbeb9 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -559,6 +559,10 @@ var imagesUploadCmd = &cobra.Command{
}
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)
@@ -582,19 +586,25 @@ func init() {
ImagesCmd.AddCommand(imagesCountsCmd)
ImagesCmd.AddCommand(updates.UpdatesCmd)
+ for _, command := range updates.UpdatesCmd.Commands() {
+ if command.Name() == "check-image" {
+ cmdutil.SetResource(ImageRef, command)
+ }
+ }
ImagesCmd.AddCommand(imagesUploadCmd)
}
var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
- Singular: "image",
- Plural: "images",
- IDHint: "the image ID",
- ListCmd: "arcane images list",
- GetPath: types.Image,
- ListPath: types.Images,
- SearchCandidates: searchImageCandidatesInternal,
- Matches: imageMatches,
+ EnvironmentScoped: true,
+ Singular: "image",
+ Plural: "images",
+ IDHint: "the image ID",
+ ListCmd: "arcane images list",
+ GetPath: types.Image,
+ ListPath: types.Images,
+ SearchCandidates: searchImageCandidates,
+ Matches: imageMatches,
Label: func(match image.Summary) string {
label := match.ID
if len(match.RepoTags) > 0 {
@@ -613,7 +623,8 @@ var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
Size: match.Size,
}
},
- IDOf: func(match image.Summary) string { return match.ID },
+ IDOf: func(match image.Summary) string { return match.ID },
+ IdentifierOf: func(details image.DetailSummary) string { return details.ID },
Validate: func(details image.DetailSummary, identifier string) error {
if details.ID == "" {
return fmt.Errorf("image lookup for %q returned empty ID", identifier)
@@ -622,8 +633,17 @@ var ImageRef = cmdutil.ResourceRef[image.DetailSummary, image.Summary]{
},
}
-func searchImageCandidatesInternal(ctx context.Context, c *client.Client, identifier string) ([]image.Summary, error) {
- terms := imageSearchTermsInternal(identifier)
+func searchImageCandidates(ctx context.Context, c *client.Client, identifier string) ([]image.Summary, error) {
+ terms := []string{identifier}
+ separator := ":"
+ if strings.Contains(identifier, "@") {
+ separator = "@"
+ }
+ 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)
@@ -656,23 +676,6 @@ func searchImageCandidatesInternal(ctx context.Context, c *client.Client, identi
return nil, nil
}
-func imageSearchTermsInternal(identifier string) []string {
- terms := []string{identifier}
- identifierLower := strings.ToLower(identifier)
- if strings.Contains(identifier, "@") {
- if repository, _, ok := strings.Cut(identifier, "@"); ok && repository != "" {
- terms = append(terms, repository)
- }
- return terms
- }
- if strings.Contains(identifier, ":") && !strings.HasPrefix(identifierLower, "sha256:") {
- if repository, _, ok := strings.Cut(identifier, ":"); ok && repository != "" {
- terms = append(terms, repository)
- }
- }
- return terms
-}
-
func imageMatches(item image.Summary, identifierLower, original string) bool {
hasSeparator := strings.Contains(original, ":") || strings.Contains(original, "@")
diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.go
index 8533a851e..6cf4a3c0b 100644
--- a/cli/pkg/images/extra.go
+++ b/cli/pkg/images/extra.go
@@ -60,10 +60,9 @@ var imagesSearchCmd = &cobra.Command{
rows = append(rows, []string{item.Name, truncateCell(item.Description, 60), strconv.Itoa(item.StarCount), official})
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "results", Total: int64(len(result.Data)), Paginated: true}); tableErr != nil {
return tableErr
}
- output.Showing(len(result.Data), int64(len(result.Data)), "results")
return nil
},
@@ -126,7 +125,7 @@ var imagesHistoryCmd = &cobra.Command{
rows = append(rows, []string{created, truncateCell(item.CreatedBy, 60), output.Bytes(item.Size), truncateCell(item.Comment, 30)})
}
- return output.Table(headers, rows)
+ return cmdutil.PrintTable(cmd, headers, rows)
},
}
@@ -151,7 +150,10 @@ var imagesTagCmd = &cobra.Command{
}
imageID := resolved.ID
- repository, tag := splitImageRef(args[1])
+ 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")
}
@@ -212,7 +214,8 @@ var imagesExportCmd = &cobra.Command{
}
imageID := resolved.ID
- outputFile := exportFileName(args[0])
+ name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(strings.TrimSpace(args[0]))
+ outputFile := cmp.Or(strings.Trim(name, "._-"), "image") + ".tar"
if len(args) == 2 {
outputFile = args[1]
}
@@ -350,7 +353,7 @@ var imagesAttestationsCmd = &cobra.Command{
rows = append(rows, []string{att.PredicateType, att.Platform, truncateCell(att.Digest, 19), output.Bytes(att.Size)})
}
_, _ = fmt.Fprintln(output.Stdout())
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows); tableErr != nil {
return tableErr
}
@@ -522,12 +525,20 @@ var imagesBuildsCmd = &cobra.Command{
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()
+ }
return []string{
record.ID,
- buildImageLabel(record),
+ label,
output.TintStatus(record.Status),
record.CreatedAt.Format(time.RFC3339),
- buildDurationLabel(record.DurationMs),
+ duration,
}
},
})
@@ -598,7 +609,11 @@ var imagesBuildsGetCmd = &cobra.Command{
if record.CompletedAt != nil {
output.KeyValue("Completed", record.CompletedAt.Format(time.RFC3339))
}
- output.KeyValue("Duration", buildDurationLabel(record.DurationMs))
+ 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)
}
@@ -618,39 +633,6 @@ var imagesBuildsGetCmd = &cobra.Command{
},
}
-func buildImageLabel(record image.BuildRecord) string {
- if len(record.Tags) > 0 {
- return record.Tags[0]
- }
- return truncateCell(record.ContextDir, 40)
-}
-
-func buildDurationLabel(durationMs *int64) string {
- if durationMs == nil {
- return ""
- }
- return (time.Duration(*durationMs) * time.Millisecond).Round(time.Second).String()
-}
-
-// splitImageRef splits an image reference into repository and tag. The tag is
-// only split off when the text after the final colon contains no slash, so
-// registry ports (registry:5000/repo) stay part of the repository.
-func splitImageRef(ref string) (string, string) {
- ref = strings.TrimSpace(ref)
- if idx := strings.LastIndex(ref, ":"); idx > 0 && !strings.Contains(ref[idx+1:], "/") {
- return ref[:idx], ref[idx+1:]
- }
- return ref, ""
-}
-
-// exportFileName mirrors the server's default export filename for an image
-// reference, replacing separators with underscores.
-func exportFileName(imageName string) string {
- name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(strings.TrimSpace(imageName))
- name = cmp.Or(strings.Trim(name, "._-"), "image")
- return name + ".tar"
-}
-
func truncateCell(value string, limit int) string {
value = strings.ReplaceAll(value, "\n", " ")
if limit > 3 && len(value) > limit {
@@ -660,6 +642,10 @@ func truncateCell(value string, limit int) string {
}
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)
@@ -696,3 +682,13 @@ func init() {
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 },
+}
diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.go
index 062157566..91d923ef5 100644
--- a/cli/pkg/images/updates/cmd.go
+++ b/cli/pkg/images/updates/cmd.go
@@ -10,9 +10,9 @@ import (
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
"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/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
@@ -26,8 +26,8 @@ var UpdatesCmd = &cobra.Command{
var checkAll bool
-// checkAllBodyInternal is an empty JSON object; older servers reject check-all without a body.
-var checkAllBodyInternal = struct{}{}
+// 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...]",
@@ -37,7 +37,7 @@ var checkCmd = &cobra.Command{
Args: cobra.ArbitraryArgs,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -47,11 +47,11 @@ var checkCmd = &cobra.Command{
return errors.New("--all cannot be combined with image references")
}
- result, checkAllUpdatesErr := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), checkAllBodyInternal)
+ 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)
}
- return printBatchResultsInternal(result.Data)
+ return printBatchResults(cmd, result.Data)
}
if len(args) == 0 {
@@ -63,7 +63,7 @@ var checkCmd = &cobra.Command{
if checkBatchUpdatesErr != nil {
return fmt.Errorf("failed to check updates: %w", checkBatchUpdatesErr)
}
- return printBatchResultsInternal(result.Data)
+ return printBatchResults(cmd, result.Data)
}
result, err := c.GetJSON[imageupdate.Response](cmd.Context(), types.ImageUpdatesCheck(c.EnvID(), args[0]))
@@ -71,6 +71,10 @@ var checkCmd = &cobra.Command{
return fmt.Errorf("failed to check updates: %w", err)
}
+ 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 jsonOutput {
return cmdutil.PrintJSON(result.Data)
}
@@ -95,31 +99,17 @@ var checkAllCmd = &cobra.Command{
Short: "Check all images for updates",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), checkAllBodyInternal)
+ 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)
}
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Header("Check All Results")
- updatesAvailable := 0
- for imageRef, update := range result.Data {
- if update != nil && update.HasUpdate {
- output.KeyValue(imageRef, fmt.Sprintf("%s → %s (%s)", update.CurrentVersion, update.LatestVersion, update.UpdateType))
- updatesAvailable++
- }
- }
-
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d images checked, %d updates available\n", len(result.Data), updatesAvailable)
- return nil
+ return printBatchResults(cmd, result.Data)
},
}
@@ -130,7 +120,7 @@ var checkImageCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -162,7 +152,7 @@ var summaryCmd = &cobra.Command{
Short: "Get image updates summary",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -185,9 +175,19 @@ var summaryCmd = &cobra.Command{
},
}
-// printBatchResultsInternal prints every requested reference, including
+// printBatchResults prints every requested reference, including
// up-to-date and failed checks.
-func printBatchResultsInternal(result imageupdate.BatchResponse) error {
+func printBatchResults(cmd *cobra.Command, result imageupdate.BatchResponse) error {
+ if app, ok := runtime.From(cmd.Context()); ok && app != nil && app.FleetConfirmed {
+ for ref, update := range result {
+ if update == nil {
+ return fmt.Errorf("image update check failed for %s: no result", ref)
+ }
+ if update.Error != "" {
+ return fmt.Errorf("image update check failed for %s: %s", ref, update.Error)
+ }
+ }
+ }
if jsonOutput {
return cmdutil.PrintJSON(result)
}
@@ -215,7 +215,7 @@ func printBatchResultsInternal(result imageupdate.BatchResponse) error {
rows = append(rows, []string{imageRef, "No", update.CurrentVersion, "", ""})
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows); tableErr != nil {
return tableErr
}
_, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d images checked, %d updates available\n", len(result), updatesAvailable)
@@ -223,6 +223,8 @@ func printBatchResultsInternal(result imageupdate.BatchResponse) error {
}
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)
diff --git a/cli/internal/integrationtest/updates_commands_test.go b/cli/pkg/images/updates/cmd_test.go
similarity index 50%
rename from cli/internal/integrationtest/updates_commands_test.go
rename to cli/pkg/images/updates/cmd_test.go
index 4e671a102..96389d5cd 100644
--- a/cli/internal/integrationtest/updates_commands_test.go
+++ b/cli/pkg/images/updates/cmd_test.go
@@ -1,4 +1,4 @@
-package integrationtest
+package updates_test
import (
"encoding/json"
@@ -9,217 +9,9 @@ import (
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
"github.com/stretchr/testify/require"
-)
-
-func TestContainersListUpdatesJSONContract(t *testing.T) {
- seenUpdatesFilter := ""
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/environments/0/containers" {
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- return
- }
-
- seenUpdatesFilter = r.URL.Query().Get("updates")
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {
- "id":"abc123",
- "names":["/nginx"],
- "image":"nginx:latest",
- "state":"running",
- "status":"Up 1 hour",
- "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
- }
- ],
- "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "containers", "list", "--updates", "has_update", "--json"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Equal(t, "has_update", seenUpdatesFilter,
- "expected updates filter query param, got %q", seenUpdatesFilter)
-
- var got map[string]any
- {
- unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, unmarshalErr,
- "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
- }
-
- for _, key := range []string{"success", "data", "pagination"} {
- {
- _, ok := got[key]
- require.True(t, ok,
- "missing key %q in output: %v", key, got)
- }
- }
-}
-
-func TestContainersUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
- seenUpdatesFilter := ""
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/environments/0/containers" {
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- return
- }
-
- seenUpdatesFilter = r.URL.Query().Get("updates")
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {
- "id":"abc123",
- "names":["/nginx"],
- "image":"nginx:latest",
- "state":"running",
- "status":"Up 1 hour",
- "updateInfo":{"hasUpdate":true,"latestVersion":"1.28.0"}
- }
- ],
- "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "--output", "text", "containers", "updates"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Equal(t, "has_update", seenUpdatesFilter,
- "expected updates filter query param, got %q", seenUpdatesFilter)
-
- require.NotEmpty(t, strings.TrimSpace(outBuf),
- "expected output from containers updates command")
-}
-func TestProjectsListUpdatesJSONContract(t *testing.T) {
- seenUpdatesFilter := ""
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/environments/0/projects" {
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- return
- }
-
- seenUpdatesFilter = r.URL.Query().Get("updates")
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {
- "id":"project-1",
- "name":"demo",
- "path":"/tmp/demo",
- "status":"running",
- "serviceCount":1,
- "runningCount":1,
- "createdAt":"2026-04-02T00:00:00Z",
- "updatedAt":"2026-04-02T00:00:00Z",
- "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
- }
- ],
- "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "projects", "list", "--updates", "has_update", "--json"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Equal(t, "has_update", seenUpdatesFilter,
- "expected updates filter query param, got %q", seenUpdatesFilter)
-
- var got map[string]any
- {
- unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, unmarshalErr,
- "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
- }
-
- for _, key := range []string{"success", "data", "pagination"} {
- {
- _, ok := got[key]
- require.True(t, ok,
- "missing key %q in output: %v", key, got)
- }
- }
-}
-
-func TestProjectsUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
- seenUpdatesFilter := ""
-
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/environments/0/projects" {
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- return
- }
-
- seenUpdatesFilter = r.URL.Query().Get("updates")
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {
- "id":"project-1",
- "name":"demo",
- "path":"/tmp/demo",
- "status":"running",
- "serviceCount":1,
- "runningCount":1,
- "createdAt":"2026-04-02T00:00:00Z",
- "updatedAt":"2026-04-02T00:00:00Z",
- "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
- }
- ],
- "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "--output", "text", "projects", "updates"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Equal(t, "has_update", seenUpdatesFilter,
- "expected updates filter query param, got %q", seenUpdatesFilter)
-
- require.NotEmpty(t, strings.TrimSpace(outBuf),
- "expected output from projects updates command")
-}
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T) {
imageRef := "registry.example.com/team/image:latest&debug=true"
@@ -250,8 +42,8 @@ func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T)
}))
defer srv.Close()
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
t,
[]string{"--config", configPath, "images", "updates", "check", imageRef, "--json"},
)
@@ -280,7 +72,7 @@ func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T)
}
func TestImagesUpdatesCheckRequiresImageRef(t *testing.T) {
- outBuf, _, err := executeCLIIntegrationCommandInternal(t, []string{"images", "updates", "check"})
+ outBuf, _, err := testutil.Execute(t, []string{"images", "updates", "check"})
require.Error(t, err,
"expected missing image reference to fail, got output %q", outBuf)
@@ -293,6 +85,14 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments":
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"0","name":"Local","enabled":true},{"id":"remote","name":"Remote","enabled":true}]}`))
+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments/0/images":
+ _, _ = w.Write([]byte(`{"success":true,"data":[]}`))
+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments/remote/images":
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"image-prefix-123","repoTags":["nginx:latest"]}]}`))
+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments/remote/image-updates/check/image-prefix-123":
+ _, _ = w.Write([]byte(`{"success":true,"data":{"hasUpdate":false,"currentVersion":"remote-version"}}`))
case r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/image-updates/check-all":
_, _ = w.Write([]byte(`{
"success": true,
@@ -335,8 +135,8 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
}))
defer srv.Close()
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
t,
[]string{"--config", configPath, "images", "updates", "check-all", "--json"},
)
@@ -354,7 +154,7 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
require.False(t, batch["nginx:latest"] == nil || !batch["nginx:latest"].HasUpdate,
"unexpected batch response: %+v", batch)
- outBuf, errOut, err = executeCLIIntegrationCommandInternal(
+ outBuf, errOut, err = testutil.Execute(
t,
[]string{"--config", configPath, "images", "updates", "check-image", "image-123", "--json"},
)
@@ -372,7 +172,7 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
require.False(t, single.HasUpdate || single.CurrentVersion != "1.1.0",
"unexpected image response: %+v", single)
- outBuf, errOut, err = executeCLIIntegrationCommandInternal(
+ outBuf, errOut, err = testutil.Execute(
t,
[]string{"--config", configPath, "images", "updates", "summary", "--json"},
)
@@ -389,6 +189,13 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
require.False(t, summary.TotalImages != 4 || summary.ImagesWithUpdates != 2 || summary.DigestUpdates != 1,
"unexpected summary response: %+v", summary)
+
+ previewPath := testutil.WriteConfig(t, srv.URL, true)
+ outBuf, errOut, err = testutil.Execute(t, []string{"--config", previewPath, "images", "updates", "check-image", "image-prefix", "--json"})
+ require.NoError(t, err, errOut)
+ require.NoError(t, json.Unmarshal([]byte(outBuf), &single))
+ require.Equal(t, "remote-version", single.CurrentVersion)
+ require.Contains(t, errOut, "Remote (remote)")
}
func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {
@@ -430,11 +237,11 @@ func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {
}))
defer srv.Close()
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
+ configPath := testutil.WriteConfig(t, srv.URL)
for _, command := range commands {
t.Run(command.name, func(t *testing.T) {
args := append([]string{"--config", configPath}, command.args...)
- outBuf, _, err := executeCLIIntegrationCommandInternal(t, args)
+ outBuf, _, err := testutil.Execute(t, args)
require.Error(t, err,
"expected %s error, got success with output %q", failure.name, outBuf)
diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.go
index 7fc452a85..ec5b40e7b 100644
--- a/cli/pkg/jobs/cmd.go
+++ b/cli/pkg/jobs/cmd.go
@@ -1,11 +1,14 @@
package jobs
import (
+ "context"
"crypto/rand"
"errors"
"fmt"
"net/http"
+ "slices"
"strconv"
+ "strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/jobschedule"
@@ -39,7 +42,7 @@ var getCmd = &cobra.Command{
Short: "Get configured job schedule intervals",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -72,7 +75,7 @@ var updateCmd = &cobra.Command{
Short: "Update job schedule intervals",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -146,10 +149,9 @@ var listCmd = &cobra.Command{
}
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "jobs"}); tableErr != nil {
return tableErr
}
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d jobs\n", len(result.Jobs))
return nil
},
}
@@ -193,6 +195,10 @@ var runCmd = &cobra.Command{
}
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)
@@ -209,3 +215,16 @@ func init() {
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)")
}
+
+var jobRef = cmdutil.ResourceRef[jobschedule.JobStatus, jobschedule.JobStatus]{
+ EnvironmentScoped: true, Singular: "job", Plural: "jobs", IDHint: "the job ID", ListCmd: "arcane-cli jobs list",
+ SearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]jobschedule.JobStatus, error) {
+ result, err := c.DoJSON[jobschedule.JobListResponse](ctx, http.MethodGet, types.Jobs(c.EnvID()), nil)
+ if err != nil {
+ return nil, err
+ }
+ 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 },
+}
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index 92b440c74..7c5cf2ecb 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -10,11 +10,12 @@ import (
"github.com/getarcaneapp/arcane/types/v2/network"
"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/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 (
@@ -33,7 +34,7 @@ var (
networkCreateSubnet string
networkCreateGateway string
networkCreateIPRange string
- networkCreateInternal bool
+ networkCreate bool
networkCreateAttachable bool
networkCreateIPv6 bool
networkCreateLabels []string
@@ -64,7 +65,7 @@ var listCmd = &cobra.Command{
if inUseOnlyFlag && unusedOnlyFlag {
return errors.New("--inuse and --unused cannot be used together")
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -116,7 +117,7 @@ var getCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -160,7 +161,7 @@ var deleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -205,7 +206,7 @@ var countsCmd = &cobra.Command{
Short: "Get network usage counts",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -243,7 +244,7 @@ var pruneCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -269,7 +270,7 @@ var createCmd = &cobra.Command{
Short: "Create a network",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -278,7 +279,7 @@ var createCmd = &cobra.Command{
Name: networkCreateName,
Options: network.CreateOptions{
Driver: networkCreateDriver,
- Internal: networkCreateInternal,
+ Internal: networkCreate,
Attachable: networkCreateAttachable,
EnableIPv6: networkCreateIPv6,
},
@@ -343,14 +344,25 @@ var connectCmd = &cobra.Command{
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
+ }
+ containerID = dependent.ID
+ }
+
req := network.ConnectContainerRequest{
- ContainerID: args[1],
+ ContainerID: containerID,
Aliases: connectAliases,
IPv4Address: connectIPv4,
IPv6Address: connectIPv6,
@@ -385,14 +397,25 @@ var disconnectCmd = &cobra.Command{
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
+ }
+ containerID = dependent.ID
+ }
+
req := network.DisconnectContainerRequest{
- ContainerID: args[1],
+ ContainerID: containerID,
Force: disconnectForce,
}
@@ -472,11 +495,15 @@ var topologyCmd = &cobra.Command{
}
rows[i] = []string{source, target, edge.IPv4Address, edge.IPv6Address}
}
- return output.Table(headers, rows)
+ 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)
@@ -515,7 +542,7 @@ func init() {
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(&networkCreateInternal, "internal", false, "Restrict external access to the network")
+ 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)")
@@ -545,13 +572,26 @@ func shortID(id string) string {
}
var networkRef = cmdutil.ResourceRef[network.Inspect, network.Summary]{
- Singular: "network",
- Plural: "networks",
- IDHint: "the network ID",
- ListCmd: "arcane networks list",
- GetPath: types.Network,
- ListPath: types.Networks,
- Matches: networkMatches,
+ EnvironmentScoped: true,
+ Singular: "network",
+ Plural: "networks",
+ IDHint: "the network ID",
+ ListCmd: "arcane networks list",
+ GetPath: types.Network,
+ 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)
+ },
Label: func(match network.Summary) string {
return fmt.Sprintf("%s (%s)", match.Name, shortID(match.ID))
},
@@ -567,17 +607,3 @@ var networkRef = cmdutil.ResourceRef[network.Inspect, network.Summary]{
}
},
}
-
-func networkMatches(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)
-}
diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.go
index 1ea24a44e..878c0075d 100644
--- a/cli/pkg/projects/actions.go
+++ b/cli/pkg/projects/actions.go
@@ -50,13 +50,12 @@ var tagsCmd = &cobra.Command{
return cmdutil.PrintJSON(result.Data)
}
- output.Header("Project Tags")
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 output.Table(headers, rows)
+ return cmdutil.PrintTable(cmd, headers, rows)
},
}
@@ -197,7 +196,7 @@ var buildCmd = &cobra.Command{
return fmt.Errorf("failed to build project images: %w", ensureSuccessStatusErr)
}
- if printOperationStreamErr := printOperationStreamInternal(resp.Body); printOperationStreamErr != nil {
+ if printOperationStreamErr := printOperationStream(resp.Body); printOperationStreamErr != nil {
return fmt.Errorf("failed to build project images: %w", printOperationStreamErr)
}
@@ -331,6 +330,7 @@ var workspaceDownloadCmd = &cobra.Command{
}
func init() {
+ cmdutil.SetScope(cmdutil.ScopeRead, tagsCmd)
ProjectsCmd.AddCommand(tagsCmd)
ProjectsCmd.AddCommand(tagCmd)
ProjectsCmd.AddCommand(archiveCmd)
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 2e4e0b6ab..f0007893e 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -21,7 +21,6 @@ import (
workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
@@ -77,7 +76,7 @@ var updatesCmd = &cobra.Command{
}
func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -135,11 +134,15 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
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,
- projectUpdateStatus(proj),
+ status,
strconv.Itoa(imageCount),
strconv.Itoa(updatedCount),
}
@@ -148,13 +151,6 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
return cmdutil.RunList(cmd, c, spec)
}
-func projectUpdateStatus(item project.Details) string {
- if item.UpdateInfo == nil || strings.TrimSpace(item.UpdateInfo.Status) == "" {
- return "unknown"
- }
- return item.UpdateInfo.Status
-}
-
var destroyCmd = &cobra.Command{
Use: "destroy <project-id|name>",
Aliases: []string{"rm", "remove"},
@@ -162,7 +158,7 @@ var destroyCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -210,7 +206,7 @@ var getCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -263,7 +259,7 @@ var downCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -287,7 +283,7 @@ var restartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -333,9 +329,7 @@ var pullCmd = &cobra.Command{
},
}
-// projectStreamActionConfig describes a project action whose endpoint responds
-// with an NDJSON operation stream: {"log":"<raw docker CLI line>"} frames are
-// printed as-is and a terminal {"error":"..."} frame fails the command.
+// projectStreamActionConfig defines an NDJSON action that prints raw logs and returns terminal errors.
type projectStreamActionConfig struct {
endpoint func(string, string) string
failureMessage string
@@ -343,7 +337,7 @@ type projectStreamActionConfig struct {
}
func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectStreamActionConfig) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -365,7 +359,7 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectSt
return fmt.Errorf("%s: %w", cfg.failureMessage, ensureSuccessStatusErr)
}
- if printOperationStreamErr := printOperationStreamInternal(resp.Body); printOperationStreamErr != nil {
+ if printOperationStreamErr := printOperationStream(resp.Body); printOperationStreamErr != nil {
return fmt.Errorf("%s: %w", cfg.failureMessage, printOperationStreamErr)
}
@@ -373,10 +367,8 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectSt
return nil
}
-// printOperationStreamInternal consumes an NDJSON operation stream, printing
-// raw docker CLI log lines to stdout. A terminal error frame is returned as an
-// error; unknown frames (e.g. the activity envelope) are skipped.
-func printOperationStreamInternal(body io.Reader) error {
+// printOperationStream prints NDJSON Docker logs and returns terminal errors, ignoring unknown frames.
+func printOperationStream(body io.Reader) error {
scanner := bufio.NewScanner(body)
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
@@ -413,7 +405,7 @@ var createCmd = &cobra.Command{
Short: "Create a new project from a Docker Compose file",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -493,7 +485,7 @@ var updateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -546,7 +538,7 @@ var updateIncludesCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -626,7 +618,7 @@ var countsCmd = &cobra.Command{
Short: "Get project counts",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -649,6 +641,9 @@ var countsCmd = &cobra.Command{
}
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)
@@ -710,32 +705,31 @@ func init() {
}
var projectRef = cmdutil.ResourceRef[project.Details, project.Details]{
- Singular: "project",
- Plural: "projects",
- IDHint: "the project ID",
- ListCmd: "arcane projects list",
- GetPath: types.Project,
- ListPath: types.Projects,
- Matches: projectMatches,
+ EnvironmentScoped: true,
+ Singular: "project",
+ Plural: "projects",
+ IDHint: "the project ID",
+ ListCmd: "arcane projects list",
+ GetPath: types.Project,
+ 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)
+ },
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 },
}
-
-func projectMatches(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)
-}
diff --git a/cli/pkg/projects/cmd_test.go b/cli/pkg/projects/cmd_test.go
new file mode 100644
index 000000000..dfff87c17
--- /dev/null
+++ b/cli/pkg/projects/cmd_test.go
@@ -0,0 +1,158 @@
+package projects_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
+
+func TestProjectsListAllIncludesArchived(t *testing.T) {
+ var (
+ mu sync.Mutex
+ gotQuery string
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ gotQuery = r.URL.RawQuery
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [],
+ "pagination": {"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":0}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ _, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "projects", "list", "--json", "--all"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ require.Equal(t, "archived=all&limit=-1", gotQuery,
+ "query = %q, want %q", gotQuery, "archived=all&limit=-1")
+}
+
+func TestProjectsListUpdatesJSONContract(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/projects" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"project-1",
+ "name":"demo",
+ "path":"/tmp/demo",
+ "status":"running",
+ "serviceCount":1,
+ "runningCount":1,
+ "createdAt":"2026-04-02T00:00:00Z",
+ "updatedAt":"2026-04-02T00:00:00Z",
+ "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "projects", "list", "--updates", "has_update", "--json"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ var got map[string]any
+ {
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
+ }
+
+ for _, key := range []string{"success", "data", "pagination"} {
+ {
+ _, ok := got[key]
+ require.True(t, ok,
+ "missing key %q in output: %v", key, got)
+ }
+ }
+}
+
+func TestProjectsUpdatesCommandUsesHasUpdateFilter(t *testing.T) {
+ seenUpdatesFilter := ""
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/environments/0/projects" {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ return
+ }
+
+ seenUpdatesFilter = r.URL.Query().Get("updates")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {
+ "id":"project-1",
+ "name":"demo",
+ "path":"/tmp/demo",
+ "status":"running",
+ "serviceCount":1,
+ "runningCount":1,
+ "createdAt":"2026-04-02T00:00:00Z",
+ "updatedAt":"2026-04-02T00:00:00Z",
+ "updateInfo":{"status":"has_update","hasUpdate":true,"imageCount":1,"checkedImageCount":1,"imagesWithUpdates":1,"errorCount":0}
+ }
+ ],
+ "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "--output", "text", "projects", "updates"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ require.Equal(t, "has_update", seenUpdatesFilter,
+ "expected updates filter query param, got %q", seenUpdatesFilter)
+
+ require.NotEmpty(t, strings.TrimSpace(outBuf),
+ "expected output from projects updates command")
+}
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index 3eab994e1..dfc74b270 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -1,34 +1,4 @@
// Package cli provides the root command and entry point for the Arcane CLI.
-//
-// The Arcane CLI is the official command-line interface for interacting with
-// Arcane servers. It provides commands for managing containers, images,
-// configuration, and more.
-//
-// # Getting Started
-//
-// Configure the CLI with your server URL and API key:
-//
-// arcane config set server-url https://your-server.com api-key YOUR_API_KEY
-//
-// # Global Flags
-//
-// The following flags are available on all commands:
-//
-// --log-level string Log level (debug, info, warn, error, fatal) (default "info")
-// --json Output in JSON format
-// -v, --version Print version information
-//
-// # Command Groups
-//
-// - admin: Administration & platform management
-// - auth: Authentication operations
-// - config: Manage CLI configuration
-// - containers: Manage containers
-// - images: Manage Docker images and updates
-// - jobs: Manage background jobs
-// - generate: Generate secrets and tokens
-// - variables: Manage global variables
-// - version: Display version information
package cli
import (
@@ -46,6 +16,7 @@ import (
"charm.land/lipgloss/v2"
"github.com/spf13/cobra"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
"github.com/getarcaneapp/arcane/cli/v2/internal/logger"
"github.com/getarcaneapp/arcane/cli/v2/internal/output"
@@ -102,20 +73,19 @@ var rootCmd = &cobra.Command{
}
}
+ outputMode = cmp.Or(strings.ToLower(strings.TrimSpace(outputMode)), string(runtimectx.OutputModeText))
if globalJSON && !cmd.Flags().Changed("output") {
outputMode = string(runtimectx.OutputModeJSON)
}
- outputMode = strings.ToLower(strings.TrimSpace(outputMode))
- if outputMode == "" {
- outputMode = string(runtimectx.OutputModeText)
- }
- if outputMode != string(runtimectx.OutputModeText) && outputMode != string(runtimectx.OutputModeJSON) {
- return fmt.Errorf("invalid --output value %q (expected text or json)", outputMode)
- }
- if 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")
}
+ case runtimectx.OutputModeText:
+ default:
+ return fmt.Errorf("invalid --output value %q (expected text or json)", outputMode)
}
// Load config to check for log level setting
@@ -126,17 +96,15 @@ var rootCmd = &cobra.Command{
logLevel = cfg.LogLevel
}
- jsonMode := outputMode == string(runtimectx.OutputModeJSON)
- if flag := cmd.Flags().Lookup("json"); flag != nil {
- localJSON, _ := cmd.Flags().GetBool("json")
- jsonMode = jsonMode || localJSON
+ if localJSON, _ := cmd.Flags().GetBool("json"); localJSON {
+ runtimeMode = runtimectx.OutputModeJSON
}
- output.Configure(cmd.OutOrStdout(), cmd.ErrOrStderr(), jsonMode, noColorOutput, cmd.Short)
+ 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: runtimectx.OutputMode(outputMode),
+ OutputMode: runtimeMode,
AssumeYes: assumeYes,
NoColor: noColorOutput,
RequestTimeout: requestTimeout,
@@ -174,7 +142,23 @@ func Execute() {
if err := fang.Execute(
ctx,
rootCmd,
- fang.WithColorSchemeFunc(arcaneFangColorSchemeInternal),
+ 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
+ }),
fang.WithErrorHandler(func(w io.Writer, _ fang.Styles, err error) { output.WriteError(w, err) }),
fang.WithVersion(config.Version),
fang.WithCommit(config.Revision),
@@ -191,27 +175,9 @@ func RootCommand() *cobra.Command {
return rootCmd
}
-func arcaneFangColorSchemeInternal(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
-}
-
-func instrumentCommandTreeInternal(cmd *cobra.Command) {
+func instrumentCommandTree(cmd *cobra.Command) {
for _, child := range cmd.Commands() {
- instrumentCommandTreeInternal(child)
+ instrumentCommandTree(child)
}
if cmd.RunE == nil && cmd.Run == nil {
@@ -232,7 +198,7 @@ func instrumentCommandTreeInternal(cmd *cobra.Command) {
originalRunE := cmd.RunE
cmd.RunE = func(command *cobra.Command, args []string) error {
logger.GetLogger().Debug(action, "command", command.CommandPath(), "arg_count", len(args))
- return originalRunE(command, args)
+ return cmdutil.RunScoped(command, args, originalRunE)
}
}
@@ -284,5 +250,5 @@ func init() {
rootCmd.AddCommand(activities.ActivitiesCmd)
rootCmd.AddCommand(webhooks.WebhooksCmd)
- instrumentCommandTreeInternal(rootCmd)
+ instrumentCommandTree(rootCmd)
}
diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.go
index f37797456..e8b826be6 100644
--- a/cli/pkg/settings/cmd.go
+++ b/cli/pkg/settings/cmd.go
@@ -9,7 +9,6 @@ import (
"github.com/getarcaneapp/arcane/types/v2/settings"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -45,7 +44,7 @@ var updateCmd = &cobra.Command{
Short: "Update environment settings",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -94,7 +93,7 @@ type settingsListConfig struct {
}
func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -114,14 +113,15 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
rows[i] = []string{s.Key, s.Type, s.Value}
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: cfg.totalLabel}); tableErr != nil {
return tableErr
}
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d %s\n", len(result), cfg.totalLabel)
return nil
}
func init() {
+ cmdutil.SetScope(cmdutil.ScopeRead, SettingsCmd)
+ cmdutil.SetScope(cmdutil.ScopeFleet, updateCmd)
SettingsCmd.AddCommand(listCmd)
SettingsCmd.AddCommand(updateCmd)
SettingsCmd.AddCommand(publicCmd)
diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.go
index 2f9ce1e1b..6992b354c 100644
--- a/cli/pkg/system/cmd.go
+++ b/cli/pkg/system/cmd.go
@@ -13,9 +13,9 @@ import (
"github.com/getarcaneapp/arcane/types/v2/system"
"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/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
@@ -33,7 +33,7 @@ var pruneCmd = &cobra.Command{
Short: "Prune all unused resources",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -65,7 +65,7 @@ var dockerInfoCmd = &cobra.Command{
Short: "Get Docker daemon information",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -102,7 +102,7 @@ var containersStartCmd = &cobra.Command{
Short: "Start all containers",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -128,7 +128,7 @@ var containersStopCmd = &cobra.Command{
Short: "Stop all containers",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -148,7 +148,7 @@ var convertCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -204,11 +204,29 @@ var upgradeCmd = &cobra.Command{
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)
+ }
+ 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("")
+ return runUpgradeAll(cmd)
+ }
if upgradeAllFlag {
- return runUpgradeAllInternal(cmd)
+ return runUpgradeAll(cmd)
}
if upgradeCheckFlag {
- return runUpgradeCheckInternal(cmd)
+ return runUpgradeCheck(cmd)
}
if !forceFlag {
@@ -222,7 +240,7 @@ var upgradeCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -240,8 +258,8 @@ var upgradeCmd = &cobra.Command{
var upgradeCheckFlag bool
-func runUpgradeCheckInternal(cmd *cobra.Command) error {
- c, err := client.NewFromConfig()
+func runUpgradeCheck(cmd *cobra.Command) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -271,9 +289,7 @@ func runUpgradeCheckInternal(cmd *cobra.Command) error {
return nil
}
-// environmentUpdateJob mirrors the backend's fleet-wide update job payload
-// (backend/internal/system.EnvironmentUpdateJob), which is not exported in the
-// shared types module.
+// environmentUpdateJob mirrors the backend fleet update payload, which has no shared public DTO.
type environmentUpdateJob struct {
ID string `json:"id"`
Status string `json:"status"`
@@ -292,7 +308,7 @@ type environmentUpdateJob struct {
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
-func printUpdateAllJobInternal(job environmentUpdateJob) error {
+func printUpdateAllJob(job environmentUpdateJob) error {
output.KeyValue("Status", job.Status)
if job.Username != "" {
output.KeyValue("Triggered By", job.Username)
@@ -331,7 +347,7 @@ var (
upgradeAllStatusFlag bool
)
-func runUpgradeAllInternal(cmd *cobra.Command) error {
+func runUpgradeAll(cmd *cobra.Command) error {
c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
@@ -348,7 +364,7 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
output.Header("Update-All Status")
- return printUpdateAllJobInternal(result.Data)
+ return printUpdateAllJob(result.Data)
}
if !forceFlag {
@@ -372,10 +388,14 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
output.Success("Update-all started")
- return printUpdateAllJobInternal(result.Data)
+ 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)
diff --git a/cli/pkg/system/cmd_test.go b/cli/pkg/system/cmd_test.go
new file mode 100644
index 000000000..33cfaf2df
--- /dev/null
+++ b/cli/pkg/system/cmd_test.go
@@ -0,0 +1,100 @@
+package system_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
+
+func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/system/containers/start-all" {
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))
+ return
+ }
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "system", "containers", "start"},
+ )
+
+ require.Error(t, err,
+ "expected an error for a 403 response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)
+
+ require.Contains(t, err.Error(), "403",
+ "expected the error to mention status 403, got: %v", err)
+
+ require.NotContains(t, outBuf, "Started all containers",
+ "expected no success message on a denied start-all, got stdout=%s", outBuf)
+ for _, tc := range []struct {
+ name string
+ partial bool
+ cancel bool
+ }{
+ {name: "fleet succeeds"}, {name: "fleet continues after failure", partial: true}, {name: "fleet confirmation cancelled", cancel: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var mu sync.Mutex
+ var mutations []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/api/environments" {
+ _, _ = w.Write([]byte(`{"success":true,"data":[{"id":"0","name":"Local","enabled":true},{"id":"remote","name":"Remote","enabled":true}]}`))
+ return
+ }
+ mu.Lock()
+ mutations = append(mutations, r.URL.Path)
+ mu.Unlock()
+ if tc.partial && strings.Contains(r.URL.Path, "/0/") {
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"success":false,"error":"start denied"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"success":true,"data":{"message":"started"}}`))
+ }))
+ defer server.Close()
+ path := testutil.WriteConfig(t, server.URL, true)
+ args := []string{"--config", path, "--json"}
+ if !tc.cancel {
+ args = append(args, "--yes")
+ }
+ out, diagnostics, runErr := testutil.Execute(t, append(args, "system", "containers", "start"))
+ mu.Lock()
+ paths := append([]string(nil), mutations...)
+ mu.Unlock()
+ if tc.cancel {
+ require.NoError(t, runErr)
+ require.Empty(t, paths)
+ require.Empty(t, out)
+ require.Contains(t, diagnostics, "Local (0), Remote (remote)")
+ return
+ }
+ require.Equal(t, []string{"/api/environments/0/system/containers/start-all", "/api/environments/remote/system/containers/start-all"}, paths)
+ if tc.partial {
+ require.ErrorContains(t, runErr, "start denied")
+ } else {
+ require.NoError(t, runErr, diagnostics)
+ }
+ var result struct {
+ Success bool `json:"success"`
+ Environments []json.RawMessage `json:"environments"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(out), &result), out)
+ require.Equal(t, !tc.partial, result.Success)
+ require.Len(t, result.Environments, 2)
+ })
+ }
+}
diff --git a/cli/pkg/templates/cmd_test.go b/cli/pkg/templates/cmd_test.go
new file mode 100644
index 000000000..bf319db82
--- /dev/null
+++ b/cli/pkg/templates/cmd_test.go
@@ -0,0 +1,121 @@
+package templates_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
+)
+
+func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
+ var (
+ mu sync.Mutex
+ gotPath string
+ gotQuery string
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ gotPath = r.URL.Path
+ gotQuery = r.URL.RawQuery
+ mu.Unlock()
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "data": [
+ {"name":"nginx","isCustom":false,"isRemote":false,"description":"Nginx template"}
+ ],
+ "pagination": {"totalPages":3,"totalItems":15,"currentPage":3,"itemsPerPage":7}
+ }`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ outBuf, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "templates", "list", "--json", "--limit", "7", "--start", "14"},
+ )
+
+ require.NoError(t, err,
+ "execute: %v (%s)", err, errOut)
+
+ mu.Lock()
+ if gotPath != "/api/templates" {
+ mu.Unlock()
+ require.FailNowf(t, "unexpected failure", "path = %q, want %q", gotPath, "/api/templates")
+ }
+ if !strings.Contains(gotQuery, "limit=7") || !strings.Contains(gotQuery, "start=14") {
+ mu.Unlock()
+ require.FailNowf(t, "unexpected failure", "query = %q, want limit=7 and start=14", gotQuery)
+ }
+ mu.Unlock()
+
+ var got map[string]any
+ {
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
+ }
+ {
+
+ _, ok := got["success"]
+ require.True(t, ok,
+ "expected success key in output: %v", got)
+ }
+ {
+
+ _, ok := got["data"]
+ require.True(t, ok,
+ "expected data key in output: %v", got)
+ }
+ {
+
+ _, ok := got["pagination"]
+ require.True(t, ok,
+ "expected pagination key in output: %v", got)
+ }
+}
+
+func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {
+ var (
+ mu sync.Mutex
+ called bool
+ )
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ called = true
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":[]}`))
+ }))
+ defer srv.Close()
+
+ configPath := testutil.WriteConfig(t, srv.URL)
+ _, errOut, err := testutil.Execute(
+ t,
+ []string{"--config", configPath, "templates", "list", "--all", "--limit", "50"},
+ )
+
+ require.Error(t, err,
+ "expected command error, got nil")
+
+ require.Contains(t, err.Error(), "--all cannot be combined with explicit pagination flags",
+ "unexpected error: %v", err)
+
+ require.Contains(t, errOut, "--all cannot be combined with explicit pagination flags",
+ "unexpected stderr output: %s", errOut)
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ require.False(t, called,
+ "expected command to fail before issuing HTTP request")
+}
diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.go
index 0d1bf3567..a74a5853c 100644
--- a/cli/pkg/updater/cmd.go
+++ b/cli/pkg/updater/cmd.go
@@ -9,9 +9,9 @@ import (
"github.com/getarcaneapp/arcane/types/v2/updater"
"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/output"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
"github.com/getarcaneapp/arcane/cli/v2/internal/types"
)
@@ -32,7 +32,7 @@ var statusCmd = &cobra.Command{
Short: "Get updater status",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -58,7 +58,7 @@ var runCmd = &cobra.Command{
Short: "Run updater",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -71,6 +71,10 @@ var runCmd = &cobra.Command{
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)
}
@@ -107,7 +111,7 @@ var historyCmd = &cobra.Command{
Short: "Get updater history",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -142,15 +146,16 @@ var historyCmd = &cobra.Command{
}
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "history entries"}); tableErr != nil {
return tableErr
}
- _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d history entries\n", len(result.Data))
return nil
},
}
func init() {
+ cmdutil.SetScope(cmdutil.ScopeRead, UpdaterCmd)
+ cmdutil.SetScope(cmdutil.ScopeFleet, runCmd)
UpdaterCmd.AddCommand(statusCmd)
UpdaterCmd.AddCommand(runCmd)
UpdaterCmd.AddCommand(historyCmd)
diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/pkg/version/cmd_test.go
similarity index 57%
rename from cli/internal/integrationtest/json_contract_test.go
rename to cli/pkg/version/cmd_test.go
index 85faccc85..be4332473 100644
--- a/cli/internal/integrationtest/json_contract_test.go
+++ b/cli/pkg/version/cmd_test.go
@@ -1,64 +1,17 @@
-package integrationtest
+package version_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
- "strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
+ "github.com/getarcaneapp/arcane/cli/v2/internal/testutil"
)
-func TestContainersListJSONContract(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if !strings.HasPrefix(r.URL.Path, "/api/environments/0/containers") {
- w.WriteHeader(http.StatusNotFound)
- _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))
- return
- }
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "success": true,
- "data": [
- {"id":"abc123","names":["/nginx"],"image":"nginx:latest","state":"running","status":"Up 1 hour"}
- ],
- "pagination": {"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}
- }`))
- }))
- defer srv.Close()
-
- configPath := writeCLIIntegrationConfigInternal(t, srv.URL)
-
- outBuf, errOut, err := executeCLIIntegrationCommandInternal(
- t,
- []string{"--config", configPath, "--log-level", "debug", "containers", "list", "--json"},
- )
-
- require.NoError(t, err,
- "execute: %v (%s)", err, errOut)
-
- require.Contains(t, errOut, "Sending request")
- require.NotContains(t, outBuf, "Sending request")
- require.NotContains(t, outBuf, "\x1b")
- var got map[string]any
- {
- unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, unmarshalErr,
- "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
- }
-
- for _, key := range []string{"success", "data", "pagination"} {
- {
- _, ok := got[key]
- require.True(t, ok,
- "missing key %q in output: %v", key, got)
- }
- }
-}
-
func TestVersionOutput(t *testing.T) {
for _, tc := range []struct {
name string
@@ -85,11 +38,11 @@ func TestVersionOutput(t *testing.T) {
_, _ = w.Write([]byte(tc.body))
}))
defer srv.Close()
- args := []string{"--config", writeCLIIntegrationConfigInternal(t, srv.URL), "--no-color", "version"}
+ args := []string{"--config", testutil.WriteConfig(t, srv.URL), "--no-color", "version"}
if tc.json {
args = append(args, "--json")
}
- out, diagnostics, err := executeCLIIntegrationCommandInternal(t, args)
+ out, diagnostics, err := testutil.Execute(t, args)
if tc.json && tc.unavailable {
require.Error(t, err)
require.Empty(t, out)
diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.go
index fd3c9e58a..d99ee0b8e 100644
--- a/cli/pkg/volumes/backup.go
+++ b/cli/pkg/volumes/backup.go
@@ -6,10 +6,10 @@ import (
"encoding/json/v2"
"errors"
"fmt"
- "io"
"mime"
"net/http"
"os"
+ "slices"
"strconv"
"time"
@@ -152,9 +152,66 @@ var backupsPolicyUpdateCmd = &cobra.Command{
return fmt.Errorf("failed to parse policy file: %w", unmarshalErr)
}
} else {
- payload, err = buildPolicyUpdate(cmd, c, resolved.Name)
- if err != nil {
- return err
+ 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,
+ }
+ if policyID != "" && p.ID == policyID {
+ targetIndex = i
+ }
+ }
+
+ 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")
+ }
+ // 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
+ }
+
+ target := &payload.Policies[targetIndex]
+ if cmd.Flags().Changed("enabled") {
+ target.Enabled = policyEnabled
+ }
+ if cmd.Flags().Changed("schedule") {
+ target.Schedule = policySchedule
+ }
+ if cmd.Flags().Changed("retention") {
+ target.RetentionCount = policyRetention
+ }
+ if cmd.Flags().Changed("stop-containers") {
+ target.StopContainers = policyStopContainers
+ }
+ if cmd.Flags().Changed("local") {
+ target.LocalEnabled = policyLocal
+ }
+ if cmd.Flags().Changed("s3") {
+ target.S3Enabled = policyS3
+ }
+ if cmd.Flags().Changed("s3-destination") {
+ target.S3DestinationID = policyS3Destination
}
}
@@ -172,76 +229,6 @@ var backupsPolicyUpdateCmd = &cobra.Command{
},
}
-// buildPolicyUpdate merges the flag values into the volume's current policy
-// collection: the whole collection is PUT back, with only the targeted policy
-// changed. A new policy is appended when the volume has none yet.
-func buildPolicyUpdate(cmd *cobra.Command, c *client.Client, volumeName string) (volume.UpdateBackupPolicies, error) {
- var payload volume.UpdateBackupPolicies
-
- current, err := c.GetJSON[volume.BackupPolicyCollection](cmd.Context(), types.VolumeBackupPolicy(c.EnvID(), volumeName))
- if err != nil {
- return payload, fmt.Errorf("failed to get current backup policies: %w", err)
- }
-
- 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,
- }
- if policyID != "" && p.ID == policyID {
- targetIndex = i
- }
- }
-
- switch {
- case policyID != "" && targetIndex == -1:
- return payload, fmt.Errorf("policy %q not found for volume %q", policyID, volumeName)
- case policyID == "" && len(payload.Policies) > 1:
- return payload, fmt.Errorf("volume %q has %d backup policies; select one with --policy-id", volumeName, len(payload.Policies))
- case policyID == "" && len(payload.Policies) == 1:
- targetIndex = 0
- case targetIndex == -1:
- if 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") || policyLocal})
- targetIndex = len(payload.Policies) - 1
- }
-
- target := &payload.Policies[targetIndex]
- if cmd.Flags().Changed("enabled") {
- target.Enabled = policyEnabled
- }
- if cmd.Flags().Changed("schedule") {
- target.Schedule = policySchedule
- }
- if cmd.Flags().Changed("retention") {
- target.RetentionCount = policyRetention
- }
- if cmd.Flags().Changed("stop-containers") {
- target.StopContainers = policyStopContainers
- }
- if cmd.Flags().Changed("local") {
- target.LocalEnabled = policyLocal
- }
- if cmd.Flags().Changed("s3") {
- target.S3Enabled = policyS3
- }
- if cmd.Flags().Changed("s3-destination") {
- target.S3DestinationID = policyS3Destination
- }
- return payload, nil
-}
-
func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollection) error {
output.Header("Backup Policies: %s", volumeName)
output.KeyValue("S3 Available", collection.S3Available)
@@ -256,22 +243,18 @@ func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollec
s3Destination := cmp.Or(p.S3DestinationName, p.S3DestinationID)
rows[i] = []string{
p.ID,
- output.TintEnabled(yesNo(p.Enabled)),
+ output.TintEnabled(kit.Ternary(p.Enabled, "Yes", "No")),
p.Schedule,
strconv.Itoa(p.RetentionCount),
- yesNo(p.StopContainers),
- yesNo(p.LocalEnabled),
- yesNo(p.S3Enabled),
+ kit.Ternary(p.StopContainers, "Yes", "No"),
+ kit.Ternary(p.LocalEnabled, "Yes", "No"),
+ kit.Ternary(p.S3Enabled, "Yes", "No"),
s3Destination,
}
}
return output.Table(headers, rows)
}
-func yesNo(v bool) string {
- return kit.Ternary(v, "Yes", "No")
-}
-
var backupsCmd = &cobra.Command{
Use: "backups <volume-name>",
Short: "Manage volume backups",
@@ -420,17 +403,17 @@ and restored instead (no backup ID).`,
return err
}
- if restoreArchiveFile != "" {
- return runUploadRestore(cmd, c, resolved.Name)
- }
-
- backupID := args[1]
- if len(restorePaths) > 0 {
- return runRestorePaths(cmd, c, resolved.Name, backupID)
+ 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, fmt.Sprintf("Restore volume %s from backup %s? Current volume contents will be replaced.", resolved.Name, backupID))
+ confirmed, confirmErr := cmdutil.Confirm(cmd, confirmation)
if confirmErr != nil {
return confirmErr
}
@@ -439,83 +422,39 @@ and restored instead (no backup ID).`,
return nil
}
}
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestore(c.EnvID(), resolved.Name, backupID), nil)
- if err != nil {
- return fmt.Errorf("failed to restore backup: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Restore of volume %s from backup %s initiated", resolved.Name, backupID)
- return nil
- },
-}
-
-func runRestorePaths(cmd *cobra.Command, c *client.Client, volumeName, backupID string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Restore %d path(s) into volume %s from backup %s?", len(restorePaths), volumeName, backupID))
- if err != nil {
- return err
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
+ 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
}
- }
-
- body := struct {
- Paths []string `json:"paths"`
- }{Paths: restorePaths}
-
- result, err := c.PostJSON[base.MessageResponse](cmd.Context(), types.VolumeBackupRestoreFiles(c.EnvID(), volumeName, backupID), body)
- if err != nil {
- return fmt.Errorf("failed to restore backup files: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- output.Success("Restore of %d path(s) into volume %s initiated", len(restorePaths), volumeName)
- return nil
-}
-
-func runUploadRestore(cmd *cobra.Command, c *client.Client, volumeName string) error {
- if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Restore volume %s from %s? Current volume contents will be replaced.", volumeName, restoreArchiveFile))
- if err != nil {
- return err
- }
- if !confirmed {
- _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")
- 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,
}
- }
-
- // Uploading and restoring large backups can take a long time
- c.SetTimeout(30 * time.Minute)
-
- sessionID, err := cmdutil.UploadFileInChunks(cmd.Context(), c, uploadtypes.KindVolumeBackup, restoreArchiveFile, !jsonOutput)
- if err != nil {
- return err
- }
-
- respBody, err := c.DoRaw(cmd.Context(), http.MethodPost, types.VolumeBackupUploadRestore(c.EnvID(), volumeName), uploadtypes.ConsumeRequest{UploadID: sessionID})
- if err != nil {
- cmdutil.AbortUploadSession(cmd.Context(), c, uploadtypes.KindVolumeBackup, sessionID)
- return fmt.Errorf("failed to upload and restore backup: %w", err)
- }
-
- if jsonOutput {
- _, _ = fmt.Fprintln(output.Stdout(), string(respBody))
- return nil
- }
-
- output.Success("Backup uploaded and restored into volume %s successfully", volumeName)
- return nil
+ 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)
+ },
}
var backupsDeleteCmd = &cobra.Command{
@@ -607,11 +546,22 @@ var backupsDownloadCmd = &cobra.Command{
outputFile = args[1]
}
if outputFile == "" {
- outputFile = downloadFilename(resp, args[0]+".tar.gz")
+ outputFile = args[0] + ".tar.gz"
+ if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
+ outputFile = cmp.Or(params["filename"], outputFile)
+ }
}
- if writeResponseToFileErr := writeResponseToFileInternal(cmd.Context(), resp.Body, resp.ContentLength, outputFile, !cmdutil.JSONOutputEnabled(cmd)); writeResponseToFileErr != nil {
- return writeResponseToFileErr
+ 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)
}
output.Success("Backup downloaded to %s", outputFile)
@@ -619,32 +569,6 @@ var backupsDownloadCmd = &cobra.Command{
},
}
-// downloadFilename extracts the filename from the response's
-// Content-Disposition header, falling back to the given default.
-func downloadFilename(resp *http.Response, fallback string) string {
- if _, params, err := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); err == nil {
- if name := params["filename"]; name != "" {
- return name
- }
- }
- return fallback
-}
-
-func writeResponseToFileInternal(ctx context.Context, body io.Reader, total int64, path string, showProgress bool) error {
- file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
- if err != nil {
- return fmt.Errorf("failed to create file %s: %w", path, err)
- }
- if _, copyErr := output.Copy(ctx, file, body, total, "Downloading backup", showProgress); copyErr != nil {
- _ = file.Close()
- return fmt.Errorf("failed to write file %s: %w", path, copyErr)
- }
- if closeErr := file.Close(); closeErr != nil {
- return fmt.Errorf("failed to write file %s: %w", path, closeErr)
- }
- return nil
-}
-
var backupsFilesCmd = &cobra.Command{
Use: "files <backup-id>",
Short: "List files in a volume backup",
@@ -673,6 +597,7 @@ var backupsFilesCmd = &cobra.Command{
}
func init() {
+ cmdutil.SetResource(backupRef, backupsDeleteCmd, backupsUploadCmd, backupsDownloadCmd, backupsFilesCmd)
VolumesCmd.AddCommand(renameCmd)
VolumesCmd.AddCommand(backupsCmd)
@@ -728,3 +653,26 @@ func init() {
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 },
+}
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index ae82f21b9..31db59878 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -10,7 +10,6 @@ import (
"github.com/getarcaneapp/arcane/types/v2/volume"
"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/output"
"github.com/getarcaneapp/arcane/cli/v2/internal/prompt"
@@ -51,7 +50,7 @@ var listCmd = &cobra.Command{
if inUseOnlyFlag && unusedOnlyFlag {
return errors.New("--inuse and --unused cannot be used together")
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -66,7 +65,7 @@ var listCmd = &cobra.Command{
query.Set("inUse", "false")
}
if includeInternalFlag {
- query.Set("includeInternal", "true")
+ query.Set("include", "true")
}
return cmdutil.RunList(cmd, c, cmdutil.ListSpec[volume.Volume]{
@@ -105,7 +104,7 @@ var getCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -141,7 +140,7 @@ var deleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -186,12 +185,21 @@ var countsCmd = &cobra.Command{
Short: "Get volume usage counts",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runVolumeDataCommand(cmd, volumeDataCommandConfig{
- endpoint: types.VolumesCounts,
- failureMessage: "failed to get volume counts",
- header: "Volume Usage Counts",
- marshalMessage: "failed to marshal volume counts",
- })
+ 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
},
}
@@ -211,7 +219,7 @@ var pruneCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -230,49 +238,31 @@ var sizesCmd = &cobra.Command{
Short: "Get volume sizes",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- return runVolumeDataCommand(cmd, volumeDataCommandConfig{
- endpoint: types.VolumesSizes,
- failureMessage: "failed to get volume sizes",
- header: "Volume Sizes",
- marshalMessage: "failed to marshal volume sizes",
- })
+ 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
},
}
-type volumeDataCommandConfig struct {
- endpoint func(string) string
- failureMessage string
- header string
- marshalMessage string
-}
-
-func runVolumeDataCommand(cmd *cobra.Command, cfg volumeDataCommandConfig) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- result, err := c.GetJSON[any](cmd.Context(), cfg.endpoint(c.EnvID()))
- if err != nil {
- return fmt.Errorf("%s: %w", cfg.failureMessage, err)
- }
-
- if !jsonOutput {
- output.Header("%s", cfg.header)
- }
- if printJSONErr := cmdutil.PrintJSON(result.Data); printJSONErr != nil {
- return fmt.Errorf("%s: %w", cfg.marshalMessage, printJSONErr)
- }
- return nil
-}
-
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 := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -302,7 +292,7 @@ var createCmd = &cobra.Command{
Short: "Create a volume",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -350,6 +340,10 @@ var createCmd = &cobra.Command{
}
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)
@@ -394,13 +388,23 @@ func init() {
}
var volumeRef = cmdutil.ResourceRef[volume.Volume, volume.Volume]{
- Singular: "volume",
- Plural: "volumes",
- IDHint: "the volume name",
- ListCmd: "arcane volumes list",
- GetPath: types.Volume,
- ListPath: types.Volumes,
- Matches: volumeMatches,
+ EnvironmentScoped: true,
+ Singular: "volume",
+ Plural: "volumes",
+ IDHint: "the volume name",
+ ListCmd: "arcane volumes list",
+ GetPath: types.Volume,
+ 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))
+ },
Label: func(match volume.Volume) string {
if match.Driver != "" {
return fmt.Sprintf("%s (%s)", match.Name, match.Driver)
@@ -409,14 +413,3 @@ var volumeRef = cmdutil.ResourceRef[volume.Volume, volume.Volume]{
},
Promote: func(match volume.Volume) *volume.Volume { return &match },
}
-
-func volumeMatches(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))
-}
diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.go
index 92824c54e..0a4c426df 100644
--- a/cli/pkg/volumes/workspace.go
+++ b/cli/pkg/volumes/workspace.go
@@ -2,9 +2,11 @@ package volumes
import (
"bytes"
+ "cmp"
"encoding/json/v2"
"errors"
"fmt"
+ "mime"
"mime/multipart"
"net/http"
"net/url"
@@ -191,11 +193,22 @@ var workspaceDownloadCmd = &cobra.Command{
outputFile = args[2]
}
if outputFile == "" {
- outputFile = downloadFilename(resp, path.Base(args[1]))
+ outputFile = path.Base(args[1])
+ if _, params, parseErr := mime.ParseMediaType(resp.Header.Get("Content-Disposition")); parseErr == nil {
+ outputFile = cmp.Or(params["filename"], outputFile)
+ }
}
- if writeResponseToFileErr := writeResponseToFileInternal(cmd.Context(), resp.Body, resp.ContentLength, outputFile, !cmdutil.JSONOutputEnabled(cmd)); writeResponseToFileErr != nil {
- return writeResponseToFileErr
+ 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)
}
output.Success("File downloaded to %s", outputFile)
diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.go
index 1c04942bc..c6a7fa313 100644
--- a/cli/pkg/vulnerabilities/cmd.go
+++ b/cli/pkg/vulnerabilities/cmd.go
@@ -1,10 +1,4 @@
-// Package vulnerabilities provides CLI commands for image vulnerability
-// scanning on Arcane servers.
-//
-// This package implements the "arcane images vulnerabilities" command group, which
-// includes subcommands for checking scanner status, viewing environment-wide
-// summaries, listing vulnerabilities, scanning images, and managing ignore
-// records.
+// Package vulnerabilities provides image vulnerability scanning commands.
package vulnerabilities
import (
@@ -208,7 +202,27 @@ var imageCmd = &cobra.Command{
}
if summaryFlag {
- return runImageSummary(cmd, c, imageID)
+ 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)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ 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 result.Data.Error != "" {
+ output.KeyValue("Error", result.Data.Error)
+ }
+ printSeveritySummary(result.Data.Summary)
+ return nil
}
query := url.Values{}
@@ -236,30 +250,6 @@ var imageCmd = &cobra.Command{
},
}
-func runImageSummary(cmd *cobra.Command, c *client.Client, imageID string) error {
- result, err := c.GetJSON[vulnerability.ScanSummary](cmd.Context(), types.ImageVulnerabilitiesSummary(c.EnvID(), imageID))
- if err != nil {
- return fmt.Errorf("failed to get image vulnerability summary: %w", err)
- }
-
- if jsonOutput {
- return cmdutil.PrintJSON(result.Data)
- }
-
- 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 result.Data.Error != "" {
- output.KeyValue("Error", result.Data.Error)
- }
- printSeveritySummary(result.Data.Summary)
- return nil
-}
-
var ignoreCmd = &cobra.Command{
Use: "ignore <cve-id>",
Short: "Ignore a vulnerability for an image",
@@ -322,10 +312,12 @@ var ignoredCmd = &cobra.Command{
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,
- shortImageID(item.ImageID),
+ imageID,
item.PkgName,
cmp.Or(reason, "-"),
item.CreatedAt.Format(time.RFC3339),
@@ -367,6 +359,9 @@ var unignoreCmd = &cobra.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)
@@ -424,14 +419,6 @@ func printSeveritySummary(s *vulnerability.SeveritySummary) {
output.KeyValue("Total", s.Total)
}
-func shortImageID(id string) string {
- trimmed := strings.TrimPrefix(id, "sha256:")
- if len(trimmed) > 12 {
- return trimmed[:12]
- }
- return trimmed
-}
-
// resolveImageID resolves an image name, tag, or (partial) ID to a full image
// ID via the shared images resolver.
func resolveImageID(ctx context.Context, c *client.Client, identifier string) (string, error) {
@@ -441,3 +428,17 @@ func resolveImageID(ctx context.Context, c *client.Client, identifier string) (s
}
return resolved.ID, nil
}
+
+var ignoreRef = cmdutil.ResourceRef[vulnerability.IgnoredVulnerability, vulnerability.IgnoredVulnerability]{
+ EnvironmentScoped: true,
+ Singular: "ignore", Plural: "ignores",
+ IDHint: "the identifier", ListCmd: "arcane-cli images vulnerabilities ignored",
+ GetPath: nil, ListPath: types.VulnerabilitiesIgnored,
+ Matches: func(item vulnerability.IgnoredVulnerability, lower, original string) bool {
+ return strings.EqualFold(item.ID, original)
+ },
+ Label: func(item vulnerability.IgnoredVulnerability) string {
+ return item.VulnerabilityID + " (" + item.ID + ")"
+ },
+ Promote: func(item vulnerability.IgnoredVulnerability) *vulnerability.IgnoredVulnerability { return &item },
+}
diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.go
index b9658ed69..54c49dce4 100644
--- a/cli/pkg/webhooks/cmd.go
+++ b/cli/pkg/webhooks/cmd.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"net/http"
+ "strings"
"time"
"github.com/getarcaneapp/arcane/types/v2/base"
@@ -66,21 +67,24 @@ var listCmd = &cobra.Command{
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,
- webhookTarget(item),
+ target,
item.TokenPrefix,
enabled,
lastTriggered,
}
}
- if tableErr := output.Table(headers, rows); tableErr != nil {
+ if tableErr := cmdutil.PrintTable(cmd, headers, rows, cmdutil.TableSummary{Resource: "webhooks", Total: int64(len(result.Data)), Paginated: true}); tableErr != nil {
return tableErr
}
- output.Showing(len(result.Data), int64(len(result.Data)), "webhooks")
return nil
},
}
@@ -218,6 +222,11 @@ var triggerCmd = &cobra.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)
@@ -249,10 +258,12 @@ func init() {
triggerCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
-func webhookTarget(item webhook.Summary) string {
- name := cmp.Or(item.TargetName, item.TargetID)
- if name == "" {
- return item.TargetType
- }
- return fmt.Sprintf("%s/%s", item.TargetType, name)
+var webhookRef = cmdutil.ResourceRef[webhook.Summary, webhook.Summary]{
+ EnvironmentScoped: true,
+ 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 },
}