Skip to content

Modern Docker Management, Designed for Everyone

feat(cli): implement missing cli commands (projects, jobs, containers, gitops) (#1946)

Jim Crowleya41b8a1cf76b
diff --git a/cli/internal/output/output.go b/cli/internal/output/output.go
index 2b996e3f7..4c79979e9 100644
--- a/cli/internal/output/output.go
+++ b/cli/internal/output/output.go
@@ -22,6 +22,7 @@ import (
"charm.land/lipgloss/v2/compat"
"charm.land/lipgloss/v2/table"
"github.com/charmbracelet/x/term"
+ "github.com/mattn/go-runewidth"
)
var (
@@ -67,12 +68,10 @@ var (
enabledStyle = lipgloss.NewStyle().Foreground(arcanePurple)
tablePurple = lipgloss.Color("99")
- tableGray = lipgloss.Color("245")
- tableLightGray = lipgloss.Color("241")
tableHeader = lipgloss.NewStyle().Foreground(tablePurple).Bold(true).Align(lipgloss.Center).Padding(0, 1)
tableCell = lipgloss.NewStyle().Padding(0, 1)
- tableOddRow = tableCell.Foreground(tableGray)
- tableEvenRow = tableCell.Foreground(tableLightGray)
+ tableOddRow = tableCell.Foreground(textPrimary)
+ tableEvenRow = tableCell.Foreground(textPrimary)
tableBorder = lipgloss.NewStyle().Foreground(tablePurple)
tablePlainCell = lipgloss.NewStyle().Padding(0, 1)
tablePlainHead = lipgloss.NewStyle().Bold(true).Padding(0, 1)
@@ -80,6 +79,8 @@ var (
var ansiRegexp = regexp.MustCompile("\x1b\\[[0-9;]*[a-zA-Z]")
+var tableWhitespaceReplacer = strings.NewReplacer("\r\n", " ", "\n", " ", "\r", " ", "\t", " ")
+
var colorEnabled = true
func shouldColor() bool {
@@ -241,8 +242,9 @@ func Table(headers []string, rows [][]string) {
return
}
- rows = tintTableRows(headers, rows)
rows = normalizeTableRows(rows, n)
+ rows = tintTableRows(headers, rows)
+ headers, rows = fitTableToTerminal(headers, rows)
t := table.New().Border(lipgloss.NormalBorder()).Headers(headers...)
@@ -275,6 +277,152 @@ func Table(headers []string, rows [][]string) {
lipgloss.Println(t)
}
+func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]string) {
+ if len(headers) == 0 {
+ return headers, rows
+ }
+
+ columnCount := len(headers)
+ displayHeaders := make([]string, columnCount)
+ for i, header := range headers {
+ displayHeaders[i] = sanitizeTableCell(header)
+ }
+
+ displayRows := normalizeTableRows(rows, columnCount)
+ for i, row := range displayRows {
+ cleaned := make([]string, columnCount)
+ for col := range columnCount {
+ cleaned[col] = sanitizeTableCell(row[col])
+ }
+ displayRows[i] = cleaned
+ }
+
+ if !term.IsTerminal(os.Stdout.Fd()) {
+ return displayHeaders, displayRows
+ }
+
+ terminalWidth, _, err := term.GetSize(os.Stdout.Fd())
+ if err != nil || terminalWidth <= 0 {
+ return displayHeaders, displayRows
+ }
+
+ columnWidths := make([]int, columnCount)
+ for i, header := range displayHeaders {
+ columnWidths[i] = maxInt(1, visibleWidth(header))
+ }
+
+ for _, row := range displayRows {
+ for col := range columnCount {
+ columnWidths[col] = maxInt(columnWidths[col], visibleWidth(row[col]))
+ }
+ }
+
+ availableContentWidth := terminalWidth - tableNonContentWidth(columnCount)
+ if availableContentWidth <= 0 {
+ return displayHeaders, displayRows
+ }
+
+ fitWidths := fitColumnWidths(columnWidths, availableContentWidth)
+ for i, header := range displayHeaders {
+ displayHeaders[i] = truncateVisible(header, fitWidths[i])
+ }
+
+ for i, row := range displayRows {
+ for col := range columnCount {
+ row[col] = truncateVisible(row[col], fitWidths[col])
+ }
+ displayRows[i] = row
+ }
+
+ return displayHeaders, displayRows
+}
+
+func sanitizeTableCell(value string) string {
+ cleaned := tableWhitespaceReplacer.Replace(value)
+ return strings.TrimSpace(cleaned)
+}
+
+func visibleWidth(value string) int {
+ return runewidth.StringWidth(ansiRegexp.ReplaceAllString(value, ""))
+}
+
+func truncateVisible(value string, maxWidth int) string {
+ if maxWidth <= 0 {
+ return ""
+ }
+ if visibleWidth(value) <= maxWidth {
+ return value
+ }
+
+ plain := ansiRegexp.ReplaceAllString(value, "")
+ if maxWidth == 1 {
+ return "…"
+ }
+
+ return runewidth.Truncate(plain, maxWidth, "…")
+}
+
+func tableNonContentWidth(columnCount int) int {
+ const horizontalCellPadding = 2
+
+ // For normal border style:
+ // - one vertical border per boundary: columnCount + 1
+ // - one space of left + right padding per cell: 2 * columnCount
+ return (columnCount + 1) + (horizontalCellPadding * columnCount)
+}
+
+func fitColumnWidths(widths []int, available int) []int {
+ fitted := make([]int, len(widths))
+ copy(fitted, widths)
+
+ if len(fitted) == 0 {
+ return fitted
+ }
+
+ if available < len(fitted) {
+ available = len(fitted)
+ }
+
+ current := sumInts(fitted)
+ for current > available {
+ idx := widestShrinkableColumn(fitted)
+ if idx < 0 {
+ break
+ }
+ fitted[idx]--
+ current--
+ }
+
+ return fitted
+}
+
+func widestShrinkableColumn(widths []int) int {
+ idx := -1
+ maxWidth := 1
+ for i, width := range widths {
+ if width > maxWidth {
+ idx = i
+ maxWidth = width
+ }
+ }
+ return idx
+}
+
+func sumInts(values []int) int {
+ total := 0
+ for _, value := range values {
+ total += value
+ }
+ return total
+}
+
+func maxInt(a, b int) int {
+ if a > b {
+ return a
+ }
+ return b
+}
+
func normalizeTableRows(rows [][]string, width int) [][]string {
if width == 0 || len(rows) == 0 {
return rows
diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go
index a6f0dec01..cd2e46b69 100644
--- a/cli/internal/prompt/prompt.go
+++ b/cli/internal/prompt/prompt.go
@@ -28,7 +28,7 @@ func Select(label string, options []string) (int, error) {
items[i] = selectItem{index: i, title: option}
}
- model := newSelectModel(label, items)
+ model := newSelectModel(items)
program := tea.NewProgram(model)
finalModel, err := program.Run()
if err != nil {
@@ -45,9 +45,26 @@ func Select(label string, options []string) (int, error) {
if result.choice < 0 {
return -1, fmt.Errorf("selection required")
}
+ if result.choice >= len(options) {
+ return -1, fmt.Errorf("selection out of range")
+ }
+
+ clearScreenAndShowSelection(label, options[result.choice])
return result.choice, nil
}
+func clearScreenAndShowSelection(label, selected string) {
+ // Clear visible terminal content and place cursor at top-left.
+ fmt.Print("\033[H\033[2J")
+
+ if label == "" {
+ fmt.Printf("Selected: %s\n\n", selected)
+ return
+ }
+
+ fmt.Printf("Selected %s: %s\n\n", label, selected)
+}
+
type selectItem struct {
index int
title string
@@ -63,10 +80,10 @@ type selectModel struct {
canceled bool
}
-func newSelectModel(label string, items []list.Item) selectModel {
+func newSelectModel(items []list.Item) selectModel {
delegate := list.NewDefaultDelegate()
model := selectModel{list: list.New(items, delegate, 0, 0), choice: -1}
- model.list.Title = fmt.Sprintf("Select %s", label)
+ model.list.Title = ""
model.list.SetShowStatusBar(false)
model.list.SetFilteringEnabled(true)
model.list.SetShowHelp(true)
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index 0f1bd734c..cfda65f7e 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -17,6 +17,7 @@ type ArcaneApiEndpoints struct {
// OIDC
OIDCDeviceCodeEndpoint string
OIDCDeviceTokenEndpoint string
+ OIDCStatusEndpoint string
// API Keys
ApiKeysEndpoint string
@@ -27,9 +28,10 @@ type ArcaneApiEndpoints struct {
UserEndpoint string
// Environments
- EnvironmentsEndpoint string
- EnvironmentEndpoint string
- EnvironmentTestEndpoint string
+ EnvironmentsEndpoint string
+ EnvironmentEndpoint string
+ EnvironmentTestEndpoint string
+ EnvironmentVersionEndpoint string
// Containers
ContainersEndpoint string
@@ -78,12 +80,17 @@ type ArcaneApiEndpoints struct {
ProjectRestartEndpoint string
ProjectRedeployEndpoint string
ProjectPullEndpoint string
+ ProjectIncludesEndpoint string
// System
SystemPruneEndpoint string
SystemDockerInfoEndpoint string
SystemContainersStartAllEndpoint string
SystemContainersStopAllEndpoint string
+ SystemStartStoppedEndpoint string
+ SystemConvertEndpoint string
+ SystemUpgradeEndpoint string
+ SystemUpgradeCheckEndpoint string
// Updater
UpdaterStatusEndpoint string
@@ -94,11 +101,15 @@ type ArcaneApiEndpoints struct {
JobSchedulesEndpoint string
// Settings
- SettingsEndpoint string
+ SettingsEndpoint string
+ SettingsPublicEndpoint string
// Notifications
- NotificationsAppriseEndpoint string
- NotificationsSettingsEndpoint string
+ NotificationsAppriseEndpoint string
+ NotificationsAppriseTestEndpoint string
+ NotificationsSettingsEndpoint string
+ NotificationSettingsProviderEndpoint string
+ NotificationsTestProviderEndpoint string
// Container Registries
ContainerRegistriesEndpoint string
@@ -120,6 +131,8 @@ type ArcaneApiEndpoints struct {
TemplateRegistryEndpoint string
TemplatesVariablesEndpoint string
TemplateContentEndpoint string
+ TemplateDownloadEndpoint string
+ TemplateFetchEndpoint string
// Dashboard
DashboardActionItemsEndpoint string
@@ -135,6 +148,22 @@ type ArcaneApiEndpoints struct {
// Customization
CustomizeCategoriesEndpoint string
CustomizeSearchEndpoint string
+
+ // GitOps Syncs
+ GitOpsSyncsEndpoint string
+ GitOpsSyncEndpoint string
+ GitOpsSyncStatusEndpoint string
+ GitOpsSyncTriggerEndpoint string
+ GitOpsSyncFilesEndpoint string
+ GitOpsSyncsImportEndpoint string
+
+ // Git Repositories
+ GitRepositoriesEndpoint string
+ GitRepositoryEndpoint string
+ GitRepositoryTestEndpoint string
+ GitRepositoryBranchesEndpoint string
+ GitRepositoryFilesEndpoint string
+ GitRepositoriesSyncEndpoint string
}
// Endpoints contains the defined API endpoints
@@ -151,6 +180,7 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
// OIDC
OIDCDeviceCodeEndpoint: "/api/oidc/device/code",
OIDCDeviceTokenEndpoint: "/api/oidc/device/token",
+ OIDCStatusEndpoint: "/api/oidc/status",
// API Keys
ApiKeysEndpoint: "/api/api-keys",
@@ -161,9 +191,10 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
UserEndpoint: "/api/users/%s",
// Environments
- EnvironmentsEndpoint: "/api/environments",
- EnvironmentEndpoint: "/api/environments/%s",
- EnvironmentTestEndpoint: "/api/environments/%s/test",
+ EnvironmentsEndpoint: "/api/environments",
+ EnvironmentEndpoint: "/api/environments/%s",
+ EnvironmentTestEndpoint: "/api/environments/%s/test",
+ EnvironmentVersionEndpoint: "/api/environments/%s/version",
// Containers
ContainersEndpoint: "/api/environments/%s/containers",
@@ -212,12 +243,17 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
ProjectRestartEndpoint: "/api/environments/%s/projects/%s/restart",
ProjectRedeployEndpoint: "/api/environments/%s/projects/%s/redeploy",
ProjectPullEndpoint: "/api/environments/%s/projects/%s/pull",
+ ProjectIncludesEndpoint: "/api/environments/%s/projects/%s/includes",
// System
SystemPruneEndpoint: "/api/environments/%s/system/prune",
SystemDockerInfoEndpoint: "/api/environments/%s/system/docker/info",
SystemContainersStartAllEndpoint: "/api/environments/%s/system/containers/start-all",
SystemContainersStopAllEndpoint: "/api/environments/%s/system/containers/stop-all",
+ SystemStartStoppedEndpoint: "/api/environments/%s/system/containers/start-stopped",
+ SystemConvertEndpoint: "/api/environments/%s/system/convert",
+ SystemUpgradeEndpoint: "/api/environments/%s/system/upgrade",
+ SystemUpgradeCheckEndpoint: "/api/environments/%s/system/upgrade/check",
// Updater
UpdaterStatusEndpoint: "/api/environments/%s/updater/status",
@@ -225,14 +261,18 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
UpdaterHistoryEndpoint: "/api/environments/%s/updater/history",
// Job Schedules
- JobSchedulesEndpoint: "/api/job-schedules",
+ JobSchedulesEndpoint: "/api/environments/%s/job-schedules",
// Settings
- SettingsEndpoint: "/api/environments/%s/settings",
+ SettingsEndpoint: "/api/environments/%s/settings",
+ SettingsPublicEndpoint: "/api/environments/%s/settings/public",
// Notifications
- NotificationsAppriseEndpoint: "/api/environments/%s/notifications/apprise",
- NotificationsSettingsEndpoint: "/api/environments/%s/notifications/settings",
+ NotificationsAppriseEndpoint: "/api/environments/%s/notifications/apprise",
+ NotificationsAppriseTestEndpoint: "/api/environments/%s/notifications/apprise/test",
+ NotificationsSettingsEndpoint: "/api/environments/%s/notifications/settings",
+ NotificationSettingsProviderEndpoint: "/api/environments/%s/notifications/settings/%s",
+ NotificationsTestProviderEndpoint: "/api/environments/%s/notifications/test/%s",
// Container Registries
ContainerRegistriesEndpoint: "/api/container-registries",
@@ -254,6 +294,8 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
TemplateRegistryEndpoint: "/api/templates/registries/%s",
TemplatesVariablesEndpoint: "/api/templates/variables",
TemplateContentEndpoint: "/api/templates/%s/content",
+ TemplateDownloadEndpoint: "/api/templates/%s/download",
+ TemplateFetchEndpoint: "/api/templates/fetch",
// Dashboard
DashboardActionItemsEndpoint: "/api/environments/%s/dashboard/action-items",
@@ -269,6 +311,22 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
// Customization
CustomizeCategoriesEndpoint: "/api/customize/categories",
CustomizeSearchEndpoint: "/api/customize/search",
+
+ // GitOps Syncs
+ GitOpsSyncsEndpoint: "/api/environments/%s/gitops-syncs",
+ GitOpsSyncEndpoint: "/api/environments/%s/gitops-syncs/%s",
+ GitOpsSyncStatusEndpoint: "/api/environments/%s/gitops-syncs/%s/status",
+ GitOpsSyncTriggerEndpoint: "/api/environments/%s/gitops-syncs/%s/sync",
+ GitOpsSyncFilesEndpoint: "/api/environments/%s/gitops-syncs/%s/files",
+ GitOpsSyncsImportEndpoint: "/api/environments/%s/gitops-syncs/import",
+
+ // Git Repositories
+ GitRepositoriesEndpoint: "/api/customize/git-repositories",
+ GitRepositoryEndpoint: "/api/customize/git-repositories/%s",
+ GitRepositoryTestEndpoint: "/api/customize/git-repositories/%s/test",
+ GitRepositoryBranchesEndpoint: "/api/customize/git-repositories/%s/branches",
+ GitRepositoryFilesEndpoint: "/api/customize/git-repositories/%s/files",
+ GitRepositoriesSyncEndpoint: "/api/git-repositories/sync",
}
// Auth endpoints
@@ -280,6 +338,7 @@ func (e ArcaneApiEndpoints) AuthRefresh() string { return e.AuthRefreshEndpoint
// OIDC endpoints
func (e ArcaneApiEndpoints) OIDCDeviceCode() string { return e.OIDCDeviceCodeEndpoint }
func (e ArcaneApiEndpoints) OIDCDeviceToken() string { return e.OIDCDeviceTokenEndpoint }
+func (e ArcaneApiEndpoints) OIDCStatus() string { return e.OIDCStatusEndpoint }
// API Key endpoints
func (e ArcaneApiEndpoints) ApiKeys() string { return e.ApiKeysEndpoint }
@@ -300,6 +359,10 @@ func (e ArcaneApiEndpoints) EnvironmentTest(envID string) string {
return fmt.Sprintf(e.EnvironmentTestEndpoint, envID)
}
+func (e ArcaneApiEndpoints) EnvironmentVersion(envID string) string {
+ return fmt.Sprintf(e.EnvironmentVersionEndpoint, envID)
+}
+
// Container endpoints
func (e ArcaneApiEndpoints) Containers(envID string) string {
return fmt.Sprintf(e.ContainersEndpoint, envID)
@@ -448,6 +511,10 @@ func (e ArcaneApiEndpoints) ProjectPull(envID, projectID string) string {
return fmt.Sprintf(e.ProjectPullEndpoint, envID, projectID)
}
+func (e ArcaneApiEndpoints) ProjectIncludes(envID, projectID string) string {
+ return fmt.Sprintf(e.ProjectIncludesEndpoint, envID, projectID)
+}
+
// System endpoints
func (e ArcaneApiEndpoints) SystemPrune(envID string) string {
return fmt.Sprintf(e.SystemPruneEndpoint, envID)
@@ -465,6 +532,22 @@ func (e ArcaneApiEndpoints) SystemContainersStopAll(envID string) string {
return fmt.Sprintf(e.SystemContainersStopAllEndpoint, envID)
}
+func (e ArcaneApiEndpoints) SystemStartStopped(envID string) string {
+ return fmt.Sprintf(e.SystemStartStoppedEndpoint, envID)
+}
+
+func (e ArcaneApiEndpoints) SystemConvert(envID string) string {
+ return fmt.Sprintf(e.SystemConvertEndpoint, envID)
+}
+
+func (e ArcaneApiEndpoints) SystemUpgrade(envID string) string {
+ return fmt.Sprintf(e.SystemUpgradeEndpoint, envID)
+}
+
+func (e ArcaneApiEndpoints) SystemUpgradeCheck(envID string) string {
+ return fmt.Sprintf(e.SystemUpgradeCheckEndpoint, envID)
+}
+
// Updater endpoints
func (e ArcaneApiEndpoints) UpdaterStatus(envID string) string {
return fmt.Sprintf(e.UpdaterStatusEndpoint, envID)
@@ -479,22 +562,40 @@ func (e ArcaneApiEndpoints) UpdaterHistory(envID string) string {
}
// Job schedule endpoints
-func (e ArcaneApiEndpoints) JobSchedules() string { return e.JobSchedulesEndpoint }
+func (e ArcaneApiEndpoints) JobSchedules(envID string) string {
+ return fmt.Sprintf(e.JobSchedulesEndpoint, envID)
+}
// Settings endpoints
func (e ArcaneApiEndpoints) Settings(envID string) string {
return fmt.Sprintf(e.SettingsEndpoint, envID)
}
+func (e ArcaneApiEndpoints) SettingsPublic(envID string) string {
+ return fmt.Sprintf(e.SettingsPublicEndpoint, envID)
+}
+
// Notification endpoints
func (e ArcaneApiEndpoints) NotificationsApprise(envID string) string {
return fmt.Sprintf(e.NotificationsAppriseEndpoint, envID)
}
+func (e ArcaneApiEndpoints) NotificationsAppriseTest(envID string) string {
+ return fmt.Sprintf(e.NotificationsAppriseTestEndpoint, envID)
+}
+
func (e ArcaneApiEndpoints) NotificationsSettings(envID string) string {
return fmt.Sprintf(e.NotificationsSettingsEndpoint, envID)
}
+func (e ArcaneApiEndpoints) NotificationSettingsProvider(envID, provider string) string {
+ return fmt.Sprintf(e.NotificationSettingsProviderEndpoint, envID, provider)
+}
+
+func (e ArcaneApiEndpoints) NotificationsTestProvider(envID, provider string) string {
+ return fmt.Sprintf(e.NotificationsTestProviderEndpoint, envID, provider)
+}
+
// Container Registry endpoints
func (e ArcaneApiEndpoints) ContainerRegistries() string { return e.ContainerRegistriesEndpoint }
@@ -526,8 +627,48 @@ func (e ArcaneApiEndpoints) TemplatesVariables() string { return e.TemplatesVari
func (e ArcaneApiEndpoints) TemplateContent(id string) string {
return fmt.Sprintf(e.TemplateContentEndpoint, id)
}
+func (e ArcaneApiEndpoints) TemplateDownload(id string) string {
+ return fmt.Sprintf(e.TemplateDownloadEndpoint, id)
+}
+func (e ArcaneApiEndpoints) TemplateFetch() string { return e.TemplateFetchEndpoint }
// Dashboard endpoints
func (e ArcaneApiEndpoints) DashboardActionItems(envID string) string {
return fmt.Sprintf(e.DashboardActionItemsEndpoint, envID)
}
+
+// GitOps Sync endpoints
+func (e ArcaneApiEndpoints) GitOpsSyncs(envID string) string {
+ return fmt.Sprintf(e.GitOpsSyncsEndpoint, envID)
+}
+func (e ArcaneApiEndpoints) GitOpsSync(envID, syncID string) string {
+ return fmt.Sprintf(e.GitOpsSyncEndpoint, envID, syncID)
+}
+func (e ArcaneApiEndpoints) GitOpsSyncStatus(envID, syncID string) string {
+ return fmt.Sprintf(e.GitOpsSyncStatusEndpoint, envID, syncID)
+}
+func (e ArcaneApiEndpoints) GitOpsSyncTrigger(envID, syncID string) string {
+ return fmt.Sprintf(e.GitOpsSyncTriggerEndpoint, envID, syncID)
+}
+func (e ArcaneApiEndpoints) GitOpsSyncFiles(envID, syncID string) string {
+ return fmt.Sprintf(e.GitOpsSyncFilesEndpoint, envID, syncID)
+}
+func (e ArcaneApiEndpoints) GitOpsSyncsImport(envID string) string {
+ return fmt.Sprintf(e.GitOpsSyncsImportEndpoint, envID)
+}
+
+// Git Repository endpoints
+func (e ArcaneApiEndpoints) GitRepositories() string { return e.GitRepositoriesEndpoint }
+func (e ArcaneApiEndpoints) GitRepository(id string) string {
+ return fmt.Sprintf(e.GitRepositoryEndpoint, id)
+}
+func (e ArcaneApiEndpoints) GitRepositoryTest(id string) string {
+ return fmt.Sprintf(e.GitRepositoryTestEndpoint, id)
+}
+func (e ArcaneApiEndpoints) GitRepositoryBranches(id string) string {
+ return fmt.Sprintf(e.GitRepositoryBranchesEndpoint, id)
+}
+func (e ArcaneApiEndpoints) GitRepositoryFiles(id string) string {
+ return fmt.Sprintf(e.GitRepositoryFilesEndpoint, id)
+}
+func (e ArcaneApiEndpoints) GitRepositoriesSync() string { return e.GitRepositoriesSyncEndpoint }
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index 7e976ba8d..936e0ca63 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -3,6 +3,7 @@ package apikeys
import (
"encoding/json"
"fmt"
+ "time"
"github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/cmdutil"
@@ -19,6 +20,12 @@ var (
jsonOutput bool
)
+var (
+ apikeyUpdateName string
+ apikeyUpdateDescription string
+ apikeyUpdateExpiresAt string
+)
+
// ApiKeysCmd is the parent command for API key operations
var ApiKeysCmd = &cobra.Command{
Use: "api-keys",
@@ -254,10 +261,61 @@ var getCmd = &cobra.Command{
},
}
+var updateCmd = &cobra.Command{
+ Use: "update <id>",
+ Short: "Update API key",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ var req apikey.UpdateApiKey
+ if cmd.Flags().Changed("name") {
+ req.Name = &apikeyUpdateName
+ }
+ if cmd.Flags().Changed("description") {
+ req.Description = &apikeyUpdateDescription
+ }
+ if cmd.Flags().Changed("expires-at") && apikeyUpdateExpiresAt != "" {
+ parsedTime, err := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)
+ if err != nil {
+ return fmt.Errorf("invalid expires-at format (use RFC3339): %w", err)
+ }
+ req.ExpiresAt = &parsedTime
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.ApiKey(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update API key: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update API key: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("API key updated successfully")
+ return nil
+ },
+}
+
func init() {
ApiKeysCmd.AddCommand(listCmd)
ApiKeysCmd.AddCommand(createCmd)
ApiKeysCmd.AddCommand(getCmd)
+ ApiKeysCmd.AddCommand(updateCmd)
ApiKeysCmd.AddCommand(deleteCmd)
// List command flags
@@ -272,6 +330,12 @@ func init() {
// Get command flags
getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ // Update command flags
+ updateCmd.Flags().StringVar(&apikeyUpdateName, "name", "", "API key name")
+ updateCmd.Flags().StringVarP(&apikeyUpdateDescription, "description", "d", "", "API key description")
+ updateCmd.Flags().StringVar(&apikeyUpdateExpiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
+ updateCmd.Flags().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")
diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.go
index eb5ae98e0..affcd6466 100644
--- a/cli/pkg/admin/notifications/cmd.go
+++ b/cli/pkg/admin/notifications/cmd.go
@@ -5,6 +5,7 @@ import (
"fmt"
"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"
@@ -12,7 +13,10 @@ import (
"github.com/spf13/cobra"
)
-var jsonOutput bool
+var (
+ jsonOutput bool
+ notifForceFlag bool
+)
// NotificationsCmd is the parent command for notification operations
var NotificationsCmd = &cobra.Command{
@@ -21,8 +25,18 @@ var NotificationsCmd = &cobra.Command{
Short: "Manage notifications",
}
+var appriseCmd = &cobra.Command{
+ Use: "apprise",
+ Short: "Manage Apprise configuration",
+}
+
+var settingsCmd = &cobra.Command{
+ Use: "settings",
+ Short: "Manage notification settings",
+}
+
var appriseGetCmd = &cobra.Command{
- Use: "apprise-get",
+ Use: "get",
Short: "Get Apprise configuration",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -62,7 +76,7 @@ var appriseGetCmd = &cobra.Command{
}
var settingsGetCmd = &cobra.Command{
- Use: "settings-get",
+ Use: "get",
Short: "Get notification settings",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -107,10 +121,126 @@ var settingsGetCmd = &cobra.Command{
},
}
+var appriseTestCmd = &cobra.Command{
+ Use: "test",
+ Short: "Test Apprise notification",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.NotificationsAppriseTest(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to test apprise: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("apprise test failed: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Apprise notification test successful")
+ return nil
+ },
+}
+
+var settingsDeleteCmd = &cobra.Command{
+ Use: "delete <provider>",
+ Short: "Delete notification provider settings",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !notifForceFlag {
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete notification settings for %s?", args[0]))
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.NotificationSettingsProvider(c.EnvID(), args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to delete notification settings: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete notification settings: %w", err)
+ }
+
+ output.Success("Notification settings for %s deleted successfully", args[0])
+ return nil
+ },
+}
+
+var testProviderCmd = &cobra.Command{
+ Use: "test <provider>",
+ Short: "Test a notification provider",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.NotificationsTestProvider(c.EnvID(), args[0]), nil)
+ if err != nil {
+ return fmt.Errorf("failed to test notification provider: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("notification test failed: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Notification test for %s successful", args[0])
+ return nil
+ },
+}
+
func init() {
- NotificationsCmd.AddCommand(appriseGetCmd)
- NotificationsCmd.AddCommand(settingsGetCmd)
+ NotificationsCmd.AddCommand(appriseCmd)
+ NotificationsCmd.AddCommand(settingsCmd)
+ NotificationsCmd.AddCommand(testProviderCmd)
+
+ appriseCmd.AddCommand(appriseGetCmd)
+ appriseCmd.AddCommand(appriseTestCmd)
+
+ settingsCmd.AddCommand(settingsGetCmd)
+ settingsCmd.AddCommand(settingsDeleteCmd)
appriseGetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ appriseTestCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
settingsGetCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ settingsDeleteCmd.Flags().BoolVarP(&notifForceFlag, "force", "f", false, "Force deletion without confirmation")
+ settingsDeleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ testProviderCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index cf685c7af..a6523fd01 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -3,8 +3,10 @@ package users
import (
"encoding/json"
"fmt"
+ "os"
"strings"
+ "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/output"
@@ -20,6 +22,21 @@ var (
jsonOutput bool
)
+var (
+ userCreateUsername string
+ userCreatePassword string
+ userCreateDisplayName string
+ userCreateEmail string
+ userCreateRoles []string
+)
+
+var (
+ userUpdateUsername string
+ userUpdateDisplayName string
+ userUpdateEmail string
+ userUpdateRoles []string
+)
+
// UsersCmd is the parent command for user operations
var UsersCmd = &cobra.Command{
Use: "users",
@@ -91,6 +108,166 @@ var listCmd = &cobra.Command{
},
}
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new user",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ if userCreatePassword == "" {
+ fmt.Print("Password: ")
+ bytePassword, err := term.ReadPassword(os.Stdin.Fd())
+ if err != nil {
+ return fmt.Errorf("failed to read password: %w", err)
+ }
+ userCreatePassword = string(bytePassword)
+ fmt.Println()
+ }
+
+ req := user.CreateUser{
+ Username: userCreateUsername,
+ Password: userCreatePassword,
+ }
+ if cmd.Flags().Changed("display-name") {
+ req.DisplayName = &userCreateDisplayName
+ }
+ if cmd.Flags().Changed("email") {
+ req.Email = &userCreateEmail
+ }
+ if cmd.Flags().Changed("role") {
+ req.Roles = userCreateRoles
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.Users(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create user: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create user: %w", err)
+ }
+
+ var result base.ApiResponse[user.User]
+ 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
+ }
+
+ output.Success("User %s created successfully", result.Data.Username)
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Username", result.Data.Username)
+ output.KeyValue("Roles", strings.Join(result.Data.Roles, ", "))
+ return nil
+ },
+}
+
+var getCmd = &cobra.Command{
+ Use: "get <user-id>",
+ Short: "Get user details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.User(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to get user: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[user.User]
+ 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
+ }
+
+ output.Header("User Details")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Username", result.Data.Username)
+ if result.Data.DisplayName != nil {
+ output.KeyValue("Display Name", *result.Data.DisplayName)
+ }
+ if result.Data.Email != nil {
+ output.KeyValue("Email", *result.Data.Email)
+ }
+ output.KeyValue("Roles", strings.Join(result.Data.Roles, ", "))
+ output.KeyValue("Created", result.Data.CreatedAt)
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <user-id>",
+ Short: "Update user",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ var req user.UpdateUser
+ if cmd.Flags().Changed("username") {
+ req.Username = &userUpdateUsername
+ }
+ if cmd.Flags().Changed("display-name") {
+ req.DisplayName = &userUpdateDisplayName
+ }
+ if cmd.Flags().Changed("email") {
+ req.Email = &userUpdateEmail
+ }
+ if cmd.Flags().Changed("role") {
+ req.Roles = userUpdateRoles
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.User(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update user: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update user: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("User updated successfully")
+ return nil
+ },
+}
+
var deleteCmd = &cobra.Command{
Use: "delete <user-id>",
Aliases: []string{"rm", "remove"},
@@ -130,11 +307,30 @@ var deleteCmd = &cobra.Command{
func init() {
UsersCmd.AddCommand(listCmd)
+ UsersCmd.AddCommand(createCmd)
+ UsersCmd.AddCommand(getCmd)
+ UsersCmd.AddCommand(updateCmd)
UsersCmd.AddCommand(deleteCmd)
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of users to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ createCmd.Flags().StringVar(&userCreateUsername, "username", "", "Username")
+ createCmd.Flags().StringVar(&userCreatePassword, "password", "", "Password (if omitted, will prompt securely)")
+ createCmd.Flags().StringVar(&userCreateDisplayName, "display-name", "", "Display name")
+ createCmd.Flags().StringVar(&userCreateEmail, "email", "", "Email address")
+ createCmd.Flags().StringArrayVar(&userCreateRoles, "role", nil, "User role")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("username")
+
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ updateCmd.Flags().StringVar(&userUpdateUsername, "username", "", "New username")
+ updateCmd.Flags().StringVar(&userUpdateDisplayName, "display-name", "", "Display name")
+ updateCmd.Flags().StringVar(&userUpdateEmail, "email", "", "Email address")
+ updateCmd.Flags().StringArrayVar(&userUpdateRoles, "role", nil, "User role")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index 6eac3ae30..7c56a1f63 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -393,12 +393,58 @@ var refreshCmd = &cobra.Command{
},
}
+var oidcStatusCmd = &cobra.Command{
+ Use: "oidc-status",
+ Short: "Show OIDC configuration status",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.OIDCStatus())
+ if err != nil {
+ return fmt.Errorf("failed to get OIDC status: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to get OIDC status: %w", err)
+ }
+
+ var result struct {
+ EnvForced bool `json:"envForced"`
+ EnvConfigured bool `json:"envConfigured"`
+ MergeAccounts bool `json:"mergeAccounts"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
+ resultBytes, err := json.MarshalIndent(result, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("OIDC Status")
+ output.KeyValue("Environment Forced", fmt.Sprintf("%t", result.EnvForced))
+ output.KeyValue("Environment Configured", fmt.Sprintf("%t", result.EnvConfigured))
+ output.KeyValue("Merge Accounts", fmt.Sprintf("%t", result.MergeAccounts))
+ return nil
+ },
+}
+
func init() {
AuthCmd.AddCommand(loginCmd)
AuthCmd.AddCommand(logoutCmd)
AuthCmd.AddCommand(meCmd)
AuthCmd.AddCommand(passwordCmd)
AuthCmd.AddCommand(refreshCmd)
+ AuthCmd.AddCommand(oidcStatusCmd)
// Login command flags
loginCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -415,6 +461,7 @@ func init() {
// Global JSON output flags
logoutCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
meCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ oidcStatusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
func extractDeviceAuthErrorCode(body string) string {
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index f0355b636..066ccc708 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/url"
+ "os"
"strings"
"time"
@@ -25,6 +26,24 @@ var (
containersAll bool
forceFlag bool
jsonOutput bool
+
+ containerCreateFile string
+ containerCreateName string
+ containerCreateImage string
+ containerCreateEnv []string
+ containerCreatePort []string
+ containerCreateVolume []string
+ containerCreateLabel []string
+ containerCreateNetwork []string
+ containerCreateRestart string
+ containerCreateMemory int64
+ containerCreateCPUs float64
+ containerCreatePrivileged bool
+ containerCreateHostname string
+ containerCreateUser string
+ containerCreateWorkdir string
+ containerCreateEntrypoint string
+ containerCreateCmd string
)
const maxPromptOptions = 20
@@ -354,18 +373,26 @@ var containersDeleteCmd = &cobra.Command{
}
}
- path := types.Endpoints.Container(c.EnvID(), resolved.ID)
+ path := types.Endpoints.Container(c.EnvID(), resolved.ID) + "?force=true"
resp, err := c.Delete(cmd.Context(), path)
if err != nil {
return fmt.Errorf("failed to delete container: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- var result base.ApiResponse[container.ActionResult]
+ var result base.ApiResponse[base.MessageResponse]
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
+ if !result.Success {
+ msg := result.Data.Message
+ if msg == "" {
+ msg = "unknown error"
+ }
+ return fmt.Errorf("failed to delete container: %s", msg)
+ }
+
if jsonOutput {
resultBytes, err := json.MarshalIndent(result.Data, "", " ")
if err != nil {
@@ -419,6 +446,135 @@ var containersCountsCmd = &cobra.Command{
},
}
+var containersCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new container",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ c.SetTimeout(30 * time.Minute)
+
+ var req container.Create
+
+ // File mode: read base config from file
+ if containerCreateFile != "" {
+ data, err := os.ReadFile(containerCreateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", containerCreateFile, err)
+ }
+ if err := json.Unmarshal(data, &req); err != nil {
+ return fmt.Errorf("failed to parse config file: %w", err)
+ }
+ }
+
+ // Flag overrides
+ if cmd.Flags().Changed("name") {
+ req.Name = containerCreateName
+ }
+ if cmd.Flags().Changed("image") {
+ req.Image = containerCreateImage
+ }
+ if cmd.Flags().Changed("env") {
+ req.Env = containerCreateEnv
+ }
+ if cmd.Flags().Changed("port") {
+ // Parse "HOST:CONTAINER" format into ports map
+ req.Ports = make(map[string]string)
+ for _, p := range containerCreatePort {
+ parts := strings.SplitN(p, ":", 2)
+ if len(parts) == 2 {
+ req.Ports[parts[1]] = parts[0]
+ }
+ }
+ }
+ if cmd.Flags().Changed("volume") {
+ req.Volumes = containerCreateVolume
+ }
+ if cmd.Flags().Changed("label") {
+ req.Labels = make(map[string]string)
+ for _, l := range containerCreateLabel {
+ parts := strings.SplitN(l, "=", 2)
+ if len(parts) == 2 {
+ req.Labels[parts[0]] = parts[1]
+ }
+ }
+ }
+ if cmd.Flags().Changed("network") {
+ req.Networks = containerCreateNetwork
+ }
+ if cmd.Flags().Changed("restart") {
+ req.RestartPolicy = containerCreateRestart
+ }
+ if cmd.Flags().Changed("memory") {
+ req.Memory = containerCreateMemory
+ }
+ if cmd.Flags().Changed("cpus") {
+ req.CPUs = containerCreateCPUs
+ }
+ if cmd.Flags().Changed("privileged") {
+ req.Privileged = containerCreatePrivileged
+ }
+ if cmd.Flags().Changed("hostname") {
+ req.Hostname = containerCreateHostname
+ }
+ if cmd.Flags().Changed("user") {
+ req.User = containerCreateUser
+ }
+ if cmd.Flags().Changed("workdir") {
+ req.WorkingDir = containerCreateWorkdir
+ }
+ if cmd.Flags().Changed("entrypoint") {
+ req.Entrypoint = []string{containerCreateEntrypoint}
+ }
+ if cmd.Flags().Changed("cmd") {
+ req.Cmd = []string{containerCreateCmd}
+ }
+
+ // Validate required fields
+ if req.Name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if req.Image == "" {
+ return fmt.Errorf("--image is required")
+ }
+
+ path := types.Endpoints.Containers(c.EnvID())
+ resp, err := c.Post(cmd.Context(), path, req)
+ if err != nil {
+ return fmt.Errorf("failed to create container: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create container: %w", err)
+ }
+
+ var result base.ApiResponse[container.Created]
+ 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
+ }
+
+ output.Success("Container %s created successfully", result.Data.Name)
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("Image", result.Data.Image)
+ output.KeyValue("Status", result.Data.Status)
+ return nil
+ },
+}
+
func init() {
ContainersCmd.AddCommand(containersListCmd)
ContainersCmd.AddCommand(containersGetCmd)
@@ -428,6 +584,27 @@ func init() {
ContainersCmd.AddCommand(containersUpdateCmd)
ContainersCmd.AddCommand(containersDeleteCmd)
ContainersCmd.AddCommand(containersCountsCmd)
+ ContainersCmd.AddCommand(containersCreateCmd)
+
+ // Create command flags
+ containersCreateCmd.Flags().StringVarP(&containerCreateFile, "file", "f", "", "JSON config file for container creation")
+ containersCreateCmd.Flags().StringVar(&containerCreateName, "name", "", "Container name")
+ containersCreateCmd.Flags().StringVar(&containerCreateImage, "image", "", "Docker image")
+ containersCreateCmd.Flags().StringArrayVarP(&containerCreateEnv, "env", "e", nil, "Environment variable (KEY=VALUE)")
+ containersCreateCmd.Flags().StringArrayVarP(&containerCreatePort, "port", "p", nil, "Port mapping (HOST:CONTAINER)")
+ containersCreateCmd.Flags().StringArrayVarP(&containerCreateVolume, "volume", "v", nil, "Volume mount (SRC:DST)")
+ containersCreateCmd.Flags().StringArrayVarP(&containerCreateLabel, "label", "l", nil, "Label (KEY=VALUE)")
+ containersCreateCmd.Flags().StringArrayVar(&containerCreateNetwork, "network", nil, "Networks to connect to")
+ containersCreateCmd.Flags().StringVar(&containerCreateRestart, "restart", "", "Restart policy (no, always, unless-stopped, on-failure)")
+ containersCreateCmd.Flags().Int64Var(&containerCreateMemory, "memory", 0, "Memory limit in bytes")
+ containersCreateCmd.Flags().Float64Var(&containerCreateCPUs, "cpus", 0, "Number of CPUs")
+ containersCreateCmd.Flags().BoolVar(&containerCreatePrivileged, "privileged", false, "Run in privileged mode")
+ containersCreateCmd.Flags().StringVar(&containerCreateHostname, "hostname", "", "Container hostname")
+ containersCreateCmd.Flags().StringVar(&containerCreateUser, "user", "", "User to run as")
+ containersCreateCmd.Flags().StringVar(&containerCreateWorkdir, "workdir", "", "Working directory")
+ containersCreateCmd.Flags().StringVar(&containerCreateEntrypoint, "entrypoint", "", "Entrypoint command")
+ containersCreateCmd.Flags().StringVar(&containerCreateCmd, "cmd", "", "Command to run")
+ containersCreateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
// List command flags
containersListCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.go
index ec306bdd8..6c0ffadd7 100644
--- a/cli/pkg/environments/cmd.go
+++ b/cli/pkg/environments/cmd.go
@@ -24,6 +24,13 @@ var (
jsonOutput bool
)
+var (
+ envUpdateName string
+ envUpdateApiUrl string
+ envUpdateEnabled bool
+ envUpdateDisabled bool
+)
+
var (
statusOnlineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#22c55e"))
statusOfflineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ef4444"))
@@ -323,12 +330,131 @@ var switchCmd = &cobra.Command{
},
}
+var updateCmd = &cobra.Command{
+ Use: "update <id>",
+ Short: "Update environment",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ var req environment.Update
+ if cmd.Flags().Changed("enabled") && cmd.Flags().Changed("disabled") {
+ return fmt.Errorf("--enabled and --disabled are mutually exclusive")
+ }
+ if cmd.Flags().Changed("name") {
+ req.Name = &envUpdateName
+ }
+ if cmd.Flags().Changed("api-url") {
+ req.ApiUrl = &envUpdateApiUrl
+ }
+ if cmd.Flags().Changed("enabled") {
+ enabled := true
+ req.Enabled = &enabled
+ }
+ if cmd.Flags().Changed("disabled") {
+ enabled := false
+ req.Enabled = &enabled
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.Environment(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update environment: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update environment: %w", err)
+ }
+
+ var result base.ApiResponse[environment.Environment]
+ 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
+ }
+
+ output.Success("Environment updated successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("API URL", result.Data.ApiUrl)
+ output.KeyValue("Enabled", result.Data.Enabled)
+ return nil
+ },
+}
+
+var versionCmd = &cobra.Command{
+ Use: "version <id>",
+ Short: "Get environment version",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.EnvironmentVersion(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to get environment version: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to get environment version: %w", err)
+ }
+
+ var result struct {
+ CurrentVersion string `json:"currentVersion"`
+ CurrentTag string `json:"currentTag"`
+ Revision string `json:"revision"`
+ ShortRevision string `json:"shortRevision"`
+ GoVersion string `json:"goVersion"`
+ BuildTime string `json:"buildTime"`
+ DisplayVersion string `json:"displayVersion"`
+ UpdateAvailable bool `json:"updateAvailable"`
+ }
+ 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, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("Environment Version")
+ output.KeyValue("Version", result.DisplayVersion)
+ output.KeyValue("Full Version", result.CurrentVersion)
+ output.KeyValue("Tag", result.CurrentTag)
+ output.KeyValue("Revision", result.ShortRevision)
+ output.KeyValue("Go Version", result.GoVersion)
+ output.KeyValue("Build Time", result.BuildTime)
+ output.KeyValue("Update Available", fmt.Sprintf("%t", result.UpdateAvailable))
+ return nil
+ },
+}
+
func init() {
EnvironmentsCmd.AddCommand(listCmd)
EnvironmentsCmd.AddCommand(getCmd)
EnvironmentsCmd.AddCommand(testCmd)
EnvironmentsCmd.AddCommand(deleteCmd)
EnvironmentsCmd.AddCommand(switchCmd)
+ EnvironmentsCmd.AddCommand(updateCmd)
+ EnvironmentsCmd.AddCommand(versionCmd)
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of environments to show")
@@ -343,4 +469,14 @@ func init() {
// Delete command flags
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Update command flags
+ updateCmd.Flags().StringVar(&envUpdateName, "name", "", "Environment name")
+ updateCmd.Flags().StringVar(&envUpdateApiUrl, "api-url", "", "API URL")
+ updateCmd.Flags().BoolVar(&envUpdateEnabled, "enabled", false, "Enable environment")
+ updateCmd.Flags().BoolVar(&envUpdateDisabled, "disabled", false, "Disable environment")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Version command flags
+ versionCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.go
new file mode 100644
index 000000000..75360d9e5
--- /dev/null
+++ b/cli/pkg/gitops/cmd.go
@@ -0,0 +1,758 @@
+package gitops
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "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"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/gitops"
+ "github.com/spf13/cobra"
+)
+
+var (
+ limitFlag int
+ forceFlag bool
+ jsonOutput bool
+)
+
+var (
+ gitopsUpdateName string
+ gitopsUpdateRepoID string
+ gitopsUpdateBranch string
+ gitopsUpdateComposePath string
+ gitopsUpdateProjectName string
+ gitopsUpdateAutoSync bool
+ gitopsUpdateInterval int
+)
+
+const maxPromptOptions = 20
+
+// GitopsCmd is the parent command for gitops sync operations
+var GitopsCmd = &cobra.Command{
+ Use: "gitops",
+ Aliases: []string{"gitops-syncs", "gs"},
+ Short: "Manage GitOps syncs",
+}
+
+var listCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List GitOps syncs",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.GitOpsSyncs(c.EnvID())
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "gitops-syncs", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
+ }
+
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list gitops syncs: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.Paginated[gitops.GitOpsSync]
+ 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, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ headers := []string{"ID", "NAME", "BRANCH", "AUTO-SYNC", "LAST STATUS", "LAST SYNC"}
+ rows := make([][]string, len(result.Data))
+ for i, sync := range result.Data {
+ autoSync := "false"
+ if sync.AutoSync {
+ autoSync = "true"
+ }
+ lastStatus := "-"
+ if sync.LastSyncStatus != nil {
+ lastStatus = *sync.LastSyncStatus
+ }
+ lastSync := "-"
+ if sync.LastSyncAt != nil {
+ lastSync = sync.LastSyncAt.Format("2006-01-02 15:04:05")
+ }
+ rows[i] = []string{
+ sync.ID,
+ sync.Name,
+ sync.Branch,
+ autoSync,
+ lastStatus,
+ lastSync,
+ }
+ }
+
+ output.Table(headers, rows)
+ fmt.Printf("\nTotal: %d gitops syncs\n", result.Pagination.TotalItems)
+ return nil
+ },
+}
+
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new GitOps sync",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ name, _ := cmd.Flags().GetString("name")
+ repoID, _ := cmd.Flags().GetString("repo-id")
+ branch, _ := cmd.Flags().GetString("branch")
+ composePath, _ := cmd.Flags().GetString("compose-path")
+ autoSync, _ := cmd.Flags().GetBool("auto-sync")
+ interval, _ := cmd.Flags().GetInt("interval")
+ projectName, _ := cmd.Flags().GetString("project-name")
+
+ req := gitops.CreateSyncRequest{
+ Name: name,
+ RepositoryID: repoID,
+ Branch: branch,
+ ComposePath: composePath,
+ ProjectName: projectName,
+ AutoSync: &autoSync,
+ }
+ if cmd.Flags().Changed("interval") {
+ req.SyncInterval = &interval
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncs(c.EnvID()), req)
+ if err != nil {
+ return fmt.Errorf("failed to create gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create gitops sync: %w", err)
+ }
+
+ var result base.ApiResponse[gitops.GitOpsSync]
+ 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
+ }
+
+ output.Success("GitOps sync %s created successfully (ID: %s)", result.Data.Name, result.Data.ID)
+ return nil
+ },
+}
+
+var getCmd = &cobra.Command{
+ Use: "get <sync-id|name>",
+ Short: "Get GitOps sync details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ allowPrompt := !jsonOutput && prompt.IsInteractive()
+ resolved, complete, err := resolveGitOpsSync(cmd.Context(), c, args[0], allowPrompt)
+ if err != nil {
+ return err
+ }
+
+ if !complete {
+ resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to get gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.GitOpsSync]
+ 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(resolved, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("GitOps Sync Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("Branch", resolved.Branch)
+ output.KeyValue("Compose Path", resolved.ComposePath)
+ output.KeyValue("Project Name", resolved.ProjectName)
+ output.KeyValue("Auto Sync", resolved.AutoSync)
+ output.KeyValue("Sync Interval", fmt.Sprintf("%d min", resolved.SyncInterval))
+ if resolved.LastSyncStatus != nil {
+ output.KeyValue("Last Status", *resolved.LastSyncStatus)
+ }
+ if resolved.LastSyncAt != nil {
+ output.KeyValue("Last Sync", resolved.LastSyncAt.Format("2006-01-02 15:04:05"))
+ }
+ if resolved.LastSyncCommit != nil {
+ output.KeyValue("Last Commit", *resolved.LastSyncCommit)
+ }
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <sync-id|name>",
+ Short: "Update a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ req := gitops.UpdateSyncRequest{}
+ if cmd.Flags().Changed("name") {
+ req.Name = &gitopsUpdateName
+ }
+ if cmd.Flags().Changed("repo-id") {
+ req.RepositoryID = &gitopsUpdateRepoID
+ }
+ if cmd.Flags().Changed("branch") {
+ req.Branch = &gitopsUpdateBranch
+ }
+ if cmd.Flags().Changed("compose-path") {
+ req.ComposePath = &gitopsUpdateComposePath
+ }
+ if cmd.Flags().Changed("project-name") {
+ req.ProjectName = &gitopsUpdateProjectName
+ }
+ if cmd.Flags().Changed("auto-sync") {
+ req.AutoSync = &gitopsUpdateAutoSync
+ }
+ if cmd.Flags().Changed("interval") {
+ req.SyncInterval = &gitopsUpdateInterval
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID), req)
+ if err != nil {
+ return fmt.Errorf("failed to update gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update gitops sync: %w", err)
+ }
+
+ output.Success("GitOps sync %s updated successfully", resolved.Name)
+ return nil
+ },
+}
+
+var deleteCmd = &cobra.Command{
+ Use: "delete <sync-id|name>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ if !forceFlag {
+ display := resolved.Name
+ if display == "" {
+ display = resolved.ID
+ }
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete gitops sync %s?", display))
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.GitOpsSync(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to delete gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete gitops sync: %w", err)
+ }
+
+ output.Success("GitOps sync %s deleted successfully", resolved.Name)
+ return nil
+ },
+}
+
+var statusCmd = &cobra.Command{
+ Use: "status <sync-id|name>",
+ Short: "Get GitOps sync status",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSyncStatus(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to get gitops sync status: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.SyncStatus]
+ 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
+ }
+
+ output.Header("GitOps Sync Status")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Auto Sync", result.Data.AutoSync)
+ if result.Data.NextSyncAt != nil {
+ output.KeyValue("Next Sync", result.Data.NextSyncAt.Format("2006-01-02 15:04:05"))
+ }
+ if result.Data.LastSyncAt != nil {
+ output.KeyValue("Last Sync", result.Data.LastSyncAt.Format("2006-01-02 15:04:05"))
+ }
+ if result.Data.LastSyncStatus != nil {
+ output.KeyValue("Last Status", *result.Data.LastSyncStatus)
+ }
+ if result.Data.LastSyncError != nil {
+ output.KeyValue("Last Error", *result.Data.LastSyncError)
+ }
+ if result.Data.LastSyncCommit != nil {
+ output.KeyValue("Last Commit", *result.Data.LastSyncCommit)
+ }
+ return nil
+ },
+}
+
+var syncCmd = &cobra.Command{
+ Use: "sync <sync-id|name>",
+ Short: "Trigger a GitOps sync",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncTrigger(c.EnvID(), resolved.ID), nil)
+ if err != nil {
+ return fmt.Errorf("failed to trigger gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.SyncResult]
+ 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
+ }
+
+ if result.Data.Success {
+ output.Success("Sync triggered successfully: %s", result.Data.Message)
+ return nil
+ }
+
+ errMsg := ""
+ if result.Data.Error != nil {
+ errMsg = *result.Data.Error
+ }
+ return fmt.Errorf("sync failed: %s %s", result.Data.Message, errMsg)
+ },
+}
+
+var filesCmd = &cobra.Command{
+ Use: "files <sync-id|name>",
+ Short: "List files from GitOps sync repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveGitOpsSync(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.GitOpsSyncFiles(c.EnvID(), resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to get gitops sync files: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.BrowseResponse]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ files := result.Data.Files
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(files, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
+ rows := flattenFileTree(files, 0)
+
+ output.Table(headers, rows)
+ return nil
+ },
+}
+
+var importCmd = &cobra.Command{
+ Use: "import",
+ Short: "Import a GitOps sync configuration",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ name, _ := cmd.Flags().GetString("name")
+ repo, _ := cmd.Flags().GetString("repo-url")
+ branch, _ := cmd.Flags().GetString("branch")
+ composePath, _ := cmd.Flags().GetString("compose-path")
+ autoSync, _ := cmd.Flags().GetBool("auto-sync")
+ interval, _ := cmd.Flags().GetInt("interval")
+
+ req := gitops.ImportGitOpsSyncRequest{
+ SyncName: name,
+ GitRepo: repo,
+ Branch: branch,
+ DockerComposePath: composePath,
+ AutoSync: autoSync,
+ SyncInterval: interval,
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitOpsSyncsImport(c.EnvID()), req)
+ if err != nil {
+ return fmt.Errorf("failed to import gitops sync: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to import gitops sync: %w", err)
+ }
+
+ var result base.ApiResponse[gitops.ImportGitOpsSyncResponse]
+ 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
+ }
+
+ output.Success("Import completed: %d succeeded, %d failed", result.Data.SuccessCount, result.Data.FailedCount)
+ if len(result.Data.Errors) > 0 {
+ output.Warning("Errors:")
+ for _, e := range result.Data.Errors {
+ fmt.Printf(" - %s\n", e)
+ }
+ }
+ return nil
+ },
+}
+
+func init() {
+ GitopsCmd.AddCommand(listCmd)
+ GitopsCmd.AddCommand(createCmd)
+ GitopsCmd.AddCommand(getCmd)
+ GitopsCmd.AddCommand(updateCmd)
+ GitopsCmd.AddCommand(deleteCmd)
+ GitopsCmd.AddCommand(statusCmd)
+ GitopsCmd.AddCommand(syncCmd)
+ GitopsCmd.AddCommand(filesCmd)
+ GitopsCmd.AddCommand(importCmd)
+
+ // List command flags
+ listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of syncs to show")
+ listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Create command flags
+ createCmd.Flags().String("name", "", "Name of the sync configuration")
+ createCmd.Flags().String("repo-id", "", "Repository ID")
+ createCmd.Flags().String("branch", "", "Branch to sync from")
+ createCmd.Flags().String("compose-path", "", "Path to docker-compose file")
+ createCmd.Flags().Bool("auto-sync", false, "Enable automatic sync")
+ createCmd.Flags().Int("interval", 0, "Sync interval in minutes")
+ createCmd.Flags().String("project-name", "", "Project name for the sync")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("name")
+ _ = createCmd.MarkFlagRequired("repo-id")
+ _ = createCmd.MarkFlagRequired("branch")
+ _ = createCmd.MarkFlagRequired("compose-path")
+
+ // Get command flags
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Update command flags
+ updateCmd.Flags().StringVar(&gitopsUpdateName, "name", "", "Name of the sync configuration")
+ updateCmd.Flags().StringVar(&gitopsUpdateRepoID, "repo-id", "", "Repository ID")
+ updateCmd.Flags().StringVar(&gitopsUpdateBranch, "branch", "", "Branch to sync from")
+ updateCmd.Flags().StringVar(&gitopsUpdateComposePath, "compose-path", "", "Path to docker-compose file")
+ updateCmd.Flags().StringVar(&gitopsUpdateProjectName, "project-name", "", "Project name for the sync")
+ updateCmd.Flags().BoolVar(&gitopsUpdateAutoSync, "auto-sync", false, "Enable automatic sync")
+ updateCmd.Flags().IntVar(&gitopsUpdateInterval, "interval", 0, "Sync interval in minutes")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Delete command flags
+ deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force delete without confirmation")
+ deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Status command flags
+ statusCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Sync command flags
+ syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Files command flags
+ filesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Import command flags
+ importCmd.Flags().String("name", "", "Name of the sync configuration")
+ importCmd.Flags().String("repo-url", "", "Git repository URL")
+ importCmd.Flags().String("branch", "", "Branch to sync from")
+ importCmd.Flags().String("compose-path", "", "Path to docker-compose file")
+ importCmd.Flags().Bool("auto-sync", false, "Enable automatic sync")
+ importCmd.Flags().Int("interval", 5, "Sync interval in minutes")
+ importCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = importCmd.MarkFlagRequired("name")
+ _ = importCmd.MarkFlagRequired("repo-url")
+ _ = importCmd.MarkFlagRequired("branch")
+ _ = importCmd.MarkFlagRequired("compose-path")
+}
+
+func resolveGitOpsSync(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*gitops.GitOpsSync, bool, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, false, fmt.Errorf("gitops sync identifier is required")
+ }
+
+ resp, err := c.Get(ctx, types.Endpoints.GitOpsSync(c.EnvID(), trimmed))
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to resolve gitops sync %q: %w", trimmed, err)
+ }
+
+ bodyBytes, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to read gitops sync response: %w", err)
+ }
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[gitops.GitOpsSync]
+ if err := json.Unmarshal(bodyBytes, &result); err != nil {
+ return nil, false, fmt.Errorf("failed to parse gitops sync response: %w", err)
+ }
+ return &result.Data, true, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ return nil, false, fmt.Errorf("failed to resolve gitops sync %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.GitOpsSyncs(c.EnvID()), url.QueryEscape(trimmed), 200)
+ searchResp, err := c.Get(ctx, searchPath)
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to search gitops syncs: %w", err)
+ }
+
+ searchBody, err := io.ReadAll(searchResp.Body)
+ _ = searchResp.Body.Close()
+ if err != nil {
+ return nil, false, fmt.Errorf("failed to read gitops syncs response: %w", err)
+ }
+
+ if searchResp.StatusCode < 200 || searchResp.StatusCode >= 300 {
+ return nil, false, fmt.Errorf("failed to search gitops syncs (status %d): %s", searchResp.StatusCode, strings.TrimSpace(string(searchBody)))
+ }
+
+ var result base.Paginated[gitops.GitOpsSync]
+ if err := json.Unmarshal(searchBody, &result); err != nil {
+ return nil, false, fmt.Errorf("failed to parse gitops syncs response: %w", err)
+ }
+
+ matches := make([]gitops.GitOpsSync, 0)
+ for _, sync := range result.Data {
+ if gitOpsSyncMatches(sync, identifierLower, trimmed) {
+ matches = append(matches, sync)
+ }
+ }
+
+ if len(matches) == 1 {
+ return &matches[0], false, nil
+ }
+
+ if len(matches) > 1 {
+ if !allowPrompt {
+ return nil, false, fmt.Errorf("multiple gitops syncs match %q; use the sync ID or run `arcane gitops list`", trimmed)
+ }
+ if len(matches) > maxPromptOptions {
+ return nil, false, fmt.Errorf("multiple gitops syncs match %q (%d results); refine your query or use the sync ID", trimmed, len(matches))
+ }
+
+ options := make([]string, 0, len(matches))
+ for _, match := range matches {
+ lastStatus := "-"
+ if match.LastSyncStatus != nil {
+ lastStatus = *match.LastSyncStatus
+ }
+ options = append(options, fmt.Sprintf("%s (%s, %s)", match.Name, match.ID, lastStatus))
+ }
+ choice, err := prompt.Select("gitops sync", options)
+ if err != nil {
+ return nil, false, err
+ }
+ return &matches[choice], false, nil
+ }
+
+ return nil, false, fmt.Errorf("gitops sync %q not found; use the sync ID or run `arcane gitops list`", trimmed)
+}
+
+func gitOpsSyncMatches(item gitops.GitOpsSync, identifierLower, original string) bool {
+ idLower := strings.ToLower(item.ID)
+ if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {
+ return true
+ }
+ if strings.Contains(idLower, identifierLower) {
+ return true
+ }
+ if strings.Contains(strings.ToLower(item.Name), identifierLower) {
+ return true
+ }
+ if strings.EqualFold(item.Name, original) {
+ return true
+ }
+ return false
+}
+
+func flattenFileTree(nodes []gitops.FileTreeNode, depth int) [][]string {
+ var rows [][]string
+ for _, node := range nodes {
+ prefix := strings.Repeat(" ", depth)
+ size := "-"
+ if node.Type == gitops.FileTreeNodeTypeFile {
+ size = formatSize(node.Size)
+ }
+ rows = append(rows, []string{
+ prefix + node.Name,
+ string(node.Type),
+ node.Path,
+ size,
+ })
+ if len(node.Children) > 0 {
+ rows = append(rows, flattenFileTree(node.Children, depth+1)...)
+ }
+ }
+ return rows
+}
+
+func formatSize(bytes int64) string {
+ if bytes == 0 {
+ return "0 B"
+ }
+ const unit = 1024
+ if bytes < unit {
+ return fmt.Sprintf("%d B", bytes)
+ }
+ div, exp := int64(unit), 0
+ for n := bytes / unit; n >= unit; n /= unit {
+ div *= unit
+ exp++
+ }
+ return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
+}
diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.go
index 5934fd3c1..0522b4f72 100644
--- a/cli/pkg/jobs/cmd.go
+++ b/cli/pkg/jobs/cmd.go
@@ -5,6 +5,7 @@ import (
"fmt"
"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"
@@ -31,11 +32,14 @@ var getCmd = &cobra.Command{
return err
}
- resp, err := c.Get(cmd.Context(), types.Endpoints.JobSchedules())
+ resp, err := c.Get(cmd.Context(), types.Endpoints.JobSchedules(c.EnvID()))
if err != nil {
return fmt.Errorf("failed to get job schedules: %w", err)
}
defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to get job schedules: %w", err)
+ }
var cfg jobschedule.Config
if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {
@@ -90,7 +94,7 @@ var updateCmd = &cobra.Command{
return fmt.Errorf("no updates provided (set at least one interval flag)")
}
- resp, err := c.Put(cmd.Context(), types.Endpoints.JobSchedules(), req)
+ resp, err := c.Put(cmd.Context(), types.Endpoints.JobSchedules(c.EnvID()), req)
if err != nil {
return fmt.Errorf("failed to update job schedules: %w", err)
}
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 3e3548a69..5ae517c12 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -7,6 +7,8 @@ import (
"io"
"net/http"
"net/url"
+ "os"
+ "path/filepath"
"strings"
"time"
@@ -24,6 +26,14 @@ var (
limitFlag int
forceFlag bool
jsonOutput bool
+
+ createName string
+ createFile string
+ createEnvFile string
+ updateName string
+ updateFile string
+ updateEnvFile string
+ includesFile string
)
const maxPromptOptions = 20
@@ -343,6 +353,191 @@ var pullCmd = &cobra.Command{
},
}
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new project from a Docker Compose file",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ composeBytes, err := os.ReadFile(createFile)
+ if err != nil {
+ return fmt.Errorf("failed to read compose file: %w", err)
+ }
+
+ body := project.CreateProject{
+ Name: createName,
+ ComposeContent: string(composeBytes),
+ }
+
+ if createEnvFile != "" {
+ envBytes, err := os.ReadFile(createEnvFile)
+ if err != nil {
+ return fmt.Errorf("failed to read env file: %w", err)
+ }
+ envStr := string(envBytes)
+ body.EnvContent = &envStr
+ }
+
+ // Creating can take a long time as it may pull images
+ c.SetTimeout(30 * time.Minute)
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.Projects(c.EnvID()), body)
+ if err != nil {
+ return fmt.Errorf("failed to create project: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create project: %w", err)
+ }
+
+ var result base.ApiResponse[project.CreateReponse]
+ 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
+ }
+
+ output.Success("Project %s created successfully", result.Data.Name)
+ output.Header("Project Details")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("Status", result.Data.Status)
+ output.KeyValue("Path", result.Data.Path)
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <project-id|name>",
+ Short: "Update an existing project",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, _, err := resolveProject(cmd.Context(), c, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ body := project.UpdateProject{}
+
+ if cmd.Flags().Changed("name") {
+ body.Name = &updateName
+ }
+
+ if cmd.Flags().Changed("file") {
+ composeBytes, err := os.ReadFile(updateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read compose file: %w", err)
+ }
+ composeStr := string(composeBytes)
+ body.ComposeContent = &composeStr
+ }
+
+ if cmd.Flags().Changed("env-file") {
+ envBytes, err := os.ReadFile(updateEnvFile)
+ if err != nil {
+ return fmt.Errorf("failed to read env file: %w", err)
+ }
+ envStr := string(envBytes)
+ body.EnvContent = &envStr
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.Project(c.EnvID(), resolved.ID), body)
+ if err != nil {
+ return fmt.Errorf("failed to update project: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update project: %w", err)
+ }
+
+ if jsonOutput {
+ 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)
+ }
+ 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("Project %s updated successfully", resolved.Name)
+ return nil
+ },
+}
+
+var updateIncludesCmd = &cobra.Command{
+ Use: "update-includes <project-id|name>",
+ Short: "Update an include file in a project",
+ 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
+ }
+
+ content, err := os.ReadFile(includesFile)
+ if err != nil {
+ return fmt.Errorf("failed to read include file: %w", err)
+ }
+
+ body := project.UpdateIncludeFile{
+ RelativePath: filepath.Base(includesFile),
+ Content: string(content),
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.ProjectIncludes(c.EnvID(), resolved.ID), body)
+ if err != nil {
+ return fmt.Errorf("failed to update include file: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update include file: %w", err)
+ }
+
+ if jsonOutput {
+ 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)
+ }
+ 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("Include file %s updated successfully for project %s", filepath.Base(includesFile), resolved.Name)
+ return nil
+ },
+}
+
var countsCmd = &cobra.Command{
Use: "counts",
Short: "Get project counts",
@@ -391,6 +586,9 @@ func init() {
ProjectsCmd.AddCommand(pullCmd)
ProjectsCmd.AddCommand(countsCmd)
ProjectsCmd.AddCommand(destroyCmd)
+ ProjectsCmd.AddCommand(createCmd)
+ ProjectsCmd.AddCommand(updateCmd)
+ ProjectsCmd.AddCommand(updateIncludesCmd)
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
@@ -405,6 +603,25 @@ func init() {
// Destroy command flags
destroyCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force destroy without confirmation")
destroyCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Create command flags
+ createCmd.Flags().StringVar(&createName, "name", "", "Project name")
+ createCmd.Flags().StringVarP(&createFile, "file", "f", "", "Docker Compose file")
+ createCmd.Flags().StringVar(&createEnvFile, "env-file", "", "Environment file")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("name")
+ _ = createCmd.MarkFlagRequired("file")
+
+ // Update command flags
+ updateCmd.Flags().StringVar(&updateName, "name", "", "New project name")
+ updateCmd.Flags().StringVarP(&updateFile, "file", "f", "", "Docker Compose file")
+ updateCmd.Flags().StringVar(&updateEnvFile, "env-file", "", "Environment file")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Update includes command flags
+ updateIncludesCmd.Flags().StringVarP(&includesFile, "file", "f", "", "Include file")
+ updateIncludesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = updateIncludesCmd.MarkFlagRequired("file")
}
func resolveProject(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*project.Details, bool, error) {
diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.go
index 4a6005cab..09e29ad0e 100644
--- a/cli/pkg/registries/cmd.go
+++ b/cli/pkg/registries/cmd.go
@@ -17,6 +17,12 @@ var (
limitFlag int
forceFlag bool
jsonOutput bool
+
+ registryUpdateURL string
+ registryUpdateUsername string
+ registryUpdatePassword string
+ registryUpdateEnabled bool
+ registryUpdateDisabled bool
)
var RegistriesCmd = &cobra.Command{
@@ -157,6 +163,108 @@ var testCmd = &cobra.Command{
},
}
+var getCmd = &cobra.Command{
+ Use: "get <registry-id>",
+ Short: "Get container registry details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.ContainerRegistry(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to get registry: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[containerregistry.ContainerRegistry]
+ 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
+ }
+
+ output.Header("Registry Details")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("URL", result.Data.URL)
+ output.KeyValue("Username", result.Data.Username)
+ output.KeyValue("Enabled", result.Data.Enabled)
+ output.KeyValue("Insecure", result.Data.Insecure)
+ output.KeyValue("Created", result.Data.CreatedAt.Format("2006-01-02 15:04"))
+ output.KeyValue("Updated", result.Data.UpdatedAt.Format("2006-01-02 15:04"))
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <registry-id>",
+ Short: "Update container registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ req := make(map[string]any)
+ if cmd.Flags().Changed("enabled") && cmd.Flags().Changed("disabled") {
+ return fmt.Errorf("--enabled and --disabled are mutually exclusive")
+ }
+ if cmd.Flags().Changed("url") {
+ req["url"] = registryUpdateURL
+ }
+ if cmd.Flags().Changed("username") {
+ req["username"] = registryUpdateUsername
+ }
+ if cmd.Flags().Changed("password") {
+ req["password"] = registryUpdatePassword
+ }
+ if cmd.Flags().Changed("enabled") {
+ req["enabled"] = true
+ }
+ if cmd.Flags().Changed("disabled") {
+ req["enabled"] = false
+ }
+
+ if len(req) == 0 {
+ return fmt.Errorf("no updates provided; use --url, --username, --password, --enabled, or --disabled")
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.ContainerRegistry(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update registry: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update registry: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Registry updated successfully")
+ return nil
+ },
+}
+
var deleteCmd = &cobra.Command{
Use: "delete <registry-id>",
Aliases: []string{"rm", "remove"},
@@ -196,16 +304,27 @@ var deleteCmd = &cobra.Command{
func init() {
RegistriesCmd.AddCommand(listCmd)
+ RegistriesCmd.AddCommand(getCmd)
RegistriesCmd.AddCommand(syncCmd)
RegistriesCmd.AddCommand(testCmd)
+ RegistriesCmd.AddCommand(updateCmd)
RegistriesCmd.AddCommand(deleteCmd)
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of registries to show")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
testCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ updateCmd.Flags().StringVar(&registryUpdateURL, "url", "", "Registry URL")
+ updateCmd.Flags().StringVar(&registryUpdateUsername, "username", "", "Username")
+ updateCmd.Flags().StringVar(&registryUpdatePassword, "password", "", "Password")
+ updateCmd.Flags().BoolVar(&registryUpdateEnabled, "enabled", false, "Enable registry")
+ updateCmd.Flags().BoolVar(&registryUpdateDisabled, "disabled", false, "Disable registry")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.go
new file mode 100644
index 000000000..2b1d28aca
--- /dev/null
+++ b/cli/pkg/repos/cmd.go
@@ -0,0 +1,708 @@
+package repos
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "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"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/gitops"
+ "github.com/spf13/cobra"
+)
+
+var (
+ limitFlag int
+ forceFlag bool
+ jsonOutput bool
+)
+
+const maxPromptOptions = 20
+
+// ReposCmd is the parent command for git repository operations.
+var ReposCmd = &cobra.Command{
+ Use: "repos",
+ Aliases: []string{"repo", "git-repositories", "git-repos"},
+ Short: "Manage git repositories",
+}
+
+// --- create flags ---
+var (
+ repoCreateName string
+ repoCreateURL string
+ repoCreateAuthType string
+ repoCreateToken string
+ repoCreateUsername string
+ repoCreateSSHKey string
+ repoCreateSSHHostKeyVerify string
+ repoCreateDescription string
+ repoCreateEnabled bool
+)
+
+// --- update flags ---
+var (
+ repoUpdateName string
+ repoUpdateURL string
+ repoUpdateAuthType string
+ repoUpdateToken string
+ repoUpdateUsername string
+ repoUpdateSSHKey string
+ repoUpdateSSHHostKeyVerify string
+ repoUpdateDescription string
+ repoUpdateEnabled bool
+)
+
+// --- files flags ---
+var (
+ filesBranch string
+ filesPath string
+)
+
+var listCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List git repositories",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.GitRepositories()
+ effectiveLimit := cmdutil.EffectiveLimit(cmd, "repos", "limit", limitFlag, 20)
+ if effectiveLimit > 0 {
+ path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
+ }
+
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list repositories: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.Paginated[gitops.GitRepository]
+ 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, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ headers := []string{"ID", "NAME", "URL", "AUTH TYPE", "ENABLED", "CREATED"}
+ rows := make([][]string, len(result.Data))
+ for i, repo := range result.Data {
+ enabled := "false"
+ if repo.Enabled {
+ enabled = "true"
+ }
+ rows[i] = []string{
+ repo.ID,
+ repo.Name,
+ repo.URL,
+ repo.AuthType,
+ enabled,
+ repo.CreatedAt.Format("2006-01-02 15:04:05"),
+ }
+ }
+
+ output.Table(headers, rows)
+ fmt.Printf("\nTotal: %d repositories\n", result.Pagination.TotalItems)
+ return nil
+ },
+}
+
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a git repository",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ req := gitops.CreateRepositoryRequest{
+ Name: repoCreateName,
+ URL: repoCreateURL,
+ AuthType: repoCreateAuthType,
+ }
+
+ if cmd.Flags().Changed("token") {
+ req.Token = repoCreateToken
+ }
+ if cmd.Flags().Changed("username") {
+ req.Username = repoCreateUsername
+ }
+ if cmd.Flags().Changed("ssh-key") {
+ sshKeyData, err := os.ReadFile(repoCreateSSHKey)
+ if err != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", err)
+ }
+ req.SSHKey = string(sshKeyData)
+ }
+ if cmd.Flags().Changed("ssh-host-key-verification") {
+ req.SSHHostKeyVerification = repoCreateSSHHostKeyVerify
+ }
+ if cmd.Flags().Changed("description") {
+ req.Description = &repoCreateDescription
+ }
+ if cmd.Flags().Changed("enabled") {
+ req.Enabled = &repoCreateEnabled
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositories(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create repository: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create repository: %w", err)
+ }
+
+ var result base.ApiResponse[gitops.GitRepository]
+ 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
+ }
+
+ output.Success("Repository created successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("URL", result.Data.URL)
+ output.KeyValue("Auth Type", result.Data.AuthType)
+ output.KeyValue("Enabled", result.Data.Enabled)
+ return nil
+ },
+}
+
+var getCmd = &cobra.Command{
+ Use: "get <repository>",
+ Short: "Get git repository details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ 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("Repository Details")
+ output.KeyValue("ID", resolved.ID)
+ output.KeyValue("Name", resolved.Name)
+ output.KeyValue("URL", resolved.URL)
+ output.KeyValue("Auth Type", resolved.AuthType)
+ if resolved.Username != "" {
+ output.KeyValue("Username", resolved.Username)
+ }
+ if resolved.SSHHostKeyVerification != "" {
+ output.KeyValue("SSH Host Key Verification", resolved.SSHHostKeyVerification)
+ }
+ if resolved.Description != nil {
+ output.KeyValue("Description", *resolved.Description)
+ }
+ output.KeyValue("Enabled", resolved.Enabled)
+ output.KeyValue("Created", resolved.CreatedAt.Format("2006-01-02 15:04:05"))
+ output.KeyValue("Updated", resolved.UpdatedAt.Format("2006-01-02 15:04:05"))
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <repository>",
+ Short: "Update a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
+
+ req := gitops.UpdateRepositoryRequest{}
+
+ if cmd.Flags().Changed("name") {
+ req.Name = &repoUpdateName
+ }
+ if cmd.Flags().Changed("url") {
+ req.URL = &repoUpdateURL
+ }
+ if cmd.Flags().Changed("auth-type") {
+ req.AuthType = &repoUpdateAuthType
+ }
+ if cmd.Flags().Changed("token") {
+ req.Token = &repoUpdateToken
+ }
+ if cmd.Flags().Changed("username") {
+ req.Username = &repoUpdateUsername
+ }
+ if cmd.Flags().Changed("ssh-key") {
+ sshKeyData, err := os.ReadFile(repoUpdateSSHKey)
+ if err != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", err)
+ }
+ sshKey := string(sshKeyData)
+ req.SSHKey = &sshKey
+ }
+ if cmd.Flags().Changed("ssh-host-key-verification") {
+ req.SSHHostKeyVerification = &repoUpdateSSHHostKeyVerify
+ }
+ if cmd.Flags().Changed("description") {
+ req.Description = &repoUpdateDescription
+ }
+ if cmd.Flags().Changed("enabled") {
+ req.Enabled = &repoUpdateEnabled
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.GitRepository(resolved.ID), req)
+ if err != nil {
+ return fmt.Errorf("failed to update repository: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update repository: %w", err)
+ }
+
+ var result base.ApiResponse[gitops.GitRepository]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ if jsonOutput {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+ output.Success("Repository updated successfully")
+ return nil
+ }
+
+ 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
+ }
+
+ output.Success("Repository updated successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("URL", result.Data.URL)
+ output.KeyValue("Auth Type", result.Data.AuthType)
+ output.KeyValue("Enabled", result.Data.Enabled)
+ return nil
+ },
+}
+
+var deleteCmd = &cobra.Command{
+ Use: "delete <repository>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
+
+ if !forceFlag {
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete repository %s (%s)?", resolved.Name, resolved.ID))
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.GitRepository(resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to delete repository: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete repository: %w", err)
+ }
+
+ output.Success("Repository deleted successfully")
+ return nil
+ },
+}
+
+var testCmd = &cobra.Command{
+ Use: "test <repository>",
+ Short: "Test git repository connection",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositoryTest(resolved.ID), nil)
+ if err != nil {
+ return fmt.Errorf("failed to test repository: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("repository connection test failed: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Repository connection test successful")
+ return nil
+ },
+}
+
+var branchesCmd = &cobra.Command{
+ Use: "branches <repository>",
+ Short: "List branches for a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.GitRepositoryBranches(resolved.ID))
+ if err != nil {
+ return fmt.Errorf("failed to list branches: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.BranchesResponse]
+ 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
+ }
+
+ headers := []string{"BRANCH", "DEFAULT"}
+ rows := make([][]string, len(result.Data.Branches))
+ for i, branch := range result.Data.Branches {
+ isDefault := ""
+ if branch.IsDefault {
+ isDefault = "*"
+ }
+ rows[i] = []string{
+ branch.Name,
+ isDefault,
+ }
+ }
+
+ output.Table(headers, rows)
+ fmt.Printf("\nTotal: %d branches\n", len(result.Data.Branches))
+ return nil
+ },
+}
+
+var filesCmd = &cobra.Command{
+ Use: "files <repository>",
+ Short: "List files in a git repository",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveGitRepository(cmd.Context(), c, args[0])
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.GitRepositoryFiles(resolved.ID)
+ params := url.Values{}
+ if filesBranch != "" {
+ params.Set("branch", filesBranch)
+ }
+ if filesPath != "" {
+ params.Set("path", filesPath)
+ }
+ if len(params) > 0 {
+ path = path + "?" + params.Encode()
+ }
+
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list files: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[gitops.BrowseResponse]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ files := result.Data.Files
+ if jsonOutput {
+ resultBytes, err := json.MarshalIndent(files, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
+ rows := make([][]string, len(files))
+ for i, node := range files {
+ size := ""
+ if node.Type == gitops.FileTreeNodeTypeFile {
+ size = fmt.Sprintf("%d", node.Size)
+ }
+ rows[i] = []string{
+ node.Name,
+ string(node.Type),
+ node.Path,
+ size,
+ }
+ }
+
+ output.Table(headers, rows)
+ fmt.Printf("\nTotal: %d entries\n", len(files))
+ return nil
+ },
+}
+
+var syncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Sync all git repositories",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.GitRepositoriesSync(), nil)
+ if err != nil {
+ return fmt.Errorf("failed to sync repositories: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to sync repositories: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Repositories synced successfully")
+ return nil
+ },
+}
+
+// resolveGitRepository attempts to resolve a repository by ID or name.
+// It first tries a direct GET by ID. If that returns 404, it falls back to
+// searching the list endpoint by name or ID prefix.
+func resolveGitRepository(ctx context.Context, c *client.Client, identifier string) (*gitops.GitRepository, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, fmt.Errorf("repository identifier is required")
+ }
+
+ // Try direct GET by ID.
+ resp, err := c.Get(ctx, types.Endpoints.GitRepository(trimmed))
+ if err == nil {
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[gitops.GitRepository]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
+ return &result.Data, nil
+ }
+ }
+ // Drain body on non-OK response.
+ _, _ = io.Copy(io.Discard, resp.Body)
+ }
+
+ // Fallback: search via list endpoint.
+ listPath := fmt.Sprintf("%s?limit=200", types.Endpoints.GitRepositories())
+ listResp, err := c.Get(ctx, listPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to search repositories: %w", err)
+ }
+ defer func() { _ = listResp.Body.Close() }()
+
+ var listResult base.Paginated[gitops.GitRepository]
+ if err := json.NewDecoder(listResp.Body).Decode(&listResult); err != nil {
+ return nil, fmt.Errorf("failed to parse repository list: %w", err)
+ }
+
+ lowerIdentifier := strings.ToLower(trimmed)
+ var matches []gitops.GitRepository
+ for _, repo := range listResult.Data {
+ if strings.EqualFold(repo.Name, trimmed) || strings.EqualFold(repo.ID, trimmed) {
+ return &repo, nil
+ }
+ if strings.HasPrefix(strings.ToLower(repo.ID), lowerIdentifier) ||
+ strings.Contains(strings.ToLower(repo.Name), lowerIdentifier) {
+ matches = append(matches, repo)
+ }
+ }
+
+ switch len(matches) {
+ case 0:
+ return nil, fmt.Errorf("repository %q not found", trimmed)
+ case 1:
+ return &matches[0], nil
+ default:
+ if !prompt.IsInteractive() || len(matches) > maxPromptOptions {
+ return nil, fmt.Errorf("ambiguous repository %q: %d matches found, please be more specific", trimmed, len(matches))
+ }
+ options := make([]string, len(matches))
+ for i, m := range matches {
+ options[i] = fmt.Sprintf("%s (%s)", m.Name, m.ID)
+ }
+ choice, err := prompt.Select("repository", options)
+ if err != nil {
+ return nil, err
+ }
+ return &matches[choice], nil
+ }
+}
+
+func init() {
+ ReposCmd.AddCommand(listCmd)
+ ReposCmd.AddCommand(createCmd)
+ ReposCmd.AddCommand(getCmd)
+ ReposCmd.AddCommand(updateCmd)
+ ReposCmd.AddCommand(deleteCmd)
+ ReposCmd.AddCommand(testCmd)
+ ReposCmd.AddCommand(branchesCmd)
+ ReposCmd.AddCommand(filesCmd)
+ ReposCmd.AddCommand(syncCmd)
+
+ // List command flags
+ listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of repositories to show")
+ listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Create command flags
+ createCmd.Flags().StringVar(&repoCreateName, "name", "", "Repository name")
+ createCmd.Flags().StringVar(&repoCreateURL, "url", "", "Repository URL")
+ createCmd.Flags().StringVar(&repoCreateAuthType, "auth-type", "", "Authentication type (none, http, ssh)")
+ createCmd.Flags().StringVar(&repoCreateToken, "token", "", "Token for HTTP authentication")
+ createCmd.Flags().StringVar(&repoCreateUsername, "username", "", "Username for HTTP authentication")
+ createCmd.Flags().StringVar(&repoCreateSSHKey, "ssh-key", "", "Path to SSH key file")
+ createCmd.Flags().StringVar(&repoCreateSSHHostKeyVerify, "ssh-host-key-verification", "", "SSH host key verification (strict, accept_new, skip)")
+ createCmd.Flags().StringVar(&repoCreateDescription, "description", "", "Repository description")
+ createCmd.Flags().BoolVar(&repoCreateEnabled, "enabled", true, "Enable the repository")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("name")
+ _ = createCmd.MarkFlagRequired("url")
+ _ = createCmd.MarkFlagRequired("auth-type")
+
+ // Get command flags
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Update command flags
+ updateCmd.Flags().StringVar(&repoUpdateName, "name", "", "Repository name")
+ updateCmd.Flags().StringVar(&repoUpdateURL, "url", "", "Repository URL")
+ updateCmd.Flags().StringVar(&repoUpdateAuthType, "auth-type", "", "Authentication type (none, http, ssh)")
+ updateCmd.Flags().StringVar(&repoUpdateToken, "token", "", "Token for HTTP authentication")
+ updateCmd.Flags().StringVar(&repoUpdateUsername, "username", "", "Username for HTTP authentication")
+ updateCmd.Flags().StringVar(&repoUpdateSSHKey, "ssh-key", "", "Path to SSH key file")
+ updateCmd.Flags().StringVar(&repoUpdateSSHHostKeyVerify, "ssh-host-key-verification", "", "SSH host key verification (strict, accept_new, skip)")
+ updateCmd.Flags().StringVar(&repoUpdateDescription, "description", "", "Repository description")
+ updateCmd.Flags().BoolVar(&repoUpdateEnabled, "enabled", true, "Enable the repository")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Delete command flags
+ deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
+ deleteCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Test command flags
+ testCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Branches command flags
+ branchesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Files command flags
+ filesCmd.Flags().StringVar(&filesBranch, "branch", "", "Branch to browse")
+ filesCmd.Flags().StringVar(&filesPath, "path", "", "Path within repository")
+ filesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Sync command flags
+ syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+}
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index 2bc5aac2c..7969d4f18 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -58,11 +58,13 @@ import (
"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/gitops"
"github.com/getarcaneapp/arcane/cli/pkg/images"
"github.com/getarcaneapp/arcane/cli/pkg/jobs"
"github.com/getarcaneapp/arcane/cli/pkg/networks"
"github.com/getarcaneapp/arcane/cli/pkg/projects"
"github.com/getarcaneapp/arcane/cli/pkg/registries"
+ "github.com/getarcaneapp/arcane/cli/pkg/repos"
"github.com/getarcaneapp/arcane/cli/pkg/settings"
"github.com/getarcaneapp/arcane/cli/pkg/system"
"github.com/getarcaneapp/arcane/cli/pkg/templates"
@@ -235,12 +237,14 @@ func init() {
rootCmd.AddCommand(projects.ProjectsCmd)
rootCmd.AddCommand(environments.EnvironmentsCmd)
rootCmd.AddCommand(registries.RegistriesCmd)
+ rootCmd.AddCommand(repos.ReposCmd)
rootCmd.AddCommand(templates.TemplatesCmd)
rootCmd.AddCommand(settings.SettingsCmd)
rootCmd.AddCommand(jobs.JobsCmd)
rootCmd.AddCommand(system.SystemCmd)
rootCmd.AddCommand(updater.UpdaterCmd)
rootCmd.AddCommand(admin.AdminCmd)
+ rootCmd.AddCommand(gitops.GitopsCmd)
}
func renderCommandHelp(cmd *cobra.Command) {
diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.go
index 773ffc31a..bb4c0a6e1 100644
--- a/cli/pkg/settings/cmd.go
+++ b/cli/pkg/settings/cmd.go
@@ -3,8 +3,10 @@ package settings
import (
"encoding/json"
"fmt"
+ "os"
"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/settings"
@@ -67,8 +69,104 @@ var listCmd = &cobra.Command{
},
}
+var settingsUpdateFile string
+
+var updateCmd = &cobra.Command{
+ Use: "update",
+ Short: "Update environment settings",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ data, err := os.ReadFile(settingsUpdateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", settingsUpdateFile, err)
+ }
+
+ var req settings.Update
+ if err := json.Unmarshal(data, &req); err != nil {
+ return fmt.Errorf("failed to parse settings file: %w", err)
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.Settings(c.EnvID()), req)
+ if err != nil {
+ return fmt.Errorf("failed to update settings: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update settings: %w", err)
+ }
+
+ if jsonOutput {
+ var result any
+ if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
+ if resultBytes, err := json.MarshalIndent(result, "", " "); err == nil {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Settings updated successfully")
+ return nil
+ },
+}
+
+var publicCmd = &cobra.Command{
+ Use: "public",
+ Short: "List public settings",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.SettingsPublic(c.EnvID()))
+ if err != nil {
+ return fmt.Errorf("failed to get public settings: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result []settings.PublicSetting
+ 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, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ headers := []string{"KEY", "TYPE", "VALUE"}
+ rows := make([][]string, len(result))
+ for i, s := range result {
+ rows[i] = []string{s.Key, s.Type, s.Value}
+ }
+
+ output.Table(headers, rows)
+ fmt.Printf("\nTotal: %d public settings\n", len(result))
+ return nil
+ },
+}
+
func init() {
SettingsCmd.AddCommand(listCmd)
+ SettingsCmd.AddCommand(updateCmd)
+ SettingsCmd.AddCommand(publicCmd)
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ updateCmd.Flags().StringVarP(&settingsUpdateFile, "file", "f", "", "Settings JSON file")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = updateCmd.MarkFlagRequired("file")
+
+ publicCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.go
index 44aa7a89b..966ad54a5 100644
--- a/cli/pkg/system/cmd.go
+++ b/cli/pkg/system/cmd.go
@@ -5,6 +5,7 @@ import (
"fmt"
"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"
@@ -139,14 +140,213 @@ var containersStopAllCmd = &cobra.Command{
},
}
+var startStoppedCmd = &cobra.Command{
+ Use: "start-stopped",
+ Short: "Start all stopped containers",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.SystemStartStopped(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to start stopped containers: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to start stopped containers: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("Started all stopped containers")
+ return nil
+ },
+}
+
+var convertCmd = &cobra.Command{
+ Use: "convert <docker-run-command>",
+ Short: "Convert docker run command to compose",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ req := map[string]string{"dockerRunCommand": args[0]}
+ resp, err := c.Post(cmd.Context(), types.Endpoints.SystemConvert(c.EnvID()), req)
+ if err != nil {
+ return fmt.Errorf("failed to convert command: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to convert command: %w", err)
+ }
+
+ var result struct {
+ Success bool `json:"success"`
+ DockerCompose string `json:"dockerCompose"`
+ EnvVars string `json:"envVars"`
+ ServiceName string `json:"serviceName"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ out := map[string]string{
+ "dockerCompose": result.DockerCompose,
+ "envVars": result.EnvVars,
+ "serviceName": result.ServiceName,
+ }
+ resultBytes, err := json.MarshalIndent(out, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("Conversion Result")
+ if result.ServiceName != "" {
+ fmt.Printf("Service: %s\n\n", result.ServiceName)
+ }
+ if result.DockerCompose != "" {
+ fmt.Println("Docker Compose:")
+ fmt.Println(result.DockerCompose)
+ }
+ if result.EnvVars != "" {
+ fmt.Println("Environment Variables:")
+ fmt.Println(result.EnvVars)
+ }
+ return nil
+ },
+}
+
+var forceFlag bool
+
+var upgradeCmd = &cobra.Command{
+ Use: "upgrade",
+ Short: "Trigger system upgrade",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !forceFlag {
+ confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to upgrade the system?")
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.SystemUpgrade(c.EnvID()), nil)
+ if err != nil {
+ return fmt.Errorf("failed to upgrade system: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to upgrade system: %w", err)
+ }
+
+ if 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 {
+ fmt.Println(string(resultBytes))
+ }
+ }
+ return nil
+ }
+
+ output.Success("System upgrade initiated")
+ return nil
+ },
+}
+
+var upgradeCheckCmd = &cobra.Command{
+ Use: "upgrade-check",
+ Short: "Check for available upgrades",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.SystemUpgradeCheck(c.EnvID()))
+ if err != nil {
+ return fmt.Errorf("failed to check for upgrades: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to check for upgrades: %w", err)
+ }
+
+ var result struct {
+ CanUpgrade bool `json:"canUpgrade"`
+ Error bool `json:"error"`
+ Message string `json:"message"`
+ }
+ 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, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(resultBytes))
+ return nil
+ }
+
+ output.Header("Upgrade Check")
+ output.KeyValue("Can Upgrade", fmt.Sprintf("%t", result.CanUpgrade))
+ output.KeyValue("Message", result.Message)
+ if result.Error {
+ output.KeyValue("Error", "true")
+ }
+ return nil
+ },
+}
+
func init() {
SystemCmd.AddCommand(pruneCmd)
SystemCmd.AddCommand(dockerInfoCmd)
SystemCmd.AddCommand(containersStartAllCmd)
SystemCmd.AddCommand(containersStopAllCmd)
+ SystemCmd.AddCommand(startStoppedCmd)
+ SystemCmd.AddCommand(convertCmd)
+ SystemCmd.AddCommand(upgradeCmd)
+ SystemCmd.AddCommand(upgradeCheckCmd)
pruneCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
dockerInfoCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
containersStartAllCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
containersStopAllCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ startStoppedCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ convertCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ upgradeCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Skip confirmation")
+ upgradeCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ upgradeCheckCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.go
index 6cafff83e..848dc3302 100644
--- a/cli/pkg/templates/cmd.go
+++ b/cli/pkg/templates/cmd.go
@@ -1,12 +1,21 @@
package templates
import (
+ "context"
"encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "unicode"
"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"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/env"
@@ -14,10 +23,31 @@ import (
"github.com/spf13/cobra"
)
+const maxTemplatePromptOptions = 20
+
var (
- limitFlag int
- forceFlag bool
- jsonOutput bool
+ limitFlag int
+ templateListAll bool
+ forceFlag bool
+ jsonOutput bool
+
+ templateUpdateName string
+ templateUpdateFile string
+ templateUpdateDescription string
+ templateUpdateEnvFile string
+ templateCreateName string
+ templateCreateFile string
+ templateCreateDescription string
+ templateCreateEnvFile string
+ templateDownloadOutput string
+ templateDefaultsSaveFile string
+ templateDefaultsEnvFile string
+ templateVarsUpdateFile string
+ templateRegUpdateName string
+ templateRegUpdateURL string
+ templateRegUpdateDesc string
+ templateRegUpdateEnabled bool
+ templateRegUpdateDisabled bool
)
// TemplatesCmd is the parent command for template operations
@@ -30,7 +60,7 @@ var TemplatesCmd = &cobra.Command{
var listCmd = &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
- Short: "List templates",
+ Short: "List local templates",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := client.NewFromConfig()
@@ -39,9 +69,13 @@ var listCmd = &cobra.Command{
}
path := types.Endpoints.Templates()
- effectiveLimit := cmdutil.EffectiveLimit(cmd, "templates", "limit", limitFlag, 20)
- if effectiveLimit > 0 {
- path = fmt.Sprintf("%s?limit=%d", path, effectiveLimit)
+ if templateListAll {
+ path = types.Endpoints.TemplatesAll()
+ } else {
+ 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)
@@ -64,7 +98,7 @@ var listCmd = &cobra.Command{
return nil
}
- headers := []string{"ID", "NAME", "DESCRIPTION", "CUSTOM", "REMOTE"}
+ headers := []string{"NAME", "CUSTOM", "REMOTE", "DESCRIPTION"}
rows := make([][]string, len(result.Data))
for i, tpl := range result.Data {
custom := "no"
@@ -76,67 +110,10 @@ var listCmd = &cobra.Command{
remote = "yes"
}
rows[i] = []string{
- tpl.ID,
tpl.Name,
- tpl.Description,
custom,
remote,
- }
- }
-
- output.Table(headers, rows)
- fmt.Printf("\nTotal: %d templates\n", len(result.Data))
- return nil
- },
-}
-
-var allCmd = &cobra.Command{
- Use: "all",
- Short: "List all templates (including remote)",
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
- if err != nil {
- return err
- }
-
- resp, err := c.Get(cmd.Context(), types.Endpoints.TemplatesAll())
- if err != nil {
- return fmt.Errorf("failed to list all templates: %w", err)
- }
- defer func() { _ = resp.Body.Close() }()
-
- var result base.ApiResponse[[]template.Template]
- 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
- }
-
- headers := []string{"ID", "NAME", "DESCRIPTION", "CUSTOM", "REMOTE"}
- rows := make([][]string, len(result.Data))
- for i, tpl := range result.Data {
- custom := "no"
- if tpl.IsCustom {
- custom = "yes"
- }
- remote := "no"
- if tpl.IsRemote {
- remote = "yes"
- }
- rows[i] = []string{
- tpl.ID,
- tpl.Name,
tpl.Description,
- custom,
- remote,
}
}
@@ -400,20 +377,776 @@ var deleteRegistryCmd = &cobra.Command{
},
}
+var getCmd = &cobra.Command{
+ Use: "get <template>",
+ Short: "Get a template by ID or name",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resolved, err := resolveTemplate(cmd.Context(), c, args[0])
+ 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
+ }
+
+ tpl := *resolved
+ output.Header("Template")
+ output.KeyValue("ID", tpl.ID)
+ output.KeyValue("Name", tpl.Name)
+ output.KeyValue("Description", tpl.Description)
+ custom := "no"
+ if tpl.IsCustom {
+ custom = "yes"
+ }
+ remote := "no"
+ if tpl.IsRemote {
+ remote = "yes"
+ }
+ output.KeyValue("Custom", custom)
+ output.KeyValue("Remote", remote)
+ return nil
+ },
+}
+
+// resolveTemplate attempts to resolve a template by ID or name.
+// It first tries direct GET by ID and falls back to searching all templates by name/ID.
+func resolveTemplate(ctx context.Context, c *client.Client, identifier string) (*template.Template, error) {
+ trimmed := strings.TrimSpace(identifier)
+ if trimmed == "" {
+ return nil, fmt.Errorf("template identifier is required")
+ }
+
+ resp, err := c.Get(ctx, types.Endpoints.Template(trimmed))
+ if err != nil {
+ return nil, fmt.Errorf("failed to get template: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode == http.StatusOK {
+ var result base.ApiResponse[template.Template]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, fmt.Errorf("failed to parse response: %w", err)
+ }
+ return &result.Data, nil
+ }
+
+ if resp.StatusCode != http.StatusNotFound {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ return nil, fmt.Errorf("failed to get template: request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ listResp, err := c.Get(ctx, types.Endpoints.TemplatesAll())
+ if err != nil {
+ return nil, fmt.Errorf("failed to search templates: %w", err)
+ }
+ defer func() { _ = listResp.Body.Close() }()
+
+ if listResp.StatusCode < http.StatusOK || listResp.StatusCode >= http.StatusMultipleChoices {
+ body, _ := io.ReadAll(io.LimitReader(listResp.Body, 4096))
+ return nil, fmt.Errorf("failed to search templates: request failed with status %d: %s", listResp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ var listResult base.ApiResponse[[]template.Template]
+ if err := json.NewDecoder(listResp.Body).Decode(&listResult); err != nil {
+ return nil, fmt.Errorf("failed to parse template list: %w", err)
+ }
+
+ lowerIdentifier := strings.ToLower(trimmed)
+ exactNameMatches := make([]template.Template, 0)
+ partialMatches := make([]template.Template, 0)
+
+ for _, tpl := range listResult.Data {
+ if strings.EqualFold(tpl.ID, trimmed) {
+ return &tpl, nil
+ }
+ if strings.EqualFold(tpl.Name, trimmed) {
+ exactNameMatches = append(exactNameMatches, tpl)
+ continue
+ }
+
+ if strings.Contains(strings.ToLower(tpl.Name), lowerIdentifier) || strings.HasPrefix(strings.ToLower(tpl.ID), lowerIdentifier) {
+ partialMatches = append(partialMatches, tpl)
+ }
+ }
+
+ if len(exactNameMatches) == 1 {
+ return &exactNameMatches[0], nil
+ }
+ if len(exactNameMatches) > 1 {
+ return selectTemplateMatch(trimmed, exactNameMatches)
+ }
+
+ if len(partialMatches) == 1 {
+ return &partialMatches[0], nil
+ }
+ if len(partialMatches) > 1 {
+ ranked := rankFuzzyTemplateMatches(trimmed, partialMatches)
+ if isConfidentBestFuzzyMatch(ranked) {
+ return &ranked[0].template, nil
+ }
+ return selectTemplateMatch(trimmed, topTemplatesFromRankedMatches(ranked, maxTemplatePromptOptions))
+ }
+
+ ranked := rankFuzzyTemplateMatches(trimmed, listResult.Data)
+ if isConfidentBestFuzzyMatch(ranked) {
+ return &ranked[0].template, nil
+ }
+ if len(ranked) > 0 {
+ return selectTemplateMatch(trimmed, topTemplatesFromRankedMatches(ranked, maxTemplatePromptOptions))
+ }
+
+ return nil, fmt.Errorf("template %q not found", trimmed)
+}
+
+func selectTemplateMatch(identifier string, matches []template.Template) (*template.Template, error) {
+ if len(matches) == 0 {
+ return nil, fmt.Errorf("template %q not found", identifier)
+ }
+ if len(matches) == 1 {
+ return &matches[0], nil
+ }
+
+ if !prompt.IsInteractive() || len(matches) > maxTemplatePromptOptions {
+ return nil, fmt.Errorf("ambiguous template %q: %s", identifier, formatTemplateCandidates(matches))
+ }
+
+ ordered := make([]template.Template, len(matches))
+ copy(ordered, matches)
+ sort.SliceStable(ordered, func(i, j int) bool {
+ left := strings.ToLower(strings.TrimSpace(ordered[i].Name))
+ right := strings.ToLower(strings.TrimSpace(ordered[j].Name))
+ if left == right {
+ return ordered[i].ID < ordered[j].ID
+ }
+ return left < right
+ })
+
+ options := make([]string, len(ordered))
+ for i, tpl := range ordered {
+ source := "local"
+ if tpl.IsRemote {
+ source = "remote"
+ }
+ custom := "builtin"
+ if tpl.IsCustom {
+ custom = "custom"
+ }
+ options[i] = fmt.Sprintf("%s (id: %s, %s, %s)", tpl.Name, tpl.ID, source, custom)
+ }
+
+ choice, err := prompt.Select("template", options)
+ if err != nil {
+ return nil, err
+ }
+
+ selected := ordered[choice]
+ return &selected, nil
+}
+
+type rankedTemplateMatch struct {
+ template template.Template
+ score int
+}
+
+func rankFuzzyTemplateMatches(query string, candidates []template.Template) []rankedTemplateMatch {
+ normalizedQuery := normalizeSearchToken(query)
+ if normalizedQuery == "" {
+ return nil
+ }
+
+ ranked := make([]rankedTemplateMatch, 0, len(candidates))
+ for _, candidate := range candidates {
+ nameScore, nameOk := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.Name))
+ idScore, idOk := fuzzyScore(normalizedQuery, normalizeSearchToken(candidate.ID))
+
+ score := 0
+ matched := false
+ switch {
+ case nameOk && idOk:
+ if nameScore <= idScore {
+ score = nameScore
+ } else {
+ score = idScore + 10
+ }
+ matched = true
+ case nameOk:
+ score = nameScore
+ matched = true
+ case idOk:
+ score = idScore + 10
+ matched = true
+ }
+
+ if matched {
+ ranked = append(ranked, rankedTemplateMatch{template: candidate, score: score})
+ }
+ }
+
+ sort.Slice(ranked, func(i, j int) bool {
+ if ranked[i].score != ranked[j].score {
+ return ranked[i].score < ranked[j].score
+ }
+ if ranked[i].template.Name != ranked[j].template.Name {
+ return ranked[i].template.Name < ranked[j].template.Name
+ }
+ return ranked[i].template.ID < ranked[j].template.ID
+ })
+
+ return ranked
+}
+
+func normalizeSearchToken(value string) string {
+ var builder strings.Builder
+ builder.Grow(len(value))
+
+ for _, r := range strings.ToLower(strings.TrimSpace(value)) {
+ if unicode.IsLetter(r) || unicode.IsDigit(r) {
+ builder.WriteRune(r)
+ }
+ }
+
+ return builder.String()
+}
+
+func fuzzyScore(query, target string) (int, bool) {
+ if query == "" || target == "" {
+ return 0, false
+ }
+ if query == target {
+ return 0, true
+ }
+
+ if strings.Contains(target, query) {
+ return 10 + absInt(len(target)-len(query)), true
+ }
+
+ if gap, ok := subsequenceGapPenalty(query, target); ok {
+ return 40 + gap, true
+ }
+
+ distance := levenshteinDistance(query, target)
+ maxDistance := maxInt(2, len(query)/3)
+ if distance <= maxDistance {
+ return 80 + (distance * 8) + absInt(len(target)-len(query)), true
+ }
+
+ return 0, false
+}
+
+func subsequenceGapPenalty(query, target string) (int, bool) {
+ q := []rune(query)
+ t := []rune(target)
+ if len(q) == 0 {
+ return 0, false
+ }
+
+ qIdx := 0
+ start := -1
+ for idx, r := range t {
+ if r != q[qIdx] {
+ continue
+ }
+ if start == -1 {
+ start = idx
+ }
+ qIdx++
+ if qIdx == len(q) {
+ span := (idx - start) + 1
+ gaps := span - len(q)
+ return gaps + absInt(len(t)-len(q)), true
+ }
+ }
+
+ return 0, false
+}
+
+func levenshteinDistance(a, b string) int {
+ ra := []rune(a)
+ rb := []rune(b)
+
+ if len(ra) == 0 {
+ return len(rb)
+ }
+ if len(rb) == 0 {
+ return len(ra)
+ }
+
+ prev := make([]int, len(rb)+1)
+ for j := 0; j <= len(rb); j++ {
+ prev[j] = j
+ }
+
+ for i := 1; i <= len(ra); i++ {
+ curr := make([]int, len(rb)+1)
+ curr[0] = i
+ for j := 1; j <= len(rb); j++ {
+ cost := 0
+ if ra[i-1] != rb[j-1] {
+ cost = 1
+ }
+ curr[j] = minInt(
+ curr[j-1]+1,
+ prev[j]+1,
+ prev[j-1]+cost,
+ )
+ }
+ prev = curr
+ }
+
+ return prev[len(rb)]
+}
+
+func isConfidentBestFuzzyMatch(matches []rankedTemplateMatch) bool {
+ if len(matches) == 0 {
+ return false
+ }
+
+ best := matches[0].score
+ if len(matches) == 1 {
+ return best <= 110
+ }
+
+ second := matches[1].score
+ return best <= 110 && (second-best) >= 8
+}
+
+func topTemplatesFromRankedMatches(matches []rankedTemplateMatch, limit int) []template.Template {
+ if limit <= 0 || len(matches) == 0 {
+ return nil
+ }
+ if len(matches) < limit {
+ limit = len(matches)
+ }
+
+ result := make([]template.Template, 0, limit)
+ for i := 0; i < limit; i++ {
+ result = append(result, matches[i].template)
+ }
+ return result
+}
+
+func minInt(values ...int) int {
+ if len(values) == 0 {
+ return 0
+ }
+ min := values[0]
+ for _, value := range values[1:] {
+ if value < min {
+ min = value
+ }
+ }
+ return min
+}
+
+func maxInt(a, b int) int {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func absInt(value int) int {
+ if value < 0 {
+ return -value
+ }
+ return value
+}
+
+func formatTemplateCandidates(matches []template.Template) string {
+ const previewLimit = 5
+
+ if len(matches) == 0 {
+ return "no matches"
+ }
+
+ limit := min(len(matches), previewLimit)
+
+ parts := make([]string, 0, limit+1)
+ for i := 0; i < limit; i++ {
+ parts = append(parts, fmt.Sprintf("%s (%s)", matches[i].Name, matches[i].ID))
+ }
+
+ if len(matches) > limit {
+ parts = append(parts, fmt.Sprintf("and %d more", len(matches)-limit))
+ }
+
+ return strings.Join(parts, ", ")
+}
+
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new template",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ content, err := os.ReadFile(templateCreateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", templateCreateFile, err)
+ }
+
+ req := template.CreateRequest{
+ Name: templateCreateName,
+ Description: templateCreateDescription,
+ Content: string(content),
+ }
+
+ if templateCreateEnvFile != "" {
+ envContent, err := os.ReadFile(templateCreateEnvFile)
+ if err != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, err)
+ }
+ req.EnvContent = string(envContent)
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.Templates(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create template: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[template.Template]
+ 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
+ }
+
+ output.Success("Template created successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <template-id>",
+ Short: "Update a template",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ req := template.UpdateRequest{
+ Name: templateUpdateName,
+ Description: templateUpdateDescription,
+ }
+
+ if templateUpdateFile != "" {
+ content, err := os.ReadFile(templateUpdateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, err)
+ }
+ req.Content = string(content)
+ }
+
+ if templateUpdateEnvFile != "" {
+ envContent, err := os.ReadFile(templateUpdateEnvFile)
+ if err != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, err)
+ }
+ req.EnvContent = string(envContent)
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.Template(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update template: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[template.Template]
+ 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
+ }
+
+ output.Success("Template updated successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ return nil
+ },
+}
+
+var downloadCmd = &cobra.Command{
+ Use: "download <template-id>",
+ Short: "Download template compose file",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.TemplateDownload(args[0]), nil)
+ if err != nil {
+ return fmt.Errorf("failed to download template: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to download template: %w", err)
+ }
+
+ var result base.ApiResponse[template.TemplateContent]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if templateDownloadOutput != "" {
+ dir := filepath.Dir(templateDownloadOutput)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return fmt.Errorf("failed to create directory %s: %w", dir, err)
+ }
+ if err := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); err != nil {
+ return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, err)
+ }
+ output.Success("Template downloaded to %s", templateDownloadOutput)
+ return nil
+ }
+
+ fmt.Print(result.Data.Content)
+ return nil
+ },
+}
+
+var defaultsSaveCmd = &cobra.Command{
+ Use: "defaults-save",
+ Short: "Save default templates",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ content, err := os.ReadFile(templateDefaultsSaveFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", templateDefaultsSaveFile, err)
+ }
+
+ req := template.SaveDefaultTemplatesRequest{
+ ComposeContent: string(content),
+ }
+
+ if templateDefaultsEnvFile != "" {
+ envContent, err := os.ReadFile(templateDefaultsEnvFile)
+ if err != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, err)
+ }
+ req.EnvContent = string(envContent)
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.TemplatesDefault(), req)
+ if err != nil {
+ return fmt.Errorf("failed to save default templates: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to save default templates: %w", err)
+ }
+
+ if jsonOutput {
+ var result base.ApiResponse[template.DefaultTemplatesResponse]
+ 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("Default templates saved successfully")
+ return nil
+ },
+}
+
+var variablesUpdateCmd = &cobra.Command{
+ Use: "variables-update",
+ Aliases: []string{"vars-update"},
+ Short: "Update template variables",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ content, err := os.ReadFile(templateVarsUpdateFile)
+ if err != nil {
+ return fmt.Errorf("failed to read file %s: %w", templateVarsUpdateFile, err)
+ }
+
+ var variables []env.Variable
+ if err := json.Unmarshal(content, &variables); err != nil {
+ return fmt.Errorf("failed to parse variables JSON: %w", err)
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.TemplatesVariables(), variables)
+ if err != nil {
+ return fmt.Errorf("failed to update variables: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update variables: %w", err)
+ }
+
+ if jsonOutput {
+ var result base.ApiResponse[[]env.Variable]
+ 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("Template variables updated successfully")
+ return nil
+ },
+}
+
+var registriesUpdateCmd = &cobra.Command{
+ Use: "registries-update <registry-id>",
+ Short: "Update a template registry",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ req := template.UpdateRegistryRequest{
+ Name: templateRegUpdateName,
+ URL: templateRegUpdateURL,
+ Description: templateRegUpdateDesc,
+ Enabled: templateRegUpdateEnabled && !templateRegUpdateDisabled,
+ }
+
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.TemplateRegistry(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update registry: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[template.TemplateRegistry]
+ 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
+ }
+
+ output.Success("Template registry updated successfully")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ return nil
+ },
+}
+
+var fetchCmd = &cobra.Command{
+ Use: "fetch",
+ Short: "Fetch remote template registries",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.TemplateFetch())
+ if err != nil {
+ return fmt.Errorf("failed to fetch templates: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to fetch templates: %w", err)
+ }
+
+ if jsonOutput {
+ var result base.ApiResponse[any]
+ 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("Remote templates fetched successfully")
+ return nil
+ },
+}
+
func init() {
TemplatesCmd.AddCommand(listCmd)
- TemplatesCmd.AddCommand(allCmd)
TemplatesCmd.AddCommand(defaultCmd)
TemplatesCmd.AddCommand(contentCmd)
TemplatesCmd.AddCommand(registriesCmd)
TemplatesCmd.AddCommand(variablesCmd)
TemplatesCmd.AddCommand(deleteCmd)
TemplatesCmd.AddCommand(deleteRegistryCmd)
+ TemplatesCmd.AddCommand(getCmd)
+ TemplatesCmd.AddCommand(createCmd)
+ TemplatesCmd.AddCommand(updateCmd)
+ TemplatesCmd.AddCommand(downloadCmd)
+ TemplatesCmd.AddCommand(defaultsSaveCmd)
+ TemplatesCmd.AddCommand(variablesUpdateCmd)
+ TemplatesCmd.AddCommand(registriesUpdateCmd)
+ TemplatesCmd.AddCommand(fetchCmd)
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of templates to show")
+ listCmd.Flags().BoolVarP(&templateListAll, "all", "a", false, "List all templates (including remote)")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
-
- allCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
defaultCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
contentCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
registriesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -424,4 +1157,49 @@ func init() {
deleteRegistryCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
deleteRegistryCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // get command flags
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // create command flags
+ createCmd.Flags().StringVar(&templateCreateName, "name", "", "Template name")
+ createCmd.Flags().StringVar(&templateCreateFile, "file", "", "Path to Docker Compose file")
+ createCmd.Flags().StringVar(&templateCreateDescription, "description", "", "Template description")
+ createCmd.Flags().StringVar(&templateCreateEnvFile, "env-file", "", "Path to environment file")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("name")
+ _ = createCmd.MarkFlagRequired("file")
+
+ // update command flags
+ updateCmd.Flags().StringVar(&templateUpdateName, "name", "", "Template name")
+ updateCmd.Flags().StringVar(&templateUpdateFile, "file", "", "Path to Docker Compose file")
+ updateCmd.Flags().StringVar(&templateUpdateDescription, "description", "", "Template description")
+ updateCmd.Flags().StringVar(&templateUpdateEnvFile, "env-file", "", "Path to environment file")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // download command flags
+ downloadCmd.Flags().StringVarP(&templateDownloadOutput, "output", "o", "", "Output file path")
+ downloadCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // defaults-save command flags
+ defaultsSaveCmd.Flags().StringVar(&templateDefaultsSaveFile, "file", "", "Path to compose content file")
+ defaultsSaveCmd.Flags().StringVar(&templateDefaultsEnvFile, "env-file", "", "Path to environment content file")
+ defaultsSaveCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = defaultsSaveCmd.MarkFlagRequired("file")
+
+ // variables-update command flags
+ variablesUpdateCmd.Flags().StringVar(&templateVarsUpdateFile, "file", "", "Path to variables JSON file")
+ variablesUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = variablesUpdateCmd.MarkFlagRequired("file")
+
+ // registries-update command flags
+ registriesUpdateCmd.Flags().StringVar(&templateRegUpdateName, "name", "", "Registry name")
+ registriesUpdateCmd.Flags().StringVar(&templateRegUpdateURL, "url", "", "Registry URL")
+ registriesUpdateCmd.Flags().StringVar(&templateRegUpdateDesc, "description", "", "Registry description")
+ registriesUpdateCmd.Flags().BoolVar(&templateRegUpdateEnabled, "enabled", false, "Enable registry")
+ registriesUpdateCmd.Flags().BoolVar(&templateRegUpdateDisabled, "disabled", false, "Disable registry")
+ registriesUpdateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // fetch command flags
+ fetchCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
}
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index 9d5366f38..c4569f975 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -27,6 +27,13 @@ var (
unusedOnlyFlag bool
)
+var (
+ volumeCreateName string
+ volumeCreateDriver string
+ volumeCreateOpts []string
+ volumeCreateLabels []string
+)
+
const maxPromptOptions = 20
// VolumesCmd is the parent command for volume operations
@@ -359,6 +366,73 @@ var usageCmd = &cobra.Command{
},
}
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a volume",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ req := volume.Create{
+ Name: volumeCreateName,
+ Driver: volumeCreateDriver,
+ }
+
+ if len(volumeCreateOpts) > 0 {
+ req.DriverOpts = make(map[string]string)
+ for _, opt := range volumeCreateOpts {
+ parts := strings.SplitN(opt, "=", 2)
+ if len(parts) == 2 {
+ req.DriverOpts[parts[0]] = parts[1]
+ }
+ }
+ }
+
+ if len(volumeCreateLabels) > 0 {
+ req.Labels = make(map[string]string)
+ for _, lbl := range volumeCreateLabels {
+ parts := strings.SplitN(lbl, "=", 2)
+ if len(parts) == 2 {
+ req.Labels[parts[0]] = parts[1]
+ }
+ }
+ }
+
+ path := types.Endpoints.Volumes(c.EnvID())
+ resp, err := c.Post(cmd.Context(), path, req)
+ if err != nil {
+ return fmt.Errorf("failed to create volume: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to create volume: %w", err)
+ }
+
+ var result base.ApiResponse[volume.Volume]
+ 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
+ }
+
+ output.Success("Volume %s created successfully", result.Data.Name)
+ output.KeyValue("Name", result.Data.Name)
+ output.KeyValue("Driver", result.Data.Driver)
+ output.KeyValue("Mountpoint", result.Data.Mountpoint)
+ return nil
+ },
+}
+
func init() {
VolumesCmd.AddCommand(listCmd)
VolumesCmd.AddCommand(getCmd)
@@ -367,6 +441,7 @@ func init() {
VolumesCmd.AddCommand(pruneCmd)
VolumesCmd.AddCommand(sizesCmd)
VolumesCmd.AddCommand(usageCmd)
+ VolumesCmd.AddCommand(createCmd)
// List command flags
listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of volumes to show")
@@ -389,6 +464,14 @@ func init() {
countsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
sizesCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
usageCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ // Create command flags
+ createCmd.Flags().StringVar(&volumeCreateName, "name", "", "Volume name")
+ createCmd.Flags().StringVar(&volumeCreateDriver, "driver", "", "Volume driver")
+ createCmd.Flags().StringArrayVar(&volumeCreateOpts, "opt", nil, "Driver option (KEY=VALUE)")
+ createCmd.Flags().StringArrayVar(&volumeCreateLabels, "label", nil, "Label (KEY=VALUE)")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("name")
}
func resolveVolume(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*volume.Volume, error) {