release-cherry-pick 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.atl/.skill-registry.cache.json +3 -0
  2. package/.atl/skill-registry.md +55 -0
  3. package/.husky/pre-commit +1 -0
  4. package/CLAUDE.md +74 -0
  5. package/LICENSE +21 -0
  6. package/README.md +181 -2
  7. package/eslint.config.js +34 -0
  8. package/openspec/changes/archive/.gitkeep +0 -0
  9. package/openspec/changes/node-cli-release-cherry-pick/.openspec.yaml +2 -0
  10. package/openspec/changes/node-cli-release-cherry-pick/design.md +126 -0
  11. package/openspec/changes/node-cli-release-cherry-pick/proposal.md +39 -0
  12. package/openspec/changes/node-cli-release-cherry-pick/specs/branch-selection/spec.md +42 -0
  13. package/openspec/changes/node-cli-release-cherry-pick/specs/cherry-pick-orchestration/spec.md +49 -0
  14. package/openspec/changes/node-cli-release-cherry-pick/specs/cli-core/spec.md +37 -0
  15. package/openspec/changes/node-cli-release-cherry-pick/specs/config-management/spec.md +52 -0
  16. package/openspec/changes/node-cli-release-cherry-pick/specs/documentation-generation/spec.md +38 -0
  17. package/openspec/changes/node-cli-release-cherry-pick/specs/gitlab-integration/spec.md +49 -0
  18. package/openspec/changes/node-cli-release-cherry-pick/specs/release-summary/spec.md +37 -0
  19. package/openspec/changes/node-cli-release-cherry-pick/tasks.md +70 -0
  20. package/openspec/config.yaml +32 -0
  21. package/openspec/specs/.gitkeep +0 -0
  22. package/package.json +48 -4
  23. package/scripts/sandbox/harness.js +130 -0
  24. package/scripts/sandbox/make-sandbox.sh +90 -0
  25. package/scripts/sandbox/run-config.js +26 -0
  26. package/scripts/sandbox/run-release.js +26 -0
  27. package/scripts/sandbox/test-package.js +571 -0
  28. package/skills-lock.json +11 -0
  29. package/src/cli/index.js +13 -0
  30. package/src/config/ai-providers.js +285 -0
  31. package/src/config/defaults.js +45 -0
  32. package/src/config/loader.js +127 -0
  33. package/src/config/setup.js +463 -0
  34. package/src/config/validator.js +80 -0
  35. package/src/doc/agents-generator.js +83 -0
  36. package/src/doc/rpd-generator.js +87 -0
  37. package/src/git/branch-parser.js +88 -0
  38. package/src/git/branch-selector.js +97 -0
  39. package/src/git/cherry-pick.js +216 -0
  40. package/src/git/git-auth.js +43 -0
  41. package/src/git/instance.js +17 -0
  42. package/src/git/release-branch.js +106 -0
  43. package/src/git/release-status.js +121 -0
  44. package/src/git/remote-url.js +34 -0
  45. package/src/git/repo-state.js +153 -0
  46. package/src/gitlab/ai-description.js +157 -0
  47. package/src/gitlab/client.js +324 -0
  48. package/src/gitlab/mr-creator.js +55 -0
  49. package/src/gitlab/reviewer-selector.js +52 -0
  50. package/src/index.js +58 -0
  51. package/src/report/summary.js +91 -0
  52. package/src/utils/errors.js +47 -0
  53. package/src/utils/logger.js +36 -0
  54. package/src/utils/prompts.js +59 -0
  55. package/src/utils/secrets.js +24 -0
  56. package/src/workflow/release.js +464 -0
  57. package/test-e2e.js +56 -0
