diff --git a/docs/README.md b/docs/README.md index 1c3a32c..e58dab6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -126,6 +126,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n project user role`](n8n_project_user_role.md) | Manage members' project roles | | [`n8n project user`](n8n_project_user.md) | Manage project members | | [`n8n project`](n8n_project.md) | Manage projects and their members | +| [`n8n promotion apply-continue`](n8n_promotion_apply-continue.md) | Continue a reviewed connection apply after binding setup | | [`n8n promotion apply`](n8n_promotion_apply.md) | Apply the Git remote into this instance | | [`n8n promotion checkout clone`](n8n_promotion_checkout_clone.md) | Clone one promotion checkout locally | | [`n8n promotion checkout disconnect`](n8n_promotion_checkout_disconnect.md) | Remove one promotion checkout | @@ -143,14 +144,20 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`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 project add`](n8n_promotion_project_add.md) | Add a project to a promotion connection | +| [`n8n promotion project apply-continue`](n8n_promotion_project_apply-continue.md) | Continue a reviewed project apply after binding setup | +| [`n8n promotion project apply`](n8n_promotion_project_apply.md) | Apply selected workflow changes from a project's branch | +| [`n8n promotion project changes`](n8n_promotion_project_changes.md) | List workflow changes for a project's promotion branch | | [`n8n promotion project list`](n8n_promotion_project_list.md) | List projects linked to a promotion connection | +| [`n8n promotion project promote`](n8n_promotion_project_promote.md) | Promote selected project workflows to the remote branch | | [`n8n promotion project remove`](n8n_promotion_project_remove.md) | Remove a project from a promotion connection | | [`n8n promotion project`](n8n_promotion_project.md) | Manage projects linked to a promotion connection | | [`n8n promotion promote`](n8n_promotion_promote.md) | Promote team projects to the Git remote | +| [`n8n promotion provider branches`](n8n_promotion_provider_branches.md) | List branches of a GitLab repository | | [`n8n promotion provider create`](n8n_promotion_provider_create.md) | Create a promotion provider | | [`n8n promotion provider delete`](n8n_promotion_provider_delete.md) | Permanently delete a promotion provider | | [`n8n promotion provider get`](n8n_promotion_provider_get.md) | Show one promotion provider | | [`n8n promotion provider list`](n8n_promotion_provider_list.md) | List promotion providers | +| [`n8n promotion provider repositories`](n8n_promotion_provider_repositories.md) | List repositories available to a GitLab provider | | [`n8n promotion provider update`](n8n_promotion_provider_update.md) | Update a promotion provider | | [`n8n promotion provider`](n8n_promotion_provider.md) | Manage promotion providers | | [`n8n promotion`](n8n_promotion.md) | Manage promotion providers, connections, and apply/promote sync | diff --git a/docs/n8n_promotion.md b/docs/n8n_promotion.md index 705e9a0..c74d3ea 100644 --- a/docs/n8n_promotion.md +++ b/docs/n8n_promotion.md @@ -4,13 +4,15 @@ Manage promotion providers, connections, and apply/promote sync ### Synopsis -Manage the upstream-only Promotions generation of Git sync. +Manage Promotions Git sync and selected project workflows. Start with 'provider list' to find a provider, then 'connection list' to find a connection. Create a provider first, then a connection on it, then a config per direction under 'config', clone each checkout under 'checkout', link team projects to a projects-scope connection under 'project', then 'promote' the instance to the remote or 'apply' -the remote into the instance. +the remote into the instance. For selected workflows, start with +project changes, then project apply or project promote. Use apply-continue +after resolving a blocked apply. 'promote' and 'apply' run on the instance connection. 'promote' commits and pushes every team project to the remote; 'apply' checks the @@ -50,6 +52,7 @@ n8n promotion [flags] * [n8n](n8n.md) - Command-line client for the n8n API * [n8n promotion apply](n8n_promotion_apply.md) - Apply the Git remote into this instance +* [n8n promotion apply-continue](n8n_promotion_apply-continue.md) - Continue a reviewed connection apply after binding setup * [n8n promotion checkout](n8n_promotion_checkout.md) - Manage promotion checkouts * [n8n promotion config](n8n_promotion_config.md) - Manage promotion direction configs * [n8n promotion connection](n8n_promotion_connection.md) - Manage promotion connections diff --git a/docs/n8n_promotion_apply-continue.md b/docs/n8n_promotion_apply-continue.md new file mode 100644 index 0000000..bd3cf0c --- /dev/null +++ b/docs/n8n_promotion_apply-continue.md @@ -0,0 +1,61 @@ +## n8n promotion apply-continue + +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, +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. +--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. + +``` +n8n promotion apply-continue [flags] +``` + +### Examples + +``` + n8n promotion apply-continue CONNECTION_ID --expected-from blocked.json + n8n promotion apply-continue CONNECTION_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 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 + --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](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync + diff --git a/docs/n8n_promotion_project.md b/docs/n8n_promotion_project.md index 8daa561..21c34cb 100644 --- a/docs/n8n_promotion_project.md +++ b/docs/n8n_promotion_project.md @@ -14,7 +14,10 @@ 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. +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. ``` n8n promotion project [flags] @@ -38,6 +41,10 @@ n8n promotion project [flags] * [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync * [n8n promotion project add](n8n_promotion_project_add.md) - Add a project to a promotion connection +* [n8n promotion project apply](n8n_promotion_project_apply.md) - Apply selected workflow changes from a project's branch +* [n8n promotion project apply-continue](n8n_promotion_project_apply-continue.md) - Continue a reviewed project apply after binding setup +* [n8n promotion project changes](n8n_promotion_project_changes.md) - List workflow changes for a project's promotion branch * [n8n promotion project list](n8n_promotion_project_list.md) - List projects linked to a promotion connection +* [n8n promotion project promote](n8n_promotion_project_promote.md) - Promote selected project workflows to the remote branch * [n8n promotion project remove](n8n_promotion_project_remove.md) - Remove a project from a promotion connection diff --git a/docs/n8n_promotion_project_apply-continue.md b/docs/n8n_promotion_project_apply-continue.md new file mode 100644 index 0000000..0c4c7c7 --- /dev/null +++ b/docs/n8n_promotion_project_apply-continue.md @@ -0,0 +1,65 @@ +## n8n promotion project apply-continue + +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. +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. +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. +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. + +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 +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. + +``` +n8n promotion project apply-continue [flags] +``` + +### Examples + +``` + n8n promotion project apply-continue PROJECT_ID --workflow-id WORKFLOW_ID --expected-from blocked.json + n8n promotion project apply-continue PROJECT_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 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 + --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 + +* [n8n promotion project](n8n_promotion_project.md) - Manage projects linked to a promotion connection + diff --git a/docs/n8n_promotion_project_apply.md b/docs/n8n_promotion_project_apply.md new file mode 100644 index 0000000..4d6c317 --- /dev/null +++ b/docs/n8n_promotion_project_apply.md @@ -0,0 +1,58 @@ +## n8n promotion project apply + +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. +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 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. + +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 +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. + +``` +n8n promotion project apply [flags] +``` + +### Examples + +``` + n8n promotion project apply PROJECT_ID --workflow-id WORKFLOW_ID + n8n promotion project apply PROJECT_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 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 + --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 + +* [n8n promotion project](n8n_promotion_project.md) - Manage projects linked to a promotion connection + diff --git a/docs/n8n_promotion_project_changes.md b/docs/n8n_promotion_project_changes.md new file mode 100644 index 0000000..03c2e46 --- /dev/null +++ b/docs/n8n_promotion_project_changes.md @@ -0,0 +1,42 @@ +## n8n promotion project changes + +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. + +``` +n8n promotion project changes [flags] +``` + +### Examples + +``` + n8n promotion project changes PROJECT_ID apply --output json > changes.json + n8n promotion project changes PROJECT_ID promote --sort updatedAt --order desc +``` + +### Options + +``` + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for changes + --order string sort order: asc or desc (default: asc) (default "asc") + --output string output format: text or json (default: text; JSON includes the reviewed source) (default "text") + --search string workflow name search string (default: no filter) + --sort string sort field: name, updatedAt, or status (default: name) (default "name") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion project](n8n_promotion_project.md) - Manage projects linked to a promotion connection + diff --git a/docs/n8n_promotion_project_promote.md b/docs/n8n_promotion_project_promote.md new file mode 100644 index 0000000..2fb5c76 --- /dev/null +++ b/docs/n8n_promotion_project_promote.md @@ -0,0 +1,49 @@ +## n8n promotion project promote + +Promote selected project workflows to the remote branch + +### Synopsis + +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. + +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 +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. + +``` +n8n promotion project promote [flags] +``` + +### Examples + +``` + n8n promotion project promote PROJECT_ID --workflow-id WORKFLOW_ID + n8n promotion project promote PROJECT_ID --input request.json --yes --output json +``` + +### Options + +``` + --commit-message string commit message, 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') + -h, --help help for promote + --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 + +* [n8n promotion project](n8n_promotion_project.md) - Manage projects linked to a promotion connection + diff --git a/docs/n8n_promotion_provider.md b/docs/n8n_promotion_provider.md index a62a812..401390a 100644 --- a/docs/n8n_promotion_provider.md +++ b/docs/n8n_promotion_provider.md @@ -7,7 +7,8 @@ Manage promotion providers 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. +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 @@ -35,9 +36,11 @@ n8n promotion provider [flags] ### SEE ALSO * [n8n promotion](n8n_promotion.md) - Manage promotion providers, connections, and apply/promote sync +* [n8n promotion provider branches](n8n_promotion_provider_branches.md) - List branches of a GitLab repository * [n8n promotion provider create](n8n_promotion_provider_create.md) - Create a promotion provider * [n8n promotion provider delete](n8n_promotion_provider_delete.md) - Permanently delete a promotion provider * [n8n promotion provider get](n8n_promotion_provider_get.md) - Show one promotion provider * [n8n promotion provider list](n8n_promotion_provider_list.md) - List promotion providers +* [n8n promotion provider repositories](n8n_promotion_provider_repositories.md) - List repositories available to a GitLab provider * [n8n promotion provider update](n8n_promotion_provider_update.md) - Update a promotion provider diff --git a/docs/n8n_promotion_provider_branches.md b/docs/n8n_promotion_provider_branches.md new file mode 100644 index 0000000..aba291b --- /dev/null +++ b/docs/n8n_promotion_provider_branches.md @@ -0,0 +1,50 @@ +## n8n promotion provider branches + +List branches of a GitLab repository + +### Synopsis + +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 +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. + +With --all, JSON output adds a collection object. Its truncated field is true, +and a warning goes to stderr, when the walk stopped at the 10,000-item limit +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n promotion provider branches [flags] +``` + +### Examples + +``` + n8n promotion provider repositories PROVIDER_ID --search automation --all + n8n promotion provider branches PROVIDER_ID org/repo --output json +``` + +### Options + +``` + --all follow all cursors, including short pages (default: one page; maximum 10,000 items) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string cursor from a previous page (default: first page) + -h, --help help for branches + --limit int items per API page, 1 to 250 (default: server default of 100; GitLab returns at most 100) + --output string output format: text or json (default: text; JSON includes data and nextCursor) (default "text") + --search string repository or branch search string, at most 255 characters (default: no filter) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion provider](n8n_promotion_provider.md) - Manage promotion providers + diff --git a/docs/n8n_promotion_provider_repositories.md b/docs/n8n_promotion_provider_repositories.md new file mode 100644 index 0000000..240aaa9 --- /dev/null +++ b/docs/n8n_promotion_provider_repositories.md @@ -0,0 +1,50 @@ +## n8n promotion provider repositories + +List repositories available to a GitLab provider + +### Synopsis + +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 +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. + +With --all, JSON output adds a collection object. Its truncated field is true, +and a warning goes to stderr, when the walk stopped at the 10,000-item limit +without reaching the end. nextCursor then resumes the walk when the limit fell +between pages; it stays empty when the limit fell inside a page, because +resuming from the next page would skip items: narrow the filters or page +explicitly with --limit and --cursor instead. + +``` +n8n promotion provider repositories [flags] +``` + +### Examples + +``` + n8n promotion provider repositories PROVIDER_ID --search automation --all + n8n promotion provider branches PROVIDER_ID org/repo --output json +``` + +### Options + +``` + --all follow all cursors, including short pages (default: one page; maximum 10,000 items) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --cursor string cursor from a previous page (default: first page) + -h, --help help for repositories + --limit int items per API page, 1 to 250 (default: server default of 100; GitLab returns at most 100) + --output string output format: text or json (default: text; JSON includes data and nextCursor) (default "text") + --search string repository or branch search string, at most 255 characters (default: no filter) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) +``` + +### SEE ALSO + +* [n8n promotion provider](n8n_promotion_provider.md) - Manage promotion providers + diff --git a/internal/cli/help_test.go b/internal/cli/help_test.go index 1f10553..40013f7 100644 --- a/internal/cli/help_test.go +++ b/internal/cli/help_test.go @@ -234,6 +234,13 @@ func TestHelpSucceedsAtEveryLevel(t *testing.T) { {"git-connection", "push"}, {"git-connection", "pull"}, {"promotion"}, + {"promotion", "apply-continue"}, + {"promotion", "provider", "repositories"}, + {"promotion", "provider", "branches"}, + {"promotion", "project", "changes"}, + {"promotion", "project", "apply"}, + {"promotion", "project", "apply-continue"}, + {"promotion", "project", "promote"}, {"promotion", "provider"}, {"promotion", "provider", "list"}, {"promotion", "provider", "create"}, diff --git a/internal/cli/promotion.go b/internal/cli/promotion.go index 5be8747..a6e4fac 100644 --- a/internal/cli/promotion.go +++ b/internal/cli/promotion.go @@ -29,13 +29,15 @@ func newPromotionCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "promotion", Short: "Manage promotion providers, connections, and apply/promote sync", - Long: "Manage the upstream-only Promotions generation of Git sync.\n" + + Long: "Manage Promotions Git sync and selected project workflows.\n" + "Start with 'provider list' to find a provider, then 'connection list'\n" + "to find a connection. Create a provider first, then a connection on\n" + "it, then a config per direction under 'config', clone each checkout\n" + "under 'checkout', link team projects to a projects-scope connection\n" + "under 'project', then 'promote' the instance to the remote or 'apply'\n" + - "the remote into the instance.\n\n" + + "the remote into the instance. For selected workflows, start with\n" + + "project 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" + @@ -65,6 +67,7 @@ func newPromotionCommand(opts Options) *cobra.Command { newPromotionProjectCommand(opts), newPromotionPromoteCommand(opts), newPromotionApplyCommand(opts), + newPromotionSelectionCommand(opts, "apply-continue", false), ) return cmd } @@ -78,7 +81,8 @@ func newPromotionProviderCommand(opts Options) *cobra.Command { 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.\n\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.", @@ -95,6 +99,8 @@ func newPromotionProviderCommand(opts Options) *cobra.Command { newPromotionProviderGetCommand(opts), newPromotionProviderUpdateCommand(opts), newPromotionProviderDeleteCommand(opts), + newPromotionDiscoveryCommand(opts, false), + newPromotionDiscoveryCommand(opts, true), ) return cmd } @@ -1280,7 +1286,10 @@ 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.", + "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.", 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", @@ -1291,6 +1300,10 @@ func newPromotionProjectCommand(opts Options) *cobra.Command { newPromotionProjectListCommand(opts), newPromotionProjectAddCommand(opts), newPromotionProjectRemoveCommand(opts), + newPromotionProjectChangesCommand(opts), + newPromotionSelectionCommand(opts, "apply", true), + newPromotionSelectionCommand(opts, "apply-continue", true), + newPromotionSelectionCommand(opts, "promote", true), ) return cmd } @@ -1634,16 +1647,21 @@ func runPromotionApply(ctx context.Context, opts Options, id string, f promotion // transport and validation errors. type promotionApplyStoppedError struct { connectionID, status string + project bool } func (e *promotionApplyStoppedError) Error() string { + target := "connection" + if e.project { + target = "project" + } switch e.status { case n8n.PromotionApplyStatusBlocked: - return fmt.Sprintf("promotion apply of connection %s was blocked at preflight; nothing was applied", e.connectionID) + return fmt.Sprintf("promotion apply of %s %s was blocked at preflight; nothing was applied", target, e.connectionID) case n8n.PromotionApplyStatusSourceChanged: - return fmt.Sprintf("promotion apply of connection %s stopped because the source branch moved; nothing was applied", e.connectionID) + return fmt.Sprintf("promotion apply of %s %s stopped because the source branch moved; nothing was applied", target, e.connectionID) default: - return fmt.Sprintf("promotion apply of connection %s answered unknown status %q; check the instance before assuming anything was applied", 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.connectionID, e.status) } } @@ -1661,6 +1679,14 @@ 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) +} + +func finishPromotionApplyTarget(opts Options, id string, result *n8n.ApplyPromotionResult, project bool) error { + prefix := "n8n promotion " + if project { + prefix += "project " + } if result.Applied() { return nil } @@ -1671,14 +1697,17 @@ func finishPromotionApply(opts Options, id string, result *n8n.ApplyPromotionRes 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 continue the apply with expected source configId=%s branchName=%s commitSha=%s (an 'apply-continue' command is upcoming in this CLI).\n", - emptyDash(source.ConfigID), emptyDash(source.BranchName), emptyDash(source.CommitSHA)) + 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)) + if project { + fmt.Fprintln(opts.Streams.Err, "Resend the same full selection with repeated --workflow-id flags or --input.") + } case n8n.PromotionApplyStatusSourceChanged: - fmt.Fprintf(opts.Streams.Err, "Nothing was applied: the branch moved since it was reviewed. Review the branch again, then re-run 'n8n promotion apply %s'.\n", id) + fmt.Fprintf(opts.Streams.Err, "Nothing was applied: the branch moved since it was reviewed. Review the branch again, then re-run '%sapply %s'.\n", prefix, id) 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} + return &promotionApplyStoppedError{connectionID: id, status: result.Status, project: project} } func promotionNeedsConfirmation(preflight *n8n.PromotionApplyPreflight) bool { @@ -2152,9 +2181,9 @@ func promotionScope(action string) string { return "gitConnection:clone" case "project add", "project remove": return "gitConnection:manageProjects" - case "promote": + case "promote", "project promote", "project changes promote": return "gitConnection:push" - case "apply": + case "apply", "apply-continue", "project apply", "project apply-continue", "project changes apply": return "gitConnection:pull" case "provider repositories", "provider branches": return "gitConnection:discover" diff --git a/internal/cli/promotion_selection.go b/internal/cli/promotion_selection.go new file mode 100644 index 0000000..8e3b092 --- /dev/null +++ b/internal/cli/promotion_selection.go @@ -0,0 +1,475 @@ +package cli + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "text/tabwriter" + "unicode/utf8" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/spf13/cobra" +) + +func newPromotionDiscoveryCommand(opts Options, branches bool) *cobra.Command { + var f promotionProviderListFlags + var search string + name, use, short := "repositories", "repositories ", "List repositories available to a GitLab provider" + if branches { + name, use, short = "branches", "branches ", "List branches of a GitLab repository" + } + cmd := &cobra.Command{ + Use: use, Short: short, + 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" + + "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, + Example: " n8n promotion provider repositories PROVIDER_ID --search automation --all\n" + + " n8n promotion provider branches PROVIDER_ID org/repo --output json", + Args: cobra.ExactArgs(1), + } + if branches { + cmd.Args = cobra.ExactArgs(2) + } + f.instance.register(cmd) + cmd.Flags().IntVar(&f.limit, "limit", 0, "items per API page, 1 to 250 (default: server default of 100; GitLab returns at most 100)") + cmd.Flags().StringVar(&f.cursor, "cursor", "", "cursor from a previous page (default: first page)") + cmd.Flags().BoolVar(&f.all, "all", false, "follow all cursors, including short pages (default: one page; maximum 10,000 items)") + cmd.Flags().StringVar(&search, "search", "", "repository or branch search string, at most 255 characters (default: no filter)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (default: text; JSON includes data and nextCursor)") + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if err := validateOutput(f.output); err != nil { + return err + } + list := n8n.PromotionDiscoveryOptions{ListOptions: n8n.ListOptions{Limit: f.limit, Cursor: f.cursor}, Search: search} + if err := list.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + subject := promotionProviderSubject(args[0]) + if branches { + subject.what += fmt.Sprintf(" or repository %q", args[1]) + subject.find += " and 'n8n promotion provider repositories'" + fetch := func(ctx context.Context, page n8n.ListOptions) (n8n.Page[n8n.PromotionRepositoryBranch], error) { + list.ListOptions = page + return client.ListPromotionProviderRepositoryBranches(ctx, args[0], args[1], list) + } + return runPromotionDiscovery(cmd.Context(), opts, resolution, f, name, subject, fetch, "NAME\tDEFAULT", func(row n8n.PromotionRepositoryBranch) string { return fmt.Sprintf("%s\t%t", row.Name, row.IsDefault) }) + } + fetch := func(ctx context.Context, page n8n.ListOptions) (n8n.Page[n8n.PromotionRepository], error) { + list.ListOptions = page + return client.ListPromotionProviderRepositories(ctx, args[0], list) + } + return runPromotionDiscovery(cmd.Context(), opts, resolution, f, name, subject, fetch, "ID\tNAME\tPATH\tREMOTE URL\tDEFAULT BRANCH", func(row n8n.PromotionRepository) string { + branch := "-" + if row.DefaultBranch != nil { + branch = *row.DefaultBranch + } + return fmt.Sprintf("%s\t%s\t%s\t%s\t%s", row.ID, row.Name, row.FullPath, row.RemoteURL, branch) + }) + } + return cmd +} + +func runPromotionDiscovery[T any](ctx context.Context, opts Options, resolution config.Resolution, f promotionProviderListFlags, name string, subject promotionSubject, fetch n8n.PageFunc[T], header string, rowText func(T) string) error { + var page n8n.Page[T] + var collection *listCollection + var err error + list := n8n.ListOptions{Limit: f.limit, Cursor: f.cursor} + if f.all { + var collected n8n.Collection[T] + collected, err = n8n.CollectPromotionDiscovery(ctx, fetch, list) + page = n8n.Page[T]{Data: collected.Data, NextCursor: collected.NextCursor} + collection = cursorCollection(collected.Truncated, collected.NextCursor, n8n.DefaultCollectLimit) + } else { + page, err = fetch(ctx, list) + } + if err != nil { + return promotionAPIError(err, resolution, "provider "+name, subject) + } + if len(page.Data) == 0 { + fmt.Fprintf(opts.Streams.Err, "No %s found; check the search filter and provider access.\n", name) + } + if f.output == outputJSON { + err = writePageJSON(opts.Streams.Out, page, collection) + } else { + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, header) + for _, row := range page.Data { + fmt.Fprintln(tw, rowText(row)) + } + err = tw.Flush() + if page.NextCursor != "" { + fmt.Fprintf(opts.Streams.Err, "More %s available: use --cursor %q or --all.\n", name, page.NextCursor) + } + } + return finishCollection(opts.Streams.Err, collection, err) +} + +func newPromotionProjectChangesCommand(opts Options) *cobra.Command { + var instance instanceFlags + var output string + var query n8n.PromotionChangesOptions + 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.", + 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), + RunE: func(cmd *cobra.Command, args []string) error { + if err := validateOutput(output); err != nil { + return err + } + if err := query.Validate(); err != nil { + return err + } + client, resolution, err := opts.apiClient(instance) + if err != nil { + return err + } + result, err := client.GetPromotionChanges(cmd.Context(), args[0], args[1], query) + if err != nil { + return promotionAPIError(err, resolution, "project changes "+args[1], promotionProjectSubject(args[0])) + } + if len(result.Changes) == 0 { + fmt.Fprintln(opts.Streams.Err, "No workflow changes found; check the search filter or review the other direction.") + } + if output == outputJSON { + return writeJSON(opts.Streams.Out, result) + } + tw := tabwriter.NewWriter(opts.Streams.Out, 0, 0, 2, ' ', 0) + commit := "-" + 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) + 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) + } + return tw.Flush() + }, + } + instance.register(cmd) + cmd.Flags().StringVar(&query.Search, "search", "", "workflow name search string (default: no filter)") + cmd.Flags().StringVar(&query.Sort, "sort", "name", "sort field: name, updatedAt, or status (default: name)") + cmd.Flags().StringVar(&query.Order, "order", "asc", "sort order: asc or desc (default: asc)") + cmd.Flags().StringVar(&output, "output", outputText, "output format: text or json (default: text; JSON includes the reviewed source)") + return cmd +} + +type promotionSelectionFlags struct { + instance instanceFlags + input, output, expectedFrom string + workflowIDs []string + source n8n.PromotionExpectedSource + commit string + yes, destructive bool +} + +// Separate commands keep the required source and selection explicit at continue time. +func newPromotionSelectionCommand(opts Options, action string, project bool) *cobra.Command { + var f promotionSelectionFlags + target, prefix := "project", "n8n promotion project " + if !project { + target, prefix = "connection", "n8n promotion " + } + isContinue := action == "apply-continue" + isPromote := action == "promote" + short := "Apply selected workflow changes from a project's branch" + if isContinue { + short = "Continue a reviewed " + target + " apply after binding setup" + } + if isPromote { + 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 { + 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" + + "folders, credentials, tables, variables, and tags can change or be removed.\n" + + "Requires gitConnection:pull and the same permissions as the initial apply.\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" + } else { + 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" + if isContinue { + long += "Expected source is required; use the blocked result's configId and git.\n" + + "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" + } + long += "--confirm-destructive-changes permits removal or retyping of data-table\n" + + "columns and loss of their values; rows and other columns remain.\n" + if !project { + long += "It also permits deleting team projects with everything in them.\n" + } + long += "This covers every such change at continue time, including changes absent\nfrom the reviewed result.\n" + } else { + long += "Expected source is optional; supply it to detect changes after review.\n" + } + long += "Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 other error. Only\n" + + "applied writes content. Resolve blocked bindings before apply-continue;\n" + + "review source-changed results again. JSON prints the full status result;\n" + + "text shows preflight details or counts and warnings. Hints go to stderr.\n" + } + if project { + long += "\nPass repeated --workflow-id flags, or use a strict JSON request.\n" + } + long += "Read request JSON with --input FILE|- (maximum 1 MiB). Input and document flags are\n" + + "mutually exclusive. Interactive runs ask for confirmation; non-interactive\n" + + "runs and stdin input require --yes. JSON returns the server result; text\n" + + "shows counts and the commit after success." + example := " " + prefix + action + " " + strings.ToUpper(target) + "_ID" + flags := "" + if project { + flags += " --workflow-id WORKFLOW_ID" + } + if isContinue { + flags += " --expected-from blocked.json" + } + cmd := &cobra.Command{Use: action + " <" + target + "-id>", Short: short, Long: long, + Example: example + flags + "\n" + example + " --input request.json --yes --output json", Args: cobra.ExactArgs(1)} + f.instance.register(cmd) + cmd.Flags().StringVar(&f.input, "input", "", "request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (default: text; JSON is the full server result)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm content changes without prompting (default: prompt; required for non-interactive or stdin input)") + documentFlags := []string{} + if project { + cmd.Flags().StringArrayVar(&f.workflowIDs, "workflow-id", nil, "selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used)") + documentFlags = append(documentFlags, "workflow-id") + } + if isPromote { + cmd.Flags().StringVar(&f.commit, "commit-message", "", "commit message, 1 to 1000 characters (default: server-generated message)") + 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") + } + 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)") + documentFlags = append(documentFlags, "confirm-destructive-changes") + } + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if err := validateOutput(f.output); err != nil { + return err + } + 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") { + for _, name := range documentFlags { + if cmd.Flags().Changed(name) { + return fmt.Errorf("--input and document flags are mutually exclusive") + } + } + if f.input == "" { + return fmt.Errorf("--input requires a file path or -") + } + } + if (f.input == "-" || f.expectedFrom == "-") && !f.yes { + return fmt.Errorf("stdin input requires --yes because stdin cannot answer confirmation") + } + 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-from") { + if explicit { + return fmt.Errorf("--expected-from and explicit expected-source flags are mutually exclusive") + } + var err error + source, err = readPromotionExpectedSource(opts, f.expectedFrom) + if err != nil { + return err + } + } else if explicit { + source = &f.source + } + } + var destructive *bool + if cmd.Flags().Changed("confirm-destructive-changes") { + destructive = &f.destructive + } + var request interface{ Validate() error } + switch { + case isPromote: + r := &n8n.PromoteProjectSelectionRequest{WorkflowIDs: f.workflowIDs} + if cmd.Flags().Changed("commit-message") { + r.CommitMessage = &f.commit + } + request = r + case isContinue && project: + r := &n8n.ContinueApplyProjectSelectionRequest{WorkflowIDs: f.workflowIDs, 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 + default: + request = &n8n.ApplyProjectSelectionRequest{WorkflowIDs: f.workflowIDs, ExpectedSource: source} + } + if f.input != "" { + if err := readPromotionDocument(opts, f.input, request); err != nil { + return err + } + } + if err := request.Validate(); err != nil { + return err + } + return runPromotionSelection(cmd.Context(), opts, args[0], f, request) + } + return cmd +} + +func readPromotionExpectedSource(opts Options, path string) (*n8n.PromotionExpectedSource, error) { + var fields map[string]json.RawMessage + if err := readPromotionDocument(opts, path, &fields); err != nil { + return nil, err + } + var result n8n.PromotionExpectedSource + // Decode only source fields. Other response fields remain forward-compatible. + decode := func(raw json.RawMessage, dst any) error { + if len(raw) == 0 || string(raw) == "null" { + return fmt.Errorf("reviewed source field is missing or null") + } + return json.Unmarshal(raw, dst) + } + 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 := decode(fields["commitSha"], &result.CommitSHA); err != nil { + return nil, fmt.Errorf("commitSha: %w", err) + } + } else { + var status string + 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) + } + var git map[string]json.RawMessage + if err := decode(fields["git"], &git); err != nil { + return nil, err + } + for key, dst := range map[string]*string{"branchName": &result.BranchName, "commitSha": &result.CommitSHA} { + if err := decode(git[key], dst); err != nil { + return nil, fmt.Errorf("git.%s: %w", key, err) + } + } + } + if err := result.Validate(); err != nil { + return nil, err + } + return &result, nil +} + +func runPromotionSelection(ctx context.Context, opts Options, id string, f promotionSelectionFlags, request interface{ Validate() error }) error { + client, resolution, err := opts.apiClient(f.instance) + if err != nil { + return err + } + subject := promotionProjectSubject(id) + 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) + switch r := request.(type) { + case *n8n.PromoteProjectSelectionRequest: + action = "project promote" + question = fmt.Sprintf("Promote selected workflows of project %q on %s? The remote branch is committed and pushed; selected workflows no longer owned by this project leave the branch.", id, resolution.URL) + case *n8n.ContinueApplyProjectSelectionRequest: + action = "project apply-continue" + if r.ConfirmDestructiveChanges != nil && *r.ConfirmDestructiveChanges { + 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) + 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." + } + } + if err := opts.confirmer(f.yes).Confirm(question); err != nil { + return err + } + var result *n8n.ApplyPromotionResult + switch r := request.(type) { + case *n8n.PromoteProjectSelectionRequest: + promoted, err := client.PromoteProjectSelection(ctx, id, *r) + if err != nil { + return promotionAPIError(err, resolution, action, subject) + } + if f.output == outputJSON { + return writeJSON(opts.Streams.Out, promoted) + } + return writePromotionPromoteResult(opts, resolution, promoted) + case *n8n.ApplyProjectSelectionRequest: + result, err = client.ApplyProjectSelection(ctx, id, *r) + case *n8n.ContinueApplyProjectSelectionRequest: + result, err = client.ContinueApplyProjectSelection(ctx, id, *r) + case *n8n.ContinueApplyPromotionRequest: + result, err = client.ContinueApplyPackage(ctx, id, *r) + } + if err != nil { + return promotionAPIError(err, resolution, action, subject) + } + if f.output == outputJSON { + err = writeJSON(opts.Streams.Out, result) + } else { + err = writePromotionApplyResult(opts, resolution, result) + } + if err != nil { + return err + } + return finishPromotionApplyTarget(opts, id, result, strings.HasPrefix(action, "project ")) +} + +func promotionProjectSubject(id string) promotionSubject { + return promotionSubject{what: fmt.Sprintf("project %q", id), find: "'n8n project list'"} +} diff --git a/internal/cli/promotion_selection_test.go b/internal/cli/promotion_selection_test.go new file mode 100644 index 0000000..cb38d05 --- /dev/null +++ b/internal/cli/promotion_selection_test.go @@ -0,0 +1,320 @@ +package cli + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +const cliSelectionSHA = "0123456789012345678901234567890123456789" +const cliSelectionSource = `{"configId":"cfg","branchName":"main","commitSha":"` + cliSelectionSHA + `"}` +const cliSelectionChanges = `{"commitSha":"` + cliSelectionSHA + `","source":{"configId":"cfg","branchName":"main"},"changes":[{"id":"w","name":"Flow","type":"workflow","status":"deleted","version":null,"updatedAt":null,"updatedBy":null,"dependencyCount":1}],"future":true}` + +func selectionExpectedFlags() []string { + return []string{"--expected-config-id", "cfg", "--expected-branch", "main", "--expected-commit", cliSelectionSHA} +} + +func TestPromotionSelectionCommands(t *testing.T) { + for _, tc := range []struct { + name string + args []string + body, path, response string + }{ + {"apply", []string{"promotion", "project", "apply", "p/1", "--workflow-id", "w", "--workflow-id", "w2"}, `{"workflowIds":["w","w2"]}`, "/promotions/projects/p%2F1/apply", cliPromotionAppliedBody}, + {"promote", []string{"promotion", "project", "promote", "p/1", "--workflow-id", "w"}, `{"workflowIds":["w"]}`, "/promotions/projects/p%2F1/promote", cliPromotionPromoteBody}, + {"continue project", append([]string{"promotion", "project", "apply-continue", "p/1", "--workflow-id", "w", "--confirm-destructive-changes=false"}, selectionExpectedFlags()...), `{"workflowIds":["w"],"expectedSource":` + cliSelectionSource + `,"confirmDestructiveChanges":false}`, "/promotions/projects/p%2F1/apply/continue", cliPromotionAppliedBody}, + {"continue connection", append([]string{"promotion", "apply-continue", "c/1", "--confirm-destructive-changes"}, selectionExpectedFlags()...), `{"expectedSource":` + cliSelectionSource + `,"confirmDestructiveChanges":true}`, "/promotions/connections/c%2F1/apply/continue", cliPromotionAppliedBody}, + } { + 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("result=%+v", got) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.EscapedPath() != n8n.BasePath+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, "workflows") { + t.Errorf("text=%+v", got) + } + }) + } +} + +func TestPromotionSelectionConfirmationBeforeTransport(t *testing.T) { + for _, tc := range []struct { + args []string + want string + }{ + {[]string{"promotion", "project", "apply", "p", "--workflow-id", "w"}, "absent from the branch are deleted"}, + {[]string{"promotion", "project", "promote", "p", "--workflow-id", "w"}, "remote branch is committed and pushed"}, + {append([]string{"promotion", "apply-continue", "c", "--confirm-destructive-changes"}, selectionExpectedFlags()...), "ALL team-project deletions with everything in them"}, + {append([]string{"promotion", "project", "apply-continue", "p", "--workflow-id", "w", "--confirm-destructive-changes"}, selectionExpectedFlags()...), "ALL destructive data-table column changes"}, + } { + t.Run(strings.Join(tc.args[:3], " "), func(t *testing.T) { + f := promotionFixture(t, cliPromotionAppliedBody) + 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) { + t.Errorf("refusal=%+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("noninteractive=%+v", got) + } + }) + } +} + +func TestPromotionSelectionInputAndStrictValidation(t *testing.T) { + for _, tc := range []struct { + args []string + body string + }{ + {[]string{"promotion", "project", "apply", "p"}, `{"workflowIds":["w"],"expectedSource":` + cliSelectionSource + `}`}, + {[]string{"promotion", "project", "promote", "p"}, `{"workflowIds":["w"],"commitMessage":"sync"}`}, + {[]string{"promotion", "project", "apply-continue", "p"}, `{"workflowIds":["w"],"expectedSource":` + cliSelectionSource + `,"confirmDestructiveChanges":true}`}, + {[]string{"promotion", "apply-continue", "c"}, `{"expectedSource":` + cliSelectionSource + `,"confirmDestructiveChanges":true}`}, + } { + t.Run(strings.Join(tc.args, " "), func(t *testing.T) { + f := promotionFixture(t, cliPromotionAppliedBody) + if tc.args[2] == "promote" { + f.body = cliPromotionPromoteBody + } + f.stdin = tc.body + before := f.requestCount() + got := f.run(append(tc.args, "--input", "-")...) + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "--yes") { + t.Fatalf("stdin refusal=%+v", got) + } + got = f.run(append(tc.args, "--input", "-", "--yes")...) + if got.code != ExitSuccess || f.lastBody() != tc.body { + t.Fatalf("stdin=%+v body=%s", got, f.lastBody()) + } + path := writePromotionInput(t, f, "request.json", tc.body) + got = f.run(append(tc.args, "--input", path, "--yes")...) + if got.code != ExitSuccess { + t.Errorf("file=%+v", got) + } + before = f.requestCount() + for _, body := range []string{`{}`, `null`, tc.body + ` {}`, strings.TrimSuffix(tc.body, "}") + `,"unknown":1}`, strings.Repeat(" ", maxPromotionDocument+1), `{"workflowIds":["w","w"]}`} { + f.stdin = body + got = f.run(append(tc.args, "--input", "-", "--yes")...) + if got.code == ExitSuccess || f.requestCount() != before { + t.Errorf("invalid accepted: %+v", got) + } + } + flag := "--expected-config-id" + if strings.Contains(strings.Join(tc.args, " "), "promote") { + flag = "--commit-message" + } + got = f.run(append(tc.args, "--input", path, flag, "", "--yes")...) + if got.code == ExitSuccess || !strings.Contains(got.stderr, "mutually exclusive") || f.requestCount() != before { + t.Errorf("mixed input=%+v", got) + } + }) + } +} + +func TestPromotionExpectedFrom(t *testing.T) { + for _, body := range []string{cliSelectionChanges, cliPromotionBlockedBody} { + f := promotionFixture(t, cliPromotionAppliedBody) + path := writePromotionInput(t, f, "review.json", body) + got := f.run("promotion", "project", "apply-continue", "p", "--workflow-id", "w", "--expected-from", path, "--yes") + if got.code != ExitSuccess { + t.Fatal(got.stderr) + } + var request n8n.ContinueApplyProjectSelectionRequest + if err := json.Unmarshal([]byte(f.lastBody()), &request); err != nil { + t.Fatal(err) + } + if request.ExpectedSource.BranchName != "main" || request.ExpectedSource.Validate() != nil || len(request.WorkflowIDs) != 1 { + t.Errorf("request=%+v", request) + } + f.stdin = body + before := f.requestCount() + got = f.run("promotion", "apply-continue", "c", "--expected-from", "-") + if got.code == ExitSuccess || f.requestCount() != before || !strings.Contains(got.stderr, "--yes") { + t.Errorf("stdin refusal=%+v", got) + } + got = f.run("promotion", "apply-continue", "c", "--expected-from", "-", "--yes") + if got.code != ExitSuccess { + t.Errorf("stdin=%+v", got) + } + } + f := promotionFixture(t, cliPromotionAppliedBody) + before := f.requestCount() + for _, body := range []string{ + `null`, `{}`, cliSelectionChanges + ` {}`, + strings.Replace(cliSelectionChanges, `"commitSha":"`+cliSelectionSHA+`"`, `"commitSha":null`, 1), + strings.Replace(cliSelectionChanges, cliSelectionSHA, "short", 1), + strings.Replace(cliSelectionChanges, `"configId":"cfg"`, `"configId":17`, 1), + strings.Replace(cliSelectionChanges, `"branchName":"main"`, `"branchName":null`, 1), + cliPromotionAppliedBody, cliPromotionSourceChangedBody, + strings.Repeat(" ", maxPromotionDocument+1), + } { + f.stdin = body + got := f.run("promotion", "apply-continue", "c", "--expected-from", "-", "--yes") + if got.code == ExitSuccess || f.requestCount() != before { + t.Errorf("bad review accepted: %+v", got) + } + } + f.stdin = cliSelectionChanges + got := f.run("promotion", "apply-continue", "c", "--expected-from", "-", "--expected-config-id", "cfg", "--yes") + if got.code == ExitSuccess || !strings.Contains(got.stderr, "mutually exclusive") || f.requestCount() != before { + t.Errorf("mixed source=%+v", got) + } +} + +func TestPromotionSelectionStatuses(t *testing.T) { + for _, args := range [][]string{ + {"promotion", "project", "apply", "p", "--workflow-id", "w"}, + append([]string{"promotion", "project", "apply-continue", "p", "--workflow-id", "w"}, selectionExpectedFlags()...), + append([]string{"promotion", "apply-continue", "c"}, selectionExpectedFlags()...), + } { + for _, tc := range []struct { + body string + code int + hint string + }{ + {cliPromotionAppliedBody, ExitSuccess, ""}, + {cliPromotionBlockedBody, ExitPromotionBlocked, "apply-continue"}, + {cliPromotionSourceChangedBody, ExitPromotionSourceChanged, "Review the branch again"}, + {`{"status":"queued","future":true}`, ExitError, "does not know"}, + } { + t.Run(strings.Join(args[:3], " ")+fmt.Sprint(tc.code), func(t *testing.T) { + f := promotionFixture(t, tc.body) + got := f.run(append(args, "--yes", "--output", "json")...) + if got.code != tc.code || !sameJSON(t, got.stdout, tc.body) || !strings.Contains(got.stderr, tc.hint) { + t.Errorf("result=%+v", got) + } + if tc.code == ExitPromotionBlocked && args[1] == "project" && (!strings.Contains(got.stderr, "promotion project apply-continue p") || !strings.Contains(got.stderr, "same full selection") || !strings.Contains(got.stderr, "project p was blocked")) { + t.Errorf("project hint=%s", got.stderr) + } + got = f.run(append(args, "--yes")...) + if got.code != tc.code { + t.Errorf("text=%+v", got) + } + }) + } + } +} + +func TestPromotionDiscoveryAndChangesCLI(t *testing.T) { + for _, branches := range []bool{false, true} { + t.Run(fmt.Sprint(branches), func(t *testing.T) { + f := promotionFixture(t, `{}`) + f.route = func(r *http.Request, page int) (int, string) { + if r.URL.Query().Get("search") != "a & b" || r.URL.Query().Get("limit") != "100" { + t.Errorf("query=%s", r.URL.RawQuery) + } + cursor := "next" + if page%2 == 1 { + cursor = "" + if r.URL.Query().Get("cursor") != "next" { + t.Errorf("cursor=%s", r.URL.RawQuery) + } + } + return 200, fmt.Sprintf(`{"data":[{"id":"1","name":"main","fullPath":"org/repo","remoteUrl":"https://gitlab.com/org/repo.git","defaultBranch":null,"isDefault":true}],"nextCursor":%q}`, cursor) + } + args := []string{"promotion", "provider", "repositories", "p"} + if branches { + args = []string{"promotion", "provider", "branches", "p", "org/repo"} + } + args = append(args, "--search", "a & b", "--limit", "100", "--all") + before := f.requestCount() + got := f.run(append(args, "--output", "json")...) + var result struct { + Data []json.RawMessage `json:"data"` + NextCursor string `json:"nextCursor"` + } + if got.code != ExitSuccess || json.Unmarshal([]byte(got.stdout), &result) != nil || len(result.Data) != 2 || result.NextCursor != "" || f.requestCount() != before+2 { + t.Fatalf("result=%+v", got) + } + got = f.run(args...) + if got.code != ExitSuccess || !strings.Contains(got.stdout, "main") { + t.Errorf("text=%+v", got) + } + if branches && !strings.Contains(f.lastRequest().URL.EscapedPath(), "org%2Frepo") { + t.Errorf("path=%s", f.lastRequest().URL.EscapedPath()) + } + f.route = nil + f.body = `{"data":[],"nextCursor":null}` + got = f.run(args...) + if got.code != ExitSuccess || !strings.Contains(got.stderr, "No ") { + t.Errorf("empty=%+v", got) + } + }) + } + f := promotionFixture(t, cliSelectionChanges) + got := f.run("promotion", "project", "changes", "p", "apply", "--search", "a & b", "--sort", "status", "--order", "desc", "--output", "json") + if got.code != ExitSuccess || !sameJSON(t, got.stdout, cliSelectionChanges) { + t.Fatalf("changes=%+v", got) + } + q := f.lastRequest().URL.Query() + if q.Get("search") != "a & b" || q.Get("sort") != "status" || q.Get("order") != "desc" { + t.Errorf("query=%v", q) + } + got = f.run("promotion", "project", "changes", "p", "promote") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "deleted") || !strings.Contains(got.stdout, cliSelectionSHA) { + t.Errorf("text=%+v", got) + } + f.body = `{"commitSha":null,"source":{"configId":"cfg","branchName":"main"},"changes":[]}` + got = f.run("promotion", "project", "changes", "p", "apply") + if got.code != ExitSuccess || !strings.Contains(got.stderr, "No workflow changes") { + t.Errorf("empty=%+v", got) + } +} + +func TestPromotionSelectionInvalidArgumentsAndScopes(t *testing.T) { + f := promotionFixture(t, `{}`) + before := f.requestCount() + for _, args := range [][]string{ + {"promotion", "provider", "repositories"}, + {"promotion", "provider", "branches", "p"}, + {"promotion", "project", "changes", "p", "bad"}, + {"promotion", "project", "changes", "p", "apply", "--sort", "bad"}, + {"promotion", "project", "changes", "p", "apply", "--order", "bad"}, + {"promotion", "project", "apply", "p"}, + {"promotion", "project", "apply", "p", "--workflow-id", "w", "--workflow-id", "w"}, + {"promotion", "project", "apply", "p", "--workflow-id", "w", "--expected-config-id", "cfg"}, + {"promotion", "project", "apply-continue", "p", "--workflow-id", "w"}, + {"promotion", "apply-continue", "c"}, + {"promotion", "project", "promote", "p", "--workflow-id", "w", "--force"}, + {"promotion", "project", "promote", "p", "--workflow-id", "w", "--commit-message", ""}, + {"promotion", "project", "apply", " p", "--workflow-id", "w"}, + {"promotion", "provider", "repositories", "p", "--output", "yaml"}, + } { + got := f.run(args...) + if got.code == ExitSuccess || f.requestCount() != before { + t.Errorf("args=%v result=%+v", args, got) + } + } + for action, want := range map[string]string{"project changes apply": "gitConnection:pull", "project changes promote": "gitConnection:push", "project apply": "gitConnection:pull", "project apply-continue": "gitConnection:pull", "apply-continue": "gitConnection:pull", "project promote": "gitConnection:push", "provider repositories": "gitConnection:discover", "provider branches": "gitConnection:discover"} { + if got := promotionScope(action); got != want { + t.Errorf("%s=%s want %s", action, got, want) + } + } + for _, tc := range []struct { + args []string + scope string + }{ + {[]string{"promotion", "project", "changes", "p", "apply"}, "gitConnection:pull"}, + {[]string{"promotion", "project", "changes", "p", "promote"}, "gitConnection:push"}, + {[]string{"promotion", "provider", "repositories", "p"}, "gitConnection:discover"}, + } { + f.status = 403 + got := f.run(tc.args...) + if got.code != ExitError || !strings.Contains(got.stderr, tc.scope) || !strings.Contains(got.stderr, "discover --resource promotions") { + t.Errorf("403=%+v", got) + } + } +} diff --git a/internal/coverage/coverage_test.go b/internal/coverage/coverage_test.go index 936a528..42253e7 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 = 30 +const deliveredThrough = 31 // 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 bc69c9c..db6dfaf 100644 --- a/internal/coverage/manifest.json +++ b/internal/coverage/manifest.json @@ -1760,8 +1760,8 @@ "scope": "gitConnection:push,gitConnection:pull", "availability": "both", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion project changes", + "status": "implemented" }, { "operationId": "continueApplyPackage", @@ -1771,8 +1771,8 @@ "scope": "gitConnection:pull", "availability": "both", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion apply-continue", + "status": "implemented" }, { "operationId": "applyProjectSelection", @@ -1782,8 +1782,8 @@ "scope": "gitConnection:pull", "availability": "both", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion project apply", + "status": "implemented" }, { "operationId": "continueApplyProjectSelection", @@ -1793,8 +1793,8 @@ "scope": "gitConnection:pull", "availability": "both", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion project apply-continue", + "status": "implemented" }, { "operationId": "promoteProjectSelection", @@ -1804,8 +1804,8 @@ "scope": "gitConnection:push", "availability": "both", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion project promote", + "status": "implemented" }, { "operationId": "getPromotionProviderRepositories", @@ -1815,8 +1815,8 @@ "scope": "gitConnection:discover", "availability": "upstream-only", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion provider repositories", + "status": "implemented" }, { "operationId": "getPromotionProviderRepositoryBranches", @@ -1826,8 +1826,8 @@ "scope": "gitConnection:discover", "availability": "upstream-only", "phase": 31, - "command": "", - "status": "planned" + "command": "n8n promotion provider branches", + "status": "implemented" }, { "operationId": "listNodeTypePolicyDocuments", diff --git a/internal/n8n/promotion_selection.go b/internal/n8n/promotion_selection.go new file mode 100644 index 0000000..b2d7d1f --- /dev/null +++ b/internal/n8n/promotion_selection.go @@ -0,0 +1,351 @@ +package n8n + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "unicode/utf8" +) + +// PromotionRepository is a GitLab repository usable as a connection target. +type PromotionRepository struct { + ID string `json:"id"` + Name string `json:"name"` + FullPath string `json:"fullPath"` + RemoteURL string `json:"remoteUrl"` + DefaultBranch *string `json:"defaultBranch"` +} + +// PromotionRepositoryBranch identifies a branch and the repository default. +type PromotionRepositoryBranch struct { + Name string `json:"name"` + IsDefault bool `json:"isDefault"` +} + +// PromotionDiscoveryOptions filters cursor-paginated repository discovery. +type PromotionDiscoveryOptions struct { + ListOptions + Search string +} + +// Validate rejects unsupported page sizes and overlong searches before transport. +func (o PromotionDiscoveryOptions) Validate() error { + if err := o.ListOptions.Validate(); err != nil { + return err + } + if o.Limit > 250 { + return fmt.Errorf("limit must not exceed 250, got %d", o.Limit) + } + if utf8.RuneCountInString(o.Search) > 255 { + return fmt.Errorf("search must contain at most 255 characters") + } + return nil +} + +// Apply encodes the page and search filters. +func (o PromotionDiscoveryOptions) Apply(q url.Values) url.Values { + q = o.ListOptions.Apply(q) + if o.Search != "" { + q.Set("search", o.Search) + } + return q +} + +// ListPromotionProviderRepositories lists one page. Follow nextCursor even on short pages. +func (c *Client) ListPromotionProviderRepositories(ctx context.Context, id string, opts PromotionDiscoveryOptions) (Page[PromotionRepository], error) { + page := Page[PromotionRepository]{Data: []PromotionRepository{}} + if err := validatePromotionID(id, "promotion provider ID"); err != nil { + return page, err + } + if err := opts.Validate(); err != nil { + return page, err + } + _, err := c.Do(ctx, Request{Path: PathJoin("promotions", "providers", id, "repositories"), Query: opts.Apply(nil)}, &page) + if page.Data == nil { + page.Data = []PromotionRepository{} + } + return page, err +} + +// ListPromotionProviderRepositoryBranches accepts a raw fullPath or GitLab project ID. +// PathJoin escapes repository slashes exactly once. Short pages can have a next cursor. +func (c *Client) ListPromotionProviderRepositoryBranches(ctx context.Context, id, repository string, opts PromotionDiscoveryOptions) (Page[PromotionRepositoryBranch], error) { + page := Page[PromotionRepositoryBranch]{Data: []PromotionRepositoryBranch{}} + if err := validatePromotionID(id, "promotion provider ID"); err != nil { + return page, err + } + if strings.TrimSpace(repository) == "" || utf8.RuneCountInString(repository) > 256 { + return page, fmt.Errorf("repository path must contain 1 to 256 characters: pass the raw fullPath or GitLab project ID") + } + if err := opts.Validate(); err != nil { + return page, err + } + _, err := c.Do(ctx, Request{Path: PathJoin("promotions", "providers", id, "repositories", repository, "branches"), Query: opts.Apply(nil)}, &page) + if page.Data == nil { + page.Data = []PromotionRepositoryBranch{} + } + return page, err +} + +// PromotionChangesOptions filters and sorts the project change preview. +type PromotionChangesOptions struct{ Search, Sort, Order string } + +// Validate checks the documented sort and order enums. +func (o PromotionChangesOptions) Validate() error { + switch o.Sort { + case "", "name", "updatedAt", "status": + default: + return fmt.Errorf("sort must be name, updatedAt, or status") + } + switch o.Order { + case "", "asc", "desc": + default: + return fmt.Errorf("order must be asc or desc") + } + return nil +} + +// PromotionChange is one selectable workflow difference. +type PromotionChange struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Status string `json:"status"` + Version *int `json:"version"` + UpdatedAt *string `json:"updatedAt"` + UpdatedBy *string `json:"updatedBy"` + DependencyCount int `json:"dependencyCount"` +} + +// PromotionChangeSource identifies the configuration and branch used for a preview. +type PromotionChangeSource struct { + ConfigID string `json:"configId"` + BranchName string `json:"branchName"` +} + +// PromotionChanges preserves the reviewed source and the complete server response. +type PromotionChanges struct { + CommitSHA *string `json:"commitSha"` + Source PromotionChangeSource `json:"source"` + Changes []PromotionChange `json:"changes"` + raw json.RawMessage +} + +// UnmarshalJSON decodes the typed view and retains all response fields. +func (r *PromotionChanges) UnmarshalJSON(data []byte) error { + type plain PromotionChanges + var p plain + if err := json.Unmarshal(data, &p); err != nil { + return err + } + *r = PromotionChanges(p) + r.raw = append(json.RawMessage(nil), data...) + return nil +} + +// MarshalJSON preserves the server response and emits empty changes as an array. +func (r PromotionChanges) MarshalJSON() ([]byte, error) { + if len(r.raw) > 0 { + return r.raw, nil + } + type plain PromotionChanges + if r.Changes == nil { + r.Changes = []PromotionChange{} + } + return json.Marshal(plain(r)) +} + +// GetPromotionChanges compares a project with its cloned apply or promote branch. +func (c *Client) GetPromotionChanges(ctx context.Context, projectID, direction string, opts PromotionChangesOptions) (*PromotionChanges, error) { + if err := validatePromotionID(projectID, "project ID"); err != nil { + return nil, err + } + if err := validatePromotionDirection(direction); err != nil { + return nil, err + } + if err := opts.Validate(); err != nil { + return nil, err + } + q := url.Values{} + if opts.Search != "" { + q.Set("search", opts.Search) + } + if opts.Sort != "" { + q.Set("sort", opts.Sort) + } + if opts.Order != "" { + q.Set("order", opts.Order) + } + var result PromotionChanges + if _, err := c.Do(ctx, Request{Path: PathJoin("promotions", "projects", projectID, "changes", direction), Query: q}, &result); err != nil { + return nil, err + } + return &result, nil +} + +// ContinueApplyPromotionRequest rechecks a reviewed full apply without a server session. +type ContinueApplyPromotionRequest struct { + ExpectedSource PromotionExpectedSource `json:"expectedSource"` + ConfirmDestructiveChanges *bool `json:"confirmDestructiveChanges,omitempty"` +} + +// Validate requires a complete reviewed source. +func (r ContinueApplyPromotionRequest) Validate() error { return r.ExpectedSource.Validate() } + +// ApplyProjectSelectionRequest applies only selected workflow changes. +type ApplyProjectSelectionRequest struct { + WorkflowIDs []string `json:"workflowIds"` + ExpectedSource *PromotionExpectedSource `json:"expectedSource,omitempty"` +} + +// Validate rejects invalid selections and incomplete expected sources. +func (r ApplyProjectSelectionRequest) Validate() error { + if err := validatePromotionWorkflowIDs(r.WorkflowIDs); err != nil { + return err + } + if r.ExpectedSource != nil { + return r.ExpectedSource.Validate() + } + return nil +} + +// ContinueApplyProjectSelectionRequest must repeat the full reviewed selection. +type ContinueApplyProjectSelectionRequest struct { + WorkflowIDs []string `json:"workflowIds"` + ExpectedSource PromotionExpectedSource `json:"expectedSource"` + ConfirmDestructiveChanges *bool `json:"confirmDestructiveChanges,omitempty"` +} + +// Validate requires the full selection and a complete reviewed source. +func (r ContinueApplyProjectSelectionRequest) Validate() error { + if err := validatePromotionWorkflowIDs(r.WorkflowIDs); err != nil { + return err + } + return r.ExpectedSource.Validate() +} + +// PromoteProjectSelectionRequest pushes selected workflows without force support. +type PromoteProjectSelectionRequest struct { + WorkflowIDs []string `json:"workflowIds"` + CommitMessage *string `json:"commitMessage,omitempty"` +} + +// Validate rejects invalid selections and empty or overlong commit messages. +func (r PromoteProjectSelectionRequest) Validate() error { + if err := validatePromotionWorkflowIDs(r.WorkflowIDs); err != nil { + return err + } + if r.CommitMessage != nil && (strings.TrimSpace(*r.CommitMessage) == "" || utf8.RuneCountInString(*r.CommitMessage) > maxPromotionCommitLength) { + return fmt.Errorf("commit message must contain 1 to 1000 characters") + } + return nil +} + +func validatePromotionWorkflowIDs(ids []string) error { + if len(ids) == 0 { + return fmt.Errorf("workflowIds requires at least one workflow ID: pass --workflow-id or --input") + } + seen := make(map[string]bool, len(ids)) + for _, id := range ids { + if err := validatePromotionID(id, "workflow ID"); err != nil { + return err + } + if seen[id] { + return fmt.Errorf("duplicate workflow ID %q: select each workflow once", id) + } + seen[id] = true + } + return nil +} + +// ContinueApplyPackage rechecks bindings and applies the reviewed full package. +func (c *Client) ContinueApplyPackage(ctx context.Context, id string, request ContinueApplyPromotionRequest) (*ApplyPromotionResult, error) { + if err := validatePromotionID(id, "promotion connection ID"); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + return c.applyPromotionSelection(ctx, PathJoin("promotions", "connections", id, "apply", "continue"), request) +} + +// ApplyProjectSelection imports or removes selected workflow IDs from the branch. +func (c *Client) ApplyProjectSelection(ctx context.Context, id string, request ApplyProjectSelectionRequest) (*ApplyPromotionResult, error) { + if err := validatePromotionID(id, "project ID"); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply"), request) +} + +// ContinueApplyProjectSelection rechecks the reviewed source and full selection. +func (c *Client) ContinueApplyProjectSelection(ctx context.Context, id string, request ContinueApplyProjectSelectionRequest) (*ApplyPromotionResult, error) { + if err := validatePromotionID(id, "project ID"); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply", "continue"), request) +} + +func (c *Client) applyPromotionSelection(ctx context.Context, path string, request any) (*ApplyPromotionResult, error) { + var result ApplyPromotionResult + if _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: path, Body: request}, &result); err != nil { + return nil, err + } + return &result, nil +} + +// PromoteProjectSelection exports selected workflow states and pushes the branch. +func (c *Client) PromoteProjectSelection(ctx context.Context, id string, request PromoteProjectSelectionRequest) (*PromotePromotionResult, error) { + if err := validatePromotionID(id, "project ID"); err != nil { + return nil, err + } + if err := request.Validate(); err != nil { + return nil, err + } + var result PromotePromotionResult + if _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: PathJoin("promotions", "projects", id, "promote"), Body: request}, &result); err != nil { + return nil, err + } + return &result, nil +} + +// CollectPromotionDiscovery follows provider cursors even across empty filtered +// pages. Both items and requests are bounded, and any repeated cursor fails. +func CollectPromotionDiscovery[T any](ctx context.Context, fetch PageFunc[T], opts ListOptions) (Collection[T], error) { + seen := make(map[string]bool) + requests := 0 + return CollectWithInfo(ctx, func(ctx context.Context, pageOpts ListOptions) (Page[T], error) { + for { + if err := ctx.Err(); err != nil { + return Page[T]{}, err + } + if seen[pageOpts.Cursor] { + return Page[T]{}, fmt.Errorf("pagination cursor %q repeated: the API is looping", pageOpts.Cursor) + } + if requests >= DefaultCollectLimit { + return Page[T]{}, fmt.Errorf("promotion discovery exceeded %d pages: narrow --search or page explicitly", DefaultCollectLimit) + } + seen[pageOpts.Cursor] = true + requests++ + page, err := fetch(ctx, pageOpts) + if err != nil { + return page, err + } + if page.HasMore() && seen[page.NextCursor] { + return Page[T]{}, fmt.Errorf("pagination cursor %q repeated: the API is looping", page.NextCursor) + } + if len(page.Data) > 0 || !page.HasMore() { + return page, nil + } + pageOpts.Cursor = page.NextCursor + } + }, opts, DefaultCollectLimit) +} diff --git a/internal/n8n/promotion_selection_test.go b/internal/n8n/promotion_selection_test.go new file mode 100644 index 0000000..0a85e45 --- /dev/null +++ b/internal/n8n/promotion_selection_test.go @@ -0,0 +1,341 @@ +package n8n + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "reflect" + "strings" + "testing" +) + +const selectionSHA = "0123456789012345678901234567890123456789" +const selectionSourceJSON = `{"configId":"cfg","branchName":"main","commitSha":"` + selectionSHA + `"}` +const selectionChangesJSON = `{"commitSha":"` + selectionSHA + `","source":{"configId":"cfg","branchName":"main"},"changes":[{"id":"wf","name":"Workflow","type":"workflow","status":"renamed-and-modified","version":null,"updatedAt":null,"updatedBy":null,"dependencyCount":2,"future":true}],"future":{"ok":true}}` + +func selectionSource() PromotionExpectedSource { + return PromotionExpectedSource{ConfigID: "cfg", BranchName: "main", CommitSHA: selectionSHA} +} + +func TestPromotionSelectionTransport(t *testing.T) { + yes, no := true, false + message := "sync" + cases := []struct { + name, path, body, response string + call func(context.Context, *Client) (any, error) + }{ + {"repositories", "/promotions/providers/prov%2F1/repositories", "", `{"data":[{"id":"1","name":"repo","fullPath":"org/repo","remoteUrl":"https://gitlab.com/org/repo.git","defaultBranch":null}],"nextCursor":"next"}`, func(ctx context.Context, c *Client) (any, error) { + return c.ListPromotionProviderRepositories(ctx, "prov/1", PromotionDiscoveryOptions{ListOptions: ListOptions{Limit: 20, Cursor: "a+b"}, Search: "a & b"}) + }}, + {"branches", "/promotions/providers/prov%2F1/repositories/org%2Frepo/branches", "", `{"data":[{"name":"main","isDefault":true}],"nextCursor":"next"}`, func(ctx context.Context, c *Client) (any, error) { + return c.ListPromotionProviderRepositoryBranches(ctx, "prov/1", "org/repo", PromotionDiscoveryOptions{ListOptions: ListOptions{Limit: 20, Cursor: "a+b"}, Search: "a & b"}) + }}, + {"changes", "/promotions/projects/proj%2F1/changes/apply", "", selectionChangesJSON, func(ctx context.Context, c *Client) (any, error) { + return c.GetPromotionChanges(ctx, "proj/1", "apply", PromotionChangesOptions{Search: "a & b", Sort: "updatedAt", Order: "desc"}) + }}, + {"apply", "/promotions/projects/proj%2F1/apply", `{"workflowIds":["wf"],"expectedSource":` + selectionSourceJSON + `}`, `{"status":"blocked","configId":"cfg","git":{"branchName":"main","commitSha":"` + selectionSHA + `"},"preflight":{"future":true}}`, func(ctx context.Context, c *Client) (any, error) { + source := selectionSource() + return c.ApplyProjectSelection(ctx, "proj/1", ApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}, ExpectedSource: &source}) + }}, + {"continue project", "/promotions/projects/proj%2F1/apply/continue", `{"workflowIds":["wf"],"expectedSource":` + selectionSourceJSON + `,"confirmDestructiveChanges":false}`, `{"status":"source-changed","configId":"cfg","git":{"branchName":"main","commitSha":"` + selectionSHA + `"}}`, func(ctx context.Context, c *Client) (any, error) { + return c.ContinueApplyProjectSelection(ctx, "proj/1", ContinueApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}, ExpectedSource: selectionSource(), ConfirmDestructiveChanges: &no}) + }}, + {"continue connection", "/promotions/connections/conn%2F1/apply/continue", `{"expectedSource":` + selectionSourceJSON + `,"confirmDestructiveChanges":true}`, `{"status":"applied","counts":{},"warnings":[]}`, func(ctx context.Context, c *Client) (any, error) { + return c.ContinueApplyPackage(ctx, "conn/1", ContinueApplyPromotionRequest{ExpectedSource: selectionSource(), ConfirmDestructiveChanges: &yes}) + }}, + {"promote", "/promotions/projects/proj%2F1/promote", `{"workflowIds":["wf"],"commitMessage":"sync"}`, promotionPromoteResultBody, func(ctx context.Context, c *Client) (any, error) { + return c.PromoteProjectSelection(ctx, "proj/1", PromoteProjectSelectionRequest{WorkflowIDs: []string{"wf"}, CommitMessage: &message}) + }}, + } + 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) + method := http.MethodGet + if tc.body != "" { + method = http.MethodPost + } + if req.Method != method || req.URL.EscapedPath() != BasePath+tc.path || req.Header.Get(HeaderAPIKey) != "community-secret" { + t.Errorf("request = %s %s auth=%q", req.Method, req.URL.EscapedPath(), req.Header.Get(HeaderAPIKey)) + } + if body != tc.body { + t.Errorf("body = %s, want %s", body, tc.body) + } + if method == http.MethodGet { + if req.URL.Query().Get("search") != "a & b" { + t.Errorf("query=%s", req.URL.RawQuery) + } + if tc.name == "changes" { + if req.URL.Query().Get("sort") != "updatedAt" || req.URL.Query().Get("order") != "desc" { + t.Errorf("query=%s", req.URL.RawQuery) + } + } else if req.URL.Query().Get("limit") != "20" || req.URL.Query().Get("cursor") != "a+b" { + t.Errorf("query=%s", req.URL.RawQuery) + } + } + 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, 401, 403, 404, 409, 415, 422, 503} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + s := newCommunityPackageServer(t, packageJSONHandler(status, `{"message":"failure"}`)) + _, err := tc.call(context.Background(), s.client(t)) + if !IsStatus(err, status) { + t.Errorf("error=%v", err) + } + }) + } + for _, status := range []int{201, 204} { + t.Run(fmt.Sprintf("empty%d", status), func(t *testing.T) { + s := newCommunityPackageServer(t, packageJSONHandler(status, "")) + if _, err := tc.call(context.Background(), s.client(t)); err != nil { + t.Fatal(err) + } + }) + } + t.Run("malformed", func(t *testing.T) { + s := newCommunityPackageServer(t, packageJSONHandler(200, `{bad`)) + if _, err := tc.call(context.Background(), s.client(t)); err == nil { + t.Fatal("accepted malformed JSON") + } + }) + t.Run("canceled", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + before := len(server.requests) + if _, err := tc.call(ctx, server.client(t)); !errors.Is(err, context.Canceled) { + t.Errorf("error=%v", err) + } + if len(server.requests) != before { + t.Error("canceled request reached transport") + } + }) + }) + } +} + +func TestPromotionSelectionValidationBeforeTransport(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(200, `{}`)) + c := server.client(t) + ctx := context.Background() + invalid := []func() error{ + func() error { + _, e := c.ListPromotionProviderRepositories(ctx, "", PromotionDiscoveryOptions{}) + return e + }, + func() error { + _, e := c.ListPromotionProviderRepositories(ctx, "p", PromotionDiscoveryOptions{ListOptions: ListOptions{Limit: 251}}) + return e + }, + func() error { + _, e := c.ListPromotionProviderRepositories(ctx, "p", PromotionDiscoveryOptions{ListOptions: ListOptions{Limit: -1}}) + return e + }, + func() error { + _, e := c.ListPromotionProviderRepositories(ctx, "p", PromotionDiscoveryOptions{Search: strings.Repeat("é", 256)}) + return e + }, + func() error { + _, e := c.ListPromotionProviderRepositoryBranches(ctx, "p", "", PromotionDiscoveryOptions{}) + return e + }, + func() error { + _, e := c.ListPromotionProviderRepositoryBranches(ctx, "p", strings.Repeat("x", 257), PromotionDiscoveryOptions{}) + return e + }, + func() error { _, e := c.GetPromotionChanges(ctx, "p", "pull", PromotionChangesOptions{}); return e }, + func() error { + _, e := c.GetPromotionChanges(ctx, "p", "apply", PromotionChangesOptions{Sort: "id"}) + return e + }, + func() error { + _, e := c.GetPromotionChanges(ctx, "p", "apply", PromotionChangesOptions{Order: "up"}) + return e + }, + func() error { _, e := c.ApplyProjectSelection(ctx, "p", ApplyProjectSelectionRequest{}); return e }, + func() error { + _, e := c.ApplyProjectSelection(ctx, "p", ApplyProjectSelectionRequest{WorkflowIDs: []string{"w", "w"}}) + return e + }, + func() error { + _, e := c.ApplyProjectSelection(ctx, "p", ApplyProjectSelectionRequest{WorkflowIDs: []string{strings.Repeat("w", 37)}}) + return e + }, + func() error { + _, e := c.ApplyProjectSelection(ctx, "p", ApplyProjectSelectionRequest{WorkflowIDs: []string{" w"}}) + return e + }, + func() error { + _, e := c.ApplyProjectSelection(ctx, "p", ApplyProjectSelectionRequest{WorkflowIDs: []string{"w"}, ExpectedSource: &PromotionExpectedSource{}}) + return e + }, + func() error { _, e := c.ContinueApplyPackage(ctx, "c", ContinueApplyPromotionRequest{}); return e }, + func() error { + _, e := c.ContinueApplyProjectSelection(ctx, "p", ContinueApplyProjectSelectionRequest{WorkflowIDs: []string{"w"}}) + return e + }, + func() error { _, e := c.PromoteProjectSelection(ctx, "p", PromoteProjectSelectionRequest{}); return e }, + } + for i, call := range invalid { + if err := call(); err == nil { + t.Errorf("case %d accepted", i) + } + } + for _, message := range []string{"", " ", strings.Repeat("x", 1001)} { + if _, err := c.PromoteProjectSelection(ctx, "p", PromoteProjectSelectionRequest{WorkflowIDs: []string{"w"}, CommitMessage: &message}); err == nil { + t.Error("invalid commit accepted") + } + } + if len(server.requests) != 0 { + t.Fatalf("validation sent %d requests", len(server.requests)) + } +} + +func TestPromotionDiscoveryCollectShortPages(t *testing.T) { + for _, branches := range []bool{false, true} { + t.Run(fmt.Sprint(branches), func(t *testing.T) { + calls := 0 + server := newCommunityPackageServer(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + w.Header().Set("Content-Type", "application/json") + if r.URL.Query().Get("search") != "space & slash/" || r.URL.Query().Get("limit") != "100" { + t.Errorf("filters=%v", r.URL.Query()) + } + cursor := "next" + if calls == 2 { + cursor = "" + if r.URL.Query().Get("cursor") != "next" { + t.Errorf("cursor=%s", r.URL.RawQuery) + } + } + fmt.Fprintf(w, `{"data":[{"id":"%d","name":"main","isDefault":true}],"nextCursor":%q}`, calls, cursor) + }) + c := server.client(t) + opts := PromotionDiscoveryOptions{Search: "space & slash/"} + if branches { + result, err := CollectPromotionDiscovery(context.Background(), func(ctx context.Context, p ListOptions) (Page[PromotionRepositoryBranch], error) { + opts.ListOptions = p + return c.ListPromotionProviderRepositoryBranches(ctx, "p", "org/repo", opts) + }, ListOptions{Limit: 100}) + if err != nil || len(result.Data) != 2 || result.Truncated { + t.Fatalf("result=%+v err=%v", result, err) + } + } else { + result, err := CollectPromotionDiscovery(context.Background(), func(ctx context.Context, p ListOptions) (Page[PromotionRepository], error) { + opts.ListOptions = p + return c.ListPromotionProviderRepositories(ctx, "p", opts) + }, ListOptions{Limit: 100}) + if err != nil || len(result.Data) != 2 || result.Truncated { + t.Fatalf("result=%+v err=%v", result, err) + } + } + if calls != 2 { + t.Errorf("calls=%d", calls) + } + }) + } +} + +func TestPromotionSelectionOptionalFieldsOmitted(t *testing.T) { + for _, request := range []any{ApplyProjectSelectionRequest{WorkflowIDs: []string{"w"}}, PromoteProjectSelectionRequest{WorkflowIDs: []string{"w"}}} { + data, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + if string(data) != `{"workflowIds":["w"]}` { + t.Errorf("request=%s", data) + } + } + request := ContinueApplyPromotionRequest{ExpectedSource: selectionSource()} + data, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "confirmDestructiveChanges") { + t.Errorf("request=%s", data) + } +} + +func TestPromotionDiscoveryCollectionBounds(t *testing.T) { + t.Run("empty nonfinal page", func(t *testing.T) { + calls := 0 + result, err := CollectPromotionDiscovery(context.Background(), func(_ context.Context, opts ListOptions) (Page[int], error) { + calls++ + switch opts.Cursor { + case "": + return Page[int]{Data: []int{}, NextCursor: "empty"}, nil + case "empty": + return Page[int]{Data: []int{1}, NextCursor: "last"}, nil + case "last": + return Page[int]{Data: []int{2}}, nil + default: + t.Fatalf("unexpected cursor %q", opts.Cursor) + return Page[int]{}, nil + } + }, ListOptions{}) + if err != nil || calls != 3 || len(result.Data) != 2 || result.Truncated { + t.Errorf("result=%+v calls=%d error=%v", result, calls, err) + } + }) + t.Run("cursor loop across empty page", func(t *testing.T) { + calls := 0 + _, err := CollectPromotionDiscovery(context.Background(), func(_ context.Context, opts ListOptions) (Page[int], error) { + calls++ + if opts.Cursor == "start" { + return Page[int]{NextCursor: "next"}, nil + } + return Page[int]{Data: []int{1}, NextCursor: "start"}, nil + }, ListOptions{Cursor: "start"}) + if err == nil || !strings.Contains(err.Error(), "repeated") || calls != 2 { + t.Errorf("calls=%d err=%v", calls, err) + } + }) + for _, clip := range []bool{false, true} { + t.Run(fmt.Sprintf("cap clip=%v", clip), func(t *testing.T) { + calls := 0 + size := DefaultCollectLimit + if clip { + size++ + } + result, err := CollectPromotionDiscovery(context.Background(), func(context.Context, ListOptions) (Page[int], error) { + calls++ + return Page[int]{Data: make([]int, size), NextCursor: "next"}, nil + }, ListOptions{}) + wantCursor := "next" + if clip { + wantCursor = "" + } + if err != nil || calls != 1 || len(result.Data) != DefaultCollectLimit || !result.Truncated || result.NextCursor != wantCursor { + t.Errorf("len=%d calls=%d truncated=%t cursor=%q err=%v", len(result.Data), calls, result.Truncated, result.NextCursor, err) + } + }) + } + t.Run("endless empty pages", func(t *testing.T) { + calls := 0 + _, err := CollectPromotionDiscovery(context.Background(), func(context.Context, ListOptions) (Page[int], error) { + calls++ + return Page[int]{NextCursor: fmt.Sprint(calls)}, nil + }, ListOptions{}) + if err == nil || !strings.Contains(err.Error(), "exceeded") || calls != DefaultCollectLimit { + t.Errorf("calls=%d err=%v", calls, err) + } + }) +} diff --git a/test/integration/promotion_selection_test.go b/test/integration/promotion_selection_test.go new file mode 100644 index 0000000..f432d3f --- /dev/null +++ b/test/integration/promotion_selection_test.go @@ -0,0 +1,116 @@ +package integration_test + +import ( + "context" + "encoding/json" + "os" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/cli" + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" + "github.com/SomeoneWithOptions/n8n-cli/internal/version" + "github.com/SomeoneWithOptions/n8n-cli/test/integration" +) + +// Discovery is read-only: never create providers, connections, or checkouts. +func TestPromotionRepositoryDiscovery(t *testing.T) { + instance := integration.Require(t) + client := instance.Client(t) + ctx := context.Background() + providers, err := client.ListPromotionProviders(ctx, n8n.ListOptions{Limit: 100}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatal(err) + } + var providerID string + for _, provider := range providers.Data { + if provider.Type == n8n.PromotionProviderTypeGitLab { + providerID = provider.ID + break + } + } + if providerID == "" { + t.Skip("no GitLab promotion provider available") + } + repositories, err := client.ListPromotionProviderRepositories(ctx, providerID, n8n.PromotionDiscoveryOptions{ListOptions: n8n.ListOptions{Limit: 10}}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatal(err) + } + runPromotionSelectionReadCLI(t, instance, []string{"promotion", "provider", "repositories", providerID, "--limit", "10"}) + if len(repositories.Data) == 0 { + t.Skip("no accessible GitLab repository to list branches") + } + repository := repositories.Data[0] + if repository.FullPath == "" || repository.RemoteURL == "" { + t.Fatalf("repository lacks fullPath or remoteUrl: %+v", repository) + } + branches, err := client.ListPromotionProviderRepositoryBranches(ctx, providerID, repository.FullPath, n8n.PromotionDiscoveryOptions{ListOptions: n8n.ListOptions{Limit: 10}}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatal(err) + } + for _, branch := range branches.Data { + if branch.Name == "" { + t.Error("branch lacks a name") + } + } + runPromotionSelectionReadCLI(t, instance, []string{"promotion", "provider", "branches", providerID, repository.FullPath, "--limit", "10"}) +} + +// The supplied project must already have a resolved, cloned promotion connection. +// These tests never clone or apply/promote content on the shared instance. +func TestPromotionProjectChanges(t *testing.T) { + instance := integration.Require(t) + projectID := os.Getenv(integration.EnvProjectID) + if projectID == "" { + t.Skip("set N8N_INTEGRATION_PROJECT_ID to a project with a cloned promotion direction") + } + client := instance.Client(t) + for _, direction := range []string{n8n.PromotionDirectionApply, n8n.PromotionDirectionPromote} { + t.Run(direction, func(t *testing.T) { + changes, err := client.GetPromotionChanges(context.Background(), projectID, direction, n8n.PromotionChangesOptions{}) + skipUnlessPromotions(t, err) + if err != nil { + t.Fatal(err) + } + if changes.Source.ConfigID == "" { + t.Error("changes lack source configId") + } + for _, change := range changes.Changes { + if change.ID == "" || change.Type != "workflow" { + t.Errorf("invalid change: %+v", change) + } + } + runPromotionSelectionReadCLI(t, instance, []string{"promotion", "project", "changes", projectID, direction}) + }) + } +} + +func runPromotionSelectionReadCLI(t *testing.T, instance integration.Instance, args []string) { + t.Helper() + env := map[string]string{config.EnvURL: instance.URL, config.EnvAPIKey: instance.APIKey.Reveal()} + interactive := false + var stdout, stderr strings.Builder + code := cli.Run(context.Background(), append(args, "--output", "json"), cli.Options{ + Streams: cli.Streams{In: strings.NewReader(""), Out: &stdout, Err: &stderr}, + Version: version.Get(), ConfigDir: t.TempDir(), Env: func(name string) string { return env[name] }, + Keyring: config.NewMemoryStore(config.StorageKeyring), Interactive: &interactive, + }) + if code != cli.ExitSuccess { + for _, status := range []string{"403", "404", "503"} { + if strings.Contains(stderr.String(), status) { + t.Skip("promotion read unavailable to integration credential") + } + } + t.Fatalf("%v exited %d: %s", args, code, stderr.String()) + } + if !json.Valid([]byte(stdout.String())) { + t.Fatalf("invalid JSON: %s", stdout.String()) + } + if strings.Contains(stdout.String(), instance.APIKey.Reveal()) { + t.Error("API credential leaked into stdout") + } +}