diff --git a/docs/README.md b/docs/README.md index f599254..70d976c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -170,6 +170,18 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n promotion connection list`](n8n_promotion_connection_list.md) | List promotion connections | | [`n8n promotion connection update`](n8n_promotion_connection_update.md) | Update a promotion connection | | [`n8n promotion connection`](n8n_promotion_connection.md) | Manage promotion connections | +| [`n8n promotion environment connect`](n8n_promotion_environment_connect.md) | Prepare the local checkout of a promotion environment | +| [`n8n promotion environment create`](n8n_promotion_environment_create.md) | Create a promotion environment | +| [`n8n promotion environment delete`](n8n_promotion_environment_delete.md) | Permanently delete a promotion environment | +| [`n8n promotion environment disconnect`](n8n_promotion_environment_disconnect.md) | Remove the local checkout of a promotion environment | +| [`n8n promotion environment get`](n8n_promotion_environment_get.md) | Show one promotion environment | +| [`n8n promotion environment list`](n8n_promotion_environment_list.md) | List promotion environments | +| [`n8n promotion environment project add`](n8n_promotion_environment_project_add.md) | Link a project to a promotion environment | +| [`n8n promotion environment project list`](n8n_promotion_environment_project_list.md) | List projects linked to a promotion environment | +| [`n8n promotion environment project remove`](n8n_promotion_environment_project_remove.md) | Unlink a project from a promotion environment | +| [`n8n promotion environment project`](n8n_promotion_environment_project.md) | Manage projects linked to a promotion environment | +| [`n8n promotion environment update`](n8n_promotion_environment_update.md) | Update a promotion environment | +| [`n8n promotion environment`](n8n_promotion_environment.md) | Manage promotion environments (n8n 2.46 and later) | | [`n8n promotion project add`](n8n_promotion_project_add.md) | Add a project to a promotion connection | | [`n8n promotion project apply-continue`](n8n_promotion_project_apply-continue.md) | Continue a reviewed project apply after binding setup | | [`n8n promotion project apply`](n8n_promotion_project_apply.md) | Apply selected workflow changes from a project's branch | @@ -187,7 +199,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n promotion provider repositories`](n8n_promotion_provider_repositories.md) | List repositories available to a GitLab provider | | [`n8n promotion provider update`](n8n_promotion_provider_update.md) | Update a promotion provider | | [`n8n promotion provider`](n8n_promotion_provider.md) | Manage promotion providers | -| [`n8n promotion`](n8n_promotion.md) | Manage promotion providers, connections, and apply/promote sync | +| [`n8n promotion`](n8n_promotion.md) | Manage promotion providers, environments, connections, and apply/promote sync | | [`n8n role create`](n8n_role_create.md) | Create a custom role | | [`n8n role delete`](n8n_role_delete.md) | Permanently delete a custom role | | [`n8n role get`](n8n_role_get.md) | Get one role | diff --git a/docs/n8n.md b/docs/n8n.md index d57938b..9dc46d3 100644 --- a/docs/n8n.md +++ b/docs/n8n.md @@ -70,7 +70,7 @@ n8n [flags] * [n8n otel](n8n_otel.md) - Manage OpenTelemetry tracing settings * [n8n package](n8n_package.md) - Export and import n8n packages (beta) * [n8n project](n8n_project.md) - Manage projects and their members -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n role](n8n_role.md) - Manage global and project roles * [n8n role-mapping](n8n_role-mapping.md) - Manage identity-provider role-mapping rules * [n8n saml](n8n_saml.md) - Manage licensed SAML SSO settings diff --git a/docs/n8n_promotion.md b/docs/n8n_promotion.md index c74d3ea..deaadcd 100644 --- a/docs/n8n_promotion.md +++ b/docs/n8n_promotion.md @@ -1,28 +1,37 @@ ## n8n promotion -Manage promotion providers, connections, and apply/promote sync +Manage promotion providers, environments, connections, and apply/promote sync ### Synopsis Manage Promotions Git sync and selected project workflows. -Start with 'provider list' to find a provider, then 'connection list' -to find a connection. Create a provider first, then a connection on -it, then a config per direction under 'config', clone each checkout -under 'checkout', link team projects to a projects-scope connection -under 'project', then 'promote' the instance to the remote or 'apply' -the remote into the instance. For selected workflows, start with -project changes, then project apply or project promote. Use apply-continue + +n8n 2.46 and later: start with 'provider list' to find a provider, +then 'environment list' to find an environment. An environment is one +remote for one direction: create one per direction on a provider with +'environment create', prepare its checkout with 'environment connect', +and link team projects to a projects-scope environment under +'environment project'. 'promote', 'apply', and the project selection +commands still address connections. + +Older instances serve connections instead: 'connection list' finds a +connection; create a provider first, then a connection on it, then a +config per direction under 'config', clone each checkout under +'checkout', link team projects to a projects-scope connection under +'project', then 'promote' the instance to the remote or 'apply' the +remote into the instance. For selected workflows, start with project +changes, then project apply or project promote. Use apply-continue after resolving a blocked apply. 'promote' and 'apply' run on the instance connection. 'promote' commits and pushes every team project to the remote; 'apply' checks the package and imports with overwrite behavior, creating, updating, or removing content to match, or reports why it is blocked and writes -nothing. Both mutate versioned -content and ask for confirmation. Config and connection removal can -remove local checkouts. This is the upstream Promotions generation: an -instance that serves GitConnections instead answers 404 or 503, which -reads as the availability diagnostic. +nothing. Both mutate versioned content and ask for confirmation. +Config, connection, and environment removal can remove local +checkouts. This is the upstream Promotions generation: an instance +that serves GitConnections instead answers 404 or 503, which reads as +the availability diagnostic. ``` n8n promotion [flags] @@ -32,6 +41,8 @@ n8n promotion [flags] ``` n8n promotion provider list + n8n promotion environment list + n8n promotion environment connect ENVIRONMENT_ID n8n promotion connection list n8n promotion provider create --input provider.json n8n promotion connection create --input connection.json @@ -56,6 +67,7 @@ n8n promotion [flags] * [n8n promotion checkout](n8n_promotion_checkout.md) - Manage promotion checkouts * [n8n promotion config](n8n_promotion_config.md) - Manage promotion direction configs * [n8n promotion connection](n8n_promotion_connection.md) - Manage promotion connections +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) * [n8n promotion project](n8n_promotion_project.md) - Manage projects linked to a promotion connection * [n8n promotion promote](n8n_promotion_promote.md) - Promote team projects to the Git remote * [n8n promotion provider](n8n_promotion_provider.md) - Manage promotion providers diff --git a/docs/n8n_promotion_apply-continue.md b/docs/n8n_promotion_apply-continue.md index 599d26b..64afbf0 100644 --- a/docs/n8n_promotion_apply-continue.md +++ b/docs/n8n_promotion_apply-continue.md @@ -62,5 +62,5 @@ n8n promotion apply-continue [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync diff --git a/docs/n8n_promotion_apply.md b/docs/n8n_promotion_apply.md index b4f9383..18e45b4 100644 --- a/docs/n8n_promotion_apply.md +++ b/docs/n8n_promotion_apply.md @@ -56,5 +56,5 @@ n8n promotion apply [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync diff --git a/docs/n8n_promotion_checkout.md b/docs/n8n_promotion_checkout.md index bbaf1f2..e9175fe 100644 --- a/docs/n8n_promotion_checkout.md +++ b/docs/n8n_promotion_checkout.md @@ -31,7 +31,7 @@ n8n promotion checkout [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n promotion checkout clone](n8n_promotion_checkout_clone.md) - Clone one promotion checkout locally * [n8n promotion checkout disconnect](n8n_promotion_checkout_disconnect.md) - Remove one promotion checkout diff --git a/docs/n8n_promotion_config.md b/docs/n8n_promotion_config.md index fbe4d81..289a336 100644 --- a/docs/n8n_promotion_config.md +++ b/docs/n8n_promotion_config.md @@ -31,7 +31,7 @@ n8n promotion config [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n promotion config apply](n8n_promotion_config_apply.md) - Manage the apply direction config * [n8n promotion config delete](n8n_promotion_config_delete.md) - Delete one direction config * [n8n promotion config promote](n8n_promotion_config_promote.md) - Manage the promote direction config diff --git a/docs/n8n_promotion_connection.md b/docs/n8n_promotion_connection.md index c30a101..358cc6d 100644 --- a/docs/n8n_promotion_connection.md +++ b/docs/n8n_promotion_connection.md @@ -5,7 +5,8 @@ Manage promotion connections ### Synopsis Manage promotion connections: one remote plus its two direction -configs. Start with 'list' to find the connection ID, then 'get' to +configs. n8n 2.46 and later replaced connections with environments: +use 'n8n promotion environment' there. Start with 'list' to find the connection ID, then 'get' to read it, 'create' to add one on a provider, or 'update' to change its name, target, or provider. @@ -33,7 +34,7 @@ n8n promotion connection [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n promotion connection create](n8n_promotion_connection_create.md) - Create a promotion connection * [n8n promotion connection delete](n8n_promotion_connection_delete.md) - Permanently delete a promotion connection * [n8n promotion connection get](n8n_promotion_connection_get.md) - Show one promotion connection diff --git a/docs/n8n_promotion_environment.md b/docs/n8n_promotion_environment.md new file mode 100644 index 0000000..2170af2 --- /dev/null +++ b/docs/n8n_promotion_environment.md @@ -0,0 +1,53 @@ +## n8n promotion environment + +Manage promotion environments (n8n 2.46 and later) + +### Synopsis + +Manage promotion environments: one remote, one direction (apply or +promote), its settings, and its local checkout. n8n 2.46 replaced +connections with environments; on older instances use 'n8n promotion +connection' instead. + +Start with 'list' to find the environment ID, then 'get' to read it, +'create' to add one on a provider, or 'update' to change its name, +provider, remote, or settings. 'connect' prepares the local checkout +and 'disconnect' removes it. Link team projects to a projects-scope +environment under 'project'. The instance can have one environment for +each direction. + +Deleting an environment removes its project links and local checkout; +its provider is kept and nothing in Git changes. + +``` +n8n promotion environment [flags] +``` + +### Examples + +``` + n8n promotion environment list + n8n promotion environment get ENVIRONMENT_ID + n8n promotion environment create --input environment.json + n8n promotion environment connect ENVIRONMENT_ID + n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID +``` + +### Options + +``` + -h, --help help for environment +``` + +### SEE ALSO + +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync +* [n8n promotion environment connect](n8n_promotion_environment_connect.md) - Prepare the local checkout of a promotion environment +* [n8n promotion environment create](n8n_promotion_environment_create.md) - Create a promotion environment +* [n8n promotion environment delete](n8n_promotion_environment_delete.md) - Permanently delete a promotion environment +* [n8n promotion environment disconnect](n8n_promotion_environment_disconnect.md) - Remove the local checkout of a promotion environment +* [n8n promotion environment get](n8n_promotion_environment_get.md) - Show one promotion environment +* [n8n promotion environment list](n8n_promotion_environment_list.md) - List promotion environments +* [n8n promotion environment project](n8n_promotion_environment_project.md) - Manage projects linked to a promotion environment +* [n8n promotion environment update](n8n_promotion_environment_update.md) - Update a promotion environment + diff --git a/docs/n8n_promotion_environment_connect.md b/docs/n8n_promotion_environment_connect.md new file mode 100644 index 0000000..fc3cdff --- /dev/null +++ b/docs/n8n_promotion_environment_connect.md @@ -0,0 +1,40 @@ +## n8n promotion environment connect + +Prepare the local checkout of a promotion environment + +### Synopsis + +Prepare one promotion environment on the instance that handles the +request; for a Git provider this clones the configured branch into +local storage. Connecting one environment does not make another +ready. + +Connecting is safe to repeat and changes no project content by itself, +so it needs no confirmation. Connect again after 'get' reports a +checkout that does not match the environment. Requires +gitConnection:clone. + +``` +n8n promotion environment connect [flags] +``` + +### Examples + +``` + n8n promotion environment connect ENVIRONMENT_ID + n8n promotion environment connect ENVIRONMENT_ID --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for connect + --output string output format: text or json (JSON is the checkout returned by the API) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_create.md b/docs/n8n_promotion_environment_create.md new file mode 100644 index 0000000..920823c --- /dev/null +++ b/docs/n8n_promotion_environment_create.md @@ -0,0 +1,49 @@ +## n8n promotion environment create + +Create a promotion environment + +### Synopsis + +Create one promotion environment from strict JSON supplied by --input. +Required fields are name (at most 128 characters), scope (instance or +projects), providerId, remote {"schemaVersion":1,"remoteUrl":"..."}, +direction (apply or promote), and settings matching the direction: +apply {"schemaVersion":1,"branchName":"main"} or promote +{"schemaVersion":1,"baseBranchName":"main", +"createBranchOnPromotion":false}. The instance can have one +environment for each direction. + +On a gitlab provider the remote URL must belong to the provider: the +environment stores only the repository path and derives remoteUrl from +the provider base URL. Read-only fields from 'environment get --output +json' (id, provider, checkout, createdAt, updatedAt, +remote.repositoryPath) are dropped with a note on stderr; other unknown +fields and trailing JSON documents are refused before transport. +Requires gitConnection:create. Follow with 'n8n promotion environment +connect ENVIRONMENT_ID'. + +``` +n8n promotion environment create [flags] +``` + +### Examples + +``` + n8n promotion environment create --input environment.json + printf '%s\n' '{"name":"prod","scope":"instance","providerId":"PROVIDER_ID","remote":{"schemaVersion":1,"remoteUrl":"git@example.com:org/repo.git"},"direction":"apply","settings":{"schemaVersion":1,"branchName":"main"}}' | n8n promotion environment create --input - +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for create + --input string promotion environment JSON file path, or - for stdin (required; maximum 1 MiB) + --output string output format: text or json (JSON is the environment returned by the API) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_delete.md b/docs/n8n_promotion_environment_delete.md new file mode 100644 index 0000000..cde3e1e --- /dev/null +++ b/docs/n8n_promotion_environment_delete.md @@ -0,0 +1,42 @@ +## n8n promotion environment delete + +Permanently delete a promotion environment + +### Synopsis + +Permanently delete one promotion environment with its project links and +local checkout. Its provider is kept and nothing in Git changes, but +linked projects fall back to the instance environment, and promote or +apply for that direction stops working until an environment is +created and connected again. This cannot be undone. + +To keep the environment and drop only the checkout, use 'n8n promotion +environment disconnect' instead. Interactive runs ask for +confirmation; non-interactive runs require --yes. Requires +gitConnection:delete. + +``` +n8n promotion environment delete [flags] +``` + +### Examples + +``` + n8n promotion environment delete ENVIRONMENT_ID + n8n promotion environment delete ENVIRONMENT_ID --yes --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for delete + --output string output format: text or json (JSON is the deletion acknowledgement) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm permanent environment, project link, and checkout deletion without prompting (required when stdin is not interactive) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_disconnect.md b/docs/n8n_promotion_environment_disconnect.md new file mode 100644 index 0000000..5ac460f --- /dev/null +++ b/docs/n8n_promotion_environment_disconnect.md @@ -0,0 +1,39 @@ +## n8n promotion environment disconnect + +Remove the local checkout of a promotion environment + +### Synopsis + +Remove the local checkout of one promotion environment. The +environment, its credentials, its trusted SSH host keys, and its +project links are kept, but promote and apply through it stop working +until 'connect' runs again. + +Interactive runs ask for confirmation; non-interactive runs require +--yes. Requires gitConnection:clone. + +``` +n8n promotion environment disconnect [flags] +``` + +### Examples + +``` + n8n promotion environment disconnect ENVIRONMENT_ID + n8n promotion environment disconnect ENVIRONMENT_ID --yes --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for disconnect + --output string output format: text or json (JSON is the checkout returned by the API) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm checkout removal without prompting (required when stdin is not interactive) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_get.md b/docs/n8n_promotion_environment_get.md new file mode 100644 index 0000000..bcfd2ae --- /dev/null +++ b/docs/n8n_promotion_environment_get.md @@ -0,0 +1,36 @@ +## n8n promotion environment get + +Show one promotion environment + +### Synopsis + +Show one promotion environment by ID: its name, scope, direction, +remote, provider, settings, local checkout state, and timestamps. +Secrets are never returned. Find the ID with 'n8n promotion environment +list'. The --output json document can be edited and passed to 'update' +as is: its read-only fields are dropped. Requires gitConnection:read. + +``` +n8n promotion environment get [flags] +``` + +### Examples + +``` + n8n promotion environment get ENVIRONMENT_ID + n8n promotion environment get ENVIRONMENT_ID --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for get + --output string output format: text or json (JSON is the environment object) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_list.md b/docs/n8n_promotion_environment_list.md new file mode 100644 index 0000000..7c819a3 --- /dev/null +++ b/docs/n8n_promotion_environment_list.md @@ -0,0 +1,54 @@ +## n8n promotion environment list + +List promotion environments + +### Synopsis + +List the promotion environments visible to the selected credential, +one cursor-paginated page at a time. Filter with --scope (instance or +projects), --direction (apply or promote), and --provider-id; filters +are preserved across --all. Use --all to follow every cursor, capped at +10,000 environments. + +Use a returned ID with get, update, delete, connect, disconnect, and +project. Requires gitConnection:list. + +With --all, JSON output adds a collection object. Its truncated field is true, +and a warning goes to stderr, when the walk stopped at the 10,000-item limit +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n promotion environment list [flags] +``` + +### Examples + +``` + n8n promotion environment list + n8n promotion environment list --scope instance --direction apply + n8n promotion environment list --provider-id PROVIDER_ID --output json + n8n promotion environment list --all +``` + +### Options + +``` + --all follow every page instead of one (maximum 10,000 environments; hitting it warns and sets JSON collection.truncated) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string pagination cursor returned by a previous list (default: the first page) + --direction string filter by direction: apply or promote (default: both directions) + -h, --help help for list + --limit int environments per API page, 1 to 250 (default: server default of 100) + --output string output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all) (default "text") + --provider-id string filter by provider ID from 'n8n promotion provider list' (default: all providers) + --scope string filter by environment scope: instance or projects (default: all scopes) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_project.md b/docs/n8n_promotion_environment_project.md new file mode 100644 index 0000000..d7a0386 --- /dev/null +++ b/docs/n8n_promotion_environment_project.md @@ -0,0 +1,42 @@ +## n8n promotion environment project + +Manage projects linked to a promotion environment + +### Synopsis + +Manage which team projects a projects-scope promotion environment +syncs. A project can have one environment for each direction; a +direction without a project environment uses the instance environment. +Start with 'list' to see the linked project IDs, then 'add' a project +or 'remove' one. + +Removing unlinks the project; its instance content is untouched. +Project IDs come from 'n8n project list'. Listing needs +gitConnection:read; adding and removing need +gitConnection:manageProjects. + +``` +n8n promotion environment project [flags] +``` + +### Examples + +``` + n8n promotion environment project list ENVIRONMENT_ID + n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID + n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID --yes +``` + +### Options + +``` + -h, --help help for project +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) +* [n8n promotion environment project add](n8n_promotion_environment_project_add.md) - Link a project to a promotion environment +* [n8n promotion environment project list](n8n_promotion_environment_project_list.md) - List projects linked to a promotion environment +* [n8n promotion environment project remove](n8n_promotion_environment_project_remove.md) - Unlink a project from a promotion environment + diff --git a/docs/n8n_promotion_environment_project_add.md b/docs/n8n_promotion_environment_project_add.md new file mode 100644 index 0000000..4cfff05 --- /dev/null +++ b/docs/n8n_promotion_environment_project_add.md @@ -0,0 +1,36 @@ +## n8n promotion environment project add + +Link a project to a promotion environment + +### Synopsis + +Link one team project to one projects-scope promotion environment, so +project-level sync in that direction uses this environment instead of +the instance environment. A project can have one environment for each +direction: adding a project that already has one for this direction +answers 409. Requires gitConnection:manageProjects. + +``` +n8n promotion environment project add [flags] +``` + +### Examples + +``` + n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID + n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for add + --output string output format: text or json (JSON is the project link returned by the API) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment project](n8n_promotion_environment_project.md) - Manage projects linked to a promotion environment + diff --git a/docs/n8n_promotion_environment_project_list.md b/docs/n8n_promotion_environment_project_list.md new file mode 100644 index 0000000..0ed08f5 --- /dev/null +++ b/docs/n8n_promotion_environment_project_list.md @@ -0,0 +1,34 @@ +## n8n promotion environment project list + +List projects linked to a promotion environment + +### Synopsis + +List the team projects linked to one projects-scope promotion +environment. Find the environment ID with 'n8n promotion environment +list --scope projects'. Requires gitConnection:read. + +``` +n8n promotion environment project list [flags] +``` + +### Examples + +``` + n8n promotion environment project list ENVIRONMENT_ID + n8n promotion environment project list ENVIRONMENT_ID --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for list + --output string output format: text or json (JSON is the projectIds object) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion environment project](n8n_promotion_environment_project.md) - Manage projects linked to a promotion environment + diff --git a/docs/n8n_promotion_environment_project_remove.md b/docs/n8n_promotion_environment_project_remove.md new file mode 100644 index 0000000..261f688 --- /dev/null +++ b/docs/n8n_promotion_environment_project_remove.md @@ -0,0 +1,40 @@ +## n8n promotion environment project remove + +Unlink a project from a promotion environment + +### Synopsis + +Unlink one project from one promotion environment. The project itself +and its instance content are untouched; only the sync link goes away, +so project-level sync in that direction falls back to the instance +environment. Re-link it later with 'n8n promotion environment project +add'. + +Interactive runs ask for confirmation; non-interactive runs require +--yes. Requires gitConnection:manageProjects. + +``` +n8n promotion environment project remove [flags] +``` + +### Examples + +``` + n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID + n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID --yes --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for remove + --output string output format: text or json (JSON is the unlinking acknowledgement) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm project unlinking without prompting (required when stdin is not interactive) +``` + +### SEE ALSO + +* [n8n promotion environment project](n8n_promotion_environment_project.md) - Manage projects linked to a promotion environment + diff --git a/docs/n8n_promotion_environment_update.md b/docs/n8n_promotion_environment_update.md new file mode 100644 index 0000000..e33199b --- /dev/null +++ b/docs/n8n_promotion_environment_update.md @@ -0,0 +1,50 @@ +## n8n promotion environment update + +Update a promotion environment + +### Synopsis + +Update one promotion environment from strict JSON supplied by --input. +Only the fields present are changed; at least one of name, providerId, +remote, or settings is required. A remote replaces the whole saved +remote and settings replace the whole saved settings, which must match +the environment's direction (promote always needs +createBranchOnPromotion). Scope and direction cannot change. + +Start from 'n8n promotion environment get ID --output json': read-only +fields (id, scope, direction, provider, checkout, createdAt, updatedAt, +remote.repositoryPath) are dropped with a note on stderr, and a +direction in the document is used to check the settings first. A 409 +means the provider changed during the update: reload and retry. + +A new remote or branch can leave the local checkout stale, so +interactive runs ask for confirmation; non-interactive runs and +--input - require --yes. Requires gitConnection:update. + +``` +n8n promotion environment update [flags] +``` + +### Examples + +``` + n8n promotion environment update ENVIRONMENT_ID --input environment-update.json + printf '%s\n' '{"name":"staging"}' | n8n promotion environment update ENVIRONMENT_ID --input - --yes + n8n promotion environment update ENVIRONMENT_ID --input environment.json --yes --output json +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for update + --input string promotion environment update JSON file path, or - for stdin (required; maximum 1 MiB; - requires --yes) + --output string output format: text or json (JSON is the environment returned by the API) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm the environment update without prompting (required when stdin is not interactive or with --input -) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_project.md b/docs/n8n_promotion_project.md index 21c34cb..dbdedb9 100644 --- a/docs/n8n_promotion_project.md +++ b/docs/n8n_promotion_project.md @@ -39,7 +39,7 @@ n8n promotion project [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n promotion project add](n8n_promotion_project_add.md) - Add a project to a promotion connection * [n8n promotion project apply](n8n_promotion_project_apply.md) - Apply selected workflow changes from a project's branch * [n8n promotion project apply-continue](n8n_promotion_project_apply-continue.md) - Continue a reviewed project apply after binding setup diff --git a/docs/n8n_promotion_promote.md b/docs/n8n_promotion_promote.md index f4e9ad9..2d71f67 100644 --- a/docs/n8n_promotion_promote.md +++ b/docs/n8n_promotion_promote.md @@ -49,5 +49,5 @@ n8n promotion promote [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync diff --git a/docs/n8n_promotion_provider.md b/docs/n8n_promotion_provider.md index 401390a..fca7d72 100644 --- a/docs/n8n_promotion_provider.md +++ b/docs/n8n_promotion_provider.md @@ -35,7 +35,7 @@ n8n promotion provider [flags] ### SEE ALSO -* [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync * [n8n promotion provider branches](n8n_promotion_provider_branches.md) - List branches of a GitLab repository * [n8n promotion provider create](n8n_promotion_provider_create.md) - Create a promotion provider * [n8n promotion provider delete](n8n_promotion_provider_delete.md) - Permanently delete a promotion provider diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 18d7b35..8da9247 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -276,6 +276,18 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"promotion", "provider", "get"}, {"promotion", "provider", "update"}, {"promotion", "provider", "delete"}, + {"promotion", "environment"}, + {"promotion", "environment", "list"}, + {"promotion", "environment", "create"}, + {"promotion", "environment", "get"}, + {"promotion", "environment", "update"}, + {"promotion", "environment", "delete"}, + {"promotion", "environment", "connect"}, + {"promotion", "environment", "disconnect"}, + {"promotion", "environment", "project"}, + {"promotion", "environment", "project", "list"}, + {"promotion", "environment", "project", "add"}, + {"promotion", "environment", "project", "remove"}, {"promotion", "connection"}, {"promotion", "connection", "list"}, {"promotion", "connection", "create"}, diff --git a/internal/cli/promotion.go b/internal/cli/promotion.go index 72c7020..6417f15 100644 --- a/internal/cli/promotion.go +++ b/internal/cli/promotion.go @@ -28,26 +28,35 @@ const ( func newPromotionCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "promotion", - Short: "Manage promotion providers, connections, and apply/promote sync", - Long: "Manage Promotions Git sync and selected project workflows.\n" + - "Start with 'provider list' to find a provider, then 'connection list'\n" + - "to find a connection. Create a provider first, then a connection on\n" + - "it, then a config per direction under 'config', clone each checkout\n" + - "under 'checkout', link team projects to a projects-scope connection\n" + - "under 'project', then 'promote' the instance to the remote or 'apply'\n" + - "the remote into the instance. For selected workflows, start with\n" + - "project changes, then project apply or project promote. Use apply-continue\n" + + Short: "Manage promotion providers, environments, connections, and apply/promote sync", + Long: "Manage Promotions Git sync and selected project workflows.\n\n" + + "n8n 2.46 and later: start with 'provider list' to find a provider,\n" + + "then 'environment list' to find an environment. An environment is one\n" + + "remote for one direction: create one per direction on a provider with\n" + + "'environment create', prepare its checkout with 'environment connect',\n" + + "and link team projects to a projects-scope environment under\n" + + "'environment project'. 'promote', 'apply', and the project selection\n" + + "commands still address connections.\n\n" + + "Older instances serve connections instead: 'connection list' finds a\n" + + "connection; create a provider first, then a connection on it, then a\n" + + "config per direction under 'config', clone each checkout under\n" + + "'checkout', link team projects to a projects-scope connection under\n" + + "'project', then 'promote' the instance to the remote or 'apply' the\n" + + "remote into the instance. For selected workflows, start with project\n" + + "changes, then project apply or project promote. Use apply-continue\n" + "after resolving a blocked apply.\n\n" + "'promote' and 'apply' run on the instance connection. 'promote'\n" + "commits and pushes every team project to the remote; 'apply' checks the\n" + "package and imports with overwrite behavior, creating, updating, or\n" + "removing content to match, or reports why it is blocked and writes\n" + - "nothing. Both mutate versioned\n" + - "content and ask for confirmation. Config and connection removal can\n" + - "remove local checkouts. This is the upstream Promotions generation: an\n" + - "instance that serves GitConnections instead answers 404 or 503, which\n" + - "reads as the availability diagnostic.", + "nothing. Both mutate versioned content and ask for confirmation.\n" + + "Config, connection, and environment removal can remove local\n" + + "checkouts. This is the upstream Promotions generation: an instance\n" + + "that serves GitConnections instead answers 404 or 503, which reads as\n" + + "the availability diagnostic.", Example: " n8n promotion provider list\n" + + " n8n promotion environment list\n" + + " n8n promotion environment connect ENVIRONMENT_ID\n" + " n8n promotion connection list\n" + " n8n promotion provider create --input provider.json\n" + " n8n promotion connection create --input connection.json\n" + @@ -61,6 +70,7 @@ func newPromotionCommand(opts Options) *cobra.Command { } cmd.AddCommand( newPromotionProviderCommand(opts), + newPromotionEnvironmentCommand(opts), newPromotionConnectionCommand(opts), newPromotionConfigCommand(opts), newPromotionCheckoutCommand(opts), @@ -526,7 +536,8 @@ func newPromotionConnectionCommand(opts Options) *cobra.Command { Use: "connection", Short: "Manage promotion connections", Long: "Manage promotion connections: one remote plus its two direction\n" + - "configs. Start with 'list' to find the connection ID, then 'get' to\n" + + "configs. n8n 2.46 and later replaced connections with environments:\n" + + "use 'n8n promotion environment' there. Start with 'list' to find the connection ID, then 'get' to\n" + "read it, 'create' to add one on a provider, or 'update' to change its\n" + "name, target, or provider.\n\n" + "Deleting a connection can remove its local checkouts. Linked projects\n" + @@ -623,7 +634,7 @@ func runPromotionConnectionList(ctx context.Context, opts Options, f promotionCo page, err = client.ListPromotionConnections(ctx, listOpts) } if err != nil { - return promotionAPIError(err, resolution, "connection list", promotionSubject{}) + return promotionAPIError(err, resolution, "connection list", promotionSubject{alt: promotionConnectionAlt}) } if f.output == outputJSON { err = writePageJSON(opts.Streams.Out, page, collection) @@ -718,7 +729,9 @@ func runPromotionConnectionCreate(ctx context.Context, opts Options, f promotion } created, err := client.CreatePromotionConnection(ctx, request) if err != nil { - return promotionAPIError(err, resolution, "connection create", promotionProviderSubject(request.ProviderID)) + subject := promotionProviderSubject(request.ProviderID) + subject.alt = promotionConnectionAlt + return promotionAPIError(err, resolution, "connection create", subject) } return writePromotionConnectionResult(opts, resolution, "Created", created, f.output) } @@ -1854,8 +1867,11 @@ type promotionMutation struct { Action string `json:"action"` ProviderID string `json:"providerId,omitempty"` ConnectionID string `json:"connectionId,omitempty"` - ProjectID string `json:"projectId,omitempty"` - Direction string `json:"direction,omitempty"` + // EnvironmentID is set by environment commands, which never set + // ConnectionID. + EnvironmentID string `json:"environmentId,omitempty"` + ProjectID string `json:"projectId,omitempty"` + Direction string `json:"direction,omitempty"` } func writePromotionMutation(opts Options, resolution config.Resolution, result promotionMutation, output string) error { @@ -1870,6 +1886,9 @@ func writePromotionMutation(opts Options, resolution config.Resolution, result p if result.ConnectionID != "" { fmt.Fprintf(tw, "Connection:\t%s\n", result.ConnectionID) } + if result.EnvironmentID != "" { + fmt.Fprintf(tw, "Environment:\t%s\n", result.EnvironmentID) + } if result.ProjectID != "" { fmt.Fprintf(tw, "Project:\t%s\n", result.ProjectID) } @@ -2121,6 +2140,17 @@ func truncatedPromotionSecret(value string) string { type promotionSubject struct { what string // e.g. promotion connection "conn-1" find string // the command that lists valid IDs + alt string // the other generation's command group, hinted on a bare 404 +} + +// altHint is the clause a bare 404 appends: the route may exist only in the +// other Promotions generation (connections before n8n 2.46, environments +// from 2.46). +func (s promotionSubject) altHint() string { + if s.alt == "" { + return "" + } + return "; " + s.alt } func promotionProviderSubject(id string) promotionSubject { @@ -2128,13 +2158,14 @@ func promotionProviderSubject(id string) promotionSubject { } func promotionConnectionSubject(id string) promotionSubject { - return promotionSubject{what: fmt.Sprintf("promotion connection %q", id), find: "'n8n promotion connection list'"} + return promotionSubject{what: fmt.Sprintf("promotion connection %q", id), find: "'n8n promotion connection list'", alt: promotionConnectionAlt} } func promotionProjectLinkSubject(id, projectID string) promotionSubject { return promotionSubject{ what: fmt.Sprintf("promotion connection %q or project %q", id, projectID), find: "'n8n promotion connection list' and 'n8n project list'", + alt: promotionConnectionAlt, } } @@ -2144,6 +2175,16 @@ func promotionAPIError(err error, resolution config.Resolution, action string, s return fmt.Errorf("%s rejected the promotion provider delete (409): the provider still has attached connections, so nothing changed; remove them first, then delete the provider: %w", resolution.URL, err) case n8n.IsConflict(err) && action == "project add": return fmt.Errorf("%s rejected the promotion project add (409): the project is already linked to a connection, so nothing changed; remove it there first, then add it here: %w", resolution.URL, err) + case n8n.IsConflict(err) && action == "environment create": + return fmt.Errorf("%s rejected the promotion environment create (409): the instance already has an environment for this direction, so nothing changed; find it with 'n8n promotion environment list --direction DIRECTION' and update it instead: %w", resolution.URL, err) + case n8n.IsConflict(err) && action == "environment update": + return fmt.Errorf("%s rejected the promotion environment update (409): the provider changed during the update, so nothing changed; reload it with 'n8n promotion environment get' and retry: %w", resolution.URL, err) + case n8n.IsConflict(err) && action == "environment project add": + return fmt.Errorf("%s rejected the promotion environment project add (409): the project already has an environment for this direction, so nothing changed; unlink it there with 'n8n promotion environment project remove', then add it here: %w", resolution.URL, err) + case n8n.IsConflict(err) && strings.HasPrefix(action, "environment "): + return fmt.Errorf("%s rejected the promotion %s (409): the environment or project is in a conflicting state, so nothing changed; reload it with 'n8n promotion environment get' and retry: %w", resolution.URL, action, err) + case n8n.IsStatus(err, http.StatusUnprocessableEntity) && strings.HasPrefix(action, "environment "): + return fmt.Errorf("%s rejected the promotion %s (422): the instance cannot use the environment as configured; check that the remote URL belongs to the provider, the branch exists, the provider credential can reach the remote, and the project is a team project: %w", resolution.URL, action, err) case n8n.IsConflict(err) && action == "provider update": return fmt.Errorf("%s rejected the promotion provider update (409): another request changed the provider's credential or configuration first, so nothing changed; reload it with 'n8n promotion provider get' and retry: %w", resolution.URL, err) case n8n.IsConflict(err): @@ -2157,8 +2198,11 @@ func promotionAPIError(err error, resolution config.Resolution, action string, s case n8n.IsNotFound(err) && subject.what != "" && !promotionRouteMissing(err): return fmt.Errorf("%s has no %s (404): check the ID with %s: %w", resolution.URL, subject.what, subject.find, err) case n8n.IsNotFound(err) && subject.what != "": - return fmt.Errorf("%s answered 404 for %s: either the ID does not exist (check it with %s) or the instance does not serve promotions (run %s): %w", - resolution.URL, subject.what, subject.find, discoverHint(promotionResource), err) + return fmt.Errorf("%s answered 404 for %s: either the ID does not exist (check it with %s) or the instance does not serve promotions (run %s)%s: %w", + resolution.URL, subject.what, subject.find, discoverHint(promotionResource), subject.altHint(), err) + case n8n.IsNotFound(err): + return fmt.Errorf("%s does not serve promotions (%d): it needs the Promotions module (a GitConnections-generation instance answers here instead); run %s to see what this instance offers%s: %w", + resolution.URL, n8n.StatusCodeOf(err), discoverHint(promotionResource), subject.altHint(), err) case n8n.IsNotFound(err), n8n.IsStatus(err, http.StatusServiceUnavailable): return fmt.Errorf("%s does not serve promotions (%d): it needs the Promotions module (a GitConnections-generation instance answers here instead); run %s to see what this instance offers: %w", resolution.URL, n8n.StatusCodeOf(err), discoverHint(promotionResource), err) @@ -2185,19 +2229,19 @@ func promotionRouteMissing(err error) bool { func promotionScope(action string) string { switch action { - case "provider list", "connection list": + case "provider list", "connection list", "environment list": return "gitConnection:list" - case "provider create", "connection create": + case "provider create", "connection create", "environment create": return "gitConnection:create" - case "provider get", "connection get", "project list": + case "provider get", "connection get", "project list", "environment get", "environment project list": return "gitConnection:read" - case "provider update", "connection update", "config apply set", "config promote set", "config delete": + case "provider update", "connection update", "config apply set", "config promote set", "config delete", "environment update": return "gitConnection:update" - case "provider delete", "connection delete": + case "provider delete", "connection delete", "environment delete": return "gitConnection:delete" - case "checkout clone", "checkout disconnect": + case "checkout clone", "checkout disconnect", "environment connect", "environment disconnect": return "gitConnection:clone" - case "project add", "project remove": + case "project add", "project remove", "environment project add", "environment project remove": return "gitConnection:manageProjects" case "promote", "project promote", "project changes promote": return "gitConnection:push" diff --git a/internal/cli/promotion_environment.go b/internal/cli/promotion_environment.go new file mode 100644 index 0000000..c69b651 --- /dev/null +++ b/internal/cli/promotion_environment.go @@ -0,0 +1,891 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +// Environments are the n8n 2.46+ generation of connections: one remote for one +// direction. Older instances answer 404 here and serve 'promotion connection'. + +const ( + promotionEnvironmentAlt = "an instance older than n8n 2.46 serves connections instead: use 'n8n promotion connection'" + promotionConnectionAlt = "n8n 2.46 and later replaced connections with environments: use 'n8n promotion environment'" +) + +// promotionEnvironmentReadOnly are the response fields an environment write +// never sends. A document copied from 'environment get --output json' carries +// them, so they are dropped with a stderr note instead of refused. +var promotionEnvironmentReadOnly = []string{"id", "provider", "checkout", "createdAt", "updatedAt"} + +// promotionEnvironmentFixed are fields only a create sets: an update cannot +// change scope or direction, so they are read-only there. +var promotionEnvironmentFixed = []string{"scope", "direction"} + +func newPromotionEnvironmentCommand(opts Options) *cobra.Command { + cmd := &cobra.Command{ + Use: "environment", + Short: "Manage promotion environments (n8n 2.46 and later)", + Long: "Manage promotion environments: one remote, one direction (apply or\n" + + "promote), its settings, and its local checkout. n8n 2.46 replaced\n" + + "connections with environments; on older instances use 'n8n promotion\n" + + "connection' instead.\n\n" + + "Start with 'list' to find the environment ID, then 'get' to read it,\n" + + "'create' to add one on a provider, or 'update' to change its name,\n" + + "provider, remote, or settings. 'connect' prepares the local checkout\n" + + "and 'disconnect' removes it. Link team projects to a projects-scope\n" + + "environment under 'project'. The instance can have one environment for\n" + + "each direction.\n\n" + + "Deleting an environment removes its project links and local checkout;\n" + + "its provider is kept and nothing in Git changes.", + Example: " n8n promotion environment list\n" + + " n8n promotion environment get ENVIRONMENT_ID\n" + + " n8n promotion environment create --input environment.json\n" + + " n8n promotion environment connect ENVIRONMENT_ID\n" + + " n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + } + cmd.AddCommand( + newPromotionEnvironmentListCommand(opts), + newPromotionEnvironmentCreateCommand(opts), + newPromotionEnvironmentGetCommand(opts), + newPromotionEnvironmentUpdateCommand(opts), + newPromotionEnvironmentDeleteCommand(opts), + newPromotionEnvironmentConnectCommand(opts), + newPromotionEnvironmentDisconnectCommand(opts), + newPromotionEnvironmentProjectCommand(opts), + ) + return cmd +} + +type promotionEnvironmentListFlags struct { + instance instanceFlags + limit int + cursor string + scope string + direction string + providerID string + all bool + output string +} + +func newPromotionEnvironmentListCommand(opts Options) *cobra.Command { + var f promotionEnvironmentListFlags + cmd := &cobra.Command{ + Use: "list", + Short: "List promotion environments", + Long: "List the promotion environments visible to the selected credential,\n" + + "one cursor-paginated page at a time. Filter with --scope (instance or\n" + + "projects), --direction (apply or promote), and --provider-id; filters\n" + + "are preserved across --all. Use --all to follow every cursor, capped at\n" + + "10,000 environments.\n\n" + + "Use a returned ID with get, update, delete, connect, disconnect, and\n" + + "project. Requires gitConnection:list.\n\n" + cursorCollectionHelp, + Example: " n8n promotion environment list\n" + + " n8n promotion environment list --scope instance --direction apply\n" + + " n8n promotion environment list --provider-id PROVIDER_ID --output json\n" + + " n8n promotion environment list --all", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return runPromotionEnvironmentList(cmd.Context(), opts, f) + }, + } + f.instance.register(cmd) + cmd.Flags().IntVar(&f.limit, "limit", 0, "environments per API page, 1 to 250 (default: server default of 100)") + cmd.Flags().StringVar(&f.cursor, "cursor", "", "pagination cursor returned by a previous list (default: the first page)") + cmd.Flags().StringVar(&f.scope, "scope", "", "filter by environment scope: instance or projects (default: all scopes)") + cmd.Flags().StringVar(&f.direction, "direction", "", "filter by direction: apply or promote (default: both directions)") + cmd.Flags().StringVar(&f.providerID, "provider-id", "", "filter by provider ID from 'n8n promotion provider list' (default: all providers)") + cmd.Flags().BoolVar(&f.all, "all", false, "follow every page instead of one (maximum 10,000 environments; hitting it warns and sets JSON collection.truncated)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is a page object with data and nextCursor, plus collection with --all)") + return cmd +} + +func runPromotionEnvironmentList(ctx context.Context, opts Options, f promotionEnvironmentListFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + listOpts := n8n.ListPromotionEnvironmentsOptions{ + ListOptions: n8n.ListOptions{Limit: f.limit, Cursor: f.cursor}, + Scope: strings.TrimSpace(f.scope), + Direction: strings.TrimSpace(f.direction), + ProviderID: strings.TrimSpace(f.providerID), + } + if f.scope != "" && listOpts.Scope == "" { + return fmt.Errorf("--scope must not be blank: use instance or projects, or omit it for all scopes") + } + if f.direction != "" && listOpts.Direction == "" { + return fmt.Errorf("--direction must not be blank: use apply or promote, or omit it for both directions") + } + if f.providerID != "" && listOpts.ProviderID == "" { + return fmt.Errorf("--provider-id must not be blank: pass a provider ID from 'n8n promotion provider list'") + } + if err := listOpts.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + var page n8n.Page[n8n.PromotionEnvironment] + var collection *listCollection + if f.all { + collect := func(ctx context.Context, base n8n.ListOptions) (n8n.Page[n8n.PromotionEnvironment], error) { + next := listOpts + next.ListOptions = base + return client.ListPromotionEnvironments(ctx, next) + } + page, collection, err = collectPage(ctx, collect, listOpts.ListOptions) + } else { + page, err = client.ListPromotionEnvironments(ctx, listOpts) + } + if err != nil { + return promotionAPIError(err, resolution, "environment list", promotionSubject{alt: promotionEnvironmentAlt}) + } + if f.output == outputJSON { + err = writePageJSON(opts.Streams.Out, page, collection) + } else { + err = writePromotionEnvironmentListText(opts, resolution, page) + } + return finishCollection(opts.Streams.Err, collection, err) +} + +func writePromotionEnvironmentListText(opts Options, resolution config.Resolution, page n8n.Page[n8n.PromotionEnvironment]) error { + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + fmt.Fprintf(tw, "Environments:\t%d\n", len(page.Data)) + if len(page.Data) > 0 { + fmt.Fprintln(tw, "\nID\tNAME\tSCOPE\tDIRECTION\tBRANCH\tREMOTE\tPROVIDER") + for _, environment := range page.Data { + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", + emptyDash(environment.ID), emptyDash(environment.Name), + emptyDash(environment.Scope), emptyDash(environment.Direction), + emptyDash(promotionEnvironmentBranch(environment.Settings)), + emptyDash(environment.Remote.RemoteURL), emptyDash(environment.Provider.Name)) + } + } + if page.NextCursor != "" { + fmt.Fprintf(tw, "\nNext cursor:\t%s\n", page.NextCursor) + } + if err := tw.Flush(); err != nil { + return err + } + if len(page.Data) == 0 { + fmt.Fprintln(opts.Streams.Err, "No promotion environments were returned. Create one with 'n8n promotion environment create --input environment.json'.") + } + return nil +} + +type promotionEnvironmentCreateFlags struct { + instance instanceFlags + input string + output string +} + +func newPromotionEnvironmentCreateCommand(opts Options) *cobra.Command { + var f promotionEnvironmentCreateFlags + cmd := &cobra.Command{ + Use: "create", + Short: "Create a promotion environment", + Long: "Create one promotion environment from strict JSON supplied by --input.\n" + + "Required fields are name (at most 128 characters), scope (instance or\n" + + "projects), providerId, remote {\"schemaVersion\":1,\"remoteUrl\":\"...\"},\n" + + "direction (apply or promote), and settings matching the direction:\n" + + "apply {\"schemaVersion\":1,\"branchName\":\"main\"} or promote\n" + + "{\"schemaVersion\":1,\"baseBranchName\":\"main\",\n" + + "\"createBranchOnPromotion\":false}. The instance can have one\n" + + "environment for each direction.\n\n" + + "On a gitlab provider the remote URL must belong to the provider: the\n" + + "environment stores only the repository path and derives remoteUrl from\n" + + "the provider base URL. Read-only fields from 'environment get --output\n" + + "json' (id, provider, checkout, createdAt, updatedAt,\n" + + "remote.repositoryPath) are dropped with a note on stderr; other unknown\n" + + "fields and trailing JSON documents are refused before transport.\n" + + "Requires gitConnection:create. Follow with 'n8n promotion environment\n" + + "connect ENVIRONMENT_ID'.", + Example: " n8n promotion environment create --input environment.json\n" + + " printf '%s\\n' '{\"name\":\"prod\",\"scope\":\"instance\",\"providerId\":\"PROVIDER_ID\",\"remote\":{\"schemaVersion\":1,\"remoteUrl\":\"git@example.com:org/repo.git\"},\"direction\":\"apply\",\"settings\":{\"schemaVersion\":1,\"branchName\":\"main\"}}' | n8n promotion environment create --input -", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return runPromotionEnvironmentCreate(cmd.Context(), opts, f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.input, "input", "", "promotion environment JSON file path, or - for stdin (required; maximum 1 MiB)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the environment returned by the API)") + return cmd +} + +func runPromotionEnvironmentCreate(ctx context.Context, opts Options, f promotionEnvironmentCreateFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + var request n8n.CreatePromotionEnvironmentRequest + if _, err := readPromotionEnvironmentDocument(opts, f.input, false, &request); err != nil { + return err + } + if err := request.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + created, err := client.CreatePromotionEnvironment(ctx, request) + if err != nil { + subject := promotionProviderSubject(request.ProviderID) + subject.alt = promotionEnvironmentAlt + return promotionAPIError(err, resolution, "environment create", subject) + } + return writePromotionEnvironmentResult(opts, resolution, "Created", created, f.output) +} + +type promotionEnvironmentGetFlags struct { + instance instanceFlags + output string +} + +func newPromotionEnvironmentGetCommand(opts Options) *cobra.Command { + var f promotionEnvironmentGetFlags + cmd := &cobra.Command{ + Use: "get ", + Short: "Show one promotion environment", + Long: "Show one promotion environment by ID: its name, scope, direction,\n" + + "remote, provider, settings, local checkout state, and timestamps.\n" + + "Secrets are never returned. Find the ID with 'n8n promotion environment\n" + + "list'. The --output json document can be edited and passed to 'update'\n" + + "as is: its read-only fields are dropped. Requires gitConnection:read.", + Example: " n8n promotion environment get ENVIRONMENT_ID\n" + + " n8n promotion environment get ENVIRONMENT_ID --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentGet(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the environment object)") + return cmd +} + +func runPromotionEnvironmentGet(ctx context.Context, opts Options, id string, f promotionEnvironmentGetFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + environment, err := client.GetPromotionEnvironment(ctx, id) + if err != nil { + return promotionAPIError(err, resolution, "environment get", promotionEnvironmentSubject(id)) + } + return writePromotionEnvironmentResult(opts, resolution, "Environment", environment, f.output) +} + +type promotionEnvironmentUpdateFlags struct { + instance instanceFlags + input string + yes bool + output string +} + +func newPromotionEnvironmentUpdateCommand(opts Options) *cobra.Command { + var f promotionEnvironmentUpdateFlags + cmd := &cobra.Command{ + Use: "update ", + Short: "Update a promotion environment", + Long: "Update one promotion environment from strict JSON supplied by --input.\n" + + "Only the fields present are changed; at least one of name, providerId,\n" + + "remote, or settings is required. A remote replaces the whole saved\n" + + "remote and settings replace the whole saved settings, which must match\n" + + "the environment's direction (promote always needs\n" + + "createBranchOnPromotion). Scope and direction cannot change.\n\n" + + "Start from 'n8n promotion environment get ID --output json': read-only\n" + + "fields (id, scope, direction, provider, checkout, createdAt, updatedAt,\n" + + "remote.repositoryPath) are dropped with a note on stderr, and a\n" + + "direction in the document is used to check the settings first. A 409\n" + + "means the provider changed during the update: reload and retry.\n\n" + + "A new remote or branch can leave the local checkout stale, so\n" + + "interactive runs ask for confirmation; non-interactive runs and\n" + + "--input - require --yes. Requires gitConnection:update.", + Example: " n8n promotion environment update ENVIRONMENT_ID --input environment-update.json\n" + + " printf '%s\\n' '{\"name\":\"staging\"}' | n8n promotion environment update ENVIRONMENT_ID --input - --yes\n" + + " n8n promotion environment update ENVIRONMENT_ID --input environment.json --yes --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentUpdate(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.input, "input", "", "promotion environment update JSON file path, or - for stdin (required; maximum 1 MiB; - requires --yes)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm the environment update without prompting (required when stdin is not interactive or with --input -)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the environment returned by the API)") + return cmd +} + +func runPromotionEnvironmentUpdate(ctx context.Context, opts Options, id string, f promotionEnvironmentUpdateFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + if f.input == "-" && !f.yes { + return fmt.Errorf("--input - consumes stdin and cannot answer the update confirmation: pass --yes after reviewing the document") + } + var request n8n.UpdatePromotionEnvironmentRequest + direction, err := readPromotionEnvironmentDocument(opts, f.input, true, &request) + if err != nil { + return err + } + if err := request.Validate(); err != nil { + return err + } + if request.Settings != nil && direction != "" { + if err := request.Settings.Validate(direction); err != nil { + return err + } + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + question := fmt.Sprintf("Update promotion environment %q on %s (%s)? A new remote, provider, or branch can leave its local checkout stale until 'connect' runs again.", id, resolution.URL, promotionEnvironmentChanges(request)) + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + updated, err := client.UpdatePromotionEnvironment(ctx, id, request) + if err != nil { + return promotionAPIError(err, resolution, "environment update", promotionEnvironmentSubject(id)) + } + return writePromotionEnvironmentResult(opts, resolution, "Updated", updated, f.output) +} + +// promotionEnvironmentChanges names the fields one update replaces, for the +// confirmation question. +func promotionEnvironmentChanges(request n8n.UpdatePromotionEnvironmentRequest) string { + var fields []string + if request.Name != nil { + fields = append(fields, "name") + } + if request.ProviderID != nil { + fields = append(fields, "provider") + } + if request.Remote != nil { + fields = append(fields, "remote") + } + if request.Settings != nil { + fields = append(fields, "settings") + } + return "changes " + strings.Join(fields, ", ") +} + +type promotionEnvironmentConfirmFlags struct { + instance instanceFlags + yes bool + output string +} + +func newPromotionEnvironmentDeleteCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConfirmFlags + cmd := &cobra.Command{ + Use: "delete ", + Short: "Permanently delete a promotion environment", + Long: "Permanently delete one promotion environment with its project links and\n" + + "local checkout. Its provider is kept and nothing in Git changes, but\n" + + "linked projects fall back to the instance environment, and promote or\n" + + "apply for that direction stops working until an environment is\n" + + "created and connected again. This cannot be undone.\n\n" + + "To keep the environment and drop only the checkout, use 'n8n promotion\n" + + "environment disconnect' instead. Interactive runs ask for\n" + + "confirmation; non-interactive runs require --yes. Requires\n" + + "gitConnection:delete.", + Example: " n8n promotion environment delete ENVIRONMENT_ID\n" + + " n8n promotion environment delete ENVIRONMENT_ID --yes --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentDelete(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm permanent environment, project link, and checkout deletion without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the deletion acknowledgement)") + return cmd +} + +func runPromotionEnvironmentDelete(ctx context.Context, opts Options, id string, f promotionEnvironmentConfirmFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + question := fmt.Sprintf("Permanently delete promotion environment %q from %s? Its project links and local checkout go away; the provider and Git stay unchanged.", id, resolution.URL) + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + if err := client.DeletePromotionEnvironment(ctx, id); err != nil { + return promotionAPIError(err, resolution, "environment delete", promotionEnvironmentSubject(id)) + } + return writePromotionMutation(opts, resolution, promotionMutation{Action: "deleted", EnvironmentID: id}, f.output) +} + +type promotionEnvironmentConnectFlags struct { + instance instanceFlags + output string +} + +func newPromotionEnvironmentConnectCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConnectFlags + cmd := &cobra.Command{ + Use: "connect ", + Short: "Prepare the local checkout of a promotion environment", + Long: "Prepare one promotion environment on the instance that handles the\n" + + "request; for a Git provider this clones the configured branch into\n" + + "local storage. Connecting one environment does not make another\n" + + "ready.\n\n" + + "Connecting is safe to repeat and changes no project content by itself,\n" + + "so it needs no confirmation. Connect again after 'get' reports a\n" + + "checkout that does not match the environment. Requires\n" + + "gitConnection:clone.", + Example: " n8n promotion environment connect ENVIRONMENT_ID\n" + + " n8n promotion environment connect ENVIRONMENT_ID --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentConnect(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the checkout returned by the API)") + return cmd +} + +func runPromotionEnvironmentConnect(ctx context.Context, opts Options, id string, f promotionEnvironmentConnectFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + checkout, err := client.ConnectPromotionEnvironment(ctx, id) + if err != nil { + return promotionAPIError(err, resolution, "environment connect", promotionEnvironmentSubject(id)) + } + return writePromotionEnvironmentCheckout(opts, resolution, "Connected", checkout, f.output) +} + +func newPromotionEnvironmentDisconnectCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConfirmFlags + cmd := &cobra.Command{ + Use: "disconnect ", + Short: "Remove the local checkout of a promotion environment", + Long: "Remove the local checkout of one promotion environment. The\n" + + "environment, its credentials, its trusted SSH host keys, and its\n" + + "project links are kept, but promote and apply through it stop working\n" + + "until 'connect' runs again.\n\n" + + "Interactive runs ask for confirmation; non-interactive runs require\n" + + "--yes. Requires gitConnection:clone.", + Example: " n8n promotion environment disconnect ENVIRONMENT_ID\n" + + " n8n promotion environment disconnect ENVIRONMENT_ID --yes --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentDisconnect(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm checkout removal without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the checkout returned by the API)") + return cmd +} + +func runPromotionEnvironmentDisconnect(ctx context.Context, opts Options, id string, f promotionEnvironmentConfirmFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + question := fmt.Sprintf("Remove the local checkout of promotion environment %q on %s? The environment stays, but promote and apply through it stop working until it is connected again.", id, resolution.URL) + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + checkout, err := client.DisconnectPromotionEnvironment(ctx, id) + if err != nil { + return promotionAPIError(err, resolution, "environment disconnect", promotionEnvironmentSubject(id)) + } + return writePromotionEnvironmentCheckout(opts, resolution, "Disconnected", checkout, f.output) +} + +// Environment projects. + +func newPromotionEnvironmentProjectCommand(opts Options) *cobra.Command { + cmd := &cobra.Command{ + Use: "project", + Short: "Manage projects linked to a promotion environment", + Long: "Manage which team projects a projects-scope promotion environment\n" + + "syncs. A project can have one environment for each direction; a\n" + + "direction without a project environment uses the instance environment.\n" + + "Start with 'list' to see the linked project IDs, then 'add' a project\n" + + "or 'remove' one.\n\n" + + "Removing unlinks the project; its instance content is untouched.\n" + + "Project IDs come from 'n8n project list'. Listing needs\n" + + "gitConnection:read; adding and removing need\n" + + "gitConnection:manageProjects.", + Example: " n8n promotion environment project list ENVIRONMENT_ID\n" + + " n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID\n" + + " n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID --yes", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + } + cmd.AddCommand( + newPromotionEnvironmentProjectListCommand(opts), + newPromotionEnvironmentProjectAddCommand(opts), + newPromotionEnvironmentProjectRemoveCommand(opts), + ) + return cmd +} + +func newPromotionEnvironmentProjectListCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConnectFlags + cmd := &cobra.Command{ + Use: "list ", + Short: "List projects linked to a promotion environment", + Long: "List the team projects linked to one projects-scope promotion\n" + + "environment. Find the environment ID with 'n8n promotion environment\n" + + "list --scope projects'. Requires gitConnection:read.", + Example: " n8n promotion environment project list ENVIRONMENT_ID\n" + + " n8n promotion environment project list ENVIRONMENT_ID --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentProjectList(cmd.Context(), opts, args[0], f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the projectIds object)") + return cmd +} + +func runPromotionEnvironmentProjectList(ctx context.Context, opts Options, id string, f promotionEnvironmentConnectFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + projects, err := client.ListPromotionEnvironmentProjects(ctx, id) + if err != nil { + return promotionAPIError(err, resolution, "environment project list", promotionEnvironmentSubject(id)) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, projects) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Environment:\t%s\n", id) + fmt.Fprintf(tw, "Projects:\t%d\n", len(projects.ProjectIDs)) + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + if len(projects.ProjectIDs) > 0 { + fmt.Fprintln(tw, "\nPROJECT ID") + for _, projectID := range projects.ProjectIDs { + fmt.Fprintf(tw, "%s\n", emptyDash(projectID)) + } + } + if err := tw.Flush(); err != nil { + return err + } + if len(projects.ProjectIDs) == 0 { + fmt.Fprintln(opts.Streams.Err, "No projects are linked. Add one with 'n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID'.") + } + return nil +} + +func newPromotionEnvironmentProjectAddCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConnectFlags + cmd := &cobra.Command{ + Use: "add ", + Short: "Link a project to a promotion environment", + Long: "Link one team project to one projects-scope promotion environment, so\n" + + "project-level sync in that direction uses this environment instead of\n" + + "the instance environment. A project can have one environment for each\n" + + "direction: adding a project that already has one for this direction\n" + + "answers 409. Requires gitConnection:manageProjects.", + Example: " n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID\n" + + " n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID --output json", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentProjectAdd(cmd.Context(), opts, args[0], args[1], f) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the project link returned by the API)") + return cmd +} + +func runPromotionEnvironmentProjectAdd(ctx context.Context, opts Options, id, projectID string, f promotionEnvironmentConnectFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentProjectArgs(id, projectID); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + link, err := client.AddProjectToPromotionEnvironment(ctx, id, projectID) + if err != nil { + return promotionAPIError(err, resolution, "environment project add", promotionEnvironmentProjectSubject(id, projectID)) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, link) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Added:\t%s\n", link.ProjectID) + fmt.Fprintf(tw, "Environment:\t%s\n", link.EnvironmentID) + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + return tw.Flush() +} + +func newPromotionEnvironmentProjectRemoveCommand(opts Options) *cobra.Command { + var f promotionEnvironmentConfirmFlags + cmd := &cobra.Command{ + Use: "remove ", + Short: "Unlink a project from a promotion environment", + Long: "Unlink one project from one promotion environment. The project itself\n" + + "and its instance content are untouched; only the sync link goes away,\n" + + "so project-level sync in that direction falls back to the instance\n" + + "environment. Re-link it later with 'n8n promotion environment project\n" + + "add'.\n\n" + + "Interactive runs ask for confirmation; non-interactive runs require\n" + + "--yes. Requires gitConnection:manageProjects.", + Example: " n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID\n" + + " n8n promotion environment project remove ENVIRONMENT_ID PROJECT_ID --yes --output json", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentProjectRemove(cmd.Context(), opts, args[0], args[1], f) + }, + } + f.instance.register(cmd) + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm project unlinking without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the unlinking acknowledgement)") + return cmd +} + +func runPromotionEnvironmentProjectRemove(ctx context.Context, opts Options, id, projectID string, f promotionEnvironmentConfirmFlags) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentProjectArgs(id, projectID); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + question := fmt.Sprintf("Unlink project %q from promotion environment %q on %s? The project content stays; project-level sync in that direction falls back to the instance environment.", projectID, id, resolution.URL) + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + if err := client.RemoveProjectFromPromotionEnvironment(ctx, id, projectID); err != nil { + return promotionAPIError(err, resolution, "environment project remove", promotionEnvironmentProjectSubject(id, projectID)) + } + return writePromotionMutation(opts, resolution, promotionMutation{Action: "project removed", EnvironmentID: id, ProjectID: projectID}, f.output) +} + +// Environment helpers. + +func validatePromotionEnvironmentArg(id string) error { + if strings.TrimSpace(id) == "" { + return fmt.Errorf("environment ID is required: pass the ID from 'n8n promotion environment list'") + } + if err := n8n.ValidatePromotionEnvironmentID(id); err != nil { + return fmt.Errorf("%w: pass the ID from 'n8n promotion environment list'", err) + } + return nil +} + +func validatePromotionEnvironmentProjectArgs(id, projectID string) error { + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + if strings.TrimSpace(projectID) == "" { + return fmt.Errorf("project ID is required: pass the ID from 'n8n project list'") + } + if strings.TrimSpace(projectID) != projectID { + return fmt.Errorf("project ID must not start or end with whitespace") + } + return nil +} + +// readPromotionEnvironmentDocument reads one strict environment document into +// dst after dropping the read-only response fields, so a document copied from +// 'environment get --output json' round-trips. Dropped fields are named on +// stderr. For an update it also drops scope and direction, returning a valid +// direction so the caller can check the settings shape against it. +func readPromotionEnvironmentDocument(opts Options, path string, update bool, dst any) (string, error) { + var doc map[string]json.RawMessage + if err := readPromotionDocument(opts, path, &doc); err != nil { + return "", err + } + if doc == nil { + return "", fmt.Errorf("decode promotion JSON: the document must be a JSON object") + } + readOnly := promotionEnvironmentReadOnly + var direction string + if update { + readOnly = append(append([]string(nil), readOnly...), promotionEnvironmentFixed...) + if raw, ok := doc["direction"]; ok { + var value string + if json.Unmarshal(raw, &value) == nil && (value == n8n.PromotionDirectionApply || value == n8n.PromotionDirectionPromote) { + direction = value + } + } + } + var dropped []string + for _, field := range readOnly { + if _, ok := doc[field]; ok { + delete(doc, field) + dropped = append(dropped, field) + } + } + if raw, ok := doc["remote"]; ok { + var remote map[string]json.RawMessage + if json.Unmarshal(raw, &remote) == nil { + if _, ok := remote["repositoryPath"]; ok { + delete(remote, "repositoryPath") + dropped = append(dropped, "remote.repositoryPath") + encoded, err := json.Marshal(remote) + if err != nil { + return "", err + } + doc["remote"] = encoded + } + } + } + if len(dropped) > 0 { + fmt.Fprintf(opts.Streams.Err, "Not sent (read-only): %s\n", strings.Join(dropped, ", ")) + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", err + } + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(dst); err != nil { + return "", fmt.Errorf("decode promotion JSON: %w", err) + } + return direction, nil +} + +func promotionEnvironmentBranch(settings n8n.PromotionEnvironmentSettings) string { + if settings.BranchName != "" { + return settings.BranchName + } + return settings.BaseBranchName +} + +func writePromotionEnvironmentResult(opts Options, resolution config.Resolution, action string, environment *n8n.PromotionEnvironment, output string) error { + if output == outputJSON { + return writeJSON(opts.Streams.Out, environment) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "%s:\t%s\n", action, environment.ID) + fmt.Fprintf(tw, "Name:\t%s\n", emptyDash(environment.Name)) + fmt.Fprintf(tw, "Scope:\t%s\n", emptyDash(environment.Scope)) + fmt.Fprintf(tw, "Direction:\t%s\n", emptyDash(environment.Direction)) + fmt.Fprintf(tw, "Remote:\t%s\n", emptyDash(environment.Remote.RemoteURL)) + if environment.Remote.RepositoryPath != "" { + fmt.Fprintf(tw, "Repository path:\t%s\n", environment.Remote.RepositoryPath) + } + fmt.Fprintf(tw, "Provider:\t%s\n", emptyDash(environment.Provider.Name)) + if environment.Settings.BranchName != "" { + fmt.Fprintf(tw, "Branch:\t%s\n", environment.Settings.BranchName) + } + if environment.Settings.BaseBranchName != "" { + fmt.Fprintf(tw, "Base branch:\t%s\n", environment.Settings.BaseBranchName) + } + if create := environment.Settings.CreateBranchOnPromotion; create != nil { + fmt.Fprintf(tw, "New branch per promote:\t%v\n", *create) + } + if checkout := environment.Checkout; checkout != nil { + fmt.Fprintf(tw, "Checkout:\t%s\n", promotionEnvironmentCheckoutState(*checkout)) + } + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + if environment.CreatedAt != "" { + fmt.Fprintf(tw, "Created:\t%s\n", environment.CreatedAt) + } + if environment.UpdatedAt != "" { + fmt.Fprintf(tw, "Updated:\t%s\n", environment.UpdatedAt) + } + return tw.Flush() +} + +// promotionEnvironmentCheckoutState says whether the environment is connected +// and whether the checkout still matches it (a stale one needs 'connect'). +func promotionEnvironmentCheckoutState(checkout n8n.PromotionEnvironmentCheckoutState) string { + switch { + case !checkout.HasCheckout: + return "not connected" + case checkout.MatchesEnvironment: + return "connected" + default: + return "connected, does not match the environment; connect again" + } +} + +func writePromotionEnvironmentCheckout(opts Options, resolution config.Resolution, action string, checkout *n8n.PromotionEnvironmentCheckout, output string) error { + if output == outputJSON { + return writeJSON(opts.Streams.Out, checkout) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "%s:\t%s\n", action, checkout.EnvironmentID) + fmt.Fprintf(tw, "Direction:\t%s\n", emptyDash(checkout.Direction)) + fmt.Fprintf(tw, "Branch:\t%s\n", emptyDash(checkout.BranchName)) + fmt.Fprintf(tw, "Checkout:\t%v\n", checkout.HasCheckout) + fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) + return tw.Flush() +} + +func promotionEnvironmentSubject(id string) promotionSubject { + return promotionSubject{ + what: fmt.Sprintf("promotion environment %q", id), + find: "'n8n promotion environment list'", + alt: promotionEnvironmentAlt, + } +} + +func promotionEnvironmentProjectSubject(id, projectID string) promotionSubject { + return promotionSubject{ + what: fmt.Sprintf("promotion environment %q or project %q", id, projectID), + find: "'n8n promotion environment list' and 'n8n project list'", + alt: promotionEnvironmentAlt, + } +} diff --git a/internal/cli/promotion_environment_test.go b/internal/cli/promotion_environment_test.go new file mode 100644 index 0000000..968a550 --- /dev/null +++ b/internal/cli/promotion_environment_test.go @@ -0,0 +1,511 @@ +package cli + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +const cliEnvironmentID = "0b8f7a2e-4c1d-4e5f-9a6b-7c8d9e0f1a2b" + +const cliEnvironmentPath = n8n.BasePath + n8n.PromotionEnvironmentsPath + "/" + cliEnvironmentID + +// cliPromotionEnvironmentBody is a full 'environment get' response, including +// every read-only field a round trip must drop. +const cliPromotionEnvironmentBody = `{ + "id":"` + cliEnvironmentID + `", + "name":"prod", + "scope":"instance", + "remote":{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git","repositoryPath":"org/repo"}, + "provider":{"id":"prov-1","name":"gitlab","type":"gitlab","authType":"token","createdAt":"2026-10-01T00:00:00.000Z","updatedAt":"2026-10-01T00:00:00.000Z"}, + "createdAt":"2026-10-01T00:00:00.000Z", + "updatedAt":"2026-10-01T00:00:00.000Z", + "direction":"apply", + "settings":{"schemaVersion":1,"branchName":"main"}, + "checkout":{"hasCheckout":true,"matchesEnvironment":false} +}` + +const cliPromotionEnvironmentCheckoutBody = `{ + "environmentId":"` + cliEnvironmentID + `", + "direction":"apply", + "branchName":"main", + "hasCheckout":true +}` + +func TestPromotionEnvironmentListTextAndJSON(t *testing.T) { + f := promotionFixture(t, `{"data":[`+cliPromotionEnvironmentBody+`],"nextCursor":"next"}`) + + got := f.run("promotion", "environment", "list") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Environments:", cliEnvironmentID, "prod", "instance", "apply", "main", "https://gitlab.example.com/org/repo.git", "gitlab", "Next cursor:"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + req := f.lastRequest() + if req.Method != http.MethodGet || req.URL.Path != n8n.BasePath+n8n.PromotionEnvironmentsPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + + got = f.run("promotion", "environment", "list", "--scope", "instance", "--direction", "apply", "--provider-id", "prov-1", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("filtered exit = %d, stderr: %s", got.code, got.stderr) + } + query := f.lastRequest().URL.Query() + if query.Get("scope") != "instance" || query.Get("direction") != "apply" || query.Get("providerId") != "prov-1" { + t.Errorf("query = %q, want scope, direction and providerId", f.lastRequest().URL.RawQuery) + } + var page n8n.Page[n8n.PromotionEnvironment] + if err := json.Unmarshal([]byte(got.stdout), &page); err != nil || len(page.Data) != 1 || page.Data[0].Settings.BranchName != "main" { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } + + before := f.requestCount() + for _, args := range [][]string{ + {"promotion", "environment", "list", "--direction", "sideways"}, + {"promotion", "environment", "list", "--direction", " "}, + {"promotion", "environment", "list", "--scope", "global"}, + {"promotion", "environment", "list", "--limit", "251"}, + } { + if got := f.run(args...); got.code != ExitError { + t.Errorf("%v exit = %d, want %d", args, got.code, ExitError) + } + } + if f.requestCount() != before { + t.Errorf("requests = %d, want %d before transport", f.requestCount(), before) + } +} + +func TestPromotionEnvironmentListAllKeepsFilters(t *testing.T) { + f := promotionFixture(t, ``) + f.bodyFunc = func(i int) string { + if i == 0 { + return `{"data":[` + cliPromotionEnvironmentBody + `],"nextCursor":"next"}` + } + return `{"data":[],"nextCursor":null}` + } + got := f.run("promotion", "environment", "list", "--all", "--direction", "apply", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if query := f.lastRequest().URL.Query(); query.Get("cursor") != "next" || query.Get("direction") != "apply" { + t.Errorf("second page query = %q, want the cursor and the filter", f.lastRequest().URL.RawQuery) + } + + f.bodyFunc = nil + f.body = `{"data":[],"nextCursor":null}` + got = f.run("promotion", "environment", "list") + if got.code != ExitSuccess || !strings.Contains(got.stderr, "No promotion environments") { + t.Errorf("empty result = %+v, want the empty hint", got) + } +} + +func TestPromotionEnvironmentCreateDropsReadOnlyFields(t *testing.T) { + f := promotionFixture(t, cliPromotionEnvironmentBody) + + // A 'get --output json' document plus providerId round-trips. + doc := strings.Replace(cliPromotionEnvironmentBody, `"name":"prod",`, `"name":"prod","providerId":"prov-1",`, 1) + path := writePromotionInput(t, f, "environment.json", doc) + got := f.run("promotion", "environment", "create", "--input", path) + if got.code != ExitSuccess { + t.Fatalf("create exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.Path != n8n.BasePath+n8n.PromotionEnvironmentsPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + var sent map[string]json.RawMessage + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("body = %q (error %v)", f.lastBody(), err) + } + for _, field := range []string{"id", "provider", "checkout", "createdAt", "updatedAt"} { + if _, ok := sent[field]; ok { + t.Errorf("read-only field %q was sent: %s", field, f.lastBody()) + } + } + if strings.Contains(f.lastBody(), "repositoryPath") { + t.Errorf("remote.repositoryPath was sent: %s", f.lastBody()) + } + for _, field := range []string{"name", "scope", "providerId", "remote", "direction", "settings"} { + if _, ok := sent[field]; !ok { + t.Errorf("writable field %q was not sent: %s", field, f.lastBody()) + } + } + if !strings.Contains(got.stderr, "Not sent (read-only): id, provider, checkout, createdAt, updatedAt, remote.repositoryPath") { + t.Errorf("stderr = %q, want the dropped fields named", got.stderr) + } + if strings.Contains(got.stdout, "Not sent") { + t.Errorf("diagnostic leaked into stdout:\n%s", got.stdout) + } + for _, want := range []string{"Created:", cliEnvironmentID, "Repository path:", "org/repo", "connected, does not match"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + + // Create needs no confirmation, so stdin input works without --yes. + f.stdin = `{"name":"push","scope":"projects","providerId":"prov-1","remote":{"schemaVersion":1,"remoteUrl":"git@example.com:o/r.git"},"direction":"promote","settings":{"schemaVersion":1,"baseBranchName":"main","createBranchOnPromotion":false}}` + got = f.run("promotion", "environment", "create", "--input", "-", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("stdin exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(f.lastBody(), `"createBranchOnPromotion":false`) { + t.Errorf("body = %s, want the explicit false", f.lastBody()) + } + var created n8n.PromotionEnvironment + if err := json.Unmarshal([]byte(got.stdout), &created); err != nil || created.ID != cliEnvironmentID { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } +} + +func TestPromotionEnvironmentCreateRejectsBadInputBeforeTransport(t *testing.T) { + f := promotionFixture(t, cliPromotionEnvironmentBody) + before := f.requestCount() + + valid := `{"name":"prod","scope":"instance","providerId":"prov-1","remote":{"schemaVersion":1,"remoteUrl":"git@example.com:o/r.git"},"direction":"apply","settings":{"schemaVersion":1,"branchName":"main"}}` + bad := map[string]string{ + "unknown field": strings.Replace(valid, `"name":"prod"`, `"name":"prod","color":"red"`, 1), + "unknown nested": strings.Replace(valid, `"branchName":"main"`, `"branchName":"main","depth":1`, 1), + "mismatched": strings.Replace(valid, `"direction":"apply"`, `"direction":"promote"`, 1), + "missing provider": strings.Replace(valid, `"providerId":"prov-1",`, ``, 1), + "two documents": valid + valid, + "array": `[]`, + "bad remote schema": strings.Replace(valid, `"remote":{"schemaVersion":1`, `"remote":{"schemaVersion":2`, 1), + } + for name, body := range bad { + path := writePromotionInput(t, f, "bad-environment.json", body) + if got := f.run("promotion", "environment", "create", "--input", path); got.code != ExitError { + t.Errorf("%s: exit = %d, want %d (stderr: %s)", name, got.code, ExitError, got.stderr) + } + } + if got := f.run("promotion", "environment", "create"); got.code != ExitError || !strings.Contains(got.stderr, "--input is required") { + t.Errorf("missing input = %+v", got) + } + if f.requestCount() != before { + t.Errorf("requests = %d, want %d before transport", f.requestCount(), before) + } +} + +func TestPromotionEnvironmentGetTextAndJSON(t *testing.T) { + f := promotionFixture(t, cliPromotionEnvironmentBody) + + got := f.run("promotion", "environment", "get", cliEnvironmentID) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Environment:", "Direction:", "apply", "Branch:", "main", "Checkout:", "connect again"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + req := f.lastRequest() + if req.Method != http.MethodGet || req.URL.Path != cliEnvironmentPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + + got = f.run("promotion", "environment", "get", cliEnvironmentID, "--output", "json") + var environment n8n.PromotionEnvironment + if err := json.Unmarshal([]byte(got.stdout), &environment); err != nil || environment.Checkout == nil || environment.Remote.RepositoryPath != "org/repo" { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } + + before := f.requestCount() + for _, id := range []string{"env-1", " ", "a/b"} { + got = f.run("promotion", "environment", "get", id) + if got.code != ExitError || !strings.Contains(got.stderr, "n8n promotion environment list") { + t.Errorf("id %q result = %+v, want the list hint", id, got) + } + } + if f.requestCount() != before { + t.Errorf("requests = %d, want %d before transport", f.requestCount(), before) + } +} + +func TestPromotionEnvironmentUpdateRoundTripAndConfirmation(t *testing.T) { + f := promotionFixture(t, cliPromotionEnvironmentBody) + path := writePromotionInput(t, f, "environment-update.json", cliPromotionEnvironmentBody) + before := f.requestCount() + + f.stdin = "no\n" + got := f.run("promotion", "environment", "update", cliEnvironmentID, "--input", path) + if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + if !strings.Contains(got.stderr, "changes name, remote, settings") { + t.Errorf("prompt = %q, want the replaced fields", got.stderr) + } + + f.interactive = false + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", path) + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + f.stdin = `{"name":"staging"}` + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", "-") + if got.code != ExitError || !strings.Contains(got.stderr, "--input - consumes stdin") || f.requestCount() != before { + t.Errorf("stdin without --yes = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + // The settings shape is checked against the document's direction before + // direction is dropped. + mismatch := writePromotionInput(t, f, "environment-mismatch.json", strings.Replace(cliPromotionEnvironmentBody, + `"settings":{"schemaVersion":1,"branchName":"main"}`, `"settings":{"schemaVersion":1,"baseBranchName":"main","createBranchOnPromotion":true}`, 1)) + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", mismatch, "--yes") + if got.code != ExitError || !strings.Contains(got.stderr, "direction is apply") || f.requestCount() != before { + t.Errorf("mismatch result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + empty := writePromotionInput(t, f, "environment-empty.json", `{"id":"x","scope":"instance"}`) + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", empty, "--yes") + if got.code != ExitError || !strings.Contains(got.stderr, "update is empty") || f.requestCount() != before { + t.Errorf("empty result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", path, "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("confirmed exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPut || req.URL.Path != cliEnvironmentPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + var sent map[string]json.RawMessage + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("body = %q (error %v)", f.lastBody(), err) + } + if len(sent) != 3 || sent["name"] == nil || sent["remote"] == nil || sent["settings"] == nil { + t.Errorf("body = %s, want only name, remote and settings", f.lastBody()) + } + if string(sent["remote"]) != `{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git"}` { + t.Errorf("remote = %s, want it without repositoryPath", sent["remote"]) + } + if !strings.Contains(got.stderr, "Not sent (read-only): id, provider, checkout, createdAt, updatedAt, scope, direction, remote.repositoryPath") { + t.Errorf("stderr = %q, want every dropped field named", got.stderr) + } + var updated n8n.PromotionEnvironment + if err := json.Unmarshal([]byte(got.stdout), &updated); err != nil || updated.ID != cliEnvironmentID { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } +} + +func TestPromotionEnvironmentDeleteConfirmation(t *testing.T) { + f := promotionFixture(t, ``) + f.status = http.StatusNoContent + before := f.requestCount() + + f.stdin = "no\n" + got := f.run("promotion", "environment", "delete", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + if !strings.Contains(got.stderr, "project links and local checkout") { + t.Errorf("prompt = %q, want the consequence", got.stderr) + } + + f.interactive = false + got = f.run("promotion", "environment", "delete", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + got = f.run("promotion", "environment", "delete", "not-a-uuid", "--yes") + if got.code != ExitError || f.requestCount() != before { + t.Errorf("bad ID result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + got = f.run("promotion", "environment", "delete", cliEnvironmentID, "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("confirmed exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodDelete || req.URL.Path != cliEnvironmentPath { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + var ack map[string]string + if err := json.Unmarshal([]byte(got.stdout), &ack); err != nil || ack["action"] != "deleted" || ack["environmentId"] != cliEnvironmentID || ack["connectionId"] != "" { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } +} + +func TestPromotionEnvironmentConnectDisconnect(t *testing.T) { + f := promotionFixture(t, cliPromotionEnvironmentCheckoutBody) + f.interactive = false + + // Connect is safe to repeat and needs no --yes even without a terminal. + got := f.run("promotion", "environment", "connect", cliEnvironmentID) + if got.code != ExitSuccess { + t.Fatalf("connect exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.Path != cliEnvironmentPath+"/connect" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + for _, want := range []string{"Connected:", cliEnvironmentID, "apply", "main", "true"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + + before := f.requestCount() + got = f.run("promotion", "environment", "disconnect", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + f.interactive = true + f.stdin = "no\n" + got = f.run("promotion", "environment", "disconnect", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + + f.body = strings.Replace(cliPromotionEnvironmentCheckoutBody, `"hasCheckout":true`, `"hasCheckout":false`, 1) + got = f.run("promotion", "environment", "disconnect", cliEnvironmentID, "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("disconnect exit = %d, stderr: %s", got.code, got.stderr) + } + req = f.lastRequest() + if req.Method != http.MethodPost || req.URL.Path != cliEnvironmentPath+"/disconnect" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + var checkout n8n.PromotionEnvironmentCheckout + if err := json.Unmarshal([]byte(got.stdout), &checkout); err != nil || checkout.HasCheckout { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } +} + +func TestPromotionEnvironmentProjectListAddRemove(t *testing.T) { + f := promotionFixture(t, `{"projectIds":["p1","p2"]}`) + + got := f.run("promotion", "environment", "project", "list", cliEnvironmentID) + if got.code != ExitSuccess { + t.Fatalf("list exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Environment:", "p1", "p2"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + if req := f.lastRequest(); req.Method != http.MethodGet || req.URL.Path != cliEnvironmentPath+"/projects" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + + f.body = `{"projectId":"a/b c","environmentId":"` + cliEnvironmentID + `"}` + got = f.run("promotion", "environment", "project", "add", cliEnvironmentID, "a/b c", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("add exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.EscapedPath() != cliEnvironmentPath+"/projects/a%2Fb%20c" { + t.Errorf("request = %s %s, want the project ID escaped", req.Method, req.URL.EscapedPath()) + } + var link n8n.PromotionEnvironmentProjectLink + if err := json.Unmarshal([]byte(got.stdout), &link); err != nil || link.EnvironmentID != cliEnvironmentID { + t.Errorf("stdout = %q (error %v)", got.stdout, err) + } + + f.status = http.StatusNoContent + f.body = `` + before := f.requestCount() + f.stdin = "no\n" + got = f.run("promotion", "environment", "project", "remove", cliEnvironmentID, "p1") + if got.code != ExitError || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + f.interactive = false + got = f.run("promotion", "environment", "project", "remove", cliEnvironmentID, "p1") + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + got = f.run("promotion", "environment", "project", "remove", cliEnvironmentID, " ", "--yes") + if got.code != ExitError || f.requestCount() != before { + t.Errorf("blank project result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + got = f.run("promotion", "environment", "project", "remove", cliEnvironmentID, "p1", "--yes") + if got.code != ExitSuccess { + t.Fatalf("remove exit = %d, stderr: %s", got.code, got.stderr) + } + if req := f.lastRequest(); req.Method != http.MethodDelete || req.URL.Path != cliEnvironmentPath+"/projects/p1" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + for _, want := range []string{"project removed", "Environment:", "Project:", "p1"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } +} + +func TestPromotionEnvironmentErrorsNameTheFix(t *testing.T) { + f := promotionFixture(t, `{}`) + + // A bare 404 may mean an instance older than n8n 2.46. + f.route = func(*http.Request, int) (int, string) { return http.StatusNotFound, `{"message":"not found"}` } + got := f.run("promotion", "environment", "list") + if got.code != ExitError || !strings.Contains(got.stderr, "older than n8n 2.46") || !strings.Contains(got.stderr, "'n8n promotion connection'") { + t.Errorf("collection 404 = %+v, want the connection hint", got) + } + got = f.run("promotion", "environment", "get", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "'n8n promotion connection'") || !strings.Contains(got.stderr, "n8n promotion environment list") { + t.Errorf("item 404 = %+v, want the list and connection hints", got) + } + // And the reverse for connections on n8n 2.46 and later. + got = f.run("promotion", "connection", "get", "conn-1") + if got.code != ExitError || !strings.Contains(got.stderr, "'n8n promotion environment'") || !strings.Contains(got.stderr, "does not serve promotions") { + t.Errorf("connection 404 = %+v, want the environment hint", got) + } + got = f.run("promotion", "connection", "list") + if got.code != ExitError || !strings.Contains(got.stderr, "'n8n promotion environment'") || !strings.Contains(got.stderr, "does not serve promotions (404)") { + t.Errorf("connection list 404 = %+v, want the environment hint", got) + } + + // A 404 with its own message is a missing environment, not a missing route. + f.route = func(*http.Request, int) (int, string) { + return http.StatusNotFound, `{"message":"Promotion environment not found"}` + } + got = f.run("promotion", "environment", "get", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "has no promotion environment") || strings.Contains(got.stderr, "older than") { + t.Errorf("missing environment = %+v, want the ID hint only", got) + } + + // 503 stays the availability diagnostic without a generation hint. + f.route = nil + f.status = http.StatusServiceUnavailable + got = f.run("promotion", "environment", "list") + if got.code != ExitError || !strings.Contains(got.stderr, "does not serve promotions (503)") || strings.Contains(got.stderr, "older than") { + t.Errorf("503 = %+v", got) + } + + f.status = http.StatusForbidden + got = f.run("promotion", "environment", "connect", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "gitConnection:clone") { + t.Errorf("connect 403 = %+v, want the missing scope", got) + } + got = f.run("promotion", "environment", "project", "add", cliEnvironmentID, "p1") + if got.code != ExitError || !strings.Contains(got.stderr, "gitConnection:manageProjects") { + t.Errorf("project add 403 = %+v, want the missing scope", got) + } + + f.status = http.StatusConflict + f.body = `{"message":"exists"}` + got = f.run("promotion", "environment", "project", "add", cliEnvironmentID, "p1") + if got.code != ExitError || !strings.Contains(got.stderr, "already has an environment for this direction") { + t.Errorf("project add 409 = %+v", got) + } + path := writePromotionInput(t, f, "env-409.json", `{"name":"x"}`) + got = f.run("promotion", "environment", "update", cliEnvironmentID, "--input", path, "--yes") + if got.code != ExitError || !strings.Contains(got.stderr, "provider changed during the update") || !strings.Contains(got.stderr, "environment get") { + t.Errorf("update 409 = %+v", got) + } + + f.status = http.StatusUnprocessableEntity + f.body = `{"message":"branch missing"}` + got = f.run("promotion", "environment", "connect", cliEnvironmentID) + if got.code != ExitError || !strings.Contains(got.stderr, "branch exists") { + t.Errorf("connect 422 = %+v", got) + } +} diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index 5160be6..9637b56 100644 --- a/internal/coverage/coverage_test.go +++ b/internal/coverage/coverage_test.go @@ -327,7 +327,7 @@ func TestAvailabilityMatchesSpecs(t *testing.T) { // // A phase is never excused because one server does not serve its resource: // every phase owns operations from the union of the documents. -const deliveredThrough = 34 +const deliveredThrough = 35 // TestPhaseCounts is how a phase exit gate reads the manifest: every operation // a delivered phase owns must be implemented, and no later phase may have diff --git a/internal/coverage/manifest.json b/internal/coverage/manifest.json index 2e162ab..e277456 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -2068,8 +2068,8 @@ "scope": "gitConnection:list", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment list", + "status": "implemented" }, { "operationId": "createPromotionEnvironment", @@ -2079,8 +2079,8 @@ "scope": "gitConnection:create", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment create", + "status": "implemented" }, { "operationId": "getPromotionEnvironment", @@ -2090,8 +2090,8 @@ "scope": "gitConnection:read", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment get", + "status": "implemented" }, { "operationId": "updatePromotionEnvironment", @@ -2101,8 +2101,8 @@ "scope": "gitConnection:update", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment update", + "status": "implemented" }, { "operationId": "deletePromotionEnvironment", @@ -2112,8 +2112,8 @@ "scope": "gitConnection:delete", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment delete", + "status": "implemented" }, { "operationId": "connectPromotionCheckout", @@ -2123,8 +2123,8 @@ "scope": "gitConnection:clone", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment connect", + "status": "implemented" }, { "operationId": "disconnectPromotionCheckout", @@ -2134,8 +2134,8 @@ "scope": "gitConnection:clone", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment disconnect", + "status": "implemented" }, { "operationId": "getPromotionEnvironmentProjects", @@ -2145,8 +2145,8 @@ "scope": "gitConnection:read", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment project list", + "status": "implemented" }, { "operationId": "addProjectToPromotionEnvironment", @@ -2156,8 +2156,8 @@ "scope": "gitConnection:manageProjects", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment project add", + "status": "implemented" }, { "operationId": "removeProjectFromPromotionEnvironment", @@ -2167,8 +2167,8 @@ "scope": "gitConnection:manageProjects", "availability": "upstream-only", "phase": 35, - "command": "", - "status": "planned" + "command": "n8n promotion environment project remove", + "status": "implemented" }, { "operationId": "applyPackage", diff --git a/internal/n8n/promotion.go b/internal/n8n/promotion.go index 5e1450c..d83cddd 100644 --- a/internal/n8n/promotion.go +++ b/internal/n8n/promotion.go @@ -230,9 +230,10 @@ func (r UpdatePromotionProviderRequest) Validate() error { return nil } -// PromotionTarget is the remote a connection syncs through, as the API -// reports it. GitLab connections also report the stored repository path, -// which is read-only: write documents use [PromotionTargetDocument]. +// PromotionTarget is the remote a connection or environment syncs through, as +// the API reports it. GitLab remotes also report the stored repository path, +// which is read-only: write documents use [PromotionTargetDocument] for +// connections and [PromotionRemoteDocument] for environments. type PromotionTarget struct { SchemaVersion int `json:"schemaVersion"` RemoteURL string `json:"remoteUrl"` diff --git a/internal/n8n/promotion_environment.go b/internal/n8n/promotion_environment.go new file mode 100644 index 0000000..0384d80 --- /dev/null +++ b/internal/n8n/promotion_environment.go @@ -0,0 +1,412 @@ +package n8n + +import ( + "context" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" +) + +// PromotionEnvironmentsPath is the environment collection. Environments +// replace connections from n8n 2.46: one environment is one remote for one +// direction, with its own settings and checkout, where a connection held one +// remote plus a config per direction. Instances older than 2.46 serve only +// connections; both generations share the gitConnection:* scopes. +const PromotionEnvironmentsPath = "/promotions/environments" + +var promotionEnvironmentID = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +// ValidatePromotionEnvironmentID rejects an environment ID that is not a UUID, +// as the route requires, before transport. +func ValidatePromotionEnvironmentID(id string) error { + if err := validatePromotionID(id, "promotion environment ID"); err != nil { + return err + } + if !promotionEnvironmentID.MatchString(id) { + return fmt.Errorf("promotion environment ID %q must be a UUID", id) + } + return nil +} + +// PromotionRemoteDocument is the remote an environment create or update sends. +// For GitLab the remote URL must belong to the provider; the server stores only +// the repository path and derives remoteUrl from the provider base URL. The +// read-only repositoryPath of [PromotionTarget] is never sent. +type PromotionRemoteDocument struct { + SchemaVersion int `json:"schemaVersion"` + RemoteURL string `json:"remoteUrl"` +} + +// Validate rejects a remote the API would reject before transport. +func (r PromotionRemoteDocument) Validate() error { + if r.SchemaVersion != promotionTargetSchemaVersion { + return fmt.Errorf("remote schemaVersion must be %d, got %d", promotionTargetSchemaVersion, r.SchemaVersion) + } + if strings.TrimSpace(r.RemoteURL) == "" { + return fmt.Errorf("remote remoteUrl is required") + } + return nil +} + +// PromotionEnvironmentSettings is the direction-specific settings union. An +// apply environment sets BranchName; a promote environment sets +// BaseBranchName and CreateBranchOnPromotion. The other direction's fields +// stay empty and are omitted. +type PromotionEnvironmentSettings struct { + SchemaVersion int `json:"schemaVersion"` + BranchName string `json:"branchName,omitempty"` + BaseBranchName string `json:"baseBranchName,omitempty"` + CreateBranchOnPromotion *bool `json:"createBranchOnPromotion,omitempty"` +} + +// Direction reports which direction the settings fit: apply, promote, or "" +// when they carry fields of both or of neither. +func (s PromotionEnvironmentSettings) Direction() string { + apply := s.BranchName != "" + promote := s.BaseBranchName != "" || s.CreateBranchOnPromotion != nil + switch { + case apply && !promote: + return PromotionDirectionApply + case promote && !apply: + return PromotionDirectionPromote + default: + return "" + } +} + +// Validate rejects settings the API would reject before transport. direction +// is the environment's direction when known; "" accepts either shape. +func (s PromotionEnvironmentSettings) Validate(direction string) error { + shape := s.Direction() + if shape == "" { + return fmt.Errorf("settings must be either apply {\"schemaVersion\":1,\"branchName\":\"main\"} or promote {\"schemaVersion\":1,\"baseBranchName\":\"main\",\"createBranchOnPromotion\":false}") + } + if direction != "" && shape != direction { + return fmt.Errorf("settings are %s settings but the environment direction is %s: use the %s settings shape", shape, direction, direction) + } + if s.SchemaVersion != promotionTargetSchemaVersion { + return fmt.Errorf("settings schemaVersion must be %d, got %d", promotionTargetSchemaVersion, s.SchemaVersion) + } + if shape == PromotionDirectionApply { + return validatePromotionBranch(s.BranchName) + } + if err := validatePromotionBranch(s.BaseBranchName); err != nil { + return fmt.Errorf("base branch: %w", err) + } + if s.CreateBranchOnPromotion == nil { + return fmt.Errorf("promote settings need createBranchOnPromotion (true or false)") + } + return nil +} + +// PromotionEnvironmentCheckoutState is the local checkout state an environment +// reports: whether it is connected and whether the checkout still matches +// the environment. +type PromotionEnvironmentCheckoutState struct { + HasCheckout bool `json:"hasCheckout"` + MatchesEnvironment bool `json:"matchesEnvironment"` +} + +// PromotionEnvironment is one promotion environment as the public DTO reports +// it. Checkout is nil on list rows, which omit it. Secrets are never returned. +type PromotionEnvironment struct { + ID string `json:"id"` + Name string `json:"name"` + Scope string `json:"scope"` + Direction string `json:"direction"` + Remote PromotionTarget `json:"remote"` + Provider PromotionProviderRef `json:"provider"` + Settings PromotionEnvironmentSettings `json:"settings"` + Checkout *PromotionEnvironmentCheckoutState `json:"checkout,omitempty"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +// CreatePromotionEnvironmentRequest creates one environment for one direction +// on an existing provider. The settings must match the direction. +type CreatePromotionEnvironmentRequest struct { + Name string `json:"name"` + Scope string `json:"scope"` + ProviderID string `json:"providerId"` + Remote PromotionRemoteDocument `json:"remote"` + Direction string `json:"direction"` + Settings PromotionEnvironmentSettings `json:"settings"` +} + +// Validate rejects a creation document the API would reject before transport. +func (r CreatePromotionEnvironmentRequest) Validate() error { + if err := validatePromotionName(r.Name); err != nil { + return err + } + if err := validatePromotionScope(r.Scope); err != nil { + return err + } + if err := validatePromotionID(r.ProviderID, "provider ID"); err != nil { + return err + } + if err := r.Remote.Validate(); err != nil { + return err + } + if err := validatePromotionDirection(r.Direction); err != nil { + return err + } + return r.Settings.Validate(r.Direction) +} + +// UpdatePromotionEnvironmentRequest patches an environment. Only the supplied +// fields change, at least one is required, and a remote or settings replaces +// the whole saved value. Scope and direction cannot change. +type UpdatePromotionEnvironmentRequest struct { + Name *string `json:"name,omitempty"` + ProviderID *string `json:"providerId,omitempty"` + Remote *PromotionRemoteDocument `json:"remote,omitempty"` + Settings *PromotionEnvironmentSettings `json:"settings,omitempty"` +} + +// Validate rejects an empty or malformed update document before transport. +// Settings are checked against either direction; the server checks them +// against the stored one. +func (r UpdatePromotionEnvironmentRequest) Validate() error { + if r.Name == nil && r.ProviderID == nil && r.Remote == nil && r.Settings == nil { + return fmt.Errorf("promotion environment update is empty: set at least one of name, providerId, remote, or settings") + } + if r.Name != nil { + if err := validatePromotionName(*r.Name); err != nil { + return err + } + } + if r.ProviderID != nil { + if err := validatePromotionID(*r.ProviderID, "provider ID"); err != nil { + return err + } + } + if r.Remote != nil { + if err := r.Remote.Validate(); err != nil { + return err + } + } + if r.Settings != nil { + if err := r.Settings.Validate(""); err != nil { + return err + } + } + return nil +} + +// ListPromotionEnvironmentsOptions filters the environment list by the +// documented query filters: scope, direction, and provider ID. +type ListPromotionEnvironmentsOptions struct { + ListOptions + Scope string + Direction string + ProviderID string +} + +// Apply writes pagination plus the documented filters into q. +func (o ListPromotionEnvironmentsOptions) Apply(q url.Values) url.Values { + q = o.ListOptions.Apply(q) + if o.Scope != "" { + q.Set("scope", o.Scope) + } + if o.Direction != "" { + q.Set("direction", o.Direction) + } + if o.ProviderID != "" { + q.Set("providerId", o.ProviderID) + } + return q +} + +// Validate rejects options the API would reject before transport. +func (o ListPromotionEnvironmentsOptions) Validate() error { + if err := o.ListOptions.Validate(); err != nil { + return err + } + if o.ListOptions.Limit > 250 { + return fmt.Errorf("limit must not exceed 250, got %d", o.ListOptions.Limit) + } + if o.Scope != "" { + if err := validatePromotionScope(o.Scope); err != nil { + return err + } + } + if o.Direction != "" { + if err := validatePromotionDirection(o.Direction); err != nil { + return err + } + } + if o.ProviderID != "" { + if err := validatePromotionID(o.ProviderID, "provider ID"); err != nil { + return err + } + } + return nil +} + +// PromotionEnvironmentCheckout is the connect and disconnect acknowledgement: +// the environment's direction, branch, and whether a checkout now exists. +type PromotionEnvironmentCheckout struct { + EnvironmentID string `json:"environmentId"` + Direction string `json:"direction"` + BranchName string `json:"branchName"` + HasCheckout bool `json:"hasCheckout"` +} + +// PromotionEnvironmentProjects is the team projects linked to one environment. +type PromotionEnvironmentProjects struct { + ProjectIDs []string `json:"projectIds"` +} + +// PromotionEnvironmentProjectLink acknowledges linking one project to an +// environment. +type PromotionEnvironmentProjectLink struct { + ProjectID string `json:"projectId"` + EnvironmentID string `json:"environmentId"` +} + +// ListPromotionEnvironments returns one cursor-paginated page of environments. +func (c *Client) ListPromotionEnvironments(ctx context.Context, opts ListPromotionEnvironmentsOptions) (Page[PromotionEnvironment], error) { + if err := opts.Validate(); err != nil { + return Page[PromotionEnvironment]{}, err + } + var page Page[PromotionEnvironment] + if _, err := c.Do(ctx, Request{Path: PromotionEnvironmentsPath, Query: opts.Apply(nil)}, &page); err != nil { + return Page[PromotionEnvironment]{}, err + } + return page, nil +} + +// CreatePromotionEnvironment creates one environment. The instance can have +// one environment for each direction; a second one answers 409. +func (c *Client) CreatePromotionEnvironment(ctx context.Context, request CreatePromotionEnvironmentRequest) (*PromotionEnvironment, error) { + if err := request.Validate(); err != nil { + return nil, err + } + var created PromotionEnvironment + if _, err := c.Do(ctx, Request{ + Method: http.MethodPost, + Path: PromotionEnvironmentsPath, + Body: request, + }, &created); err != nil { + return nil, err + } + return &created, nil +} + +// GetPromotionEnvironment returns one environment with its checkout state. +func (c *Client) GetPromotionEnvironment(ctx context.Context, id string) (*PromotionEnvironment, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + var environment PromotionEnvironment + if _, err := c.Do(ctx, Request{Path: PathJoin("promotions", "environments", id)}, &environment); err != nil { + return nil, err + } + return &environment, nil +} + +// UpdatePromotionEnvironment patches one environment. +func (c *Client) UpdatePromotionEnvironment(ctx context.Context, id string, request UpdatePromotionEnvironmentRequest) (*PromotionEnvironment, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + var updated PromotionEnvironment + if _, err := c.Do(ctx, Request{ + Method: http.MethodPut, + Path: PathJoin("promotions", "environments", id), + Body: request, + }, &updated); err != nil { + return nil, err + } + return &updated, nil +} + +// DeletePromotionEnvironment removes one environment with its project links +// and local checkout. Its provider is kept and nothing in Git changes. +func (c *Client) DeletePromotionEnvironment(ctx context.Context, id string) error { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return err + } + _, err := c.Do(ctx, Request{Method: http.MethodDelete, Path: PathJoin("promotions", "environments", id)}, nil) + return err +} + +// ConnectPromotionEnvironment prepares the environment's checkout on the +// instance that handles the request. It is safe to repeat. +func (c *Client) ConnectPromotionEnvironment(ctx context.Context, id string) (*PromotionEnvironmentCheckout, error) { + return c.promotionEnvironmentCheckout(ctx, id, "connect") +} + +// DisconnectPromotionEnvironment removes the environment's local checkout and +// keeps the environment, its credentials, and its trusted SSH host keys. +func (c *Client) DisconnectPromotionEnvironment(ctx context.Context, id string) (*PromotionEnvironmentCheckout, error) { + return c.promotionEnvironmentCheckout(ctx, id, "disconnect") +} + +func (c *Client) promotionEnvironmentCheckout(ctx context.Context, id, action string) (*PromotionEnvironmentCheckout, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + var checkout PromotionEnvironmentCheckout + if _, err := c.Do(ctx, Request{ + Method: http.MethodPost, + Path: PathJoin("promotions", "environments", id, action), + }, &checkout); err != nil { + return nil, err + } + return &checkout, nil +} + +// ListPromotionEnvironmentProjects returns the team projects linked to one +// environment. +func (c *Client) ListPromotionEnvironmentProjects(ctx context.Context, id string) (*PromotionEnvironmentProjects, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + var projects PromotionEnvironmentProjects + if _, err := c.Do(ctx, Request{Path: PathJoin("promotions", "environments", id, "projects")}, &projects); err != nil { + return nil, err + } + return &projects, nil +} + +// AddProjectToPromotionEnvironment links one team project to a projects-scope +// environment. A project can have one environment per direction; a second +// link for the same direction answers 409. +func (c *Client) AddProjectToPromotionEnvironment(ctx context.Context, id, projectID string) (*PromotionEnvironmentProjectLink, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + if err := validatePromotionID(projectID, "project ID"); err != nil { + return nil, err + } + var link PromotionEnvironmentProjectLink + if _, err := c.Do(ctx, Request{ + Method: http.MethodPost, + Path: PathJoin("promotions", "environments", id, "projects", projectID), + }, &link); err != nil { + return nil, err + } + return &link, nil +} + +// RemoveProjectFromPromotionEnvironment unlinks one project from an +// environment. The project itself is untouched. +func (c *Client) RemoveProjectFromPromotionEnvironment(ctx context.Context, id, projectID string) error { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return err + } + if err := validatePromotionID(projectID, "project ID"); err != nil { + return err + } + _, err := c.Do(ctx, Request{ + Method: http.MethodDelete, + Path: PathJoin("promotions", "environments", id, "projects", projectID), + }, nil) + return err +} diff --git a/internal/n8n/promotion_environment_test.go b/internal/n8n/promotion_environment_test.go new file mode 100644 index 0000000..d2e52a4 --- /dev/null +++ b/internal/n8n/promotion_environment_test.go @@ -0,0 +1,410 @@ +package n8n + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" +) + +const testEnvironmentID = "0b8f7a2e-4c1d-4e5f-9a6b-7c8d9e0f1a2b" + +const promotionApplyEnvironmentBody = `{ + "id":"` + testEnvironmentID + `", + "name":"prod", + "scope":"instance", + "remote":{"schemaVersion":1,"remoteUrl":"https://gitlab.example.com/org/repo.git","repositoryPath":"org/repo"}, + "provider":{"id":"prov-1","name":"gitlab","type":"gitlab","authType":"token","createdAt":"2026-10-01T00:00:00.000Z","updatedAt":"2026-10-01T00:00:00.000Z"}, + "createdAt":"2026-10-01T00:00:00.000Z", + "updatedAt":"2026-10-01T00:00:00.000Z", + "direction":"apply", + "settings":{"schemaVersion":1,"branchName":"main"}, + "checkout":{"hasCheckout":true,"matchesEnvironment":false} +}` + +const promotionPromoteEnvironmentBody = `{ + "id":"` + testEnvironmentID + `", + "name":"prod-push", + "scope":"projects", + "remote":{"schemaVersion":1,"remoteUrl":"git@example.com:org/repo.git"}, + "provider":{"id":"prov-1","name":"github","type":"git","authType":"ssh-key","createdAt":"2026-10-01T00:00:00.000Z","updatedAt":"2026-10-01T00:00:00.000Z"}, + "createdAt":"2026-10-01T00:00:00.000Z", + "updatedAt":"2026-10-01T00:00:00.000Z", + "direction":"promote", + "settings":{"schemaVersion":1,"baseBranchName":"main","createBranchOnPromotion":false} +}` + +const promotionEnvironmentCheckoutBody = `{ + "environmentId":"` + testEnvironmentID + `", + "direction":"apply", + "branchName":"main", + "hasCheckout":true +}` + +func boolPtr(v bool) *bool { return &v } + +func validApplyEnvironment() CreatePromotionEnvironmentRequest { + return CreatePromotionEnvironmentRequest{ + Name: "prod", Scope: PromotionScopeInstance, ProviderID: "prov-1", + Remote: PromotionRemoteDocument{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"}, + Direction: PromotionDirectionApply, + Settings: PromotionEnvironmentSettings{SchemaVersion: 1, BranchName: "main"}, + } +} + +func TestListPromotionEnvironments(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[`+promotionApplyEnvironmentBody+`,`+promotionPromoteEnvironmentBody+`],"nextCursor":"next"}`)) + + page, err := server.client(t).ListPromotionEnvironments(context.Background(), ListPromotionEnvironmentsOptions{ + ListOptions: ListOptions{Limit: 10, Cursor: "c1"}, + Scope: PromotionScopeInstance, + Direction: PromotionDirectionApply, + ProviderID: "prov-1", + }) + if err != nil { + t.Fatalf("ListPromotionEnvironments: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodGet || req.URL.Path != BasePath+PromotionEnvironmentsPath { + t.Errorf("request = %s %s, want GET %s", req.Method, req.URL.Path, BasePath+PromotionEnvironmentsPath) + } + query := req.URL.Query() + if query.Get("limit") != "10" || query.Get("cursor") != "c1" || query.Get("scope") != "instance" || + query.Get("direction") != "apply" || query.Get("providerId") != "prov-1" { + t.Errorf("query = %q, want limit, cursor, scope, direction and providerId", req.URL.RawQuery) + } + if body != "" { + t.Errorf("body = %q, want empty", body) + } + if len(page.Data) != 2 || page.NextCursor != "next" { + t.Fatalf("page = %+v, want two environments with a cursor", page) + } + apply, promote := page.Data[0], page.Data[1] + if apply.Direction != PromotionDirectionApply || apply.Settings.BranchName != "main" || apply.Remote.RepositoryPath != "org/repo" { + t.Errorf("apply environment = %+v", apply) + } + if apply.Checkout == nil || !apply.Checkout.HasCheckout || apply.Checkout.MatchesEnvironment { + t.Errorf("apply checkout = %+v, want a stale checkout", apply.Checkout) + } + if promote.Direction != PromotionDirectionPromote || promote.Settings.BaseBranchName != "main" || + promote.Settings.CreateBranchOnPromotion == nil || *promote.Settings.CreateBranchOnPromotion || promote.Checkout != nil { + t.Errorf("promote environment = %+v", promote) + } +} + +func TestListPromotionEnvironmentsValidation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[],"nextCursor":null}`)) + client := server.client(t) + + cases := []ListPromotionEnvironmentsOptions{ + {ListOptions: ListOptions{Limit: 251}}, + {Scope: "global"}, + {Direction: "sideways"}, + {ProviderID: " "}, + } + for i, opts := range cases { + if _, err := client.ListPromotionEnvironments(context.Background(), opts); err == nil { + t.Errorf("case %d: want a validation error", i) + } + } + if len(server.requests) != 0 { + t.Errorf("requests = %d, want 0 before transport", len(server.requests)) + } +} + +func TestCreatePromotionEnvironment(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, promotionPromoteEnvironmentBody)) + + request := CreatePromotionEnvironmentRequest{ + Name: "prod-push", Scope: PromotionScopeProjects, ProviderID: "prov-1", + Remote: PromotionRemoteDocument{SchemaVersion: 1, RemoteURL: "git@example.com:org/repo.git"}, + Direction: PromotionDirectionPromote, + Settings: PromotionEnvironmentSettings{SchemaVersion: 1, BaseBranchName: "main", CreateBranchOnPromotion: boolPtr(false)}, + } + created, err := server.client(t).CreatePromotionEnvironment(context.Background(), request) + if err != nil { + t.Fatalf("CreatePromotionEnvironment: %v", err) + } + req, raw := server.last(t) + if req.Method != http.MethodPost || req.URL.Path != BasePath+PromotionEnvironmentsPath { + t.Errorf("request = %s %s, want POST %s", req.Method, req.URL.Path, BasePath+PromotionEnvironmentsPath) + } + var sent map[string]any + if err := json.Unmarshal([]byte(raw), &sent); err != nil { + t.Fatalf("request body is not JSON: %v\n%s", err, raw) + } + if sent["direction"] != "promote" || sent["providerId"] != "prov-1" || sent["scope"] != "projects" { + t.Errorf("request = %v, want direction, providerId and scope", sent) + } + settings, _ := sent["settings"].(map[string]any) + if _, ok := settings["branchName"]; ok || settings["createBranchOnPromotion"] != false || settings["baseBranchName"] != "main" { + t.Errorf("settings = %v, want only the promote shape with an explicit false", settings) + } + if strings.Contains(raw, "repositoryPath") || strings.Contains(raw, `"id"`) || strings.Contains(raw, "checkout") { + t.Errorf("request carries a read-only field: %s", raw) + } + if created.ID != testEnvironmentID || created.Direction != PromotionDirectionPromote { + t.Errorf("created = %+v", created) + } +} + +func TestCreatePromotionEnvironmentValidation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusCreated, promotionApplyEnvironmentBody)) + client := server.client(t) + + mutate := func(change func(*CreatePromotionEnvironmentRequest)) CreatePromotionEnvironmentRequest { + request := validApplyEnvironment() + change(&request) + return request + } + cases := map[string]CreatePromotionEnvironmentRequest{ + "empty": {}, + "blank name": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Name = " " }), + "bad scope": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Scope = "global" }), + "no provider": mutate(func(r *CreatePromotionEnvironmentRequest) { r.ProviderID = "" }), + "remote version": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Remote.SchemaVersion = 2 }), + "remote url": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Remote.RemoteURL = " " }), + "bad direction": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Direction = "sideways" }), + "mismatched": mutate(func(r *CreatePromotionEnvironmentRequest) { + r.Direction = PromotionDirectionPromote + }), + "mixed settings": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Settings.BaseBranchName = "main" }), + "blank branch": mutate(func(r *CreatePromotionEnvironmentRequest) { r.Settings.BranchName = " " }), + "settings version": mutate(func(r *CreatePromotionEnvironmentRequest) { + r.Settings.SchemaVersion = 0 + }), + "promote without create flag": mutate(func(r *CreatePromotionEnvironmentRequest) { + r.Direction = PromotionDirectionPromote + r.Settings = PromotionEnvironmentSettings{SchemaVersion: 1, BaseBranchName: "main"} + }), + } + for name, request := range cases { + if _, err := client.CreatePromotionEnvironment(context.Background(), request); err == nil { + t.Errorf("%s: want a validation error", name) + } + } + if len(server.requests) != 0 { + t.Errorf("requests = %d, want 0 before transport", len(server.requests)) + } +} + +func TestGetPromotionEnvironment(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, promotionApplyEnvironmentBody)) + + environment, err := server.client(t).GetPromotionEnvironment(context.Background(), testEnvironmentID) + if err != nil { + t.Fatalf("GetPromotionEnvironment: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodGet || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + if body != "" { + t.Errorf("body = %q, want empty", body) + } + if environment.Name != "prod" || environment.Provider.Type != PromotionProviderTypeGitLab { + t.Errorf("environment = %+v", environment) + } +} + +func TestPromotionEnvironmentIDValidation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, promotionApplyEnvironmentBody)) + client := server.client(t) + ctx := context.Background() + + for _, id := range []string{"", " " + testEnvironmentID, "env-1", "a/b", testEnvironmentID + "0"} { + if _, err := client.GetPromotionEnvironment(ctx, id); err == nil { + t.Errorf("get %q: want a validation error", id) + } + if err := client.DeletePromotionEnvironment(ctx, id); err == nil { + t.Errorf("delete %q: want a validation error", id) + } + if _, err := client.ConnectPromotionEnvironment(ctx, id); err == nil { + t.Errorf("connect %q: want a validation error", id) + } + if _, err := client.ListPromotionEnvironmentProjects(ctx, id); err == nil { + t.Errorf("projects %q: want a validation error", id) + } + } + if _, err := client.AddProjectToPromotionEnvironment(ctx, testEnvironmentID, " "); err == nil { + t.Error("blank project ID: want a validation error") + } + if err := client.RemoveProjectFromPromotionEnvironment(ctx, testEnvironmentID, ""); err == nil { + t.Error("empty project ID: want a validation error") + } + if len(server.requests) != 0 { + t.Errorf("requests = %d, want 0 before transport", len(server.requests)) + } + if err := ValidatePromotionEnvironmentID(strings.ToUpper(testEnvironmentID)); err != nil { + t.Errorf("upper-case UUID: %v", err) + } +} + +func TestUpdatePromotionEnvironment(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, promotionApplyEnvironmentBody)) + + updated, err := server.client(t).UpdatePromotionEnvironment(context.Background(), testEnvironmentID, UpdatePromotionEnvironmentRequest{ + Name: strPtr("staging"), + Settings: &PromotionEnvironmentSettings{SchemaVersion: 1, BranchName: "release"}, + }) + if err != nil { + t.Fatalf("UpdatePromotionEnvironment: %v", err) + } + req, raw := server.last(t) + if req.Method != http.MethodPut || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID { + t.Errorf("request = %s %s, want PUT", req.Method, req.URL.Path) + } + var sent map[string]json.RawMessage + if err := json.Unmarshal([]byte(raw), &sent); err != nil { + t.Fatalf("body = %q (error %v)", raw, err) + } + if string(sent["name"]) != `"staging"` || string(sent["settings"]) != `{"schemaVersion":1,"branchName":"release"}` || len(sent) != 2 { + t.Errorf("body = %s, want only name and settings", raw) + } + if updated.ID != testEnvironmentID { + t.Errorf("updated = %+v", updated) + } +} + +func TestUpdatePromotionEnvironmentValidation(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, promotionApplyEnvironmentBody)) + client := server.client(t) + + cases := map[string]UpdatePromotionEnvironmentRequest{ + "empty": {}, + "blank name": {Name: strPtr("")}, + "blank provider": {ProviderID: strPtr(" ")}, + "bad remote": {Remote: &PromotionRemoteDocument{SchemaVersion: 9, RemoteURL: "x"}}, + "mixed settings": {Settings: &PromotionEnvironmentSettings{SchemaVersion: 1, BranchName: "a", BaseBranchName: "b"}}, + "no settings": {Settings: &PromotionEnvironmentSettings{SchemaVersion: 1}}, + } + for name, request := range cases { + if _, err := client.UpdatePromotionEnvironment(context.Background(), testEnvironmentID, request); err == nil { + t.Errorf("%s: want a validation error", name) + } + } + if len(server.requests) != 0 { + t.Errorf("requests = %d, want 0 before transport", len(server.requests)) + } +} + +func TestPromotionEnvironmentSettingsValidateDirection(t *testing.T) { + apply := PromotionEnvironmentSettings{SchemaVersion: 1, BranchName: "main"} + promote := PromotionEnvironmentSettings{SchemaVersion: 1, BaseBranchName: "main", CreateBranchOnPromotion: boolPtr(true)} + if err := apply.Validate(PromotionDirectionApply); err != nil { + t.Errorf("apply/apply: %v", err) + } + if err := promote.Validate(PromotionDirectionPromote); err != nil { + t.Errorf("promote/promote: %v", err) + } + if err := apply.Validate(PromotionDirectionPromote); err == nil || !strings.Contains(err.Error(), "direction is promote") { + t.Errorf("apply/promote = %v, want a direction mismatch", err) + } + if err := promote.Validate(""); err != nil { + t.Errorf("promote/any: %v", err) + } +} + +func TestDeletePromotionEnvironment(t *testing.T) { + server := newCommunityPackageServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + + if err := server.client(t).DeletePromotionEnvironment(context.Background(), testEnvironmentID); err != nil { + t.Fatalf("DeletePromotionEnvironment: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodDelete || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + if body != "" { + t.Errorf("body = %q, want empty", body) + } +} + +func TestConnectDisconnectPromotionEnvironment(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, promotionEnvironmentCheckoutBody)) + client := server.client(t) + + checkout, err := client.ConnectPromotionEnvironment(context.Background(), testEnvironmentID) + if err != nil { + t.Fatalf("ConnectPromotionEnvironment: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodPost || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID+"/connect" { + t.Errorf("connect request = %s %s", req.Method, req.URL.Path) + } + if body != "" { + t.Errorf("connect body = %q, want empty", body) + } + if checkout.EnvironmentID != testEnvironmentID || checkout.Direction != PromotionDirectionApply || !checkout.HasCheckout { + t.Errorf("checkout = %+v", checkout) + } + + if _, err := client.DisconnectPromotionEnvironment(context.Background(), testEnvironmentID); err != nil { + t.Fatalf("DisconnectPromotionEnvironment: %v", err) + } + req, _ = server.last(t) + if req.Method != http.MethodPost || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID+"/disconnect" { + t.Errorf("disconnect request = %s %s", req.Method, req.URL.Path) + } +} + +func TestPromotionEnvironmentProjects(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"projectIds":["p1","p2"]}`)) + + projects, err := server.client(t).ListPromotionEnvironmentProjects(context.Background(), testEnvironmentID) + if err != nil { + t.Fatalf("ListPromotionEnvironmentProjects: %v", err) + } + req, _ := server.last(t) + if req.Method != http.MethodGet || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID+"/projects" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + if len(projects.ProjectIDs) != 2 { + t.Errorf("projects = %+v", projects) + } +} + +func TestAddRemovePromotionEnvironmentProject(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"projectId":"p1","environmentId":"`+testEnvironmentID+`"}`)) + + link, err := server.client(t).AddProjectToPromotionEnvironment(context.Background(), testEnvironmentID, "p1") + if err != nil { + t.Fatalf("AddProjectToPromotionEnvironment: %v", err) + } + req, body := server.last(t) + if req.Method != http.MethodPost || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID+"/projects/p1" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } + if body != "" { + t.Errorf("body = %q, want empty", body) + } + if link.ProjectID != "p1" || link.EnvironmentID != testEnvironmentID { + t.Errorf("link = %+v", link) + } + + removeServer := newCommunityPackageServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) + if err := removeServer.client(t).RemoveProjectFromPromotionEnvironment(context.Background(), testEnvironmentID, "p1"); err != nil { + t.Fatalf("RemoveProjectFromPromotionEnvironment: %v", err) + } + req, _ = removeServer.last(t) + if req.Method != http.MethodDelete || req.URL.Path != BasePath+PromotionEnvironmentsPath+"/"+testEnvironmentID+"/projects/p1" { + t.Errorf("request = %s %s", req.Method, req.URL.Path) + } +} + +func TestPromotionEnvironmentProjectEscapesID(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"projectId":"a/b c","environmentId":"`+testEnvironmentID+`"}`)) + + if _, err := server.client(t).AddProjectToPromotionEnvironment(context.Background(), testEnvironmentID, "a/b c"); err != nil { + t.Fatalf("AddProjectToPromotionEnvironment: %v", err) + } + req, _ := server.last(t) + if !strings.HasSuffix(req.URL.EscapedPath(), "/projects/a%2Fb%20c") { + t.Errorf("path = %q, want the project ID escaped", req.URL.EscapedPath()) + } +} diff --git a/test/integration/promotion_environment_test.go b/test/integration/promotion_environment_test.go new file mode 100644 index 0000000..7ec826c --- /dev/null +++ b/test/integration/promotion_environment_test.go @@ -0,0 +1,91 @@ +package integration_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/cli" + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/SomeoneWithOptions/n8n-cli/internal/version" + "github.com/SomeoneWithOptions/n8n-cli/test/integration" +) + +// TestPromotionEnvironments verifies the read-only environment list, get, and +// project list through both client and CLI. Instances older than n8n 2.46 +// serve connections instead and answer 404, which skips. Nothing is created, +// connected, or linked: environments mutate instance-wide sync state. +func TestPromotionEnvironments(t *testing.T) { + instance := integration.Require(t) + client := instance.Client(t) + ctx := context.Background() + + page, err := client.ListPromotionEnvironments(ctx, n8n.ListPromotionEnvironmentsOptions{}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatalf("ListPromotionEnvironments: %v", err) + } + for _, environment := range page.Data { + if environment.ID == "" || environment.Name == "" || environment.Scope == "" { + t.Errorf("environment is missing id, name, or scope: %+v", environment) + } + if environment.Direction != n8n.PromotionDirectionApply && environment.Direction != n8n.PromotionDirectionPromote { + t.Errorf("environment %q direction = %q, want apply or promote", environment.ID, environment.Direction) + } + if environment.Settings.Direction() != environment.Direction { + t.Errorf("environment %q settings %+v do not match direction %q", environment.ID, environment.Settings, environment.Direction) + } + } + filtered, err := client.ListPromotionEnvironments(ctx, n8n.ListPromotionEnvironmentsOptions{Direction: n8n.PromotionDirectionApply}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatalf("ListPromotionEnvironments with direction: %v", err) + } + for _, environment := range filtered.Data { + if environment.Direction != n8n.PromotionDirectionApply { + t.Errorf("direction filter returned %q environment %q", environment.Direction, environment.ID) + } + } + if len(page.Data) > 0 { + first := page.Data[0] + got, err := client.GetPromotionEnvironment(ctx, first.ID) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatalf("GetPromotionEnvironment(%q): %v", first.ID, err) + } + if got.ID != first.ID || got.Checkout == nil { + t.Errorf("get = %+v, want ID %q with a checkout state", got, first.ID) + } + if _, err := client.ListPromotionEnvironmentProjects(ctx, first.ID); err != nil { + skipUnlessPromotions(t, err) + t.Fatalf("ListPromotionEnvironmentProjects(%q): %v", first.ID, err) + } + } + + env := map[string]string{config.EnvURL: instance.URL, config.EnvAPIKey: instance.APIKey.Reveal()} + interactive := false + var out, errOut strings.Builder + code := cli.Run(ctx, []string{"promotion", "environment", "list", "--output", "json"}, cli.Options{ + Streams: cli.Streams{In: strings.NewReader(""), Out: &out, Err: &errOut}, + Version: version.Get(), + ConfigDir: t.TempDir(), + Env: func(name string) string { return env[name] }, + Keyring: config.NewMemoryStore(config.StorageKeyring), + Interactive: &interactive, + }) + if code != cli.ExitSuccess { + if strings.Contains(errOut.String(), "403") || strings.Contains(errOut.String(), "404") || strings.Contains(errOut.String(), "503") { + t.Skip("integration instance has no promotion environments") + } + t.Fatalf("promotion environment list exit code = %d (stderr: %s)", code, errOut.String()) + } + var listPage n8n.Page[n8n.PromotionEnvironment] + if err := json.Unmarshal([]byte(out.String()), &listPage); err != nil { + t.Fatalf("stdout is not a promotion environment page: %v\n%s", err, out.String()) + } + if strings.Contains(out.String(), instance.APIKey.Reveal()) { + t.Error("API credential leaked into stdout") + } +}