Skip to content

Modern Docker Management, Designed for Everyone

feat(cli): allow resource actions by name instead of just id (#1683)

Kyle Mendell5baff4172f1d
diff --git a/cli/README.md b/cli/README.md
index a12fdd546..21420a81b 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -33,7 +33,7 @@ Set the Arcane server URL:
### Authenticate (choose one)
-#### Option A: Device code (OIDC)
+#### Option A: Device code (OIDC must be enabled for this method, as it uses your external provider.)
- `arcane auth login`
diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go
new file mode 100644
index 000000000..778b0f734
--- /dev/null
+++ b/cli/internal/prompt/prompt.go
@@ -0,0 +1,54 @@
+package prompt
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/charmbracelet/x/term"
+)
+
+// IsInteractive reports whether stdin is a terminal.
+func IsInteractive() bool {
+ return term.IsTerminal(os.Stdin.Fd())
+}
+
+// Select prompts the user to select from a list of options and returns the zero-based index.
+func Select(label string, options []string) (int, error) {
+ if len(options) == 0 {
+ return -1, fmt.Errorf("no %s options available", label)
+ }
+
+ reader := bufio.NewReader(os.Stdin)
+ for {
+ fmt.Printf("\nMultiple %s match. Select one:\n", label)
+ for i, option := range options {
+ fmt.Printf(" %d) %s\n", i+1, option)
+ }
+ fmt.Printf("Enter number (1-%d): ", len(options))
+
+ input, err := reader.ReadString('\n')
+ if err != nil {
+ return -1, fmt.Errorf("failed to read selection: %w", err)
+ }
+
+ input = strings.TrimSpace(input)
+ if input == "" {
+ return -1, fmt.Errorf("selection required")
+ }
+
+ if strings.EqualFold(input, "q") || strings.EqualFold(input, "quit") {
+ return -1, fmt.Errorf("selection canceled")
+ }
+
+ index, err := strconv.Atoi(input)
+ if err != nil || index < 1 || index > len(options) {
+ fmt.Println("Invalid selection. Try again or press q to cancel.")
+ continue
+ }
+
+ return index - 1, nil
+ }
+}
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index 5df0e6962..ad974c726 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -1,13 +1,18 @@
package containers
import (
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "net/url"
"strings"
"time"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/container"
@@ -21,6 +26,8 @@ var (
jsonOutput bool
)
+const maxPromptOptions = 20
+
// ContainersCmd is the parent command for container operations
var ContainersCmd = &cobra.Command{
Use: "containers",
@@ -94,7 +101,7 @@ var containersListCmd = &cobra.Command{
}
var containersGetCmd = &cobra.Command{
- Use: "get <container-id>",
+ Use: "get <container-id|name>",
Short: "Get detailed container information",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -104,20 +111,29 @@ var containersGetCmd = &cobra.Command{
return err
}
- path := types.Endpoints.Container(c.EnvID(), args[0])
- resp, err := c.Get(cmd.Context(), path)
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, complete, err := resolveContainer(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
- return fmt.Errorf("failed to get container: %w", err)
+ return err
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[container.Details]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if !complete {
+ path := types.Endpoints.Container(c.EnvID(), resolved.ID)
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to get container: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[container.Details]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ resolved = &result.Data
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ resultBytes, err := json.MarshalIndent(resolved, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
@@ -126,17 +142,17 @@ var containersGetCmd = &cobra.Command{
}
output.Header("Container Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Image", result.Data.Image)
- output.KeyValue("State", fmt.Sprintf("%s (Running: %v)", result.Data.State.Status, result.Data.State.Running))
- output.KeyValue("Created", result.Data.Created)
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Image", resolved.Image)
+ output.KeyValue("State", fmt.Sprintf("%s (Running: %v)", resolved.State.Status, resolved.State.Running))
+ output.KeyValue("Created", resolved.Created)
return nil
},
}
var containersStartCmd = &cobra.Command{
- Use: "start <container-id>",
+ Use: "start <container-id|name>",
Short: "Start a container",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -146,7 +162,12 @@ var containersStartCmd = &cobra.Command{
return err
}
- path := types.Endpoints.ContainerStart(c.EnvID(), args[0])
+ resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.ContainerStart(c.EnvID(), resolved.ID)
resp, err := c.Post(cmd.Context(), path, nil)
if err != nil {
return fmt.Errorf("failed to start container: %w", err)
@@ -167,13 +188,13 @@ var containersStartCmd = &cobra.Command{
return nil
}
- output.Success("Container %s started successfully", shortID(args[0]))
+ output.Success("Container %s started successfully", containerDisplayName(resolved))
return nil
},
}
var containersStopCmd = &cobra.Command{
- Use: "stop <container-id>",
+ Use: "stop <container-id|name>",
Short: "Stop a container",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -183,7 +204,12 @@ var containersStopCmd = &cobra.Command{
return err
}
- path := types.Endpoints.ContainerStop(c.EnvID(), args[0])
+ resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.ContainerStop(c.EnvID(), resolved.ID)
resp, err := c.Post(cmd.Context(), path, nil)
if err != nil {
return fmt.Errorf("failed to stop container: %w", err)
@@ -204,13 +230,13 @@ var containersStopCmd = &cobra.Command{
return nil
}
- output.Success("Container %s stopped successfully", shortID(args[0]))
+ output.Success("Container %s stopped successfully", containerDisplayName(resolved))
return nil
},
}
var containersRestartCmd = &cobra.Command{
- Use: "restart <container-id>",
+ Use: "restart <container-id|name>",
Short: "Restart a container",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -220,7 +246,12 @@ var containersRestartCmd = &cobra.Command{
return err
}
- path := types.Endpoints.ContainerRestart(c.EnvID(), args[0])
+ resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.ContainerRestart(c.EnvID(), resolved.ID)
resp, err := c.Post(cmd.Context(), path, nil)
if err != nil {
return fmt.Errorf("failed to restart container: %w", err)
@@ -241,13 +272,13 @@ var containersRestartCmd = &cobra.Command{
return nil
}
- output.Success("Container %s restarted successfully", shortID(args[0]))
+ output.Success("Container %s restarted successfully", containerDisplayName(resolved))
return nil
},
}
var containersUpdateCmd = &cobra.Command{
- Use: "update <container-id>",
+ Use: "update <container-id|name>",
Short: "Update a container",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -257,10 +288,15 @@ var containersUpdateCmd = &cobra.Command{
return err
}
+ resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
// Updating a container can take a long time as it pulls the image
c.SetTimeout(30 * time.Minute)
- path := types.Endpoints.ContainerUpdate(c.EnvID(), args[0])
+ path := types.Endpoints.ContainerUpdate(c.EnvID(), resolved.ID)
resp, err := c.Post(cmd.Context(), path, nil)
if err != nil {
return fmt.Errorf("failed to update container: %w", err)
@@ -281,20 +317,32 @@ var containersUpdateCmd = &cobra.Command{
return nil
}
- output.Success("Container %s updated successfully", shortID(args[0]))
+ output.Success("Container %s updated successfully", containerDisplayName(resolved))
return nil
},
}
var containersDeleteCmd = &cobra.Command{
- Use: "delete <container-id>",
+ Use: "delete <container-id|name>",
Aliases: []string{"rm", "remove"},
Short: "Delete a container",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveContainer(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ displayName := containerDisplayName(resolved)
+
if !forceFlag {
- fmt.Printf("Are you sure you want to delete container %s? (y/N): ", shortID(args[0]))
+ 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")
@@ -306,12 +354,7 @@ var containersDeleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- path := types.Endpoints.Container(c.EnvID(), args[0])
+ path := types.Endpoints.Container(c.EnvID(), resolved.ID)
resp, err := c.Delete(cmd.Context(), path)
if err != nil {
return fmt.Errorf("failed to delete container: %w", err)
@@ -332,7 +375,7 @@ var containersDeleteCmd = &cobra.Command{
return nil
}
- output.Success("Container %s deleted successfully", shortID(args[0]))
+ output.Success("Container %s deleted successfully", displayName)
return nil
},
}
@@ -410,3 +453,236 @@ func shortID(id string) string {
}
return id
}
+
+func containerDisplayName(details *container.Details) string {
+ if details == nil {
+ return ""
+ }
+ if strings.TrimSpace(details.Name) != "" {
+ return details.Name
+ }
+ if details.ID != "" {
+ return shortID(details.ID)
+ }
+ return ""
+}
+
+func resolveContainer(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*container.Details, bool, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, false, fmt.Errorf("container identifier is required")
+ }
+
+ details, complete, found, err := fetchContainerByIdentifier(ctx, c, trimmed)
+ if err != nil {
+ return nil, false, err
+ }
+ if found {
+ return details, complete, nil
+ }
+
+ matches, err := searchContainerMatches(ctx, c, trimmed)
+ if err != nil {
+ return nil, false, err
+ }
+
+ selected, err := selectContainerMatch(matches, trimmed, allowPrompt)
+ if err != nil {
+ return nil, false, err
+ }
+ if selected != nil {
+ return containerDetailsFromSummary(*selected), false, nil
+ }
+
+ identifierLower := strings.ToLower(trimmed)
+ if looksLikeIDPrefix(identifierLower) {
+ fallback, ok, err := fallbackContainerByIDPrefix(ctx, c, identifierLower)
+ if err != nil {
+ return nil, false, err
+ }
+ if ok {
+ return fallback, false, nil
+ }
+ }
+
+ return nil, false, fmt.Errorf("container %q not found; use the container ID or run `arcane containers list`", trimmed)
+}
+
+func fetchContainerByIdentifier(ctx context.Context, c *client.Client, identifier string) (*container.Details, bool, bool, error) {
+ resp, err := c.Get(ctx, types.Endpoints.Container(c.EnvID(), identifier))
+ if err != nil {
+ return nil, false, false, fmt.Errorf("failed to resolve container %q: %w", identifier, err)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, false, false, fmt.Errorf("failed to read container response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[container.Details]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, false, false, fmt.Errorf("failed to parse container response: %w", err)
+ }
+ return &result.Data, true, true, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return nil, false, false, fmt.Errorf("failed to resolve container %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ return nil, false, false, nil
+}
+
+func searchContainerMatches(ctx context.Context, c *client.Client, identifier string) ([]container.Summary, error) {
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Containers(c.EnvID()), url.QueryEscape(identifier), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to search containers: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return nil, fmt.Errorf("failed to read containers response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return nil, fmt.Errorf("failed to search containers (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result base.Paginated[container.Summary]
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse containers response: %w", err)
+ }
+
+ identifierLower := strings.ToLower(identifier)
+ matches := make([]container.Summary, 0)
+ for _, item := range result.Data {
+ if containerMatches(item, identifierLower, identifier) {
+ matches = append(matches, item)
+ }
+ }
+
+ return matches, nil
+}
+
+func selectContainerMatch(matches []container.Summary, identifier string, allowPrompt bool) (*container.Summary, error) {
+ if len(matches) == 1 {
+ return &matches[0], nil
+ }
+ if len(matches) == 0 {
+ return nil, nil
+ }
+
+ if !allowPrompt {
+ return nil, fmt.Errorf("multiple containers match %q; use the container ID or run `arcane containers list`", identifier)
+ }
+ if len(matches) > maxPromptOptions {
+ return nil, fmt.Errorf("multiple containers match %q (%d results); refine your query or use the container ID", identifier, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ options = append(options, formatContainerOption(match))
+ }
+ choice, err := prompt.Select("container", options)
+ if err != nil {
+ return nil, err
+ }
+ return &matches[choice], nil
+}
+
+func containerSummaryName(summary container.Summary) string {
+ if len(summary.Names) == 0 {
+ return ""
+ }
+ return strings.TrimPrefix(summary.Names[0], "/")
+}
+
+func containerDetailsFromSummary(summary container.Summary) *container.Details {
+ return &container.Details{ID: summary.ID, Name: containerSummaryName(summary)}
+}
+
+func fallbackContainerByIDPrefix(ctx context.Context, c *client.Client, identifierLower string) (*container.Details, bool, error) {
+ fallbackPath := fmt.Sprintf("%s?limit=%d", types.Endpoints.Containers(c.EnvID()), 200)
+ fallbackResp, err := c.Get(ctx, fallbackPath)
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to search containers: %w", err)
+ }
+ fallbackBody, err := io.ReadAll(fallbackResp.Body)
+ _ = fallbackResp.Body.Close()
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to read containers response: %w", err)
+ }
+ if fallbackResp.StatusCode < 200 || fallbackResp.StatusCode >= 300 {
+ return nil, false, nil
+ }
+
+ var fallbackResult base.Paginated[container.Summary]
+ if err := json.Unmarshal(fallbackBody, &fallbackResult); err != nil {
+ return nil, false, fmt.Errorf("failed to parse containers response: %w", err)
+ }
+ for _, item := range fallbackResult.Data {
+ if strings.HasPrefix(strings.ToLower(item.ID), identifierLower) {
+ return containerDetailsFromSummary(item), true, nil
+ }
+ }
+
+ return nil, false, nil
+}
+
+func containerMatches(item container.Summary, identifierLower, original string) bool {
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+ if strings.Contains(idLower, identifierLower) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Image), identifierLower) {
+ return true
+ }
+ for _, name := range item.Names {
+ trimmedName := strings.TrimPrefix(name, "/")
+ if strings.Contains(strings.ToLower(trimmedName), identifierLower) {
+ return true
+ }
+ if strings.EqualFold(trimmedName, original) || strings.EqualFold(name, original) {
+ return true
+ }
+ }
+ return false
+}
+
+func formatContainerOption(item container.Summary) string {
+ name := ""
+ if len(item.Names) > 0 {
+ name = strings.TrimPrefix(item.Names[0], "/")
+ }
+ if name == "" {
+ name = shortID(item.ID)
+ }
+ image := item.Image
+ if image == "" {
+ image = "<unknown>"
+ }
+ state := item.State
+ if state == "" {
+ state = "unknown"
+ }
+ return fmt.Sprintf("%s (%s, %s)", name, shortID(item.ID), image+" / "+state)
+}
+
+func looksLikeIDPrefix(value string) bool {
+ if len(value) < 4 {
+ return false
+ }
+ for _, r := range value {
+ if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index e3e3724ad..83a92c728 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -31,6 +31,7 @@ package images
import (
"bytes"
+ "context"
"encoding/json"
"fmt"
"io"
@@ -47,6 +48,7 @@ import (
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/logger"
"github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/image"
"github.com/schollz/progressbar/v3"
@@ -62,6 +64,8 @@ var (
imagesSearch string
)
+const maxPromptOptions = 20
+
// ImagesCmd is the parent command for image operations
var ImagesCmd = &cobra.Command{
Use: "images",
@@ -165,8 +169,8 @@ var imagesListCmd = &cobra.Command{
}
var imagesGetCmd = &cobra.Command{
- Use: "get [IMAGE_ID]",
- Short: "Get image details by ID",
+ Use: "get <image-id|name>",
+ Short: "Get image details by ID or name",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -176,7 +180,13 @@ var imagesGetCmd = &cobra.Command{
return err
}
- imageID := args[0]
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+
+ imageID, err := resolveImageID(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
path := types.Endpoints.Image(c.EnvID(), imageID)
log.Debugf("Getting image details from: %s", path)
@@ -194,7 +204,7 @@ var imagesGetCmd = &cobra.Command{
log.Debugf("Response body: %s", string(body))
- if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ if jsonOutput {
fmt.Println(string(body))
return nil
}
@@ -259,7 +269,7 @@ var (
)
var imagesRemoveCmd = &cobra.Command{
- Use: "remove [IMAGE_ID]",
+ Use: "remove <image-id|name>",
Aliases: []string{"rm", "delete"},
Short: "Remove an image",
Args: cobra.ExactArgs(1),
@@ -271,7 +281,10 @@ var imagesRemoveCmd = &cobra.Command{
return err
}
- imageID := args[0]
+ imageID, err := resolveImageID(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
path := types.Endpoints.Image(c.EnvID(), imageID)
if removeForce {
@@ -741,3 +754,207 @@ func init() {
ImagesCmd.AddCommand(imagesUploadCmd)
}
+
+func resolveImageID(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (string, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return "", fmt.Errorf("image identifier is required")
+ }
+
+ resolvedID, found, err := resolveImageByID(ctx, c, trimmed)
+ if err != nil {
+ return "", err
+ }
+ if found {
+ return resolvedID, nil
+ }
+
+ terms := buildImageSearchTerms(trimmed)
+ seenTerms := make(map[string]struct{}, len(terms))
+ for _, term := range terms {
+ term = strings.TrimSpace(term)
+ if term == "" {
+ continue
+ }
+ if _, ok := seenTerms[term]; ok {
+ continue
+ }
+ seenTerms[term] = struct{}{}
+
+ matches, err := searchImageMatches(ctx, c, term, trimmed)
+ if err != nil {
+ return "", err
+ }
+
+ selectedID, resolved, err := selectImageMatchID(matches, trimmed, allowPrompt)
+ if err != nil {
+ return "", err
+ }
+ if resolved {
+ return selectedID, nil
+ }
+ }
+
+ return "", fmt.Errorf("image %q not found; use the image ID or run `arcane images list`", trimmed)
+}
+
+func resolveImageByID(ctx context.Context, c *client.Client, identifier string) (string, bool, error) {
+ resp, err := c.Get(ctx, types.Endpoints.Image(c.EnvID(), identifier))
+ if err != nil {
+ return "", false, fmt.Errorf("failed to resolve image %q: %w", identifier, err)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return "", false, fmt.Errorf("failed to read image response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result struct {
+ Success bool `json:"success"`
+ Data image.DetailSummary `json:"data"`
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ return "", false, fmt.Errorf("failed to parse image response: %w", err)
+ }
+ if result.Data.ID == "" {
+ return "", false, fmt.Errorf("image lookup for %q returned empty ID", identifier)
+ }
+ return result.Data.ID, true, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return "", false, fmt.Errorf("failed to resolve image %q (status %d): %s", identifier, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ return "", false, nil
+}
+
+func buildImageSearchTerms(trimmed string) []string {
+ terms := []string{trimmed}
+ identifierLower := strings.ToLower(trimmed)
+ if strings.Contains(trimmed, "@") {
+ if repo, _, ok := strings.Cut(trimmed, "@"); ok && repo != "" {
+ terms = append(terms, repo)
+ }
+ return terms
+ }
+ if strings.Contains(trimmed, ":") && !strings.HasPrefix(identifierLower, "sha256:") {
+ if repo, _, ok := strings.Cut(trimmed, ":"); ok && repo != "" {
+ terms = append(terms, repo)
+ }
+ }
+ return terms
+}
+
+func searchImageMatches(ctx context.Context, c *client.Client, term, trimmed string) ([]image.Summary, error) {
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Images(c.EnvID()), url.QueryEscape(term), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to search images: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return nil, fmt.Errorf("failed to read images response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return nil, fmt.Errorf("failed to search images (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result struct {
+ Success bool `json:"success"`
+ Data []image.Summary `json:"data"`
+ }
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse images response: %w", err)
+ }
+
+ return filterImageMatches(result.Data, trimmed), nil
+}
+
+func filterImageMatches(items []image.Summary, trimmed string) []image.Summary {
+ identifierLower := strings.ToLower(trimmed)
+ hasSeparator := strings.Contains(trimmed, ":") || strings.Contains(trimmed, "@")
+ matches := make([]image.Summary, 0)
+ for _, item := range items {
+ if imageMatches(item, trimmed, identifierLower, hasSeparator) {
+ matches = append(matches, item)
+ }
+ }
+ return matches
+}
+
+func imageMatches(item image.Summary, trimmed, identifierLower string, hasSeparator bool) bool {
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+
+ if !hasSeparator && strings.Contains(strings.ToLower(item.Repo), identifierLower) {
+ return true
+ }
+
+ for _, tag := range item.RepoTags {
+ tagLower := strings.ToLower(tag)
+ if (!hasSeparator && strings.Contains(tagLower, identifierLower)) || strings.EqualFold(tag, trimmed) {
+ return true
+ }
+ }
+
+ if item.Repo != "" && item.Tag != "" {
+ combined := item.Repo + ":" + item.Tag
+ combinedLower := strings.ToLower(combined)
+ if strings.EqualFold(combined, trimmed) || (hasSeparator && strings.Contains(combinedLower, identifierLower)) {
+ return true
+ }
+ }
+
+ for _, digest := range item.RepoDigests {
+ digestLower := strings.ToLower(digest)
+ if strings.EqualFold(digest, trimmed) || strings.Contains(digestLower, identifierLower) {
+ return true
+ }
+ }
+
+ return false
+}
+
+func selectImageMatchID(matches []image.Summary, trimmed string, allowPrompt bool) (string, bool, error) {
+ if len(matches) == 1 {
+ return matches[0].ID, true, nil
+ }
+ if len(matches) == 0 {
+ return "", false, nil
+ }
+
+ if !allowPrompt {
+ return "", false, fmt.Errorf("multiple images match %q; use the image ID or run `arcane images list`", trimmed)
+ }
+ if len(matches) > maxPromptOptions {
+ return "", false, fmt.Errorf("multiple images match %q (%d results); refine your query or use the image ID", trimmed, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ options = append(options, formatImageMatchOption(match))
+ }
+ choice, err := prompt.Select("image", options)
+ if err != nil {
+ return "", false, err
+ }
+ return matches[choice].ID, true, nil
+}
+
+func formatImageMatchOption(match image.Summary) string {
+ label := match.ID
+ if len(match.RepoTags) > 0 {
+ label = match.RepoTags[0]
+ } else if match.Repo != "" && match.Tag != "" {
+ label = match.Repo + ":" + match.Tag
+ }
+ return fmt.Sprintf("%s (%s)", label, match.ID)
+}
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index 166658588..4387dc460 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -1,12 +1,17 @@
package networks
import (
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "net/url"
"strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/network"
@@ -19,6 +24,8 @@ var (
jsonOutput bool
)
+const maxPromptOptions = 20
+
// NetworksCmd is the parent command for network operations
var NetworksCmd = &cobra.Command{
Use: "networks",
@@ -80,15 +87,86 @@ var listCmd = &cobra.Command{
},
}
+var getCmd = &cobra.Command{
+ Use: "get <network-id|name>",
+ Short: "Get network details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.Network(c.EnvID(), resolvedID))
+ if err != nil {
+ return fmt.Errorf("failed to get network: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[network.Inspect]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ display := resolvedName
+ if display == "" {
+ display = result.Data.Name
+ }
+
+ output.Header("Network Details")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", display)
+ output.KeyValue("Driver", result.Data.Driver)
+ output.KeyValue("Scope", result.Data.Scope)
+ output.KeyValue("Created", result.Data.Created.Format("2006-01-02 15:04"))
+ output.KeyValue("Internal", result.Data.Internal)
+ output.KeyValue("Attachable", result.Data.Attachable)
+ output.KeyValue("Ingress", result.Data.Ingress)
+ output.KeyValue("Containers", len(result.Data.ContainersList))
+ return nil
+ },
+}
+
var deleteCmd = &cobra.Command{
- Use: "delete <network-id>",
+ Use: "delete <network-id|name>",
Aliases: []string{"rm", "remove"},
Short: "Delete a network",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolvedID, resolvedName, err := resolveNetworkID(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ display := resolvedName
+ if display == "" {
+ display = shortID(resolvedID)
+ }
+
if !forceFlag {
- fmt.Printf("Are you sure you want to delete network %s? (y/N): ", shortID(args[0]))
+ 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")
@@ -100,12 +178,7 @@ var deleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resp, err := c.Delete(cmd.Context(), types.Endpoints.Network(c.EnvID(), args[0]))
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.Network(c.EnvID(), resolvedID))
if err != nil {
return fmt.Errorf("failed to delete network: %w", err)
}
@@ -113,15 +186,18 @@ var deleteCmd = &cobra.Command{
if jsonOutput {
var result base.ApiResponse[interface{}]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
}
+ fmt.Println(string(resultBytes))
return nil
}
- output.Success("Network %s deleted successfully", shortID(args[0]))
+ output.Success("Network %s deleted successfully", display)
return nil
},
}
@@ -215,6 +291,7 @@ var pruneCmd = &cobra.Command{
func init() {
NetworksCmd.AddCommand(listCmd)
+ NetworksCmd.AddCommand(getCmd)
NetworksCmd.AddCommand(deleteCmd)
NetworksCmd.AddCommand(countsCmd)
NetworksCmd.AddCommand(pruneCmd)
@@ -223,6 +300,9 @@ func init() {
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of networks to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ // Get command flags
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
// Delete command flags
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -241,3 +321,101 @@ func shortID(id string) string {
}
return id
}
+
+func resolveNetworkID(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (string, string, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return "", "", fmt.Errorf("network identifier is required")
+ }
+
+ resp, err := c.Get(ctx, types.Endpoints.Network(c.EnvID(), trimmed))
+ if err != nil {
+ return "", "", fmt.Errorf("failed to resolve network %q: %w", trimmed, err)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return "", "", fmt.Errorf("failed to read network response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[network.Inspect]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return "", "", fmt.Errorf("failed to parse network response: %w", err)
+ }
+ return result.Data.ID, result.Data.Name, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return "", "", fmt.Errorf("failed to resolve network %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Networks(c.EnvID()), url.QueryEscape(trimmed), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return "", "", fmt.Errorf("failed to search networks: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return "", "", fmt.Errorf("failed to read networks response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return "", "", fmt.Errorf("failed to search networks (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result base.Paginated[network.Summary]
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return "", "", fmt.Errorf("failed to parse networks response: %w", err)
+ }
+
+ identifierLower := strings.ToLower(trimmed)
+ matches := make([]network.Summary, 0)
+ for _, item := range result.Data {
+ if networkMatches(item, identifierLower, trimmed) {
+ matches = append(matches, item)
+ }
+ }
+
+ if len(matches) == 1 {
+ return matches[0].ID, matches[0].Name, nil
+ }
+
+ if len(matches) > 1 {
+ if !allowPrompt {
+ return "", "", fmt.Errorf("multiple networks match %q; use the network ID or run `arcane networks list`", trimmed)
+ }
+ if len(matches) > maxPromptOptions {
+ return "", "", fmt.Errorf("multiple networks match %q (%d results); refine your query or use the network ID", trimmed, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ options = append(options, fmt.Sprintf("%s (%s)", match.Name, shortID(match.ID)))
+ }
+ choice, err := prompt.Select("network", options)
+ if err != nil {
+ return "", "", err
+ }
+ return matches[choice].ID, matches[choice].Name, nil
+ }
+
+ return "", "", fmt.Errorf("network %q not found; use the network ID or run `arcane networks list`", trimmed)
+}
+
+func networkMatches(item network.Summary, identifierLower, original string) bool {
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+ if strings.Contains(idLower, identifierLower) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Name), identifierLower) {
+ return true
+ }
+ return strings.EqualFold(item.Name, original)
+}
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 6dcb9e14f..7d8c3b5f3 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -1,13 +1,18 @@
package projects
import (
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "net/url"
"strings"
"time"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/project"
@@ -20,6 +25,8 @@ var (
jsonOutput bool
)
+const maxPromptOptions = 20
+
// ProjectsCmd is the parent command for project operations
var ProjectsCmd = &cobra.Command{
Use: "projects",
@@ -83,14 +90,28 @@ var listCmd = &cobra.Command{
}
var destroyCmd = &cobra.Command{
- Use: "destroy <project-id>",
+ Use: "destroy <project-id|name>",
Aliases: []string{"rm", "remove"},
Short: "Destroy project and remove all containers",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
if !forceFlag {
- fmt.Printf("Are you sure you want to destroy project %s? This will remove all containers! (y/N): ", args[0])
+ display := resolved.Name
+ 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")
@@ -102,24 +123,19 @@ var destroyCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resp, err := c.Delete(cmd.Context(), types.Endpoints.ProjectDestroy(c.EnvID(), args[0]))
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.ProjectDestroy(c.EnvID(), resolved.ID))
if err != nil {
return fmt.Errorf("failed to destroy project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Project %s destroyed successfully", args[0])
+ output.Success("Project %s destroyed successfully", resolved.Name)
return nil
},
}
var getCmd = &cobra.Command{
- Use: "get <project-id>",
+ Use: "get <project-id|name>",
Short: "Get project details",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -129,19 +145,28 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Endpoints.Project(c.EnvID(), args[0]))
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, complete, err := resolveProject(cmd.Context(), c, args[0], allowPrompt)
if err != nil {
- return fmt.Errorf("failed to get project: %w", err)
+ return err
}
- defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[project.Details]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if !complete {
+ resp, err := c.Get(cmd.Context(), types.Endpoints.Project(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to get project: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[project.Details]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ resolved = &result.Data
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
+ resultBytes, err := json.MarshalIndent(resolved, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
@@ -150,17 +175,17 @@ var getCmd = &cobra.Command{
}
output.Header("Project Details")
- output.KeyValue("ID", result.Data.ID)
- output.KeyValue("Name", result.Data.Name)
- output.KeyValue("Status", result.Data.Status)
- output.KeyValue("Services", result.Data.ServiceCount)
- output.KeyValue("Running", result.Data.RunningCount)
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Status", resolved.Status)
+ output.KeyValue("Services", resolved.ServiceCount)
+ output.KeyValue("Running", resolved.RunningCount)
return nil
},
}
var upCmd = &cobra.Command{
- Use: "up <project-id>",
+ Use: "up <project-id|name>",
Short: "Start project services",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -170,19 +195,24 @@ var upCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectUp(c.EnvID(), args[0]), nil)
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectUp(c.EnvID(), resolved.ID), nil)
if err != nil {
return fmt.Errorf("failed to start project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Project %s started successfully", args[0])
+ output.Success("Project %s started successfully", resolved.Name)
return nil
},
}
var downCmd = &cobra.Command{
- Use: "down <project-id>",
+ Use: "down <project-id|name>",
Short: "Stop project services",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -192,19 +222,24 @@ var downCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectDown(c.EnvID(), args[0]), nil)
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectDown(c.EnvID(), resolved.ID), nil)
if err != nil {
return fmt.Errorf("failed to stop project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Project %s stopped successfully", args[0])
+ output.Success("Project %s stopped successfully", resolved.Name)
return nil
},
}
var restartCmd = &cobra.Command{
- Use: "restart <project-id>",
+ Use: "restart <project-id|name>",
Short: "Restart project services",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -214,19 +249,24 @@ var restartCmd = &cobra.Command{
return err
}
- resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectRestart(c.EnvID(), args[0]), nil)
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectRestart(c.EnvID(), resolved.ID), nil)
if err != nil {
return fmt.Errorf("failed to restart project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Project %s restarted successfully", args[0])
+ output.Success("Project %s restarted successfully", resolved.Name)
return nil
},
}
var redeployCmd = &cobra.Command{
- Use: "redeploy <project-id>",
+ Use: "redeploy <project-id|name>",
Short: "Redeploy project (pull images and restart)",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -236,22 +276,27 @@ var redeployCmd = &cobra.Command{
return err
}
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
// Redeploying can take a long time as it pulls images and restarts containers
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectRedeploy(c.EnvID(), args[0]), nil)
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectRedeploy(c.EnvID(), resolved.ID), nil)
if err != nil {
return fmt.Errorf("failed to redeploy project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Project %s redeployed successfully", args[0])
+ output.Success("Project %s redeployed successfully", resolved.Name)
return nil
},
}
var pullCmd = &cobra.Command{
- Use: "pull <project-id>",
+ Use: "pull <project-id|name>",
Short: "Pull latest images for project",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
@@ -261,16 +306,21 @@ var pullCmd = &cobra.Command{
return err
}
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
// Pulling images can take a long time
c.SetTimeout(30 * time.Minute)
- resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectPull(c.EnvID(), args[0]), nil)
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ProjectPull(c.EnvID(), resolved.ID), nil)
if err != nil {
return fmt.Errorf("failed to pull images: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Images pulled successfully for project %s", args[0])
+ output.Success("Images pulled successfully for project %s", resolved.Name)
return nil
},
}
@@ -338,3 +388,108 @@ func init() {
destroyCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force destroy without confirmation")
destroyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
+
+func resolveProject(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*project.Details, bool, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, false, fmt.Errorf("project identifier is required")
+ }
+
+ resp, err := c.Get(ctx, types.Endpoints.Project(c.EnvID(), trimmed))
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to resolve project %q: %w", trimmed, err)
+ }
+
+ bodyBytes, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to read project response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[project.Details]
+ if err := json.Unmarshal(bodyBytes, &result); err != nil {
+ return nil, false, fmt.Errorf("failed to parse project response: %w", err)
+ }
+ return &result.Data, true, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return nil, false, fmt.Errorf("failed to resolve project %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
+ }
+
+ identifierLower := strings.ToLower(trimmed)
+
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Projects(c.EnvID()), url.QueryEscape(trimmed), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to search projects: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to read projects response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return nil, false, fmt.Errorf("failed to search projects (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result base.Paginated[project.Details]
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return nil, false, fmt.Errorf("failed to parse projects response: %w", err)
+ }
+
+ matches := make([]project.Details, 0)
+ for _, proj := range result.Data {
+ if projectMatches(proj, identifierLower, trimmed) {
+ matches = append(matches, proj)
+ }
+ }
+
+ if len(matches) == 1 {
+ return &matches[0], false, nil
+ }
+
+ if len(matches) > 1 {
+ if !allowPrompt {
+ return nil, false, fmt.Errorf("multiple projects match %q; use the project ID or run `arcane projects list`", trimmed)
+ }
+ if len(matches) > maxPromptOptions {
+ return nil, false, fmt.Errorf("multiple projects match %q (%d results); refine your query or use the project ID", trimmed, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ options = append(options, fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, match.Status))
+ }
+ choice, err := prompt.Select("project", options)
+ if err != nil {
+ return nil, false, err
+ }
+ return &matches[choice], false, nil
+ }
+
+ return nil, false, fmt.Errorf("project %q not found; use the project ID or run `arcane projects list`", trimmed)
+}
+
+func projectMatches(item project.Details, identifierLower, original string) bool {
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+ if strings.Contains(idLower, identifierLower) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Name), identifierLower) {
+ return true
+ }
+ if strings.EqualFold(item.Name, original) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Path), identifierLower) {
+ return true
+ }
+ return false
+}
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index 0756cf0e4..a047d8af3 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -107,23 +107,15 @@ func init() {
rootCmd.AddCommand(configClient.ConfigCmd)
rootCmd.AddCommand(generate.GenerateCmd)
rootCmd.AddCommand(version.VersionCmd)
-
- // Authentication
rootCmd.AddCommand(auth.AuthCmd)
-
- // Core resource management
rootCmd.AddCommand(containers.ContainersCmd)
rootCmd.AddCommand(images.ImagesCmd)
rootCmd.AddCommand(volumes.VolumesCmd)
rootCmd.AddCommand(networks.NetworksCmd)
rootCmd.AddCommand(projects.ProjectsCmd)
-
- // Management
rootCmd.AddCommand(apikeys.ApiKeysCmd)
rootCmd.AddCommand(environments.EnvironmentsCmd)
rootCmd.AddCommand(users.UsersCmd)
-
- // Advanced features
rootCmd.AddCommand(registries.RegistriesCmd)
rootCmd.AddCommand(templates.TemplatesCmd)
rootCmd.AddCommand(settings.SettingsCmd)
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index ce1e12b8b..8b0fe3cb7 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -1,12 +1,17 @@
package volumes
import (
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "net/url"
"strings"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/prompt"
"github.com/getarcaneapp/arcane/cli/internal/types"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/volume"
@@ -19,6 +24,8 @@ var (
jsonOutput bool
)
+const maxPromptOptions = 20
+
// VolumesCmd is the parent command for volume operations
var VolumesCmd = &cobra.Command{
Use: "volumes",
@@ -79,6 +86,46 @@ var listCmd = &cobra.Command{
},
}
+var getCmd = &cobra.Command{
+ Use: "get <volume-name>",
+ Short: "Get volume details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(resolved, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("Volume Details")
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Driver", resolved.Driver)
+ output.KeyValue("Mountpoint", resolved.Mountpoint)
+ output.KeyValue("Scope", resolved.Scope)
+ output.KeyValue("Created", resolved.CreatedAt)
+ output.KeyValue("In Use", resolved.InUse)
+ if resolved.Size > 0 {
+ output.KeyValue("Size (bytes)", resolved.Size)
+ }
+ return nil
+ },
+}
+
var deleteCmd = &cobra.Command{
Use: "delete <volume-name>",
Aliases: []string{"rm", "remove"},
@@ -86,8 +133,19 @@ var deleteCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ allowPrompt := !forceFlag && prompt.IsInteractive()
+ resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+
if !forceFlag {
- fmt.Printf("Are you sure you want to delete volume %s? (y/N): ", args[0])
+ 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")
@@ -99,18 +157,13 @@ var deleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resp, err := c.Delete(cmd.Context(), types.Endpoints.Volume(c.EnvID(), args[0]))
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.Volume(c.EnvID(), resolved.Name))
if err != nil {
return fmt.Errorf("failed to delete volume: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- output.Success("Volume %s deleted successfully", args[0])
+ output.Success("Volume %s deleted successfully", resolved.Name)
return nil
},
}
@@ -254,7 +307,13 @@ var usageCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Endpoints.VolumeUsage(c.EnvID(), args[0]))
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, err := resolveVolume(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.VolumeUsage(c.EnvID(), resolved.Name))
if err != nil {
return fmt.Errorf("failed to get volume usage: %w", err)
}
@@ -274,7 +333,7 @@ var usageCmd = &cobra.Command{
return nil
}
- output.Header("Volume Usage: %s", args[0])
+ output.Header("Volume Usage: %s", resolved.Name)
resultBytes, err := json.MarshalIndent(result.Data, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal volume usage: %w", err)
@@ -286,6 +345,7 @@ var usageCmd = &cobra.Command{
func init() {
VolumesCmd.AddCommand(listCmd)
+ VolumesCmd.AddCommand(getCmd)
VolumesCmd.AddCommand(deleteCmd)
VolumesCmd.AddCommand(countsCmd)
VolumesCmd.AddCommand(pruneCmd)
@@ -296,6 +356,9 @@ func init() {
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of volumes to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ // Get command flags
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
// Delete command flags
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -309,3 +372,105 @@ func init() {
sizesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
usageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
+
+func resolveVolume(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*volume.Volume, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, fmt.Errorf("volume identifier is required")
+ }
+
+ resp, err := c.Get(ctx, types.Endpoints.Volume(c.EnvID(), trimmed))
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve volume %q: %w", trimmed, err)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, fmt.Errorf("failed to read volume response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[volume.Volume]
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse volume response: %w", err)
+ }
+ return &result.Data, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return nil, fmt.Errorf("failed to resolve volume %q (status %d): %s", trimmed, resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ searchPath := fmt.Sprintf("%s?search=%s&limit=%d", types.Endpoints.Volumes(c.EnvID()), url.QueryEscape(trimmed), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to search volumes: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return nil, fmt.Errorf("failed to read volumes response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return nil, fmt.Errorf("failed to search volumes (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result base.Paginated[volume.Volume]
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse volumes response: %w", err)
+ }
+
+ identifierLower := strings.ToLower(trimmed)
+ matches := make([]volume.Volume, 0)
+ for _, item := range result.Data {
+ if volumeMatches(item, identifierLower, trimmed) {
+ matches = append(matches, item)
+ }
+ }
+
+ if len(matches) == 1 {
+ return &matches[0], nil
+ }
+
+ if len(matches) > 1 {
+ if !allowPrompt {
+ return nil, fmt.Errorf("multiple volumes match %q; use the volume name or run `arcane volumes list`", trimmed)
+ }
+ if len(matches) > maxPromptOptions {
+ return nil, fmt.Errorf("multiple volumes match %q (%d results); refine your query or use the volume name", trimmed, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ label := match.Name
+ if match.Driver != "" {
+ label = fmt.Sprintf("%s (%s)", match.Name, match.Driver)
+ }
+ options = append(options, label)
+ }
+ choice, err := prompt.Select("volume", options)
+ if err != nil {
+ return nil, err
+ }
+ return &matches[choice], nil
+ }
+
+ return nil, fmt.Errorf("volume %q not found; use the volume name or run `arcane volumes list`", trimmed)
+}
+
+func volumeMatches(item volume.Volume, identifierLower, original string) bool {
+ if strings.EqualFold(item.Name, original) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Name), identifierLower) {
+ return true
+ }
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+ return false
+}