@@ -0,0 +1,42 @@
1
+ ## Purpose
2
+
3
+ Permitir la selección de ramas mediante listas predefinidas o interacción directa con el repositorio Git.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: Branch list file support
8
+ The system SHALL support reading branches from a predefined list file.
9
+
10
+ #### Scenario: Load branches from file
11
+ - **WHEN** user provides a file path with branch list
12
+ - **THEN** the system SHALL parse the file and extract branch names matching the pattern `*TASK-ID*: Description`
13
+
14
+ #### Scenario: Parse branch format
15
+ - **WHEN** parsing branch list entries
16
+ - **THEN** the system SHALL extract task ID and branch name from each line
17
+
18
+ ### Requirement: Interactive branch selection
19
+ The system SHALL provide interactive branch selection when no file is provided.
20
+
21
+ #### Scenario: List available branches
22
+ - **WHEN** user chooses interactive selection
23
+ - **THEN** the system SHALL list all feature and hotfix branches from the repository
24
+
25
+ #### Scenario: Search branches
26
+ - **WHEN** user wants to search for specific branches
27
+ - **THEN** the system SHALL provide a search/filter functionality
28
+
29
+ #### Scenario: Select multiple branches
30
+ - **WHEN** user selects branches for release
31
+ - **THEN** the system SHALL allow selecting multiple branches simultaneously
32
+
33
+ ### Requirement: Branch validation
34
+ The system SHALL validate that selected branches exist and are accessible.
35
+
36
+ #### Scenario: Validate branch exists
37
+ - **WHEN** a branch is selected
38
+ - **THEN** the system SHALL verify the branch exists in the remote repository
39
+
40
+ #### Scenario: Validate branch is mergeable
41
+ - **WHEN** a branch is selected
42
+ - **THEN** the system SHALL check if the branch can be merged without conflicts
@@ -0,0 +1,49 @@
1
+ ## Purpose
2
+
3
+ Orquestar el proceso de cherry-pick de ramas feature/hotfix hacia ramas de release con manejo de conflictos.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: Release branch creation
8
+ The system SHALL create release branches from the staging branch.
9
+
10
+ #### Scenario: Create release branch from staging
11
+ - **WHEN** user initiates release process
12
+ - **THEN** the system SHALL create a new branch from staging with the pattern `release/<task-id>-<description>`
13
+
14
+ #### Scenario: Handle existing release branch
15
+ - **WHEN** a release branch already exists
16
+ - **THEN** the system SHALL ask user whether to overwrite or skip
17
+
18
+ ### Requirement: Cherry-pick execution
19
+ The system SHALL execute cherry-pick of commits from source branches to release branches.
20
+
21
+ #### Scenario: Cherry-pick single commit
22
+ - **WHEN** source branch has commits to cherry-pick
23
+ - **THEN** the system SHALL execute `git cherry-pick` for each commit
24
+
25
+ #### Scenario: Cherry-pick multiple commits
26
+ - **WHEN** source branch has multiple commits
27
+ - **THEN** the system SHALL cherry-pick commits in chronological order
28
+
29
+ ### Requirement: Conflict detection and handling
30
+ The system SHALL detect and handle cherry-pick conflicts.
31
+
32
+ #### Scenario: Detect conflicts
33
+ - **WHEN** cherry-pick encounters conflicts
34
+ - **THEN** the system SHALL mark the operation as "NO PROCEDE" and log the conflicting files
35
+
36
+ #### Scenario: Report conflict details
37
+ - **WHEN** conflicts are detected
38
+ - **THEN** the system SHALL display which files have conflicts and suggest resolution
39
+
40
+ ### Requirement: Success tracking
41
+ The system SHALL track which cherry-picks succeeded and which failed.
42
+
43
+ #### Scenario: Mark successful cherry-pick
44
+ - **WHEN** cherry-pick completes without conflicts
45
+ - **THEN** the system SHALL mark the operation as "PROCEDE"
46
+
47
+ #### Scenario: Generate operation report
48
+ - **WHEN** all cherry-picks are complete
49
+ - **THEN** the system SHALL generate a summary showing PROCEDE/NO PROCEDE status for each branch
@@ -0,0 +1,37 @@
1
+ ## Purpose
2
+
3
+ Proporcionar la estructura base de la CLI con manejo de argumentos, configuración y logging para el proceso de release cherry-pick.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: CLI entry point
8
+ The system SHALL provide a CLI entry point that can be executed via `node` or as a global command after installation.
9
+
10
+ #### Scenario: Execute CLI command
11
+ - **WHEN** user runs `npx release-cherry-pick` or the installed CLI command
12
+ - **THEN** the CLI SHALL initialize and display the main menu or execute the specified command
13
+
14
+ ### Requirement: Argument parsing
15
+ The system SHALL parse command-line arguments to determine the operation mode.
16
+
17
+ #### Scenario: Parse --help argument
18
+ - **WHEN** user runs `release-cherry-pick --help`
19
+ - **THEN** the system SHALL display usage information and available commands
20
+
21
+ #### Scenario: Parse --version argument
22
+ - **WHEN** user runs `release-cherry-pick --version`
23
+ - **THEN** the system SHALL display the current version number
24
+
25
+ ### Requirement: Logging system
26
+ The system SHALL implement a logging system that outputs messages to the console.
27
+
28
+ #### Scenario: Log info messages
29
+ - **WHEN** the system needs to display informational messages
30
+ - **THEN** messages SHALL be displayed in green color for success, yellow for warnings, and red for errors
31
+
32
+ ### Requirement: Error handling
33
+ The system SHALL handle errors gracefully and provide meaningful error messages.
34
+
35
+ #### Scenario: Handle missing dependencies
36
+ - **WHEN** required system dependencies are missing (git, node)
37
+ - **THEN** the system SHALL display a clear error message indicating which dependency is missing and how to install it
@@ -0,0 +1,52 @@
1
+ ## Purpose
2
+
3
+ Gestionar configuraciones persistentes incluyendo ramas, proveedores Git y opciones de IA para el proceso de release.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: Configuration file storage
8
+ The system SHALL store configuration in a `.release-cherry-pick.json` file in the project root.
9
+
10
+ #### Scenario: Create configuration file
11
+ - **WHEN** the configuration file does not exist
12
+ - **THEN** the system SHALL create it with default values and prompt the user for initial setup
13
+
14
+ #### Scenario: Load existing configuration
15
+ - **WHEN** the configuration file exists
16
+ - **THEN** the system SHALL load and validate the configuration before proceeding
17
+
18
+ ### Requirement: Branch configuration
19
+ The system SHALL allow users to configure branch naming patterns.
20
+
21
+ #### Scenario: Configure branch prefix
22
+ - **WHEN** user configures branch prefix
23
+ - **THEN** the system SHALL store the prefix and use it when creating release branches
24
+
25
+ #### Scenario: Configure staging branch name
26
+ - **WHEN** user configures the staging branch name
27
+ - **THEN** the system SHALL use this as the base for creating release branches
28
+
29
+ ### Requirement: GitLab provider configuration
30
+ The system SHALL store GitLab connection settings.
31
+
32
+ #### Scenario: Configure GitLab URL
33
+ - **WHEN** user provides GitLab instance URL
34
+ - **THEN** the system SHALL store the URL and validate connectivity
35
+
36
+ #### Scenario: Configure GitLab token
37
+ - **WHEN** user provides personal access token
38
+ - **THEN** the system SHALL store the token securely and validate permissions
39
+
40
+ ### Requirement: AI provider configuration
41
+ The system SHALL optionally store AI provider settings for generating MR descriptions.
42
+
43
+ #### Scenario: Configure AI provider
44
+ - **WHEN** user enables AI description generation
45
+ - **THEN** the system SHALL store provider settings and API keys
46
+
47
+ ### Requirement: Configuration validation
48
+ The system SHALL validate all configuration values before proceeding with operations.
49
+
50
+ #### Scenario: Validate required fields
51
+ - **WHEN** configuration is loaded
52
+ - **THEN** the system SHALL verify all required fields are present and valid
@@ -0,0 +1,38 @@
1
+ ## Purpose
2
+
3
+ Generar documentación automática AGENTS.md y RPD.md como parte del proceso de release.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: AGENTS.md generation
8
+ The system SHALL generate an AGENTS.md file documenting the project structure and conventions.
9
+
10
+ #### Scenario: Generate AGENTS.md
11
+ - **WHEN** release process completes successfully
12
+ - **THEN** the system SHALL create AGENTS.md with project overview, architecture, and conventions
13
+
14
+ #### Scenario: Include code conventions
15
+ - **WHEN** generating AGENTS.md
16
+ - **THEN** the system SHALL document coding standards, file structure, and naming conventions
17
+
18
+ ### Requirement: RPD.md generation
19
+ The system SHALL generate an RPD.md (Release Process Document) file.
20
+
21
+ #### Scenario: Generate RPD.md
22
+ - **WHEN** release process completes
23
+ - **THEN** the system SHALL create RPD.md documenting the release process, steps taken, and results
24
+
25
+ #### Scenario: Include release details
26
+ - **WHEN** generating RPD.md
27
+ - **THEN** the system SHALL include branch names, commit hashes, and MR links
28
+
29
+ ### Requirement: Documentation placement
30
+ The system SHALL place generated documentation in the correct location.
31
+
32
+ #### Scenario: Save to project root
33
+ - **WHEN** generating documentation files
34
+ - **THEN** the system SHALL save AGENTS.md and RPD.md in the project root directory
35
+
36
+ #### Scenario: Overwrite existing files
37
+ - **WHEN** documentation files already exist
38
+ - **THEN** the system SHALL ask user whether to overwrite or skip
@@ -0,0 +1,49 @@
1
+ ## Purpose
2
+
3
+ Integrar con la API de GitLab para crear Merge Requests automatizados con títulos y descripciones generadas.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: GitLab authentication
8
+ The system SHALL authenticate with GitLab using personal access tokens.
9
+
10
+ #### Scenario: Validate token permissions
11
+ - **WHEN** user provides GitLab token
12
+ - **THEN** the system SHALL validate the token has required permissions (api scope)
13
+
14
+ #### Scenario: Handle authentication failure
15
+ - **WHEN** token is invalid or expired
16
+ - **THEN** the system SHALL display clear error message and prompt for new token
17
+
18
+ ### Requirement: MR creation
19
+ The system SHALL create Merge Requests in GitLab.
20
+
21
+ #### Scenario: Create MR with title format
22
+ - **WHEN** creating a Merge Request
23
+ - **THEN** the system SHALL use format `[TASK-ID] Description` as title
24
+
25
+ #### Scenario: Set MR source and target branches
26
+ - **WHEN** creating a Merge Request
27
+ - **THEN** the system SHALL set source branch as release branch and target as staging
28
+
29
+ #### Scenario: Add MR description
30
+ - **WHEN** creating a Merge Request
31
+ - **THEN** the system SHALL generate description from source branch commits
32
+
33
+ ### Requirement: AI-powered descriptions
34
+ The system SHALL optionally use AI to generate MR descriptions.
35
+
36
+ #### Scenario: Generate AI description
37
+ - **WHEN** AI is enabled and configured
38
+ - **THEN** the system SHALL send commit messages to AI provider and use generated description
39
+
40
+ #### Scenario: Fallback to manual description
41
+ - **WHEN** AI generation fails
42
+ - **THEN** the system SHALL fall back to using commit messages directly
43
+
44
+ ### Requirement: MR link retrieval
45
+ The system SHALL retrieve the created MR URL for user reference.
46
+
47
+ #### Scenario: Get MR URL
48
+ - **WHEN** MR is successfully created
49
+ - **THEN** the system SHALL return the MR URL for display in summary
@@ -0,0 +1,37 @@
1
+ ## Purpose
2
+
3
+ Generar reportes de resumen del proceso de release con estado de cada operación y enlaces a MRs creados.
4
+
5
+ ## ADDED Requirements
6
+
7
+ ### Requirement: Operation summary generation
8
+ The system SHALL generate a comprehensive summary after completing the release process.
9
+
10
+ #### Scenario: Display release summary
11
+ - **WHEN** release process completes
12
+ - **THEN** the system SHALL display a summary table with branch name, status (PROCEDE/NO PROCEDE), and MR link
13
+
14
+ #### Scenario: Include timestamp
15
+ - **WHEN** generating summary
16
+ - **THEN** the system SHALL include the date and time of the release operation
17
+
18
+ ### Requirement: MR link tracking
19
+ The system SHALL track and display MR links for each created Merge Request.
20
+
21
+ #### Scenario: Display MR links
22
+ - **WHEN** MRs are created
23
+ - **THEN** the system SHALL display clickable links to each MR in GitLab
24
+
25
+ ### Requirement: Export summary
26
+ The system SHALL allow exporting the summary to a file.
27
+
28
+ #### Scenario: Export to markdown
29
+ - **WHEN** user requests export
30
+ - **THEN** the system SHALL save the summary as a markdown file in the project root
31
+
32
+ ### Requirement: Conflict reporting
33
+ The system SHALL provide detailed information about conflicts.
34
+
35
+ #### Scenario: Report conflicting files
36
+ - **WHEN** cherry-pick fails due to conflicts
37
+ - **THEN** the system SHALL list the specific files that have conflicts
@@ -0,0 +1,70 @@
1
+ ## 1. Project Setup
2
+
3
+ - [x] 1.1 Initialize Node.js project with `npm init` and verify package.json is created
4
+ - [x] 1.2 Install dependencies: commander, inquirer, simple-git, axios, chalk
5
+ - [x] 1.3 Create project structure: src/cli/, src/config/, src/git/, src/gitlab/, src/utils/
6
+ - [x] 1.4 Create entry point file `src/index.js` and verify it runs without errors
7
+
8
+ ## 2. CLI Core Implementation
9
+
10
+ - [x] 2.1 Implement Commander.js setup with basic commands in `src/cli/index.js`
11
+ - [x] 2.2 Implement logging system with colored output in `src/utils/logger.js`
12
+ - [x] 2.3 Implement error handling middleware in `src/utils/errors.js`
13
+ - [x] 2.4 Create help command and verify `--help` displays usage information
14
+
15
+ ## 3. Configuration Management
16
+
17
+ - [x] 3.1 Create configuration loader in `src/config/loader.js`
18
+ - [x] 3.2 Implement default configuration template
19
+ - [x] 3.3 Create configuration validation function
20
+ - [x] 3.4 Implement interactive configuration setup wizard
21
+ - [x] 3.5 Test configuration load/save/validate cycle
22
+
23
+ ## 4. Branch Selection
24
+
25
+ - [x] 4.1 Implement branch list file parser in `src/git/branch-parser.js`
26
+ - [x] 4.2 Create interactive branch selection with Inquirer.js in `src/git/branch-selector.js`
27
+ - [x] 4.3 Implement branch search/filter functionality
28
+ - [x] 4.4 Add branch validation (exists, mergeable)
29
+ - [x] 4.5 Test branch selection with both file and interactive modes
30
+
31
+ ## 5. Cherry-Pick Orchestration
32
+
33
+ - [x] 5.1 Create release branch creator in `src/git/release-branch.js`
34
+ - [x] 5.2 Implement cherry-pick executor in `src/git/cherry-pick.js`
35
+ - [x] 5.3 Add conflict detection and reporting
36
+ - [x] 5.4 Implement PROCEDE/NO PROCEDE status tracking
37
+ - [x] 5.5 Create operation summary generator
38
+ - [x] 5.6 Test complete cherry-pick flow with mock branches
39
+
40
+ ## 6. GitLab Integration
41
+
42
+ - [x] 6.1 Create GitLab client in `src/gitlab/client.js`
43
+ - [x] 6.2 Implement token validation and authentication
44
+ - [x] 6.3 Create MR creator with title format `[TASK-ID] Description`
45
+ - [x] 6.4 Implement MR description generator from commits
46
+ - [x] 6.5 Add optional AI description generation
47
+ - [x] 6.6 Test GitLab API calls with mock responses
48
+
49
+ ## 7. Release Summary
50
+
51
+ - [x] 7.1 Create summary generator in `src/report/summary.js`
52
+ - [x] 7.2 Implement summary display with table format
53
+ - [x] 7.3 Add MR link tracking and display
54
+ - [x] 7.4 Implement markdown export functionality
55
+ - [x] 7.5 Test summary generation with sample data
56
+
57
+ ## 8. Documentation Generation
58
+
59
+ - [x] 8.1 Create AGENTS.md generator in `src/doc/agents-generator.js`
60
+ - [x] 8.2 Create RPD.md generator in `src/doc/rpd-generator.js`
61
+ - [x] 8.3 Implement file overwrite confirmation
62
+ - [x] 8.4 Test documentation generation in project root
63
+
64
+ ## 9. Integration and Testing
65
+
66
+ - [x] 9.1 Create main orchestration flow in `src/workflow/release.js`
67
+ - [x] 9.2 Integrate all modules into complete release workflow
68
+ - [x] 9.3 Create end-to-end test with sample repository
69
+ - [x] 9.4 Verify all specs are implemented correctly
70
+ - [x] 9.5 Create README.md with usage instructions
@@ -0,0 +1,32 @@
1
+ schema: spec-driven
2
+
3
+ # Project context (optional)
4
+ # This is shown to AI when creating artifacts.
5
+ # Add your tech stack, conventions, style guides, domain knowledge, etc.
6
+ # Example:
7
+ # context: |
8
+ # Tech stack: TypeScript, React, Node.js
9
+ # We use conventional commits
10
+ # Domain: e-commerce platform
11
+
12
+ # Per-artifact rules (optional)
13
+ # Add custom rules for specific artifacts.
14
+ # Example:
15
+ # rules:
16
+ # proposal:
17
+ # - Keep proposals under 500 words
18
+ # - Always include a "Non-goals" section
19
+ # tasks:
20
+ # - Break tasks into chunks of max 2 hours
21
+
22
+ # Per-operation guidance (optional)
23
+ # Add advisory guidance for how apply and archive work should be conducted.
24
+ # This is separate from artifact rules above.
25
+ # Example:
26
+ # operations:
27
+ # apply:
28
+ # guidance:
29
+ # - Keep test summaries concise
30
+ # archive:
31
+ # guidance:
32
+ # - Summarize the archive outcome before finishing
File without changes
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "release-cherry-pick",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "CLI tool for automating release cherry-pick and GitLab MR creation",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "release-cherry-pick": "./src/index.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node src/index.js",
11
+ "lint": "eslint .",
12
+ "lint:fix": "eslint . --fix",
13
+ "sandbox:create": "bash scripts/sandbox/make-sandbox.sh",
14
+ "sandbox:run": "node scripts/sandbox/run-release.js",
15
+ "sandbox:config": "node scripts/sandbox/run-config.js",
16
+ "test:package": "node scripts/sandbox/test-package.js",
17
+ "setup": "husky"
18
+ },
19
+ "lint-staged": {
20
+ "*.js": "eslint --fix"
21
+ },
22
+ "keywords": [
23
+ "cli",
24
+ "git",
25
+ "cherry-pick",
26
+ "gitlab",
27
+ "release"
28
+ ],
29
+ "author": "",
30
+ "license": "MIT",
31
+ "type": "commonjs",
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
35
+ "dependencies": {
36
+ "@anthropic-ai/sdk": "^0.32.0",
37
+ "chalk": "^4.1.2",
38
+ "commander": "^15.0.0",
39
+ "inquirer": "^8.2.7",
40
+ "inquirer-autocomplete-prompt": "^2.0.0",
41
+ "inquirer-checkbox-plus-prompt": "^1.4.2",
42
+ "simple-git": "^4.0.2"
43
+ },
44
+ "devDependencies": {
45
+ "@eslint/js": "^10.0.1",
46
+ "eslint": "^10.11.0",
47
+ "husky": "^9.1.7",
48
+ "lint-staged": "^17.5.1"
49
+ }
50
+ }
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+
3
+ // Shared setup for the sandbox runners: parses the common flags, chdirs into the sandbox, makes
4
+ // every Inquirer prompt answer itself and, with --fake-gitlab, replaces the GitLab REST API with a fake.
5
+ //
6
+ // Common flags:
7
+ // --work <dir> sandbox clone to run in (default: $TMPDIR/release-cherry-pick-sandbox/work)
8
+ // --tool <dir> tool to load instead of this checkout (e.g. an installed copy under
9
+ // <prefix>/node_modules/release-cherry-pick) — inquirer is resolved from it
10
+ // --answer name=value force the answer of the prompt named `name` (repeatable); value is parsed
11
+ // as JSON when possible, e.g. --answer autoCreateMR=true --answer 'x=["a"]'
12
+ // --fake-gitlab intercept fetch() calls to <host>/api/v4 (GET /user, project members, POST
13
+ // merge_requests — which prints the request body and returns a fake URL), so
14
+ // the real src/gitlab/client.js runs with no GitLab; sets a fake GITLAB_TOKEN
15
+ //
16
+ // Auto-answers (when not forced): list/searchable list -> its default if any, else the first choice;
17
+ // checkbox -> the checked choices (or all if none are checked); input -> its default; confirm ->
18
+ // `confirmDefault` (see setup()).
19
+
20
+ const os = require('os');
21
+ const path = require('path');
22
+
23
+ const TOOL_DIR = path.resolve(__dirname, '..', '..');
24
+
25
+ const FAKE_MEMBERS = [
26
+ { id: 1, username: 'cheiner', name: 'Cheiner Reviewer' },
27
+ { id: 2, username: 'abel', name: 'Abel Developer' },
28
+ { id: 3, username: 'ariel', name: 'Ariel Developer' },
29
+ { id: 4, username: 'drobinet', name: 'D. Robinet' }
30
+ ];
31
+
32
+ function parseArgs(argv) {
33
+ const options = { workDir: path.join(os.tmpdir(), 'release-cherry-pick-sandbox', 'work'), toolDir: TOOL_DIR, answers: {}, fakeGitlab: false, rest: [] };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const arg = argv[i];
36
+ if (arg === '--work') options.workDir = path.resolve(argv[++i]);
37
+ else if (arg === '--tool') options.toolDir = path.resolve(argv[++i]);
38
+ else if (arg === '--fake-gitlab') options.fakeGitlab = true;
39
+ else if (arg === '--answer') {
40
+ const [name, ...value] = argv[++i].split('=');
41
+ const raw = value.join('=');
42
+ try {
43
+ options.answers[name] = JSON.parse(raw);
44
+ } catch {
45
+ options.answers[name] = raw;
46
+ }
47
+ } else options.rest.push(arg);
48
+ }
49
+ return options;
50
+ }
51
+
52
+ function installFakeGitlab() {
53
+ const realFetch = globalThis.fetch;
54
+ if (!process.env.GITLAB_TOKEN) {
55
+ process.env.GITLAB_TOKEN = 'fake-sandbox-token';
56
+ }
57
+
58
+ globalThis.fetch = async (url, init = {}) => {
59
+ const { pathname } = new URL(url);
60
+ if (!pathname.startsWith('/api/v4/')) {
61
+ return realFetch(url, init);
62
+ }
63
+ const method = init.method || 'GET';
64
+ const json = (status, body) => new globalThis.Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
65
+
66
+ if (method === 'GET' && pathname === '/api/v4/user') return json(200, { id: 2, username: 'abel' });
67
+ if (method === 'GET' && /\/members\/all$/.test(pathname)) return json(200, FAKE_MEMBERS);
68
+ if (method === 'POST' && /\/merge_requests$/.test(pathname)) {
69
+ const body = JSON.parse(init.body);
70
+ console.log(` [fake-gitlab] POST ${pathname} ${JSON.stringify({ ...body, description: `(${body.description.length} chars)` })}`);
71
+ return json(201, { web_url: `https://gitlab.example.com/group/project/-/merge_requests/1?source=${body.source_branch}` });
72
+ }
73
+ return json(404, { message: `fake gitlab: unsupported ${method} ${pathname}` });
74
+ };
75
+ }
76
+
77
+ function choiceValue(choice) {
78
+ return typeof choice === 'string' ? choice : choice.value;
79
+ }
80
+
81
+ function setup(argv, { confirmDefault }) {
82
+ const options = parseArgs(argv);
83
+ const toolDir = options.toolDir;
84
+
85
+ // simple-git captures the cwd when its modules load, so chdir before requiring the tool
86
+ process.chdir(options.workDir);
87
+
88
+ // Keep the sandbox's config inside the sandbox, never in the real ~/.release-cherry-pick
89
+ process.env.RELEASE_CHERRY_PICK_CONFIG_DIR = path.join(path.dirname(options.workDir), 'config');
90
+
91
+ if (options.fakeGitlab) {
92
+ installFakeGitlab();
93
+ }
94
+
95
+ // Resolved through the tool dir so --tool works for an installed copy too, where inquirer is
96
+ // hoisted next to the package instead of living inside it.
97
+ const inquirer = require(require.resolve('inquirer', { paths: [toolDir] }));
98
+ inquirer.prompt = async (questions, previous = {}) => {
99
+ const answers = { ...previous };
100
+ for (const q of [].concat(questions)) {
101
+ if (typeof q.when === 'function' && !q.when(answers)) continue;
102
+
103
+ // Searchable prompts (autocomplete / checkbox-plus) provide their choices through source()
104
+ const choices = typeof q.source === 'function' ? await q.source(answers, '') : q.choices;
105
+
106
+ let value;
107
+ if (q.name in options.answers) value = options.answers[q.name];
108
+ else if (q.type === 'list' || q.type === 'autocomplete') {
109
+ const values = choices.map(choiceValue);
110
+ value = q.default !== undefined && values.includes(q.default) ? q.default : values[0];
111
+ } else if (q.type === 'checkbox' || q.type === 'checkbox-plus') {
112
+ const checked = choices.filter(c => c.checked);
113
+ value = (checked.length > 0 ? checked : choices).map(choiceValue);
114
+ } else if (q.type === 'confirm') value = confirmDefault === 'default' ? q.default : confirmDefault;
115
+ else value = q.default;
116
+
117
+ console.log(` [auto-answer] ${q.message} -> ${JSON.stringify(value)}`);
118
+ answers[q.name] = value;
119
+ }
120
+ return answers;
121
+ };
122
+ // src/utils/prompts.js registers custom prompt types (autocomplete, checkbox-plus); since every
123
+ // prompt is answered above, registering is a no-op here.
124
+ inquirer.registerPrompt = () => {};
125
+ inquirer.prompt.registerPrompt = () => {};
126
+
127
+ return { ...options, require: (relative) => require(path.join(toolDir, relative)) };
128
+ }
129
+
130
+ module.exports = { setup, FAKE_MEMBERS };