Skip to content

Modern Docker Management, Designed for Everyone

refactor: cli config rework and pagination tweaks (#1854)

Kyle Mendell474003275eb6
diff --git a/cli/README.md b/cli/README.md
index 21420a81b..3edae7308 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -27,9 +27,14 @@ CLI versions are tagged as `cli/vX.Y.Z` in the main repo. Use module tags to pin
The CLI stores config in `~/.config/arcanecli.yml`.
+Create a starter config file (all supported keys):
+
+- `arcane config init`
+- `arcane config backup` (moves current config to `~/.config/arcanecli.yml.bak`)
+
Set the Arcane server URL:
-- `arcane config set --server-url http://localhost:3552`
+- `arcane config set server-url http://localhost:3552`
### Authenticate (choose one)
@@ -39,4 +44,50 @@ Set the Arcane server URL:
#### Option B: API key
-- `arcane config set --api-key arc_xxxxxxxxxxxxx`
+- `arcane config set api-key arc_xxxxxxxxxxxxx`
+
+## Useful Global Flags
+
+- `--output text|json` for output mode (`--json` is an alias for `--output json`)
+- `--env <id>` to override the configured default environment for one command
+- `--yes` to auto-confirm destructive prompts
+- `--no-color` to disable ANSI color output
+- `--request-timeout <duration>` to override HTTP timeout per command
+
+## Utilities
+
+- `arcane completion bash|zsh|fish|powershell` to generate shell completions
+- `arcane doctor` to run local CLI diagnostics
+
+## Pagination Config
+
+Set global and per-resource list limits in config:
+
+```yaml
+pagination:
+ default:
+ limit: 25
+ resources:
+ containers:
+ limit: 50
+ images:
+ limit: 100
+ volumes:
+ limit: 40
+ networks:
+ limit: 40
+```
+
+CLI precedence is:
+1. `--limit`
+2. `pagination.resources.<resource>.limit`
+3. `pagination.default.limit`
+4. command built-in default
+
+You can configure limits with:
+- `arcane config set default-limit 25`
+- `arcane config set pagination.resources.containers.limit 50 pagination.resources.images.limit 100`
+
+Legacy flag syntax remains supported:
+- `arcane config set --default-limit 25`
+- `arcane config set --resource-limit containers=50 --resource-limit images=100`
diff --git a/cli/go.mod b/cli/go.mod
index 796062d5d..7794061c8 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -10,11 +10,12 @@ require (
github.com/charmbracelet/x/term v0.2.2
github.com/fatih/color v1.18.0
github.com/getarcaneapp/arcane/types v1.15.3
+ github.com/go-viper/mapstructure/v2 v2.5.0
github.com/mattn/go-runewidth v0.0.20
github.com/sirupsen/logrus v1.9.4
github.com/spf13/cobra v1.10.2
+ github.com/spf13/viper v1.21.0
go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67
- gopkg.in/yaml.v3 v3.0.1
)
require (
@@ -38,9 +39,8 @@ require (
github.com/docker/go-connections v0.6.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
- github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
+ github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
- github.com/kr/pretty v0.3.1 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -56,12 +56,19 @@ require (
github.com/muesli/termenv v0.16.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
+ github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
+ github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
+ github.com/spf13/afero v1.15.0 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
+ github.com/subosito/gotenv v1.6.0 // indirect
github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
+ go.yaml.in/yaml/v3 v3.0.4 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.3 // indirect
golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect
golang.org/x/sync v0.19.0 // indirect
diff --git a/cli/go.sum b/cli/go.sum
index 43708e683..44856e9be 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -39,10 +39,10 @@ github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/Wfc
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
+github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/compose-spec/compose-go/v2 v2.10.1 h1:mFbXobojGRFIVi1UknrvaDAZ+PkJfyjqkA1yseh+vAU=
github.com/compose-spec/compose-go/v2 v2.10.1/go.mod h1:Ohac1SzhO/4fXXrzWIztIVB6ckmKBv1Nt5Z5mGVESUg=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
@@ -57,6 +57,10 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/getarcaneapp/arcane/types v1.15.3 h1:UMhhWPNvy+lGVdg+5w9b47hr83aMe2KfV6dJIs4RHZY=
github.com/getarcaneapp/arcane/types v1.15.3/go.mod h1:kqkuqZZ9TkfWOvAuzCKq5UTX/11NO77lyPg5ECJrMXo=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
@@ -106,32 +110,45 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
-github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
-github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
+github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=
github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67 h1:nHPqmzoLZv+9OqER7S2oXnIBDAbIaIKKrVtNtDvJzjc=
go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67/go.mod h1:WFmSrzphcXaSV4LG3YfIw42bPHDK8A6WsAYZCxyys/c=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go=
go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
diff --git a/cli/internal/benchmark/baseline_benchmark_test.go b/cli/internal/benchmark/baseline_benchmark_test.go
new file mode 100644
index 000000000..21517f4ad
--- /dev/null
+++ b/cli/internal/benchmark/baseline_benchmark_test.go
@@ -0,0 +1,55 @@
+package benchmark
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/cli/internal/client"
+ clitypes "github.com/getarcaneapp/arcane/cli/internal/types"
+)
+
+func BenchmarkClientListMediumPayload(b *testing.B) {
+ payload := make(map[string]any, 0)
+ items := make([]map[string]any, 0, 200)
+ for i := 0; i < 200; i++ {
+ items = append(items, map[string]any{
+ "id": fmt.Sprintf("id-%d", i),
+ "name": fmt.Sprintf("name-%d", i),
+ "state": "running",
+ })
+ }
+ payload["success"] = true
+ payload["data"] = items
+ payload["pagination"] = map[string]any{
+ "currentPage": 1,
+ "itemsPerPage": 200,
+ "totalItems": 200,
+ "totalPages": 1,
+ }
+ raw, _ := json.Marshal(payload)
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(raw)
+ }))
+ defer srv.Close()
+
+ cfg := &clitypes.Config{ServerURL: srv.URL, APIKey: "arc_test_key"}
+ c, err := client.New(cfg)
+ if err != nil {
+ b.Fatalf("new client: %v", err)
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ resp, err := c.Get(context.Background(), "/api/environments/0/containers?limit=200")
+ if err != nil {
+ b.Fatalf("request: %v", err)
+ }
+ _ = resp.Body.Close()
+ }
+}
diff --git a/cli/internal/client/client.go b/cli/internal/client/client.go
index e98526823..700636ea2 100644
--- a/cli/internal/client/client.go
+++ b/cli/internal/client/client.go
@@ -26,14 +26,17 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "net"
"net/http"
"net/url"
"strings"
"time"
"github.com/getarcaneapp/arcane/cli/internal/config"
+ "github.com/getarcaneapp/arcane/cli/internal/runstate"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/auth"
"github.com/getarcaneapp/arcane/types/base"
@@ -43,19 +46,31 @@ const (
headerAPIKey = "X-API-KEY" //nolint:gosec
defaultTimeout = 10 * time.Minute
defaultEnvID = "0"
+ maxErrorBody = 4096
)
+var retryableStatusCodes = map[int]struct{}{
+ http.StatusTooManyRequests: {},
+ http.StatusBadGateway: {},
+ http.StatusServiceUnavailable: {},
+ 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.
type Client struct {
- baseURL string
- apiKey string
- jwtToken string
- refreshToken string
- envID string
- httpClient *http.Client
+ baseURL string
+ baseURLParsed *url.URL
+ apiKey string
+ jwtToken string
+ refreshToken string
+ envID string
+ httpClient *http.Client
+ maxAttempts int
+ baseBackoff time.Duration
+ maxBackoff time.Duration
}
// New creates a new API client from the provided configuration.
@@ -66,6 +81,10 @@ func New(cfg *types.Config) (*Client, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
+ parsedURL, err := url.Parse(cfg.ServerURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid server_url: %w", err)
+ }
envID := cfg.DefaultEnvironment
if envID == "" {
@@ -73,12 +92,16 @@ func New(cfg *types.Config) (*Client, error) {
}
return &Client{
- baseURL: cfg.ServerURL,
- apiKey: cfg.APIKey,
- jwtToken: cfg.JWTToken,
- refreshToken: cfg.RefreshToken,
- envID: envID,
- httpClient: newHTTPClientInternal(),
+ baseURL: cfg.ServerURL,
+ baseURLParsed: parsedURL,
+ apiKey: cfg.APIKey,
+ jwtToken: cfg.JWTToken,
+ refreshToken: cfg.RefreshToken,
+ envID: envID,
+ httpClient: newHTTPClientInternal(),
+ maxAttempts: 3,
+ baseBackoff: 150 * time.Millisecond,
+ maxBackoff: 2 * time.Second,
}, nil
}
@@ -88,6 +111,10 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {
if err := cfg.ValidateServerURL(); err != nil {
return nil, err
}
+ parsedURL, err := url.Parse(cfg.ServerURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid server_url: %w", err)
+ }
envID := cfg.DefaultEnvironment
if envID == "" {
@@ -95,10 +122,14 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {
}
return &Client{
- baseURL: cfg.ServerURL,
- envID: envID,
- refreshToken: cfg.RefreshToken,
- httpClient: newHTTPClientInternal(),
+ baseURL: cfg.ServerURL,
+ baseURLParsed: parsedURL,
+ envID: envID,
+ refreshToken: cfg.RefreshToken,
+ httpClient: newHTTPClientInternal(),
+ maxAttempts: 3,
+ baseBackoff: 150 * time.Millisecond,
+ maxBackoff: 2 * time.Second,
}, nil
}
@@ -124,7 +155,18 @@ func NewFromConfig() (*Client, error) {
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
- return New(cfg)
+ state := runstate.Get()
+ if strings.TrimSpace(state.EnvOverride) != "" {
+ cfg.DefaultEnvironment = strings.TrimSpace(state.EnvOverride)
+ }
+ c, err := New(cfg)
+ if err != nil {
+ return nil, err
+ }
+ if state.RequestTimeout > 0 {
+ c.SetTimeout(state.RequestTimeout)
+ }
+ return c, nil
}
// NewFromConfigUnauthenticated loads config and returns an unauthenticated client.
@@ -133,7 +175,18 @@ func NewFromConfigUnauthenticated() (*Client, error) {
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
- return NewUnauthenticated(cfg)
+ state := runstate.Get()
+ if strings.TrimSpace(state.EnvOverride) != "" {
+ cfg.DefaultEnvironment = strings.TrimSpace(state.EnvOverride)
+ }
+ c, err := NewUnauthenticated(cfg)
+ if err != nil {
+ return nil, err
+ }
+ if state.RequestTimeout > 0 {
+ c.SetTimeout(state.RequestTimeout)
+ }
+ return c, nil
}
// SetEnvironment changes the environment ID for subsequent requests.
@@ -148,6 +201,16 @@ func (c *Client) SetTimeout(timeout time.Duration) {
c.httpClient.Timeout = timeout
}
+// SetRetryPolicy configures retry behavior for idempotent requests.
+func (c *Client) SetRetryPolicy(maxAttempts int, baseBackoff, maxBackoff time.Duration) {
+ if maxAttempts < 1 {
+ maxAttempts = 1
+ }
+ c.maxAttempts = maxAttempts
+ c.baseBackoff = baseBackoff
+ c.maxBackoff = maxBackoff
+}
+
// EnvID returns the current environment ID configured for this client.
// The environment ID is used to scope API requests to a specific environment.
func (c *Client) EnvID() string {
@@ -182,18 +245,11 @@ type PaginatedResponse[T any] struct {
// as JSON (if provided), and includes authentication headers. The caller is
// responsible for closing the response body.
func (c *Client) Request(ctx context.Context, method, path string, body any) (*http.Response, error) {
- u, err := url.Parse(c.baseURL)
- if err != nil {
- return nil, fmt.Errorf("invalid base URL: %w", err)
- }
-
- rel, err := url.Parse(path)
+ fullURL, err := c.resolveURL(path)
if err != nil {
- return nil, fmt.Errorf("invalid path: %w", err)
+ return nil, err
}
- fullURL := u.ResolveReference(rel).String()
-
var bodyBytes []byte
if body != nil {
switch v := body.(type) {
@@ -232,18 +288,11 @@ func (c *Client) Request(ctx context.Context, method, path string, body any) (*h
// suitable for multipart form uploads and other non-JSON content types.
// Custom headers can be provided to set Content-Type and other headers.
func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Reader, headers map[string]string) (*http.Response, error) {
- u, err := url.Parse(c.baseURL)
- if err != nil {
- return nil, fmt.Errorf("invalid base URL: %w", err)
- }
-
- rel, err := url.Parse(path)
+ fullURL, err := c.resolveURL(path)
if err != nil {
- return nil, fmt.Errorf("invalid path: %w", err)
+ return nil, err
}
- fullURL := u.ResolveReference(rel).String()
-
req, err := http.NewRequestWithContext(ctx, method, fullURL, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
@@ -264,35 +313,133 @@ func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Re
return resp, nil
}
+func (c *Client) resolveURL(path string) (string, error) {
+ if strings.TrimSpace(path) == "" {
+ return "", fmt.Errorf("invalid path: empty")
+ }
+ if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
+ if _, err := url.Parse(path); err != nil {
+ return "", fmt.Errorf("invalid path: %w", err)
+ }
+ return path, nil
+ }
+ rel, err := url.Parse(path)
+ if err != nil {
+ return "", fmt.Errorf("invalid path: %w", err)
+ }
+ if c.baseURLParsed == nil {
+ return "", fmt.Errorf("invalid base URL")
+ }
+ return c.baseURLParsed.ResolveReference(rel).String(), nil
+}
+
func (c *Client) doRequest(ctx context.Context, method, fullURL string, bodyBytes []byte, allowRefresh bool) (*http.Response, error) {
- var bodyReader io.Reader
- if bodyBytes != nil {
- bodyReader = bytes.NewReader(bodyBytes)
+ attempts := c.maxAttempts
+ if attempts < 1 {
+ attempts = 1
}
- req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
- if err != nil {
- return nil, fmt.Errorf("failed to create request: %w", err)
+ for attempt := 1; attempt <= attempts; attempt++ {
+ var bodyReader io.Reader
+ if bodyBytes != nil {
+ bodyReader = bytes.NewReader(bodyBytes)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ c.applyAuth(req)
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+
+ resp, err := c.httpClient.Do(req) //nolint:gosec // intentional request to configured Arcane server URL
+ if err != nil {
+ if attempt < attempts && c.shouldRetry(method, 0, err) {
+ if backoffErr := c.waitRetry(ctx, attempt); backoffErr != nil {
+ return nil, backoffErr
+ }
+ continue
+ }
+ return nil, fmt.Errorf("request failed: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusUnauthorized && allowRefresh && c.jwtToken != "" && c.refreshToken != "" {
+ _ = resp.Body.Close()
+ if err := c.refreshAccessToken(ctx); err != nil {
+ return nil, err
+ }
+ allowRefresh = false
+ continue
+ }
+
+ if attempt < attempts && c.shouldRetry(method, resp.StatusCode, nil) {
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxErrorBody))
+ _ = resp.Body.Close()
+ if backoffErr := c.waitRetry(ctx, attempt); backoffErr != nil {
+ return nil, backoffErr
+ }
+ continue
+ }
+
+ return resp, nil
}
- c.applyAuth(req)
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Accept", "application/json")
+ return nil, fmt.Errorf("request failed after %d attempts", attempts)
+}
- resp, err := c.httpClient.Do(req) //nolint:gosec // intentional request to configured Arcane server URL
- if err != nil {
- return nil, fmt.Errorf("request failed: %w", err)
+func (c *Client) shouldRetry(method string, status int, err error) bool {
+ if !isIdempotentMethod(method) {
+ return false
}
+ if err != nil {
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return false
+ }
+ lowerErr := strings.ToLower(err.Error())
+ if strings.Contains(lowerErr, "context canceled") || strings.Contains(lowerErr, "deadline exceeded") {
+ return false
+ }
- if resp.StatusCode == http.StatusUnauthorized && allowRefresh && c.jwtToken != "" && c.refreshToken != "" {
- _ = resp.Body.Close()
- if err := c.refreshAccessToken(ctx); err != nil {
- return nil, err
+ var netErr net.Error
+ if errors.As(err, &netErr) {
+ return netErr.Timeout()
}
- return c.doRequest(ctx, method, fullURL, bodyBytes, false)
+ return true
}
+ _, ok := retryableStatusCodes[status]
+ return ok
+}
- return resp, nil
+func (c *Client) waitRetry(ctx context.Context, attempt int) error {
+ delay := c.baseBackoff
+ if delay <= 0 {
+ delay = 150 * time.Millisecond
+ }
+ for i := 1; i < attempt; i++ {
+ delay *= 2
+ }
+ if c.maxBackoff > 0 && delay > c.maxBackoff {
+ delay = c.maxBackoff
+ }
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return nil
+ }
+}
+
+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) {
@@ -317,11 +464,10 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
return fmt.Errorf("failed to marshal refresh request: %w", err)
}
- u, err := url.Parse(c.baseURL)
- if err != nil {
- return fmt.Errorf("invalid base URL: %w", err)
+ if c.baseURLParsed == nil {
+ return fmt.Errorf("invalid base URL")
}
- refreshURL := u.ResolveReference(&url.URL{Path: types.Endpoints.AuthRefresh()}).String()
+ refreshURL := c.baseURLParsed.ResolveReference(&url.URL{Path: types.Endpoints.AuthRefresh()}).String()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, refreshURL, bytes.NewReader(bodyBytes))
if err != nil {
@@ -406,14 +552,71 @@ func (c *Client) EnvPath(path string) string {
return fmt.Sprintf("/api/environments/%s%s", c.envID, path)
}
+// DoJSON performs a request and decodes a standard API envelope into out.
+func (c *Client) DoJSON(ctx context.Context, method, path string, body any, out any) error {
+ resp, err := c.Request(ctx, method, path, body)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
+ return fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
+ }
+
+ if out == nil {
+ return nil
+ }
+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
+ return fmt.Errorf("failed to decode response: %w", err)
+ }
+ return nil
+}
+
+// DoPaginated performs a request and decodes a paginated API envelope into out.
+func (c *Client) DoPaginated(ctx context.Context, method, path string, body any, out any) error {
+ return c.DoJSON(ctx, method, path, body, out)
+}
+
+// DoRaw performs a request and returns the response payload when status is 2xx.
+func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]byte, error) {
+ resp, err := c.Request(ctx, method, path, body)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
+ return nil, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response body: %w", err)
+ }
+ return b, nil
+}
+
// DecodeResponse decodes an API response into the given type.
// It reads the response body, unmarshals it as JSON, and returns the typed
// result. If the response indicates failure (Success=false) with a 4xx/5xx
// status code, an error is returned with the error message from the API.
// Note: This function closes the response body.
func DecodeResponse[T any](resp *http.Response) (*APIResponse[T], error) {
+ return DecodeResponseStrict[T](resp)
+}
+
+// DecodeResponseStrict decodes a response envelope and enforces HTTP and API success.
+func DecodeResponseStrict[T any](resp *http.Response) (*APIResponse[T], error) {
defer func() { _ = resp.Body.Close() }()
+ 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)))
+ }
+
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
@@ -424,8 +627,11 @@ func DecodeResponse[T any](resp *http.Response) (*APIResponse[T], error) {
return nil, fmt.Errorf("failed to decode response: %w (body: %s)", err, string(body))
}
- if !result.Success && resp.StatusCode >= 400 {
- return &result, fmt.Errorf("API error: %s", result.Error)
+ if !result.Success {
+ if strings.TrimSpace(result.Error) != "" {
+ return &result, fmt.Errorf("API error: %s", result.Error)
+ }
+ return &result, fmt.Errorf("API error: request was not successful")
}
return &result, nil
@@ -436,8 +642,18 @@ func DecodeResponse[T any](resp *http.Response) (*APIResponse[T], error) {
// containing the items array and pagination metadata.
// Note: This function closes the response body.
func DecodePaginatedResponse[T any](resp *http.Response) (*PaginatedResponse[T], error) {
+ return DecodePaginatedResponseStrict[T](resp)
+}
+
+// DecodePaginatedResponseStrict decodes a paginated envelope and enforces HTTP and API success.
+func DecodePaginatedResponseStrict[T any](resp *http.Response) (*PaginatedResponse[T], error) {
defer func() { _ = resp.Body.Close() }()
+ 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)))
+ }
+
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.go
new file mode 100644
index 000000000..1b59c18e3
--- /dev/null
+++ b/cli/internal/client/retry_test.go
@@ -0,0 +1,132 @@
+package client
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/cli/internal/types"
+)
+
+func TestClient_RetriesIdempotentRequests(t *testing.T) {
+ t.Parallel()
+
+ var attempts int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ current := atomic.AddInt32(&attempts, 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)
+ if err != nil {
+ t.Fatalf("New() error: %v", err)
+ }
+ c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
+
+ resp, err := c.Get(context.Background(), "/api/version")
+ if err != nil {
+ t.Fatalf("Get() error: %v", err)
+ }
+ _ = resp.Body.Close()
+ if got := atomic.LoadInt32(&attempts); got != 2 {
+ t.Fatalf("expected 2 attempts, got %d", got)
+ }
+}
+
+func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
+ t.Parallel()
+
+ var attempts int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&attempts, 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)
+ if err != nil {
+ t.Fatalf("New() error: %v", err)
+ }
+ c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
+
+ resp, err := c.Post(context.Background(), "/api/version", map[string]any{"a": 1})
+ if err != nil {
+ t.Fatalf("Post() returned transport error: %v", err)
+ }
+ _ = resp.Body.Close()
+ if got := atomic.LoadInt32(&attempts); got != 1 {
+ t.Fatalf("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)
+ if err != nil {
+ t.Fatalf("New() error: %v", err)
+ }
+
+ var out map[string]any
+ if err := c.DoJSON(context.Background(), http.MethodGet, "/api/version", nil, &out); err == nil {
+ t.Fatal("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()
+ if _, err := DecodeResponseStrict[map[string]any](resp); err == nil {
+ t.Fatal("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)
+ if err != nil {
+ t.Fatalf("New() error: %v", err)
+ }
+
+ b, err := c.DoRaw(context.Background(), http.MethodGet, "/api/version", nil)
+ if err != nil {
+ t.Fatalf("DoRaw() error: %v", err)
+ }
+ if len(b) == 0 {
+ t.Fatal("expected response payload")
+ }
+}
diff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.go
new file mode 100644
index 000000000..defd92e08
--- /dev/null
+++ b/cli/internal/cmdutil/confirm.go
@@ -0,0 +1,31 @@
+package cmdutil
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+// Confirm prompts the user unless --yes is enabled.
+func Confirm(cmd *cobra.Command, prompt string) (bool, error) {
+ if AssumeYes(cmd) {
+ return true, nil
+ }
+
+ fmt.Printf("%s (y/N): ", strings.TrimSpace(prompt))
+ var response string
+ if _, err := fmt.Scanln(&response); err != nil && !errors.Is(err, io.EOF) {
+ // Keep EOF as a default "no" response, but surface other input failures.
+ return false, fmt.Errorf("failed to read confirmation input: %w", err)
+ }
+
+ switch strings.ToLower(strings.TrimSpace(response)) {
+ case "y", "yes":
+ return true, nil
+ default:
+ return false, nil
+ }
+}
diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.go
new file mode 100644
index 000000000..0cb8db657
--- /dev/null
+++ b/cli/internal/cmdutil/context.go
@@ -0,0 +1,72 @@
+package cmdutil
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/cli/internal/client"
+ runtimectx "github.com/getarcaneapp/arcane/cli/internal/runtime"
+ "github.com/spf13/cobra"
+)
+
+// ClientFromCommand returns a configured authenticated client for the command.
+func ClientFromCommand(cmd *cobra.Command) (*client.Client, error) {
+ if cmd == nil {
+ return nil, fmt.Errorf("nil command")
+ }
+ if app, ok := runtimectx.From(cmd.Context()); ok {
+ return app.Client()
+ }
+ return client.NewFromConfig()
+}
+
+// UnauthClientFromCommand returns a configured unauthenticated client for the command.
+func UnauthClientFromCommand(cmd *cobra.Command) (*client.Client, error) {
+ if cmd == nil {
+ return nil, fmt.Errorf("nil command")
+ }
+ if app, ok := runtimectx.From(cmd.Context()); ok {
+ return app.UnauthClient()
+ }
+ return client.NewFromConfigUnauthenticated()
+}
+
+// JSONOutputEnabled returns true if JSON output is enabled for this command.
+func JSONOutputEnabled(cmd *cobra.Command) bool {
+ if cmd == nil {
+ return false
+ }
+ if flag := cmd.Flags().Lookup("json"); flag != nil && flag.Changed {
+ val, err := cmd.Flags().GetBool("json")
+ return err == nil && val
+ }
+ if app, ok := runtimectx.From(cmd.Context()); ok {
+ return app.IsJSON()
+ }
+ return false
+}
+
+// AssumeYes returns true when prompts should be skipped.
+func AssumeYes(cmd *cobra.Command) bool {
+ if cmd == nil {
+ return false
+ }
+ if app, ok := runtimectx.From(cmd.Context()); ok {
+ return app.AssumeYes()
+ }
+ return false
+}
+
+// ResolveOutputMode validates a free-form output mode value.
+func ResolveOutputMode(mode string) (runtimectx.OutputMode, error) {
+ normalized := strings.ToLower(strings.TrimSpace(mode))
+ if normalized == "" {
+ return runtimectx.OutputModeText, nil
+ }
+ switch runtimectx.OutputMode(normalized) {
+ case runtimectx.OutputModeText, runtimectx.OutputModeJSON:
+ return runtimectx.OutputMode(normalized), nil
+ default:
+ return "", fmt.Errorf("invalid output mode %q", mode)
+ }
+}
diff --git a/cli/internal/cmdutil/limit.go b/cli/internal/cmdutil/limit.go
new file mode 100644
index 000000000..f0894791e
--- /dev/null
+++ b/cli/internal/cmdutil/limit.go
@@ -0,0 +1,62 @@
+package cmdutil
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/cli/internal/config"
+ runtimectx "github.com/getarcaneapp/arcane/cli/internal/runtime"
+ clitypes "github.com/getarcaneapp/arcane/cli/internal/types"
+ "github.com/spf13/cobra"
+)
+
+// EffectiveLimit resolves the final list limit with precedence:
+// explicit flag > per-resource config > global config > fallback default.
+func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int {
+ if cmd != nil {
+ if flag := cmd.Flags().Lookup(flagName); flag != nil && flag.Changed {
+ if flagValue > 0 {
+ return flagValue
+ }
+ return 0
+ }
+ }
+
+ resource = clitypes.NormalizePaginatedResource(resource)
+ if app, ok := runtimectx.From(cmd.Context()); ok {
+ if cfg := app.Config(); cfg != nil {
+ if v := cfg.LimitFor(resource); v > 0 {
+ return v
+ }
+ }
+ } else if cfg, err := config.Load(); err == nil && cfg != nil {
+ if v := cfg.LimitFor(resource); v > 0 {
+ return v
+ }
+ }
+
+ if fallbackDefault > 0 {
+ return fallbackDefault
+ }
+ if flagValue > 0 {
+ return flagValue
+ }
+ return 0
+}
+
+// ParseResourceLimit parses a "resource=limit" pair.
+func ParseResourceLimit(pair string) (resource string, limit int, ok bool) {
+ left, right, found := strings.Cut(pair, "=")
+ if !found {
+ return "", 0, false
+ }
+ resource = clitypes.NormalizePaginatedResource(left)
+ if resource == "" {
+ return "", 0, false
+ }
+ parsed, err := strconv.Atoi(strings.TrimSpace(right))
+ if err != nil {
+ return "", 0, false
+ }
+ return resource, parsed, true
+}
diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.go
new file mode 100644
index 000000000..c2f854b4a
--- /dev/null
+++ b/cli/internal/cmdutil/response.go
@@ -0,0 +1,64 @@
+package cmdutil
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+)
+
+const maxErrorBodyBytes = 4096
+
+// HTTPStatusError represents a non-2xx HTTP response.
+type HTTPStatusError struct {
+ StatusCode int
+ Body string
+}
+
+func (e *HTTPStatusError) Error() string {
+ body := strings.TrimSpace(e.Body)
+ if body == "" {
+ return fmt.Sprintf("request failed with status %d", e.StatusCode)
+ }
+ return fmt.Sprintf("request failed with status %d: %s", e.StatusCode, body)
+}
+
+// EnsureSuccessStatus returns an error for non-2xx responses.
+func EnsureSuccessStatus(resp *http.Response) error {
+ if resp == nil {
+ return fmt.Errorf("nil HTTP response")
+ }
+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+ return nil
+ }
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))
+ return &HTTPStatusError{
+ StatusCode: resp.StatusCode,
+ Body: string(body),
+ }
+}
+
+// DecodeJSON decodes JSON into out and enforces a successful HTTP status.
+func DecodeJSON[T any](resp *http.Response, out *T) error {
+ if err := EnsureSuccessStatus(resp); err != nil {
+ return err
+ }
+ if out == nil {
+ return fmt.Errorf("nil decode target")
+ }
+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ return nil
+}
+
+// PrintJSON prints indented JSON to stdout.
+func PrintJSON(v any) error {
+ b, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(b))
+ return nil
+}
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
index 75deaf782..6d2cd3b76 100644
--- a/cli/internal/config/config.go
+++ b/cli/internal/config/config.go
@@ -25,9 +25,12 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
+ "time"
"github.com/getarcaneapp/arcane/cli/internal/types"
- "gopkg.in/yaml.v3"
+ "github.com/go-viper/mapstructure/v2"
+ "github.com/spf13/viper"
)
// Version and build information - set via ldflags at build time
@@ -37,11 +40,74 @@ var (
)
const (
- configFileName = "arcanecli.yml"
+ configFileName = "arcanecli.yml"
+ defaultPaginationInitLimit = 20
)
var customConfigPath string
+var (
+ cacheMu sync.RWMutex
+ cachedPath string
+ cachedCfg *types.Config
+ cacheLoaded bool
+)
+
+func cloneConfig(cfg *types.Config) *types.Config {
+ return cfg.Clone()
+}
+
+func normalizeConfig(cfg *types.Config) *types.Config {
+ if cfg == nil {
+ return DefaultConfig()
+ }
+ normalized := cfg.Clone()
+ if normalized == nil {
+ return DefaultConfig()
+ }
+
+ if normalized.Pagination.Default.Limit <= 0 && normalized.DefaultLimit > 0 {
+ normalized.Pagination.Default.Limit = normalized.DefaultLimit
+ }
+ if normalized.DefaultLimit <= 0 && normalized.Pagination.Default.Limit > 0 {
+ normalized.DefaultLimit = normalized.Pagination.Default.Limit
+ }
+
+ if normalized.Pagination.Resources == nil {
+ normalized.Pagination.Resources = make(map[string]types.PaginationResourceConfig)
+ }
+ if normalized.ResourceLimits == nil {
+ normalized.ResourceLimits = make(map[string]int)
+ }
+
+ for resource, limit := range normalized.ResourceLimits {
+ resource = types.NormalizePaginatedResource(resource)
+ if resource == "" || limit <= 0 {
+ continue
+ }
+ if _, exists := normalized.Pagination.Resources[resource]; !exists {
+ normalized.Pagination.Resources[resource] = types.PaginationResourceConfig{Limit: limit}
+ }
+ }
+ for resource, cfg := range normalized.Pagination.Resources {
+ resource = types.NormalizePaginatedResource(resource)
+ if resource == "" || cfg.Limit <= 0 {
+ continue
+ }
+ normalized.ResourceLimits[resource] = cfg.Limit
+ }
+
+ return normalized
+}
+
+func invalidateCache() {
+ cacheMu.Lock()
+ defer cacheMu.Unlock()
+ cacheLoaded = false
+ cachedPath = ""
+ cachedCfg = nil
+}
+
// DefaultConfig returns a Config with sensible default values.
// The defaults are:
// - ServerURL: http://localhost:3552
@@ -76,6 +142,7 @@ func ConfigPath() (string, error) {
func SetConfigPath(path string) error {
if strings.TrimSpace(path) == "" {
customConfigPath = ""
+ invalidateCache()
return nil
}
@@ -95,6 +162,7 @@ func SetConfigPath(path string) error {
}
customConfigPath = absPath
+ invalidateCache()
return nil
}
@@ -107,20 +175,55 @@ func Load() (*types.Config, error) {
return nil, err
}
+ cacheMu.RLock()
+ if cacheLoaded && cachedCfg != nil && cachedPath == path {
+ cfg := cloneConfig(cachedCfg)
+ cacheMu.RUnlock()
+ return cfg, nil
+ }
+ cacheMu.RUnlock()
+
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
- return DefaultConfig(), nil
+ def := DefaultConfig()
+ cacheMu.Lock()
+ cacheLoaded = true
+ cachedPath = path
+ cachedCfg = cloneConfig(def)
+ cacheMu.Unlock()
+ return def, nil
}
return nil, fmt.Errorf("failed to read config file: %w", err)
}
+ _ = data
- var cfg types.Config
- if err := yaml.Unmarshal(data, &cfg); err != nil {
+ v := viper.New()
+ v.SetConfigFile(path)
+ v.SetConfigType("yaml")
+ v.SetDefault("server_url", "http://localhost:3552")
+ v.SetDefault("default_environment", "0")
+ v.SetDefault("log_level", "info")
+ if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed to parse config file: %w", err)
}
- return &cfg, nil
+ var cfg types.Config
+ if err := v.Unmarshal(&cfg, func(dc *mapstructure.DecoderConfig) {
+ dc.TagName = "mapstructure"
+ dc.WeaklyTypedInput = true
+ }); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal config: %w", err)
+ }
+ normalized := normalizeConfig(&cfg)
+
+ cacheMu.Lock()
+ cacheLoaded = true
+ cachedPath = path
+ cachedCfg = cloneConfig(normalized)
+ cacheMu.Unlock()
+
+ return normalized, nil
}
// Save writes the configuration to disk.
@@ -138,14 +241,169 @@ func Save(c *types.Config) error {
return fmt.Errorf("failed to create config directory: %w", err)
}
- data, err := yaml.Marshal(c)
- if err != nil {
- return fmt.Errorf("failed to serialize config: %w", err)
+ cfg := normalizeConfig(c)
+ v := viper.New()
+ v.SetConfigType("yaml")
+ v.Set("server_url", cfg.ServerURL)
+ if cfg.APIKey != "" {
+ v.Set("api_key", cfg.APIKey)
+ }
+ if cfg.JWTToken != "" {
+ v.Set("jwt_token", cfg.JWTToken)
+ }
+ if cfg.RefreshToken != "" {
+ v.Set("refresh_token", cfg.RefreshToken)
+ }
+ if cfg.DefaultEnvironment != "" {
+ v.Set("default_environment", cfg.DefaultEnvironment)
+ }
+ if cfg.LogLevel != "" {
+ v.Set("log_level", cfg.LogLevel)
+ }
+
+ // Canonical pagination structure.
+ if cfg.Pagination.Default.Limit > 0 {
+ v.Set("pagination.default.limit", cfg.Pagination.Default.Limit)
+ }
+ for resource, rc := range cfg.Pagination.Resources {
+ resource = types.NormalizePaginatedResource(resource)
+ if resource == "" || rc.Limit <= 0 {
+ continue
+ }
+ v.Set(fmt.Sprintf("pagination.resources.%s.limit", resource), rc.Limit)
}
- if err := os.WriteFile(path, data, 0o600); err != nil {
+ // Legacy keys retained for backward compatibility.
+ if cfg.DefaultLimit > 0 {
+ v.Set("default_limit", cfg.DefaultLimit)
+ }
+ if len(cfg.ResourceLimits) > 0 {
+ legacy := make(map[string]int)
+ for resource, limit := range cfg.ResourceLimits {
+ resource = types.NormalizePaginatedResource(resource)
+ if resource == "" || limit <= 0 {
+ continue
+ }
+ legacy[resource] = limit
+ }
+ if len(legacy) > 0 {
+ v.Set("resource_limits", legacy)
+ }
+ }
+
+ if err := v.WriteConfigAs(path); err != nil {
return fmt.Errorf("failed to write config file: %w", err)
}
+ if err := os.Chmod(path, 0o600); err != nil {
+ return fmt.Errorf("failed to set config permissions: %w", err)
+ }
+
+ cacheMu.Lock()
+ cacheLoaded = true
+ cachedPath = path
+ cachedCfg = cloneConfig(cfg)
+ cacheMu.Unlock()
return nil
}
+
+// InitDefaultFile creates a default config file with all known keys if one does
+// not already exist. It returns true when a file is created, or false when an
+// existing file is left unchanged.
+func InitDefaultFile() (bool, error) {
+ path, err := ConfigPath()
+ if err != nil {
+ return false, err
+ }
+
+ info, err := os.Stat(path)
+ switch {
+ case err == nil:
+ if info.IsDir() {
+ return false, fmt.Errorf("config path is a directory: %s", path)
+ }
+ return false, nil
+ case os.IsNotExist(err):
+ // Continue and create the file below.
+ default:
+ return false, fmt.Errorf("failed to stat config path: %w", err)
+ }
+
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return false, fmt.Errorf("failed to create config directory: %w", err)
+ }
+
+ v := viper.New()
+ v.SetConfigType("yaml")
+ v.Set("server_url", "http://localhost:3552")
+ v.Set("api_key", "")
+ v.Set("jwt_token", "")
+ v.Set("refresh_token", "")
+ v.Set("default_environment", "0")
+ v.Set("log_level", "info")
+
+ v.Set("pagination.default.limit", defaultPaginationInitLimit)
+ for _, resource := range types.KnownPaginatedResources {
+ v.Set(fmt.Sprintf("pagination.resources.%s.limit", resource), defaultPaginationInitLimit)
+ }
+
+ v.Set("default_limit", defaultPaginationInitLimit)
+ legacy := make(map[string]int, len(types.KnownPaginatedResources))
+ for _, resource := range types.KnownPaginatedResources {
+ legacy[resource] = defaultPaginationInitLimit
+ }
+ v.Set("resource_limits", legacy)
+
+ if err := v.WriteConfigAs(path); err != nil {
+ return false, fmt.Errorf("failed to write config file: %w", err)
+ }
+ if err := os.Chmod(path, 0o600); err != nil {
+ return false, fmt.Errorf("failed to set config permissions: %w", err)
+ }
+
+ invalidateCache()
+ return true, 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.
+func BackupFile() (backupPath string, moved bool, err error) {
+ path, err := ConfigPath()
+ if err != nil {
+ return "", false, err
+ }
+ backupPath = path + ".bak"
+
+ info, err := os.Stat(path)
+ switch {
+ case err == nil:
+ if info.IsDir() {
+ return "", false, fmt.Errorf("config path is a directory: %s", path)
+ }
+ case os.IsNotExist(err):
+ return backupPath, false, nil
+ default:
+ return "", false, fmt.Errorf("failed to stat config path: %w", err)
+ }
+
+ if existingBackup, backupErr := os.Stat(backupPath); backupErr == nil {
+ if existingBackup.IsDir() {
+ return "", false, fmt.Errorf("backup path is a directory: %s", backupPath)
+ }
+ rotatedPath := fmt.Sprintf("%s.%s", backupPath, time.Now().UTC().Format("20060102150405"))
+ if err := os.Rename(backupPath, rotatedPath); err != nil {
+ return "", false, fmt.Errorf("failed to rotate existing backup %s: %w", backupPath, err)
+ }
+ } else if !os.IsNotExist(backupErr) {
+ return "", false, fmt.Errorf("failed to stat backup path: %w", backupErr)
+ }
+
+ if err := os.Rename(path, backupPath); err != nil {
+ return "", false, fmt.Errorf("failed to move config to backup: %w", err)
+ }
+
+ invalidateCache()
+ return backupPath, true, nil
+}
diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go
new file mode 100644
index 000000000..6b618a0e7
--- /dev/null
+++ b/cli/internal/config/config_test.go
@@ -0,0 +1,347 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func setTempConfigPath(t *testing.T) string {
+ t.Helper()
+
+ path := filepath.Join(t.TempDir(), "arcanecli.yml")
+ if err := SetConfigPath(path); err != nil {
+ t.Fatalf("SetConfigPath() failed: %v", err)
+ }
+ t.Cleanup(func() {
+ if err := SetConfigPath(""); err != nil {
+ t.Errorf("SetConfigPath(reset) failed: %v", err)
+ }
+ })
+ return path
+}
+
+func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {
+ path := setTempConfigPath(t)
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("expected config file to be missing, got err=%v", err)
+ }
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() failed: %v", err)
+ }
+ if cfg.ServerURL != "http://localhost:3552" {
+ t.Fatalf("ServerURL=%q, want %q", cfg.ServerURL, "http://localhost:3552")
+ }
+ if cfg.DefaultEnvironment != "0" {
+ t.Fatalf("DefaultEnvironment=%q, want %q", cfg.DefaultEnvironment, "0")
+ }
+ if cfg.LogLevel != "info" {
+ t.Fatalf("LogLevel=%q, want %q", cfg.LogLevel, "info")
+ }
+
+ // Ensure callers cannot mutate cached config state.
+ cfg.ServerURL = "https://mutated.invalid"
+ cfg2, err := Load()
+ if err != nil {
+ t.Fatalf("Load() second call failed: %v", err)
+ }
+ if cfg2.ServerURL != "http://localhost:3552" {
+ t.Fatalf("cached config was mutated, ServerURL=%q", cfg2.ServerURL)
+ }
+}
+
+func TestSaveAndLoadRoundTripPaginationCompatibility(t *testing.T) {
+ path := setTempConfigPath(t)
+
+ cfg := DefaultConfig()
+ cfg.APIKey = "k_test"
+ cfg.SetDefaultLimit(42)
+ cfg.SetResourceLimit("images", 17)
+ cfg.SetResourceLimit("Containers", 9)
+
+ if err := Save(cfg); err != nil {
+ t.Fatalf("Save() failed: %v", err)
+ }
+
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("failed to read saved config: %v", err)
+ }
+ text := string(raw)
+ if !strings.Contains(text, "pagination:") {
+ t.Fatalf("expected saved YAML to include pagination block:\n%s", text)
+ }
+ if !strings.Contains(text, "default_limit: 42") {
+ t.Fatalf("expected saved YAML to include legacy default_limit key:\n%s", text)
+ }
+ if !strings.Contains(text, "resource_limits:") {
+ t.Fatalf("expected saved YAML to include legacy resource_limits key:\n%s", text)
+ }
+
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("failed to stat config file: %v", err)
+ }
+ if got := info.Mode().Perm(); got != 0o600 {
+ t.Fatalf("config file permissions=%#o, want %#o", got, 0o600)
+ }
+
+ loaded, err := Load()
+ if err != nil {
+ t.Fatalf("Load() failed: %v", err)
+ }
+ if loaded.Pagination.Default.Limit != 42 || loaded.DefaultLimit != 42 {
+ t.Fatalf("default limit mismatch: pagination=%d legacy=%d", loaded.Pagination.Default.Limit, loaded.DefaultLimit)
+ }
+ if got := loaded.LimitFor("images"); got != 17 {
+ t.Fatalf("images limit=%d, want 17", got)
+ }
+ if got := loaded.LimitFor("containers"); got != 9 {
+ t.Fatalf("containers limit=%d, want 9", got)
+ }
+}
+
+func TestLoadLegacyPaginationKeys(t *testing.T) {
+ path := setTempConfigPath(t)
+ content := `
+server_url: https://arcane.example
+default_environment: "7"
+log_level: warn
+default_limit: 25
+resource_limits:
+ image: 31
+ Volumes: 5
+`
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatalf("failed to write config fixture: %v", err)
+ }
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() failed: %v", err)
+ }
+ if cfg.ServerURL != "https://arcane.example" {
+ t.Fatalf("ServerURL=%q, want %q", cfg.ServerURL, "https://arcane.example")
+ }
+ if cfg.Pagination.Default.Limit != 25 || cfg.DefaultLimit != 25 {
+ t.Fatalf("default limit mismatch: pagination=%d legacy=%d", cfg.Pagination.Default.Limit, cfg.DefaultLimit)
+ }
+ if got := cfg.LimitFor("images"); got != 31 {
+ t.Fatalf("images limit=%d, want 31", got)
+ }
+ if got := cfg.LimitFor("volumes"); got != 5 {
+ t.Fatalf("volumes limit=%d, want 5", got)
+ }
+}
+
+func TestLoadCanonicalPaginationBlock(t *testing.T) {
+ path := setTempConfigPath(t)
+ content := `
+server_url: https://api.arcane.test
+api_key: k_123
+default_environment: "2"
+log_level: debug
+pagination:
+ default:
+ limit: 13
+ resources:
+ networks:
+ limit: 4
+ registries:
+ limit: 9
+`
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatalf("failed to write config fixture: %v", err)
+ }
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() failed: %v", err)
+ }
+ if cfg.ServerURL != "https://api.arcane.test" {
+ t.Fatalf("ServerURL=%q, want %q", cfg.ServerURL, "https://api.arcane.test")
+ }
+ if cfg.APIKey != "k_123" {
+ t.Fatalf("APIKey=%q, want %q", cfg.APIKey, "k_123")
+ }
+ if cfg.Pagination.Default.Limit != 13 {
+ t.Fatalf("Pagination.Default.Limit=%d, want 13", cfg.Pagination.Default.Limit)
+ }
+ if got := cfg.LimitFor("networks"); got != 4 {
+ t.Fatalf("networks limit=%d, want 4", got)
+ }
+ if got := cfg.LimitFor("registries"); got != 9 {
+ t.Fatalf("registries limit=%d, want 9", got)
+ }
+}
+
+func TestInitDefaultFileCreatesTemplate(t *testing.T) {
+ path := setTempConfigPath(t)
+
+ created, err := InitDefaultFile()
+ if err != nil {
+ t.Fatalf("InitDefaultFile() failed: %v", err)
+ }
+ if !created {
+ t.Fatal("InitDefaultFile() created = false, want true")
+ }
+
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("failed to read config file: %v", err)
+ }
+ text := string(raw)
+
+ requiredKeys := []string{
+ "server_url:",
+ "api_key:",
+ "jwt_token:",
+ "refresh_token:",
+ "default_environment:",
+ "log_level:",
+ "pagination:",
+ "default_limit:",
+ "resource_limits:",
+ }
+ for _, key := range requiredKeys {
+ if !strings.Contains(text, key) {
+ t.Fatalf("expected generated config to contain %q:\n%s", key, text)
+ }
+ }
+ for _, resource := range []string{"containers", "images", "volumes", "networks", "projects", "environments", "registries", "templates", "users", "events", "apikeys"} {
+ if !strings.Contains(text, resource+":") {
+ t.Fatalf("expected generated config to contain resource key %q:\n%s", resource, text)
+ }
+ }
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() after init failed: %v", err)
+ }
+ if cfg.Pagination.Default.Limit != defaultPaginationInitLimit {
+ t.Fatalf("Pagination.Default.Limit=%d, want %d", cfg.Pagination.Default.Limit, defaultPaginationInitLimit)
+ }
+ if cfg.DefaultLimit != defaultPaginationInitLimit {
+ t.Fatalf("DefaultLimit=%d, want %d", cfg.DefaultLimit, defaultPaginationInitLimit)
+ }
+ for _, resource := range []string{"containers", "images", "volumes", "networks", "projects", "environments", "registries", "templates", "users", "events", "apikeys"} {
+ if got := cfg.LimitFor(resource); got != defaultPaginationInitLimit {
+ t.Fatalf("LimitFor(%s)=%d, want %d", resource, got, defaultPaginationInitLimit)
+ }
+ }
+}
+
+func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {
+ path := setTempConfigPath(t)
+ original := "server_url: https://custom.arcane.example\napi_key: custom\n"
+ if err := os.WriteFile(path, []byte(original), 0o600); err != nil {
+ t.Fatalf("failed to write fixture file: %v", err)
+ }
+
+ created, err := InitDefaultFile()
+ if err != nil {
+ t.Fatalf("InitDefaultFile() failed: %v", err)
+ }
+ if created {
+ t.Fatal("InitDefaultFile() created = true, want false")
+ }
+
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("failed to read config file: %v", err)
+ }
+ if string(raw) != original {
+ t.Fatalf("existing file was modified:\nwant:\n%s\ngot:\n%s", original, string(raw))
+ }
+}
+
+func TestBackupFileMovesConfig(t *testing.T) {
+ path := setTempConfigPath(t)
+ original := "server_url: https://backup.arcane.example\napi_key: abc123\n"
+ if err := os.WriteFile(path, []byte(original), 0o600); err != nil {
+ t.Fatalf("failed to write config fixture: %v", err)
+ }
+
+ backupPath, moved, err := BackupFile()
+ if err != nil {
+ t.Fatalf("BackupFile() failed: %v", err)
+ }
+ if !moved {
+ t.Fatal("BackupFile() moved = false, want true")
+ }
+ if backupPath != path+".bak" {
+ t.Fatalf("backup path = %q, want %q", backupPath, path+".bak")
+ }
+
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("expected original config to be removed, stat err=%v", err)
+ }
+
+ raw, err := os.ReadFile(backupPath)
+ if err != nil {
+ t.Fatalf("failed to read backup file: %v", err)
+ }
+ if string(raw) != original {
+ t.Fatalf("backup content mismatch:\nwant:\n%s\ngot:\n%s", original, string(raw))
+ }
+}
+
+func TestBackupFileNoConfig(t *testing.T) {
+ path := setTempConfigPath(t)
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("expected missing config before backup, stat err=%v", err)
+ }
+
+ backupPath, moved, err := BackupFile()
+ if err != nil {
+ t.Fatalf("BackupFile() failed: %v", err)
+ }
+ if moved {
+ t.Fatal("BackupFile() moved = true, want false")
+ }
+ if backupPath != path+".bak" {
+ t.Fatalf("backup path = %q, want %q", backupPath, path+".bak")
+ }
+}
+
+func TestBackupFileRotatesExistingBak(t *testing.T) {
+ path := setTempConfigPath(t)
+ backupPath := path + ".bak"
+
+ if err := os.WriteFile(path, []byte("server_url: https://new.example\n"), 0o600); err != nil {
+ t.Fatalf("failed to write primary config: %v", err)
+ }
+ if err := os.WriteFile(backupPath, []byte("server_url: https://old.example\n"), 0o600); err != nil {
+ t.Fatalf("failed to write existing backup: %v", err)
+ }
+
+ newBackupPath, moved, err := BackupFile()
+ if err != nil {
+ t.Fatalf("BackupFile() failed: %v", err)
+ }
+ if !moved {
+ t.Fatal("BackupFile() moved = false, want true")
+ }
+ if newBackupPath != backupPath {
+ t.Fatalf("backup path = %q, want %q", newBackupPath, backupPath)
+ }
+
+ raw, err := os.ReadFile(backupPath)
+ if err != nil {
+ t.Fatalf("failed to read newest backup: %v", err)
+ }
+ if !strings.Contains(string(raw), "new.example") {
+ t.Fatalf("expected newest backup to contain new config, got:\n%s", string(raw))
+ }
+
+ rotated, err := filepath.Glob(backupPath + ".*")
+ if err != nil {
+ t.Fatalf("failed to glob rotated backups: %v", err)
+ }
+ if len(rotated) == 0 {
+ t.Fatalf("expected rotated backup matching %q", backupPath+".*")
+ }
+}
diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/internal/integrationtest/json_contract_test.go
new file mode 100644
index 000000000..08721d50f
--- /dev/null
+++ b/cli/internal/integrationtest/json_contract_test.go
@@ -0,0 +1,86 @@
+package integrationtest
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ clipkg "github.com/getarcaneapp/arcane/cli/pkg"
+)
+
+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()
+
+ tempDir := t.TempDir()
+ configPath := filepath.Join(tempDir, "arcanecli.yml")
+ configContent := strings.Join([]string{
+ "server_url: " + srv.URL,
+ "api_key: arc_test_key",
+ "default_environment: \"0\"",
+ "log_level: info",
+ "",
+ }, "\n")
+ if err := os.WriteFile(configPath, []byte(configContent), 0o600); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ root := clipkg.RootCommand()
+ errOut := &strings.Builder{}
+ root.SetErr(errOut)
+ root.SetArgs([]string{"--config", configPath, "containers", "list", "--json"})
+
+ stdout := os.Stdout
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("pipe: %v", err)
+ }
+ os.Stdout = w
+ defer func() {
+ _ = w.Close()
+ os.Stdout = stdout
+ }()
+
+ if err := root.Execute(); err != nil {
+ t.Fatalf("execute: %v (%s)", err, errOut.String())
+ }
+ _ = w.Close()
+ stdoutBytes, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatalf("read stdout: %v", err)
+ }
+ outBuf := string(stdoutBytes)
+ if runtime.GOOS == "windows" {
+ outBuf = strings.ReplaceAll(outBuf, "\r\n", "\n")
+ }
+
+ var got map[string]any
+ if err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got); err != nil {
+ t.Fatalf("json parse failed: %v\noutput=%s", err, outBuf)
+ }
+ for _, key := range []string{"success", "data", "pagination"} {
+ if _, ok := got[key]; !ok {
+ t.Fatalf("missing key %q in output: %v", key, got)
+ }
+ }
+}
diff --git a/cli/internal/output/output.go b/cli/internal/output/output.go
index 0b93ef30f..972d78938 100644
--- a/cli/internal/output/output.go
+++ b/cli/internal/output/output.go
@@ -14,68 +14,120 @@ package output
import (
"fmt"
+ "os"
"regexp"
"strings"
"github.com/charmbracelet/lipgloss"
+ "github.com/charmbracelet/x/term"
"github.com/mattn/go-runewidth"
)
-const arcanePurple = lipgloss.Color("#6d28d9")
+var (
+ arcanePurple = lipgloss.AdaptiveColor{
+ Light: "#6d28d9",
+ Dark: "#a78bfa",
+ }
+ textPrimary = lipgloss.AdaptiveColor{
+ Light: "#1f2937",
+ Dark: "#e5e7eb",
+ }
+ textMuted = lipgloss.AdaptiveColor{
+ Light: "#64748b",
+ Dark: "#cbd5e1",
+ }
+ statusOnline = lipgloss.AdaptiveColor{
+ Light: "#15803d",
+ Dark: "#4ade80",
+ }
+ statusOffline = lipgloss.AdaptiveColor{
+ Light: "#b91c1c",
+ Dark: "#f87171",
+ }
+ statusWarn = lipgloss.AdaptiveColor{
+ Light: "#b45309",
+ Dark: "#fbbf24",
+ }
+)
var (
- successStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("10"))
- errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
- warnStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
+ successStyle = lipgloss.NewStyle().Foreground(statusOnline)
+ errorStyle = lipgloss.NewStyle().Foreground(statusOffline)
+ warnStyle = lipgloss.NewStyle().Foreground(statusWarn)
infoStyle = lipgloss.NewStyle().Foreground(arcanePurple)
headerStyle = lipgloss.NewStyle().Bold(true).Foreground(arcanePurple)
- keyStyle = lipgloss.NewStyle().Bold(true)
+ keyStyle = lipgloss.NewStyle().Bold(true).Foreground(textPrimary)
valueStyle = lipgloss.NewStyle().Foreground(arcanePurple)
- columnStyle = lipgloss.NewStyle().Foreground(arcanePurple)
+
+ // Keep purple as accent in headers, but avoid purple body cells for readability.
+ columnStyle = lipgloss.NewStyle().Foreground(textPrimary)
columnHeader = lipgloss.NewStyle().Bold(true).Foreground(arcanePurple)
- statusOnlineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#22c55e"))
- statusOfflineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ef4444"))
- statusWarnStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#f59e0b"))
- statusMutedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#94a3b8"))
+ statusOnlineStyle = lipgloss.NewStyle().Foreground(statusOnline)
+ statusOfflineStyle = lipgloss.NewStyle().Foreground(statusOffline)
+ statusWarnStyle = lipgloss.NewStyle().Foreground(statusWarn)
+ statusMutedStyle = lipgloss.NewStyle().Foreground(textMuted)
enabledStyle = lipgloss.NewStyle().Foreground(arcanePurple)
)
var ansiRegexp = regexp.MustCompile("\x1b\\[[0-9;]*[a-zA-Z]")
+var colorEnabled = true
+
+func shouldColor() bool {
+ return colorEnabled && term.IsTerminal(os.Stdout.Fd())
+}
+
+func render(style lipgloss.Style, value string) string {
+ if !shouldColor() {
+ return value
+ }
+ return style.Render(value)
+}
+
+// SetColorEnabled controls whether CLI output should render ANSI colors.
+func SetColorEnabled(enabled bool) {
+ colorEnabled = enabled
+}
+
// Success prints a success message in green.
// The message is prefixed with a newline for visual separation.
// Format specifiers and arguments work like fmt.Printf.
func Success(format string, a ...any) {
- fmt.Printf("\n%s\n", successStyle.Render(fmt.Sprintf(format, a...)))
+ msg := fmt.Sprintf(format, a...)
+ fmt.Printf("\n%s\n", render(successStyle, msg))
}
// Error prints an error message in red.
// The message is prefixed with a newline for visual separation.
// Format specifiers and arguments work like fmt.Printf.
func Error(format string, a ...any) {
- fmt.Printf("\n%s\n", errorStyle.Render(fmt.Sprintf(format, a...)))
+ msg := fmt.Sprintf(format, a...)
+ fmt.Printf("\n%s\n", render(errorStyle, msg))
}
// Warning prints a warning message in yellow.
// The message is prefixed with a newline for visual separation.
// Format specifiers and arguments work like fmt.Printf.
func Warning(format string, a ...any) {
- fmt.Printf("\n%s\n", warnStyle.Render(fmt.Sprintf(format, a...)))
+ msg := fmt.Sprintf(format, a...)
+ fmt.Printf("\n%s\n", render(warnStyle, msg))
}
// Info prints an info message in cyan.
// The message is prefixed with a newline for visual separation.
// Format specifiers and arguments work like fmt.Printf.
func Info(format string, a ...any) {
- fmt.Printf("\n%s\n", infoStyle.Render(fmt.Sprintf(format, a...)))
+ msg := fmt.Sprintf(format, a...)
+ fmt.Printf("\n%s\n", render(infoStyle, msg))
}
// Header prints a header message in bold white.
// Use this to introduce sections of output. The message is prefixed
// with a newline for visual separation.
func Header(format string, a ...any) {
- fmt.Printf("\n%s\n", headerStyle.Render(fmt.Sprintf(format, a...)))
+ msg := fmt.Sprintf(format, a...)
+ fmt.Printf("\n%s\n", render(headerStyle, msg))
}
// Print prints a standard message without color formatting.
@@ -88,7 +140,9 @@ func Print(format string, a ...any) {
// This is useful for displaying structured information like image details
// or configuration values.
func KeyValue(key string, value any) {
- fmt.Printf("%s: %v\n", keyStyle.Render(key), valueStyle.Render(fmt.Sprint(value)))
+ keyText := key
+ valueText := fmt.Sprint(value)
+ fmt.Printf("%s: %v\n", render(keyStyle, keyText), render(valueStyle, valueText))
}
func stripAnsi(s string) string {
@@ -108,7 +162,7 @@ func hasAnsi(s string) bool {
// TintStatus applies semantic status coloring to a value.
func TintStatus(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsi(trimmed) {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -128,7 +182,7 @@ func TintStatus(value string) string {
// TintEnabled applies tints for enabled/disabled values.
func TintEnabled(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsi(trimmed) {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -145,7 +199,7 @@ func TintEnabled(value string) string {
// TintYesNo applies tints for yes/no style values.
func TintYesNo(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsi(trimmed) {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -162,7 +216,7 @@ func TintYesNo(value string) string {
// TintInsecure applies warning tints for insecure values.
func TintInsecure(value string) string {
trimmed := strings.TrimSpace(value)
- if trimmed == "" || hasAnsi(trimmed) {
+ if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {
return value
}
lower := strings.ToLower(trimmed)
@@ -200,6 +254,9 @@ func tintTableRows(headers []string, rows [][]string) [][]string {
if len(rows) == 0 {
return rows
}
+ if !shouldColor() {
+ return rows
+ }
result := make([][]string, len(rows))
for i, row := range rows {
@@ -256,7 +313,7 @@ func printHeader(headers []string, widths []int) {
n := len(headers)
for i, h := range headers {
visible := stripAnsi(h)
- colored := columnHeader.Render(h)
+ colored := render(columnHeader, h)
padLen := max(widths[i]-runewidth.StringWidth(visible), 0)
if i < n-1 {
fmt.Print(colored + strings.Repeat(" ", padLen) + sep)
@@ -294,7 +351,7 @@ func printRow(row []string, widths []int, n int) {
var rendered string
if i == 0 {
- rendered = columnStyle.Render(val)
+ rendered = render(columnStyle, val)
} else {
rendered = fmt.Sprint(val)
}
diff --git a/cli/internal/runstate/state.go b/cli/internal/runstate/state.go
new file mode 100644
index 000000000..ede998199
--- /dev/null
+++ b/cli/internal/runstate/state.go
@@ -0,0 +1,31 @@
+package runstate
+
+import (
+ "sync"
+ "time"
+)
+
+type State struct {
+ EnvOverride string
+ OutputMode string
+ AssumeYes bool
+ NoColor bool
+ RequestTimeout time.Duration
+}
+
+var (
+ mu sync.RWMutex
+ state State
+)
+
+func Set(next State) {
+ mu.Lock()
+ defer mu.Unlock()
+ state = next
+}
+
+func Get() State {
+ mu.RLock()
+ defer mu.RUnlock()
+ return state
+}
diff --git a/cli/internal/runtime/context.go b/cli/internal/runtime/context.go
new file mode 100644
index 000000000..9c0aaa2e4
--- /dev/null
+++ b/cli/internal/runtime/context.go
@@ -0,0 +1,174 @@
+package runtime
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/config"
+ clitypes "github.com/getarcaneapp/arcane/cli/internal/types"
+)
+
+type contextKey string
+
+const appContextKey contextKey = "arcane_app_context"
+
+type OutputMode string
+
+const (
+ OutputModeText OutputMode = "text"
+ OutputModeJSON OutputMode = "json"
+)
+
+type Options struct {
+ EnvOverride string
+ OutputMode OutputMode
+ AssumeYes bool
+ NoColor bool
+ RequestTimeout time.Duration
+}
+
+type AppContext struct {
+ cfg *clitypes.Config
+ envOverride string
+ outputMode OutputMode
+ assumeYes bool
+ noColor bool
+ requestTimeout time.Duration
+
+ clientOnce sync.Once
+ clientErr error
+ client *client.Client
+
+ unauthClientOnce sync.Once
+ unauthClientErr error
+ unauthClient *client.Client
+}
+
+func New(opts Options) (*AppContext, error) {
+ cfg, err := config.Load()
+ if err != nil {
+ return nil, fmt.Errorf("failed to load config: %w", err)
+ }
+
+ mode := opts.OutputMode
+ if mode == "" {
+ mode = OutputModeText
+ }
+ switch mode {
+ case OutputModeText, OutputModeJSON:
+ default:
+ 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
+}
+
+func WithAppContext(ctx context.Context, app *AppContext) context.Context {
+ return context.WithValue(ctx, appContextKey, app)
+}
+
+func From(ctx context.Context) (*AppContext, bool) {
+ if ctx == nil {
+ return nil, false
+ }
+ app, ok := ctx.Value(appContextKey).(*AppContext)
+ return app, ok && app != nil
+}
+
+func (a *AppContext) Config() *clitypes.Config {
+ if a == nil || a.cfg == nil {
+ return nil
+ }
+ copyCfg := a.cfg.Clone()
+ if copyCfg == nil {
+ return nil
+ }
+ if a.envOverride != "" {
+ copyCfg.DefaultEnvironment = a.envOverride
+ }
+ return copyCfg
+}
+
+func (a *AppContext) EnvID() string {
+ if a == nil {
+ return ""
+ }
+ if a.envOverride != "" {
+ return a.envOverride
+ }
+ if a.cfg != nil {
+ return a.cfg.DefaultEnvironment
+ }
+ 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
+}
+
+func (a *AppContext) Client() (*client.Client, error) {
+ if a == nil {
+ return client.NewFromConfig()
+ }
+ a.clientOnce.Do(func() {
+ cfg := a.Config()
+ a.client, a.clientErr = client.New(cfg)
+ if a.clientErr != nil {
+ return
+ }
+ if a.requestTimeout > 0 {
+ a.client.SetTimeout(a.requestTimeout)
+ }
+ })
+ return a.client, a.clientErr
+}
+
+func (a *AppContext) UnauthClient() (*client.Client, error) {
+ if a == nil {
+ return client.NewFromConfigUnauthenticated()
+ }
+ a.unauthClientOnce.Do(func() {
+ cfg := a.Config()
+ a.unauthClient, a.unauthClientErr = client.NewUnauthenticated(cfg)
+ if a.unauthClientErr != nil {
+ return
+ }
+ if a.requestTimeout > 0 {
+ a.unauthClient.SetTimeout(a.requestTimeout)
+ }
+ })
+ return a.unauthClient, a.unauthClientErr
+}
diff --git a/cli/internal/types/config.go b/cli/internal/types/config.go
index 13e9d7acc..092691d35 100644
--- a/cli/internal/types/config.go
+++ b/cli/internal/types/config.go
@@ -1,22 +1,94 @@
package types
-import "fmt"
+import (
+ "fmt"
+ "strings"
+)
+
+// PaginationResourceConfig defines pagination options for a specific resource.
+type PaginationResourceConfig struct {
+ // Limit is the default page size for list commands for this resource.
+ Limit int `yaml:"limit,omitempty" mapstructure:"limit"`
+}
+
+// PaginationConfig contains global and per-resource pagination settings.
+type PaginationConfig struct {
+ // Default applies to paginated resources that do not have explicit per-resource config.
+ Default PaginationResourceConfig `yaml:"default,omitempty" mapstructure:"default"`
+ // Resources contains per-resource pagination settings keyed by resource name.
+ Resources map[string]PaginationResourceConfig `yaml:"resources,omitempty" mapstructure:"resources"`
+}
+
+// KnownPaginatedResources is the canonical list of paginated CLI resources.
+var KnownPaginatedResources = []string{
+ "containers",
+ "images",
+ "volumes",
+ "networks",
+ "projects",
+ "environments",
+ "registries",
+ "templates",
+ "users",
+ "events",
+ "apikeys",
+}
+
+// NormalizePaginatedResource normalizes resource names and common aliases.
+func NormalizePaginatedResource(resource string) string {
+ r := strings.ToLower(strings.TrimSpace(resource))
+ r = strings.ReplaceAll(r, "_", "")
+ r = strings.ReplaceAll(r, "-", "")
+ r = strings.ReplaceAll(r, " ", "")
+ switch r {
+ case "apikey", "apikeys", "keys", "key":
+ return "apikeys"
+ case "container":
+ return "containers"
+ case "image":
+ return "images"
+ case "volume":
+ return "volumes"
+ case "network":
+ return "networks"
+ case "project":
+ return "projects"
+ case "environment":
+ return "environments"
+ case "registry", "registrys":
+ return "registries"
+ case "template":
+ return "templates"
+ case "user":
+ return "users"
+ case "event":
+ return "events"
+ default:
+ return r
+ }
+}
// Config holds the CLI configuration for connecting to an Arcane server.
// 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)
- ServerURL string `yaml:"server_url"`
+ ServerURL string `yaml:"server_url" mapstructure:"server_url"`
// APIKey is the API key for authentication (sent as X-API-KEY)
- APIKey string `yaml:"api_key,omitempty"` //nolint:gosec // persisted config schema requires this field name
+ APIKey string `yaml:"api_key,omitempty" mapstructure:"api_key"` //nolint:gosec // persisted config schema requires this field name
// JWTToken is the JWT access token for authentication (sent as Authorization: Bearer)
- JWTToken string `yaml:"jwt_token,omitempty"` //nolint:gosec // persisted config schema requires this field name
+ JWTToken string `yaml:"jwt_token,omitempty" mapstructure:"jwt_token"` //nolint:gosec // persisted config schema requires this field name
// RefreshToken is the refresh token for obtaining new access tokens
- RefreshToken string `yaml:"refresh_token,omitempty"` //nolint:gosec // persisted config schema requires this field name
+ RefreshToken string `yaml:"refresh_token,omitempty" mapstructure:"refresh_token"` //nolint:gosec // persisted config schema requires this field name
// DefaultEnvironment is the default environment ID to use
- DefaultEnvironment string `yaml:"default_environment,omitempty"`
+ DefaultEnvironment string `yaml:"default_environment,omitempty" mapstructure:"default_environment"`
// LogLevel is the logging level (debug, info, warn, error, fatal, panic)
- LogLevel string `yaml:"log_level,omitempty"`
+ LogLevel string `yaml:"log_level,omitempty" mapstructure:"log_level"`
+ // Pagination contains global and per-resource pagination configuration.
+ Pagination PaginationConfig `yaml:"pagination,omitempty" mapstructure:"pagination"`
+ // DefaultLimit is a legacy global default list limit for paginated resources.
+ DefaultLimit int `yaml:"default_limit,omitempty" mapstructure:"default_limit"`
+ // ResourceLimits is a legacy map of per-resource list limits.
+ ResourceLimits map[string]int `yaml:"resource_limits,omitempty" mapstructure:"resource_limits"`
}
// HasAuth returns true if either an API key or JWT token is configured.
@@ -52,3 +124,86 @@ func (c *Config) Validate() error {
func (c *Config) IsConfigured() bool {
return c.ServerURL != "" && c.HasAuth()
}
+
+// Clone returns a deep-copy of Config.
+func (c *Config) Clone() *Config {
+ if c == nil {
+ return nil
+ }
+ out := *c
+ if c.ResourceLimits != nil {
+ out.ResourceLimits = make(map[string]int, len(c.ResourceLimits))
+ for k, v := range c.ResourceLimits {
+ out.ResourceLimits[k] = v
+ }
+ }
+ if c.Pagination.Resources != nil {
+ out.Pagination.Resources = make(map[string]PaginationResourceConfig, len(c.Pagination.Resources))
+ for k, v := range c.Pagination.Resources {
+ out.Pagination.Resources[k] = v
+ }
+ }
+ return &out
+}
+
+// LimitFor returns the configured limit for a resource, falling back to DefaultLimit.
+func (c *Config) LimitFor(resource string) int {
+ if c == nil {
+ return 0
+ }
+ resource = NormalizePaginatedResource(resource)
+ if resource != "" && c.Pagination.Resources != nil {
+ if v, ok := c.Pagination.Resources[resource]; ok && v.Limit > 0 {
+ return v.Limit
+ }
+ }
+ if c.Pagination.Default.Limit > 0 {
+ return c.Pagination.Default.Limit
+ }
+
+ // Backward-compatibility with legacy keys.
+ if resource != "" && c.ResourceLimits != nil {
+ if v, ok := c.ResourceLimits[resource]; ok && v > 0 {
+ return v
+ }
+ }
+ if c.DefaultLimit > 0 {
+ return c.DefaultLimit
+ }
+ return 0
+}
+
+// SetDefaultLimit configures the global pagination default.
+func (c *Config) SetDefaultLimit(limit int) {
+ if c == nil {
+ return
+ }
+ c.Pagination.Default.Limit = limit
+ // Keep legacy field in sync for compatibility.
+ c.DefaultLimit = limit
+}
+
+// SetResourceLimit configures per-resource pagination defaults.
+func (c *Config) SetResourceLimit(resource string, limit int) {
+ if c == nil {
+ return
+ }
+ resource = NormalizePaginatedResource(resource)
+ if resource == "" {
+ return
+ }
+ if c.Pagination.Resources == nil {
+ c.Pagination.Resources = make(map[string]PaginationResourceConfig)
+ }
+ if c.ResourceLimits == nil {
+ c.ResourceLimits = make(map[string]int)
+ }
+ if limit <= 0 {
+ delete(c.Pagination.Resources, resource)
+ delete(c.ResourceLimits, resource)
+ return
+ }
+ c.Pagination.Resources[resource] = PaginationResourceConfig{Limit: limit}
+ // Keep legacy field in sync for compatibility.
+ c.ResourceLimits[resource] = limit
+}
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index 410fd13bf..7e976ba8d 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -3,9 +3,9 @@ package apikeys
import (
"encoding/json"
"fmt"
- "strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/apikey"
@@ -38,8 +38,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.ApiKeys()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "apikeys", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -125,6 +126,9 @@ var createCmd = &cobra.Command{
return fmt.Errorf("failed to create API key: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create API key: %w", err)
+ }
var result base.ApiResponse[apikey.ApiKeyCreatedDto]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -159,13 +163,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete API key %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete API key %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -181,6 +183,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete API key: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete API key: %w", err)
+ }
if jsonOutput {
var result base.ApiResponse[any]
diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.go
index 5f0520389..73567882b 100644
--- a/cli/pkg/admin/events/cmd.go
+++ b/cli/pkg/admin/events/cmd.go
@@ -3,9 +3,9 @@ package events
import (
"encoding/json"
"fmt"
- "strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
@@ -38,8 +38,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Events()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "events", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -99,8 +100,9 @@ var listEnvCmd = &cobra.Command{
}
path := types.Endpoints.EventsEnvironment(c.EnvID())
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "events", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -157,13 +159,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete event %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete event %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -179,6 +179,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete event: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete event: %w", err)
+ }
output.Success("Event deleted successfully")
return nil
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index 63735e554..cf685c7af 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
@@ -38,8 +39,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Users()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "users", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -97,13 +99,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete user %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete user %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -119,6 +119,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete user: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete user: %w", err)
+ }
output.Success("User deleted successfully")
return nil
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index 797274a78..6eac3ae30 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -9,7 +9,7 @@ import (
"time"
"github.com/charmbracelet/x/term"
- "github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/config"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -32,7 +32,7 @@ var loginCmd = &cobra.Command{
Short: "Login to Arcane using OIDC device authorization",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfigUnauthenticated()
+ c, err := cmdutil.UnauthClientFromCommand(cmd)
if err != nil {
return err
}
@@ -76,22 +76,25 @@ var loginCmd = &cobra.Command{
}
expiresAt := time.Now().Add(time.Duration(deviceAuth.ExpiresIn) * time.Second)
+ tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})
+ if err != nil {
+ return fmt.Errorf("failed to marshal token request: %w", err)
+ }
+
+ ticker := time.NewTicker(pollInterval)
+ defer ticker.Stop()
+
for {
if time.Now().After(expiresAt) {
return fmt.Errorf("device authorization expired; run login again")
}
select {
- case <-time.After(pollInterval):
+ case <-ticker.C:
case <-cmd.Context().Done():
return cmd.Context().Err()
}
- tokenReqBody, err := json.Marshal(auth.OidcDeviceTokenRequest{DeviceCode: deviceAuth.DeviceCode})
- if err != nil {
- return fmt.Errorf("failed to marshal token request: %w", err)
- }
-
tokenResp, err := c.Post(cmd.Context(), types.Endpoints.OIDCDeviceToken(), tokenReqBody)
if err != nil {
return fmt.Errorf("device token exchange failed: %w", err)
@@ -110,6 +113,7 @@ var loginCmd = &cobra.Command{
continue
case "slow_down":
pollInterval += 5 * time.Second
+ ticker.Reset(pollInterval)
continue
case "expired_token":
return fmt.Errorf("device authorization expired; run login again")
@@ -128,7 +132,7 @@ var loginCmd = &cobra.Command{
return fmt.Errorf("device token exchange failed: unexpected response from server")
}
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
resultBytes, err := json.MarshalIndent(tokenResult, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
@@ -161,7 +165,7 @@ var logoutCmd = &cobra.Command{
Short: "Logout from Arcane",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -171,8 +175,11 @@ var logoutCmd = &cobra.Command{
return fmt.Errorf("logout failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("logout failed: %w", err)
+ }
- // Clear token from config regardless of API response
+ // Clear token from config after successful API logout.
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
@@ -183,7 +190,7 @@ var logoutCmd = &cobra.Command{
return fmt.Errorf("failed to clear token: %w", err)
}
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
var result base.ApiResponse[any]
if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
@@ -205,7 +212,7 @@ var meCmd = &cobra.Command{
Short: "Get current user 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
}
@@ -215,13 +222,16 @@ var meCmd = &cobra.Command{
return fmt.Errorf("failed to get user info: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to get user info: %w", err)
+ }
var result base.ApiResponse[any]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
resultBytes, err := json.MarshalIndent(result.Data, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
@@ -268,7 +278,7 @@ var passwordCmd = &cobra.Command{
fmt.Println()
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -288,8 +298,11 @@ var passwordCmd = &cobra.Command{
return fmt.Errorf("password change failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("password change failed: %w", err)
+ }
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
var result base.ApiResponse[any]
if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
@@ -326,7 +339,7 @@ var refreshCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -345,13 +358,16 @@ var refreshCmd = &cobra.Command{
return fmt.Errorf("token refresh failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("token refresh failed: %w", err)
+ }
var result base.ApiResponse[auth.TokenRefreshResponse]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
- if jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
resultBytes, err := json.MarshalIndent(result.Data, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
diff --git a/cli/pkg/completion/cmd.go b/cli/pkg/completion/cmd.go
new file mode 100644
index 000000000..8a5e60262
--- /dev/null
+++ b/cli/pkg/completion/cmd.go
@@ -0,0 +1,37 @@
+package completion
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/spf13/cobra"
+)
+
+// NewCommand returns an explicit shell completion command.
+func NewCommand(root *cobra.Command) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "completion [bash|zsh|fish|powershell]",
+ Short: "Generate shell completion scripts",
+ Long: "Generate shell completion scripts for bash, zsh, fish, or powershell.",
+ Args: cobra.ExactArgs(1),
+ ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
+ SilenceUsage: true,
+ DisableFlagsInUseLine: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ switch args[0] {
+ case "bash":
+ return root.GenBashCompletionV2(os.Stdout, true)
+ case "zsh":
+ return root.GenZshCompletion(os.Stdout)
+ case "fish":
+ return root.GenFishCompletion(os.Stdout, true)
+ case "powershell":
+ return root.GenPowerShellCompletionWithDesc(os.Stdout)
+ default:
+ return fmt.Errorf("unsupported shell %q", args[0])
+ }
+ },
+ }
+
+ return cmd
+}
diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.go
index f121f2636..0385775ed 100644
--- a/cli/pkg/config/cmd.go
+++ b/cli/pkg/config/cmd.go
@@ -4,18 +4,24 @@ import (
"fmt"
"io"
"net/http"
+ "sort"
+ "strconv"
+ "strings"
"time"
"github.com/getarcaneapp/arcane/cli/internal/config"
+ clitypes "github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/spf13/cobra"
)
var (
- setServerURL string
- setAPIKey string
- setJWTToken string
- setEnvironment string
- setLogLevel string
+ setServerURL string
+ setAPIKey string
+ setJWTToken string
+ setEnvironment string
+ setLogLevel string
+ setDefaultLimit int
+ setResourceLimit []string
)
// ConfigCmd is the command for managing API configuration
@@ -41,6 +47,49 @@ var configShowCmd = &cobra.Command{
fmt.Printf("Refresh Token: %s\n", maskAPIKey(cfg.RefreshToken))
fmt.Printf("Default Environment: %s\n", maskIfEmpty(cfg.DefaultEnvironment, "0 (local)"))
fmt.Printf("Log Level: %s\n", maskIfEmpty(cfg.LogLevel, "info (default)"))
+ globalLimit := cfg.Pagination.Default.Limit
+ if globalLimit <= 0 {
+ globalLimit = cfg.DefaultLimit
+ }
+ fmt.Printf("Pagination Default: %s\n", maskIfEmpty(intToString(globalLimit), "(not set)"))
+
+ fmt.Println("\nPagination Resources:")
+ printed := 0
+ for _, resource := range clitypes.KnownPaginatedResources {
+ limit := cfg.LimitFor(resource)
+ explicit := cfg.Pagination.Resources != nil && cfg.Pagination.Resources[resource].Limit > 0
+ label := "(inherit)"
+ if explicit {
+ label = strconv.Itoa(limit)
+ } else if limit > 0 {
+ label = fmt.Sprintf("%d (from global)", limit)
+ }
+ fmt.Printf(" %-14s %s\n", resource+":", label)
+ printed++
+ }
+ if cfg.Pagination.Resources != nil {
+ extras := make([]string, 0)
+ for k, v := range cfg.Pagination.Resources {
+ known := false
+ for _, resource := range clitypes.KnownPaginatedResources {
+ if resource == k {
+ known = true
+ break
+ }
+ }
+ if !known && v.Limit > 0 {
+ extras = append(extras, k)
+ }
+ }
+ sort.Strings(extras)
+ for _, k := range extras {
+ fmt.Printf(" %-14s %d\n", k+":", cfg.Pagination.Resources[k].Limit)
+ printed++
+ }
+ }
+ if printed == 0 {
+ fmt.Println(" (none)")
+ }
if cfg.IsConfigured() {
fmt.Println("\n✓ Configuration is complete")
@@ -53,11 +102,20 @@ var configShowCmd = &cobra.Command{
}
var configSetCmd = &cobra.Command{
- Use: "set",
+ Use: "set [key value]...",
Short: "Set configuration values",
Long: `Set configuration values for connecting to an Arcane server.
+Preferred syntax (key/value pairs):
+
Examples:
+ arcane config set server-url http://localhost:3553
+ arcane config set api-key arc_xxxxxxxxxxxxx
+ 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
+
+Legacy flag syntax (flags shown below) is still supported:
arcane config set --server-url http://localhost:3553
arcane config set --api-key arc_xxxxxxxxxxxxx
arcane auth login
@@ -69,45 +127,20 @@ Examples:
}
updated := false
-
- if setServerURL != "" {
- cfg.ServerURL = setServerURL
- fmt.Printf("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.Printf("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.Printf("Set jwt_token = %s\n", maskAPIKey(setJWTToken))
- updated = true
- }
-
- if setEnvironment != "" {
- cfg.DefaultEnvironment = setEnvironment
- fmt.Printf("Set default_environment = %s\n", setEnvironment)
- updated = true
+ updatedByArgs, err := applyConfigSetArgs(cfg, args)
+ if err != nil {
+ return err
}
+ updated = updated || updatedByArgs
- if setLogLevel != "" {
- cfg.LogLevel = setLogLevel
- fmt.Printf("Set log_level = %s\n", setLogLevel)
- updated = true
+ updatedByFlags, err := applyConfigSetFlags(cmd, cfg)
+ if err != nil {
+ return err
}
+ updated = updated || updatedByFlags
if !updated {
- return fmt.Errorf("no configuration values provided. Use --server-url, --api-key, --jwt-token, --environment, or --log-level")
+ return fmt.Errorf("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url http://localhost:3552`) or legacy flags (--server-url, --api-key, --jwt-token, --environment, --log-level, --default-limit, --resource-limit)")
}
if err := config.Save(cfg); err != nil {
@@ -178,9 +211,69 @@ var configTestCmd = &cobra.Command{
},
}
+var configInitCmd = &cobra.Command{
+ Use: "init",
+ Short: "Create a default config file if it does not exist",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ Long: `Create a starter config file with all supported configuration keys.
+
+If the config file already exists, this command is a no-op and does not overwrite it.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path, err := config.ConfigPath()
+ if err != nil {
+ return err
+ }
+
+ created, err := config.InitDefaultFile()
+ if err != nil {
+ return fmt.Errorf("failed to initialize config: %w", err)
+ }
+ if !created {
+ fmt.Printf("Config file already exists at %s (no changes made)\n", path)
+ return nil
+ }
+
+ fmt.Printf("Created default config at %s\n", path)
+ fmt.Println("Update values with `arcane config set <key> <value>` or run `arcane auth login`.")
+ return nil
+ },
+}
+
+var configBackupCmd = &cobra.Command{
+ Use: "backup",
+ Short: "Move the current config file to a .bak backup",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ Long: `Move the active config file to <config-path>.bak.
+
+This removes the original config file from its previous path.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ path, err := config.ConfigPath()
+ if err != nil {
+ return err
+ }
+
+ backupPath, moved, err := config.BackupFile()
+ if err != nil {
+ return fmt.Errorf("failed to backup config: %w", err)
+ }
+ if !moved {
+ fmt.Printf("No config file found at %s (no changes made)\n", path)
+ return nil
+ }
+
+ fmt.Printf("Backed up config to %s\n", backupPath)
+ fmt.Printf("Removed original config at %s\n", path)
+ return nil
+ },
+}
+
func init() {
ConfigCmd.AddCommand(configShowCmd)
ConfigCmd.AddCommand(configSetCmd)
+ ConfigCmd.AddCommand(configInitCmd)
+ ConfigCmd.AddCommand(configBackupCmd)
ConfigCmd.AddCommand(configPathCmd)
ConfigCmd.AddCommand(configTestCmd)
@@ -189,6 +282,8 @@ func init() {
configSetCmd.Flags().StringVar(&setJWTToken, "jwt-token", "", "JWT access token for authentication (Bearer token)")
configSetCmd.Flags().StringVar(&setEnvironment, "environment", "", "Default environment ID")
configSetCmd.Flags().StringVar(&setLogLevel, "log-level", "", "Default log level (debug, info, warn, error)")
+ configSetCmd.Flags().IntVar(&setDefaultLimit, "default-limit", 0, "Global default list limit for paginated resources (0 clears)")
+ configSetCmd.Flags().StringSliceVar(&setResourceLimit, "resource-limit", nil, "Per-resource list limit in the form resource=limit (repeatable, 0 clears)")
}
func maskIfEmpty(value, fallback string) string {
@@ -207,3 +302,241 @@ func maskAPIKey(key string) string {
}
return key[:4] + "..." + key[len(key)-4:]
}
+
+func parseResourceLimitPair(pair string) (resource string, limit int, ok bool) {
+ left, right, found := strings.Cut(pair, "=")
+ if !found {
+ return "", 0, false
+ }
+ resource = clitypes.NormalizePaginatedResource(left)
+ if resource == "" {
+ return "", 0, false
+ }
+ known := false
+ for _, candidate := range clitypes.KnownPaginatedResources {
+ if candidate == resource {
+ known = true
+ break
+ }
+ }
+ if !known {
+ return "", 0, false
+ }
+ parsed, err := strconv.Atoi(strings.TrimSpace(right))
+ if err != nil {
+ return "", 0, false
+ }
+ return resource, parsed, true
+}
+
+func applyConfigSetFlags(cmd *cobra.Command, cfg *clitypes.Config) (bool, error) {
+ updated := false
+
+ if setServerURL != "" {
+ cfg.ServerURL = setServerURL
+ fmt.Printf("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.Printf("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.Printf("Set jwt_token = %s\n", maskAPIKey(setJWTToken))
+ updated = true
+ }
+
+ if setEnvironment != "" {
+ cfg.DefaultEnvironment = setEnvironment
+ fmt.Printf("Set default_environment = %s\n", setEnvironment)
+ updated = true
+ }
+
+ if setLogLevel != "" {
+ cfg.LogLevel = setLogLevel
+ fmt.Printf("Set log_level = %s\n", setLogLevel)
+ updated = true
+ }
+
+ if cmd.Flags().Changed("default-limit") {
+ if setDefaultLimit < 0 {
+ return false, fmt.Errorf("--default-limit must be >= 0")
+ }
+ cfg.SetDefaultLimit(setDefaultLimit)
+ if setDefaultLimit == 0 {
+ fmt.Println("Cleared pagination.default.limit")
+ } else {
+ fmt.Printf("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(clitypes.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.Printf("Cleared pagination.resources.%s.limit\n", resource)
+ } else {
+ fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)
+ }
+ updated = true
+ }
+
+ return updated, nil
+}
+
+func applyConfigSetArgs(cfg *clitypes.Config, args []string) (bool, error) {
+ if len(args) == 0 {
+ return false, nil
+ }
+ if len(args)%2 != 0 {
+ return false, fmt.Errorf("expected key/value pairs, got odd number of arguments (%d). Example: `arcane config set server-url http://localhost:3552`", len(args))
+ }
+
+ updated := false
+ for i := 0; i < len(args); i += 2 {
+ changed, err := applyConfigSetArg(cfg, args[i], args[i+1])
+ if err != nil {
+ return false, err
+ }
+ updated = updated || changed
+ }
+ return updated, nil
+}
+
+func applyConfigSetArg(cfg *clitypes.Config, key, value string) (bool, error) {
+ normalized := normalizeConfigKey(key)
+ switch normalized {
+ case "server-url", "server", "serverurl", "server_url":
+ cfg.ServerURL = value
+ fmt.Printf("Set server_url = %s\n", value)
+ return true, nil
+ case "api-key", "apikey", "api_key":
+ cfg.APIKey = value
+ // If switching to API key auth, clear any existing JWT token.
+ cfg.JWTToken = ""
+ cfg.RefreshToken = ""
+ fmt.Printf("Set api_key = %s\n", maskAPIKey(value))
+ return true, nil
+ case "jwt-token", "jwt", "jwt_token":
+ cfg.JWTToken = value
+ // If switching to JWT auth, clear any existing API key.
+ cfg.APIKey = ""
+ cfg.RefreshToken = ""
+ fmt.Printf("Set jwt_token = %s\n", maskAPIKey(value))
+ return true, nil
+ case "environment", "default-environment", "default_environment":
+ cfg.DefaultEnvironment = value
+ fmt.Printf("Set default_environment = %s\n", value)
+ return true, nil
+ case "log-level", "loglevel", "log_level":
+ cfg.LogLevel = value
+ fmt.Printf("Set log_level = %s\n", value)
+ return true, nil
+ case "default-limit", "default_limit", "pagination.default.limit":
+ limit, err := parseLimitValue(normalized, value)
+ if err != nil {
+ return false, err
+ }
+ cfg.SetDefaultLimit(limit)
+ if limit == 0 {
+ fmt.Println("Cleared pagination.default.limit")
+ } else {
+ fmt.Printf("Set pagination.default.limit = %d\n", limit)
+ }
+ return true, nil
+ case "resource-limit", "resource_limit":
+ resource, limit, ok := parseResourceLimitPair(value)
+ if !ok {
+ return false, fmt.Errorf("invalid value %q for key %q (expected resource=number, resources: %s)", value, key, strings.Join(clitypes.KnownPaginatedResources, ", "))
+ }
+ if limit < 0 {
+ return false, fmt.Errorf("invalid value %q for key %q (limit must be >= 0)", value, key)
+ }
+ cfg.SetResourceLimit(resource, limit)
+ if limit == 0 {
+ fmt.Printf("Cleared pagination.resources.%s.limit\n", resource)
+ } else {
+ fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)
+ }
+ return true, nil
+ }
+
+ if strings.HasPrefix(normalized, "resource-limit.") || strings.HasPrefix(normalized, "resource_limit.") {
+ resource := strings.TrimPrefix(strings.TrimPrefix(normalized, "resource-limit."), "resource_limit.")
+ return applyResourceLimitByKey(cfg, key, resource, value)
+ }
+ if strings.HasPrefix(normalized, "pagination.resources.") && strings.HasSuffix(normalized, ".limit") {
+ resource := strings.TrimSuffix(strings.TrimPrefix(normalized, "pagination.resources."), ".limit")
+ return applyResourceLimitByKey(cfg, key, resource, value)
+ }
+
+ return false, fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)
+}
+
+func applyResourceLimitByKey(cfg *clitypes.Config, key, resourceValue, limitValue string) (bool, error) {
+ resource := clitypes.NormalizePaginatedResource(resourceValue)
+ if resource == "" || !isKnownPaginatedResource(resource) {
+ return false, fmt.Errorf("invalid resource %q for key %q (supported resources: %s)", resourceValue, key, strings.Join(clitypes.KnownPaginatedResources, ", "))
+ }
+ limit, err := parseLimitValue(key, limitValue)
+ if err != nil {
+ return false, err
+ }
+ cfg.SetResourceLimit(resource, limit)
+ if limit == 0 {
+ fmt.Printf("Cleared pagination.resources.%s.limit\n", resource)
+ } else {
+ fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)
+ }
+ return true, nil
+}
+
+func isKnownPaginatedResource(resource string) bool {
+ for _, candidate := range clitypes.KnownPaginatedResources {
+ if candidate == resource {
+ return true
+ }
+ }
+ return false
+}
+
+func parseLimitValue(key, value string) (int, error) {
+ parsed, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil {
+ return 0, fmt.Errorf("invalid value %q for key %q (expected a non-negative integer)", value, key)
+ }
+ if parsed < 0 {
+ return 0, fmt.Errorf("invalid value %q for key %q (must be >= 0)", value, key)
+ }
+ 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
new file mode 100644
index 000000000..587f4c6c9
--- /dev/null
+++ b/cli/pkg/config/cmd_test.go
@@ -0,0 +1,84 @@
+package config
+
+import (
+ "strings"
+ "testing"
+
+ clitypes "github.com/getarcaneapp/arcane/cli/internal/types"
+)
+
+func TestApplyConfigSetArgs(t *testing.T) {
+ cfg := &clitypes.Config{}
+
+ changed, err := applyConfigSetArgs(cfg, []string{
+ "server-url", "http://localhost:3552",
+ "api-key", "arc_test_12345678",
+ "default-limit", "25",
+ "pagination.resources.images.limit", "100",
+ "resource-limit.volumes", "40",
+ })
+ if err != nil {
+ t.Fatalf("applyConfigSetArgs() error = %v", err)
+ }
+ if !changed {
+ t.Fatal("applyConfigSetArgs() changed = false, want true")
+ }
+
+ if cfg.ServerURL != "http://localhost:3552" {
+ t.Fatalf("ServerURL = %q, want %q", cfg.ServerURL, "http://localhost:3552")
+ }
+ if cfg.APIKey != "arc_test_12345678" {
+ t.Fatalf("APIKey = %q, want %q", cfg.APIKey, "arc_test_12345678")
+ }
+ if cfg.JWTToken != "" {
+ t.Fatalf("JWTToken = %q, want empty", cfg.JWTToken)
+ }
+ if cfg.Pagination.Default.Limit != 25 {
+ t.Fatalf("Pagination.Default.Limit = %d, want 25", cfg.Pagination.Default.Limit)
+ }
+ if got := cfg.LimitFor("images"); got != 100 {
+ t.Fatalf("LimitFor(images) = %d, want 100", got)
+ }
+ if got := cfg.LimitFor("volumes"); got != 40 {
+ t.Fatalf("LimitFor(volumes) = %d, want 40", got)
+ }
+}
+
+func TestApplyConfigSetArgs_OddArgs(t *testing.T) {
+ cfg := &clitypes.Config{}
+ changed, err := applyConfigSetArgs(cfg, []string{"server-url", "http://localhost:3552", "api-key"})
+ if err == nil {
+ t.Fatal("expected error for odd key/value args, got nil")
+ }
+ if changed {
+ t.Fatal("changed = true, want false")
+ }
+}
+
+func TestApplyConfigSetArg_UnknownKey(t *testing.T) {
+ cfg := &clitypes.Config{}
+ changed, err := applyConfigSetArg(cfg, "not-a-real-key", "value")
+ if err == nil {
+ t.Fatal("expected unknown key error, got nil")
+ }
+ if changed {
+ t.Fatal("changed = true, want false")
+ }
+ if !strings.Contains(err.Error(), "unknown config key") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func TestApplyConfigSetArg_ResourceLimitPair(t *testing.T) {
+ cfg := &clitypes.Config{}
+ changed, err := applyConfigSetArg(cfg, "resource-limit", "containers=55")
+ if err != nil {
+ t.Fatalf("applyConfigSetArg() error = %v", err)
+ }
+ if !changed {
+ t.Fatal("changed = false, want true")
+ }
+ if got := cfg.LimitFor("containers"); got != 55 {
+ t.Fatalf("LimitFor(containers) = %d, want 55", got)
+ }
+}
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index ad974c726..f0355b636 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -47,8 +48,9 @@ var containersListCmd = &cobra.Command{
}
path := types.Endpoints.Containers(c.EnvID())
- if containersLimit > 0 {
- path = fmt.Sprintf("%s?pageSize=%d", path, containersLimit)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "containers", "limit", containersLimit, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?pageSize=%d", path, effectiveLimit)
}
if containersAll {
separator := "?"
@@ -342,13 +344,11 @@ var containersDeleteCmd = &cobra.Command{
displayName := containerDisplayName(resolved)
if !forceFlag {
- fmt.Printf("Are you sure you want to delete container %s? (y/N): ", displayName)
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete container %s?", displayName))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.go
new file mode 100644
index 000000000..529ba78fd
--- /dev/null
+++ b/cli/pkg/doctor/cmd.go
@@ -0,0 +1,134 @@
+package doctor
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/cli/internal/config"
+ "github.com/getarcaneapp/arcane/cli/internal/output"
+ runtimectx "github.com/getarcaneapp/arcane/cli/internal/runtime"
+ "github.com/spf13/cobra"
+)
+
+type checkResult struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Details string `json:"details,omitempty"`
+}
+
+type report struct {
+ Healthy bool `json:"healthy"`
+ Checks []checkResult `json:"checks"`
+}
+
+var jsonOutput bool
+
+// DoctorCmd runs environment and connection diagnostics.
+var DoctorCmd = &cobra.Command{
+ Use: "doctor",
+ Short: "Run CLI diagnostics",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ app, ok := runtimectx.From(cmd.Context())
+ if !ok {
+ created, err := runtimectx.New(runtimectx.Options{})
+ if err != nil {
+ return err
+ }
+ app = created
+ }
+
+ cfg := app.Config()
+ if cfg == nil {
+ return fmt.Errorf("configuration unavailable")
+ }
+
+ rep := report{Healthy: true}
+ path, _ := config.ConfigPath()
+ rep.Checks = append(rep.Checks, checkResult{
+ Name: "config_path",
+ Status: "ok",
+ Details: path,
+ })
+
+ if strings.TrimSpace(cfg.ServerURL) == "" {
+ rep.Healthy = false
+ rep.Checks = append(rep.Checks, checkResult{
+ Name: "server_url",
+ Status: "fail",
+ Details: "server_url is not configured (run `arcane config set server-url <url>`)",
+ })
+ } else {
+ rep.Checks = append(rep.Checks, checkResult{Name: "server_url", Status: "ok", Details: cfg.ServerURL})
+ }
+
+ env := cfg.DefaultEnvironment
+ if app.EnvID() != "" {
+ env = app.EnvID()
+ }
+ if strings.TrimSpace(env) == "" {
+ env = "0"
+ }
+ rep.Checks = append(rep.Checks, checkResult{Name: "environment", Status: "ok", Details: env})
+
+ if cfg.HasAuth() {
+ rep.Checks = append(rep.Checks, checkResult{Name: "auth", Status: "ok", Details: "credentials configured"})
+ } else {
+ rep.Healthy = false
+ rep.Checks = append(rep.Checks, checkResult{
+ Name: "auth",
+ Status: "fail",
+ Details: "authentication is not configured (run `arcane config set api-key ...` or `arcane auth login`)",
+ })
+ }
+
+ if strings.TrimSpace(cfg.ServerURL) != "" && cfg.HasAuth() {
+ c, err := app.Client()
+ if err != nil {
+ rep.Healthy = false
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
+ } else {
+ if err := c.TestConnection(cmd.Context()); err != nil {
+ rep.Healthy = false
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
+ } else {
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "ok", Details: "connected"})
+ }
+ }
+ } else if strings.TrimSpace(cfg.ServerURL) == "" {
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "skip", Details: "server_url missing"})
+ } else {
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "skip", Details: "auth missing"})
+ }
+
+ if jsonOutput || app.IsJSON() {
+ b, err := json.MarshalIndent(rep, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal doctor output: %w", err)
+ }
+ fmt.Println(string(b))
+ } else {
+ output.Header("Arcane CLI Diagnostics")
+ rows := make([][]string, 0, len(rep.Checks))
+ for _, item := range rep.Checks {
+ rows = append(rows, []string{item.Name, item.Status, item.Details})
+ }
+ output.Table([]string{"CHECK", "STATUS", "DETAILS"}, rows)
+ if rep.Healthy {
+ output.Success("Doctor checks passed")
+ } else {
+ output.Warning("Doctor found issues")
+ }
+ }
+
+ if !rep.Healthy {
+ return fmt.Errorf("diagnostics failed")
+ }
+ return nil
+ },
+}
+
+func init() {
+ DoctorCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+}
diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.go
index 830140b99..100750cb4 100644
--- a/cli/pkg/environments/cmd.go
+++ b/cli/pkg/environments/cmd.go
@@ -8,6 +8,7 @@ import (
"github.com/charmbracelet/lipgloss"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/config"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
@@ -49,8 +50,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Environments()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "environments", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -103,13 +105,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete environment %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete environment %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -125,6 +125,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete environment: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete environment: %w", err)
+ }
output.Success("Environment deleted successfully")
return nil
@@ -188,6 +191,9 @@ var testCmd = &cobra.Command{
return fmt.Errorf("failed to test environment: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to test environment: %w", err)
+ }
if jsonOutput {
var result base.ApiResponse[any]
@@ -211,7 +217,7 @@ var switchCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !prompt.IsInteractive() {
- return fmt.Errorf("interactive terminal required; run `arcane config set --environment <id>` instead")
+ return fmt.Errorf("interactive terminal required; run `arcane config set environment <id>` instead")
}
cfg, err := config.Load()
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index 3f71b04f8..d682970e0 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -31,7 +31,6 @@
package images
import (
- "bytes"
"context"
"encoding/json"
"fmt"
@@ -47,6 +46,7 @@ import (
"github.com/fatih/color"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/logger"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
@@ -58,11 +58,13 @@ import (
)
var (
- imagesLimit int
- imagesStart int
- imagesSort string
- imagesOrder string
- imagesSearch string
+ imagesLimit int
+ imagesStart int
+ imagesSort string
+ imagesOrder string
+ imagesSearch string
+ imagesInUseOnly bool
+ imagesUnusedOnly bool
)
const maxPromptOptions = 20
@@ -81,10 +83,13 @@ var imagesListCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
+ if imagesInUseOnly && imagesUnusedOnly {
+ return fmt.Errorf("--inuse and --unused cannot be used together")
+ }
path := types.Endpoints.Images(c.EnvID())
@@ -95,8 +100,9 @@ var imagesListCmd = &cobra.Command{
}
q := u.Query()
- if imagesLimit > 0 {
- q.Set("limit", fmt.Sprintf("%d", imagesLimit))
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "images", "limit", imagesLimit, 0)
+ if effectiveLimit > 0 {
+ q.Set("limit", fmt.Sprintf("%d", effectiveLimit))
}
if imagesStart > 0 {
q.Set("start", fmt.Sprintf("%d", imagesStart))
@@ -129,7 +135,7 @@ var imagesListCmd = &cobra.Command{
log.Debugf("Response body: %s", string(body))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) && !imagesInUseOnly && !imagesUnusedOnly {
fmt.Println(string(body))
return nil
}
@@ -145,6 +151,17 @@ var imagesListCmd = &cobra.Command{
if err := json.Unmarshal(body, &result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
+ result.Data = filterImagesByUsage(result.Data, imagesInUseOnly, imagesUnusedOnly)
+ result.Pagination.TotalItems = int64(len(result.Data))
+
+ if cmdutil.JSONOutputEnabled(cmd) {
+ resultBytes, err := json.MarshalIndent(result, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
headers := []string{"ID", "REPOSITORY:TAG", "SIZE", "IN USE"}
var rows [][]string
@@ -176,12 +193,12 @@ var imagesGetCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
- jsonOutput, _ := cmd.Flags().GetBool("json")
+ jsonOutput := cmdutil.JSONOutputEnabled(cmd)
allowPrompt := !jsonOutput && prompt.IsInteractive()
imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
@@ -275,7 +292,7 @@ var imagesRemoveCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -304,6 +321,10 @@ var imagesRemoveCmd = &cobra.Command{
return fmt.Errorf("failed to remove image: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return fmt.Errorf("failed to remove image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
+ }
body, err := io.ReadAll(resp.Body)
if err != nil {
@@ -312,7 +333,7 @@ var imagesRemoveCmd = &cobra.Command{
log.Debugf("Response body: %s", string(body))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) {
fmt.Println(string(body))
return nil
}
@@ -341,7 +362,7 @@ var imagesPullCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -363,9 +384,13 @@ var imagesPullCmd = &cobra.Command{
return fmt.Errorf("failed to pull image: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return fmt.Errorf("failed to pull image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
+ }
// Stream the response
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) {
_, err = io.Copy(cmd.OutOrStdout(), resp.Body)
if err != nil {
return fmt.Errorf("failed to read pull stream: %w", err)
@@ -455,7 +480,7 @@ var imagesPruneCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -468,7 +493,7 @@ var imagesPruneCmd = &cobra.Command{
"dangling": pruneDangling,
}
- jsonOutput, _ := cmd.Flags().GetBool("json")
+ jsonOutput := cmdutil.JSONOutputEnabled(cmd)
var spinner *output.Spinner
if !jsonOutput {
@@ -485,6 +510,10 @@ var imagesPruneCmd = &cobra.Command{
return fmt.Errorf("failed to prune images: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return fmt.Errorf("failed to prune images (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
+ }
body, err := io.ReadAll(resp.Body)
if err != nil {
@@ -493,7 +522,7 @@ var imagesPruneCmd = &cobra.Command{
log.Debugf("Response body: %s", string(body))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) {
fmt.Println(string(body))
return nil
}
@@ -522,7 +551,7 @@ var imagesCountsCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -544,7 +573,7 @@ var imagesCountsCmd = &cobra.Command{
log.Debugf("Response body: %s", string(body))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if cmdutil.JSONOutputEnabled(cmd) {
fmt.Println(string(body))
return nil
}
@@ -575,7 +604,7 @@ var imagesUploadCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.GetLogger()
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -594,38 +623,43 @@ var imagesUploadCmd = &cobra.Command{
return fmt.Errorf("failed to open file: %w", err)
}
defer func() { _ = file.Close() }()
-
- // Create a multipart form
- body := &bytes.Buffer{}
- writer := multipart.NewWriter(body)
-
- part, err := writer.CreateFormFile("file", filepath.Base(filePath))
- if err != nil {
- return fmt.Errorf("failed to create form file: %w", err)
- }
-
- _, err = io.Copy(part, file)
+ fileInfo, err := file.Stat()
if err != nil {
- return fmt.Errorf("failed to copy file: %w", err)
+ return fmt.Errorf("failed to stat file: %w", err)
}
- err = writer.Close()
- if err != nil {
- return fmt.Errorf("failed to close writer: %w", err)
- }
+ pr, pw := io.Pipe()
+ writer := multipart.NewWriter(pw)
output.Info("Uploading image: %s", filePath)
- var requestBody io.Reader = body
+ var requestBody io.Reader = pr
- jsonOutput, _ := cmd.Flags().GetBool("json")
+ jsonOutput := cmdutil.JSONOutputEnabled(cmd)
var progressUI *output.Progress
if !jsonOutput {
- progressUI = output.StartProgress("Uploading", int64(body.Len()))
- requestBody = output.NewProgressReader(body, progressUI)
+ progressUI = output.StartProgress("Uploading", fileInfo.Size())
+ requestBody = output.NewProgressReader(pr, progressUI)
defer progressUI.Stop()
}
+ go func() {
+ part, err := writer.CreateFormFile("file", filepath.Base(filePath))
+ if err != nil {
+ _ = pw.CloseWithError(fmt.Errorf("failed to create form file: %w", err))
+ return
+ }
+ if _, err := io.Copy(part, file); err != nil {
+ _ = pw.CloseWithError(fmt.Errorf("failed to copy file: %w", err))
+ return
+ }
+ if err := writer.Close(); err != nil {
+ _ = pw.CloseWithError(fmt.Errorf("failed to close multipart writer: %w", err))
+ return
+ }
+ _ = pw.Close()
+ }()
+
// Use client.RequestRaw to make the multipart request with correct headers
headers := map[string]string{
"Content-Type": writer.FormDataContentType(),
@@ -637,6 +671,11 @@ var imagesUploadCmd = &cobra.Command{
}
defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ errorBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return fmt.Errorf("failed to upload image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errorBody)))
+ }
+
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
@@ -644,7 +683,7 @@ var imagesUploadCmd = &cobra.Command{
log.Debugf("Response body: %s", string(respBody))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if jsonOutput {
fmt.Println(string(respBody))
return nil
}
@@ -675,6 +714,8 @@ func init() {
imagesListCmd.Flags().StringVar(&imagesSort, "sort", "", "Field to sort by")
imagesListCmd.Flags().StringVar(&imagesOrder, "order", "", "Sort order (asc/desc)")
imagesListCmd.Flags().StringVar(&imagesSearch, "search", "", "Search query")
+ imagesListCmd.Flags().BoolVar(&imagesInUseOnly, "inuse", false, "Only show images currently in use")
+ imagesListCmd.Flags().BoolVar(&imagesUnusedOnly, "unused", false, "Only show images not in use")
ImagesCmd.AddCommand(imagesGetCmd)
@@ -895,3 +936,20 @@ func formatImageMatchOption(match image.Summary) string {
}
return fmt.Sprintf("%s (%s)", label, match.ID)
}
+
+func filterImagesByUsage(items []image.Summary, inUseOnly, unusedOnly bool) []image.Summary {
+ if !inUseOnly && !unusedOnly {
+ return items
+ }
+ filtered := make([]image.Summary, 0, len(items))
+ for _, item := range items {
+ if inUseOnly && !item.InUse {
+ continue
+ }
+ if unusedOnly && item.InUse {
+ continue
+ }
+ filtered = append(filtered, item)
+ }
+ return filtered
+}
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index a9451bd14..f4e944f04 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -19,9 +20,11 @@ import (
)
var (
- limitFlag int
- forceFlag bool
- jsonOutput bool
+ limitFlag int
+ forceFlag bool
+ jsonOutput bool
+ inUseOnlyFlag bool
+ unusedOnlyFlag bool
)
const maxPromptOptions = 20
@@ -39,14 +42,18 @@ var listCmd = &cobra.Command{
Short: "List networks",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ if inUseOnlyFlag && unusedOnlyFlag {
+ return fmt.Errorf("--inuse and --unused cannot be used together")
+ }
c, err := client.NewFromConfig()
if err != nil {
return err
}
path := types.Endpoints.Networks(c.EnvID())
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "networks", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -59,6 +66,8 @@ var listCmd = &cobra.Command{
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
+ result.Data = filterNetworksByUsage(result.Data, inUseOnlyFlag, unusedOnlyFlag)
+ result.Pagination.TotalItems = int64(len(result.Data))
if jsonOutput {
resultBytes, err := json.MarshalIndent(result, "", " ")
@@ -69,15 +78,20 @@ var listCmd = &cobra.Command{
return nil
}
- headers := []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED"}
+ headers := []string{"ID", "NAME", "DRIVER", "SCOPE", "CREATED", "IN USE"}
rows := make([][]string, len(result.Data))
for i, net := range result.Data {
+ inUse := "No"
+ if net.InUse {
+ inUse = "Yes"
+ }
rows[i] = []string{
shortID(net.ID),
net.Name,
net.Driver,
net.Scope,
net.Created.Format("2006-01-02 15:04"),
+ inUse,
}
}
@@ -166,13 +180,11 @@ var deleteCmd = &cobra.Command{
}
if !forceFlag {
- fmt.Printf("Are you sure you want to delete network %s? (y/N): ", display)
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete network %s?", display))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -183,6 +195,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete network: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete network: %w", err)
+ }
if jsonOutput {
var result base.ApiResponse[any]
@@ -246,13 +261,11 @@ var pruneCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Print("Are you sure you want to prune unused networks? (y/N): ")
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to prune unused networks?")
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -268,6 +281,9 @@ var pruneCmd = &cobra.Command{
return fmt.Errorf("failed to prune networks: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to prune networks: %w", err)
+ }
var result base.ApiResponse[network.PruneReport]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -299,6 +315,8 @@ func init() {
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of networks to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ listCmd.Flags().BoolVar(&inUseOnlyFlag, "inuse", false, "Only show networks currently in use")
+ listCmd.Flags().BoolVar(&unusedOnlyFlag, "unused", false, "Only show networks not in use")
// Get command flags
getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -419,3 +437,20 @@ func networkMatches(item network.Summary, identifierLower, original string) bool
}
return strings.EqualFold(item.Name, original)
}
+
+func filterNetworksByUsage(items []network.Summary, inUseOnly, unusedOnly bool) []network.Summary {
+ if !inUseOnly && !unusedOnly {
+ return items
+ }
+ filtered := make([]network.Summary, 0, len(items))
+ for _, item := range items {
+ if inUseOnly && !item.InUse {
+ continue
+ }
+ if unusedOnly && item.InUse {
+ continue
+ }
+ filtered = append(filtered, item)
+ }
+ return filtered
+}
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index a49376b9d..3e3548a69 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -46,8 +47,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Projects(c.EnvID())
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "projects", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -111,13 +113,11 @@ var destroyCmd = &cobra.Command{
if display == "" {
display = resolved.ID
}
- fmt.Printf("Are you sure you want to destroy project %s? This will remove all containers! (y/N): ", display)
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to destroy project %s? This will remove all containers!", display))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -128,6 +128,9 @@ var destroyCmd = &cobra.Command{
return fmt.Errorf("failed to destroy project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to destroy project: %w", err)
+ }
output.Success("Project %s destroyed successfully", resolved.Name)
return nil
@@ -205,6 +208,9 @@ var upCmd = &cobra.Command{
return fmt.Errorf("failed to start project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to start project: %w", err)
+ }
output.Success("Project %s started successfully", resolved.Name)
return nil
@@ -232,6 +238,9 @@ var downCmd = &cobra.Command{
return fmt.Errorf("failed to stop project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to stop project: %w", err)
+ }
output.Success("Project %s stopped successfully", resolved.Name)
return nil
@@ -259,6 +268,9 @@ var restartCmd = &cobra.Command{
return fmt.Errorf("failed to restart project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to restart project: %w", err)
+ }
output.Success("Project %s restarted successfully", resolved.Name)
return nil
@@ -289,6 +301,9 @@ var redeployCmd = &cobra.Command{
return fmt.Errorf("failed to redeploy project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to redeploy project: %w", err)
+ }
output.Success("Project %s redeployed successfully", resolved.Name)
return nil
@@ -319,6 +334,9 @@ var pullCmd = &cobra.Command{
return fmt.Errorf("failed to pull images: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to pull images: %w", err)
+ }
output.Success("Images pulled successfully for project %s", resolved.Name)
return nil
diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.go
index dd36ec632..4a6005cab 100644
--- a/cli/pkg/registries/cmd.go
+++ b/cli/pkg/registries/cmd.go
@@ -3,9 +3,9 @@ package registries
import (
"encoding/json"
"fmt"
- "strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
@@ -37,8 +37,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.ContainerRegistries()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "registries", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -102,6 +103,9 @@ var syncCmd = &cobra.Command{
return fmt.Errorf("failed to sync registries: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to sync registries: %w", err)
+ }
if jsonOutput {
var result base.ApiResponse[any]
@@ -134,6 +138,9 @@ var testCmd = &cobra.Command{
return fmt.Errorf("failed to test registry: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to test registry: %w", err)
+ }
if jsonOutput {
var result base.ApiResponse[any]
@@ -158,13 +165,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete registry %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete registry %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -180,6 +185,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete registry: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete registry: %w", err)
+ }
output.Success("Registry deleted successfully")
return nil
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index f5dda79f4..2958e167e 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -8,7 +8,7 @@
//
// Configure the CLI with your server URL and API key:
//
-// arcane config set --server-url https://your-server.com --api-key YOUR_API_KEY
+// arcane config set server-url https://your-server.com api-key YOUR_API_KEY
//
// # Global Flags
//
@@ -35,14 +35,22 @@ import (
"fmt"
"os"
"runtime"
+ "strings"
+ "time"
"github.com/charmbracelet/fang"
+ "github.com/fatih/color"
"github.com/getarcaneapp/arcane/cli/internal/config"
"github.com/getarcaneapp/arcane/cli/internal/logger"
+ "github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/runstate"
+ runtimectx "github.com/getarcaneapp/arcane/cli/internal/runtime"
"github.com/getarcaneapp/arcane/cli/pkg/admin"
"github.com/getarcaneapp/arcane/cli/pkg/auth"
+ "github.com/getarcaneapp/arcane/cli/pkg/completion"
configClient "github.com/getarcaneapp/arcane/cli/pkg/config"
"github.com/getarcaneapp/arcane/cli/pkg/containers"
+ "github.com/getarcaneapp/arcane/cli/pkg/doctor"
"github.com/getarcaneapp/arcane/cli/pkg/environments"
"github.com/getarcaneapp/arcane/cli/pkg/generate"
"github.com/getarcaneapp/arcane/cli/pkg/images"
@@ -60,10 +68,16 @@ import (
)
var (
- logLevel string
- jsonOutput bool
- showVersion bool
- configPath string
+ logLevel string
+ logJSONOutput bool
+ showVersion bool
+ configPath string
+ outputMode string
+ envOverride string
+ assumeYes bool
+ noColorOutput bool
+ requestTimeout time.Duration
+ globalJSON bool
)
var rootCmd = &cobra.Command{
@@ -76,6 +90,22 @@ var rootCmd = &cobra.Command{
}
}
+ 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) {
+ if flag := cmd.Flags().Lookup("json"); flag != nil && !flag.Changed {
+ _ = cmd.Flags().Set("json", "true")
+ }
+ }
+
// Load config to check for log level setting
cfg, _ := config.Load()
@@ -84,7 +114,34 @@ var rootCmd = &cobra.Command{
logLevel = cfg.LogLevel
}
- logger.Setup(logLevel, jsonOutput)
+ if noColorOutput {
+ output.SetColorEnabled(false)
+ color.NoColor = true
+ } else {
+ output.SetColorEnabled(true)
+ color.NoColor = false
+ }
+
+ logger.Setup(logLevel, logJSONOutput)
+
+ app, err := runtimectx.New(runtimectx.Options{
+ EnvOverride: envOverride,
+ OutputMode: runtimectx.OutputMode(outputMode),
+ AssumeYes: assumeYes,
+ NoColor: noColorOutput,
+ RequestTimeout: requestTimeout,
+ })
+ if err != nil {
+ return err
+ }
+ cmd.SetContext(runtimectx.WithAppContext(cmd.Context(), app))
+ runstate.Set(runstate.State{
+ EnvOverride: envOverride,
+ OutputMode: outputMode,
+ AssumeYes: assumeYes,
+ NoColor: noColorOutput,
+ RequestTimeout: requestTimeout,
+ })
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
@@ -106,13 +163,27 @@ func Execute() {
}
}
+// RootCommand returns the configured root command.
+// Intended for integration tests and embedding.
+func RootCommand() *cobra.Command {
+ return rootCmd
+}
+
func init() {
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error, fatal, panic)")
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "Path to config file (default ~/.config/arcanecli.yml)")
- rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Log in JSON format")
+ rootCmd.PersistentFlags().StringVar(&outputMode, "output", "text", "Output mode (text, json)")
+ rootCmd.PersistentFlags().StringVar(&envOverride, "env", "", "Override default environment ID for this invocation")
+ rootCmd.PersistentFlags().BoolVarP(&assumeYes, "yes", "y", false, "Automatic yes to prompts")
+ rootCmd.PersistentFlags().BoolVar(&noColorOutput, "no-color", false, "Disable colored output")
+ rootCmd.PersistentFlags().DurationVar(&requestTimeout, "request-timeout", 0, "HTTP request timeout override (e.g. 30s, 2m)")
+ rootCmd.PersistentFlags().BoolVar(&globalJSON, "json", false, "Alias for --output json")
+ rootCmd.PersistentFlags().BoolVar(&logJSONOutput, "log-json", false, "Log in JSON format")
rootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "Print version information")
rootCmd.AddCommand(configClient.ConfigCmd)
+ rootCmd.AddCommand(completion.NewCommand(rootCmd))
+ rootCmd.AddCommand(doctor.DoctorCmd)
rootCmd.AddCommand(generate.GenerateCmd)
rootCmd.AddCommand(version.VersionCmd)
rootCmd.AddCommand(auth.AuthCmd)
diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.go
index b2dae1b48..6cafff83e 100644
--- a/cli/pkg/templates/cmd.go
+++ b/cli/pkg/templates/cmd.go
@@ -3,9 +3,9 @@ package templates
import (
"encoding/json"
"fmt"
- "strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
@@ -39,8 +39,9 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Templates()
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "templates", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -334,13 +335,11 @@ var deleteCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete template %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete template %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -356,6 +355,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete template: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete template: %w", err)
+ }
output.Success("Template deleted successfully")
return nil
@@ -369,13 +371,11 @@ var deleteRegistryCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Printf("Are you sure you want to delete template registry %s? (y/N): ", args[0])
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete template registry %s?", args[0]))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -391,6 +391,9 @@ var deleteRegistryCmd = &cobra.Command{
return fmt.Errorf("failed to delete registry: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete registry: %w", err)
+ }
output.Success("Template registry deleted successfully")
return nil
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index 3706b7654..9d5366f38 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -19,9 +20,11 @@ import (
)
var (
- limitFlag int
- forceFlag bool
- jsonOutput bool
+ limitFlag int
+ forceFlag bool
+ jsonOutput bool
+ inUseOnlyFlag bool
+ unusedOnlyFlag bool
)
const maxPromptOptions = 20
@@ -39,14 +42,18 @@ var listCmd = &cobra.Command{
Short: "List volumes",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ if inUseOnlyFlag && unusedOnlyFlag {
+ return fmt.Errorf("--inuse and --unused cannot be used together")
+ }
c, err := client.NewFromConfig()
if err != nil {
return err
}
path := types.Endpoints.Volumes(c.EnvID())
- if limitFlag > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, limitFlag)
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "volumes", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
}
resp, err := c.Get(cmd.Context(), path)
@@ -59,6 +66,8 @@ var listCmd = &cobra.Command{
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
+ result.Data = filterVolumesByUsage(result.Data, inUseOnlyFlag, unusedOnlyFlag)
+ result.Pagination.TotalItems = int64(len(result.Data))
if jsonOutput {
resultBytes, err := json.MarshalIndent(result, "", " ")
@@ -69,14 +78,19 @@ var listCmd = &cobra.Command{
return nil
}
- headers := []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED"}
+ headers := []string{"NAME", "DRIVER", "MOUNTPOINT", "CREATED", "IN USE"}
rows := make([][]string, len(result.Data))
for i, vol := range result.Data {
+ inUse := "No"
+ if vol.InUse {
+ inUse = "Yes"
+ }
rows[i] = []string{
vol.Name,
vol.Driver,
vol.Mountpoint,
vol.CreatedAt,
+ inUse,
}
}
@@ -145,13 +159,11 @@ var deleteCmd = &cobra.Command{
}
if !forceFlag {
- fmt.Printf("Are you sure you want to delete volume %s? (y/N): ", resolved.Name)
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete volume %s?", resolved.Name))
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -162,6 +174,9 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete volume: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete volume: %w", err)
+ }
output.Success("Volume %s deleted successfully", resolved.Name)
return nil
@@ -214,13 +229,11 @@ var pruneCmd = &cobra.Command{
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if !forceFlag {
- fmt.Print("Are you sure you want to prune unused volumes? (y/N): ")
- var response string
- if _, err := fmt.Scanln(&response); err != nil {
- fmt.Println("Cancelled")
- return nil
+ confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to prune unused volumes?")
+ if err != nil {
+ return err
}
- if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
+ if !confirmed {
fmt.Println("Cancelled")
return nil
}
@@ -236,6 +249,9 @@ var pruneCmd = &cobra.Command{
return fmt.Errorf("failed to prune volumes: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to prune volumes: %w", err)
+ }
var result base.ApiResponse[any]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -355,6 +371,8 @@ func init() {
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of volumes to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ listCmd.Flags().BoolVar(&inUseOnlyFlag, "inuse", false, "Only show volumes currently in use")
+ listCmd.Flags().BoolVar(&unusedOnlyFlag, "unused", false, "Only show volumes not in use")
// Get command flags
getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -474,3 +492,20 @@ func volumeMatches(item volume.Volume, identifierLower, original string) bool {
}
return false
}
+
+func filterVolumesByUsage(items []volume.Volume, inUseOnly, unusedOnly bool) []volume.Volume {
+ if !inUseOnly && !unusedOnly {
+ return items
+ }
+ filtered := make([]volume.Volume, 0, len(items))
+ for _, item := range items {
+ if inUseOnly && !item.InUse {
+ continue
+ }
+ if unusedOnly && item.InUse {
+ continue
+ }
+ filtered = append(filtered, item)
+ }
+ return filtered
+}
diff --git a/go.work.sum b/go.work.sum
index e2f682ebc..5c53afb96 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -623,8 +623,10 @@ golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE=
golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
+golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=