From 9d4f4e493bb1ba813309e7e995081bbdc8dd1e3a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 21:06:58 +0000 Subject: [PATCH 1/3] Update extension to the current spec-kit and glab formats (v1.1.0) Bring the extension in line with spec-kit 1.3 and glab 1.128: - Use the standard `scripts: {sh, ps}` frontmatter with `{SCRIPT}`; the custom keys and `{SCRIPT:name}` placeholders made registration fail - Resolve the feature directory with check-prerequisites --paths-only - Reference commands with __SPECKIT_COMMAND_*__ tokens - Parse the spec-kit tasks.md ([P] = parallel, [X] = done) and spec.md (User Story N - Title (Priority: PN)) formats, keeping legacy formats - Replace glab calls that don't exist (issue create --type, issue relation, issue list --state, api --repo) with supported flags and REST API calls, with pagination and --hostname for self-hosted GitLab - Fix invalid YAML in the mapping file and make local config overrides apply per key - Add an optional after_implement hook, task_issue_type option, offline tests, CI, .extensionignore and a CHANGELOG Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FU4A2CPkCPyvBLkPvUsoVg --- .extensionignore | 5 + .github/workflows/test.yml | 30 ++ CHANGELOG.md | 47 +++ README.md | 132 ++++--- commands/close-issues.md | 115 +++--- commands/feature-to-issue.md | 105 +++--- commands/import-feature.md | 110 +++--- commands/init.md | 107 +++--- commands/status.md | 121 ++++--- commands/stories-to-issues.md | 150 ++++---- commands/sync.md | 127 +++---- commands/tasks-to-issues.md | 153 ++++---- extension.yml | 34 +- gitlab-config.template.yml | 27 +- scripts/bash/gitlab-helpers.sh | 620 +++++++++++++++++++++++++-------- tests/test-helpers.sh | 157 +++++++++ 16 files changed, 1336 insertions(+), 704 deletions(-) create mode 100644 .extensionignore create mode 100644 .github/workflows/test.yml create mode 100644 CHANGELOG.md create mode 100644 tests/test-helpers.sh diff --git a/.extensionignore b/.extensionignore new file mode 100644 index 0000000..7a5046b --- /dev/null +++ b/.extensionignore @@ -0,0 +1,5 @@ +# Files not copied into a project by `specify extension add` +tests/ +.github/ +.gitignore +CHANGELOG.md diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..e0c81c9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,30 @@ +name: Test + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + helpers: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - name: Install jq (macOS) + if: runner.os == 'macOS' + run: command -v jq || brew install jq + - name: Run helper tests + run: bash tests/test-helpers.sh + + shellcheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: ShellCheck + run: shellcheck --severity=warning -s bash scripts/bash/gitlab-helpers.sh tests/test-helpers.sh diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..290d01a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +All notable changes to this extension are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.1.0] - 2026-11-05 + +Brings the extension up to date with spec-kit 1.3 and the current glab CLI. + +### Changed + +- Requires spec-kit `>=0.12.17` and glab `>=1.50.0`; `jq` is now listed as a required tool. +- Command frontmatter uses the standard `scripts: {sh, ps}` keys with the `{SCRIPT}` placeholder. The old custom keys (`gitlab-helpers.sh: ...`) and `{SCRIPT:name}` placeholders made the registrar fail ("No runnable script variant") and were never substituted. +- The feature directory is resolved with `check-prerequisites --json --paths-only`, so commands no longer require `plan.md` and use the correct `.specify/scripts/bash/` path. +- Commands reference each other with `__SPECKIT_COMMAND_*__` tokens instead of hard-coded `/speckit.*` invocations, so they render correctly for skills-based agents. `/speckit.spec` (which doesn't exist) is replaced with the specify command. +- Task parsing follows the spec-kit `tasks.md` format: `[P]` is the parallel marker, `[US1]` the story, and `[X]` counts as done. A task inherits its priority from its story. Legacy `[P1]` markers still work. +- Story parsing follows the spec-kit `spec.md` format `### User Story 1 - Title (Priority: P1)`. The legacy `### US1: Title [P1]` format still works. +- Task IDs with four or more digits (`T1000`) are supported. +- The local override `gitlab-config.local.yml` (or `local-config.yml`) now overrides individual keys instead of replacing the whole configuration. +- The config template uses empty values instead of `${GITLAB_URL}` placeholders, since spec-kit copies it into the project on install and doesn't expand placeholders. + +### Added + +- Optional `after_implement` hook that offers to close completed tasks in GitLab. +- `mapping.task_issue_type` (`task` or `issue`) to choose the GitLab type of task issues. +- Helpers `parse_tasks`, `parse_stories`, `list_mapping_ids`, `set_task_checkbox`, `annotate_task_issue`, `glab_set_issue_type`, `glab_check_connection`, and `label_to_priority`. +- `--dry-run` for close-issues and sync, `--no-update` for status. +- Offline tests (`tests/test-helpers.sh`) and a CI workflow. +- `.extensionignore`, so tests and CI files aren't copied into projects. + +### Fixed + +- `glab issue create --type` doesn't exist; the task type is now set through the API after creation. +- `glab issue relation` doesn't exist; issues are linked with `--linked-issues` on creation or through the issue links API. +- `glab issue list --state all` doesn't exist and only returned the first 30 issues; issues are now listed through the API with pagination. +- `glab api` has no `--repo` flag; API calls use `--hostname` and the URL-encoded project path, so they work outside a clone of the GitLab project and with self-hosted instances. +- The mapping file was written as invalid YAML (`stories: {}` followed by entries). +- Sourcing the helper script no longer turns on `set -euo pipefail` in the caller's shell. +- YAML parsing works with BSD/macOS `sed` and ignores trailing comments. + +## [1.0.0] + +### Added + +- Initial release: init, feature-to-issue, import-feature, stories-to-issues, tasks-to-issues, close-issues, sync, and status commands. diff --git a/README.md b/README.md index 1ac983d..907515d 100644 --- a/README.md +++ b/README.md @@ -2,34 +2,35 @@ GitLab integration for [spec-kit](https://github.com/github/spec-kit): create issues, sync, and post status updates via the `glab` CLI. -Supports self-hosted GitLab instances. +Supports gitlab.com and self-hosted GitLab instances. ## Requirements -- **spec-kit** >= 0.1.0 -- **glab CLI** >= 1.0.0 ([GitLab CLI](https://gitlab.com/gitlab-org/cli)) +- **spec-kit** >= 0.12.17 (tested against the 1.3 extension format) +- **glab CLI** >= 1.50.0 ([GitLab CLI](https://gitlab.com/gitlab-org/cli)) +- **jq** +- **bash** (macOS, Linux, or Git Bash/WSL on Windows) ## Installation ```bash # Install and authenticate the glab CLI -brew install glab +brew install glab jq glab auth login --hostname gitlab.example.com -# Install the extension (development mode) +# Install the extension into your spec-kit project cd /path/to/your/spec-kit-project +specify extension add gitlab --from https://github.com/ohartwig/spec-kit-gitlab/archive/refs/heads/main.zip + +# ...or from a local clone (development mode) specify extension add --dev ~/spec-kit-gitlab/ ``` -## Configuration - -The easiest way is via the interactive setup: +On install, spec-kit copies the config template to `.specify/extensions/gitlab/gitlab-config.yml` and registers the commands for your coding agent. -```bash -/speckit.gitlab.init -``` +## Configuration -This creates the configuration file at `.specify/extensions/gitlab/gitlab-config.yml`: +The easiest way is the interactive setup command (`speckit.gitlab.init`, see [Invoking the commands](#invoking-the-commands)). It writes `.specify/extensions/gitlab/gitlab-config.yml`: ```yaml gitlab: @@ -43,82 +44,90 @@ labels: feature_label: "feature" mapping: - priority_to_label: true # P1/P2/P3 → priority::1/2/3 - feature_to_milestone: true # Feature name as a GitLab milestone + priority_to_label: true # Story priority P1/P2/P3 → priority::1/2/3 + feature_to_milestone: true # Feature directory name as a GitLab milestone feature_to_issue: true # Create the feature as a GitLab issue - link_tasks_to_stories: true # Link tasks to story issues + link_tasks_to_stories: true # Link task issues to story issues + task_issue_type: "task" # GitLab type for task issues: "task" or "issue" ``` -Alternatively, via environment variables: +Configuration is resolved in this order (highest first): -```bash -export GITLAB_URL="https://gitlab.example.com" -export GITLAB_PROJECT="group/project" -export GITLAB_TOKEN="glpat-xxxxxxxxxxxx" -``` +1. Environment variables `GITLAB_URL` and `GITLAB_PROJECT` +2. Local overrides in `.specify/extensions/gitlab/gitlab-config.local.yml` (per key, not committed, kept on reinstall) +3. `.specify/extensions/gitlab/gitlab-config.yml` +4. Built-in defaults + +Authentication is handled entirely by `glab` (`glab auth login`, or `GITLAB_TOKEN` with the `api` scope). Never put a token in the config file. + +## Invoking the commands + +The command names below are the extension's command IDs. How you type them depends on your coding agent, for example `/speckit.gitlab.init` for agents with slash commands, or `/speckit-gitlab-init` for agents that use skills (such as GitHub Copilot's skills layout). See spec-kit's [command invocation reference](https://github.com/github/spec-kit/blob/main/docs/integrations/cli.md#command-invocation). ## Commands -### `/speckit.gitlab.init` +### `speckit.gitlab.init` -Interactive setup of the GitLab configuration. Checks the `glab` installation, tests the connection, and writes the configuration file. +Interactive setup of the GitLab configuration. Checks `glab` and `jq`, suggests values from the git remote, tests the connection, and writes the configuration file. -### `/speckit.gitlab.feature-to-issue` +### `speckit.gitlab.feature-to-issue` -Creates a GitLab issue for the current feature and links existing story issues to it. Uses the feature directory name as the title and the context from `spec.md` as the description. Labels: `spec-kit`, `feature`. +Creates a GitLab issue for the current feature and links existing story issues to it. Uses the feature name from `spec.md` as the title and the overview section as the description. Labels: `spec-kit`, `feature`. -### `/speckit.gitlab.import-feature` +### `speckit.gitlab.import-feature` -Imports an existing GitLab issue as a feature. Argument: issue number (e.g. `232` or `#232`). Writes the mapping, optionally creates a `spec.md` from the issue description, and links existing stories. +Imports an existing GitLab issue as a feature. Argument: issue number (`232`, `#232`) or issue URL. Writes the mapping, optionally seeds `spec.md` from the issue description, and links existing stories. -### `/speckit.gitlab.stories-to-issues` +### `speckit.gitlab.stories-to-issues` -Creates GitLab issues for all user stories from `spec.md`. Expects the format `### US1: Title [P1]` and automatically assigns labels (`spec-kit`, `user-story`, `priority::X`). Automatically links new stories to the feature issue (if one exists). +Creates GitLab issues for all user stories in `spec.md`. Reads the spec-kit template format `### User Story 1 - Title (Priority: P1)` (the older `### US1: Title [P1]` still works) and sets the labels `spec-kit`, `user-story`, and `priority::N`. New stories are linked to the feature issue, if there is one. -### `/speckit.gitlab.tasks-to-issues` +### `speckit.gitlab.tasks-to-issues` -Creates GitLab issues (Type: Task) for all tasks from `tasks.md`. Expects the format `- [ ] T001 [P1] [US1] Description`. Automatically links tasks to their story issues. +Creates GitLab issues (type *Task* by default) for all tasks in `tasks.md`. Reads the spec-kit format `- [ ] T012 [P] [US1] Description`, where `[P]` marks a parallelizable task and `[US1]` the story. Tasks inherit the priority of their story and are linked to the story issue. -### `/speckit.gitlab.close-issues` +### `speckit.gitlab.close-issues` -Syncs the local completion status to GitLab. Tasks marked `[x]` in `tasks.md` are closed in GitLab; tasks reopened (`[ ]`) are reopened. Stories are automatically closed once all their tasks are complete. +Pushes the local completion status to GitLab. Tasks marked `[x]`/`[X]` in `tasks.md` are closed in GitLab, tasks reopened (`[ ]`) are reopened. Stories are closed once all their tasks are complete. Supports `--dry-run`. -### `/speckit.gitlab.sync` +### `speckit.gitlab.sync` -Syncs GitLab issue status into the local `tasks.md` files. Updates checkboxes based on issue status (open/closed). Shows the feature issue status (if one exists). Optional: imports new GitLab issues with `--import`. +Pulls the GitLab issue status into `tasks.md` (closed → `[x]`, open → `[ ]`) and shows the feature issue status. With `--import`, adds GitLab task issues that aren't in `tasks.md` yet. Supports `--dry-run`. -### `/speckit.gitlab.status` +### `speckit.gitlab.status` -Shows an overview of all GitLab issues with their current status (task ID, issue number, status, assignee) and updates `tasks.md`. Shows the feature issue status at the top of the overview. Includes progress statistics (open, closed, percent). +Shows an overview of all issues of the feature (task ID, issue number, status, assignee, story progress) and updates `tasks.md`. If local and GitLab status contradict each other, it asks which side wins. `--no-update` only shows the overview. ## Workflow -### Push workflow (Local → GitLab) +### Push workflow (local → GitLab) ``` -1. /speckit.gitlab.init → Set up the GitLab connection -2. /speckit.spec → Create spec.md -3. /speckit.gitlab.feature-to-issue → Create the feature as a GitLab issue -4. /speckit.tasks → Generate tasks.md -5. /speckit.gitlab.stories-to-issues → Stories as GitLab issues (linked to the feature) -6. /speckit.gitlab.tasks-to-issues → Tasks as GitLab issues (linked to stories) -7. /speckit.gitlab.close-issues → Close completed issues in GitLab -8. /speckit.gitlab.status → Sync status +1. speckit.gitlab.init → Set up the GitLab connection +2. speckit.specify → Create spec.md +3. speckit.gitlab.feature-to-issue → Feature as a GitLab issue +4. speckit.gitlab.stories-to-issues → Stories as GitLab issues (linked to the feature) +5. speckit.plan, speckit.tasks → Plan and generate tasks.md +6. speckit.gitlab.tasks-to-issues → Tasks as GitLab issues (linked to stories) +7. speckit.implement → Implement +8. speckit.gitlab.close-issues → Close completed issues in GitLab ``` -### Pull workflow (GitLab → Local) +### Pull workflow (GitLab → local) ``` -1. /speckit.gitlab.import-feature 232 → Import an existing issue as a feature -2. /speckit.spec → Create/refine the specification -3. /speckit.tasks → Generate tasks -4. /speckit.gitlab.stories-to-issues → Stories as GitLab issues -5. /speckit.gitlab.tasks-to-issues → Tasks as GitLab issues +1. speckit.specify → Start the feature in spec-kit +2. speckit.gitlab.import-feature 232 → Link the feature to the existing issue +3. speckit.clarify → Refine the specification +4. speckit.gitlab.stories-to-issues → Stories as GitLab issues +5. speckit.plan, speckit.tasks → Plan and generate tasks +6. speckit.gitlab.tasks-to-issues → Tasks as GitLab issues +7. speckit.gitlab.sync → Pull status changes made in GitLab ``` ## Mapping file -The extension maintains a `.gitlab-mapping.yml` in the feature directory to ensure idempotency: +The extension keeps a `.gitlab-mapping.yml` in the feature directory, so commands can be run repeatedly without creating duplicates: ```yaml feature: "#232 https://gitlab.example.com/group/project/-/issues/232" @@ -128,13 +137,22 @@ tasks: T001: "#42 https://gitlab.example.com/group/project/-/issues/42" ``` -The `feature:` field is set by `/speckit.gitlab.feature-to-issue` (push) or `/speckit.gitlab.import-feature` (pull). Stories are automatically linked to the feature issue. +Task lines in `tasks.md` also get a `` comment. The `feature:` entry is set by `speckit.gitlab.feature-to-issue` (push) or `speckit.gitlab.import-feature` (pull). + +## Hooks -This lets commands be run multiple times without creating duplicates. +- **after_tasks**: after task generation, you're asked whether to create the tasks as GitLab issues. +- **after_implement**: after implementation, you're asked whether to close completed tasks in GitLab. -## Hook +Both hooks are optional and can be turned off in `.specify/extensions.yml`. + +## Development + +```bash +bash tests/test-helpers.sh +``` -After `/speckit.tasks`, you're automatically asked whether tasks should be created as GitLab issues. +The tests cover config loading, `tasks.md`/`spec.md` parsing, and the mapping file. They run offline. `tests/`, `.github/`, and `CHANGELOG.md` are excluded from installation via `.extensionignore`. ## License diff --git a/commands/close-issues.md b/commands/close-issues.md index 35c3e53..59acea6 100644 --- a/commands/close-issues.md +++ b/commands/close-issues.md @@ -1,115 +1,114 @@ --- description: "Close completed tasks/stories in GitLab, reopen reopened ones" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Close completed issues in GitLab -Syncs the local completion status (checkboxes in `tasks.md`) to GitLab: completed tasks/stories are closed, reopened ones are reopened. - -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `tasks.md` and `.gitlab-mapping.yml` is present +Pushes the local completion status (checkboxes in `tasks.md`) to GitLab: completed tasks and stories are closed, reopened ones are reopened. This is the push direction; `__SPECKIT_COMMAND_GITLAB_SYNC__` pulls the GitLab status into `tasks.md`. ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). `--dry-run` means: show what would change, but don't change anything in GitLab. + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `tasks.md` and `.gitlab-mapping.yml` (`__SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__`) + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. - -If no feature directory is found, inform the user and abort. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR` and `TASKS`. All paths are absolute. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +``` ### Step 3: Load the mapping file and tasks.md -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml`. If no mapping file exists: -- Inform the user that `/speckit.gitlab.tasks-to-issues` must be run first -- Abort +The mapping file is `$FEATURE_DIR/.gitlab-mapping.yml`. If it doesn't exist, tell the user to run `__SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__` first and abort. + +```bash +MAPPING_PATH="$FEATURE_DIR/.gitlab-mapping.yml" +list_mapping_ids "$MAPPING_PATH" tasks # T001#42 https://... +list_mapping_ids "$MAPPING_PATH" stories # US1#10 https://... +parse_tasks "$TASKS" # ID, STATUS (open/done), STORY, ... +``` -Read `tasks.md` in the feature directory and extract for each task: -- **Task ID**: e.g. `T001` -- **Status**: `[x]` = complete, `[ ]` = open +A task's issue number comes from the mapping or, if missing there, from the ISSUE column (``). ### Step 4: Query the current GitLab status -For each issue number in the mapping file (both the `tasks:` and `stories:` sections), fetch the current status: +Fetch the state of all mapped issues in one request instead of one call per issue: ```bash -glab_view_issue "$ISSUE_NUMBER" +glab_list_issues "$GITLAB_SPECKIT_LABEL" all | jq -r '.[] | "\(.iid)\t\(.state)"' ``` -Extract the `state` (`opened` or `closed`). +For mapped issues missing from that list (for example because the label was removed), fall back to `glab_issue_state `. -### Step 5: Reconcile tasks and close/reopen issues +### Step 5: Reconcile tasks -For each task in the mapping file: +For each mapped task: -1. **Complete locally (`[x]`) + open in GitLab (`opened`)** → Close the issue: - ```bash - glab_close_issue "$ISSUE_NUMBER" - ``` +1. **Done locally + `opened` in GitLab** → `glab_close_issue ` +2. **Open locally + `closed` in GitLab** → `glab_reopen_issue ` +3. **Status matches** → skip -2. **Open locally (`[ ]`) + closed in GitLab (`closed`)** → Reopen the issue: - ```bash - glab_reopen_issue "$ISSUE_NUMBER" - ``` - -3. **Status matches** → Skip +A task that is in the mapping but no longer in `tasks.md` is reported as "orphaned" and left unchanged. ### Step 6: Reconcile stories -Stories have no checkboxes in `spec.md`. Instead, a story is considered complete when **all its tasks** are complete. +Stories have no checkboxes in `spec.md`. A story counts as done when **all** tasks with its `[USx]` marker are done. -For each story in the mapping file: +For each mapped story: -1. Determine all tasks that belong to this story (tasks with a `[USx]` reference in `tasks.md`) -2. If **all** associated tasks have `[x]` and the story issue is open → close the issue -3. If **not all** tasks are complete and the story issue is closed → reopen the issue -4. If the story has no tasks → skip +1. All its tasks done + story issue `opened` → close it +2. Not all tasks done + story issue `closed` → reopen it +3. Story has no tasks → skip -### Step 7: Reconcile the feature issue (optional) +### Step 7: Reconcile the feature issue -If a feature issue is present in the mapping file (a `feature:` entry): +If a feature issue is mapped (`read_feature_mapping "$MAPPING_PATH"`): -1. Check whether **all** story issues are closed -2. If yes and the feature issue is open → ask the user: +1. All story issues closed (and all tasks done) + feature issue open → ask the user: > All stories are complete. Should feature issue #232 be closed? -3. If not all stories are complete and the feature issue is closed → inform the user: +2. Open stories or tasks + feature issue closed → ask the user: > Feature issue #232 is closed, but there are still open stories. Should it be reopened? -### Step 8: Summary +Never close or reopen the feature issue without the user's confirmation. -Show an overview: +### Step 8: Summary ``` Issues closed/reopened for feature: ======================================================== Closed: - T001 → #42 (closed) - T003 → #44 (closed) - US1 → #10 (closed, all tasks complete) + T001 → #42 + T003 → #44 + US1 → #10 (all tasks complete) Reopened: - T002 → #43 (reopened) + T002 → #43 -Unchanged: - T004 → #45 (already closed) - T005 → #46 (already open) +Unchanged: 2 Orphaned: 0 -Summary: - Closed: 3 - Reopened: 1 - Unchanged: 2 +Closed: 3 Reopened: 1 ``` + +With `--dry-run`, show the same table under the heading "Would change" and change nothing. diff --git a/commands/feature-to-issue.md b/commands/feature-to-issue.md index 542de8e..06a6985 100644 --- a/commands/feature-to-issue.md +++ b/commands/feature-to-issue.md @@ -1,85 +1,90 @@ --- description: "Create the feature as a GitLab issue and link stories" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Create the feature as a GitLab issue Creates a GitLab issue for the current feature and links existing story issues to it. -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `spec.md` is present - ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty), for example a custom issue title. + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `spec.md` (`__SPECKIT_COMMAND_SPECIFY__`) + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. The feature directory contains `spec.md`. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR` and `FEATURE_SPEC`. All paths are absolute. -If no feature directory is found, inform the user and abort. +If `FEATURE_SPEC` doesn't exist, tell the user to run `__SPECKIT_COMMAND_SPECIFY__` first and abort. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. - -The following values are needed: -- `GITLAB_URL` - URL of the GitLab server -- `GITLAB_PROJECT` - project path -- `GITLAB_FEATURE_TO_ISSUE` - whether the feature is created as an issue -- `GITLAB_FEATURE_LABEL` - label for feature issues -- `GITLAB_FEATURE_TO_MILESTONE` - whether the feature is mapped to a milestone +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +``` -If `GITLAB_FEATURE_TO_ISSUE` is not `true`, inform the user and abort: +If `GITLAB_FEATURE_TO_ISSUE` is not `true`, tell the user and abort: > Feature-to-issue is disabled in the configuration (`feature_to_issue: false`). ### Step 3: Check idempotency -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml` (if present). Check the `feature:` entry with `read_feature_mapping`. +```bash +MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" +read_feature_mapping "$MAPPING_PATH" +``` -If a feature issue is already mapped, show the existing mapping and abort: +If a feature issue is already mapped, show it and stop creating; continue with Step 6 to link stories that aren't linked yet: > Feature issue already exists: #232 (https://...) -> Skipping creation. ### Step 4: Create the feature issue -1. **Determine the feature name**: directory name of the feature directory (e.g. `user-authentication`). +1. **Title:** the feature name from the first heading of `spec.md` (`# Feature Specification: `). Fall back to the directory name (`get_feature_name "$FEATURE_DIR"`, e.g. `001-user-auth`). -2. **Extract the description** from `spec.md`: read the content before `## User Stories` (overview/context of the feature). If `## User Stories` doesn't exist, use the entire content of `spec.md`. +2. **Description:** from `spec.md`, the content before `## User Scenarios & Testing` (or the legacy `## User Stories`), plus a short list of the user stories (`parse_stories "$FEATURE_SPEC"`) and a reference line: + ```markdown + + ``` + If neither heading exists, use the whole `spec.md`. Keep the description under 1 MB. -3. **Assemble labels:** - - Always: `spec-kit`, the configured `GITLAB_FEATURE_LABEL` (default: `feature`) +3. **Labels:** `$GITLAB_SPECKIT_LABEL,$GITLAB_FEATURE_LABEL` -4. **Determine the milestone** (if `feature_to_milestone: true`): +4. **Milestone** (if `GITLAB_FEATURE_TO_MILESTONE` is `true`): ```bash MILESTONE_TITLE="$(glab_ensure_milestone "$(get_feature_name "$FEATURE_DIR")")" ``` -5. **Create the issue** via `glab_create_issue`: - - Title: feature name (human-readable, e.g. `user-authentication`) - - Description: extracted context from `spec.md` - - Labels: `spec-kit,feature` - - Milestone: if set, `MILESTONE_TITLE` - -6. **Extract the issue URL and number** from the output. +5. **Create the issue:** + ```bash + OUT="$(glab_create_issue "$TITLE" "$DESCRIPTION" "$LABELS" "$MILESTONE_TITLE")" + ISSUE_URL="$(extract_issue_url "$OUT")" + ISSUE_NUMBER="$(extract_issue_number "$OUT")" + ``` + If no issue URL comes back, show the glab output and abort. ### Step 5: Write the mapping -Write the feature mapping to `FEATURE_DIR/.gitlab-mapping.yml`: - ```bash write_feature_mapping "$MAPPING_PATH" "$ISSUE_NUMBER" "$ISSUE_URL" ``` -This produces e.g.: +Result: ```yaml feature: "#232 https://gitlab.example.com/group/project/-/issues/232" stories: @@ -89,22 +94,24 @@ tasks: {} ### Step 6: Link existing stories -Read all entries from `stories:` in the mapping file. For each story entry: +```bash +FEATURE_IID="$(extract_feature_issue_number "$(read_feature_mapping "$MAPPING_PATH")")" +list_mapping_ids "$MAPPING_PATH" stories # prints "US1#10 https://..." +``` -1. Extract the story issue number -2. Link the story issue to the feature issue: - ```bash - glab_add_relation "$STORY_ISSUE_NUMBER" "$FEATURE_ISSUE_NUMBER" - ``` +For each story, link it to the feature issue (existing links are ignored): + +```bash +glab_add_relation "$(extract_mapping_issue_number "$VALUE")" "$FEATURE_IID" +``` -If no stories are present, skip this step with a note: +If there are no stories yet: > No existing story issues found to link. ### Step 7: Summary -Show an overview: -- Feature issue created: `#232 - user-authentication` -- URL: `https://gitlab.example.com/.../issues/232` -- Milestone: if set +Show: +- Feature issue: `#232 - ` and its URL +- Milestone, if set - Linked stories: count and list -- Note: "Run `/speckit.gitlab.stories-to-issues` to create new stories — they will be linked automatically." +- Next step: `__SPECKIT_COMMAND_GITLAB_STORIES-TO-ISSUES__` creates story issues that are linked automatically. diff --git a/commands/import-feature.md b/commands/import-feature.md index 076fceb..bce0afc 100644 --- a/commands/import-feature.md +++ b/commands/import-feature.md @@ -1,125 +1,127 @@ --- description: "Import an existing GitLab issue as a feature" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Import a GitLab issue as a feature Takes an existing GitLab issue and adopts it as a feature in spec-kit. -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) - ## User Input +```text $ARGUMENTS +``` + +The argument is the **issue number** of the GitLab issue to import (e.g. `232`, `#232`, or the issue URL). + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) -The argument is the **issue number** of the GitLab issue to import (e.g. `232` or `#232`). +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the issue number -Extract the issue number from the argument. Accept formats such as `232`, `#232`, or a full GitLab URL. +Extract the issue number from the argument: `232`, `#232`, or a URL ending in `/-/issues/232`. If the URL points to a different project than the configured one, warn the user and abort. If no argument was passed, ask the user for the issue number. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +``` ### Step 3: Fetch the issue from GitLab -Fetch the issue details: - ```bash -glab_view_issue "$ISSUE_NUMBER" +glab_view_issue "$ISSUE_NUMBER" | jq '{iid, title, description, state, labels, web_url}' ``` -Extract: -- **Title**: e.g. `user-authentication` -- **Description**: issue body -- **Status**: `opened` or `closed` -- **Labels**: current labels -- **URL**: web URL of the issue - -If the issue is not found, inform the user and abort. +If the issue is not found, tell the user and abort. ### Step 4: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. +Run `{SCRIPT}` from the project root and parse `FEATURE_DIR` from the JSON output. -If no feature directory is found: -- Derive the directory name from the issue title (lowercase, spaces replaced with hyphens) -- Inform the user of the proposed path -- Ask whether the directory should be created +If there is no active feature, or its directory doesn't exist yet, don't create one by hand. Tell the user to start the feature with spec-kit and pass the issue as input, for example: + +> `__SPECKIT_COMMAND_SPECIFY__ <issue title> (GitLab #232)` + +Then run this command again; it links the new feature directory to the issue. (spec-kit's specify command creates the numbered feature directory and branch.) ### Step 5: Check idempotency -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml` (if present). Check the `feature:` entry. +```bash +MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" +read_feature_mapping "$MAPPING_PATH" +``` -If a different feature issue is already mapped, warn the user: +If a different feature issue is already mapped, ask the user: > The feature directory is already linked to issue #XYZ. > Should the mapping be updated to #232? ### Step 6: Write the mapping -Initialize the mapping file (if needed) and write the feature mapping: - ```bash -MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" write_feature_mapping "$MAPPING_PATH" "$ISSUE_NUMBER" "$ISSUE_URL" ``` -### Step 7: Optional — spec.md seed +Add the labels `$GITLAB_SPECKIT_LABEL` and `$GITLAB_FEATURE_LABEL` to the issue if they're missing: + +```bash +glab_cmd issue update "$ISSUE_NUMBER" --label "$GITLAB_SPECKIT_LABEL,$GITLAB_FEATURE_LABEL" +``` + +### Step 7: Optional — seed spec.md -If no `spec.md` exists yet in the feature directory and the issue has a description: +If `spec.md` doesn't exist yet or is still the empty template, and the issue has a description: -1. Create an initial `spec.md` using the issue description as a starting point: +1. Create `spec.md` from the issue: ```markdown - # Feature Title - - <!-- Imported from GitLab issue #232 --> + # Feature Specification: <issue title> - <Issue description> + <!-- Imported from GitLab issue #232: <issue URL> --> - ## User Stories + **Input**: GitLab issue #232 - <!-- Create user stories with /speckit.spec --> + <issue description> ``` -2. Inform the user: +2. Tell the user: > `spec.md` was seeded with the issue description. - > Refine the specification with `/speckit.spec`. + > Refine it with `__SPECKIT_COMMAND_SPECIFY__` or `__SPECKIT_COMMAND_CLARIFY__`. -If `spec.md` already exists, skip this step. +If `spec.md` already has content, don't change it. ### Step 8: Link existing stories -If story issues are present in the mapping file (the `stories:` section), link them to the feature issue: +For each entry from `list_mapping_ids "$MAPPING_PATH" stories`, link the story issue to the feature issue: ```bash -glab_add_relation "$STORY_ISSUE_NUMBER" "$FEATURE_ISSUE_NUMBER" +glab_add_relation "$(extract_mapping_issue_number "$VALUE")" "$ISSUE_NUMBER" ``` ### Step 9: Summary and next steps -Show an overview: -- Imported issue: `#232 - user-authentication` -- Status: `Open` -- Feature directory: `<path>` +Show: +- Imported issue: `#232 - <title>` (Open/Closed) +- Feature directory - Mapping written: yes -- spec.md seed: created / skipped (already present) +- spec.md seed: created / skipped - Linked stories: count Next steps: ``` -1. /speckit.spec → Create/refine the specification -2. /speckit.tasks → Generate tasks -3. /speckit.gitlab.stories-to-issues → Stories as GitLab issues -4. /speckit.gitlab.tasks-to-issues → Tasks as GitLab issues +1. __SPECKIT_COMMAND_SPECIFY__ / __SPECKIT_COMMAND_CLARIFY__ → Create or refine the specification +2. __SPECKIT_COMMAND_GITLAB_STORIES-TO-ISSUES__ → Stories as GitLab issues +3. __SPECKIT_COMMAND_PLAN__, __SPECKIT_COMMAND_TASKS__ → Plan and generate tasks +4. __SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__ → Tasks as GitLab issues ``` diff --git a/commands/init.md b/commands/init.md index 0aeb90a..8ceff55 100644 --- a/commands/init.md +++ b/commands/init.md @@ -1,109 +1,105 @@ --- description: "Interactively set up the GitLab configuration" -scripts: - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" --- # Set up the GitLab configuration Interactively sets up the GitLab integration by asking for all necessary configuration values and writing them to the config file. +## User Input + +```text +$ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). It may already contain values such as the GitLab URL or project path; use them instead of asking again. + ## Prerequisites -- `glab` CLI is installed -- spec-kit GitLab extension is installed (`specify extension add --dev ~/spec-kit-gitlab/`) +- `glab` CLI (>= 1.50) and `jq` are installed +- The spec-kit GitLab extension is installed (`specify extension add --dev /path/to/spec-kit-gitlab`) -## User Input +## Notes -$ARGUMENTS +- Run all commands from the project root. +- The helper functions live in `.specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh`. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. +- Never write a token into the configuration file. ## Steps -### Step 1: Check whether the glab CLI is available - -Check whether `glab` is installed: +### Step 1: Check the required tools ```bash -command -v glab +command -v glab && glab version +command -v jq ``` -If not present, inform the user: +If `glab` is missing, tell the user how to install it: - macOS: `brew install glab` -- Linux: see https://gitlab.com/gitlab-org/cli +- Linux/Windows: see https://gitlab.com/gitlab-org/cli#installation + +If `jq` is missing: `brew install jq`, `apt-get install jq`, or see https://jqlang.org/download/. ### Step 2: Check for an existing configuration -Check whether a configuration file already exists at `.specify/extensions/gitlab/gitlab-config.yml`. +The configuration lives at `.specify/extensions/gitlab/gitlab-config.yml`. Spec Kit copies the template there when the extension is installed, so the file usually exists but has an empty `url` and `project`. -If so, read the existing values and show them to the user. Ask whether they want to update or keep them. +If it already contains a URL and project, show the current values and ask whether to update or keep them. If the user keeps them, continue with Step 9 (connection test). ### Step 3: Ask for the GitLab URL -Ask the user for the GitLab server URL: - > **GitLab server URL?** -> e.g. `https://gitlab.example.com` or `https://gitlab.moselwal.io` +> e.g. `https://gitlab.example.com` Validation: - Must start with `https://` or `http://` -- No trailing slash +- Remove a trailing slash -If the `GITLAB_URL` environment variable is set, suggest it as the default. +If the `GITLAB_URL` environment variable is set, or the project's git remote points to a GitLab host (`git config --get remote.origin.url`), suggest that as the default. ### Step 4: Ask for the GitLab project -Ask the user for the project path: - > **GitLab project path?** > e.g. `group/project` or `group/subgroup/project` -If `glab` is already authenticated, try listing the available projects as a helper: - -```bash -glab repo list --output json 2>/dev/null | head -20 -``` - -If the `GITLAB_PROJECT` environment variable is set, suggest it as the default. +If the git remote points to the same host, suggest the path from the remote URL (without `.git`). If the `GITLAB_PROJECT` environment variable is set, suggest it as the default. ### Step 5: Check glab authentication -Check whether `glab` is authenticated for the given GitLab server: - ```bash glab auth status --hostname <gitlab-host> ``` -If not authenticated, inform the user: +`<gitlab-host>` is the host part of the URL (for example `gitlab.example.com`). + +If not authenticated, tell the user: > `glab` is not authenticated for `<gitlab-host>`. -> Please run: `glab auth login --hostname <gitlab-host>` -> Or set the environment variable: `export GITLAB_TOKEN="glpat-..."` +> Run `glab auth login --hostname <gitlab-host>` in your terminal, +> or export a token: `export GITLAB_TOKEN="glpat-..."` (scope: `api`). -Ask whether to continue anyway (the config can be written even without auth). +Ask whether to continue anyway (the config can be written without auth). ### Step 6: Ask for the label configuration -Ask the user for the labels (with defaults): +Ask for the labels (with defaults). Most users accept the defaults: > **Label for user stories?** (Default: `user-story`) > **Label for tasks?** (Default: `task`) > **Label for spec-kit tracking?** (Default: `spec-kit`) > **Label for feature issues?** (Default: `feature`) -Most users will accept the defaults. - ### Step 7: Ask for mapping options -Ask about the mapping options (with defaults): - -> **Map priority to a label?** (e.g. P1 → `priority::1`) (Default: yes) -> **Link tasks to story issues?** (Default: yes) -> **Create the feature as a milestone?** (The feature name is used as the GitLab milestone) (Default: yes) -> **Create the feature as a GitLab issue?** (Creates a parent issue per feature) (Default: yes) +> **Map story priority to a label?** (P1 → `priority::1`) (Default: yes) +> **Link tasks to their story issues?** (Default: yes) +> **Use the feature as a milestone?** (The feature directory name becomes a GitLab milestone) (Default: yes) +> **Create the feature as a GitLab issue?** (A parent issue per feature) (Default: yes) +> **GitLab type for task issues?** `task` or `issue` (Default: `task`; use `issue` if your GitLab version or license doesn't support the task type) ### Step 8: Write the configuration file -Create the configuration file at `.specify/extensions/gitlab/gitlab-config.yml`: +Make sure `.specify/extensions/gitlab/` exists, then write `.specify/extensions/gitlab/gitlab-config.yml`: ```yaml gitlab: @@ -121,19 +117,19 @@ mapping: feature_to_milestone: <true/false> feature_to_issue: <true/false> link_tasks_to_stories: <true/false> + task_issue_type: "<task/issue>" ``` -Make sure the `.specify/extensions/gitlab/` directory exists. - ### Step 9: Test the connection If `glab` is authenticated, test the connection: ```bash -glab api projects/:id --repo "<project-path>" 2>/dev/null +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +load_gitlab_config && glab_check_connection ``` -On success show: +On success (a project URL is printed): > Connection to `<gitlab-url>` successful. Project `<project>` found. On failure: @@ -141,21 +137,20 @@ On failure: ### Step 10: Summary and next steps -Show a summary of the written configuration and the next steps: - ``` GitLab configuration saved. Server: <url> Project: <project> - Labels: <speckit-label>, <story-label>, <task-label> + Labels: <speckit-label>, <story-label>, <task-label>, <feature-label> Next steps: - 1. /speckit.spec → Create the specification - 2. /speckit.tasks → Generate tasks - 3. /speckit.gitlab.stories-to-issues → Stories as GitLab issues - 4. /speckit.gitlab.tasks-to-issues → Tasks as GitLab issues + 1. __SPECKIT_COMMAND_SPECIFY__ → Create the specification + 2. __SPECKIT_COMMAND_GITLAB_FEATURE-TO-ISSUE__ → Feature as a GitLab issue + 3. __SPECKIT_COMMAND_GITLAB_STORIES-TO-ISSUES__ → Stories as GitLab issues + 4. __SPECKIT_COMMAND_PLAN__ and __SPECKIT_COMMAND_TASKS__ → Plan and generate tasks + 5. __SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__ → Tasks as GitLab issues -Tip: The config can be updated at any time with /speckit.gitlab.init. +Tip: Run __SPECKIT_COMMAND_GITLAB_INIT__ again at any time to change the config. Local overrides: .specify/extensions/gitlab/gitlab-config.local.yml ``` diff --git a/commands/status.md b/commands/status.md index 165a865..62bd317 100644 --- a/commands/status.md +++ b/commands/status.md @@ -1,96 +1,97 @@ --- -description: "Update the status of GitLab issues in tasks.md and show an overview" +description: "Show GitLab issue status and update tasks.md" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- -# Sync GitLab issue status +# GitLab issue status -Update the status of the tasks in `tasks.md` based on the current GitLab issue status and show an overview. - -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `tasks.md` and `.gitlab-mapping.yml` is present +Shows an overview of the feature's GitLab issues and updates the checkboxes in `tasks.md` to match GitLab. ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). `--no-update` means: only show the overview, don't change `tasks.md`. + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `tasks.md` and `.gitlab-mapping.yml` + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. - -If no feature directory is found, inform the user and abort. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR` and `TASKS`. All paths are absolute. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +MAPPING_PATH="$FEATURE_DIR/.gitlab-mapping.yml" +``` -### Step 3: Load the mapping file +### Step 3: Load the mapping -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml`. This contains the mapping of task IDs to GitLab issue numbers. +```bash +list_mapping_ids "$MAPPING_PATH" tasks +list_mapping_ids "$MAPPING_PATH" stories +parse_tasks "$TASKS" +``` -If no mapping file exists, check `tasks.md` for `<!-- gitlab:#123 -->` comments and build a temporary mapping from those. +If there is no mapping file, build a temporary mapping from the ISSUE column of `parse_tasks` (`<!-- gitlab:#123 -->` comments). -If neither a mapping file nor comments are present: -- Inform the user that `/speckit.gitlab.tasks-to-issues` must be run first -- Abort +If neither exists, tell the user to run `__SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__` first and abort. -### Step 4: Query the status of each issue +### Step 4: Query the issues -For each issue number in the mapping file: +Fetch all spec-kit issues in one request: ```bash -glab issue view <issue-number> --repo "$GITLAB_PROJECT" --output json +glab_list_issues "$GITLAB_SPECKIT_LABEL" all \ + | jq -r '.[] | [.iid, .state, ((.assignees // []) | map("@" + .username) | join(" ")), .updated_at] | @tsv' ``` -Extract: -- **Status**: `opened` or `closed` -- **Labels**: current labels -- **Assignee**: assigned person (if any) -- **Updated at**: last update date - -### Step 5: Update tasks.md +For mapped issues missing from that list, fall back to `glab_view_issue <iid>`. -For each task with an assigned GitLab issue: +### Step 5: Detect discrepancies -1. **Closed issue** → set `[x]` in tasks.md -2. **Open issue** → set `[ ]` in tasks.md +Compare the local checkbox (STATUS from `parse_tasks`) with the GitLab state. Collect tasks where they differ: +- `[x]` locally, but the issue is open +- `[ ]` locally, but the issue is closed -Only make actual changes (avoid unnecessary writes). +### Step 6: Update tasks.md -### Step 6: Show the overview +Unless `--no-update` was passed: -If a feature issue is present in the mapping file (a `feature:` entry), fetch its status and show it first: +- If there are no discrepancies, change nothing. +- If the only discrepancies are issues closed in GitLab but open locally, update `tasks.md` with `set_task_checkbox "$TASKS" <ID> done`. +- If there are tasks marked `[x]` locally whose issue is still open, don't silently uncheck them (that would undo local work). Show them and ask the user which side wins: + - **GitLab wins:** `set_task_checkbox "$TASKS" <ID> open` + - **Local wins:** suggest `__SPECKIT_COMMAND_GITLAB_CLOSE-ISSUES__` -```bash -FEATURE_MAPPING="$(read_feature_mapping "$MAPPING_PATH")" -if [[ -n "$FEATURE_MAPPING" ]]; then - FEATURE_ISSUE_NUMBER="$(extract_feature_issue_number "$FEATURE_MAPPING")" - # Fetch issue details via glab_view_issue -fi -``` - -Show a formatted table: +### Step 7: Show the overview ``` -Feature: #232 - user-authentication (Open) +Feature: #232 - <title> (Open) URL: https://gitlab.example.com/.../issues/232 ================================================ GitLab issue status for feature: <feature-name> -================================================ -| Task | GitLab | Status | Assignee | -|-------|---------|-------------|-------------| -| T001 | #42 | ✅ Closed | @username | -| T002 | #43 | 🔄 Open | @other | -| T003 | #44 | 🔄 Open | - | +| Task | GitLab | Status | Assignee | +|-------|--------|-----------|-----------| +| T001 | #42 | ✅ Closed | @username | +| T002 | #43 | 🔄 Open | @other | +| T003 | #44 | 🔄 Open | - | Summary: Open: 2 @@ -98,16 +99,12 @@ Summary: Total: 3 Progress: 33% -Stories: -| Story | GitLab | Status | -|-------|---------|-------------| -| US1 | #10 | 🔄 Open | +| Story | GitLab | Status | Tasks done | +|-------|--------|---------|------------| +| US1 | #10 | 🔄 Open | 1/3 | +Tasks without an issue: T004, T005 Last updated: <current date/time> ``` -### Step 7: Bidirectional warning - -If there are discrepancies (e.g. a task marked `[x]` in tasks.md but the GitLab issue is still open): -- Show a warning with the affected tasks -- Ask the user whether the GitLab status or the local status should take precedence +Leave out the feature block if no feature issue is mapped, and the "without an issue" line if there are none. diff --git a/commands/stories-to-issues.md b/commands/stories-to-issues.md index a84ec05..0ab0d26 100644 --- a/commands/stories-to-issues.md +++ b/commands/stories-to-issues.md @@ -1,138 +1,130 @@ --- description: "Create user stories from spec.md as GitLab issues" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Create user stories as GitLab issues -Create a parent GitLab issue for each user story in `spec.md`. - -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `spec.md` is present +Create a GitLab issue for each user story in `spec.md`. ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). It may limit the run to specific stories (e.g. `US1 US3`). + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `spec.md` + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. The feature directory contains `spec.md`. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR` and `FEATURE_SPEC`. All paths are absolute. -If no feature directory is found, inform the user and abort. +If the script fails or `FEATURE_SPEC` doesn't exist, tell the user to run `__SPECKIT_COMMAND_SPECIFY__` first and abort. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +``` -The following values are needed: -- `GITLAB_URL` - URL of the GitLab server -- `GITLAB_PROJECT` - project path -- Labels: `spec-kit`, `user-story` -- `GITLAB_FEATURE_TO_MILESTONE` - whether the feature is mapped to a milestone +If this fails, show the error and point the user to `__SPECKIT_COMMAND_GITLAB_INIT__`. -If `feature_to_milestone: true`, determine the feature name from the feature directory (directory name) and make sure a corresponding milestone exists in GitLab: +If `GITLAB_FEATURE_TO_MILESTONE` is `true`, make sure the feature milestone exists: ```bash MILESTONE_TITLE="$(glab_ensure_milestone "$(get_feature_name "$FEATURE_DIR")")" ``` -### Step 3: Read spec.md and extract user stories +### Step 3: Extract the user stories from spec.md -Read the `spec.md` file in the feature directory. Extract all user stories. User stories are typically in this format: +```bash +parse_stories "$FEATURE_SPEC" +``` + +This prints one line per story: `ID<TAB>PRIORITY<TAB>TITLE`. It understands the spec-kit template heading and the legacy format: ```markdown -## User Stories +### User Story 1 - Log in with SSO (Priority: P1) +### US1: Log in with SSO [P1] +``` -### US1: Story title [P1] -As a <role> I want <capability>, so that <benefit>. +Both become story ID `US1`. For each story, also read its section from `spec.md` (up to the next `###` heading or `---`): +- **Description**: the plain-language user journey +- **Why this priority** (if present) +- **Independent Test** (if present) +- **Acceptance Scenarios**: the numbered Given/When/Then list -**Acceptance criteria:** -- Criterion 1 -- Criterion 2 +If no stories are found, tell the user and abort. -### US2: Story title [P2] -... +### Step 4: Check idempotency + +```bash +MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" +read_mapping "$MAPPING_PATH" stories US1 # prints "#10 https://..." if already created ``` -Extract for each story: -- **Story ID**: e.g. `US1` -- **Title**: e.g. "Story title" -- **Priority**: e.g. `P1` -- **Description**: the user story in "As a... I want... so that..." format -- **Acceptance criteria**: list of criteria +Skip stories that already have an entry. -### Step 4: Check idempotency +### Step 5: Create the GitLab issues -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml` (if present). Skip stories that already have a GitLab issue number there. +If a feature issue is mapped, look it up once so new stories are linked to it: -### Step 5: Create GitLab issues +```bash +FEATURE_IID="$(extract_feature_issue_number "$(read_feature_mapping "$MAPPING_PATH")")" +``` For each story not yet created: -1. **Assemble labels:** - - Always: `spec-kit`, `user-story` - - If priority is set: `priority::1` (for P1), `priority::2` (for P2), etc. +1. **Labels:** `$GITLAB_SPECKIT_LABEL,$GITLAB_STORY_LABEL`, plus `priority_to_label P1` (→ `priority::1`) if `GITLAB_PRIORITY_TO_LABEL` is `true` and the story has a priority. -2. **Format the issue description:** +2. **Description** (Markdown): ```markdown **Story ID:** US1 **Priority:** P1 + **Feature:** <feature name> ## User Story - As a <role> I want <capability>, so that <benefit>. + <description> + + **Why this priority:** <text> + + **Independent Test:** <text> ## Acceptance Criteria - - [ ] Criterion 1 - - [ ] Criterion 2 + - [ ] **Given** ..., **When** ..., **Then** ... ``` + Leave out sections that are empty. -3. **Create the issue** via `glab`: +3. **Create the issue** (the 5th argument links it to the feature issue, if any): ```bash - glab issue create \ - --repo "$GITLAB_PROJECT" \ - --title "US1: Story title" \ - --description "<formatted description>" \ - --label "spec-kit,user-story,priority::1" \ - --milestone "$MILESTONE_TITLE" \ - --yes + OUT="$(glab_create_issue "US1: Log in with SSO" "$DESCRIPTION" "$LABELS" "$MILESTONE_TITLE" "$FEATURE_IID")" + ISSUE_URL="$(extract_issue_url "$OUT")" + ISSUE_NUMBER="$(extract_issue_number "$OUT")" ``` + Pass an empty milestone if `GITLAB_FEATURE_TO_MILESTONE` isn't `true`. If no issue URL comes back, report the glab output as an error for this story and continue with the next one. - Only set the `--milestone` parameter if `feature_to_milestone: true` and `MILESTONE_TITLE` is set. Use `glab_create_issue` with the 5th parameter for the milestone. - -4. **Extract the issue URL and number** from the output. - -5. **Link to the feature issue:** - If `feature:` is set in `.gitlab-mapping.yml`, link the newly created story issue to the feature issue: +4. **Write the mapping right away** (so a later failure doesn't cause duplicates): ```bash - FEATURE_MAPPING="$(read_feature_mapping "$MAPPING_PATH")" - if [[ -n "$FEATURE_MAPPING" ]]; then - FEATURE_ISSUE_NUMBER="$(extract_feature_issue_number "$FEATURE_MAPPING")" - glab_add_relation "$STORY_ISSUE_NUMBER" "$FEATURE_ISSUE_NUMBER" - fi + write_mapping "$MAPPING_PATH" stories US1 "$ISSUE_NUMBER" "$ISSUE_URL" ``` -### Step 6: Update the mapping file - -Write/update the mapping file `FEATURE_DIR/.gitlab-mapping.yml`: - -```yaml -stories: - US1: "#10 https://gitlab.example.com/group/project/-/issues/10" - US2: "#11 https://gitlab.example.com/group/project/-/issues/11" -tasks: {} -``` - -### Step 7: Summary +### Step 6: Summary -Show an overview: -- Number of story issues created +Show: +- Number of story issues created, with links - Number of stories skipped (already present) -- Links to the created issues -- Note: "Run `/speckit.gitlab.tasks-to-issues` to link tasks with these stories." +- Errors, if any +- Next step: run `__SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__` after `__SPECKIT_COMMAND_TASKS__` to create tasks linked to these stories. diff --git a/commands/sync.md b/commands/sync.md index 967fd99..952ab35 100644 --- a/commands/sync.md +++ b/commands/sync.md @@ -1,109 +1,112 @@ --- description: "Import and sync GitLab issues into spec-kit files" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Sync GitLab issues -Sync GitLab issues with the local spec-kit files (`tasks.md`). - -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `tasks.md` is present +Pulls the GitLab issue status into the local `tasks.md` (GitLab → local). Optionally imports issues that don't exist locally yet. The opposite direction is `__SPECKIT_COMMAND_GITLAB_CLOSE-ISSUES__`. ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). Supported flags: +- `--import`: also add GitLab issues that aren't in `tasks.md` yet +- `--dry-run`: show what would change, don't write files + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `tasks.md` + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR` and `TASKS`. All paths are absolute. -If no feature directory is found, inform the user and abort. +If `TASKS` doesn't exist, tell the user to run `__SPECKIT_COMMAND_TASKS__` first and abort. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" +``` -### Step 3: Fetch the feature issue and issues from GitLab +### Step 3: Fetch the feature issue and the issues from GitLab -If a feature issue is present in the mapping file (a `feature:` entry), fetch its current status: +If a feature issue is mapped, fetch it: ```bash -FEATURE_MAPPING="$(read_feature_mapping "$MAPPING_PATH")" -if [[ -n "$FEATURE_MAPPING" ]]; then - FEATURE_ISSUE_NUMBER="$(extract_feature_issue_number "$FEATURE_MAPPING")" - FEATURE_STATUS="$(glab_view_issue "$FEATURE_ISSUE_NUMBER" | jq -r '.state')" -fi +FEATURE_IID="$(extract_feature_issue_number "$(read_feature_mapping "$MAPPING_PATH")")" +[[ -n "$FEATURE_IID" ]] && glab_view_issue "$FEATURE_IID" | jq '{iid, title, state, web_url}' ``` -Load all issues with the `spec-kit` label from the configured GitLab project: +Load all issues with the spec-kit label (all pages, open and closed): ```bash -# All issues with the spec-kit label (open and closed) -glab issue list --repo "$GITLAB_PROJECT" --label "spec-kit" --state all --output json +glab_list_issues "$GITLAB_SPECKIT_LABEL" all \ + | jq -r '.[] | [.iid, .state, (.labels | join(",")), .web_url, .title] | @tsv' ``` -Parse the JSON output and extract for each issue: -- **Issue number**: e.g. `#42` -- **Title**: e.g. "T001: Task description" -- **Status**: `opened` or `closed` -- **Labels**: all labels of the issue -- **URL**: web URL of the issue +If `GITLAB_FEATURE_TO_MILESTONE` is `true`, only consider issues in this feature's milestone (`.milestone.title == <feature name>`), so issues of other features aren't imported. -### Step 4: Load the mapping file +### Step 4: Match issues to tasks -Read the existing mapping file `FEATURE_DIR/.gitlab-mapping.yml` (if present). +```bash +parse_tasks "$TASKS" +list_mapping_ids "$MAPPING_PATH" tasks +``` -### Step 5: Update tasks.md +A task is matched to an issue by, in this order: +1. the mapping file entry +2. the `<!-- gitlab:#42 -->` comment on its line +3. the issue title: a task ID matching `\bT\d{3,}\b` (e.g. `T012: ...`) -For each issue referenced in the mapping file or in `tasks.md` (via a `<!-- gitlab:#123 -->` comment): +### Step 5: Update tasks.md -1. **Closed issues**: set the checkbox to `[x]` - ``` - - [x] T001 [P1] [US1] Task description <!-- gitlab:#42 --> - ``` +For each matched task whose status differs: -2. **Open issues**: set the checkbox to `[ ]` - ``` - - [ ] T002 [P2] [US1] Other task description <!-- gitlab:#43 --> - ``` +```bash +set_task_checkbox "$TASKS" T012 done # issue closed +set_task_checkbox "$TASKS" T013 open # issue opened +``` -### Step 6: Import new issues (optional) +Only touch lines whose status really changes. If a matched task had no mapping entry yet, add it (`write_mapping`) and the line comment (`annotate_task_issue`). -If the user passed `--import` as an argument or confirms it: +### Step 6: Import new issues (only with `--import`, or after the user confirms) -For each GitLab issue with the `spec-kit` label that is NOT yet in `tasks.md`: +For each issue that isn't matched to a task and has the `$GITLAB_TASK_LABEL` label (story and feature issues are never imported as tasks): -1. Determine the task ID from the issue title (e.g. "T001" from "T001: Description") -2. If there's no task ID in the title: generate the next free task ID -3. Determine the priority from labels (e.g. `priority::1` → `P1`) -4. Determine the story reference from labels (e.g. `story::US1` → `US1`) -5. Append the task at the end of `tasks.md`: +1. **Task ID:** from the title (`T099: ...`); otherwise the next free ID (highest existing ID + 1, at least three digits) +2. **Story:** from a `story::US1` label +3. **Description:** the title without the task ID prefix +4. Append the task to the end of `tasks.md` under a heading `## Imported from GitLab` (create it once): ``` - - [ ] T099 [P2] [US3] Imported task description <!-- gitlab:#99 --> + - [ ] T099 [US3] Imported task description <!-- gitlab:#99 --> ``` + Use `[x]` for closed issues. Don't add a `[P]` marker: whether it can run in parallel is unknown. +5. Write the mapping: `write_mapping "$MAPPING_PATH" tasks T099 99 "$URL"` -### Step 7: Update the mapping file - -Update the mapping file with all new assignments. - -### Step 8: Summary +### Step 7: Summary -If a feature issue is present, show its status first: +If a feature issue is mapped, show it first: ``` -Feature: #232 - user-authentication (Open) +Feature: #232 - <title> (Open) ``` -Show an overview: -- Feature issue status (if present) -- Number of tasks updated (status changed) -- Number of tasks newly imported (if --import) -- Number of tasks unchanged -- Any conflicts or warnings +Then: +- Tasks updated (status changed), with the direction (open → done, done → open) +- Tasks newly imported (with `--import`) +- Tasks unchanged +- Warnings: mapped issues that no longer exist, tasks without an issue (suggest `__SPECKIT_COMMAND_GITLAB_TASKS-TO-ISSUES__`) diff --git a/commands/tasks-to-issues.md b/commands/tasks-to-issues.md index 6f2daf0..b36d407 100644 --- a/commands/tasks-to-issues.md +++ b/commands/tasks-to-issues.md @@ -1,120 +1,141 @@ --- description: "Create tasks from tasks.md as GitLab issues (Type: Task)" scripts: - check-prerequisites.sh: "../../scripts/check-prerequisites.sh" - gitlab-helpers.sh: "../scripts/bash/gitlab-helpers.sh" + sh: ../../scripts/bash/check-prerequisites.sh --json --paths-only + ps: ../../scripts/powershell/check-prerequisites.ps1 -Json -PathsOnly --- # Create tasks as GitLab issues -Create a GitLab issue of type "Task" for each task in `tasks.md`. - -## Prerequisites - -- `glab` CLI is installed and authenticated (`GITLAB_TOKEN` set) -- GitLab configuration exists (`.specify/extensions/gitlab/gitlab-config.yml`) -- Feature directory with `tasks.md` is present +Create a GitLab issue (type "Task" by default) for each task in `tasks.md`. ## User Input +```text $ARGUMENTS +``` + +You **MUST** consider the user input before proceeding (if not empty). It may limit the run to specific tasks (e.g. `T001-T010`) or one story (e.g. `US2`). + +## Prerequisites + +- `glab` CLI is installed and authenticated (`glab auth login` or `GITLAB_TOKEN`), `jq` is installed +- The GitLab configuration exists (`__SPECKIT_COMMAND_GITLAB_INIT__`) +- The feature directory contains `tasks.md` (`__SPECKIT_COMMAND_TASKS__`) + +Run all commands from the project root. Shell state may not persist between your tool calls, so `source` the helpers in the same invocation as the functions you call. ## Steps ### Step 1: Determine the feature directory -Use `{SCRIPT:check-prerequisites.sh}` to determine the current feature directory. The feature directory contains `tasks.md`. +Run `{SCRIPT}` from the project root and parse the JSON output for `FEATURE_DIR`, `FEATURE_SPEC` and `TASKS`. All paths are absolute. -If no feature directory is found, inform the user and abort. +If `TASKS` doesn't exist, tell the user to run `__SPECKIT_COMMAND_TASKS__` first and abort. ### Step 2: Load configuration -Load the GitLab configuration from `.specify/extensions/gitlab/gitlab-config.yml`. Use the helper functions from `{SCRIPT:gitlab-helpers.sh}`. - -The following values are needed: -- `GITLAB_URL` - URL of the GitLab server -- `GITLAB_PROJECT` - project path (e.g. "group/project") -- Labels: `spec-kit`, `task`, and priority labels if applicable -- `GITLAB_FEATURE_TO_MILESTONE` - whether the feature is mapped to a milestone +```bash +source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +require_tools && load_gitlab_config +``` -If `GITLAB_URL` or `GITLAB_PROJECT` are not set, also check the environment variables. +If this fails, show the error and point the user to `__SPECKIT_COMMAND_GITLAB_INIT__`. -If `feature_to_milestone: true`, determine the feature name and make sure a milestone exists: +If `GITLAB_FEATURE_TO_MILESTONE` is `true`, make sure the feature milestone exists: ```bash MILESTONE_TITLE="$(glab_ensure_milestone "$(get_feature_name "$FEATURE_DIR")")" ``` -### Step 3: Read and parse tasks.md +### Step 3: Parse tasks.md + +```bash +parse_tasks "$TASKS" +``` + +This prints one line per task: -Read the `tasks.md` file in the feature directory. Parse each task in the format: +``` +ID<TAB>STATUS<TAB>STORY<TAB>PRIORITY<TAB>PARALLEL<TAB>ISSUE<TAB>DESCRIPTION +``` + +It understands the spec-kit task format, where `[P]` marks a task that can run in parallel and `[US1]` the user story it belongs to: ``` -- [ ] T001 [P1] [US1] Task description -- [x] T002 [P2] [US1] Already completed task +- [ ] T001 Create project structure per implementation plan +- [ ] T012 [P] [US1] Create User model in src/models/user.py +- [X] T014 [US1] Implement UserService in src/services/user_service.py ``` -Extract for each task: -- **Task ID**: e.g. `T001` -- **Priority**: e.g. `P1` (from `[P1]`) -- **Story reference**: e.g. `US1` (from `[US1]`) -- **Description**: the rest of the line -- **Status**: `[ ]` = open, `[x]` = complete +- **STATUS** is `open` for `[ ]` and `done` for `[x]`/`[X]`. +- **PRIORITY** is only set by a legacy `[P1]`-style marker. Otherwise the task inherits the priority of its story: look it up with `parse_stories "$FEATURE_SPEC"` (if `spec.md` exists). +- **ISSUE** is set when the line already has a `<!-- gitlab:#42 -->` comment. + +Also note the phase heading (`## Phase N: ...`) each task is under; it goes into the issue description. ### Step 4: Check idempotency -Read the mapping file `FEATURE_DIR/.gitlab-mapping.yml` (if present). Skip tasks that already have a GitLab issue number there. +```bash +MAPPING_PATH="$(init_mapping_file "$FEATURE_DIR")" +read_mapping "$MAPPING_PATH" tasks T001 +``` -Also check whether `tasks.md` already has GitLab URLs as comments (format: `<!-- gitlab:#123 -->`). Skip these tasks as well. +Skip tasks that have a mapping entry or an ISSUE value from Step 3. -### Step 5: Create GitLab issues +### Step 5: Create the GitLab issues For each task not yet created: -1. **Assemble labels:** - - Always: `spec-kit`, `task` - - If priority is set: `priority::1` (for P1), `priority::2` (for P2), etc. - - Story label: `story::US1` (if a story reference is present) +1. **Labels:** `$GITLAB_SPECKIT_LABEL,$GITLAB_TASK_LABEL`, plus + - `priority::N` if `GITLAB_PRIORITY_TO_LABEL` is `true` and a priority is known (`priority_to_label P1`) + - `story::US1` if the task belongs to a story + - `parallel` is **not** a label; mention it in the description instead -2. **Create the issue** via `glab`: - ```bash - glab issue create \ - --repo "$GITLAB_PROJECT" \ - --title "T001: Task description" \ - --description "**Task ID:** T001\n**Priority:** P1\n**Story:** US1\n\nTask description" \ - --label "spec-kit,task,priority::1,story::US1" \ - --type "task" \ - --milestone "$MILESTONE_TITLE" \ - --yes +2. **Description** (Markdown): + ```markdown + **Task ID:** T012 + **Story:** US1 (#10) + **Priority:** P1 + **Phase:** Phase 3: User Story 1 - Log in with SSO + **Parallelizable:** yes + + Create User model in src/models/user.py ``` + Leave out lines that don't apply. - Only set the `--milestone` parameter if `feature_to_milestone: true` and `MILESTONE_TITLE` is set. Use `glab_create_issue` with the 5th parameter for the milestone. +3. **Linked story:** if `GITLAB_LINK_TASKS` is `true` and the story has an issue (`read_mapping "$MAPPING_PATH" stories US1`), pass its number so the issues are linked on creation. -3. **Extract the issue URL and number** from the output. +4. **Create the issue:** + ```bash + OUT="$(glab_create_issue "T012: Create User model in src/models/user.py" "$DESCRIPTION" "$LABELS" "$MILESTONE_TITLE" "$STORY_IID")" + ISSUE_URL="$(extract_issue_url "$OUT")" + ISSUE_NUMBER="$(extract_issue_number "$OUT")" + ``` + Use the title format `T012: <description>` (task ID once, then the description without markers). Pass an empty milestone if `GITLAB_FEATURE_TO_MILESTONE` isn't `true`. If no issue URL comes back, report the glab output as an error for this task and continue with the next one. -4. **Link to the story issue** (if `link_tasks_to_stories: true` and a story issue exists): +5. **Set the issue type** (`task` by default, `issue` leaves it unchanged): ```bash - glab issue relation add <task-issue-nr> --related <story-issue-nr> --repo "$GITLAB_PROJECT" + glab_set_issue_type "$ISSUE_NUMBER" "$GITLAB_TASK_ISSUE_TYPE" ``` + If this prints a warning, the issue stays a regular issue; mention it once in the summary and suggest `task_issue_type: "issue"`. -### Step 6: Update the mapping and tasks.md +6. **If the task is already done** (`[x]`), close the new issue: `glab_close_issue "$ISSUE_NUMBER"`. -1. **Update the mapping file** (`FEATURE_DIR/.gitlab-mapping.yml`): - ```yaml - tasks: - T001: "#42 https://gitlab.example.com/group/project/-/issues/42" - T002: "#43 https://gitlab.example.com/group/project/-/issues/43" +7. **Record the issue right away** (so a later failure doesn't cause duplicates): + ```bash + write_mapping "$MAPPING_PATH" tasks T012 "$ISSUE_NUMBER" "$ISSUE_URL" + annotate_task_issue "$TASKS" T012 "$ISSUE_NUMBER" ``` - -2. **Add GitLab references to tasks.md** (as an HTML comment at the end of the line): + This adds a comment at the end of the line in `tasks.md`: ``` - - [ ] T001 [P1] [US1] Task description <!-- gitlab:#42 --> + - [ ] T012 [P] [US1] Create User model in src/models/user.py <!-- gitlab:#42 --> ``` -### Step 7: Summary +### Step 6: Summary -Show an overview: -- Number of issues created -- Number of issues skipped (already present) -- Links to the created issues -- Any errors +Show: +- Number of issues created, with links +- Number of tasks skipped (already present) +- Errors and warnings, if any +- Next step: `__SPECKIT_COMMAND_IMPLEMENT__`, then `__SPECKIT_COMMAND_GITLAB_CLOSE-ISSUES__` to close completed tasks in GitLab. diff --git a/extension.yml b/extension.yml index fc36386..e5a1fcb 100644 --- a/extension.yml +++ b/extension.yml @@ -3,17 +3,33 @@ schema_version: "1.0" extension: id: "gitlab" name: "spec-kit GitLab Integration" - version: "1.0.0" + version: "1.1.0" description: "GitLab integration for spec-kit: create issues, sync, and post status updates via the glab CLI" + category: "integration" + effect: "read-write" author: "Kaio Lehartwig" + repository: "https://github.com/ohartwig/spec-kit-gitlab" + homepage: "https://github.com/ohartwig/spec-kit-gitlab" license: "MIT" requires: - speckit_version: ">=0.1.0" + # 0.12.17 is the first spec-kit release that rewrites extension-local + # script paths and resolves __SPECKIT_COMMAND_*__ tokens in every + # registerable layout (commands and skills). + speckit_version: ">=0.12.17" tools: - name: "glab" - version: ">=1.0.0" + version: ">=1.50.0" required: true + description: "GitLab CLI used for issues, milestones, and API calls" + install_url: "https://gitlab.com/gitlab-org/cli" + - name: "jq" + required: true + description: "Parses JSON returned by the GitLab API" + install_url: "https://jqlang.org/" + - name: "bash" + required: true + description: "The helper script is written for bash" provides: commands: @@ -47,7 +63,7 @@ provides: - name: "speckit.gitlab.status" file: "commands/status.md" - description: "Update the status of GitLab issues in tasks.md" + description: "Show GitLab issue status and update tasks.md" config: - name: "gitlab-config.yml" @@ -60,7 +76,14 @@ hooks: command: "speckit.gitlab.tasks-to-issues" optional: true prompt: "Create tasks as GitLab issues?" - description: "Automatically creates GitLab issues after task generation" + description: "Creates GitLab issues after task generation" + condition: null + + after_implement: + command: "speckit.gitlab.close-issues" + optional: true + prompt: "Close completed tasks in GitLab?" + description: "Syncs completed tasks to GitLab after implementation" condition: null tags: @@ -83,3 +106,4 @@ defaults: feature_to_milestone: true feature_to_issue: true link_tasks_to_stories: true + task_issue_type: "task" diff --git a/gitlab-config.template.yml b/gitlab-config.template.yml index 211e948..89ca1d6 100644 --- a/gitlab-config.template.yml +++ b/gitlab-config.template.yml @@ -1,8 +1,18 @@ +# spec-kit GitLab extension configuration +# Created on install at .specify/extensions/gitlab/gitlab-config.yml. +# Fill it in with /speckit.gitlab.init (or edit it by hand). +# +# Never put a token in this file. Authenticate glab instead: +# glab auth login --hostname gitlab.example.com +# or export GITLAB_TOKEN in your shell. + gitlab: - # URL of your self-hosted GitLab (e.g. https://gitlab.example.com) - url: "${GITLAB_URL}" + # URL of your GitLab instance (e.g. https://gitlab.example.com), no trailing slash + # Can be overridden with the GITLAB_URL environment variable. + url: "" # Project path (e.g. "group/project" or "group/subgroup/project") - project: "${GITLAB_PROJECT}" + # Can be overridden with the GITLAB_PROJECT environment variable. + project: "" labels: # Labels that are set automatically @@ -12,8 +22,13 @@ labels: feature_label: "feature" # Label for feature issues mapping: - # How tasks are mapped to GitLab fields - priority_to_label: true # P1 → priority::1 - feature_to_milestone: true # Feature name as milestone + # How spec-kit artifacts are mapped to GitLab fields + priority_to_label: true # Story priority P1 → label priority::1 + feature_to_milestone: true # Feature directory name as milestone feature_to_issue: true # Create the feature as a GitLab issue link_tasks_to_stories: true # Link task issues to story issues + task_issue_type: "task" # GitLab type for task issues: "task" or "issue" + +# Local overrides (not committed, kept on extension reinstall): +# .specify/extensions/gitlab/gitlab-config.local.yml +# Values there win key by key over this file. diff --git a/scripts/bash/gitlab-helpers.sh b/scripts/bash/gitlab-helpers.sh index 7910315..a718743 100755 --- a/scripts/bash/gitlab-helpers.sh +++ b/scripts/bash/gitlab-helpers.sh @@ -1,109 +1,293 @@ #!/usr/bin/env bash # gitlab-helpers.sh - Shared helper functions for the spec-kit GitLab extension -set -euo pipefail +# +# Usage (from the project root): +# source .specify/extensions/gitlab/scripts/bash/gitlab-helpers.sh +# load_gitlab_config +# +# This file is meant to be sourced. It deliberately does not call `set -e`, +# `set -u` or `set -o pipefail`, so it doesn't change the options of the +# calling shell. +# +# Requirements: bash, glab (>= 1.50), jq + +# Variables set here are read by the commands that source this file. +# shellcheck disable=SC2034 + +GITLAB_EXT_DIR="${GITLAB_EXT_DIR:-.specify/extensions/gitlab}" +GITLAB_CONFIG_FILE="${GITLAB_CONFIG_FILE:-$GITLAB_EXT_DIR/gitlab-config.yml}" + +# ============================================================================ +# Simple YAML reading (flat "key: value" pairs, nested one level deep) +# ============================================================================ + +_yaml_value() { + # _yaml_value <file> <key> + # Prints the first value for <key> (anywhere in the file), without quotes + # and without trailing comments. + local file="$1" + local key="$2" + [[ -f "$file" ]] || return 0 + grep -E "^[[:space:]]*${key}:" "$file" 2>/dev/null | head -1 \ + | sed -E "s/^[[:space:]]*${key}:[[:space:]]*//" \ + | sed -E 's/[[:space:]]+#.*$//' \ + | sed -E 's/^"(.*)"$/\1/' \ + | sed -E "s/^'(.*)'\$/\\1/" \ + | sed -E 's/[[:space:]]+$//' +} + +_config_value() { + # _config_value <key> + # Looks the key up in the local override first, then in the project config. + local key="$1" + local value="" + local file + for file in "${GITLAB_CONFIG_LOCAL_FILES[@]}" "$GITLAB_CONFIG_FILE"; do + value="$(_yaml_value "$file" "$key")" + if [[ -n "$value" ]]; then + printf '%s' "$value" + return 0 + fi + done + return 0 +} + +_is_placeholder() { + # Empty or an unresolved "${...}" placeholder + [[ -z "$1" || "$1" =~ ^\$\{.*\}$ ]] +} # ============================================================================ # Load configuration # ============================================================================ load_gitlab_config() { - local config_file="${1:-.specify/extensions/gitlab/gitlab-config.yml}" - local local_override="${config_file%.yml}.local.yml" - - if [[ -f "$local_override" ]]; then - config_file="$local_override" + # Precedence (highest first): + # 1. Environment variables (GITLAB_URL, GITLAB_PROJECT) + # 2. Local override (gitlab-config.local.yml or local-config.yml, gitignored) + # 3. Project config (.specify/extensions/gitlab/gitlab-config.yml) + # 4. Built-in defaults + if [[ -n "${1:-}" ]]; then + GITLAB_CONFIG_FILE="$1" fi - - if [[ ! -f "$config_file" ]]; then - echo "ERROR: GitLab configuration not found: $config_file" >&2 - echo "Run 'specify extension add --dev ~/spec-kit-gitlab/'." >&2 - return 1 + local config_dir + config_dir="$(dirname "$GITLAB_CONFIG_FILE")" + GITLAB_CONFIG_LOCAL_FILES=( + "${GITLAB_CONFIG_FILE%.yml}.local.yml" + "$config_dir/local-config.yml" + ) + + if [[ ! -f "$GITLAB_CONFIG_FILE" ]]; then + local f found=false + for f in "${GITLAB_CONFIG_LOCAL_FILES[@]}"; do + [[ -f "$f" ]] && found=true + done + if [[ "$found" != true && -z "${GITLAB_URL:-}" ]]; then + echo "ERROR: GitLab configuration not found: $GITLAB_CONFIG_FILE" >&2 + echo "Run the GitLab init command (speckit.gitlab.init) to create it." >&2 + return 1 + fi fi - # Extract values from config (simple YAML parsing) - GITLAB_URL="${GITLAB_URL:-$(grep '^\s*url:' "$config_file" | head -1 | sed 's/.*url:\s*//' | tr -d '"' | tr -d "'")}" - GITLAB_PROJECT="${GITLAB_PROJECT:-$(grep '^\s*project:' "$config_file" | head -1 | sed 's/.*project:\s*//' | tr -d '"' | tr -d "'")}" - GITLAB_STORY_LABEL="$(grep '^\s*story_label:' "$config_file" | head -1 | sed 's/.*story_label:\s*//' | tr -d '"' | tr -d "'")" - GITLAB_TASK_LABEL="$(grep '^\s*task_label:' "$config_file" | head -1 | sed 's/.*task_label:\s*//' | tr -d '"' | tr -d "'")" - GITLAB_SPECKIT_LABEL="$(grep '^\s*speckit_label:' "$config_file" | head -1 | sed 's/.*speckit_label:\s*//' | tr -d '"' | tr -d "'")" - GITLAB_PRIORITY_TO_LABEL="$(grep '^\s*priority_to_label:' "$config_file" | head -1 | sed 's/.*priority_to_label:\s*//' | tr -d ' ')" - GITLAB_LINK_TASKS="$(grep '^\s*link_tasks_to_stories:' "$config_file" | head -1 | sed 's/.*link_tasks_to_stories:\s*//' | tr -d ' ')" - GITLAB_FEATURE_TO_MILESTONE="$(grep '^\s*feature_to_milestone:' "$config_file" | head -1 | sed 's/.*feature_to_milestone:\s*//' | tr -d ' ')" - GITLAB_FEATURE_TO_ISSUE="$(grep '^\s*feature_to_issue:' "$config_file" | head -1 | sed 's/.*feature_to_issue:\s*//' | tr -d ' ')" - GITLAB_FEATURE_LABEL="$(grep '^\s*feature_label:' "$config_file" | head -1 | sed 's/.*feature_label:\s*//' | tr -d '"' | tr -d "'")" + local url project + url="$(_config_value url)" + project="$(_config_value project)" + _is_placeholder "$url" && url="" + _is_placeholder "$project" && project="" + + GITLAB_URL="${GITLAB_URL:-$url}" + GITLAB_URL="${GITLAB_URL%/}" + GITLAB_PROJECT="${GITLAB_PROJECT:-$project}" + GITLAB_PROJECT="${GITLAB_PROJECT#/}" + GITLAB_PROJECT="${GITLAB_PROJECT%/}" + + GITLAB_STORY_LABEL="$(_config_value story_label)" + GITLAB_TASK_LABEL="$(_config_value task_label)" + GITLAB_SPECKIT_LABEL="$(_config_value speckit_label)" + GITLAB_FEATURE_LABEL="$(_config_value feature_label)" + GITLAB_PRIORITY_TO_LABEL="$(_config_value priority_to_label)" + GITLAB_LINK_TASKS="$(_config_value link_tasks_to_stories)" + GITLAB_FEATURE_TO_MILESTONE="$(_config_value feature_to_milestone)" + GITLAB_FEATURE_TO_ISSUE="$(_config_value feature_to_issue)" + GITLAB_TASK_ISSUE_TYPE="$(_config_value task_issue_type)" # Defaults GITLAB_STORY_LABEL="${GITLAB_STORY_LABEL:-user-story}" GITLAB_TASK_LABEL="${GITLAB_TASK_LABEL:-task}" GITLAB_SPECKIT_LABEL="${GITLAB_SPECKIT_LABEL:-spec-kit}" + GITLAB_FEATURE_LABEL="${GITLAB_FEATURE_LABEL:-feature}" GITLAB_PRIORITY_TO_LABEL="${GITLAB_PRIORITY_TO_LABEL:-true}" GITLAB_LINK_TASKS="${GITLAB_LINK_TASKS:-true}" GITLAB_FEATURE_TO_MILESTONE="${GITLAB_FEATURE_TO_MILESTONE:-true}" GITLAB_FEATURE_TO_ISSUE="${GITLAB_FEATURE_TO_ISSUE:-true}" - GITLAB_FEATURE_LABEL="${GITLAB_FEATURE_LABEL:-feature}" + GITLAB_TASK_ISSUE_TYPE="${GITLAB_TASK_ISSUE_TYPE:-task}" # Validation - if [[ -z "$GITLAB_URL" || "$GITLAB_URL" == '${GITLAB_URL}' ]]; then - echo "ERROR: GITLAB_URL is not configured. Set the URL in gitlab-config.yml or as an environment variable." >&2 + if [[ -z "$GITLAB_URL" ]]; then + echo "ERROR: GITLAB_URL is not configured. Set gitlab.url in $GITLAB_CONFIG_FILE or export GITLAB_URL." >&2 return 1 fi - if [[ -z "$GITLAB_PROJECT" || "$GITLAB_PROJECT" == '${GITLAB_PROJECT}' ]]; then - echo "ERROR: GITLAB_PROJECT is not configured." >&2 + if [[ ! "$GITLAB_URL" =~ ^https?:// ]]; then + echo "ERROR: GITLAB_URL must start with https:// or http:// (got: $GITLAB_URL)" >&2 + return 1 + fi + if [[ -z "$GITLAB_PROJECT" ]]; then + echo "ERROR: GITLAB_PROJECT is not configured. Set gitlab.project in $GITLAB_CONFIG_FILE or export GITLAB_PROJECT." >&2 + return 1 + fi + + GITLAB_HOSTNAME="$(gitlab_hostname)" + GITLAB_PROJECT_ENC="$(urlencode "$GITLAB_PROJECT")" + GITLAB_PROJECT_ID="" + + export GITLAB_URL GITLAB_PROJECT GITLAB_HOSTNAME GITLAB_PROJECT_ENC +} + +# ============================================================================ +# Utilities +# ============================================================================ + +urlencode() { + printf '%s' "$1" | jq -sRr @uri +} + +gitlab_hostname() { + # https://gitlab.example.com:8443/ → gitlab.example.com:8443 + local host="${GITLAB_URL#*://}" + printf '%s' "${host%%/*}" +} + +require_tools() { + local missing=() + command -v glab >/dev/null 2>&1 || missing+=("glab") + command -v jq >/dev/null 2>&1 || missing+=("jq") + if [[ ${#missing[@]} -gt 0 ]]; then + echo "ERROR: Missing required tools: ${missing[*]}" >&2 return 1 fi } # ============================================================================ -# glab wrapper +# glab wrappers # ============================================================================ glab_cmd() { - # Runs glab with the correct host - GITLAB_HOST="$GITLAB_URL" glab "$@" --repo "$GITLAB_PROJECT" + # Runs a `glab` subcommand that supports --repo (issue, mr, ...) against the + # configured project. The full project URL selects the host as well. + glab "$@" --repo "$GITLAB_URL/$GITLAB_PROJECT" +} + +glab_api() { + # Runs `glab api` against the configured host. `glab api` has no --repo + # flag, so endpoints must reference the project explicitly, e.g. + # "projects/$GITLAB_PROJECT_ENC/issues". + glab api --hostname "$GITLAB_HOSTNAME" "$@" +} + +glab_project_id() { + # Numeric project ID (cached) + if [[ -z "${GITLAB_PROJECT_ID:-}" ]]; then + GITLAB_PROJECT_ID="$(glab_api "projects/$GITLAB_PROJECT_ENC" 2>/dev/null | jq -r '.id // empty')" + fi + [[ -n "$GITLAB_PROJECT_ID" ]] && printf '%s' "$GITLAB_PROJECT_ID" +} + +glab_check_connection() { + # Prints the project's web URL on success + glab_api "projects/$GITLAB_PROJECT_ENC" 2>/dev/null | jq -r '.web_url // empty' } glab_create_issue() { + # glab_create_issue <title> [description] [labels] [milestone] [linked-iids] + # Prints glab's output (contains the issue URL). local title="$1" local description="${2:-}" local labels="${3:-}" - local issue_type="${4:-}" - local milestone="${5:-}" + local milestone="${4:-}" + local linked="${5:-}" local args=(issue create --title "$title" --yes) - if [[ -n "$description" ]]; then - args+=(--description "$description") - fi + # Always pass a description: without one glab may open an editor/prompt. + args+=(--description "${description:-Created by spec-kit.}") if [[ -n "$labels" ]]; then args+=(--label "$labels") fi - if [[ -n "$issue_type" ]]; then - args+=(--type "$issue_type") - fi if [[ -n "$milestone" ]]; then args+=(--milestone "$milestone") fi + if [[ -n "$linked" ]]; then + args+=(--linked-issues "$linked" --link-type "relates_to") + fi glab_cmd "${args[@]}" 2>&1 } +glab_set_issue_type() { + # glab_set_issue_type <iid> <type> (issue | task | incident | test_case) + local iid="$1" + local type="${2:-issue}" + [[ "$type" == "issue" ]] && return 0 + if ! glab_api --method PUT "projects/$GITLAB_PROJECT_ENC/issues/$iid" \ + -f "issue_type=$type" --silent 2>/dev/null; then + echo "WARN: Could not set type '$type' on issue #$iid; it stays a regular issue." >&2 + return 1 + fi +} + glab_list_issues() { + # glab_list_issues [labels] [state] + # All issues (all pages) as one JSON array. state: all | opened | closed local labels="${1:-$GITLAB_SPECKIT_LABEL}" local state="${2:-all}" - glab_cmd issue list --label "$labels" --state "$state" --output json 2>/dev/null || echo "[]" + glab_api --paginate --method GET "projects/$GITLAB_PROJECT_ENC/issues" \ + -f "labels=$labels" -f "state=$state" -f "per_page=100" 2>/dev/null \ + | jq -s 'flatten' 2>/dev/null || echo "[]" } glab_view_issue() { - local issue_number="$1" - glab_cmd issue view "$issue_number" --output json 2>/dev/null + # JSON of a single issue (iid, title, state, labels, assignees, web_url, ...) + local iid="$1" + glab_api "projects/$GITLAB_PROJECT_ENC/issues/$iid" 2>/dev/null +} + +glab_issue_state() { + # Prints "opened" or "closed" + glab_view_issue "$1" | jq -r '.state // empty' } glab_add_relation() { - local child_issue="$1" - local parent_issue="$2" - # Links the child issue to the parent issue - glab_cmd issue relation add "$child_issue" --related "$parent_issue" 2>/dev/null || true + # glab_add_relation <source-iid> <target-iid> [link_type] + # Creates an issue link (default: relates_to). Already existing links are + # ignored. + local source_iid="$1" + local target_iid="$2" + local link_type="${3:-relates_to}" + local project_id + project_id="$(glab_project_id)" || true + [[ -z "$project_id" ]] && project_id="$GITLAB_PROJECT" + + local out + if out="$(glab_api --method POST "projects/$GITLAB_PROJECT_ENC/issues/$source_iid/links" \ + -f "target_project_id=$project_id" \ + -f "target_issue_iid=$target_iid" \ + -f "link_type=$link_type" 2>&1)"; then + return 0 + fi + if printf '%s' "$out" | grep -qi "already"; then + return 0 + fi + echo "WARN: Could not link #$source_iid to #$target_iid: $out" >&2 + return 1 +} + +glab_close_issue() { + glab_cmd issue close "$1" 2>&1 +} + +glab_reopen_issue() { + glab_cmd issue reopen "$1" 2>&1 } # ============================================================================ @@ -128,28 +312,42 @@ YAML echo "$mapping_path" } +_ensure_section() { + # Makes sure "<section>:" exists as a block mapping header (not "{}"). + local mapping_path="$1" + local section="$2" + if grep -qE "^${section}:[[:space:]]*\{\}[[:space:]]*$" "$mapping_path"; then + sed -i.bak -E "s/^${section}:[[:space:]]*\{\}[[:space:]]*$/${section}:/" "$mapping_path" + rm -f "${mapping_path}.bak" + elif ! grep -qE "^${section}:" "$mapping_path"; then + printf '%s:\n' "$section" >> "$mapping_path" + fi +} + read_mapping() { + # read_mapping <mapping-path> <stories|tasks> <id> + # Prints the stored value, e.g. "#42 https://.../issues/42" local mapping_path="$1" - local section="$2" # "stories" or "tasks" + local section="$2" local id="$3" - if [[ ! -f "$mapping_path" ]]; then - return 1 - fi + [[ -f "$mapping_path" ]] || return 1 - # Reads the issue number for a given ID from the mapping file - local in_section=false - while IFS= read -r line; do + local in_section=false line + while IFS= read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ ^${section}: ]]; then in_section=true continue fi if [[ "$in_section" == true ]]; then - if [[ "$line" =~ ^[a-z] ]]; then - break # A new section begins + if [[ "$line" =~ ^[^[:space:]#] ]]; then + break # The next section begins fi - if [[ "$line" =~ ^[[:space:]]+${id}: ]]; then - echo "$line" | sed "s/.*${id}:\s*//" | tr -d '"' | tr -d "'" + if [[ "$line" =~ ^[[:space:]]+${id}:[[:space:]]*(.*)$ ]]; then + local value="${BASH_REMATCH[1]}" + value="${value#\"}"; value="${value%\"}" + value="${value#\'}"; value="${value%\'}" + printf '%s\n' "$value" return 0 fi fi @@ -158,9 +356,34 @@ read_mapping() { return 1 } +list_mapping_ids() { + # list_mapping_ids <mapping-path> <stories|tasks> + # Prints "ID<TAB>value" for every entry of the section. + local mapping_path="$1" + local section="$2" + [[ -f "$mapping_path" ]] || return 0 + + local in_section=false line + while IFS= read -r line || [[ -n "$line" ]]; do + if [[ "$line" =~ ^${section}: ]]; then + in_section=true + continue + fi + if [[ "$in_section" == true ]]; then + [[ "$line" =~ ^[^[:space:]#] ]] && break + if [[ "$line" =~ ^[[:space:]]+([A-Za-z0-9_-]+):[[:space:]]*(.*)$ ]]; then + local value="${BASH_REMATCH[2]}" + value="${value#\"}"; value="${value%\"}" + printf '%s\t%s\n' "${BASH_REMATCH[1]}" "$value" + fi + fi + done < "$mapping_path" +} + write_mapping() { + # write_mapping <mapping-path> <stories|tasks> <id> <issue-number> [issue-url] local mapping_path="$1" - local section="$2" # "stories" or "tasks" + local section="$2" local id="$3" local issue_number="$4" local issue_url="${5:-}" @@ -168,6 +391,7 @@ write_mapping() { if [[ ! -f "$mapping_path" ]]; then init_mapping_file "$(dirname "$mapping_path")" > /dev/null fi + _ensure_section "$mapping_path" "$section" local entry=" ${id}: \"#${issue_number}" if [[ -n "$issue_url" ]]; then @@ -175,31 +399,94 @@ write_mapping() { fi entry+="\"" - # Check whether the entry already exists - if grep -q "^\s*${id}:" "$mapping_path" 2>/dev/null; then - # Update the existing entry - sed -i.bak "s|^\(\s*\)${id}:.*|${entry}|" "$mapping_path" - rm -f "${mapping_path}.bak" + local tmp="${mapping_path}.tmp" + local in_section=false done=false line + : > "$tmp" + while IFS= read -r line || [[ -n "$line" ]]; do + if [[ "$done" == false ]]; then + if [[ "$line" =~ ^${section}: ]]; then + in_section=true + printf '%s\n' "$line" >> "$tmp" + continue + fi + if [[ "$in_section" == true ]]; then + if [[ "$line" =~ ^[[:space:]]+${id}: ]]; then + printf '%s\n' "$entry" >> "$tmp" # update existing entry + done=true + continue + fi + if [[ "$line" =~ ^[^[:space:]#] ]]; then + printf '%s\n' "$entry" >> "$tmp" # append at the end of the section + done=true + in_section=false + fi + fi + fi + printf '%s\n' "$line" >> "$tmp" + done < "$mapping_path" + if [[ "$done" == false ]]; then + printf '%s\n' "$entry" >> "$tmp" + fi + mv "$tmp" "$mapping_path" +} + +read_feature_mapping() { + local mapping_path="$1" + [[ -f "$mapping_path" ]] || return 1 + + local value + value="$(_yaml_value "$mapping_path" feature)" + if [[ -n "$value" ]]; then + printf '%s\n' "$value" + return 0 + fi + return 1 +} + +write_feature_mapping() { + local mapping_path="$1" + local issue_number="$2" + local issue_url="${3:-}" + + if [[ ! -f "$mapping_path" ]]; then + init_mapping_file "$(dirname "$mapping_path")" > /dev/null + fi + + local entry="feature: \"#${issue_number}" + if [[ -n "$issue_url" ]]; then + entry+=" ${issue_url}" + fi + entry+="\"" + + if grep -qE '^feature:' "$mapping_path" 2>/dev/null; then + sed -i.bak "s|^feature:.*|${entry}|" "$mapping_path" else - # Insert a new entry after the section header - sed -i.bak "/^${section}:/a\\ -${entry}" "$mapping_path" - rm -f "${mapping_path}.bak" + sed -i.bak "/^stories:/i\\ +${entry} +" "$mapping_path" fi + rm -f "${mapping_path}.bak" +} + +extract_mapping_issue_number() { + # "#42 https://..." or "#42" → 42 + printf '%s' "$1" | grep -oE '#[0-9]+' | head -1 | tr -d '#' +} + +extract_feature_issue_number() { + extract_mapping_issue_number "$1" } # ============================================================================ -# Extract the issue URL from glab output +# Extract the issue URL / number from glab output # ============================================================================ extract_issue_url() { - local output="$1" - echo "$output" | grep -oE 'https?://[^ ]+/issues/[0-9]+' | head -1 + printf '%s' "$1" | grep -oE 'https?://[^[:space:]]+/-/issues/[0-9]+|https?://[^[:space:]]+/issues/[0-9]+' | head -1 } extract_issue_number() { - local output="$1" - echo "$output" | grep -oE '/issues/([0-9]+)' | head -1 | grep -oE '[0-9]+' + printf '%s' "$1" | grep -oE '/issues/[0-9]+' | head -1 | grep -oE '[0-9]+' } # ============================================================================ @@ -208,13 +495,19 @@ extract_issue_number() { priority_to_label() { local priority="$1" - case "$priority" in - P1|p1) echo "priority::1" ;; - P2|p2) echo "priority::2" ;; - P3|p3) echo "priority::3" ;; - P4|p4) echo "priority::4" ;; - *) echo "" ;; - esac + if [[ "$priority" =~ ^[Pp]([0-9]+)$ ]]; then + echo "priority::${BASH_REMATCH[1]}" + else + echo "" + fi +} + +label_to_priority() { + # priority::2 → P2 + local label="$1" + if [[ "$label" =~ ^priority::([0-9]+)$ ]]; then + echo "P${BASH_REMATCH[1]}" + fi } # ============================================================================ @@ -222,28 +515,27 @@ priority_to_label() { # ============================================================================ get_feature_name() { - local feature_dir="$1" - # Feature name = name of the feature directory - basename "$feature_dir" + # Feature name = name of the feature directory (e.g. 001-user-auth) + basename "$1" } glab_find_milestone() { - # Looks up a milestone by title, returns the milestone ID + # Looks up an active milestone by title, prints its ID local title="$1" - glab_cmd api "projects/:id/milestones?title=$(printf '%s' "$title" | jq -sRr @uri)" 2>/dev/null \ - | jq -r ".[0].id // empty" 2>/dev/null || true + glab_api --method GET "projects/$GITLAB_PROJECT_ENC/milestones" \ + -f "title=$title" 2>/dev/null | jq -r '.[0].id // empty' 2>/dev/null || true } glab_create_milestone() { - # Creates a new milestone and returns the ID local title="$1" local description="${2:-Automatically created by spec-kit for feature: $title}" - glab_cmd api "projects/:id/milestones" -f "title=$title" -f "description=$description" 2>/dev/null \ - | jq -r ".id" 2>/dev/null + glab_api --method POST "projects/$GITLAB_PROJECT_ENC/milestones" \ + -f "title=$title" -f "description=$description" 2>/dev/null \ + | jq -r '.id // empty' 2>/dev/null } glab_ensure_milestone() { - # Finds or creates a milestone, returns the title (for the --milestone flag) + # Finds or creates a milestone, prints its title (for --milestone) local feature_name="$1" local milestone_id @@ -259,81 +551,109 @@ glab_ensure_milestone() { fi fi - # glab issue create --milestone expects the title echo "$feature_name" } # ============================================================================ -# Feature issue mapping +# spec-kit artifact parsing # ============================================================================ -read_feature_mapping() { - local mapping_path="$1" - - if [[ ! -f "$mapping_path" ]]; then - return 1 - fi - - local value - value="$(grep '^\s*feature:' "$mapping_path" | head -1 | sed 's/.*feature:\s*//' | tr -d '"' | tr -d "'")" - - if [[ -n "$value" ]]; then - echo "$value" - return 0 - fi - - return 1 -} - -write_feature_mapping() { - local mapping_path="$1" - local issue_number="$2" - local issue_url="${3:-}" - - if [[ ! -f "$mapping_path" ]]; then - init_mapping_file "$(dirname "$mapping_path")" > /dev/null - fi - - local entry="feature: \"#${issue_number}" - if [[ -n "$issue_url" ]]; then - entry+=" ${issue_url}" - fi - entry+="\"" +parse_tasks() { + # parse_tasks <tasks.md> + # Prints one line per task: ID<TAB>STATUS<TAB>STORY<TAB>PRIORITY<TAB>PARALLEL<TAB>ISSUE<TAB>DESCRIPTION + # STATUS: open | done + # STORY: e.g. US1 (empty if none) + # PRIORITY: e.g. P1, only from a legacy "[P1]" marker (empty otherwise) + # PARALLEL: yes | no ("[P]" marker) + # ISSUE: GitLab IID from a "<!-- gitlab:#42 -->" comment (empty if none) + local tasks_file="$1" + [[ -f "$tasks_file" ]] || return 1 + + local line + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*[-*][[:space:]]+\[([ xX])\][[:space:]]+(T[0-9]{3,})[[:space:]]*(.*)$ ]] || continue + local mark="${BASH_REMATCH[1]}" id="${BASH_REMATCH[2]}" rest="${BASH_REMATCH[3]}" + local status="open" story="" priority="" parallel="no" issue="" + [[ "$mark" == "x" || "$mark" == "X" ]] && status="done" + + if [[ "$rest" =~ \<\!--[[:space:]]*gitlab:#([0-9]+)[[:space:]]*--\> ]]; then + issue="${BASH_REMATCH[1]}" + rest="$(printf '%s' "$rest" | sed -E 's/[[:space:]]*<!--[[:space:]]*gitlab:#[0-9]+[[:space:]]*-->//')" + fi - # Check whether the feature entry already exists - if grep -q '^\s*feature:' "$mapping_path" 2>/dev/null; then - sed -i.bak "s|^\(\s*\)feature:.*|${entry}|" "$mapping_path" - rm -f "${mapping_path}.bak" - else - # Insert before stories: - sed -i.bak "/^stories:/i\\ -${entry}" "$mapping_path" - rm -f "${mapping_path}.bak" - fi + # Leading markers: [P], [P1], [US1] in any order + while [[ "$rest" =~ ^\[([A-Za-z0-9]+)\][[:space:]]*(.*)$ ]]; do + local marker="${BASH_REMATCH[1]}" + rest="${BASH_REMATCH[2]}" + case "$marker" in + P|p) parallel="yes" ;; + P[0-9]*|p[0-9]*) priority="P${marker:1}" ;; + US[0-9]*|us[0-9]*) story="US${marker:2}" ;; + *) rest="[$marker] $rest"; break ;; + esac + done + rest="${rest%"${rest##*[![:space:]]}"}" + + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$status" "$story" "$priority" "$parallel" "$issue" "$rest" + done < "$tasks_file" } -extract_feature_issue_number() { - local mapping_value="$1" - # Extracts the issue number from "#232 https://..." or "#232" - echo "$mapping_value" | grep -oE '#[0-9]+' | head -1 | tr -d '#' -} +parse_stories() { + # parse_stories <spec.md> + # Prints one line per user story: ID<TAB>PRIORITY<TAB>TITLE + # Supported headings: + # ### User Story 1 - Title (Priority: P1) (spec-kit template) + # ### US1: Title [P1] (legacy format) + local spec_file="$1" + [[ -f "$spec_file" ]] || return 1 + + local line + while IFS= read -r line || [[ -n "$line" ]]; do + local id="" title="" priority="" + if [[ "$line" =~ ^\#{2,4}[[:space:]]+User[[:space:]]+Story[[:space:]]+([0-9]+)[[:space:]]*(-|–|—|:)[[:space:]]*(.*)$ ]]; then + id="US${BASH_REMATCH[1]}" + title="${BASH_REMATCH[3]}" + elif [[ "$line" =~ ^\#{2,4}[[:space:]]+US([0-9]+)[[:space:]]*(-|–|—|:)[[:space:]]*(.*)$ ]]; then + id="US${BASH_REMATCH[1]}" + title="${BASH_REMATCH[3]}" + else + continue + fi -# ============================================================================ -# Close / reopen issue -# ============================================================================ + if [[ "$title" =~ ^(.*)\(Priority:[[:space:]]*(P[0-9]+)\)[[:space:]]*$ ]]; then + title="${BASH_REMATCH[1]}" + priority="${BASH_REMATCH[2]}" + elif [[ "$title" =~ ^(.*)\[(P[0-9]+)\][[:space:]]*$ ]]; then + title="${BASH_REMATCH[1]}" + priority="${BASH_REMATCH[2]}" + fi + title="${title%"${title##*[![:space:]]}"}" -glab_close_issue() { - local issue_number="$1" - glab_cmd issue close "$issue_number" 2>&1 + printf '%s\t%s\t%s\n' "$id" "$priority" "$title" + done < "$spec_file" } -glab_reopen_issue() { - local issue_number="$1" - glab_cmd issue reopen "$issue_number" 2>&1 +set_task_checkbox() { + # set_task_checkbox <tasks.md> <task-id> <open|done> + # Only touches the checkbox of the given task line. + local tasks_file="$1" + local id="$2" + local status="$3" + local mark=" " + [[ "$status" == "done" ]] && mark="x" + sed -i.bak -E "s/^([[:space:]]*[-*][[:space:]]+)\[[ xX]\]([[:space:]]+${id}([[:space:]]|$))/\1[${mark}]\2/" "$tasks_file" + rm -f "${tasks_file}.bak" } -extract_mapping_issue_number() { - local mapping_value="$1" - # Extracts the issue number from "#42 https://..." or "#42" - echo "$mapping_value" | grep -oE '#[0-9]+' | head -1 | tr -d '#' +annotate_task_issue() { + # annotate_task_issue <tasks.md> <task-id> <issue-number> + # Appends "<!-- gitlab:#N -->" to the task line (once). + local tasks_file="$1" + local id="$2" + local issue="$3" + if grep -qE "^[[:space:]]*[-*][[:space:]]+\[[ xX]\][[:space:]]+${id}([[:space:]]|$).*<!--[[:space:]]*gitlab:#" "$tasks_file"; then + return 0 + fi + sed -i.bak -E "s/^([[:space:]]*[-*][[:space:]]+\[[ xX]\][[:space:]]+${id}([[:space:]].*)?)$/\1 <!-- gitlab:#${issue} -->/" "$tasks_file" + rm -f "${tasks_file}.bak" } diff --git a/tests/test-helpers.sh b/tests/test-helpers.sh new file mode 100644 index 0000000..999bb6d --- /dev/null +++ b/tests/test-helpers.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# Offline tests for scripts/bash/gitlab-helpers.sh (no GitLab access needed). +# Run: bash tests/test-helpers.sh +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# shellcheck source=../scripts/bash/gitlab-helpers.sh +source "$ROOT/scripts/bash/gitlab-helpers.sh" + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +FAIL_LOG="$TMP/failures" +: > "$FAIL_LOG" + +read_lines() { + # read_lines <array-name> < input (mapfile replacement for bash 3.2) + local __line __i=0 + eval "$1=()" + while IFS= read -r __line; do + eval "$1[$__i]=\"\$__line\"" + __i=$((__i + 1)) + done +} + +assert_eq() { + local expected="$1" actual="$2" msg="$3" + if [[ "$expected" == "$actual" ]]; then + echo "ok - $msg" + else + echo "FAIL - $msg" + echo " expected: $(printf '%q' "$expected")" + echo " actual: $(printf '%q' "$actual")" + echo "$msg" >> "$FAIL_LOG" # a file, so failures in subshells count too + fi +} + +# --- config ----------------------------------------------------------------- +mkdir -p "$TMP/cfg" +cat > "$TMP/cfg/gitlab-config.yml" << 'YAML' +gitlab: + url: "https://gitlab.example.com/" # trailing slash is removed + project: "group/sub/project" +labels: + story_label: "story" +mapping: + priority_to_label: false +YAML +cat > "$TMP/cfg/gitlab-config.local.yml" << 'YAML' +labels: + story_label: "local-story" +YAML +( + unset GITLAB_URL GITLAB_PROJECT + load_gitlab_config "$TMP/cfg/gitlab-config.yml" + assert_eq "https://gitlab.example.com" "$GITLAB_URL" "url is read and trailing slash stripped" + assert_eq "group/sub/project" "$GITLAB_PROJECT" "project is read" + assert_eq "group%2Fsub%2Fproject" "$GITLAB_PROJECT_ENC" "project path is URL-encoded" + assert_eq "gitlab.example.com" "$GITLAB_HOSTNAME" "hostname is derived" + assert_eq "local-story" "$GITLAB_STORY_LABEL" "local override wins per key" + assert_eq "task" "$GITLAB_TASK_LABEL" "defaults apply for missing keys" + assert_eq "false" "$GITLAB_PRIORITY_TO_LABEL" "booleans are read" + assert_eq "task" "$GITLAB_TASK_ISSUE_TYPE" "task_issue_type defaults to task" +) + +cat > "$TMP/cfg/placeholder-config.yml" << 'YAML' +gitlab: + url: "${GITLAB_URL}" + project: "${GITLAB_PROJECT}" +YAML +( + unset GITLAB_URL GITLAB_PROJECT + if load_gitlab_config "$TMP/cfg/placeholder-config.yml" 2>/dev/null; then + assert_eq "fail" "ok" "placeholder config without env must fail" + else + assert_eq "1" "1" "placeholder config without env fails" + fi + GITLAB_URL="https://env.example.com" GITLAB_PROJECT="env/proj" load_gitlab_config "$TMP/cfg/placeholder-config.yml" + assert_eq "env/proj" "$GITLAB_PROJECT" "environment variables override placeholders" +) + +# --- tasks.md parsing ------------------------------------------------------- +cat > "$TMP/tasks.md" << 'MD' +# Tasks + +- [ ] T001 Create project structure per implementation plan +- [X] T002 [P] Configure linting and formatting tools +- [ ] T010 [P] [US1] Contract test for endpoint in tests/contract/test_x.py <!-- gitlab:#42 --> +- [x] T1000 [US2] Implement service (depends on T012) +- [ ] T003 [P1] [US1] Legacy priority marker +Not a task line T004 +MD +read_lines TASKS < <(parse_tasks "$TMP/tasks.md") +assert_eq "5" "${#TASKS[@]}" "parse_tasks finds 5 tasks" +assert_eq $'T001\topen\t\t\tno\t\tCreate project structure per implementation plan' "${TASKS[0]}" "plain task" +assert_eq $'T002\tdone\t\t\tyes\t\tConfigure linting and formatting tools' "${TASKS[1]}" "[X] and [P] markers" +assert_eq $'T010\topen\tUS1\t\tyes\t42\tContract test for endpoint in tests/contract/test_x.py' "${TASKS[2]}" "story marker and gitlab comment" +assert_eq $'T1000\tdone\tUS2\t\tno\t\tImplement service (depends on T012)' "${TASKS[3]}" "four-digit task ID" +assert_eq $'T003\topen\tUS1\tP1\tno\t\tLegacy priority marker' "${TASKS[4]}" "legacy [P1] priority marker" + +set_task_checkbox "$TMP/tasks.md" T001 done +set_task_checkbox "$TMP/tasks.md" T002 open +annotate_task_issue "$TMP/tasks.md" T001 7 +annotate_task_issue "$TMP/tasks.md" T001 7 +annotate_task_issue "$TMP/tasks.md" T010 99 +assert_eq "- [x] T001 Create project structure per implementation plan <!-- gitlab:#7 -->" "$(grep 'T001 ' "$TMP/tasks.md")" "checkbox set and annotated once" +assert_eq "- [ ] T002 [P] Configure linting and formatting tools" "$(grep 'T002 ' "$TMP/tasks.md")" "checkbox cleared" +assert_eq "1" "$(grep -c 'gitlab:#' <(grep 'T010 ' "$TMP/tasks.md"))" "existing annotation is kept" +assert_eq "- [x] T1000 [US2] Implement service (depends on T012)" "$(grep 'T1000 ' "$TMP/tasks.md")" "T100x prefix does not collide" + +# --- spec.md parsing -------------------------------------------------------- +cat > "$TMP/spec.md" << 'MD' +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Log in with SSO (Priority: P1) +### User Story 2 - Reset password (Priority: P2) +### US3: Legacy story [P3] +### User Story 4 – Em dash title (Priority: P2) +### Edge Cases +MD +read_lines STORIES < <(parse_stories "$TMP/spec.md") +assert_eq "4" "${#STORIES[@]}" "parse_stories finds 4 stories" +assert_eq $'US1\tP1\tLog in with SSO' "${STORIES[0]}" "template story format" +assert_eq $'US3\tP3\tLegacy story' "${STORIES[2]}" "legacy story format" +assert_eq $'US4\tP2\tEm dash title' "${STORIES[3]}" "en dash separator" + +# --- mapping file ----------------------------------------------------------- +mkdir -p "$TMP/feature" +MAP="$(init_mapping_file "$TMP/feature")" +write_mapping "$MAP" stories US1 10 "https://gitlab.example.com/g/p/-/issues/10" +write_mapping "$MAP" tasks T001 42 "https://gitlab.example.com/g/p/-/issues/42" +write_mapping "$MAP" tasks T002 43 +write_mapping "$MAP" tasks T001 44 +write_feature_mapping "$MAP" 232 "https://gitlab.example.com/g/p/-/issues/232" +assert_eq "#10 https://gitlab.example.com/g/p/-/issues/10" "$(read_mapping "$MAP" stories US1)" "story mapping" +assert_eq "#44" "$(read_mapping "$MAP" tasks T001)" "task mapping is updated in place" +assert_eq "#43" "$(read_mapping "$MAP" tasks T002)" "second task mapping" +assert_eq "" "$(read_mapping "$MAP" stories T001)" "lookups are section-scoped" +assert_eq "232" "$(extract_feature_issue_number "$(read_feature_mapping "$MAP")")" "feature mapping" +assert_eq $'T001\t#44\nT002\t#43' "$(list_mapping_ids "$MAP" tasks)" "list_mapping_ids" +if command -v python3 >/dev/null && python3 -c 'import yaml' 2>/dev/null; then + assert_eq "ok" "$(python3 -c 'import sys,yaml; d=yaml.safe_load(open(sys.argv[1])); print("ok" if d["tasks"]["T001"]=="#44" and d["stories"]["US1"].startswith("#10") else d)' "$MAP")" "mapping file is valid YAML" +fi + +# --- misc ------------------------------------------------------------------- +OUT=$'Creating issue in group/project\n#42 T001: Something (now)\n https://gitlab.example.com/group/project/-/issues/42\n' +assert_eq "https://gitlab.example.com/group/project/-/issues/42" "$(extract_issue_url "$OUT")" "extract_issue_url" +assert_eq "42" "$(extract_issue_number "$OUT")" "extract_issue_number" +assert_eq "priority::2" "$(priority_to_label P2)" "priority_to_label" +assert_eq "P3" "$(label_to_priority priority::3)" "label_to_priority" + +echo +FAILURES="$(wc -l < "$FAIL_LOG" | tr -d ' ')" +if [[ "$FAILURES" -gt 0 ]]; then + echo "$FAILURES test(s) failed" + exit 1 +fi +echo "All tests passed" From 5160d86eafaad4a0d5111e881af2af1eb184335a Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 21:08:08 +0000 Subject: [PATCH 2/3] Quote checkbox status argument in tests (ShellCheck SC1010) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FU4A2CPkCPyvBLkPvUsoVg --- tests/test-helpers.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test-helpers.sh b/tests/test-helpers.sh index 999bb6d..4ee1b84 100644 --- a/tests/test-helpers.sh +++ b/tests/test-helpers.sh @@ -97,8 +97,8 @@ assert_eq $'T010\topen\tUS1\t\tyes\t42\tContract test for endpoint in tests/cont assert_eq $'T1000\tdone\tUS2\t\tno\t\tImplement service (depends on T012)' "${TASKS[3]}" "four-digit task ID" assert_eq $'T003\topen\tUS1\tP1\tno\t\tLegacy priority marker' "${TASKS[4]}" "legacy [P1] priority marker" -set_task_checkbox "$TMP/tasks.md" T001 done -set_task_checkbox "$TMP/tasks.md" T002 open +set_task_checkbox "$TMP/tasks.md" T001 "done" +set_task_checkbox "$TMP/tasks.md" T002 "open" annotate_task_issue "$TMP/tasks.md" T001 7 annotate_task_issue "$TMP/tasks.md" T001 7 annotate_task_issue "$TMP/tasks.md" T010 99 From 9b440b5ae19b9e2a4e7652b42ab5c4efd9205e0d Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Thu, 5 Nov 2026 21:16:12 +0000 Subject: [PATCH 3/3] Add release workflow for one-command install Pushing a vX.Y.Z tag now builds spec-kit-gitlab.zip (manifest at the archive root), checks the tag against extension.yml, CHANGELOG.md and README.md, runs the tests and publishes a GitHub release with the zip, its SHA-256 and the install command. The README leads with that single-command install. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FU4A2CPkCPyvBLkPvUsoVg --- .github/workflows/release.yml | 80 +++++++++++++++++++++++++++++++++++ CHANGELOG.md | 1 + README.md | 29 ++++++++++--- 3 files changed, 104 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..385df11 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,80 @@ +name: Release + +# Push a tag like v1.1.0 to publish a release. The tag must match the version +# in extension.yml, and CHANGELOG.md needs a "## [1.1.0]" section. + +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Check version + id: version + run: | + TAG="${GITHUB_REF_NAME}" + VERSION="${TAG#v}" + MANIFEST_VERSION="$(grep -E '^[[:space:]]+version:' extension.yml | head -1 | sed -E 's/.*version:[[:space:]]*"?([^"]+)"?.*/\1/')" + if [[ "$VERSION" != "$MANIFEST_VERSION" ]]; then + echo "::error::Tag $TAG does not match extension.yml version $MANIFEST_VERSION" + exit 1 + fi + if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Version must be X.Y.Z (got $VERSION)" + exit 1 + fi + if ! grep -q "^## \[$VERSION\]" CHANGELOG.md; then + echo "::error::CHANGELOG.md has no section for $VERSION" + exit 1 + fi + if ! grep -q "/download/v$VERSION/" README.md; then + echo "::error::README.md install command doesn't point to v$VERSION" + exit 1 + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Run tests + run: bash tests/test-helpers.sh + + - name: Build archive + run: | + mkdir -p dist + zip -r -X dist/spec-kit-gitlab.zip \ + extension.yml README.md LICENSE CHANGELOG.md .extensionignore \ + gitlab-config.template.yml commands scripts + (cd dist && sha256sum spec-kit-gitlab.zip > spec-kit-gitlab.zip.sha256) + cat dist/spec-kit-gitlab.zip.sha256 + + - name: Release notes + run: | + awk -v v="${{ steps.version.outputs.version }}" ' + $0 ~ "^## \\[" v "\\]" { found = 1; next } + found && /^## \[/ { exit } + found { print } + ' CHANGELOG.md > dist/notes.md + { + echo + echo "## Install" + echo + echo '```bash' + echo "specify extension add gitlab --from https://github.com/${GITHUB_REPOSITORY}/releases/download/${GITHUB_REF_NAME}/spec-kit-gitlab.zip" + echo '```' + echo + echo "SHA-256: \`$(cut -d' ' -f1 dist/spec-kit-gitlab.zip.sha256)\`" + } >> dist/notes.md + + - name: Create release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" \ + dist/spec-kit-gitlab.zip dist/spec-kit-gitlab.zip.sha256 \ + --title "$GITHUB_REF_NAME" \ + --notes-file dist/notes.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 290d01a..88bb8f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ Brings the extension up to date with spec-kit 1.3 and the current glab CLI. - `--dry-run` for close-issues and sync, `--no-update` for status. - Offline tests (`tests/test-helpers.sh`) and a CI workflow. - `.extensionignore`, so tests and CI files aren't copied into projects. +- Release workflow: pushing a `vX.Y.Z` tag publishes a GitHub release with an installable `spec-kit-gitlab.zip` and its SHA-256, so the extension installs with a single `specify extension add ... --from <release URL>`. ### Fixed diff --git a/README.md b/README.md index 907515d..aec736c 100644 --- a/README.md +++ b/README.md @@ -13,20 +13,37 @@ Supports gitlab.com and self-hosted GitLab instances. ## Installation +In your spec-kit project: + ```bash -# Install and authenticate the glab CLI -brew install glab jq +specify extension add gitlab --from https://github.com/ohartwig/spec-kit-gitlab/releases/download/v1.1.0/spec-kit-gitlab.zip +``` + +Then run the setup command `speckit.gitlab.init` in your coding agent. Done. + +On install, spec-kit copies the config template to `.specify/extensions/gitlab/gitlab-config.yml` and registers the commands for your coding agent. Each [release](https://github.com/ohartwig/spec-kit-gitlab/releases) lists its install command and the archive's SHA-256. + +If `glab` and `jq` aren't installed yet: + +```bash +brew install glab jq # macOS; other systems: https://gitlab.com/gitlab-org/cli#installation glab auth login --hostname gitlab.example.com +``` + +<details> +<summary>Other ways to install</summary> -# Install the extension into your spec-kit project -cd /path/to/your/spec-kit-project +```bash +# Latest development version (main branch) specify extension add gitlab --from https://github.com/ohartwig/spec-kit-gitlab/archive/refs/heads/main.zip -# ...or from a local clone (development mode) +# From a local clone (development mode, picks up changes without reinstalling) specify extension add --dev ~/spec-kit-gitlab/ ``` -On install, spec-kit copies the config template to `.specify/extensions/gitlab/gitlab-config.yml` and registers the commands for your coding agent. +To update, run the install command of the new release with `--force`. Your `gitlab-config.yml` and `gitlab-config.local.yml` are kept. + +</details> ## Configuration