diff --git a/docs/README.md b/docs/README.md index 70d976c..66af234 100644 --- a/docs/README.md +++ b/docs/README.md @@ -170,6 +170,8 @@ 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 apply-continue`](n8n_promotion_environment_apply-continue.md) | Continue a reviewed environment apply after binding setup | +| [`n8n promotion environment apply`](n8n_promotion_environment_apply.md) | Apply an environment's Git branch into this instance | | [`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 | @@ -180,6 +182,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`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 promote`](n8n_promotion_environment_promote.md) | Promote team projects to an environment's Git remote | | [`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 | diff --git a/docs/n8n_promotion.md b/docs/n8n_promotion.md index deaadcd..d69786b 100644 --- a/docs/n8n_promotion.md +++ b/docs/n8n_promotion.md @@ -11,23 +11,27 @@ 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. +'environment project'. Sync the whole instance with 'environment +promote' and 'environment apply' (then 'environment apply-continue' +after resolving a blocked apply) on the instance-scope environment. 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. +remote into the instance, and 'apply-continue' after resolving a +blocked apply. These run on the instance connection. -'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. +On both generations, start selected-workflow sync with 'project +changes', then 'project apply' or 'project promote'; the project's own +environment or connection resolves before the instance one. + +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, 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 @@ -43,6 +47,8 @@ n8n promotion [flags] n8n promotion provider list n8n promotion environment list n8n promotion environment connect ENVIRONMENT_ID + n8n promotion environment apply ENVIRONMENT_ID --yes + n8n promotion environment promote ENVIRONMENT_ID --commit-message "sync" --yes n8n promotion connection list n8n promotion provider create --input provider.json n8n promotion connection create --input connection.json diff --git a/docs/n8n_promotion_apply-continue.md b/docs/n8n_promotion_apply-continue.md index 64afbf0..9c297b9 100644 --- a/docs/n8n_promotion_apply-continue.md +++ b/docs/n8n_promotion_apply-continue.md @@ -5,15 +5,18 @@ Continue a reviewed connection apply after binding setup ### Synopsis Continue a full instance-connection apply after resolving its preflight items. -Start with 'n8n promotion apply CONNECTION_ID --output json'. The apply -checkout must be cloned. Every team project is synchronized: workflows, +Connections exist before n8n 2.46; on 2.46 use 'n8n promotion environment +apply-continue'. Start with 'n8n promotion apply CONNECTION_ID --output json'. +The apply checkout must be cloned. Every team project is synchronized: workflows, folders, credentials, tables, variables, and tags can change or be removed. Requires gitConnection:pull and the same permissions as the initial apply. Use --expected-from FILE|- with changes JSON or a blocked apply result, -or supply all three --expected-config-id, --expected-branch, --expected-commit -flags (full lowercase 40- or 64-digit hex SHA). A null commit cannot be used. -Expected source is required; use the blocked result's configId and git. -The server keeps no session and provides no exactly-once guarantee. +or supply --expected-config-id, --expected-branch, and +--expected-commit together (full lowercase 40- or 64-digit hex SHA). A +null commit cannot be used. --expected-from passes through the +identifier the instance returned: configId. +Expected source is required; use the blocked result's configId +and git. The server keeps no session and provides no exactly-once guarantee. --confirm-destructive-changes permits removal or retyping of data-table columns and loss of their values; rows and other columns remain. It also permits deleting team projects with everything in them. @@ -48,8 +51,8 @@ n8n promotion apply-continue [flags] ``` --confirm-destructive-changes allow all destructive changes at continue time, including unreviewed column value loss and, for full apply, team-project deletion (default: false) --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --expected-branch string reviewed branch name (default: omitted; requires expected config ID and commit) - --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires expected config ID and branch) + --expected-branch string reviewed branch name (default: omitted; requires the expected ID and commit) + --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch) --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) -h, --help help for apply-continue diff --git a/docs/n8n_promotion_apply.md b/docs/n8n_promotion_apply.md index 18e45b4..07ee9d1 100644 --- a/docs/n8n_promotion_apply.md +++ b/docs/n8n_promotion_apply.md @@ -6,7 +6,8 @@ Apply the Git remote into this instance Check the full package at the apply branch tip and import it into the instance, overwriting to match. Runs on the instance connection; the -apply checkout must be cloned first. +apply checkout must be cloned first. Connections exist before n8n +2.46; on 2.46 use 'n8n promotion environment apply'. The server answers one of three statuses, and only one writes: applied content was imported; counts and warnings follow. diff --git a/docs/n8n_promotion_environment.md b/docs/n8n_promotion_environment.md index 2170af2..d31562c 100644 --- a/docs/n8n_promotion_environment.md +++ b/docs/n8n_promotion_environment.md @@ -16,6 +16,13 @@ and 'disconnect' removes it. Link team projects to a projects-scope environment under 'project'. The instance can have one environment for each direction. +Sync the whole instance through the connected instance-scope +environment: 'promote' pushes every team project to a promote +environment; 'apply' imports an apply environment's branch, and +'apply-continue' finishes an apply that preflight blocked. For selected +workflows of one project use 'n8n promotion project changes', 'apply', +and 'promote'. + Deleting an environment removes its project links and local checkout; its provider is kept and nothing in Git changes. @@ -30,6 +37,8 @@ n8n promotion environment [flags] n8n promotion environment get ENVIRONMENT_ID n8n promotion environment create --input environment.json n8n promotion environment connect ENVIRONMENT_ID + n8n promotion environment apply ENVIRONMENT_ID --yes + n8n promotion environment promote ENVIRONMENT_ID --commit-message "sync" --yes n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID ``` @@ -42,6 +51,8 @@ n8n promotion environment [flags] ### SEE ALSO * [n8n promotion](n8n_promotion.md) - Manage promotion providers, environments, connections, and apply/promote sync +* [n8n promotion environment apply](n8n_promotion_environment_apply.md) - Apply an environment's Git branch into this instance +* [n8n promotion environment apply-continue](n8n_promotion_environment_apply-continue.md) - Continue a reviewed environment apply after binding setup * [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 @@ -49,5 +60,6 @@ n8n promotion environment [flags] * [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 promote](n8n_promotion_environment_promote.md) - Promote team projects to an environment's Git remote * [n8n promotion environment update](n8n_promotion_environment_update.md) - Update a promotion environment diff --git a/docs/n8n_promotion_environment_apply-continue.md b/docs/n8n_promotion_environment_apply-continue.md new file mode 100644 index 0000000..e0676a1 --- /dev/null +++ b/docs/n8n_promotion_environment_apply-continue.md @@ -0,0 +1,71 @@ +## n8n promotion environment apply-continue + +Continue a reviewed environment apply after binding setup + +### Synopsis + +Continue a full environment apply (n8n 2.46 and later) after resolving its +preflight items. Start with 'n8n promotion environment apply ENVIRONMENT_ID +--output json'. The instance-scope apply environment must still be +connected. Every team project is synchronized: workflows, folders, +credentials, tables, variables, and tags can be created, updated, moved, +renamed, or removed to match. Requires gitConnection:pull and the same +permissions as the initial apply. + +Use --expected-from FILE|- with changes JSON or a blocked apply result, +or supply --expected-environment-id, --expected-branch, and +--expected-commit together (full lowercase 40- or 64-digit hex SHA). A +null commit cannot be used. --expected-from passes through the +identifier the instance returned: environmentId. +Expected source is required; use the blocked result's environmentId +and git. The server keeps no session and provides no exactly-once guarantee. +--confirm-destructive-changes permits removal or retyping of data-table +columns and loss of their values; rows and other columns remain. +It also permits deleting team projects with everything in them. +This covers every such change at continue time, including changes absent +from the reviewed result. +Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 other error. Only +applied writes content. Resolve blocked bindings before apply-continue; +review source-changed results again. JSON prints the full status result; +text shows preflight details or counts and warnings. Hints go to stderr. +Read request JSON with --input FILE|- (maximum 1 MiB). Input and document flags are +mutually exclusive. Interactive runs ask for confirmation; non-interactive +runs and stdin input require --yes. JSON returns the server result; text +shows counts and the commit after success. + +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + +``` +n8n promotion environment apply-continue [flags] +``` + +### Examples + +``` + n8n promotion environment apply-continue ENVIRONMENT_ID --expected-from blocked.json + n8n promotion environment apply-continue ENVIRONMENT_ID --input request.json --yes --output json +``` + +### Options + +``` + --confirm-destructive-changes allow all destructive changes at continue time, including unreviewed column value loss and, for full apply, team-project deletion (default: false) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --expected-branch string reviewed branch name (default: omitted; requires the expected ID and commit) + --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch) + --expected-environment-id string reviewed environment ID, 1 to 36 characters (default: omitted; requires expected branch and commit) + --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) + -h, --help help for apply-continue + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) + --output string output format: text or json (default: text; JSON is the full server result) (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 content changes without prompting (default: prompt; required for non-interactive or stdin input) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_apply.md b/docs/n8n_promotion_environment_apply.md new file mode 100644 index 0000000..0e89286 --- /dev/null +++ b/docs/n8n_promotion_environment_apply.md @@ -0,0 +1,70 @@ +## n8n promotion environment apply + +Apply an environment's Git branch into this instance + +### Synopsis + +Check the full package at the branch tip of an instance-scope apply +environment (n8n 2.46 and later) and import it into the instance, +overwriting to match. Before 2.46 use 'n8n promotion apply' with a +connection. Start with 'n8n promotion environment list --direction +apply' and connect it first with 'n8n promotion environment connect'. +Personal projects are ignored. An applied run rewrites every team +project from the branch and cannot be undone: workflows, folders, +credentials, data tables, variables, and tags are created, updated, +or removed to match, workflows and folders move within their project, +folders take the branch name, and credential gaps become stubs. +Existing variable values are kept. A workflow or folder the branch and +the instance hold in different projects is refused with 409 before any +write. Requires gitConnection:pull. + +Use --expected-from FILE|- with changes JSON or a blocked apply result, +or supply --expected-environment-id, --expected-branch, and +--expected-commit together (full lowercase 40- or 64-digit hex SHA). A +null commit cannot be used. --expected-from passes through the +identifier the instance returned: environmentId. +Expected source is optional; supply it to detect changes after review. +Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 other error. Only +applied writes content. Resolve blocked bindings before apply-continue; +review source-changed results again. JSON prints the full status result; +text shows preflight details or counts and warnings. Hints go to stderr. +Read request JSON with --input FILE|- (maximum 1 MiB). Input and document flags are +mutually exclusive. Interactive runs ask for confirmation; non-interactive +runs and stdin input require --yes. JSON returns the server result; text +shows counts and the commit after success. + +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + +``` +n8n promotion environment apply [flags] +``` + +### Examples + +``` + n8n promotion environment apply ENVIRONMENT_ID + n8n promotion environment apply ENVIRONMENT_ID --input request.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') + --expected-branch string reviewed branch name (default: omitted; requires the expected ID and commit) + --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch) + --expected-environment-id string reviewed environment ID, 1 to 36 characters (default: omitted; requires expected branch and commit) + --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) + -h, --help help for apply + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) + --output string output format: text or json (default: text; JSON is the full server result) (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 content changes without prompting (default: prompt; required for non-interactive or stdin input) +``` + +### SEE ALSO + +* [n8n promotion environment](n8n_promotion_environment.md) - Manage promotion environments (n8n 2.46 and later) + diff --git a/docs/n8n_promotion_environment_promote.md b/docs/n8n_promotion_environment_promote.md new file mode 100644 index 0000000..6b520bf --- /dev/null +++ b/docs/n8n_promotion_environment_promote.md @@ -0,0 +1,62 @@ +## n8n promotion environment promote + +Promote team projects to an environment's Git remote + +### Synopsis + +Export every team project, commit it, and push through an +instance-scope promote environment (n8n 2.46 and later) to its base +branch or a new timestamped branch (the result names it). Before 2.46 +use 'n8n promotion promote' with a connection. Start with 'n8n +promotion environment list --direction promote' and connect it first +with 'n8n promotion environment connect'. Personal projects are +ignored, and project links do not select what is promoted; for one +project's workflows use 'n8n promotion project promote'. A workflow on +the branch that moved to a personal project, or to another team project +while its old project still exists, is refused with 400. + +--commit-message is optional (1 to 1000 characters; default: a +server-generated message). Without --force a promote the remote would +reject is refused with 409 and nothing is pushed; --force pushes anyway +and rewrites remote history. This mutates the remote branch. +Interactive runs ask for confirmation and non-interactive runs require +--yes. Requires gitConnection:push, plus variable:list when workflows +reference variables. + +Text shows the commit, branch, counts, and any review the Git host +opened; JSON is the full result. Advisory warnings go to stderr in both +formats. + +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + +``` +n8n promotion environment promote [flags] +``` + +### Examples + +``` + n8n promotion environment promote ENVIRONMENT_ID --commit-message "sync workflows" + n8n promotion environment promote ENVIRONMENT_ID --yes + n8n promotion environment promote ENVIRONMENT_ID --commit-message "sync" --force --yes --output json +``` + +### Options + +``` + --commit-message string commit message for the promote, 1 to 1000 characters (default: server-generated message) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --force promote even when the remote would reject it, rewriting remote history (default: reject a rejected promote with 409) + -h, --help help for promote + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --output string output format: text or json (JSON is the promote result with counts, commit, and any review and warnings) (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 promoting every team project to the remote 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_project.md b/docs/n8n_promotion_project.md index dbdedb9..079fd91 100644 --- a/docs/n8n_promotion_project.md +++ b/docs/n8n_promotion_project.md @@ -14,10 +14,12 @@ A project can belong to only one connection, so adding a linked project elsewhere answers 409. Removing unlinks the project; its instance content is untouched. Project IDs come from 'n8n project list'. Adding and listing need gitConnection:read for reads and -gitConnection:manageProjects for writes. For selected workflow sync, -start with changes PROJECT_ID apply|promote, then apply or promote. -Selection commands take a project ID first and resolve its own connection -before falling back to the instance connection. +gitConnection:manageProjects for writes; on n8n 2.46 and later link +projects with 'n8n promotion environment project' instead. For selected +workflow sync on either generation, start with changes PROJECT_ID +apply|promote, then apply or promote. Selection commands take a project +ID first and resolve its own environment (2.46) or connection (older) +before falling back to the instance one. ``` n8n promotion project [flags] diff --git a/docs/n8n_promotion_project_apply-continue.md b/docs/n8n_promotion_project_apply-continue.md index 8b99bec..99663a1 100644 --- a/docs/n8n_promotion_project_apply-continue.md +++ b/docs/n8n_promotion_project_apply-continue.md @@ -5,16 +5,24 @@ Continue a reviewed project apply after binding setup ### Synopsis Start with 'n8n promotion project changes PROJECT_ID apply' to review workflow IDs. -The project's own connection resolves first, otherwise the instance connection. -The apply direction must be cloned. Selected IDs on the branch are imported; -selected workflows owned by this project whose IDs are absent from the branch -are removed. Unselected content stays unchanged. Duplicate or invalid IDs -reject the whole request. Requires gitConnection:pull. +The project's own apply environment (n8n 2.46 and later) or connection +(older) resolves first, otherwise the instance one. It must be prepared: +'n8n promotion environment connect' on 2.46, 'n8n promotion checkout +clone' before. Selected IDs on the branch are imported; selected workflows +owned by this project whose IDs are absent from the branch are removed. +On 2.46 a selected workflow also moves within the project to match the +branch, with the folders that hold it, which take the branch name; one +the branch and the instance hold in different projects is refused with +409 before any write. Unselected content stays unchanged. Duplicate or +invalid IDs reject the whole request. Requires gitConnection:pull. Use --expected-from FILE|- with changes JSON or a blocked apply result, -or supply all three --expected-config-id, --expected-branch, --expected-commit -flags (full lowercase 40- or 64-digit hex SHA). A null commit cannot be used. -Expected source is required; use the blocked result's configId and git. -The server keeps no session and provides no exactly-once guarantee. +or supply --expected-environment-id (n8n 2.46 and later) or +--expected-config-id (older; mutually exclusive), --expected-branch, and +--expected-commit together (full lowercase 40- or 64-digit hex SHA). A +null commit cannot be used. --expected-from passes through the +identifier the instance returned: environmentId (2.46) or configId (older). +Expected source is required; use the blocked result's environmentId (2.46) or configId (older) +and git. The server keeps no session and provides no exactly-once guarantee. Resend the same full workflow ID selection used for the initial apply. --confirm-destructive-changes permits removal or retyping of data-table columns and loss of their values; rows and other columns remain. @@ -49,19 +57,20 @@ n8n promotion project apply-continue [flags] ### Options ``` - --confirm-destructive-changes allow all destructive changes at continue time, including unreviewed column value loss and, for full apply, team-project deletion (default: false) - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --expected-branch string reviewed branch name (default: omitted; requires expected config ID and commit) - --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires expected config ID and branch) - --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) - --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) - -h, --help help for apply-continue - --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) - --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) - --output string output format: text or json (default: text; JSON is the full server result) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --workflow-id stringArray selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used) - --yes confirm content changes without prompting (default: prompt; required for non-interactive or stdin input) + --confirm-destructive-changes allow all destructive changes at continue time, including unreviewed column value loss and, for full apply, team-project deletion (default: false) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --expected-branch string reviewed branch name (default: omitted; requires the expected ID and commit) + --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch) + --expected-config-id string reviewed config ID on n8n 2.45 and earlier, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-environment-id) + --expected-environment-id string reviewed environment ID on n8n 2.46 and later, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-config-id) + --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) + -h, --help help for apply-continue + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) + --output string output format: text or json (default: text; JSON is the full server result) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --workflow-id stringArray selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used) + --yes confirm content changes without prompting (default: prompt; required for non-interactive or stdin input) ``` ### SEE ALSO diff --git a/docs/n8n_promotion_project_apply.md b/docs/n8n_promotion_project_apply.md index 54bbcde..17beffa 100644 --- a/docs/n8n_promotion_project_apply.md +++ b/docs/n8n_promotion_project_apply.md @@ -5,14 +5,22 @@ Apply selected workflow changes from a project's branch ### Synopsis Start with 'n8n promotion project changes PROJECT_ID apply' to review workflow IDs. -The project's own connection resolves first, otherwise the instance connection. -The apply direction must be cloned. Selected IDs on the branch are imported; -selected workflows owned by this project whose IDs are absent from the branch -are removed. Unselected content stays unchanged. Duplicate or invalid IDs -reject the whole request. Requires gitConnection:pull. +The project's own apply environment (n8n 2.46 and later) or connection +(older) resolves first, otherwise the instance one. It must be prepared: +'n8n promotion environment connect' on 2.46, 'n8n promotion checkout +clone' before. Selected IDs on the branch are imported; selected workflows +owned by this project whose IDs are absent from the branch are removed. +On 2.46 a selected workflow also moves within the project to match the +branch, with the folders that hold it, which take the branch name; one +the branch and the instance hold in different projects is refused with +409 before any write. Unselected content stays unchanged. Duplicate or +invalid IDs reject the whole request. Requires gitConnection:pull. Use --expected-from FILE|- with changes JSON or a blocked apply result, -or supply all three --expected-config-id, --expected-branch, --expected-commit -flags (full lowercase 40- or 64-digit hex SHA). A null commit cannot be used. +or supply --expected-environment-id (n8n 2.46 and later) or +--expected-config-id (older; mutually exclusive), --expected-branch, and +--expected-commit together (full lowercase 40- or 64-digit hex SHA). A +null commit cannot be used. --expected-from passes through the +identifier the instance returned: environmentId (2.46) or configId (older). Expected source is optional; supply it to detect changes after review. Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 other error. Only applied writes content. Resolve blocked bindings before apply-continue; @@ -43,18 +51,19 @@ n8n promotion project apply [flags] ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --expected-branch string reviewed branch name (default: omitted; requires expected config ID and commit) - --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires expected config ID and branch) - --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) - --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) - -h, --help help for apply - --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) - --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) - --output string output format: text or json (default: text; JSON is the full server result) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --workflow-id stringArray selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used) - --yes confirm content changes without prompting (default: prompt; required for non-interactive or stdin input) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --expected-branch string reviewed branch name (default: omitted; requires the expected ID and commit) + --expected-commit string reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch) + --expected-config-id string reviewed config ID on n8n 2.45 and earlier, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-environment-id) + --expected-environment-id string reviewed environment ID on n8n 2.46 and later, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-config-id) + --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) + -h, --help help for apply + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) + --output string output format: text or json (default: text; JSON is the full server result) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --workflow-id stringArray selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used) + --yes confirm content changes without prompting (default: prompt; required for non-interactive or stdin input) ``` ### SEE ALSO diff --git a/docs/n8n_promotion_project_changes.md b/docs/n8n_promotion_project_changes.md index 03c2e46..9f68569 100644 --- a/docs/n8n_promotion_project_changes.md +++ b/docs/n8n_promotion_project_changes.md @@ -5,13 +5,17 @@ List workflow changes for a project's promotion branch ### Synopsis Compare a team project with its resolved promotion branch without changing content. -Start with 'n8n project list' for the project ID. The project's own connection -takes precedence over the instance connection; clone the chosen direction -first with 'n8n promotion checkout clone'. Apply requires gitConnection:pull; -promote requires gitConnection:push. Text lists workflow IDs, statuses, and -dependency counts; JSON includes changes, source, and nullable commitSha. -Review the IDs before project apply or promote. Save apply JSON for ---expected-from to reject a branch that moves after review. +Start with 'n8n project list' for the project ID. The project's own +environment (n8n 2.46 and later) or connection (older) for the direction +takes precedence over the instance one. Prepare the checkout first: 'n8n +promotion environment connect' on 2.46, 'n8n promotion checkout clone' +before. Apply requires gitConnection:pull; promote requires +gitConnection:push. Text lists workflow IDs, statuses, and dependency +counts; JSON includes changes, source (environmentId on 2.46, configId +before), and nullable commitSha. On 2.46 a deleted or new promote row can +be a workflow that moved between projects; promoting it is refused until +it moves back. Review the IDs before project apply or promote. Save apply +JSON for --expected-from to reject a branch that moves after review. ``` n8n promotion project changes [flags] diff --git a/docs/n8n_promotion_project_promote.md b/docs/n8n_promotion_project_promote.md index f81626d..795bf80 100644 --- a/docs/n8n_promotion_project_promote.md +++ b/docs/n8n_promotion_project_promote.md @@ -6,12 +6,17 @@ Promote selected project workflows to the remote branch Start with 'n8n promotion project changes PROJECT_ID promote' to review IDs. Push the current state of selected workflows to the project's resolved -promotion connection (its own, otherwise the instance connection). Clone -the promote direction first. Archived workflows remain archived on the -branch; workflows no longer owned by the project leave the branch. Unknown -deletions reject the whole request. Requires gitConnection:push, plus -variable:list when workflows use variables. Commit message is optional; -the server supplies a default. Force pushing is not supported. +promote environment (n8n 2.46 and later) or connection (older): its own, +otherwise the instance one. Prepare it first: 'n8n promotion environment +connect' on 2.46, 'n8n promotion checkout clone' before. Archived +workflows remain archived on the branch; workflows gone from the instance +leave the branch. On 2.46 a workflow that moved into or out of the +project since the branch was written is refused with 400; move it back +first. Unknown deletions reject the whole request. Requires +gitConnection:push, plus variable:list when workflows use variables. +Commit message is optional; the server supplies a default. Force pushing +is not supported. The result can name a review the Git host opened; +advisory warnings go to stderr. Pass repeated --workflow-id flags, or use a strict JSON request. Read request JSON with --input FILE|- (maximum 1 MiB). Input and document flags are diff --git a/docs/n8n_promotion_promote.md b/docs/n8n_promotion_promote.md index 2d71f67..1b7b090 100644 --- a/docs/n8n_promotion_promote.md +++ b/docs/n8n_promotion_promote.md @@ -6,11 +6,13 @@ Promote team projects to the Git remote Export every team project, commit it, and push to the configured base branch or a new timestamped branch (the result names it). Personal -projects are ignored. This runs on the instance connection only, so -project links from 'n8n promotion project add' do not select what is -promoted. The promote checkout must be cloned first: run 'n8n promotion -checkout clone CONNECTION_ID promote'. When workflows reference -variables, the API key also needs variable:list. +projects are ignored. Connections exist before n8n 2.46; on 2.46 use +'n8n promotion environment promote'. This runs on the instance +connection only, so project links from 'n8n promotion project add' do +not select what is promoted. The promote checkout must be cloned +first: run 'n8n promotion checkout clone CONNECTION_ID promote'. +When workflows reference variables, the API key also needs +variable:list. Pass --commit-message once (1 to 1000 characters). Without --force a promote the remote would reject is refused with 409 and nothing is diff --git a/docs/n8n_promotion_provider.md b/docs/n8n_promotion_provider.md index fca7d72..ef07bd4 100644 --- a/docs/n8n_promotion_provider.md +++ b/docs/n8n_promotion_provider.md @@ -5,14 +5,15 @@ Manage promotion providers ### Synopsis Manage promotion providers: the stored Git credentials one or more -connections sync through. Start with 'list' to find the provider ID, -then 'get' to read it, 'create' to add one, or 'update' to rename it -or replace its credential. Use repositories then branches to discover -GitLab targets before creating a connection. - -Replacing a provider credential affects every connection attached to -it, so 'update' asks for confirmation. Deleting a provider removes it -while attached connections keep their content but lose their credential. +environments (n8n 2.46 and later) or connections (older) sync through. +Start with 'list' to find the provider ID, then 'get' to read it, +'create' to add one, or 'update' to rename it or replace its +credential. Use repositories then branches to discover GitLab remotes +before creating an environment or connection. + +Replacing a provider credential affects every environment or +connection that uses it, so 'update' asks for confirmation. A provider +still used by an environment or connection cannot be deleted. ``` n8n promotion provider [flags] diff --git a/docs/n8n_promotion_provider_branches.md b/docs/n8n_promotion_provider_branches.md index aba291b..8be69dc 100644 --- a/docs/n8n_promotion_provider_branches.md +++ b/docs/n8n_promotion_provider_branches.md @@ -7,8 +7,9 @@ List branches of a GitLab repository Discover GitLab repositories or branches using a saved provider with gitConnection:discover. Start with 'n8n promotion provider list', then repositories, then branches. Pass the raw fullPath (for example org/repo) or GitLab project ID to branches; -the CLI escapes it. Use remoteUrl from repositories as a connection target. -No saved connection is required and no content changes. Other provider types +the CLI escapes it. Use remoteUrl from repositories as an environment remote +(n8n 2.46 and later) or a connection target (older). No saved environment +or connection is required and no content changes. Other provider types do not support discovery. Text lists repository targets or branch names and defaults; JSON returns data and nextCursor. Follow nextCursor even after a short page. --all follows cursors up to 10,000 items. diff --git a/docs/n8n_promotion_provider_delete.md b/docs/n8n_promotion_provider_delete.md index 7aeee54..6b120ed 100644 --- a/docs/n8n_promotion_provider_delete.md +++ b/docs/n8n_promotion_provider_delete.md @@ -4,10 +4,10 @@ Permanently delete a promotion provider ### Synopsis -Permanently delete one promotion provider. Attached connections keep -their stored content but lose their credential, so promote, apply, and -checkout commands stop working until a provider is attached again. -This cannot be undone. +Permanently delete one promotion provider and its stored credential. +A provider still used by an environment (n8n 2.46 and later) or a +connection (older) cannot be deleted: the instance answers 409 and +nothing changes, so delete or move those first. This cannot be undone. Interactive runs ask for confirmation; non-interactive runs require --yes. Requires gitConnection:delete. diff --git a/docs/n8n_promotion_provider_repositories.md b/docs/n8n_promotion_provider_repositories.md index 240aaa9..de611ec 100644 --- a/docs/n8n_promotion_provider_repositories.md +++ b/docs/n8n_promotion_provider_repositories.md @@ -7,8 +7,9 @@ List repositories available to a GitLab provider Discover GitLab repositories or branches using a saved provider with gitConnection:discover. Start with 'n8n promotion provider list', then repositories, then branches. Pass the raw fullPath (for example org/repo) or GitLab project ID to branches; -the CLI escapes it. Use remoteUrl from repositories as a connection target. -No saved connection is required and no content changes. Other provider types +the CLI escapes it. Use remoteUrl from repositories as an environment remote +(n8n 2.46 and later) or a connection target (older). No saved environment +or connection is required and no content changes. Other provider types do not support discovery. Text lists repository targets or branch names and defaults; JSON returns data and nextCursor. Follow nextCursor even after a short page. --all follows cursors up to 10,000 items. diff --git a/docs/n8n_promotion_provider_update.md b/docs/n8n_promotion_provider_update.md index bd7c7bd..66ed2b7 100644 --- a/docs/n8n_promotion_provider_update.md +++ b/docs/n8n_promotion_provider_update.md @@ -12,11 +12,12 @@ providers). The auth type cannot change. A gitlab provider can change its base URL with config {"schemaVersion":1,"baseUrl":"..."}; a different API destination needs auth in the same document. -Replacing the credential affects every connection attached to this -provider, so interactive runs ask for confirmation and non-interactive -runs require --yes. Credentials travel only as --input because secrets -are never flags. A 409 means another request changed the provider -first: reload it and retry. Requires gitConnection:update. +Replacing the credential affects every environment (n8n 2.46 and +later) or connection (older) that uses this provider, so interactive +runs ask for confirmation and non-interactive runs require --yes. +Credentials travel only as --input because secrets are never flags. A +409 means another request changed the provider first: reload it and +retry. Requires gitConnection:update. ``` n8n promotion provider update [flags] @@ -38,7 +39,7 @@ n8n promotion provider update [flags] --input string promotion provider JSON file path, or - for stdin (required; maximum 1 MiB) --output string output format: text or json (JSON is the provider 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 credential replacement for every attached connection without prompting (required when stdin is not interactive) + --yes confirm credential replacement for every environment or connection using the provider without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 8da9247..eb30b83 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -288,6 +288,9 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"promotion", "environment", "project", "list"}, {"promotion", "environment", "project", "add"}, {"promotion", "environment", "project", "remove"}, + {"promotion", "environment", "apply"}, + {"promotion", "environment", "apply-continue"}, + {"promotion", "environment", "promote"}, {"promotion", "connection"}, {"promotion", "connection", "list"}, {"promotion", "connection", "create"}, diff --git a/internal/cli/idempotency_test.go b/internal/cli/idempotency_test.go index 08446ed..abf7cc7 100644 --- a/internal/cli/idempotency_test.go +++ b/internal/cli/idempotency_test.go @@ -43,6 +43,9 @@ func idempotentCommands() []idempotentCommand { {"project apply", fixed("promotion", "project", "apply", "proj-1", "--workflow-id", "wf", "--yes"), "/promotions/projects/proj-1/apply", applied}, {"project apply-continue", fixed(append([]string{"promotion", "project", "apply-continue", "proj-1", "--workflow-id", "wf", "--yes"}, expected...)...), "/promotions/projects/proj-1/apply/continue", applied}, {"project promote", fixed("promotion", "project", "promote", "proj-1", "--workflow-id", "wf", "--yes"), "/promotions/projects/proj-1/promote", cliPromotionPromoteBody}, + {"environment promote", fixed("promotion", "environment", "promote", cliEnvironmentID, "--yes"), n8n.PromotionEnvironmentsPath + "/" + cliEnvironmentID + "/promote", cliEnvPromoteBody}, + {"environment apply", fixed("promotion", "environment", "apply", cliEnvironmentID, "--yes"), n8n.PromotionEnvironmentsPath + "/" + cliEnvironmentID + "/apply", applied}, + {"environment apply-continue", fixed(append([]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--yes"}, envExpectedFlags()...)...), n8n.PromotionEnvironmentsPath + "/" + cliEnvironmentID + "/apply/continue", applied}, {"package import", func(t *testing.T) []string { return []string{"package", "import", "--file", writePackageArchive(t, cliPackageArchive), "--workflow-conflict-policy", "fail", "--yes"} }, n8n.N8nPackageImportPath, cliPackageImportResult}, diff --git a/internal/cli/promotion.go b/internal/cli/promotion.go index 6417f15..5345337 100644 --- a/internal/cli/promotion.go +++ b/internal/cli/promotion.go @@ -35,21 +35,24 @@ func newPromotionCommand(opts Options) *cobra.Command { "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" + + "'environment project'. Sync the whole instance with 'environment\n" + + "promote' and 'environment apply' (then 'environment apply-continue'\n" + + "after resolving a blocked apply) on the instance-scope environment.\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 content and ask for confirmation.\n" + + "remote into the instance, and 'apply-continue' after resolving a\n" + + "blocked apply. These run on the instance connection.\n\n" + + "On both generations, start selected-workflow sync with 'project\n" + + "changes', then 'project apply' or 'project promote'; the project's own\n" + + "environment or connection resolves before the instance one.\n\n" + + "Promote commits and pushes every team project to the remote; apply\n" + + "checks the package and imports with overwrite behavior, creating,\n" + + "updating, or removing content to match, or reports why it is blocked\n" + + "and writes nothing. Both mutate versioned content and ask for\n" + + "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" + @@ -57,6 +60,8 @@ func newPromotionCommand(opts Options) *cobra.Command { Example: " n8n promotion provider list\n" + " n8n promotion environment list\n" + " n8n promotion environment connect ENVIRONMENT_ID\n" + + " n8n promotion environment apply ENVIRONMENT_ID --yes\n" + + " n8n promotion environment promote ENVIRONMENT_ID --commit-message \"sync\" --yes\n" + " n8n promotion connection list\n" + " n8n promotion provider create --input provider.json\n" + " n8n promotion connection create --input connection.json\n" + @@ -77,7 +82,7 @@ func newPromotionCommand(opts Options) *cobra.Command { newPromotionProjectCommand(opts), newPromotionPromoteCommand(opts), newPromotionApplyCommand(opts), - newPromotionSelectionCommand(opts, "apply-continue", false), + newPromotionSelectionCommand(opts, "apply-continue", promotionTargetConnection), ) return cmd } @@ -89,13 +94,14 @@ func newPromotionProviderCommand(opts Options) *cobra.Command { Use: "provider", Short: "Manage promotion providers", Long: "Manage promotion providers: the stored Git credentials one or more\n" + - "connections sync through. Start with 'list' to find the provider ID,\n" + - "then 'get' to read it, 'create' to add one, or 'update' to rename it\n" + - "or replace its credential. Use repositories then branches to discover\n" + - "GitLab targets before creating a connection.\n\n" + - "Replacing a provider credential affects every connection attached to\n" + - "it, so 'update' asks for confirmation. Deleting a provider removes it\n" + - "while attached connections keep their content but lose their credential.", + "environments (n8n 2.46 and later) or connections (older) sync through.\n" + + "Start with 'list' to find the provider ID, then 'get' to read it,\n" + + "'create' to add one, or 'update' to rename it or replace its\n" + + "credential. Use repositories then branches to discover GitLab remotes\n" + + "before creating an environment or connection.\n\n" + + "Replacing a provider credential affects every environment or\n" + + "connection that uses it, so 'update' asks for confirmation. A provider\n" + + "still used by an environment or connection cannot be deleted.", Example: " n8n promotion provider list\n" + " n8n promotion provider get PROVIDER_ID\n" + " n8n promotion provider create --input provider.json\n" + @@ -420,11 +426,12 @@ func newPromotionProviderUpdateCommand(opts Options) *cobra.Command { "providers). The auth type cannot change. A gitlab provider can change\n" + "its base URL with config {\"schemaVersion\":1,\"baseUrl\":\"...\"}; a\n" + "different API destination needs auth in the same document.\n\n" + - "Replacing the credential affects every connection attached to this\n" + - "provider, so interactive runs ask for confirmation and non-interactive\n" + - "runs require --yes. Credentials travel only as --input because secrets\n" + - "are never flags. A 409 means another request changed the provider\n" + - "first: reload it and retry. Requires gitConnection:update.", + "Replacing the credential affects every environment (n8n 2.46 and\n" + + "later) or connection (older) that uses this provider, so interactive\n" + + "runs ask for confirmation and non-interactive runs require --yes.\n" + + "Credentials travel only as --input because secrets are never flags. A\n" + + "409 means another request changed the provider first: reload it and\n" + + "retry. Requires gitConnection:update.", Example: " n8n promotion provider update PROVIDER_ID --input provider-update.json\n" + " printf '%s\\n' '{\"name\":\"github-new\"}' | n8n promotion provider update PROVIDER_ID --input -\n" + " n8n promotion provider update PROVIDER_ID --input provider-update.json --yes --output json", @@ -435,7 +442,7 @@ func newPromotionProviderUpdateCommand(opts Options) *cobra.Command { } f.instance.register(cmd) cmd.Flags().StringVar(&f.input, "input", "", "promotion provider JSON file path, or - for stdin (required; maximum 1 MiB)") - cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm credential replacement for every attached connection without prompting (required when stdin is not interactive)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm credential replacement for every environment or connection using the provider without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the provider returned by the API)") return cmd } @@ -464,7 +471,7 @@ func runPromotionProviderUpdate(ctx context.Context, opts Options, id string, f if err != nil { return err } - question := fmt.Sprintf("Update promotion provider %q on %s? A replaced credential affects every connection attached to it.", id, resolution.URL) + question := fmt.Sprintf("Update promotion provider %q on %s? A replaced credential affects every environment or connection that uses it.", id, resolution.URL) if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } @@ -486,10 +493,10 @@ func newPromotionProviderDeleteCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "delete ", Short: "Permanently delete a promotion provider", - Long: "Permanently delete one promotion provider. Attached connections keep\n" + - "their stored content but lose their credential, so promote, apply, and\n" + - "checkout commands stop working until a provider is attached again.\n" + - "This cannot be undone.\n\n" + + Long: "Permanently delete one promotion provider and its stored credential.\n" + + "A provider still used by an environment (n8n 2.46 and later) or a\n" + + "connection (older) cannot be deleted: the instance answers 409 and\n" + + "nothing changes, so delete or move those first. This cannot be undone.\n\n" + "Interactive runs ask for confirmation; non-interactive runs require\n" + "--yes. Requires gitConnection:delete.", Example: " n8n promotion provider delete PROVIDER_ID\n" + @@ -519,7 +526,7 @@ func runPromotionProviderDelete(ctx context.Context, opts Options, id string, f if err != nil { return err } - question := fmt.Sprintf("Permanently delete promotion provider %q from %s? Attached connections keep their content but lose their credential.", id, resolution.URL) + question := fmt.Sprintf("Permanently delete promotion provider %q from %s? Its stored credential is removed; this cannot be undone.", id, resolution.URL) if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } @@ -1299,10 +1306,12 @@ func newPromotionProjectCommand(opts Options) *cobra.Command { "project elsewhere answers 409. Removing unlinks the project; its\n" + "instance content is untouched. Project IDs come from 'n8n project\n" + "list'. Adding and listing need gitConnection:read for reads and\n" + - "gitConnection:manageProjects for writes. For selected workflow sync,\n" + - "start with changes PROJECT_ID apply|promote, then apply or promote.\n" + - "Selection commands take a project ID first and resolve its own connection\n" + - "before falling back to the instance connection.", + "gitConnection:manageProjects for writes; on n8n 2.46 and later link\n" + + "projects with 'n8n promotion environment project' instead. For selected\n" + + "workflow sync on either generation, start with changes PROJECT_ID\n" + + "apply|promote, then apply or promote. Selection commands take a project\n" + + "ID first and resolve its own environment (2.46) or connection (older)\n" + + "before falling back to the instance one.", Example: " n8n promotion project list CONNECTION_ID\n" + " n8n promotion project add CONNECTION_ID PROJECT_ID\n" + " n8n promotion project remove CONNECTION_ID PROJECT_ID --yes", @@ -1314,9 +1323,9 @@ func newPromotionProjectCommand(opts Options) *cobra.Command { newPromotionProjectAddCommand(opts), newPromotionProjectRemoveCommand(opts), newPromotionProjectChangesCommand(opts), - newPromotionSelectionCommand(opts, "apply", true), - newPromotionSelectionCommand(opts, "apply-continue", true), - newPromotionSelectionCommand(opts, "promote", true), + newPromotionSelectionCommand(opts, "apply", promotionTargetProject), + newPromotionSelectionCommand(opts, "apply-continue", promotionTargetProject), + newPromotionSelectionCommand(opts, "promote", promotionTargetProject), ) return cmd } @@ -1516,11 +1525,13 @@ func newPromotionPromoteCommand(opts Options) *cobra.Command { Short: "Promote team projects to the Git remote", Long: "Export every team project, commit it, and push to the configured base\n" + "branch or a new timestamped branch (the result names it). Personal\n" + - "projects are ignored. This runs on the instance connection only, so\n" + - "project links from 'n8n promotion project add' do not select what is\n" + - "promoted. The promote checkout must be cloned first: run 'n8n promotion\n" + - "checkout clone CONNECTION_ID promote'. When workflows reference\n" + - "variables, the API key also needs variable:list.\n\n" + + "projects are ignored. Connections exist before n8n 2.46; on 2.46 use\n" + + "'n8n promotion environment promote'. This runs on the instance\n" + + "connection only, so project links from 'n8n promotion project add' do\n" + + "not select what is promoted. The promote checkout must be cloned\n" + + "first: run 'n8n promotion checkout clone CONNECTION_ID promote'.\n" + + "When workflows reference variables, the API key also needs\n" + + "variable:list.\n\n" + "Pass --commit-message once (1 to 1000 characters). Without --force a\n" + "promote the remote would reject is refused with 409 and nothing is\n" + "pushed; --force pushes anyway and rewrites remote history. This\n" + @@ -1579,10 +1590,7 @@ func runPromotionPromote(ctx context.Context, opts Options, id string, f promoti } return promotionAPIError(err, resolution, "promote", promotionConnectionSubject(id)) } - if f.output == outputJSON { - return writeJSON(opts.Streams.Out, result) - } - return writePromotionPromoteResult(opts, resolution, result) + return writePromotionPromoteOutput(opts, resolution, result, f.output) } type promotionApplyFlags struct { @@ -1599,7 +1607,8 @@ func newPromotionApplyCommand(opts Options) *cobra.Command { Short: "Apply the Git remote into this instance", Long: "Check the full package at the apply branch tip and import it into the\n" + "instance, overwriting to match. Runs on the instance connection; the\n" + - "apply checkout must be cloned first.\n\n" + + "apply checkout must be cloned first. Connections exist before n8n\n" + + "2.46; on 2.46 use 'n8n promotion environment apply'.\n\n" + "The server answers one of three statuses, and only one writes:\n" + " applied content was imported; counts and warnings follow.\n" + " blocked preflight stopped before any write: missing projects,\n" + @@ -1677,22 +1686,21 @@ func runPromotionApply(ctx context.Context, opts Options, id string, f promotion // the status to its own exit code so scripts can tell these apart from // transport and validation errors. type promotionApplyStoppedError struct { - connectionID, status string - project bool + id, status string + // target is promotionTargetConnection, promotionTargetProject, or + // promotionTargetEnvironment. + target string } func (e *promotionApplyStoppedError) Error() string { - target := "connection" - if e.project { - target = "project" - } + target := cmp.Or(e.target, promotionTargetConnection) switch e.status { case n8n.PromotionApplyStatusBlocked: - return fmt.Sprintf("promotion apply of %s %s was blocked at preflight; nothing was applied", target, e.connectionID) + return fmt.Sprintf("promotion apply of %s %s was blocked at preflight; nothing was applied", target, e.id) case n8n.PromotionApplyStatusSourceChanged: - return fmt.Sprintf("promotion apply of %s %s stopped because the source branch moved; nothing was applied", target, e.connectionID) + return fmt.Sprintf("promotion apply of %s %s stopped because the source branch moved; nothing was applied", target, e.id) default: - return fmt.Sprintf("promotion apply of %s %s answered unknown status %q; check the instance before assuming anything was applied", target, e.connectionID, e.status) + return fmt.Sprintf("promotion apply of %s %s answered unknown status %q; check the instance before assuming anything was applied", target, e.id, e.status) } } @@ -1710,14 +1718,15 @@ func (e *promotionApplyStoppedError) exitCode() int { // finishPromotionApply writes the next-step hint for a result that wrote // nothing and returns the matching error; an applied result returns nil. func finishPromotionApply(opts Options, id string, result *n8n.ApplyPromotionResult) error { - return finishPromotionApplyTarget(opts, id, result, false) + return finishPromotionApplyTarget(opts, id, result, promotionTargetConnection) } -func finishPromotionApplyTarget(opts Options, id string, result *n8n.ApplyPromotionResult, project bool) error { +func finishPromotionApplyTarget(opts Options, id string, result *n8n.ApplyPromotionResult, target string) error { prefix := "n8n promotion " - if project { - prefix += "project " + if target != promotionTargetConnection { + prefix += target + " " } + project := target == promotionTargetProject if result.Applied() { return nil } @@ -1728,8 +1737,12 @@ func finishPromotionApplyTarget(opts Options, id string, result *n8n.ApplyPromot if promotionNeedsConfirmation(result.Preflight) { fmt.Fprintln(opts.Streams.Err, "project-deletion and destructive-change conflicts are applied only with explicit confirmation when the apply is continued.") } - fmt.Fprintf(opts.Streams.Err, "Then run '%sapply-continue %s --expected-from blocked.json' using the saved --output json result (configId=%s branchName=%s commitSha=%s).\n", - prefix, id, emptyDash(source.ConfigID), emptyDash(source.BranchName), emptyDash(source.CommitSHA)) + idField, idValue := "configId", source.ConfigID + if source.EnvironmentID != "" { + idField, idValue = "environmentId", source.EnvironmentID + } + fmt.Fprintf(opts.Streams.Err, "Then run '%sapply-continue %s --expected-from blocked.json' using the saved --output json result (%s=%s branchName=%s commitSha=%s).\n", + prefix, id, idField, emptyDash(idValue), emptyDash(source.BranchName), emptyDash(source.CommitSHA)) if project { fmt.Fprintln(opts.Streams.Err, "Resend the same full selection with repeated --workflow-id flags or --input.") } @@ -1738,7 +1751,7 @@ func finishPromotionApplyTarget(opts Options, id string, result *n8n.ApplyPromot default: fmt.Fprintln(opts.Streams.Err, "This CLI does not know the apply status; read the full result with --output json.") } - return &promotionApplyStoppedError{connectionID: id, status: result.Status, project: project} + return &promotionApplyStoppedError{id: id, status: result.Status, target: target} } func promotionNeedsConfirmation(preflight *n8n.PromotionApplyPreflight) bool { @@ -1912,11 +1925,40 @@ func writePromotionCheckout(opts Options, resolution config.Resolution, action s return tw.Flush() } +// writePromotionPromoteOutput prints a promote result: the verbatim JSON or +// the text summary on stdout, then any advisory warnings on stderr in either +// format. A warning never means the push failed. +func writePromotionPromoteOutput(opts Options, resolution config.Resolution, result *n8n.PromotePromotionResult, output string) error { + var err error + if output == outputJSON { + err = writeJSON(opts.Streams.Out, result) + } else { + err = writePromotionPromoteResult(opts, resolution, result) + } + if err != nil { + return err + } + for _, warning := range result.Warnings { + if warning.LinkURL != "" { + fmt.Fprintf(opts.Streams.Err, "Warning: %s (see %s)\n", warning.Message, warning.LinkURL) + } else { + fmt.Fprintf(opts.Streams.Err, "Warning: %s\n", warning.Message) + } + } + return nil +} + func writePromotionPromoteResult(opts Options, resolution config.Resolution, result *n8n.PromotePromotionResult) error { tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) - fmt.Fprintf(tw, "Promoted:\t%s\n", result.ConnectionID) + fmt.Fprintf(tw, "Promoted:\t%s\n", emptyDash(result.SourceID())) + if result.EnvironmentID != "" { + fmt.Fprintf(tw, "Environment:\t%s\n", result.EnvironmentID) + } fmt.Fprintf(tw, "Commit:\t%s\n", emptyDash(result.Git.CommitSHA)) fmt.Fprintf(tw, "Branch:\t%s\n", emptyDash(result.Git.BranchName)) + if review := result.Review; review != nil { + fmt.Fprintf(tw, "Review:\t#%d %s\n", review.Number, emptyDash(review.WebURL)) + } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) fmt.Fprintln(tw, "\nENTITY\tCOUNT") fmt.Fprintf(tw, "workflows\t%d\n", result.Counts.Workflows) @@ -1946,9 +1988,14 @@ func writePromotionApplyHeader(tw *tabwriter.Writer, resolution config.Resolutio if result.Applied() { label = "Applied" } - fmt.Fprintf(tw, "%s:\t%s\n", label, result.ConnectionID) + fmt.Fprintf(tw, "%s:\t%s\n", label, result.SourceID()) fmt.Fprintf(tw, "Status:\t%s\n", emptyDash(result.Status)) - fmt.Fprintf(tw, "Config:\t%s\n", emptyDash(result.ConfigID)) + // n8n 2.46 and later name an environment; older instances a config. + if result.EnvironmentID != "" { + fmt.Fprintf(tw, "Environment:\t%s\n", result.EnvironmentID) + } else { + fmt.Fprintf(tw, "Config:\t%s\n", emptyDash(result.ConfigID)) + } fmt.Fprintf(tw, "Commit:\t%s\n", emptyDash(result.Git.CommitSHA)) fmt.Fprintf(tw, "Branch:\t%s\n", emptyDash(result.Git.BranchName)) fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) @@ -1967,10 +2014,14 @@ func writePromotionAppliedResult(opts Options, resolution config.Resolution, res fmt.Fprintf(tw, "projects\tskipped\t%d\n", counts.Projects.Skipped) fmt.Fprintf(tw, "projects\tdeleted\t%d\n", counts.Projects.Deleted) fmt.Fprintf(tw, "folders\tcreated\t%d\n", counts.Folders.Created) + writePromotionOptionalCount(tw, "folders", "updated", counts.Folders.Updated) + writePromotionOptionalCount(tw, "folders", "moved", counts.Folders.Moved) + writePromotionOptionalCount(tw, "folders", "renamed", counts.Folders.Renamed) fmt.Fprintf(tw, "folders\tskipped\t%d\n", counts.Folders.Skipped) fmt.Fprintf(tw, "folders\tremoved\t%d\n", counts.Folders.Removed) fmt.Fprintf(tw, "workflows\tcreated\t%d\n", counts.Workflows.Created) fmt.Fprintf(tw, "workflows\tupdated\t%d\n", counts.Workflows.Updated) + writePromotionOptionalCount(tw, "workflows", "moved", counts.Workflows.Moved) fmt.Fprintf(tw, "workflows\tskipped\t%d\n", counts.Workflows.Skipped) fmt.Fprintf(tw, "workflows\tarchived\t%d\n", counts.Workflows.Archived) fmt.Fprintf(tw, "workflows\tdeleted\t%d\n", counts.Workflows.Deleted) @@ -1981,6 +2032,7 @@ func writePromotionAppliedResult(opts Options, resolution config.Resolution, res fmt.Fprintf(tw, "workflows\tfailed\t%d\n", counts.Workflows.Publishing.Failed) fmt.Fprintf(tw, "credentials\tmatched\t%d\n", counts.Credentials.Matched) fmt.Fprintf(tw, "credentials\tstubbed\t%d\n", counts.Credentials.Stubbed) + writePromotionOptionalCount(tw, "credentials", "updated", counts.Credentials.Updated) fmt.Fprintf(tw, "dataTables\tmatched\t%d\n", counts.DataTables.Matched) fmt.Fprintf(tw, "dataTables\tcreated\t%d\n", counts.DataTables.Created) fmt.Fprintf(tw, "dataTables\tupdated\t%d\n", counts.DataTables.Updated) @@ -2010,6 +2062,15 @@ func writePromotionAppliedResult(opts Options, resolution config.Resolution, res return nil } +// writePromotionOptionalCount writes a count row only n8n 2.46 and later +// report. An older instance omits the count, and a missing row is truer than a +// zero it never sent. +func writePromotionOptionalCount(tw *tabwriter.Writer, entity, detail string, count *int) { + if count != nil { + fmt.Fprintf(tw, "%s\t%s\t%d\n", entity, detail, *count) + } +} + func writePromotionBlockedResult(opts Options, resolution config.Resolution, result *n8n.ApplyPromotionResult) error { var preflight n8n.PromotionApplyPreflight if result.Preflight != nil { @@ -2172,7 +2233,7 @@ func promotionProjectLinkSubject(id, projectID string) promotionSubject { func promotionAPIError(err error, resolution config.Resolution, action string, subject promotionSubject) error { switch { case n8n.IsConflict(err) && action == "provider delete": - 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) + return fmt.Errorf("%s rejected the promotion provider delete (409): the provider is still used by an environment (n8n 2.46 and later) or a connection (older), so nothing changed; delete them or move them to another provider with 'n8n promotion environment update' (or 'n8n promotion connection update'), 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": @@ -2181,9 +2242,15 @@ func promotionAPIError(err error, resolution config.Resolution, action string, s 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) && promotionMovesContent(action): + return fmt.Errorf("%s rejected the promotion %s (409), so nothing was applied: on n8n 2.46 and later a workflow or folder that the branch and the instance hold in different projects is refused before any write; move it back into the same project on one side, then retry. Otherwise the environment, connection, or project is in a conflicting state; check it and retry: %w", resolution.URL, action, err) + case n8n.IsConflict(err) && action == "environment promote": + return fmt.Errorf("%s rejected the promotion environment promote (409): the remote would reject the push, so nothing was pushed; review the remote branch, or re-run with --force to push anyway and rewrite remote history: %w", resolution.URL, err) + case n8n.IsStatus(err, http.StatusBadRequest) && (action == "environment promote" || action == "project promote"): + return fmt.Errorf("%s rejected the promotion %s (400), so nothing was pushed: check the workflow IDs and the commit message; on n8n 2.46 and later a workflow or folder on the branch that moved to another project or to a personal project is also refused, so move it back first: %w", resolution.URL, action, 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 "): + case n8n.IsStatus(err, http.StatusUnprocessableEntity) && strings.HasPrefix(action, "environment ") && !promotionMovesContent(action): 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) @@ -2227,6 +2294,17 @@ func promotionRouteMissing(err error) bool { return message == "" || message == "not found" || strings.HasPrefix(message, "cannot ") } +// promotionMovesContent reports apply actions that, from n8n 2.46, move +// workflows and folders to match the branch and refuse cross-project moves +// with 409. The connection apply predates that and keeps its own messages. +func promotionMovesContent(action string) bool { + switch action { + case "environment apply", "environment apply-continue", "project apply", "project apply-continue": + return true + } + return false +} + func promotionScope(action string) string { switch action { case "provider list", "connection list", "environment list": @@ -2243,9 +2321,9 @@ func promotionScope(action string) string { return "gitConnection:clone" case "project add", "project remove", "environment project add", "environment project remove": return "gitConnection:manageProjects" - case "promote", "project promote", "project changes promote": + case "promote", "project promote", "project changes promote", "environment promote": return "gitConnection:push" - case "apply", "apply-continue", "project apply", "project apply-continue", "project changes apply": + case "apply", "apply-continue", "project apply", "project apply-continue", "project changes apply", "environment apply", "environment apply-continue": return "gitConnection:pull" case "provider repositories", "provider branches": return "gitConnection:discover" diff --git a/internal/cli/promotion_apply_test.go b/internal/cli/promotion_apply_test.go index 9f7dea4..36e0c16 100644 --- a/internal/cli/promotion_apply_test.go +++ b/internal/cli/promotion_apply_test.go @@ -342,7 +342,7 @@ func TestPromotionApplyStoppedErrorExitCodes(t *testing.T) { n8n.PromotionApplyStatusSourceChanged: ExitPromotionSourceChanged, "queued": ExitError, } { - if got := (&promotionApplyStoppedError{connectionID: "c", status: status}).exitCode(); got != want { + if got := (&promotionApplyStoppedError{id: "c", status: status}).exitCode(); got != want { t.Errorf("exit code for %q = %d, want %d", status, got, want) } } diff --git a/internal/cli/promotion_environment.go b/internal/cli/promotion_environment.go index c69b651..2d4809d 100644 --- a/internal/cli/promotion_environment.go +++ b/internal/cli/promotion_environment.go @@ -45,12 +45,20 @@ func newPromotionEnvironmentCommand(opts Options) *cobra.Command { "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" + + "Sync the whole instance through the connected instance-scope\n" + + "environment: 'promote' pushes every team project to a promote\n" + + "environment; 'apply' imports an apply environment's branch, and\n" + + "'apply-continue' finishes an apply that preflight blocked. For selected\n" + + "workflows of one project use 'n8n promotion project changes', 'apply',\n" + + "and 'promote'.\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 apply ENVIRONMENT_ID --yes\n" + + " n8n promotion environment promote ENVIRONMENT_ID --commit-message \"sync\" --yes\n" + " n8n promotion environment project add ENVIRONMENT_ID PROJECT_ID", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, @@ -64,6 +72,9 @@ func newPromotionEnvironmentCommand(opts Options) *cobra.Command { newPromotionEnvironmentConnectCommand(opts), newPromotionEnvironmentDisconnectCommand(opts), newPromotionEnvironmentProjectCommand(opts), + newPromotionEnvironmentPromoteCommand(opts), + newPromotionSelectionCommand(opts, "apply", promotionTargetEnvironment), + newPromotionSelectionCommand(opts, "apply-continue", promotionTargetEnvironment), ) return cmd } @@ -541,6 +552,101 @@ func runPromotionEnvironmentDisconnect(ctx context.Context, opts Options, id str return writePromotionEnvironmentCheckout(opts, resolution, "Disconnected", checkout, f.output) } +// Environment promote. Apply and apply-continue share the selection command, +// which already carries the expected-source and --input handling they need. + +type promotionEnvironmentPromoteFlags struct { + instance instanceFlags + commit string + force bool + yes bool + output string + idempotency idempotencyFlag +} + +func newPromotionEnvironmentPromoteCommand(opts Options) *cobra.Command { + var f promotionEnvironmentPromoteFlags + cmd := &cobra.Command{ + Use: "promote ", + Short: "Promote team projects to an environment's Git remote", + Long: "Export every team project, commit it, and push through an\n" + + "instance-scope promote environment (n8n 2.46 and later) to its base\n" + + "branch or a new timestamped branch (the result names it). Before 2.46\n" + + "use 'n8n promotion promote' with a connection. Start with 'n8n\n" + + "promotion environment list --direction promote' and connect it first\n" + + "with 'n8n promotion environment connect'. Personal projects are\n" + + "ignored, and project links do not select what is promoted; for one\n" + + "project's workflows use 'n8n promotion project promote'. A workflow on\n" + + "the branch that moved to a personal project, or to another team project\n" + + "while its old project still exists, is refused with 400.\n\n" + + "--commit-message is optional (1 to 1000 characters; default: a\n" + + "server-generated message). Without --force a promote the remote would\n" + + "reject is refused with 409 and nothing is pushed; --force pushes anyway\n" + + "and rewrites remote history. This mutates the remote branch.\n" + + "Interactive runs ask for confirmation and non-interactive runs require\n" + + "--yes. Requires gitConnection:push, plus variable:list when workflows\n" + + "reference variables.\n\n" + + "Text shows the commit, branch, counts, and any review the Git host\n" + + "opened; JSON is the full result. Advisory warnings go to stderr in both\n" + + "formats.\n\n" + + idempotencyHelp, + Example: " n8n promotion environment promote ENVIRONMENT_ID --commit-message \"sync workflows\"\n" + + " n8n promotion environment promote ENVIRONMENT_ID --yes\n" + + " n8n promotion environment promote ENVIRONMENT_ID --commit-message \"sync\" --force --yes --output json", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runPromotionEnvironmentPromote(cmd.Context(), opts, args[0], f, cmd.Flags().Changed("commit-message")) + }, + } + f.instance.register(cmd) + cmd.Flags().StringVar(&f.commit, "commit-message", "", "commit message for the promote, 1 to 1000 characters (default: server-generated message)") + cmd.Flags().BoolVar(&f.force, "force", false, "promote even when the remote would reject it, rewriting remote history (default: reject a rejected promote with 409)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm promoting every team project to the remote without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the promote result with counts, commit, and any review and warnings)") + f.idempotency.register(cmd) + return cmd +} + +func runPromotionEnvironmentPromote(ctx context.Context, opts Options, id string, f promotionEnvironmentPromoteFlags, hasCommit bool) error { + if err := validateOutput(f.output); err != nil { + return err + } + if err := validatePromotionEnvironmentArg(id); err != nil { + return err + } + request := n8n.PromotePromotionEnvironmentRequest{Force: f.force} + message := "a server-generated commit message" + if hasCommit { + request.CommitMessage = &f.commit + message = fmt.Sprintf("commit message %q", f.commit) + } + if err := request.Validate(); err != nil { + return err + } + if err := f.idempotency.validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + question := fmt.Sprintf("Promote every team project on %s to the remote of promotion environment %q with %s? Team projects are committed and pushed.", resolution.URL, id, message) + if request.Force { + question = fmt.Sprintf("Force-promote every team project on %s to the remote of promotion environment %q with %s? Remote history is rewritten.", resolution.URL, id, message) + } + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + result, err := client.PromotePromotionEnvironment(ctx, id, request, f.idempotency.resolve(opts.Streams.Err)...) + if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } + return promotionAPIError(err, resolution, "environment promote", promotionEnvironmentSubject(id)) + } + return writePromotionPromoteOutput(opts, resolution, result, f.output) +} + // Environment projects. func newPromotionEnvironmentProjectCommand(opts Options) *cobra.Command { diff --git a/internal/cli/promotion_environment_sync_test.go b/internal/cli/promotion_environment_sync_test.go new file mode 100644 index 0000000..3ffd51d --- /dev/null +++ b/internal/cli/promotion_environment_sync_test.go @@ -0,0 +1,418 @@ +package cli + +import ( + "net/http" + "strings" + "testing" +) + +// n8n 2.46 shapes: environmentId replaces connectionId and configId, folders +// gain updated/moved/renamed, workflows gain moved, credentials gain updated, +// and promote can add review and warnings. + +const cliEnvSource = `{"environmentId":"` + cliEnvironmentID + `","branchName":"main","commitSha":"` + cliSelectionSHA + `"}` + +const cliEnvAppliedBody = `{ + "environmentId":"` + cliEnvironmentID + `", + "git":{"commitSha":"` + cliSelectionSHA + `","branchName":"main"}, + "status":"applied", + "counts":{ + "projects":{"created":0,"updated":1,"skipped":0,"deleted":0}, + "folders":{"created":1,"updated":3,"skipped":0,"removed":0,"moved":2,"renamed":1}, + "workflows":{"created":0,"updated":4,"skipped":0,"archived":0,"deleted":0,"moved":2,"publishing":{"published":0,"unpublished":0,"unchanged":4,"blocked":0,"failed":0}}, + "credentials":{"matched":1,"stubbed":0,"updated":5}, + "dataTables":{"matched":0,"created":0,"updated":0}, + "variables":{"matched":0,"created":0,"updated":0,"stubbed":0,"missing":0}, + "tags":{"matched":0,"created":0,"renamed":0,"reconciled":0,"skipped":0} + }, + "warnings":[] +}` + +const cliEnvBlockedBody = `{ + "environmentId":"` + cliEnvironmentID + `", + "git":{"commitSha":"` + cliSelectionSHA + `","branchName":"main"}, + "status":"blocked", + "preflight":{"missingProjects":[{"id":"p-9","name":"Ops"}],"missingBindings":[],"accessRequirements":[],"conflicts":[],"warnings":[]} +}` + +const cliEnvSourceChangedBody = `{ + "environmentId":"` + cliEnvironmentID + `", + "git":{"commitSha":"` + cliSelectionSHA + `","branchName":"main"}, + "status":"source-changed" +}` + +const cliEnvPromoteBody = `{ + "environmentId":"` + cliEnvironmentID + `", + "counts":{"workflows":2,"folders":1,"credentials":0,"dataTables":0,"variables":0,"tags":3}, + "git":{"commitSha":"deadbeef","branchName":"n8n/promotion-1"}, + "review":{"reviewId":"mr-1","number":42,"webUrl":"https://gitlab.example.com/org/repo/-/merge_requests/42"}, + "warnings":[{"message":"Branch protection blocks merging","linkUrl":"https://gitlab.example.com/help"},{"message":"No reviewers"}] +}` + +var cliEnvChanges = strings.Replace(cliSelectionChanges, `"configId":"cfg"`, `"environmentId":"`+cliEnvironmentID+`"`, 1) + +func envExpectedFlags() []string { + return []string{"--expected-environment-id", cliEnvironmentID, "--expected-branch", "main", "--expected-commit", cliSelectionSHA} +} + +func TestPromotionEnvironmentSyncCommands(t *testing.T) { + for _, tc := range []struct { + name string + args []string + path, body, response string + }{ + {"apply", []string{"promotion", "environment", "apply", cliEnvironmentID}, "/apply", `{}`, cliEnvAppliedBody}, + {"apply with source", append([]string{"promotion", "environment", "apply", cliEnvironmentID}, envExpectedFlags()...), "/apply", `{"expectedSource":` + cliEnvSource + `}`, cliEnvAppliedBody}, + {"apply-continue", append([]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--confirm-destructive-changes"}, envExpectedFlags()...), "/apply/continue", `{"expectedSource":` + cliEnvSource + `,"confirmDestructiveChanges":true}`, cliEnvAppliedBody}, + {"promote", []string{"promotion", "environment", "promote", cliEnvironmentID}, "/promote", `{}`, cliEnvPromoteBody}, + {"promote with message and force", []string{"promotion", "environment", "promote", cliEnvironmentID, "--commit-message", "sync", "--force"}, "/promote", `{"commitMessage":"sync","force":true}`, cliEnvPromoteBody}, + } { + t.Run(tc.name, func(t *testing.T) { + f := promotionFixture(t, tc.response) + got := f.run(append(tc.args, "--yes", "--output", "json")...) + if got.code != ExitSuccess || !sameJSON(t, got.stdout, tc.response) { + t.Fatalf("json result = %+v", got) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.EscapedPath() != cliEnvironmentPath+tc.path || f.lastBody() != tc.body { + t.Errorf("request = %s %s body=%s", req.Method, req.URL.EscapedPath(), f.lastBody()) + } + got = f.run(append(tc.args, "--yes")...) + if got.code != ExitSuccess || !strings.Contains(got.stdout, cliEnvironmentID) || !strings.Contains(got.stdout, "Environment:") { + t.Errorf("text = %+v", got) + } + }) + } +} + +func TestPromotionEnvironmentApplyTextShowsNewCounts(t *testing.T) { + f := promotionFixture(t, cliEnvAppliedBody) + got := f.run("promotion", "environment", "apply", cliEnvironmentID, "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + for _, want := range []string{"Applied:", "Environment:", "folders updated 3", "folders moved 2", "folders renamed 1", "workflows moved 2", "credentials updated 5"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + if strings.Contains(got.stdout, "Config:") { + t.Errorf("stdout = %s, want no Config line for an environment result", got.stdout) + } + + // n8n 2.45 project apply: Config line, and no 2.46 count rows. + f.body = cliPromotionAppliedBody + got = f.run("promotion", "project", "apply", "p", "--workflow-id", "w", "--yes") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "Config:") || !strings.Contains(got.stdout, "cfg-apply") { + t.Fatalf("old shape = %+v", got) + } + for _, absent := range []string{"Environment:", "folders updated", "folders moved", "folders renamed", "workflows moved", "credentials updated"} { + if strings.Contains(got.stdout, absent) { + t.Errorf("old shape stdout invents %q:\n%s", absent, got.stdout) + } + } + + // n8n 2.46 project apply renders the new shape the same way. + f.body = cliEnvAppliedBody + got = f.run("promotion", "project", "apply", "p", "--workflow-id", "w", "--yes") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "Environment:") || !strings.Contains(got.stdout, "folders moved 2") { + t.Errorf("new project shape = %+v", got) + } +} + +func TestPromotionEnvironmentApplyStatuses(t *testing.T) { + for _, args := range [][]string{ + {"promotion", "environment", "apply", cliEnvironmentID}, + append([]string{"promotion", "environment", "apply-continue", cliEnvironmentID}, envExpectedFlags()...), + } { + for _, tc := range []struct { + body string + code int + hints []string + }{ + {cliEnvAppliedBody, ExitSuccess, nil}, + {cliEnvBlockedBody, ExitPromotionBlocked, []string{"n8n promotion environment apply-continue " + cliEnvironmentID, "environmentId=" + cliEnvironmentID, "environment " + cliEnvironmentID + " was blocked"}}, + {cliEnvSourceChangedBody, ExitPromotionSourceChanged, []string{"Review the branch again", "n8n promotion environment apply " + cliEnvironmentID}}, + {`{"status":"queued"}`, ExitError, []string{"does not know"}}, + } { + f := promotionFixture(t, tc.body) + got := f.run(append(args, "--yes", "--output", "json")...) + if got.code != tc.code || !sameJSON(t, got.stdout, tc.body) { + t.Errorf("%s: result = %+v, want exit %d", args[2], got, tc.code) + } + for _, hint := range tc.hints { + if !strings.Contains(got.stderr, hint) { + t.Errorf("%s: stderr missing %q:\n%s", args[2], hint, got.stderr) + } + } + if strings.Contains(got.stderr, "configId=") { + t.Errorf("%s: stderr = %s, want the environmentId hint only", args[2], got.stderr) + } + if got = f.run(append(args, "--yes")...); got.code != tc.code { + t.Errorf("%s text: exit = %d, want %d", args[2], got.code, tc.code) + } + } + } +} + +func TestPromotionEnvironmentSyncConfirmationBeforeTransport(t *testing.T) { + for _, tc := range []struct { + args []string + want string + }{ + {[]string{"promotion", "environment", "apply", cliEnvironmentID}, "this cannot be undone"}, + {append([]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--confirm-destructive-changes"}, envExpectedFlags()...), "ALL team-project deletions"}, + {[]string{"promotion", "environment", "promote", cliEnvironmentID}, "server-generated commit message"}, + {[]string{"promotion", "environment", "promote", cliEnvironmentID, "--commit-message", "sync", "--force"}, "Remote history is rewritten"}, + } { + t.Run(strings.Join(tc.args[:3], " "), func(t *testing.T) { + f := promotionFixture(t, cliEnvAppliedBody) + before := f.requestCount() + f.stdin = "no\n" + got := f.run(tc.args...) + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, tc.want) || !strings.Contains(got.stderr, "aborted") { + t.Errorf("declined = %+v, requests = %d want %d", got, f.requestCount(), before) + } + f.interactive = false + got = f.run(tc.args...) + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "--yes") { + t.Errorf("non-interactive = %+v, requests = %d want %d", got, f.requestCount(), before) + } + }) + } +} + +func TestPromotionEnvironmentSyncRejectsBeforeTransport(t *testing.T) { + f := promotionFixture(t, cliEnvAppliedBody) + configFile := writePromotionInput(t, f, "old-changes.json", cliSelectionChanges) + bothFile := writePromotionInput(t, f, "both.json", strings.Replace(cliEnvChanges, `"branchName":"main"`, `"configId":"cfg","branchName":"main"`, 1)) + before := f.requestCount() + for _, tc := range []struct { + args []string + want string + }{ + {[]string{"promotion", "environment", "apply", "conn-1", "--yes"}, "must be a UUID"}, + {[]string{"promotion", "environment", "promote", "conn-1", "--yes"}, "must be a UUID"}, + {[]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--yes"}, "--expected-environment-id"}, + {[]string{"promotion", "environment", "apply", cliEnvironmentID, "--expected-config-id", "cfg", "--yes"}, "unknown flag"}, + {[]string{"promotion", "environment", "apply", cliEnvironmentID, "--expected-environment-id", cliEnvironmentID, "--yes"}, "branch name is required"}, + {[]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--expected-from", configFile, "--yes"}, "only n8n 2.45 and earlier return"}, + {[]string{"promotion", "environment", "apply", cliEnvironmentID, "--expected-from", bothFile, "--yes"}, "both present"}, + {[]string{"promotion", "environment", "apply", cliEnvironmentID, "--input", "-"}, "--yes"}, + {[]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--expected-from", "-"}, "--yes"}, + {[]string{"promotion", "environment", "promote", cliEnvironmentID, "--commit-message", "", "--yes"}, "commit message is required"}, + {[]string{"promotion", "environment", "promote", cliEnvironmentID, "--commit-message", strings.Repeat("m", 1001), "--yes"}, "at most 1000"}, + {[]string{"promotion", "environment", "promote", cliEnvironmentID, "--output", "yaml", "--yes"}, "output"}, + } { + got := f.run(tc.args...) + if got.code == ExitSuccess || !strings.Contains(got.stderr, tc.want) || f.requestCount() != before { + t.Errorf("%v: result = %+v, want %q and no request", tc.args, got, tc.want) + } + } +} + +func TestPromotionEnvironmentApplyInputAndExpectedFrom(t *testing.T) { + f := promotionFixture(t, cliEnvAppliedBody) + f.stdin = `{"expectedSource":` + cliEnvSource + `,"confirmDestructiveChanges":false}` + got := f.run("promotion", "environment", "apply-continue", cliEnvironmentID, "--input", "-", "--yes") + if got.code != ExitSuccess || f.lastBody() != f.stdin { + t.Fatalf("stdin = %+v body=%s", got, f.lastBody()) + } + f.stdin = `{}` + got = f.run("promotion", "environment", "apply", cliEnvironmentID, "--input", "-", "--yes") + if got.code != ExitSuccess || f.lastBody() != `{}` { + t.Fatalf("empty input = %+v body=%s", got, f.lastBody()) + } + for _, review := range []string{cliEnvChanges, cliEnvBlockedBody} { + path := writePromotionInput(t, f, "review.json", review) + got = f.run("promotion", "environment", "apply-continue", cliEnvironmentID, "--expected-from", path, "--yes") + if got.code != ExitSuccess || f.lastBody() != `{"expectedSource":`+cliEnvSource+`}` { + t.Errorf("expected-from = %+v body=%s", got, f.lastBody()) + } + } +} + +// Project routes serve both generations: pass through whichever identifier the +// instance returned, and keep the two flags apart. +func TestPromotionProjectApplyBothExpectedSources(t *testing.T) { + f := promotionFixture(t, cliEnvAppliedBody) + got := f.run(append([]string{"promotion", "project", "apply", "p", "--workflow-id", "w", "--yes"}, envExpectedFlags()...)...) + if got.code != ExitSuccess || f.lastBody() != `{"workflowIds":["w"],"expectedSource":`+cliEnvSource+`}` { + t.Errorf("environment flag = %+v body=%s", got, f.lastBody()) + } + got = f.run(append([]string{"promotion", "project", "apply-continue", "p", "--workflow-id", "w", "--yes"}, selectionExpectedFlags()...)...) + if got.code != ExitSuccess || f.lastBody() != `{"workflowIds":["w"],"expectedSource":`+cliSelectionSource+`}` { + t.Errorf("config flag = %+v body=%s", got, f.lastBody()) + } + for _, review := range []string{cliEnvChanges, cliEnvBlockedBody} { + path := writePromotionInput(t, f, "review.json", review) + got = f.run("promotion", "project", "apply-continue", "p", "--workflow-id", "w", "--expected-from", path, "--yes") + if got.code != ExitSuccess || f.lastBody() != `{"workflowIds":["w"],"expectedSource":`+cliEnvSource+`}` { + t.Errorf("2.46 expected-from = %+v body=%s", got, f.lastBody()) + } + } + path := writePromotionInput(t, f, "old-review.json", cliSelectionChanges) + got = f.run("promotion", "project", "apply", "p", "--workflow-id", "w", "--expected-from", path, "--yes") + if got.code != ExitSuccess || f.lastBody() != `{"workflowIds":["w"],"expectedSource":`+cliSelectionSource+`}` { + t.Errorf("2.45 expected-from = %+v body=%s", got, f.lastBody()) + } + + before := f.requestCount() + got = f.run(append([]string{"promotion", "project", "apply", "p", "--workflow-id", "w", "--expected-config-id", "cfg", "--yes"}, envExpectedFlags()...)...) + if got.code == ExitSuccess || f.requestCount() != before || + !strings.Contains(got.stderr, "mutually exclusive") || !strings.Contains(got.stderr, "n8n 2.46 and later") || !strings.Contains(got.stderr, "n8n 2.45 and earlier") { + t.Errorf("both flags = %+v, want the per-version explanation and no request", got) + } + got = f.run("promotion", "project", "apply-continue", "p", "--workflow-id", "w", "--expected-branch", "main", "--expected-commit", cliSelectionSHA, "--yes") + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "--expected-environment-id") || !strings.Contains(got.stderr, "--expected-config-id") { + t.Errorf("no id = %+v", got) + } + // The connection apply-continue predates environments. + got = f.run(append([]string{"promotion", "apply-continue", "c", "--yes"}, envExpectedFlags()...)...) + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "unknown flag") { + t.Errorf("connection environment flag = %+v", got) + } + envFile := writePromotionInput(t, f, "env-review.json", cliEnvChanges) + got = f.run("promotion", "apply-continue", "c", "--expected-from", envFile, "--yes") + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "n8n promotion environment apply-continue") { + t.Errorf("connection environment source = %+v", got) + } +} + +func TestPromotionPromoteReviewAndWarnings(t *testing.T) { + for _, args := range [][]string{ + {"promotion", "environment", "promote", cliEnvironmentID}, + {"promotion", "project", "promote", "p", "--workflow-id", "w"}, + } { + f := promotionFixture(t, cliEnvPromoteBody) + got := f.run(append(args, "--yes")...) + if got.code != ExitSuccess { + t.Fatalf("%v: exit = %d, stderr: %s", args, got.code, got.stderr) + } + for _, want := range []string{"Promoted:", cliEnvironmentID, "n8n/promotion-1", "Review:", "#42 https://gitlab.example.com/org/repo/-/merge_requests/42", "workflows"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("%v: stdout missing %q:\n%s", args, want, got.stdout) + } + } + for _, want := range []string{"Warning: Branch protection blocks merging (see https://gitlab.example.com/help)", "Warning: No reviewers\n"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("%v: stderr missing %q:\n%s", args, want, got.stderr) + } + } + if strings.Contains(got.stdout, "Warning") { + t.Errorf("%v: stdout = %s, want warnings on stderr only", args, got.stdout) + } + got = f.run(append(args, "--yes", "--output", "json")...) + if got.code != ExitSuccess || !sameJSON(t, got.stdout, cliEnvPromoteBody) || !strings.Contains(got.stderr, "Warning: No reviewers") { + t.Errorf("%v json = %+v", args, got) + } + } + // n8n 2.45: no review line, no warnings, identifiers kept as sent. + f := promotionFixture(t, cliPromotionPromoteBody) + got := f.run("promotion", "project", "promote", "p", "--workflow-id", "w", "--yes") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "conn-1") || strings.Contains(got.stdout, "Review:") || strings.Contains(got.stdout, "Environment:") || got.stderr != "" { + t.Errorf("old shape = %+v", got) + } + got = f.run("promotion", "project", "promote", "p", "--workflow-id", "w", "--yes", "--output", "json") + if got.code != ExitSuccess || !sameJSON(t, got.stdout, cliPromotionPromoteBody) { + t.Errorf("old shape json = %+v", got) + } +} + +func TestPromotionChangesEnvironmentSourceText(t *testing.T) { + f := promotionFixture(t, cliEnvChanges) + got := f.run("promotion", "project", "changes", "p", "apply") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "Environment:") || !strings.Contains(got.stdout, cliEnvironmentID) || strings.Contains(got.stdout, "Config:") { + t.Errorf("2.46 changes = %+v", got) + } + got = f.run("promotion", "project", "changes", "p", "apply", "--output", "json") + if got.code != ExitSuccess || !sameJSON(t, got.stdout, cliEnvChanges) { + t.Errorf("2.46 changes json = %+v", got) + } + f.body = cliSelectionChanges + got = f.run("promotion", "project", "changes", "p", "apply") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "Config:") || strings.Contains(got.stdout, "Environment:") { + t.Errorf("2.45 changes = %+v", got) + } +} + +func TestPromotionEnvironmentSyncErrorsNameTheFix(t *testing.T) { + f := promotionFixture(t, `{}`) + // A bare 404: the instance may predate environments. + f.route = func(*http.Request, int) (int, string) { return http.StatusNotFound, `{"message":"not found"}` } + for _, args := range [][]string{ + {"promotion", "environment", "apply", cliEnvironmentID, "--yes"}, + append([]string{"promotion", "environment", "apply-continue", cliEnvironmentID, "--yes"}, envExpectedFlags()...), + {"promotion", "environment", "promote", cliEnvironmentID, "--yes"}, + } { + got := f.run(args...) + if got.code != ExitError || !strings.Contains(got.stderr, "older than n8n 2.46") || !strings.Contains(got.stderr, "'n8n promotion connection'") || !strings.Contains(got.stderr, "n8n promotion environment list") { + t.Errorf("%s 404 = %+v, want the connection and list hints", args[2], got) + } + } + // And the connection commands point at environments. + got := f.run("promotion", "apply", "conn-1", "--yes") + if got.code != ExitError || !strings.Contains(got.stderr, "'n8n promotion environment'") { + t.Errorf("connection apply 404 = %+v", got) + } + f.route = nil + + f.status = http.StatusForbidden + for scope, args := range map[string][]string{ + "gitConnection:pull": {"promotion", "environment", "apply", cliEnvironmentID, "--yes"}, + "gitConnection:push": {"promotion", "environment", "promote", cliEnvironmentID, "--yes"}, + } { + if got := f.run(args...); got.code != ExitError || !strings.Contains(got.stderr, scope) { + t.Errorf("%v 403 = %+v, want %s", args, got, scope) + } + } + for action, want := range map[string]string{"environment apply": "gitConnection:pull", "environment apply-continue": "gitConnection:pull", "environment promote": "gitConnection:push"} { + if got := promotionScope(action); got != want { + t.Errorf("scope(%s) = %s, want %s", action, got, want) + } + } + + f.status = http.StatusConflict + f.body = `{"message":"moved"}` + for _, args := range [][]string{ + {"promotion", "environment", "apply", cliEnvironmentID, "--yes"}, + {"promotion", "project", "apply", "p", "--workflow-id", "w", "--yes"}, + } { + if got := f.run(args...); got.code != ExitError || !strings.Contains(got.stderr, "different projects") || !strings.Contains(got.stderr, "nothing was applied") { + t.Errorf("%v 409 = %+v", args, got) + } + } + if got := f.run("promotion", "environment", "promote", cliEnvironmentID, "--yes"); got.code != ExitError || !strings.Contains(got.stderr, "--force") || !strings.Contains(got.stderr, "nothing was pushed") { + t.Errorf("promote 409 = %+v", got) + } + + f.status = http.StatusBadRequest + for _, args := range [][]string{ + {"promotion", "environment", "promote", cliEnvironmentID, "--yes"}, + {"promotion", "project", "promote", "p", "--workflow-id", "w", "--yes"}, + } { + if got := f.run(args...); got.code != ExitError || !strings.Contains(got.stderr, "personal project") || !strings.Contains(got.stderr, "move it back") { + t.Errorf("%v 400 = %+v", args, got) + } + } + + f.status = http.StatusUnprocessableEntity + if got := f.run("promotion", "environment", "apply", cliEnvironmentID, "--yes"); got.code != ExitError || !strings.Contains(got.stderr, "cannot be imported") { + t.Errorf("apply 422 = %+v, want the import diagnostic", got) + } +} + +func TestPromotionHelpNamesEnvironmentSync(t *testing.T) { + f := promotionFixture(t, `{}`) + got := f.run("promotion", "--help") + if got.code != ExitSuccess || strings.Contains(got.stdout, "still address connections") || + !strings.Contains(got.stdout, "environment apply") || !strings.Contains(got.stdout, "environment promote") { + t.Errorf("group help = %s", got.stdout) + } + got = f.run("promotion", "environment", "--help") + for _, want := range []string{"apply", "apply-continue", "promote"} { + if !strings.Contains(got.stdout, " "+want+" ") { + t.Errorf("environment help lacks %q:\n%s", want, got.stdout) + } + } +} diff --git a/internal/cli/promotion_selection.go b/internal/cli/promotion_selection.go index fa3e070..1239c16 100644 --- a/internal/cli/promotion_selection.go +++ b/internal/cli/promotion_selection.go @@ -25,8 +25,9 @@ func newPromotionDiscoveryCommand(opts Options, branches bool) *cobra.Command { Long: "Discover GitLab repositories or branches using a saved provider with gitConnection:discover.\n" + "Start with 'n8n promotion provider list', then repositories, then branches.\n" + "Pass the raw fullPath (for example org/repo) or GitLab project ID to branches;\n" + - "the CLI escapes it. Use remoteUrl from repositories as a connection target.\n" + - "No saved connection is required and no content changes. Other provider types\n" + + "the CLI escapes it. Use remoteUrl from repositories as an environment remote\n" + + "(n8n 2.46 and later) or a connection target (older). No saved environment\n" + + "or connection is required and no content changes. Other provider types\n" + "do not support discovery. Text lists repository targets or branch names and\n" + "defaults; JSON returns data and nextCursor. Follow nextCursor even after a\n" + "short page. --all follows cursors up to 10,000 items.\n\n" + cursorCollectionHelp, @@ -122,13 +123,17 @@ func newPromotionProjectChangesCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "changes ", Short: "List workflow changes for a project's promotion branch", Long: "Compare a team project with its resolved promotion branch without changing content.\n" + - "Start with 'n8n project list' for the project ID. The project's own connection\n" + - "takes precedence over the instance connection; clone the chosen direction\n" + - "first with 'n8n promotion checkout clone'. Apply requires gitConnection:pull;\n" + - "promote requires gitConnection:push. Text lists workflow IDs, statuses, and\n" + - "dependency counts; JSON includes changes, source, and nullable commitSha.\n" + - "Review the IDs before project apply or promote. Save apply JSON for\n" + - "--expected-from to reject a branch that moves after review.", + "Start with 'n8n project list' for the project ID. The project's own\n" + + "environment (n8n 2.46 and later) or connection (older) for the direction\n" + + "takes precedence over the instance one. Prepare the checkout first: 'n8n\n" + + "promotion environment connect' on 2.46, 'n8n promotion checkout clone'\n" + + "before. Apply requires gitConnection:pull; promote requires\n" + + "gitConnection:push. Text lists workflow IDs, statuses, and dependency\n" + + "counts; JSON includes changes, source (environmentId on 2.46, configId\n" + + "before), and nullable commitSha. On 2.46 a deleted or new promote row can\n" + + "be a workflow that moved between projects; promoting it is refused until\n" + + "it moves back. Review the IDs before project apply or promote. Save apply\n" + + "JSON for --expected-from to reject a branch that moves after review.", Example: " n8n promotion project changes PROJECT_ID apply --output json > changes.json\n" + " n8n promotion project changes PROJECT_ID promote --sort updatedAt --order desc", Args: cobra.ExactArgs(2), @@ -158,7 +163,12 @@ func newPromotionProjectChangesCommand(opts Options) *cobra.Command { if result.CommitSHA != nil { commit = *result.CommitSHA } - fmt.Fprintf(tw, "Config:\t%s\nBranch:\t%s\nCommit:\t%s\n", result.Source.ConfigID, result.Source.BranchName, commit) + if result.Source.EnvironmentID != "" { + fmt.Fprintf(tw, "Environment:\t%s\n", result.Source.EnvironmentID) + } else { + fmt.Fprintf(tw, "Config:\t%s\n", emptyDash(result.Source.ConfigID)) + } + fmt.Fprintf(tw, "Branch:\t%s\nCommit:\t%s\n", result.Source.BranchName, commit) fmt.Fprintln(tw, "ID\tNAME\tSTATUS\tDEPENDENCIES") for _, row := range result.Changes { fmt.Fprintf(tw, "%s\t%s\t%s\t%d\n", row.ID, row.Name, row.Status, row.DependencyCount) @@ -174,6 +184,14 @@ func newPromotionProjectChangesCommand(opts Options) *cobra.Command { return cmd } +// What a selection or apply-continue command addresses. Connections exist only +// before n8n 2.46, environments only from 2.46; projects exist on both. +const ( + promotionTargetConnection = "connection" + promotionTargetProject = "project" + promotionTargetEnvironment = "environment" +) + type promotionSelectionFlags struct { instance instanceFlags input, output, expectedFrom string @@ -185,15 +203,24 @@ type promotionSelectionFlags struct { } // Separate commands keep the required source and selection explicit at continue time. -func newPromotionSelectionCommand(opts Options, action string, project bool) *cobra.Command { +func newPromotionSelectionCommand(opts Options, action, target string) *cobra.Command { var f promotionSelectionFlags - target, prefix := "project", "n8n promotion project " - if !project { - target, prefix = "connection", "n8n promotion " + project := target == promotionTargetProject + environment := target == promotionTargetEnvironment + prefix := "n8n promotion " + target + " " + if target == promotionTargetConnection { + prefix = "n8n promotion " } isContinue := action == "apply-continue" isPromote := action == "promote" + // Which expected-source identifier flags exist: each generation accepts + // only its own field, and projects are served by both. + configFlag := !environment + environmentFlag := target != promotionTargetConnection short := "Apply selected workflow changes from a project's branch" + if environment { + short = "Apply an environment's Git branch into this instance" + } if isContinue { short = "Continue a reviewed " + target + " apply after binding setup" } @@ -201,33 +228,79 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co short = "Promote selected project workflows to the remote branch" } long := "Start with 'n8n promotion project changes PROJECT_ID apply' to review workflow IDs.\n" + - "The project's own connection resolves first, otherwise the instance connection.\n" + - "The apply direction must be cloned. Selected IDs on the branch are imported;\n" + - "selected workflows owned by this project whose IDs are absent from the branch\n" + - "are removed. Unselected content stays unchanged. Duplicate or invalid IDs\n" + - "reject the whole request. Requires gitConnection:pull.\n" - if !project { + "The project's own apply environment (n8n 2.46 and later) or connection\n" + + "(older) resolves first, otherwise the instance one. It must be prepared:\n" + + "'n8n promotion environment connect' on 2.46, 'n8n promotion checkout\n" + + "clone' before. Selected IDs on the branch are imported; selected workflows\n" + + "owned by this project whose IDs are absent from the branch are removed.\n" + + "On 2.46 a selected workflow also moves within the project to match the\n" + + "branch, with the folders that hold it, which take the branch name; one\n" + + "the branch and the instance hold in different projects is refused with\n" + + "409 before any write. Unselected content stays unchanged. Duplicate or\n" + + "invalid IDs reject the whole request. Requires gitConnection:pull.\n" + switch { + case target == promotionTargetConnection: long = "Continue a full instance-connection apply after resolving its preflight items.\n" + - "Start with 'n8n promotion apply CONNECTION_ID --output json'. The apply\n" + - "checkout must be cloned. Every team project is synchronized: workflows,\n" + + "Connections exist before n8n 2.46; on 2.46 use 'n8n promotion environment\n" + + "apply-continue'. Start with 'n8n promotion apply CONNECTION_ID --output json'.\n" + + "The apply checkout must be cloned. Every team project is synchronized: workflows,\n" + "folders, credentials, tables, variables, and tags can change or be removed.\n" + "Requires gitConnection:pull and the same permissions as the initial apply.\n" + case environment && isContinue: + long = "Continue a full environment apply (n8n 2.46 and later) after resolving its\n" + + "preflight items. Start with 'n8n promotion environment apply ENVIRONMENT_ID\n" + + "--output json'. The instance-scope apply environment must still be\n" + + "connected. Every team project is synchronized: workflows, folders,\n" + + "credentials, tables, variables, and tags can be created, updated, moved,\n" + + "renamed, or removed to match. Requires gitConnection:pull and the same\n" + + "permissions as the initial apply.\n\n" + case environment: + long = "Check the full package at the branch tip of an instance-scope apply\n" + + "environment (n8n 2.46 and later) and import it into the instance,\n" + + "overwriting to match. Before 2.46 use 'n8n promotion apply' with a\n" + + "connection. Start with 'n8n promotion environment list --direction\n" + + "apply' and connect it first with 'n8n promotion environment connect'.\n" + + "Personal projects are ignored. An applied run rewrites every team\n" + + "project from the branch and cannot be undone: workflows, folders,\n" + + "credentials, data tables, variables, and tags are created, updated,\n" + + "or removed to match, workflows and folders move within their project,\n" + + "folders take the branch name, and credential gaps become stubs.\n" + + "Existing variable values are kept. A workflow or folder the branch and\n" + + "the instance hold in different projects is refused with 409 before any\n" + + "write. Requires gitConnection:pull.\n\n" } if isPromote { long = "Start with 'n8n promotion project changes PROJECT_ID promote' to review IDs.\n" + "Push the current state of selected workflows to the project's resolved\n" + - "promotion connection (its own, otherwise the instance connection). Clone\n" + - "the promote direction first. Archived workflows remain archived on the\n" + - "branch; workflows no longer owned by the project leave the branch. Unknown\n" + - "deletions reject the whole request. Requires gitConnection:push, plus\n" + - "variable:list when workflows use variables. Commit message is optional;\n" + - "the server supplies a default. Force pushing is not supported.\n" + "promote environment (n8n 2.46 and later) or connection (older): its own,\n" + + "otherwise the instance one. Prepare it first: 'n8n promotion environment\n" + + "connect' on 2.46, 'n8n promotion checkout clone' before. Archived\n" + + "workflows remain archived on the branch; workflows gone from the instance\n" + + "leave the branch. On 2.46 a workflow that moved into or out of the\n" + + "project since the branch was written is refused with 400; move it back\n" + + "first. Unknown deletions reject the whole request. Requires\n" + + "gitConnection:push, plus variable:list when workflows use variables.\n" + + "Commit message is optional; the server supplies a default. Force pushing\n" + + "is not supported. The result can name a review the Git host opened;\n" + + "advisory warnings go to stderr.\n" } else { + var idFlags, idField string + switch target { + case promotionTargetConnection: + idFlags, idField = "--expected-config-id", "configId" + case promotionTargetEnvironment: + idFlags, idField = "--expected-environment-id", "environmentId" + default: + idFlags = "--expected-environment-id (n8n 2.46 and later) or\n--expected-config-id (older; mutually exclusive)" + idField = "environmentId (2.46) or configId (older)" + } long += "Use --expected-from FILE|- with changes JSON or a blocked apply result,\n" + - "or supply all three --expected-config-id, --expected-branch, --expected-commit\n" + - "flags (full lowercase 40- or 64-digit hex SHA). A null commit cannot be used.\n" + "or supply " + idFlags + ", --expected-branch, and\n" + + "--expected-commit together (full lowercase 40- or 64-digit hex SHA). A\n" + + "null commit cannot be used. --expected-from passes through the\n" + + "identifier the instance returned: " + idField + ".\n" if isContinue { - long += "Expected source is required; use the blocked result's configId and git.\n" + + long += "Expected source is required; use the blocked result's " + idField + "\nand git. " + "The server keeps no session and provides no exactly-once guarantee.\n" if project { long += "Resend the same full workflow ID selection used for the initial apply.\n" @@ -278,10 +351,26 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co documentFlags = append(documentFlags, "commit-message") } else { cmd.Flags().StringVar(&f.expectedFrom, "expected-from", "", "changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes)") - cmd.Flags().StringVar(&f.source.ConfigID, "expected-config-id", "", "reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit)") - cmd.Flags().StringVar(&f.source.BranchName, "expected-branch", "", "reviewed branch name (default: omitted; requires expected config ID and commit)") - cmd.Flags().StringVar(&f.source.CommitSHA, "expected-commit", "", "reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires expected config ID and branch)") - documentFlags = append(documentFlags, "expected-from", "expected-config-id", "expected-branch", "expected-commit") + documentFlags = append(documentFlags, "expected-from") + if environmentFlag { + usage := "reviewed environment ID, 1 to 36 characters (default: omitted; requires expected branch and commit)" + if project { + usage = "reviewed environment ID on n8n 2.46 and later, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-config-id)" + } + cmd.Flags().StringVar(&f.source.EnvironmentID, "expected-environment-id", "", usage) + documentFlags = append(documentFlags, "expected-environment-id") + } + if configFlag { + usage := "reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit)" + if project { + usage = "reviewed config ID on n8n 2.45 and earlier, 1 to 36 characters (default: omitted; requires expected branch and commit; excludes --expected-environment-id)" + } + cmd.Flags().StringVar(&f.source.ConfigID, "expected-config-id", "", usage) + documentFlags = append(documentFlags, "expected-config-id") + } + cmd.Flags().StringVar(&f.source.BranchName, "expected-branch", "", "reviewed branch name (default: omitted; requires the expected ID and commit)") + cmd.Flags().StringVar(&f.source.CommitSHA, "expected-commit", "", "reviewed lowercase full 40- or 64-digit hex commit SHA (default: omitted; requires the expected ID and branch)") + documentFlags = append(documentFlags, "expected-branch", "expected-commit") } if isContinue { cmd.Flags().BoolVar(&f.destructive, "confirm-destructive-changes", false, "allow all destructive changes at continue time, including unreviewed column value loss and, for full apply, team-project deletion (default: false)") @@ -291,7 +380,11 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co if err := validateOutput(f.output); err != nil { return err } - if strings.TrimSpace(args[0]) != args[0] || args[0] == "" || utf8.RuneCountInString(args[0]) > 36 { + if environment { + if err := validatePromotionEnvironmentArg(args[0]); err != nil { + return err + } + } else if strings.TrimSpace(args[0]) != args[0] || args[0] == "" || utf8.RuneCountInString(args[0]) > 36 { return fmt.Errorf("%s ID must contain 1 to 36 characters without surrounding whitespace", target) } if cmd.Flags().Changed("input") { @@ -312,7 +405,11 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co } var source *n8n.PromotionExpectedSource if !isPromote && f.input == "" { - explicit := cmd.Flags().Changed("expected-config-id") || cmd.Flags().Changed("expected-branch") || cmd.Flags().Changed("expected-commit") + if cmd.Flags().Changed("expected-config-id") && cmd.Flags().Changed("expected-environment-id") { + return fmt.Errorf("--expected-config-id and --expected-environment-id are mutually exclusive: use --expected-environment-id on n8n 2.46 and later, --expected-config-id on n8n 2.45 and earlier") + } + explicit := cmd.Flags().Changed("expected-config-id") || cmd.Flags().Changed("expected-environment-id") || + cmd.Flags().Changed("expected-branch") || cmd.Flags().Changed("expected-commit") if cmd.Flags().Changed("expected-from") { if explicit { return fmt.Errorf("--expected-from and explicit expected-source flags are mutually exclusive") @@ -344,12 +441,20 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co r.ExpectedSource = *source } request = r + case isContinue && environment: + r := &n8n.ContinueApplyPromotionEnvironmentRequest{ConfirmDestructiveChanges: destructive} + if source != nil { + r.ExpectedSource = *source + } + request = r case isContinue: r := &n8n.ContinueApplyPromotionRequest{ConfirmDestructiveChanges: destructive} if source != nil { r.ExpectedSource = *source } request = r + case environment: + request = &n8n.ApplyPromotionEnvironmentRequest{ExpectedSource: source} default: request = &n8n.ApplyProjectSelectionRequest{WorkflowIDs: f.workflowIDs, ExpectedSource: source} } @@ -366,6 +471,10 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co return cmd } +// readPromotionExpectedSource reads the reviewed source from 'project changes' +// JSON or a blocked apply result. It passes through whichever identifier the +// instance returned (environmentId from n8n 2.46, configId before); the +// request's own validation then checks it fits the route. func readPromotionExpectedSource(opts Options, path string) (*n8n.PromotionExpectedSource, error) { var fields map[string]json.RawMessage if err := readPromotionDocument(opts, path, &fields); err != nil { @@ -379,15 +488,34 @@ func readPromotionExpectedSource(opts Options, path string) (*n8n.PromotionExpec } return json.Unmarshal(raw, dst) } + // sourceID decodes environmentId or configId, whichever the object has. + sourceID := func(object map[string]json.RawMessage, where string) error { + _, hasEnvironment := object["environmentId"] + _, hasConfig := object["configId"] + switch { + case hasEnvironment && hasConfig: + return fmt.Errorf("%senvironmentId and %sconfigId are both present: keep the one the instance returned", where, where) + case hasEnvironment: + if err := decode(object["environmentId"], &result.EnvironmentID); err != nil { + return fmt.Errorf("%senvironmentId: %w", where, err) + } + default: + if err := decode(object["configId"], &result.ConfigID); err != nil { + return fmt.Errorf("%sconfigId (or environmentId on n8n 2.46 and later): %w", where, err) + } + } + return nil + } if raw, ok := fields["source"]; ok { var source map[string]json.RawMessage if err := decode(raw, &source); err != nil { return nil, err } - for key, dst := range map[string]*string{"configId": &result.ConfigID, "branchName": &result.BranchName} { - if err := decode(source[key], dst); err != nil { - return nil, fmt.Errorf("source.%s: %w", key, err) - } + if err := sourceID(source, "source."); err != nil { + return nil, err + } + if err := decode(source["branchName"], &result.BranchName); err != nil { + return nil, fmt.Errorf("source.branchName: %w", err) } if err := decode(fields["commitSha"], &result.CommitSHA); err != nil { return nil, fmt.Errorf("commitSha: %w", err) @@ -397,8 +525,8 @@ func readPromotionExpectedSource(opts Options, path string) (*n8n.PromotionExpec if err := decode(fields["status"], &status); err != nil || status != n8n.PromotionApplyStatusBlocked { return nil, fmt.Errorf("--expected-from requires changes JSON or a blocked apply result") } - if err := decode(fields["configId"], &result.ConfigID); err != nil { - return nil, fmt.Errorf("configId: %w", err) + if err := sourceID(fields, ""); err != nil { + return nil, err } var git map[string]json.RawMessage if err := decode(fields["git"], &git); err != nil { @@ -422,8 +550,11 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo return err } subject := promotionProjectSubject(id) + target := promotionTargetProject action := "project apply" question := fmt.Sprintf("Apply selected workflow changes to project %q on %s? Selected workflows absent from the branch are deleted; selected content and dependencies are overwritten.", id, resolution.URL) + fullApply := " Every team project's workflows, folders, credentials, tables, variables, and tags may be overwritten or removed." + allDestructive := " ALL team-project deletions with everything in them and destructive data-table column changes at continue time are allowed, including unreviewed changes; column values are lost." switch r := request.(type) { case *n8n.PromoteProjectSelectionRequest: action = "project promote" @@ -434,10 +565,19 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo question += " ALL destructive data-table column changes at continue time are allowed, including unreviewed changes; removed or retyped column values are lost." } case *n8n.ContinueApplyPromotionRequest: - action, subject = "apply-continue", promotionConnectionSubject(id) - question = fmt.Sprintf("Continue applying connection %q into %s? Every team project's workflows, folders, credentials, tables, variables, and tags may be overwritten or removed.", id, resolution.URL) + action, subject, target = "apply-continue", promotionConnectionSubject(id), promotionTargetConnection + question = fmt.Sprintf("Continue applying connection %q into %s?", id, resolution.URL) + fullApply + if r.ConfirmDestructiveChanges != nil && *r.ConfirmDestructiveChanges { + question += allDestructive + } + case *n8n.ApplyPromotionEnvironmentRequest: + action, subject, target = "environment apply", promotionEnvironmentSubject(id), promotionTargetEnvironment + question = fmt.Sprintf("Apply the remote of promotion environment %q into %s and overwrite instance projects to match? Workflows, folders, credentials, tables, variables, and tags change; this cannot be undone.", id, resolution.URL) + case *n8n.ContinueApplyPromotionEnvironmentRequest: + action, subject, target = "environment apply-continue", promotionEnvironmentSubject(id), promotionTargetEnvironment + question = fmt.Sprintf("Continue applying environment %q into %s?", id, resolution.URL) + fullApply if r.ConfirmDestructiveChanges != nil && *r.ConfirmDestructiveChanges { - question += " ALL team-project deletions with everything in them and destructive data-table column changes at continue time are allowed, including unreviewed changes; column values are lost." + question += allDestructive } } if err := opts.confirmer(f.yes).Confirm(question); err != nil { @@ -454,16 +594,17 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo } return promotionAPIError(err, resolution, action, subject) } - if f.output == outputJSON { - return writeJSON(opts.Streams.Out, promoted) - } - return writePromotionPromoteResult(opts, resolution, promoted) + return writePromotionPromoteOutput(opts, resolution, promoted, f.output) case *n8n.ApplyProjectSelectionRequest: result, err = client.ApplyProjectSelection(ctx, id, *r, callOpts...) case *n8n.ContinueApplyProjectSelectionRequest: result, err = client.ContinueApplyProjectSelection(ctx, id, *r, callOpts...) case *n8n.ContinueApplyPromotionRequest: result, err = client.ContinueApplyPackage(ctx, id, *r, callOpts...) + case *n8n.ApplyPromotionEnvironmentRequest: + result, err = client.ApplyPromotionEnvironment(ctx, id, *r, callOpts...) + case *n8n.ContinueApplyPromotionEnvironmentRequest: + result, err = client.ContinueApplyPromotionEnvironment(ctx, id, *r, callOpts...) } if err != nil { if refused := f.idempotency.refusal(err, resolution); refused != nil { @@ -479,7 +620,7 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo if err != nil { return err } - return finishPromotionApplyTarget(opts, id, result, strings.HasPrefix(action, "project ")) + return finishPromotionApplyTarget(opts, id, result, target) } func promotionProjectSubject(id string) promotionSubject { diff --git a/internal/cli/promotion_test.go b/internal/cli/promotion_test.go index 129ff16..e283df9 100644 --- a/internal/cli/promotion_test.go +++ b/internal/cli/promotion_test.go @@ -270,8 +270,8 @@ func TestPromotionProviderUpdateConfirmation(t *testing.T) { 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, "every connection") { - t.Errorf("prompt = %q, want the attached-connection consequence", got.stderr) + if !strings.Contains(got.stderr, "every environment or connection") { + t.Errorf("prompt = %q, want the environment-or-connection consequence", got.stderr) } f.interactive = false diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index 9637b56..7b6aad9 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 = 35 +const deliveredThrough = 36 // 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 e277456..30e0a45 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -2178,8 +2178,8 @@ "scope": "gitConnection:pull", "availability": "upstream-only", "phase": 36, - "command": "", - "status": "planned" + "command": "n8n promotion environment apply", + "status": "implemented" }, { "operationId": "continueApplyPackage", @@ -2189,8 +2189,8 @@ "scope": "gitConnection:pull", "availability": "upstream-only", "phase": 36, - "command": "", - "status": "planned" + "command": "n8n promotion environment apply-continue", + "status": "implemented" }, { "operationId": "promotePackage", @@ -2200,8 +2200,8 @@ "scope": "gitConnection:push", "availability": "upstream-only", "phase": 36, - "command": "", - "status": "planned" + "command": "n8n promotion environment promote", + "status": "implemented" } ] } diff --git a/internal/n8n/idempotency_test.go b/internal/n8n/idempotency_test.go index 8884cb6..cb391cd 100644 --- a/internal/n8n/idempotency_test.go +++ b/internal/n8n/idempotency_test.go @@ -120,6 +120,18 @@ func TestIdempotencyKeyHeader(t *testing.T) { _, err := c.PromoteProjectSelection(ctx, "proj-1", PromoteProjectSelectionRequest{WorkflowIDs: []string{"wf"}, CommitMessage: &message}, opts...) return err }}, + {"environment promote", "/promotions/environments/" + testEnvironmentID + "/promote", envPromoteResultBody, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.PromotePromotionEnvironment(ctx, testEnvironmentID, PromotePromotionEnvironmentRequest{CommitMessage: &message}, opts...) + return err + }}, + {"environment apply", "/promotions/environments/" + testEnvironmentID + "/apply", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{}, opts...) + return err + }}, + {"environment apply continue", "/promotions/environments/" + testEnvironmentID + "/apply/continue", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ContinueApplyPromotionEnvironment(ctx, testEnvironmentID, ContinueApplyPromotionEnvironmentRequest{ExpectedSource: envSource()}, opts...) + return err + }}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/n8n/promotion.go b/internal/n8n/promotion.go index d83cddd..9112b27 100644 --- a/internal/n8n/promotion.go +++ b/internal/n8n/promotion.go @@ -568,12 +568,66 @@ type PromotionGit struct { BranchName string `json:"branchName"` } -// PromotePromotionResult is the promote acknowledgement. +// PromotionReview is the code review a promote opened on the Git host, for +// example a GitLab merge request. Only n8n 2.46 and later report it. +type PromotionReview struct { + ReviewID string `json:"reviewId"` + Number int `json:"number"` + WebURL string `json:"webUrl"` +} + +// PromotionPromoteWarning is one advisory a promote reports after pushing. +// The push already happened; a warning never means nothing was promoted. +type PromotionPromoteWarning struct { + Message string `json:"message"` + LinkURL string `json:"linkUrl,omitempty"` +} + +// PromotePromotionResult is the promote acknowledgement. Instances older than +// n8n 2.46 identify the source with ConnectionID and ConfigID; 2.46 and later +// with EnvironmentID, and may add Review and Warnings. Both shapes decode. +// +// JSON encoding re-emits the verbatim response, so --output json never +// invents the identifier fields the other generation uses. type PromotePromotionResult struct { - ConnectionID string `json:"connectionId"` - ConfigID string `json:"configId"` - Counts PromotionPromoteCounts `json:"counts"` - Git PromotionGit `json:"git"` + ConnectionID string `json:"connectionId,omitempty"` + ConfigID string `json:"configId,omitempty"` + EnvironmentID string `json:"environmentId,omitempty"` + Counts PromotionPromoteCounts `json:"counts"` + Git PromotionGit `json:"git"` + Review *PromotionReview `json:"review,omitempty"` + Warnings []PromotionPromoteWarning `json:"warnings,omitempty"` + raw json.RawMessage +} + +// UnmarshalJSON decodes the typed view and keeps the verbatim response. +func (r *PromotePromotionResult) UnmarshalJSON(data []byte) error { + type plain PromotePromotionResult + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *r = PromotePromotionResult(decoded) + r.raw = append(json.RawMessage(nil), data...) + return nil +} + +// MarshalJSON re-emits the verbatim response when present. +func (r PromotePromotionResult) MarshalJSON() ([]byte, error) { + if len(r.raw) > 0 { + return r.raw, nil + } + type plain PromotePromotionResult + return json.Marshal(plain(r)) +} + +// SourceID is the connection (before n8n 2.46) or environment (2.46 and +// later) the promote pushed through. +func (r PromotePromotionResult) SourceID() string { + if r.EnvironmentID != "" { + return r.EnvironmentID + } + return r.ConnectionID } // PromotionApplyProjectCounts counts project rows created, updated, skipped or @@ -585,11 +639,17 @@ type PromotionApplyProjectCounts struct { Deleted int `json:"deleted"` } -// PromotionApplyFolderCounts counts folders created, skipped or removed. +// PromotionApplyFolderCounts counts folders created, skipped or removed. n8n +// 2.46 and later also count existing folders updated to match the branch, and +// of those, the ones moved and the ones renamed; older instances omit them, +// so they are nil there rather than a misleading zero. type PromotionApplyFolderCounts struct { - Created int `json:"created"` - Skipped int `json:"skipped"` - Removed int `json:"removed"` + Created int `json:"created"` + Updated *int `json:"updated,omitempty"` + Skipped int `json:"skipped"` + Removed int `json:"removed"` + Moved *int `json:"moved,omitempty"` + Renamed *int `json:"renamed,omitempty"` } // PromotionApplyPublishingCounts counts per-workflow publishing outcomes. @@ -602,20 +662,24 @@ type PromotionApplyPublishingCounts struct { } // PromotionApplyWorkflowCounts counts workflows created, updated, skipped, -// archived or deleted by one apply. +// archived or deleted by one apply. Moved (n8n 2.46 and later; nil before) +// counts updated workflows that also moved to another folder of their project. type PromotionApplyWorkflowCounts struct { Created int `json:"created"` Updated int `json:"updated"` Skipped int `json:"skipped"` Archived int `json:"archived"` Deleted int `json:"deleted"` + Moved *int `json:"moved,omitempty"` Publishing PromotionApplyPublishingCounts `json:"publishing"` } -// PromotionApplyCredentialCounts counts credentials matched or stubbed. +// PromotionApplyCredentialCounts counts credentials matched or stubbed, and +// from n8n 2.46 updated (nil on older instances). type PromotionApplyCredentialCounts struct { - Matched int `json:"matched"` - Stubbed int `json:"stubbed"` + Matched int `json:"matched"` + Stubbed int `json:"stubbed"` + Updated *int `json:"updated,omitempty"` } // PromotionApplyDataTableCounts counts data tables matched, created or updated. @@ -775,20 +839,38 @@ func (p PromotionApplyPreflight) Empty() bool { } // PromotionExpectedSource pins the source an apply or continue may import: -// the config, branch and full commit a review saw. A mismatch answers status -// source-changed and writes nothing. +// the environment or config, branch and full commit a review saw. A mismatch +// answers status source-changed and writes nothing. +// +// The identifier changed with the generation: n8n 2.46 and later require +// EnvironmentID, older instances ConfigID. Exactly one is set, and it is sent +// as given, because each generation rejects the other's field. type PromotionExpectedSource struct { - ConfigID string `json:"configId"` - BranchName string `json:"branchName"` - CommitSHA string `json:"commitSha"` + ConfigID string `json:"configId,omitempty"` + EnvironmentID string `json:"environmentId,omitempty"` + BranchName string `json:"branchName"` + CommitSHA string `json:"commitSha"` } var promotionCommitSHA = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) // Validate rejects an expected source the API would reject before transport. +// Either identifier passes; [PromotionExpectedSource.ValidateEnvironment] and +// [PromotionExpectedSource.ValidateConfig] pin one generation. func (s PromotionExpectedSource) Validate() error { - if err := validatePromotionID(s.ConfigID, "expected source config ID"); err != nil { - return err + switch { + case s.ConfigID != "" && s.EnvironmentID != "": + return fmt.Errorf("expected source must name environmentId (n8n 2.46 and later) or configId (n8n 2.45 and earlier), not both: keep the one the instance returned") + case s.EnvironmentID != "": + if err := validatePromotionID(s.EnvironmentID, "expected source environment ID"); err != nil { + return err + } + case s.ConfigID != "": + if err := validatePromotionID(s.ConfigID, "expected source config ID"); err != nil { + return err + } + default: + return fmt.Errorf("expected source needs environmentId on n8n 2.46 and later (--expected-environment-id) or configId on n8n 2.45 and earlier (--expected-config-id)") } if strings.TrimSpace(s.BranchName) == "" { return fmt.Errorf("expected source branch name is required") @@ -799,30 +881,57 @@ func (s PromotionExpectedSource) Validate() error { return nil } +// ValidateEnvironment is Validate for environment routes, which exist only on +// n8n 2.46 and later and accept only environmentId. +func (s PromotionExpectedSource) ValidateEnvironment() error { + if err := s.Validate(); err != nil { + return err + } + if s.EnvironmentID == "" { + return fmt.Errorf("environment commands need expectedSource.environmentId (n8n 2.46 and later), but the source names configId, which only n8n 2.45 and earlier return: review again with 'n8n promotion environment apply' or 'n8n promotion project changes' and use that environmentId") + } + return nil +} + +// ValidateConfig is Validate for connection routes, which exist only before +// n8n 2.46 and accept only configId. +func (s PromotionExpectedSource) ValidateConfig() error { + if err := s.Validate(); err != nil { + return err + } + if s.ConfigID == "" { + return fmt.Errorf("connection commands need expectedSource.configId (n8n 2.45 and earlier), but the source names environmentId, which only n8n 2.46 and later return: on n8n 2.46 use 'n8n promotion environment apply-continue' instead") + } + return nil +} + // ApplyPromotionResult is the apply acknowledgement. Inspect Status before // reading anything else: applied carries Counts and Warnings; blocked carries // Preflight and wrote nothing; source-changed carries neither and wrote -// nothing. ConfigID and Git identify the source for a later continue. +// nothing. ConfigID (before n8n 2.46) or EnvironmentID (2.46 and later) and +// Git identify the source for a later continue; older instances also report +// ConnectionID. // // Extra holds top-level fields this type does not name. JSON encoding // re-emits the verbatim response, so --output json is lossless even for // fields and variants newer than the client. type ApplyPromotionResult struct { - ConnectionID string `json:"connectionId"` - ConfigID string `json:"configId"` - Status string `json:"status,omitempty"` - Git PromotionGit `json:"git"` - Counts *PromotionApplyCounts `json:"counts,omitempty"` - Warnings []PromotionApplyIssue `json:"warnings,omitempty"` - Preflight *PromotionApplyPreflight `json:"preflight,omitempty"` - Extra map[string]json.RawMessage `json:"-"` - raw json.RawMessage + ConnectionID string `json:"connectionId,omitempty"` + ConfigID string `json:"configId,omitempty"` + EnvironmentID string `json:"environmentId,omitempty"` + Status string `json:"status,omitempty"` + Git PromotionGit `json:"git"` + Counts *PromotionApplyCounts `json:"counts,omitempty"` + Warnings []PromotionApplyIssue `json:"warnings,omitempty"` + Preflight *PromotionApplyPreflight `json:"preflight,omitempty"` + Extra map[string]json.RawMessage `json:"-"` + raw json.RawMessage } // applyPromotionResultFields are the field names [ApplyPromotionResult] // decodes itself. Anything else lands in Extra. var applyPromotionResultFields = []string{ - "connectionId", "configId", "status", "git", "counts", "warnings", "preflight", + "connectionId", "configId", "environmentId", "status", "git", "counts", "warnings", "preflight", } // UnmarshalJSON decodes by shape, keeps unknown fields in Extra, and keeps the @@ -888,10 +997,25 @@ func (r ApplyPromotionResult) Applied() bool { return r.Status == PromotionApplyStatusApplied || (r.Status == "" && r.Counts != nil) } -// ExpectedSource returns the source a continue must name: the config and the -// branch and commit this result was checked against. +// ExpectedSource returns the source a continue must name: the environment or +// config and the branch and commit this result was checked against. The +// identifier is the one the instance returned; environmentId wins when a +// response carries both. func (r ApplyPromotionResult) ExpectedSource() PromotionExpectedSource { - return PromotionExpectedSource{ConfigID: r.ConfigID, BranchName: r.Git.BranchName, CommitSHA: r.Git.CommitSHA} + source := PromotionExpectedSource{EnvironmentID: r.EnvironmentID, BranchName: r.Git.BranchName, CommitSHA: r.Git.CommitSHA} + if source.EnvironmentID == "" { + source.ConfigID = r.ConfigID + } + return source +} + +// SourceID is the connection (before n8n 2.46) or environment (2.46 and +// later) the apply read from. +func (r ApplyPromotionResult) SourceID() string { + if r.EnvironmentID != "" { + return r.EnvironmentID + } + return r.ConnectionID } // ListPromotionProviders returns one cursor-paginated page of providers. diff --git a/internal/n8n/promotion_environment.go b/internal/n8n/promotion_environment.go index 0384d80..dad0ed6 100644 --- a/internal/n8n/promotion_environment.go +++ b/internal/n8n/promotion_environment.go @@ -410,3 +410,93 @@ func (c *Client) RemoveProjectFromPromotionEnvironment(ctx context.Context, id, }, nil) return err } + +// ApplyPromotionEnvironmentRequest is the optional body of a full apply +// through an environment. ExpectedSource pins the reviewed environment, branch +// and commit; without it the apply checks whatever the branch tip is now. +type ApplyPromotionEnvironmentRequest struct { + ExpectedSource *PromotionExpectedSource `json:"expectedSource,omitempty"` +} + +// Validate rejects an incomplete expected source, or one that names configId, +// before transport. +func (r ApplyPromotionEnvironmentRequest) Validate() error { + if r.ExpectedSource == nil { + return nil + } + return r.ExpectedSource.ValidateEnvironment() +} + +// ContinueApplyPromotionEnvironmentRequest rechecks a reviewed full apply +// through an environment. The server keeps no session: the expected source is +// required. +type ContinueApplyPromotionEnvironmentRequest struct { + ExpectedSource PromotionExpectedSource `json:"expectedSource"` + ConfirmDestructiveChanges *bool `json:"confirmDestructiveChanges,omitempty"` +} + +// Validate requires a complete reviewed source that names environmentId. +func (r ContinueApplyPromotionEnvironmentRequest) Validate() error { + return r.ExpectedSource.ValidateEnvironment() +} + +// PromotePromotionEnvironmentRequest commits every team project and pushes +// through an environment. Unlike the connection promote, the commit message is +// optional: the server generates one when it is omitted. +type PromotePromotionEnvironmentRequest struct { + CommitMessage *string `json:"commitMessage,omitempty"` + Force bool `json:"force,omitempty"` +} + +// Validate rejects a blank or overlong commit message before transport. +func (r PromotePromotionEnvironmentRequest) Validate() error { + if r.CommitMessage == nil { + return nil + } + return PromotePromotionRequest{CommitMessage: *r.CommitMessage}.Validate() +} + +// ApplyPromotionEnvironment checks the full package at the branch tip of an +// instance-scope apply environment and imports it, overwriting to match. The +// environment must be connected first. Inspect the result status before +// reading counts. opts accepts [IdempotencyKey]. +func (c *Client) ApplyPromotionEnvironment(ctx context.Context, id string, request ApplyPromotionEnvironmentRequest, opts ...CallOption) (*ApplyPromotionResult, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + return c.applyPromotionSelection(ctx, PathJoin("promotions", "environments", id, "apply"), request, opts) +} + +// ContinueApplyPromotionEnvironment rechecks bindings and applies the reviewed +// full package of an apply environment. opts accepts [IdempotencyKey]. +func (c *Client) ContinueApplyPromotionEnvironment(ctx context.Context, id string, request ContinueApplyPromotionEnvironmentRequest, opts ...CallOption) (*ApplyPromotionResult, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + return c.applyPromotionSelection(ctx, PathJoin("promotions", "environments", id, "apply", "continue"), request, opts) +} + +// PromotePromotionEnvironment exports every team project, commits it and +// pushes through an instance-scope promote environment. The environment must +// be connected first. opts accepts [IdempotencyKey]. +func (c *Client) PromotePromotionEnvironment(ctx context.Context, id string, request PromotePromotionEnvironmentRequest, opts ...CallOption) (*PromotePromotionResult, error) { + if err := ValidatePromotionEnvironmentID(id); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + var result PromotePromotionResult + req := Request{Method: http.MethodPost, Path: PathJoin("promotions", "environments", id, "promote"), Body: request} + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { + return nil, err + } + return &result, nil +} diff --git a/internal/n8n/promotion_environment_sync_test.go b/internal/n8n/promotion_environment_sync_test.go new file mode 100644 index 0000000..ac2fdcc --- /dev/null +++ b/internal/n8n/promotion_environment_sync_test.go @@ -0,0 +1,320 @@ +package n8n + +import ( + "context" + "encoding/json" + "net/http" + "reflect" + "strings" + "testing" +) + +// n8n 2.46 apply, continue, and promote shapes: environmentId replaces +// connectionId and configId, folders gain updated/moved/renamed, workflows +// gain moved, credentials gain updated, and promote can add review and +// warnings. + +const envSourceJSON = `{"environmentId":"` + testEnvironmentID + `","branchName":"main","commitSha":"` + selectionSHA + `"}` + +const envAppliedResultBody = `{ + "environmentId":"` + testEnvironmentID + `", + "git":{"commitSha":"` + selectionSHA + `","branchName":"main"}, + "status":"applied", + "counts":{ + "projects":{"created":0,"updated":1,"skipped":0,"deleted":0}, + "folders":{"created":1,"updated":3,"skipped":0,"removed":0,"moved":2,"renamed":1}, + "workflows":{"created":0,"updated":4,"skipped":0,"archived":0,"deleted":0,"moved":2,"publishing":{"published":0,"unpublished":0,"unchanged":4,"blocked":0,"failed":0}}, + "credentials":{"matched":1,"stubbed":0,"updated":5}, + "dataTables":{"matched":0,"created":0,"updated":0}, + "variables":{"matched":0,"created":0,"updated":0,"stubbed":0,"missing":0}, + "tags":{"matched":0,"created":0,"renamed":0,"reconciled":0,"skipped":0} + }, + "warnings":[] +}` + +const envBlockedResultBody = `{ + "environmentId":"` + testEnvironmentID + `", + "git":{"commitSha":"` + selectionSHA + `","branchName":"main"}, + "status":"blocked", + "preflight":{"missingProjects":[],"missingBindings":[],"accessRequirements":[],"conflicts":[],"warnings":[]} +}` + +const envPromoteResultBody = `{ + "environmentId":"` + testEnvironmentID + `", + "counts":{"workflows":2,"folders":1,"credentials":0,"dataTables":0,"variables":0,"tags":3}, + "git":{"commitSha":"deadbeef","branchName":"n8n/promotion-1"}, + "review":{"reviewId":"mr-1","number":42,"webUrl":"https://gitlab.example.com/org/repo/-/merge_requests/42"}, + "warnings":[{"message":"Branch protection blocks merging","linkUrl":"https://gitlab.example.com/help"},{"message":"No reviewers"}] +}` + +func envSource() PromotionExpectedSource { + return PromotionExpectedSource{EnvironmentID: testEnvironmentID, BranchName: "main", CommitSHA: selectionSHA} +} + +func TestPromotionEnvironmentSyncTransport(t *testing.T) { + yes := true + message := "sync" + path := PromotionEnvironmentsPath + "/" + testEnvironmentID + cases := []struct { + name, path, body, response string + call func(context.Context, *Client) (any, error) + }{ + {"apply without source", path + "/apply", `{}`, envAppliedResultBody, func(ctx context.Context, c *Client) (any, error) { + return c.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{}) + }}, + {"apply with source", path + "/apply", `{"expectedSource":` + envSourceJSON + `}`, envBlockedResultBody, func(ctx context.Context, c *Client) (any, error) { + source := envSource() + return c.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{ExpectedSource: &source}) + }}, + {"continue", path + "/apply/continue", `{"expectedSource":` + envSourceJSON + `,"confirmDestructiveChanges":true}`, envAppliedResultBody, func(ctx context.Context, c *Client) (any, error) { + return c.ContinueApplyPromotionEnvironment(ctx, testEnvironmentID, ContinueApplyPromotionEnvironmentRequest{ExpectedSource: envSource(), ConfirmDestructiveChanges: &yes}) + }}, + {"promote without message", path + "/promote", `{}`, envPromoteResultBody, func(ctx context.Context, c *Client) (any, error) { + return c.PromotePromotionEnvironment(ctx, testEnvironmentID, PromotePromotionEnvironmentRequest{}) + }}, + {"promote with message and force", path + "/promote", `{"commitMessage":"sync","force":true}`, envPromoteResultBody, func(ctx context.Context, c *Client) (any, error) { + return c.PromotePromotionEnvironment(ctx, testEnvironmentID, PromotePromotionEnvironmentRequest{CommitMessage: &message, Force: true}) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, tc.response)) + result, err := tc.call(context.Background(), server.client(t)) + if err != nil { + t.Fatal(err) + } + req, body := server.last(t) + if req.Method != http.MethodPost || req.URL.EscapedPath() != BasePath+tc.path { + t.Errorf("request = %s %s, want POST %s", req.Method, req.URL.EscapedPath(), BasePath+tc.path) + } + if body != tc.body { + t.Errorf("body = %s, want %s", body, tc.body) + } + encoded, err := json.Marshal(result) + if err != nil { + t.Fatal(err) + } + var got, want any + if err := json.Unmarshal(encoded, &got); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(tc.response), &want); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("response not preserved: %s", encoded) + } + for _, status := range []int{400, 403, 404, 409, 422, 503} { + s := newCommunityPackageServer(t, packageJSONHandler(status, `{"message":"failure"}`)) + if _, err := tc.call(context.Background(), s.client(t)); !IsStatus(err, status) { + t.Errorf("status %d: error = %v", status, err) + } + } + }) + } +} + +func TestPromotionEnvironmentSyncValidationBeforeTransport(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, envAppliedResultBody)) + client := server.client(t) + ctx := context.Background() + configSource := selectionSource() + both := envSource() + both.ConfigID = "cfg" + incomplete := envSource() + incomplete.CommitSHA = "abc" + blank := "" + long := strings.Repeat("m", maxPromotionCommitLength+1) + cases := []struct { + name, want string + call func() error + }{ + {"apply bad id", "must be a UUID", func() error { + _, err := client.ApplyPromotionEnvironment(ctx, "conn-1", ApplyPromotionEnvironmentRequest{}) + return err + }}, + {"apply config source", "configId, which only n8n 2.45", func() error { + _, err := client.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{ExpectedSource: &configSource}) + return err + }}, + {"apply both ids", "not both", func() error { + _, err := client.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{ExpectedSource: &both}) + return err + }}, + {"apply short commit", "full lowercase", func() error { + _, err := client.ApplyPromotionEnvironment(ctx, testEnvironmentID, ApplyPromotionEnvironmentRequest{ExpectedSource: &incomplete}) + return err + }}, + {"continue missing source", "--expected-environment-id", func() error { + _, err := client.ContinueApplyPromotionEnvironment(ctx, testEnvironmentID, ContinueApplyPromotionEnvironmentRequest{}) + return err + }}, + {"continue config source", "environmentId", func() error { + _, err := client.ContinueApplyPromotionEnvironment(ctx, testEnvironmentID, ContinueApplyPromotionEnvironmentRequest{ExpectedSource: configSource}) + return err + }}, + {"continue bad id", "whitespace", func() error { + _, err := client.ContinueApplyPromotionEnvironment(ctx, " "+testEnvironmentID, ContinueApplyPromotionEnvironmentRequest{ExpectedSource: envSource()}) + return err + }}, + {"promote blank message", "commit message is required", func() error { + _, err := client.PromotePromotionEnvironment(ctx, testEnvironmentID, PromotePromotionEnvironmentRequest{CommitMessage: &blank}) + return err + }}, + {"promote long message", "at most", func() error { + _, err := client.PromotePromotionEnvironment(ctx, testEnvironmentID, PromotePromotionEnvironmentRequest{CommitMessage: &long}) + return err + }}, + {"promote bad id", "must be a UUID", func() error { + _, err := client.PromotePromotionEnvironment(ctx, "env", PromotePromotionEnvironmentRequest{}) + return err + }}, + // Connection routes exist only before n8n 2.46, so an environment + // source can never be right there. + {"connection continue environment source", "n8n promotion environment apply-continue", func() error { + _, err := client.ContinueApplyPackage(ctx, "conn-1", ContinueApplyPromotionRequest{ExpectedSource: envSource()}) + return err + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := tc.call() + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("error = %v, want %q", err, tc.want) + } + if len(server.requests) != 0 { + t.Fatalf("%d request(s) reached the instance", len(server.requests)) + } + }) + } +} + +// Project routes are served by both generations, so either identifier passes +// through as given. +func TestPromotionProjectSelectionBothExpectedSources(t *testing.T) { + for _, tc := range []struct { + name string + source PromotionExpectedSource + json string + }{ + {"n8n 2.45 configId", selectionSource(), selectionSourceJSON}, + {"n8n 2.46 environmentId", envSource(), envSourceJSON}, + } { + t.Run(tc.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, envAppliedResultBody)) + client := server.client(t) + source := tc.source + if _, err := client.ApplyProjectSelection(context.Background(), "p1", ApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}, ExpectedSource: &source}); err != nil { + t.Fatal(err) + } + if _, body := server.last(t); body != `{"workflowIds":["wf"],"expectedSource":`+tc.json+`}` { + t.Errorf("apply body = %s", body) + } + if _, err := client.ContinueApplyProjectSelection(context.Background(), "p1", ContinueApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}, ExpectedSource: tc.source}); err != nil { + t.Fatal(err) + } + if _, body := server.last(t); body != `{"workflowIds":["wf"],"expectedSource":`+tc.json+`}` { + t.Errorf("continue body = %s", body) + } + }) + } + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, envAppliedResultBody)) + if _, err := server.client(t).ContinueApplyProjectSelection(context.Background(), "p1", ContinueApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}}); err == nil || + !strings.Contains(err.Error(), "--expected-environment-id") || !strings.Contains(err.Error(), "--expected-config-id") { + t.Errorf("missing source error = %v, want both flags named", err) + } + if len(server.requests) != 0 { + t.Error("request without a source reached the instance") + } +} + +func TestApplyPromotionResultBothShapes(t *testing.T) { + var applied ApplyPromotionResult + if err := json.Unmarshal([]byte(envAppliedResultBody), &applied); err != nil { + t.Fatal(err) + } + if applied.EnvironmentID != testEnvironmentID || applied.ConnectionID != "" || applied.ConfigID != "" || applied.Extra != nil { + t.Errorf("identifiers = %+v, want only environmentId and no extras", applied) + } + if applied.SourceID() != testEnvironmentID || !applied.Applied() { + t.Errorf("SourceID = %q applied = %v", applied.SourceID(), applied.Applied()) + } + c := applied.Counts + for name, got := range map[string]*int{"folders.updated": c.Folders.Updated, "folders.moved": c.Folders.Moved, "folders.renamed": c.Folders.Renamed, "workflows.moved": c.Workflows.Moved, "credentials.updated": c.Credentials.Updated} { + want := map[string]int{"folders.updated": 3, "folders.moved": 2, "folders.renamed": 1, "workflows.moved": 2, "credentials.updated": 5}[name] + if got == nil || *got != want { + t.Errorf("%s = %v, want %d", name, got, want) + } + } + + var blocked ApplyPromotionResult + if err := json.Unmarshal([]byte(envBlockedResultBody), &blocked); err != nil { + t.Fatal(err) + } + if source := blocked.ExpectedSource(); source != envSource() || source.ValidateEnvironment() != nil { + t.Errorf("ExpectedSource = %+v, want the environment source", source) + } + + // n8n 2.45: connectionId and configId, no new counts. + var old ApplyPromotionResult + if err := json.Unmarshal([]byte(promotionApplyResultBody), &old); err != nil { + t.Fatal(err) + } + if old.SourceID() != "conn-1" || old.ExpectedSource().ConfigID == "" || old.ExpectedSource().EnvironmentID != "" { + t.Errorf("old shape = %+v", old) + } + if old.Counts != nil && (old.Counts.Folders.Updated != nil || old.Counts.Folders.Moved != nil || old.Counts.Folders.Renamed != nil || old.Counts.Workflows.Moved != nil || old.Counts.Credentials.Updated != nil) { + t.Errorf("old shape invented 2.46 counts: %+v", *old.Counts) + } +} + +func TestPromotePromotionResultBothShapes(t *testing.T) { + var result PromotePromotionResult + if err := json.Unmarshal([]byte(envPromoteResultBody), &result); err != nil { + t.Fatal(err) + } + if result.SourceID() != testEnvironmentID || result.ConnectionID != "" || result.ConfigID != "" { + t.Errorf("identifiers = %+v", result) + } + if result.Review == nil || *result.Review != (PromotionReview{ReviewID: "mr-1", Number: 42, WebURL: "https://gitlab.example.com/org/repo/-/merge_requests/42"}) { + t.Errorf("review = %+v", result.Review) + } + if len(result.Warnings) != 2 || result.Warnings[0].LinkURL == "" || result.Warnings[1].Message != "No reviewers" || result.Warnings[1].LinkURL != "" { + t.Errorf("warnings = %+v", result.Warnings) + } + + var old PromotePromotionResult + if err := json.Unmarshal([]byte(promotionPromoteResultBody), &old); err != nil { + t.Fatal(err) + } + if old.SourceID() != "conn-1" || old.Review != nil || old.Warnings != nil { + t.Errorf("old shape = %+v", old) + } + encoded, err := json.Marshal(old) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "environmentId") || !strings.Contains(string(encoded), `"configId":"cfg-promote"`) { + t.Errorf("old shape re-encoded as %s, want the verbatim response", encoded) + } + // A constructed result names only the identifiers it has. + encoded, err = json.Marshal(PromotePromotionResult{EnvironmentID: "e"}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "connectionId") || strings.Contains(string(encoded), "configId") || strings.Contains(string(encoded), "review") { + t.Errorf("constructed result = %s", encoded) + } +} + +func TestPromotionChangesEnvironmentSource(t *testing.T) { + body := strings.Replace(selectionChangesJSON, `"configId":"cfg"`, `"environmentId":"`+testEnvironmentID+`"`, 1) + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + changes, err := server.client(t).GetPromotionChanges(context.Background(), "p1", PromotionDirectionApply, PromotionChangesOptions{}) + if err != nil { + t.Fatal(err) + } + if changes.Source.EnvironmentID != testEnvironmentID || changes.Source.ConfigID != "" || changes.Source.BranchName != "main" { + t.Errorf("source = %+v", changes.Source) + } +} diff --git a/internal/n8n/promotion_selection.go b/internal/n8n/promotion_selection.go index fe2c6bf..8637fde 100644 --- a/internal/n8n/promotion_selection.go +++ b/internal/n8n/promotion_selection.go @@ -120,10 +120,13 @@ type PromotionChange struct { DependencyCount int `json:"dependencyCount"` } -// PromotionChangeSource identifies the configuration and branch used for a preview. +// PromotionChangeSource identifies the environment (n8n 2.46 and later) or +// configuration (2.45 and earlier) and the branch used for a preview. Exactly +// one identifier is set, matching the instance generation. type PromotionChangeSource struct { - ConfigID string `json:"configId"` - BranchName string `json:"branchName"` + ConfigID string `json:"configId,omitempty"` + EnvironmentID string `json:"environmentId,omitempty"` + BranchName string `json:"branchName"` } // PromotionChanges preserves the reviewed source and the complete server response. @@ -192,8 +195,9 @@ type ContinueApplyPromotionRequest struct { ConfirmDestructiveChanges *bool `json:"confirmDestructiveChanges,omitempty"` } -// Validate requires a complete reviewed source. -func (r ContinueApplyPromotionRequest) Validate() error { return r.ExpectedSource.Validate() } +// Validate requires a complete reviewed source. Connection routes exist only +// before n8n 2.46, so the source must name configId. +func (r ContinueApplyPromotionRequest) Validate() error { return r.ExpectedSource.ValidateConfig() } // ApplyProjectSelectionRequest applies only selected workflow changes. type ApplyProjectSelectionRequest struct { diff --git a/test/integration/promotion_selection_test.go b/test/integration/promotion_selection_test.go index f432d3f..b4abee9 100644 --- a/test/integration/promotion_selection_test.go +++ b/test/integration/promotion_selection_test.go @@ -60,7 +60,8 @@ func TestPromotionRepositoryDiscovery(t *testing.T) { runPromotionSelectionReadCLI(t, instance, []string{"promotion", "provider", "branches", providerID, repository.FullPath, "--limit", "10"}) } -// The supplied project must already have a resolved, cloned promotion connection. +// The supplied project must already have a resolved, connected promotion +// environment (n8n 2.46 and later) or cloned connection (older). // These tests never clone or apply/promote content on the shared instance. func TestPromotionProjectChanges(t *testing.T) { instance := integration.Require(t) @@ -76,8 +77,9 @@ func TestPromotionProjectChanges(t *testing.T) { if err != nil { t.Fatal(err) } - if changes.Source.ConfigID == "" { - t.Error("changes lack source configId") + // n8n 2.46 and later name the environment; older instances the config. + if (changes.Source.EnvironmentID == "") == (changes.Source.ConfigID == "") { + t.Errorf("changes source = %+v, want exactly one of environmentId or configId", changes.Source) } for _, change := range changes.Changes { if change.ID == "" || change.Type != "workflow" {