mirror of
https://github.com/Fission-AI/OpenSpec.git
synced 2026-10-03 22:13:19 +08:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
313afbb4c7 | ||
|
|
e4a02174f3 | ||
|
|
ce79ec0bab | ||
|
|
6de04f3b2b | ||
|
|
c2a1a4c807 | ||
|
|
2e71835d23 | ||
|
|
971f8ca4a3 | ||
|
|
68e0a7e68e | ||
|
|
f39cc5c1fb | ||
|
|
5129a8cf96 | ||
|
|
4ff893048d | ||
|
|
cefb4719aa | ||
|
|
5e1cef3b3b | ||
|
|
1adf3cea88 | ||
|
|
6d3cfe0443 | ||
|
|
17d1e5db3f | ||
|
|
3f5a66d3e4 | ||
|
|
c08fbc1ba0 | ||
|
|
938d03be9a |
@@ -142,6 +142,9 @@ jobs:
|
||||
- name: Type check
|
||||
run: pnpm exec tsc --noEmit
|
||||
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
|
||||
- name: Check for build artifacts
|
||||
run: |
|
||||
if [ ! -d "dist" ]; then
|
||||
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
id-token: write # Required for npm OIDC trusted publishing
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
@@ -27,11 +28,9 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24' # Node 24 includes npm 11.5.1+ required for OIDC
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
scope: '@fission-ai'
|
||||
always-auth: true
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -46,5 +45,4 @@ jobs:
|
||||
publish: pnpm run release:ci
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# npm authentication handled via OIDC trusted publishing (no token needed)
|
||||
|
||||
@@ -1,5 +1,40 @@
|
||||
# @fission-ai/openspec
|
||||
|
||||
## 0.17.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 2e71835: ### New Features
|
||||
|
||||
- Add `openspec config` command for managing global configuration settings
|
||||
- Implement global config directory with XDG Base Directory specification support
|
||||
- Add Oh-my-zsh shell completions support for enhanced CLI experience
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fix hang in pre-commit hooks by using dynamic imports
|
||||
- Respect XDG_CONFIG_HOME environment variable on all platforms
|
||||
- Resolve Windows compatibility issues in zsh-installer tests
|
||||
- Align cli-completion spec with implementation
|
||||
- Remove hardcoded agent field from slash commands
|
||||
|
||||
### Documentation
|
||||
|
||||
- Alphabetize AI tools list in README and make it collapsible
|
||||
|
||||
## 0.16.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- c08fbc1: Add new AI tool integrations and enhancements:
|
||||
|
||||
- **feat(iflow-cli)**: Add iFlow-cli integration with slash command support and documentation
|
||||
- **feat(init)**: Add IDE restart instruction after init to inform users about slash command availability
|
||||
**feat(antigravity)**: Add Antigravity slash command support
|
||||
- **fix**: Generate TOML commands for Qwen Code (fixes #293)
|
||||
- Clarify scaffold proposal documentation and enhance proposal guidelines
|
||||
- Update proposal guidelines to emphasize design-first approach before implementation
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -85,42 +85,49 @@ See the full comparison in [How OpenSpec Compares](#how-openspec-compares).
|
||||
|
||||
### Supported AI Tools
|
||||
|
||||
#### Native Slash Commands
|
||||
<details>
|
||||
<summary><strong>Native Slash Commands</strong> (click to expand)</summary>
|
||||
|
||||
These tools have built-in OpenSpec commands. Select the OpenSpec integration when prompted.
|
||||
|
||||
| Tool | Commands |
|
||||
|------|----------|
|
||||
| **Amazon Q Developer** | `@openspec-proposal`, `@openspec-apply`, `@openspec-archive` (`.amazonq/prompts/`) |
|
||||
| **Antigravity** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.agent/workflows/`) |
|
||||
| **Auggie (Augment CLI)** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.augment/commands/`) |
|
||||
| **Claude Code** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` |
|
||||
| **CodeBuddy Code (CLI)** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` (`.codebuddy/commands/`) — see [docs](https://www.codebuddy.ai/cli) |
|
||||
| **CoStrict** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.cospec/openspec/commands/`) — see [docs](https://costrict.ai)|
|
||||
| **Cursor** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **Cline** | Workflows in `.clinerules/workflows/` directory (`.clinerules/workflows/openspec-*.md`) |
|
||||
| **CodeBuddy Code (CLI)** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` (`.codebuddy/commands/`) — see [docs](https://www.codebuddy.ai/cli) |
|
||||
| **Codex** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (global: `~/.codex/prompts`, auto-installed) |
|
||||
| **CoStrict** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.cospec/openspec/commands/`) — see [docs](https://costrict.ai)|
|
||||
| **Crush** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.crush/commands/openspec/`) |
|
||||
| **RooCode** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.roo/commands/`) |
|
||||
| **Cursor** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **Factory Droid** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.factory/commands/`) |
|
||||
| **Gemini CLI** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` (`.gemini/commands/openspec/`) |
|
||||
| **OpenCode** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **Kilo Code** | `/openspec-proposal.md`, `/openspec-apply.md`, `/openspec-archive.md` (`.kilocode/workflows/`) |
|
||||
| **Qoder (CLI)** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` (`.qoder/commands/openspec/`) — see [docs](https://qoder.com/cli) |
|
||||
| **Antigravity** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.agent/workflows/`) |
|
||||
| **Windsurf** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.windsurf/workflows/`) |
|
||||
| **Codex** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (global: `~/.codex/prompts`, auto-installed) |
|
||||
| **GitHub Copilot** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.github/prompts/`) |
|
||||
| **Amazon Q Developer** | `@openspec-proposal`, `@openspec-apply`, `@openspec-archive` (`.amazonq/prompts/`) |
|
||||
| **Auggie (Augment CLI)** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.augment/commands/`) |
|
||||
| **Qwen Code** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.qwen/commands/`) |
|
||||
| **iFlow (iflow-cli)** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.iflow/commands/`) |
|
||||
|
||||
| **Kilo Code** | `/openspec-proposal.md`, `/openspec-apply.md`, `/openspec-archive.md` (`.kilocode/workflows/`) |
|
||||
| **OpenCode** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **Qoder (CLI)** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` (`.qoder/commands/openspec/`) — see [docs](https://qoder.com/cli) |
|
||||
| **Qwen Code** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.qwen/commands/`) |
|
||||
| **RooCode** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.roo/commands/`) |
|
||||
| **Windsurf** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.windsurf/workflows/`) |
|
||||
|
||||
Kilo Code discovers team workflows automatically. Save the generated files under `.kilocode/workflows/` and trigger them from the command palette with `/openspec-proposal.md`, `/openspec-apply.md`, or `/openspec-archive.md`.
|
||||
|
||||
#### AGENTS.md Compatible
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>AGENTS.md Compatible</strong> (click to expand)</summary>
|
||||
|
||||
These tools automatically read workflow instructions from `openspec/AGENTS.md`. Ask them to follow the OpenSpec workflow if they need a reminder. Learn more about the [AGENTS.md convention](https://agents.md/).
|
||||
|
||||
| Tools |
|
||||
|-------|
|
||||
| Amp • Jules • Others |
|
||||
|
||||
</details>
|
||||
|
||||
### Install & Initialize
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
files: ['src/**/*.ts'],
|
||||
extends: [...tseslint.configs.recommended],
|
||||
rules: {
|
||||
// Prevent static imports of @inquirer modules to avoid pre-commit hook hangs.
|
||||
// These modules have side effects that can keep the Node.js event loop alive
|
||||
// when stdin is piped. Use dynamic import() instead.
|
||||
// See: https://github.com/Fission-AI/OpenSpec/issues/367
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
patterns: [
|
||||
{
|
||||
group: ['@inquirer/*'],
|
||||
message:
|
||||
'Use dynamic import() for @inquirer modules to prevent pre-commit hook hangs. See #367.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
// Disable rules that need broader cleanup - focus on critical issues only
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'no-empty': 'off',
|
||||
'prefer-const': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// init.ts is dynamically imported from cli/index.ts, so static @inquirer
|
||||
// imports there are safe - they won't be loaded at CLI startup
|
||||
files: ['src/core/init.ts'],
|
||||
rules: {
|
||||
'no-restricted-imports': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: ['dist/**', 'node_modules/**', '*.js', '*.mjs'],
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,525 @@
|
||||
# Shell Completions Design
|
||||
|
||||
## Overview
|
||||
|
||||
This design establishes a plugin-based architecture for shell completions that prioritizes clean TypeScript patterns, scalability, and maintainability. The system separates concerns between shell-specific generation logic, dynamic completion data providers, and installation automation.
|
||||
|
||||
**Scope:** This proposal implements **Zsh completion only** (with Oh My Zsh priority). The architecture is designed to support bash, fish, and PowerShell in future proposals.
|
||||
|
||||
## Native Shell Completion Behaviors
|
||||
|
||||
**Design Philosophy:** We integrate with each shell's native completion system rather than attempting to customize or unify behaviors. This ensures familiar UX for users and reduces maintenance complexity.
|
||||
|
||||
**Note:** While all four shell behaviors are documented below for architectural reference, **only Zsh is implemented in this proposal**. Bash, Fish, and PowerShell are documented to guide future implementations.
|
||||
|
||||
### Bash Completion Behavior
|
||||
|
||||
**Interaction Pattern:**
|
||||
- **Single TAB:** Completes if only one match exists, otherwise does nothing
|
||||
- **Double TAB (TAB TAB):** Displays all possible completions as a list
|
||||
- **Type more characters + TAB:** Narrows matches and completes or shows refined list
|
||||
|
||||
**OpenSpec Integration:**
|
||||
```bash
|
||||
# After installing: openspec completion install bash
|
||||
openspec val<TAB> # Completes to "openspec validate"
|
||||
openspec validate <TAB><TAB> # Shows: --all --changes --specs --strict --json [change-ids] [spec-ids]
|
||||
openspec show add-<TAB><TAB> # Shows all changes starting with "add-"
|
||||
```
|
||||
|
||||
**Implementation:** Uses bash-completion framework with `_init_completion`, `compgen`, and `COMPREPLY` array.
|
||||
|
||||
### Zsh Completion Behavior (with Oh My Zsh)
|
||||
|
||||
**Interaction Pattern:**
|
||||
- **Single TAB:** Shows interactive menu with all matches immediately
|
||||
- **TAB / Arrow Keys:** Navigate through completion options
|
||||
- **Enter:** Selects highlighted option
|
||||
- **Ctrl+C / Esc:** Cancels completion menu
|
||||
|
||||
**OpenSpec Integration:**
|
||||
```zsh
|
||||
# After installing: openspec completion install zsh
|
||||
openspec val<TAB> # Shows menu with "validate" and "view" highlighted
|
||||
openspec show <TAB> # Shows menu with all change IDs and spec IDs, categorized
|
||||
```
|
||||
|
||||
**Implementation:** Uses Zsh completion system with `_arguments`, `_describe`, and `compadd` built-ins. Oh My Zsh provides enhanced menu styling automatically.
|
||||
|
||||
### Fish Completion Behavior
|
||||
|
||||
**Interaction Pattern:**
|
||||
- **As-you-type:** Gray suggestions appear automatically in real-time
|
||||
- **Right Arrow / Ctrl+F:** Accepts the suggestion
|
||||
- **TAB:** Shows menu with all matches if multiple exist
|
||||
- **TAB again:** Cycles through options or navigates menu
|
||||
- **Enter:** Accepts current selection
|
||||
|
||||
**OpenSpec Integration:**
|
||||
```fish
|
||||
# After installing: openspec completion install fish
|
||||
openspec val # Gray suggestion shows "validate" immediately
|
||||
openspec show a # Real-time suggestions for changes starting with "a"
|
||||
openspec <TAB> # Shows all commands with descriptions in paged menu
|
||||
```
|
||||
|
||||
**Implementation:** Uses Fish's declarative `complete -c` syntax. Completions are auto-loaded from `~/.config/fish/completions/`.
|
||||
|
||||
### PowerShell Completion Behavior
|
||||
|
||||
**Interaction Pattern:**
|
||||
- **TAB:** Cycles forward through completions one at a time (inline replacement)
|
||||
- **Shift+TAB:** Cycles backward through completions
|
||||
- **Ctrl+Space:** Shows IntelliSense-style menu (PSReadLine v2.2+)
|
||||
- **Arrow Keys:** Navigate menu if shown
|
||||
|
||||
**OpenSpec Integration:**
|
||||
```powershell
|
||||
# After installing: openspec completion install powershell
|
||||
openspec val<TAB> # Cycles: validate → view → validate
|
||||
openspec show <TAB> # Cycles through change IDs one by one
|
||||
openspec <Ctrl+Space> # Shows IntelliSense menu with all commands
|
||||
```
|
||||
|
||||
**Implementation:** Uses `Register-ArgumentCompleter` with custom script block that returns `[System.Management.Automation.CompletionResult]` objects.
|
||||
|
||||
### Comparison Table
|
||||
|
||||
| Shell | Trigger | Display Style | Navigation | Selection |
|
||||
|-------------|-----------------|------------------------|----------------------|----------------|
|
||||
| Bash | TAB TAB | List (printed once) | Type more + TAB | Auto-complete |
|
||||
| Zsh | TAB | Interactive menu | TAB/Arrows | Enter |
|
||||
| Fish | TAB/Auto | Real-time + menu | TAB/Arrows | Enter/Right |
|
||||
| PowerShell | TAB | Inline cycling | TAB/Shift+TAB | Stop cycling |
|
||||
|
||||
**Key Insight:** Each shell's completion UX reflects its design philosophy. We respect these conventions rather than forcing uniformity.
|
||||
|
||||
## Architectural Principles
|
||||
|
||||
### 1. Plugin-Based Generator System
|
||||
|
||||
Each shell has unique completion syntax and conventions. Rather than creating a monolithic generator with branching logic, we use a plugin pattern where each shell implements a common interface:
|
||||
|
||||
```typescript
|
||||
interface CompletionGenerator {
|
||||
generate(): string;
|
||||
getInstallPath(): string;
|
||||
getConfigFile(): string;
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- New shells can be added without modifying existing generators
|
||||
- Shell-specific logic is isolated and testable
|
||||
- Type safety ensures all generators implement required methods
|
||||
- Easy to maintain and understand (single responsibility per generator)
|
||||
|
||||
**Implementation Classes:**
|
||||
- `ZshCompletionGenerator` - Uses Zsh's `_arguments` and `_describe` functions
|
||||
- `BashCompletionGenerator` - Uses `_init_completion` and `compgen` built-ins
|
||||
- `FishCompletionGenerator` - Uses `complete -c` declarative syntax
|
||||
- `PowerShellCompletionGenerator` - Uses `Register-ArgumentCompleter` cmdlet
|
||||
|
||||
### 2. Centralized Command Registry
|
||||
|
||||
Shell completions must stay synchronized with actual CLI commands. To avoid duplication and drift, we maintain a single source of truth:
|
||||
|
||||
```typescript
|
||||
type CommandDefinition = {
|
||||
name: string;
|
||||
description: string;
|
||||
flags: FlagDefinition[];
|
||||
acceptsChangeId: boolean;
|
||||
acceptsSpecId: boolean;
|
||||
subcommands?: CommandDefinition[];
|
||||
};
|
||||
|
||||
const COMMAND_REGISTRY: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec in your project',
|
||||
flags: [
|
||||
{ name: '--tools', description: 'Configure AI tools non-interactively', hasValue: true }
|
||||
],
|
||||
acceptsChangeId: false,
|
||||
acceptsSpecId: false
|
||||
},
|
||||
// ... all other commands
|
||||
];
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- All generators consume the same command definitions
|
||||
- Adding a new command automatically propagates to all shells
|
||||
- Flag changes only need to be made in one place
|
||||
- Type safety prevents typos and missing fields
|
||||
- Easier to test (mock the registry)
|
||||
|
||||
**TypeScript Sugar:**
|
||||
- Use `const` assertions for readonly registry
|
||||
- Leverage discriminated unions for command types
|
||||
- Use `satisfies` operator to ensure registry matches interface
|
||||
|
||||
### 3. Dynamic Completion Provider
|
||||
|
||||
Change and spec IDs are project-specific and discovered at runtime. A dedicated provider encapsulates this logic:
|
||||
|
||||
```typescript
|
||||
class CompletionProvider {
|
||||
private changeCache: { ids: string[]; timestamp: number } | null = null;
|
||||
private specCache: { ids: string[]; timestamp: number } | null = null;
|
||||
private readonly CACHE_TTL_MS = 2000;
|
||||
|
||||
async getChangeIds(): Promise<string[]> {
|
||||
if (this.changeCache && Date.now() - this.changeCache.timestamp < this.CACHE_TTL_MS) {
|
||||
return this.changeCache.ids;
|
||||
}
|
||||
|
||||
const ids = await discoverActiveChangeIds();
|
||||
this.changeCache = { ids, timestamp: Date.now() };
|
||||
return ids;
|
||||
}
|
||||
|
||||
async getSpecIds(): Promise<string[]> {
|
||||
// Similar caching logic
|
||||
}
|
||||
|
||||
isOpenSpecProject(): boolean {
|
||||
// Check for openspec/ directory
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Caching reduces file system overhead during rapid tab completion
|
||||
- Encapsulates project detection logic
|
||||
- Easy to test with mocked file system
|
||||
- Shared across all shell generators
|
||||
|
||||
**Design Decisions:**
|
||||
- 2-second cache TTL balances freshness with performance
|
||||
- Cache per-process (not persistent) to avoid stale data across sessions
|
||||
- Graceful degradation when outside OpenSpec projects
|
||||
|
||||
### 4. Separate Installation Logic
|
||||
|
||||
Installation involves shell configuration file manipulation, which differs from generation. We separate this concern:
|
||||
|
||||
```typescript
|
||||
interface CompletionInstaller {
|
||||
install(): Promise<InstallResult>;
|
||||
uninstall(): Promise<UninstallResult>;
|
||||
isInstalled(): Promise<boolean>;
|
||||
}
|
||||
```
|
||||
|
||||
**Shell-Specific Installers:**
|
||||
- `ZshInstaller` - Handles both Oh My Zsh (custom completions) and standard Zsh (fpath)
|
||||
- `BashInstaller` - Detects completion directories and sources from `.bashrc`
|
||||
- `FishInstaller` - Writes to `~/.config/fish/completions/` (auto-loaded)
|
||||
- `PowerShellInstaller` - Appends to PowerShell profile
|
||||
|
||||
**Benefits:**
|
||||
- Installation logic doesn't pollute generator code
|
||||
- Can test installation without generating completion scripts
|
||||
- Easier to handle edge cases (missing directories, permissions, already installed)
|
||||
|
||||
### 5. Type-Safe Shell Detection
|
||||
|
||||
We use TypeScript's literal types and type guards for shell detection:
|
||||
|
||||
```typescript
|
||||
type SupportedShell = 'bash' | 'zsh' | 'fish' | 'powershell';
|
||||
|
||||
function detectShell(): SupportedShell {
|
||||
const shellPath = process.env.SHELL || '';
|
||||
const shellName = path.basename(shellPath).toLowerCase();
|
||||
|
||||
// PowerShell normalization
|
||||
if (shellName === 'pwsh' || shellName === 'powershell') {
|
||||
return 'powershell';
|
||||
}
|
||||
|
||||
const supported: SupportedShell[] = ['bash', 'zsh', 'fish', 'powershell'];
|
||||
if (supported.includes(shellName as SupportedShell)) {
|
||||
return shellName as SupportedShell;
|
||||
}
|
||||
|
||||
throw new Error(`Shell '${shellName}' is not supported. Supported: ${supported.join(', ')}`);
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Compile-time type checking prevents invalid shell names
|
||||
- Easy to add new shells (add to union type)
|
||||
- Type narrowing works in switch statements
|
||||
- Clear error messages for unsupported shells
|
||||
|
||||
### 6. Factory Pattern for Instantiation
|
||||
|
||||
A factory function selects the appropriate generator/installer based on shell type:
|
||||
|
||||
```typescript
|
||||
function createGenerator(shell: SupportedShell, provider: CompletionProvider): CompletionGenerator {
|
||||
switch (shell) {
|
||||
case 'bash': return new BashCompletionGenerator(COMMAND_REGISTRY, provider);
|
||||
case 'zsh': return new ZshCompletionGenerator(COMMAND_REGISTRY, provider);
|
||||
case 'fish': return new FishCompletionGenerator(COMMAND_REGISTRY, provider);
|
||||
case 'powershell': return new PowerShellCompletionGenerator(COMMAND_REGISTRY, provider);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Single point of instantiation
|
||||
- Type safety ensures exhaustive switch (TypeScript error if shell type missing)
|
||||
- Easy to inject dependencies (registry, provider)
|
||||
|
||||
## Command Structure
|
||||
|
||||
**This Proposal (Zsh-only):**
|
||||
```
|
||||
openspec completion
|
||||
├── zsh # Generate Zsh completion script
|
||||
├── install [shell] # Install Zsh completion (auto-detects or explicit zsh)
|
||||
└── uninstall [shell] # Remove Zsh completion (auto-detects or explicit zsh)
|
||||
```
|
||||
|
||||
**Future (after follow-up proposals):**
|
||||
```
|
||||
openspec completion
|
||||
├── bash # Generate Bash completion script (future)
|
||||
├── zsh # Generate Zsh completion script (this proposal)
|
||||
├── fish # Generate Fish completion script (future)
|
||||
├── powershell # Generate PowerShell completion script (future)
|
||||
├── install [shell] # Install completion (auto-detects or explicit shell)
|
||||
└── uninstall [shell] # Remove completion (auto-detects or explicit shell)
|
||||
```
|
||||
|
||||
## File Organization
|
||||
|
||||
**This Proposal (Zsh-only):**
|
||||
```
|
||||
src/
|
||||
├── commands/
|
||||
│ └── completion.ts # CLI command registration (zsh, install, uninstall)
|
||||
├── core/
|
||||
│ └── completions/
|
||||
│ ├── types.ts # Interfaces: CompletionGenerator, CommandDefinition, etc.
|
||||
│ ├── command-registry.ts # Single source of truth for OpenSpec commands
|
||||
│ ├── completion-provider.ts # Dynamic change/spec ID discovery with caching
|
||||
│ ├── factory.ts # Factory for instantiating Zsh generator/installer
|
||||
│ ├── generators/
|
||||
│ │ └── zsh-generator.ts # Zsh completion script generator
|
||||
│ └── installers/
|
||||
│ └── zsh-installer.ts # Handles Oh My Zsh + standard Zsh installation
|
||||
└── utils/
|
||||
└── shell-detection.ts # Shell detection (returns 'zsh' or throws)
|
||||
```
|
||||
|
||||
**Future additions (bash, fish, powershell):**
|
||||
- `generators/bash-generator.ts`, `fish-generator.ts`, `powershell-generator.ts`
|
||||
- `installers/bash-installer.ts`, `fish-installer.ts`, `powershell-installer.ts`
|
||||
- Update `shell-detection.ts` to support additional shell types
|
||||
|
||||
## Oh My Zsh Priority
|
||||
|
||||
Zsh implementation prioritizes Oh My Zsh because:
|
||||
1. **Popularity** - Oh My Zsh is the most popular Zsh configuration framework
|
||||
2. **Convention** - Has standard completion directory (`~/.oh-my-zsh/custom/completions/`)
|
||||
3. **Detection** - Easy to detect via `$ZSH` environment variable
|
||||
4. **Fallback** - Standard Zsh support provides compatibility when Oh My Zsh isn't installed
|
||||
|
||||
**Installation Strategy:**
|
||||
```typescript
|
||||
if (isOhMyZshInstalled()) {
|
||||
// Install to ~/.oh-my-zsh/custom/completions/_openspec
|
||||
// Automatically loaded by Oh My Zsh
|
||||
} else {
|
||||
// Install to ~/.zsh/completions/_openspec
|
||||
// Update ~/.zshrc with fpath and compinit if needed
|
||||
}
|
||||
```
|
||||
|
||||
## Caching Strategy
|
||||
|
||||
Dynamic completions cache results for 2 seconds to balance freshness with performance:
|
||||
|
||||
**Why 2 seconds?**
|
||||
- Typical tab completion sessions last < 2 seconds
|
||||
- Prevents repeated file system scans during rapid tabbing
|
||||
- Short enough to feel "live" when changes/specs are added
|
||||
- Automatic per-process expiration (no stale data across sessions)
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
private changeCache: { ids: string[]; timestamp: number } | null = null;
|
||||
private readonly CACHE_TTL_MS = 2000;
|
||||
|
||||
if (this.changeCache && Date.now() - this.changeCache.timestamp < this.CACHE_TTL_MS) {
|
||||
return this.changeCache.ids; // Use cached
|
||||
}
|
||||
// Refresh cache
|
||||
```
|
||||
|
||||
## Error Handling Philosophy
|
||||
|
||||
Completions should degrade gracefully rather than break workflows:
|
||||
|
||||
1. **Unsupported shell** - Clear error with list of supported shells
|
||||
2. **Not in OpenSpec project** - Skip dynamic completions, only offer static commands
|
||||
3. **Permission errors** - Suggest alternative installation methods
|
||||
4. **Missing config directories** - Auto-create with user notification
|
||||
5. **Already installed** - Offer to reinstall/update
|
||||
6. **Not installed (during uninstall)** - Exit gracefully with informational message
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Each component is independently testable:
|
||||
|
||||
1. **Unit Tests**
|
||||
- Shell detection with mocked `$SHELL` environment variable
|
||||
- Generator output verification (regex pattern matching)
|
||||
- Completion provider caching behavior
|
||||
- Command registry structure validation
|
||||
|
||||
2. **Integration Tests**
|
||||
- Installation to temporary test directories
|
||||
- Configuration file modifications
|
||||
- End-to-end command flow (generate → install → verify)
|
||||
|
||||
3. **Manual Testing**
|
||||
- Real shell environments (Oh My Zsh, Bash, Fish, PowerShell)
|
||||
- Tab completion behavior in OpenSpec projects
|
||||
- Dynamic change/spec ID suggestions
|
||||
- Installation/uninstallation workflows
|
||||
|
||||
## TypeScript Sugar Patterns
|
||||
|
||||
### 1. Const Assertions for Immutable Data
|
||||
```typescript
|
||||
const COMMAND_REGISTRY = [
|
||||
{ name: 'init', ... },
|
||||
{ name: 'list', ... }
|
||||
] as const;
|
||||
```
|
||||
|
||||
### 2. Discriminated Unions for Command Types
|
||||
```typescript
|
||||
type Command =
|
||||
| { type: 'simple'; name: string }
|
||||
| { type: 'with-subcommands'; name: string; subcommands: Command[] };
|
||||
```
|
||||
|
||||
### 3. Template Literal Types for Strings
|
||||
```typescript
|
||||
type ShellConfigFile = `~/.${SupportedShell}rc` | `~/.${SupportedShell}_profile`;
|
||||
```
|
||||
|
||||
### 4. Satisfies Operator for Type Validation
|
||||
```typescript
|
||||
const config = {
|
||||
shell: 'zsh',
|
||||
path: '~/.zshrc'
|
||||
} satisfies ShellConfig;
|
||||
```
|
||||
|
||||
### 5. Optional Chaining and Nullish Coalescing
|
||||
```typescript
|
||||
const path = process.env.ZSH ?? `${os.homedir()}/.oh-my-zsh`;
|
||||
```
|
||||
|
||||
### 6. Async/Await with Promise.all for Parallel Operations
|
||||
```typescript
|
||||
const [changes, specs] = await Promise.all([
|
||||
provider.getChangeIds(),
|
||||
provider.getSpecIds()
|
||||
]);
|
||||
```
|
||||
|
||||
## Scalability Considerations
|
||||
|
||||
### Adding a New Shell
|
||||
|
||||
1. Define shell in `SupportedShell` union type
|
||||
2. Create generator class implementing `CompletionGenerator`
|
||||
3. Create installer class implementing `CompletionInstaller`
|
||||
4. Add cases to factory functions
|
||||
5. Add command registration in CLI
|
||||
6. Write tests
|
||||
|
||||
**TypeScript will enforce** that all switch statements are updated (exhaustiveness checking).
|
||||
|
||||
### Adding a New Command
|
||||
|
||||
1. Add to `COMMAND_REGISTRY` with appropriate metadata
|
||||
2. All generators automatically include it
|
||||
3. Update tests to verify new command appears
|
||||
|
||||
### Changing Completion Behavior
|
||||
|
||||
Dynamic completion logic is centralized in `CompletionProvider`, making behavior changes trivial without touching shell-specific code.
|
||||
|
||||
## Trade-offs and Decisions
|
||||
|
||||
### Decision: Separate Generators vs. Template Engine
|
||||
|
||||
**Chosen:** Separate generator classes per shell
|
||||
|
||||
**Alternative:** Template engine with shell-specific templates
|
||||
|
||||
**Rationale:**
|
||||
- Shell completion syntax is fundamentally different (not just text substitution)
|
||||
- Type safety is better with classes than templates
|
||||
- Logic complexity (caching, dynamic completions) doesn't fit template paradigm
|
||||
- Easier to debug and test dedicated classes
|
||||
|
||||
### Decision: 2-Second Cache TTL
|
||||
|
||||
**Chosen:** 2-second cache
|
||||
|
||||
**Alternatives:** No cache (slow), longer cache (stale), persistent cache (complex)
|
||||
|
||||
**Rationale:**
|
||||
- Balances performance with freshness
|
||||
- Matches typical user interaction patterns
|
||||
- Simple implementation (no invalidation complexity)
|
||||
- Automatic cleanup on process exit
|
||||
|
||||
### Decision: Oh My Zsh Detection
|
||||
|
||||
**Chosen:** Check `$ZSH` env var first, then `~/.oh-my-zsh/` directory
|
||||
|
||||
**Rationale:**
|
||||
- `$ZSH` is set by Oh My Zsh initialization (reliable)
|
||||
- Directory check is fallback for non-interactive scenarios
|
||||
- Standard Zsh serves as ultimate fallback
|
||||
|
||||
### Decision: Installation Automation vs. Manual Instructions
|
||||
|
||||
**Chosen:** Automated installation with install/uninstall commands
|
||||
|
||||
**Alternative:** Generate script and provide manual installation instructions
|
||||
|
||||
**Rationale:**
|
||||
- Better user experience (one command vs. multiple manual steps)
|
||||
- Reduces errors from manual configuration
|
||||
- Aligns with user expectations for modern CLI tools
|
||||
- Still supports manual workflow via script generation to stdout
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Contextual Flag Completion** - Suggest only valid flags for current command
|
||||
2. **Fuzzy Matching** - Allow partial matching for change/spec IDs
|
||||
3. **Rich Descriptions** - Include "why" section in completion suggestions (shell-dependent)
|
||||
4. **Completion Stats** - Track completion usage for analytics
|
||||
5. **Custom Completion Hooks** - Allow projects to extend completions
|
||||
6. **MCP Integration** - Provide completions via Model Context Protocol
|
||||
|
||||
## References
|
||||
|
||||
- [Bash Programmable Completion](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html)
|
||||
- [Zsh Completion System](https://zsh.sourceforge.io/Doc/Release/Completion-System.html)
|
||||
- [Fish Completions](https://fishshell.com/docs/current/completions.html)
|
||||
- [PowerShell Argument Completers](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/register-argumentcompleter)
|
||||
- [Oh My Zsh Custom Completions](https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#adding-custom-completions)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Add Shell Completions
|
||||
|
||||
## Why
|
||||
|
||||
OpenSpec CLI commands lack shell completion, forcing users to remember all commands, subcommands, flags, and change/spec IDs manually. This creates friction during daily use and slows developer workflows. Shell completions are a standard expectation for modern CLI tools and significantly improve user experience through:
|
||||
- Faster command discovery via tab completion
|
||||
- Reduced cognitive load by removing memorization requirements
|
||||
- Fewer typos through validated suggestions
|
||||
- Professional polish expected of production-grade tools
|
||||
|
||||
## What Changes
|
||||
|
||||
This change adds shell completion support for the OpenSpec CLI, starting with **Zsh (including Oh My Zsh)** and establishing a scalable architecture for future shells (bash, fish, PowerShell). The implementation provides:
|
||||
|
||||
1. **New `openspec completion` command** with Zsh generation and installation/uninstallation capabilities
|
||||
2. **Native Zsh integration** that respects standard Zsh tab completion behavior (single-TAB menu navigation)
|
||||
3. **Dynamic completion providers** that discover active changes and specs from the current project
|
||||
4. **Plugin-based architecture** using TypeScript interfaces for easy extension to additional shells in future proposals
|
||||
5. **Installation automation** for Oh My Zsh (priority) and standard Zsh configurations
|
||||
6. **Context-aware suggestions** that only activate within OpenSpec-enabled projects
|
||||
|
||||
The architecture emphasizes clean TypeScript patterns, composable generators, separation of concerns between shell-specific logic and shared completion data providers, and integration with native shell completion systems. Other shells (bash, fish, PowerShell) are architecturally documented but not implemented in this proposal—they will be added in follow-up changes.
|
||||
|
||||
## Deltas
|
||||
|
||||
### Delta: New CLI completion specification
|
||||
- **Spec:** cli-completion
|
||||
- **Operation:** ADDED
|
||||
- **Description:** Defines requirements for the new `openspec completion` command including generation, installation, and shell-specific behaviors for Oh My Zsh, bash, fish, and PowerShell.
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
# CLI Completion Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
The `openspec completion` command SHALL provide shell completion functionality for all OpenSpec CLI commands, flags, and dynamic values (change IDs, spec IDs), with support for Zsh (including Oh My Zsh) and a scalable architecture ready for future shells (bash, fish, PowerShell). The completion system SHALL integrate with Zsh's native completion behavior rather than attempting to customize the user experience.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Native Shell Behavior Integration
|
||||
|
||||
The completion system SHALL respect and integrate with Zsh's native completion patterns and user interaction model.
|
||||
|
||||
#### Scenario: Zsh native completion
|
||||
|
||||
- **WHEN** generating Zsh completion scripts
|
||||
- **THEN** use Zsh completion system with `_arguments`, `_describe`, and `compadd`
|
||||
- **AND** completions SHALL trigger on single TAB (standard Zsh behavior)
|
||||
- **AND** display as an interactive menu that users navigate with TAB/arrow keys
|
||||
- **AND** support Oh My Zsh's enhanced menu styling automatically
|
||||
|
||||
#### Scenario: No custom UX patterns
|
||||
|
||||
- **WHEN** implementing Zsh completion
|
||||
- **THEN** do NOT attempt to customize completion trigger behavior
|
||||
- **AND** do NOT override Zsh-specific navigation patterns
|
||||
- **AND** ensure completions feel native to experienced Zsh users
|
||||
|
||||
### Requirement: Command Structure
|
||||
|
||||
The completion command SHALL follow a subcommand pattern for generating and managing completion scripts.
|
||||
|
||||
#### Scenario: Available subcommands
|
||||
|
||||
- **WHEN** user executes `openspec completion --help`
|
||||
- **THEN** display available subcommands:
|
||||
- `zsh` - Generate Zsh completion script
|
||||
- `install [shell]` - Install completion for Zsh (auto-detects or requires explicit shell)
|
||||
- `uninstall [shell]` - Remove completion for Zsh (auto-detects or requires explicit shell)
|
||||
|
||||
### Requirement: Shell Detection
|
||||
|
||||
The completion system SHALL automatically detect the user's current shell environment.
|
||||
|
||||
#### Scenario: Detecting Zsh from environment
|
||||
|
||||
- **WHEN** no shell is explicitly specified
|
||||
- **THEN** read the `$SHELL` environment variable
|
||||
- **AND** extract the shell name from the path (e.g., `/bin/zsh` → `zsh`)
|
||||
- **AND** validate the shell is `zsh`
|
||||
- **AND** throw an error if the shell is not `zsh`, with message indicating only Zsh is currently supported
|
||||
|
||||
#### Scenario: Non-Zsh shell detection
|
||||
|
||||
- **WHEN** shell path indicates bash, fish, powershell, or other non-Zsh shell
|
||||
- **THEN** throw error: "Shell '<name>' is not supported yet. Currently supported: zsh"
|
||||
|
||||
### Requirement: Completion Generation
|
||||
|
||||
The completion command SHALL generate Zsh completion scripts on demand.
|
||||
|
||||
#### Scenario: Generating Zsh completion
|
||||
|
||||
- **WHEN** user executes `openspec completion zsh`
|
||||
- **THEN** output a complete Zsh completion script to stdout
|
||||
- **AND** include completions for all commands: init, list, show, validate, archive, view, update, change, spec, completion
|
||||
- **AND** include all command-specific flags and options
|
||||
- **AND** use Zsh's `_arguments` and `_describe` built-in functions
|
||||
- **AND** support dynamic completion for change and spec IDs
|
||||
|
||||
### Requirement: Dynamic Completions
|
||||
|
||||
The completion system SHALL provide context-aware dynamic completions for project-specific values.
|
||||
|
||||
#### Scenario: Completing change IDs
|
||||
|
||||
- **WHEN** completing arguments for commands that accept change names (show, validate, archive)
|
||||
- **THEN** discover active changes from `openspec/changes/` directory
|
||||
- **AND** exclude archived changes in `openspec/changes/archive/`
|
||||
- **AND** return change IDs as completion suggestions
|
||||
- **AND** only provide suggestions when inside an OpenSpec-enabled project
|
||||
|
||||
#### Scenario: Completing spec IDs
|
||||
|
||||
- **WHEN** completing arguments for commands that accept spec names (show, validate)
|
||||
- **THEN** discover specs from `openspec/specs/` directory
|
||||
- **AND** return spec IDs as completion suggestions
|
||||
- **AND** only provide suggestions when inside an OpenSpec-enabled project
|
||||
|
||||
#### Scenario: Completion caching
|
||||
|
||||
- **WHEN** dynamic completions are requested
|
||||
- **THEN** cache discovered change and spec IDs for 2 seconds
|
||||
- **AND** reuse cached values for subsequent requests within cache window
|
||||
- **AND** automatically refresh cache after expiration
|
||||
|
||||
#### Scenario: Project detection
|
||||
|
||||
- **WHEN** user requests completions outside an OpenSpec project
|
||||
- **THEN** skip dynamic change/spec ID completions
|
||||
- **AND** only suggest static commands and flags
|
||||
|
||||
### Requirement: Installation Automation
|
||||
|
||||
The completion command SHALL automatically install completion scripts into shell configuration files.
|
||||
|
||||
#### Scenario: Installing for Oh My Zsh
|
||||
|
||||
- **WHEN** user executes `openspec completion install zsh`
|
||||
- **THEN** detect if Oh My Zsh is installed by checking for `$ZSH` environment variable or `~/.oh-my-zsh/` directory
|
||||
- **AND** create custom completions directory at `~/.oh-my-zsh/custom/completions/` if it doesn't exist
|
||||
- **AND** write completion script to `~/.oh-my-zsh/custom/completions/_openspec`
|
||||
- **AND** ensure `~/.oh-my-zsh/custom/completions` is in `$fpath` by updating `~/.zshrc` if needed
|
||||
- **AND** display success message with instruction to run `exec zsh` or restart terminal
|
||||
|
||||
#### Scenario: Installing for standard Zsh
|
||||
|
||||
- **WHEN** user executes `openspec completion install zsh` and Oh My Zsh is not detected
|
||||
- **THEN** create completions directory at `~/.zsh/completions/` if it doesn't exist
|
||||
- **AND** write completion script to `~/.zsh/completions/_openspec`
|
||||
- **AND** add `fpath=(~/.zsh/completions $fpath)` to `~/.zshrc` if not already present
|
||||
- **AND** add `autoload -Uz compinit && compinit` to `~/.zshrc` if not already present
|
||||
- **AND** display success message with instruction to run `exec zsh` or restart terminal
|
||||
|
||||
#### Scenario: Auto-detecting Zsh for installation
|
||||
|
||||
- **WHEN** user executes `openspec completion install` without specifying a shell
|
||||
- **THEN** detect current shell using shell detection logic
|
||||
- **AND** install completion if detected shell is Zsh
|
||||
- **AND** throw error if detected shell is not Zsh
|
||||
- **AND** display which shell was detected
|
||||
|
||||
#### Scenario: Already installed
|
||||
|
||||
- **WHEN** completion is already installed for the target shell
|
||||
- **THEN** display message indicating completion is already installed
|
||||
- **AND** offer to reinstall/update by overwriting existing files
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Uninstallation
|
||||
|
||||
The completion command SHALL remove installed completion scripts and configuration.
|
||||
|
||||
#### Scenario: Uninstalling Oh My Zsh completion
|
||||
|
||||
- **WHEN** user executes `openspec completion uninstall zsh`
|
||||
- **THEN** remove `~/.oh-my-zsh/custom/completions/_openspec` if Oh My Zsh is detected
|
||||
- **AND** remove `~/.zsh/completions/_openspec` if standard Zsh setup is detected
|
||||
- **AND** optionally remove fpath modifications from `~/.zshrc` (with confirmation)
|
||||
- **AND** display success message
|
||||
|
||||
#### Scenario: Auto-detecting Zsh for uninstallation
|
||||
|
||||
- **WHEN** user executes `openspec completion uninstall` without specifying a shell
|
||||
- **THEN** detect current shell and uninstall completion if shell is Zsh
|
||||
- **AND** throw error if detected shell is not Zsh
|
||||
|
||||
#### Scenario: Not installed
|
||||
|
||||
- **WHEN** attempting to uninstall completion that isn't installed
|
||||
- **THEN** display message indicating completion is not installed
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Architecture Patterns
|
||||
|
||||
The completion implementation SHALL follow clean architecture principles with TypeScript best practices.
|
||||
|
||||
#### Scenario: Shell-specific generators
|
||||
|
||||
- **WHEN** implementing completion generators
|
||||
- **THEN** create `ZshCompletionGenerator` class for Zsh
|
||||
- **AND** implement a common `CompletionGenerator` interface with methods:
|
||||
- `generate(): string` - Returns complete shell script
|
||||
- `getInstallPath(): string` - Returns target installation path
|
||||
- `getConfigFile(): string` - Returns shell configuration file path
|
||||
- **AND** design interface to be extensible for future shells (bash, fish, powershell)
|
||||
|
||||
#### Scenario: Dynamic completion providers
|
||||
|
||||
- **WHEN** implementing dynamic completions
|
||||
- **THEN** create a `CompletionProvider` class that encapsulates project discovery logic
|
||||
- **AND** implement methods:
|
||||
- `getChangeIds(): Promise<string[]>` - Discovers active change IDs
|
||||
- `getSpecIds(): Promise<string[]>` - Discovers spec IDs
|
||||
- `isOpenSpecProject(): boolean` - Checks if current directory is OpenSpec-enabled
|
||||
- **AND** implement caching with 2-second TTL using class properties
|
||||
|
||||
#### Scenario: Command registry
|
||||
|
||||
- **WHEN** defining completable commands
|
||||
- **THEN** create a centralized `CommandDefinition` type with properties:
|
||||
- `name: string` - Command name
|
||||
- `description: string` - Help text
|
||||
- `flags: FlagDefinition[]` - Available flags
|
||||
- `acceptsChangeId: boolean` - Whether command takes change ID argument
|
||||
- `acceptsSpecId: boolean` - Whether command takes spec ID argument
|
||||
- `subcommands?: CommandDefinition[]` - Nested subcommands
|
||||
- **AND** export a `COMMAND_REGISTRY` constant with all command definitions
|
||||
- **AND** generators consume this registry to ensure consistency
|
||||
|
||||
#### Scenario: Type-safe shell detection
|
||||
|
||||
- **WHEN** implementing shell detection
|
||||
- **THEN** define a `SupportedShell` type as literal type: `'zsh'`
|
||||
- **AND** implement `detectShell()` function that returns 'zsh' or throws error
|
||||
- **AND** design type to be extensible (e.g., future: `'bash' | 'zsh' | 'fish' | 'powershell'`)
|
||||
|
||||
### Requirement: Error Handling
|
||||
|
||||
The completion command SHALL provide clear error messages for common failure scenarios.
|
||||
|
||||
#### Scenario: Unsupported shell
|
||||
|
||||
- **WHEN** user requests completion for unsupported shell (bash, fish, powershell, etc.)
|
||||
- **THEN** display error message: "Shell '<name>' is not supported yet. Currently supported: zsh"
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Permission errors during installation
|
||||
|
||||
- **WHEN** installation fails due to file permission issues
|
||||
- **THEN** display clear error message indicating permission problem
|
||||
- **AND** suggest using appropriate permissions or alternative installation method
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Missing shell configuration directory
|
||||
|
||||
- **WHEN** expected shell configuration directory doesn't exist
|
||||
- **THEN** create the directory automatically (with user notification)
|
||||
- **AND** proceed with installation
|
||||
|
||||
#### Scenario: Shell not detected
|
||||
|
||||
- **WHEN** `openspec completion install` cannot detect current shell or detects non-Zsh shell
|
||||
- **THEN** display error: "Could not detect Zsh. Please specify explicitly: openspec completion install zsh"
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Output Format
|
||||
|
||||
The completion command SHALL provide machine-parseable and human-readable output.
|
||||
|
||||
#### Scenario: Script generation output
|
||||
|
||||
- **WHEN** generating completion script to stdout
|
||||
- **THEN** output only the completion script content (no extra messages)
|
||||
- **AND** allow redirection to files: `openspec completion zsh > /path/to/_openspec`
|
||||
|
||||
#### Scenario: Installation success output
|
||||
|
||||
- **WHEN** installation completes successfully
|
||||
- **THEN** display formatted success message with:
|
||||
- Checkmark indicator
|
||||
- Installation location
|
||||
- Next steps (shell reload instructions)
|
||||
- **AND** use colors when terminal supports it (unless `--no-color` is set)
|
||||
|
||||
#### Scenario: Verbose installation output
|
||||
|
||||
- **WHEN** user provides `--verbose` flag during installation
|
||||
- **THEN** display detailed steps:
|
||||
- Shell detection result
|
||||
- Target file paths
|
||||
- Configuration modifications
|
||||
- File creation confirmations
|
||||
|
||||
### Requirement: Testing Support
|
||||
|
||||
The completion implementation SHALL be testable with unit and integration tests.
|
||||
|
||||
#### Scenario: Mock shell environment
|
||||
|
||||
- **WHEN** writing tests for shell detection
|
||||
- **THEN** allow overriding `$SHELL` environment variable
|
||||
- **AND** use dependency injection for file system operations
|
||||
|
||||
#### Scenario: Generator output verification
|
||||
|
||||
- **WHEN** testing completion generators
|
||||
- **THEN** verify generated scripts contain expected patterns
|
||||
- **AND** test that command registry is properly consumed
|
||||
- **AND** ensure dynamic completion placeholders are present
|
||||
|
||||
#### Scenario: Installation simulation
|
||||
|
||||
- **WHEN** testing installation logic
|
||||
- **THEN** use temporary test directories instead of actual home directories
|
||||
- **AND** verify file creation without modifying real shell configurations
|
||||
- **AND** test path resolution logic independently
|
||||
|
||||
## Not in Scope
|
||||
|
||||
The following shells are **architecturally documented but not implemented** in this proposal. They will be added in future proposals:
|
||||
|
||||
- **Bash completion** - Will use bash-completion framework with `_init_completion`, `compgen`, and `COMPREPLY`
|
||||
- **Fish completion** - Will use Fish's declarative `complete -c` syntax
|
||||
- **PowerShell completion** - Will use `Register-ArgumentCompleter` with completion result objects
|
||||
|
||||
The plugin-based architecture (CompletionGenerator interface, command registry, dynamic providers) is designed to make adding these shells straightforward in follow-up changes.
|
||||
|
||||
## Why
|
||||
|
||||
Shell completions are essential for professional CLI tools and significantly improve developer experience by reducing friction, errors, and cognitive load during daily workflows.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Implementation Tasks
|
||||
|
||||
## Phase 1: Foundation & Architecture
|
||||
|
||||
- [x] Create `src/utils/shell-detection.ts` with `SupportedShell` type and `detectShell()` function
|
||||
- [x] Create `src/core/completions/types.ts` with interfaces: `CompletionGenerator`, `CommandDefinition`, `FlagDefinition`
|
||||
- [x] Create `src/core/completions/command-registry.ts` with `COMMAND_REGISTRY` constant defining all OpenSpec commands, flags, and metadata
|
||||
- [x] Create `src/core/completions/completion-provider.ts` with `CompletionProvider` class for dynamic change/spec ID discovery with 2-second caching
|
||||
- [x] Write tests for shell detection (`test/utils/shell-detection.test.ts`)
|
||||
- [x] Write tests for completion provider (`test/core/completions/completion-provider.test.ts`)
|
||||
|
||||
## Phase 2: Zsh Completion (Oh My Zsh Priority)
|
||||
|
||||
- [x] Create `src/core/completions/generators/zsh-generator.ts` implementing `CompletionGenerator` interface
|
||||
- [x] Implement Zsh script generation using `_arguments` and `_describe` patterns
|
||||
- [x] Add dynamic completion logic for change/spec IDs using completion provider
|
||||
- [x] Test Zsh generator output (`test/core/completions/generators/zsh-generator.test.ts`)
|
||||
- [x] Create `src/core/completions/installers/zsh-installer.ts` with Oh My Zsh and standard Zsh support
|
||||
- [x] Implement Oh My Zsh detection (`$ZSH` env var or `~/.oh-my-zsh/` directory)
|
||||
- [x] Implement installation to `~/.oh-my-zsh/custom/completions/_openspec` for Oh My Zsh
|
||||
- [x] Implement fallback installation to `~/.zsh/completions/_openspec` with `fpath` updates
|
||||
- [x] Test Zsh installer logic with mocked file system (`test/core/completions/installers/zsh-installer.test.ts`)
|
||||
|
||||
## Phase 3: CLI Command Implementation
|
||||
|
||||
- [x] Create `src/commands/completion.ts` with `CompletionCommand` class
|
||||
- [x] Register `completion` command in `src/cli/index.ts` with subcommands: generate, install, uninstall
|
||||
- [x] Implement `generateSubcommand()` that outputs Zsh script to stdout
|
||||
- [x] Implement `installSubcommand(shell?: 'zsh')` with auto-detection for Zsh-only
|
||||
- [x] Implement `uninstallSubcommand(shell?: 'zsh')` for removing Zsh completions
|
||||
- [x] Add `--verbose` flag support for detailed installation output
|
||||
- [x] Add error handling with clear messages: "Shell '<name>' is not supported yet. Currently supported: zsh"
|
||||
- [x] Test completion command integration (`test/commands/completion.test.ts`)
|
||||
|
||||
## Phase 4: Integration & Polish
|
||||
|
||||
- [x] Create factory pattern in `src/core/completions/factory.ts` to instantiate Zsh generator/installer (extensible for future shells)
|
||||
- [x] Add `completion` command to command registry for self-referential completion
|
||||
- [x] Implement dynamic completion helper functions in Zsh generator (`_openspec_complete_changes`, `_openspec_complete_specs`, `_openspec_complete_items`)
|
||||
- [x] Add 'shell' positional type for completion command arguments
|
||||
- [x] Test completion generation with dynamic helpers
|
||||
- [x] Test completion install/uninstall flow
|
||||
- [x] Verify all tests pass (97 completion tests, 340 total tests)
|
||||
- [x] Implement auto-install via npm postinstall script
|
||||
- [x] Add safety checks (CI detection, opt-out flag)
|
||||
- [x] Handle Oh My Zsh vs standard Zsh installation paths
|
||||
- [x] Add test script for postinstall validation
|
||||
- [x] Document auto-install behavior and opt-out in README
|
||||
- [ ] Manually test Zsh completion in Oh My Zsh environment (install, test tab completion, uninstall)
|
||||
- [ ] Manually test Zsh completion in standard Zsh environment
|
||||
- [ ] Test dynamic change/spec ID completion in real OpenSpec projects
|
||||
- [ ] Verify completion cache behavior (2-second TTL)
|
||||
- [ ] Test behavior outside OpenSpec projects (should skip dynamic completions)
|
||||
- [x] Update `openspec --help` output to include completion command (automatically done via Commander)
|
||||
|
||||
## Phase 5: Edge Cases & Error Handling
|
||||
|
||||
- [ ] Test and handle permission errors during installation
|
||||
- [ ] Test and handle missing shell configuration directories (auto-create with notification)
|
||||
- [ ] Test "already installed" detection and reinstall flow
|
||||
- [ ] Test "not installed" detection during uninstall
|
||||
- [ ] Verify `--no-color` flag is respected in completion command output
|
||||
- [ ] Test shell detection failure scenarios with helpful error messages
|
||||
- [ ] Ensure graceful handling when `$SHELL` is unset or invalid
|
||||
- [ ] Test non-Zsh shells get clear "not supported yet" error messages
|
||||
- [ ] Test generator output can be redirected to files without corruption
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Phase 2 depends on Phase 1 (foundation must exist first)
|
||||
- Phase 3 depends on Phase 2 (CLI needs Zsh generator working)
|
||||
- Phase 4 depends on Phase 3 (integration requires CLI + Zsh implementation)
|
||||
- Phase 5 depends on Phase 4 (edge case testing after core functionality works)
|
||||
|
||||
## Future Work (Not in This Proposal)
|
||||
|
||||
- **Bash completions** - Create bash-generator.ts and bash-installer.ts in follow-up proposal
|
||||
- **Fish completions** - Create fish-generator.ts and fish-installer.ts in follow-up proposal
|
||||
- **PowerShell completions** - Create powershell-generator.ts and powershell-installer.ts in follow-up proposal
|
||||
|
||||
The architecture is designed to make adding these shells straightforward by implementing the `CompletionGenerator` interface.
|
||||
@@ -0,0 +1,105 @@
|
||||
## Context
|
||||
|
||||
OpenSpec needs a standard location for user-level configuration that works across platforms and follows established conventions. This will serve as the foundation for settings, feature flags, and future artifacts like workflows or templates.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Provide a single, well-defined location for global config
|
||||
- Follow XDG Base Directory Specification (widely adopted by CLI tools)
|
||||
- Support cross-platform usage (Unix, macOS, Windows)
|
||||
- Keep implementation minimal - just the foundation
|
||||
- Enable future expansion (cache, state, workflows)
|
||||
|
||||
**Non-Goals:**
|
||||
- Project-local config override (not in scope)
|
||||
- Config file migration tooling
|
||||
- Config validation CLI commands
|
||||
- Multiple config profiles
|
||||
|
||||
## Decisions
|
||||
|
||||
### Path Resolution Strategy
|
||||
|
||||
**Decision:** Use XDG Base Directory Specification with platform fallbacks.
|
||||
|
||||
```
|
||||
Unix/macOS: $XDG_CONFIG_HOME/openspec/ or ~/.config/openspec/
|
||||
Windows: %APPDATA%/openspec/
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- XDG is the de facto standard for CLI tools (used by gh, bat, ripgrep, etc.)
|
||||
- Environment variable override allows user customization
|
||||
- Windows uses its native convention (%APPDATA%) for better integration
|
||||
|
||||
**Alternatives considered:**
|
||||
- `~/.openspec/` - Simple but clutters home directory
|
||||
- `~/Library/Application Support/` on macOS - Overkill for a CLI tool
|
||||
|
||||
### Config File Format
|
||||
|
||||
**Decision:** JSON (`config.json`)
|
||||
|
||||
**Rationale:**
|
||||
- Native Node.js support (no dependencies)
|
||||
- Human-readable and editable
|
||||
- Type-safe with TypeScript
|
||||
- Matches project.md's "minimal dependencies" principle
|
||||
|
||||
**Alternatives considered:**
|
||||
- YAML - Requires dependency, more error-prone to edit
|
||||
- TOML - Less common in Node.js ecosystem
|
||||
- Environment variables only - Too limited for structured settings
|
||||
|
||||
### Config Schema
|
||||
|
||||
**Decision:** Flat structure with typed fields, start minimal.
|
||||
|
||||
```typescript
|
||||
interface GlobalConfig {
|
||||
featureFlags?: Record<string, boolean>;
|
||||
}
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- `featureFlags` enables controlled rollout of new features
|
||||
- Optional fields with defaults avoid breaking changes
|
||||
- Flat structure is easy to understand and extend
|
||||
|
||||
### Loading Strategy
|
||||
|
||||
**Decision:** Read from disk on each call, no caching.
|
||||
|
||||
```typescript
|
||||
export function getGlobalConfig(): GlobalConfig {
|
||||
return loadConfigFromDisk();
|
||||
}
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- CLI commands are short-lived; caching adds complexity without benefit
|
||||
- Reading a small JSON file is ~1ms; negligible overhead
|
||||
- Always returns fresh data; no cache invalidation concerns
|
||||
- Simpler implementation
|
||||
|
||||
### Directory Creation
|
||||
|
||||
**Decision:** Create directory only when saving, not when reading.
|
||||
|
||||
**Rationale:**
|
||||
- Don't create empty directories on read operations
|
||||
- Users who never save config won't have unnecessary directories
|
||||
- Aligns with principle of least surprise
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Config file corruption | Return defaults on parse error, log warning |
|
||||
| Permissions issues | Check write permissions before save, clear error message |
|
||||
| Future schema changes | Use optional fields, add version field if needed later |
|
||||
|
||||
## Open Questions
|
||||
|
||||
None - this proposal is intentionally minimal.
|
||||
@@ -0,0 +1,20 @@
|
||||
## Why
|
||||
|
||||
OpenSpec currently has no mechanism for user-level global settings or feature flags. As the CLI grows, we need a standard location to store user preferences, experimental features, and other configuration that persists across projects. Following XDG Base Directory Specification provides a well-understood, cross-platform approach.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add new `src/core/global-config.ts` module with:
|
||||
- Path resolution following XDG Base Directory spec (`$XDG_CONFIG_HOME/openspec/` or fallback)
|
||||
- Cross-platform support (Unix, macOS, Windows)
|
||||
- Lazy config loading with sensible defaults
|
||||
- TypeScript types for config shape
|
||||
- Export a global config directory path getter for future use (workflows, templates, cache)
|
||||
- Initial config schema supports 1-2 settings/feature flags only
|
||||
|
||||
## Impact
|
||||
|
||||
- Affected specs: New `global-config` capability (no existing specs modified)
|
||||
- Affected code:
|
||||
- New `src/core/global-config.ts`
|
||||
- Update `src/core/index.ts` to export new module
|
||||
@@ -0,0 +1,76 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Global Config Directory Path
|
||||
|
||||
The system SHALL resolve the global configuration directory path following XDG Base Directory Specification with platform-specific fallbacks.
|
||||
|
||||
#### Scenario: Unix/macOS with XDG_CONFIG_HOME set
|
||||
- **WHEN** `$XDG_CONFIG_HOME` environment variable is set to `/custom/config`
|
||||
- **THEN** `getGlobalConfigDir()` returns `/custom/config/openspec`
|
||||
|
||||
#### Scenario: Unix/macOS without XDG_CONFIG_HOME
|
||||
- **WHEN** `$XDG_CONFIG_HOME` environment variable is not set
|
||||
- **AND** the platform is Unix or macOS
|
||||
- **THEN** `getGlobalConfigDir()` returns `~/.config/openspec` (expanded to absolute path)
|
||||
|
||||
#### Scenario: Windows platform
|
||||
- **WHEN** the platform is Windows
|
||||
- **AND** `%APPDATA%` is set to `C:\Users\User\AppData\Roaming`
|
||||
- **THEN** `getGlobalConfigDir()` returns `C:\Users\User\AppData\Roaming\openspec`
|
||||
|
||||
### Requirement: Global Config Loading
|
||||
|
||||
The system SHALL load global configuration from the config directory with sensible defaults when the config file does not exist or cannot be parsed.
|
||||
|
||||
#### Scenario: Config file exists and is valid
|
||||
- **WHEN** `config.json` exists in the global config directory
|
||||
- **AND** the file contains valid JSON matching the config schema
|
||||
- **THEN** `getGlobalConfig()` returns the parsed configuration
|
||||
|
||||
#### Scenario: Config file does not exist
|
||||
- **WHEN** `config.json` does not exist in the global config directory
|
||||
- **THEN** `getGlobalConfig()` returns the default configuration
|
||||
- **AND** no directory or file is created
|
||||
|
||||
#### Scenario: Config file is invalid JSON
|
||||
- **WHEN** `config.json` exists but contains invalid JSON
|
||||
- **THEN** `getGlobalConfig()` returns the default configuration
|
||||
- **AND** a warning is logged to stderr
|
||||
|
||||
### Requirement: Global Config Saving
|
||||
|
||||
The system SHALL save global configuration to the config directory, creating the directory if it does not exist.
|
||||
|
||||
#### Scenario: Save config to new directory
|
||||
- **WHEN** `saveGlobalConfig(config)` is called
|
||||
- **AND** the global config directory does not exist
|
||||
- **THEN** the directory is created
|
||||
- **AND** `config.json` is written with the provided configuration
|
||||
|
||||
#### Scenario: Save config to existing directory
|
||||
- **WHEN** `saveGlobalConfig(config)` is called
|
||||
- **AND** the global config directory already exists
|
||||
- **THEN** `config.json` is written (overwriting if exists)
|
||||
|
||||
### Requirement: Default Configuration
|
||||
|
||||
The system SHALL provide a default configuration that is used when no config file exists.
|
||||
|
||||
#### Scenario: Default config structure
|
||||
- **WHEN** no config file exists
|
||||
- **THEN** the default configuration includes an empty `featureFlags` object
|
||||
|
||||
### Requirement: Config Schema Evolution
|
||||
|
||||
The system SHALL merge loaded configuration with default values to ensure new config fields are available even when loading older config files.
|
||||
|
||||
#### Scenario: Config file missing new fields
|
||||
- **WHEN** `config.json` exists with `{ "featureFlags": {} }`
|
||||
- **AND** the current schema includes a new field `defaultAiTool`
|
||||
- **THEN** `getGlobalConfig()` returns `{ featureFlags: {}, defaultAiTool: <default> }`
|
||||
- **AND** the loaded values take precedence over defaults for fields that exist in both
|
||||
|
||||
#### Scenario: Config file has extra unknown fields
|
||||
- **WHEN** `config.json` contains fields not in the current schema
|
||||
- **THEN** the unknown fields are preserved in the returned configuration
|
||||
- **AND** no error or warning is raised
|
||||
@@ -0,0 +1,26 @@
|
||||
## 1. Core Implementation
|
||||
|
||||
- [x] 1.1 Create `src/core/global-config.ts` with path resolution
|
||||
- Implement `getGlobalConfigDir()` following XDG spec
|
||||
- Support `$XDG_CONFIG_HOME` environment variable override
|
||||
- Platform-specific fallbacks (Unix: `~/.config/`, Windows: `%APPDATA%`)
|
||||
- [x] 1.2 Define TypeScript interfaces for config shape
|
||||
- `GlobalConfig` interface with optional fields
|
||||
- Start minimal: just `featureFlags?: Record<string, boolean>`
|
||||
- [x] 1.3 Implement config loading with defaults
|
||||
- `getGlobalConfig()` - reads config.json if exists, merges with defaults
|
||||
- No directory/file creation on read (lazy initialization)
|
||||
- [x] 1.4 Implement config saving
|
||||
- `saveGlobalConfig(config)` - writes config.json, creates directory if needed
|
||||
|
||||
## 2. Integration
|
||||
|
||||
- [x] 2.1 Export new module from `src/core/index.ts`
|
||||
- [x] 2.2 Add constants for config file name and directory name
|
||||
|
||||
## 3. Testing
|
||||
|
||||
- [x] 3.1 Manual testing of path resolution on current platform
|
||||
- [x] 3.2 Test with/without `$XDG_CONFIG_HOME` set
|
||||
- [x] 3.3 Test config load when file doesn't exist (should return defaults)
|
||||
- [x] 3.4 Unit tests in `test/core/global-config.test.ts` (18 tests)
|
||||
@@ -0,0 +1,89 @@
|
||||
## Context
|
||||
|
||||
The `global-config` spec defines how OpenSpec reads/writes `config.json`, but users currently must edit it by hand. This command provides a CLI interface to that config.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Provide a discoverable CLI for config management
|
||||
- Support scripting with machine-readable output
|
||||
- Validate config changes with zod schema
|
||||
- Handle nested keys gracefully
|
||||
|
||||
**Non-Goals:**
|
||||
- Project-local config (reserved for future via `--scope` flag)
|
||||
- Complex queries (JSONPath, filtering)
|
||||
- Config file format migration
|
||||
|
||||
## Decisions
|
||||
|
||||
### Key Naming: camelCase with Dot Notation
|
||||
|
||||
**Decision:** Keys use camelCase matching the JSON structure, with dot notation for nesting.
|
||||
|
||||
**Rationale:**
|
||||
- Matches the actual JSON keys (no translation layer)
|
||||
- Dot notation is intuitive and widely used (lodash, jq, kubectl)
|
||||
- Avoids complexity of supporting multiple casing styles
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
openspec config get featureFlags # Returns object
|
||||
openspec config get featureFlags.experimental # Returns nested value
|
||||
openspec config set featureFlags.newFlag true
|
||||
```
|
||||
|
||||
### Type Coercion: Auto-detect with `--string` Override
|
||||
|
||||
**Decision:** Parse values automatically; provide `--string` flag to force string storage.
|
||||
|
||||
**Rationale:**
|
||||
- Most intuitive for common cases (`true`, `false`, `123`)
|
||||
- Explicit override for edge cases (storing literal string "true")
|
||||
- Follows npm/yarn config patterns
|
||||
|
||||
**Coercion rules:**
|
||||
| Input | Stored As |
|
||||
|-------|-----------|
|
||||
| `true`, `false` | boolean |
|
||||
| Numeric string (`123`, `3.14`) | number |
|
||||
| Everything else | string |
|
||||
| Any value with `--string` | string |
|
||||
|
||||
### Output Format: Raw by Default
|
||||
|
||||
**Decision:** `get` prints raw value only. `list` prints YAML-like format by default, JSON with `--json`.
|
||||
|
||||
**Rationale:**
|
||||
- Raw output enables piping: `VAR=$(openspec config get key)`
|
||||
- YAML-like is human-readable for inspection
|
||||
- JSON for automation/scripting
|
||||
|
||||
### Schema Validation: Zod with Unknown Field Passthrough
|
||||
|
||||
**Decision:** Use zod for validation but preserve unknown fields per `global-config` spec.
|
||||
|
||||
**Rationale:**
|
||||
- Type safety for known fields
|
||||
- Forward compatibility (old CLI doesn't break new config)
|
||||
- Follows existing `global-config` spec requirement
|
||||
|
||||
### Reserved Flag: `--scope`
|
||||
|
||||
**Decision:** Reserve `--scope global|project` but only implement `global` initially.
|
||||
|
||||
**Rationale:**
|
||||
- Avoids breaking change if project-local config is added later
|
||||
- Clear error message if someone tries `--scope project`
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Dot notation conflicts with keys containing dots | Rare in practice; document limitation |
|
||||
| Type coercion surprises | `--string` escape hatch; document rules |
|
||||
| $EDITOR not set | Check and provide helpful error message |
|
||||
|
||||
## Open Questions
|
||||
|
||||
None - design is straightforward.
|
||||
@@ -0,0 +1,60 @@
|
||||
## Why
|
||||
|
||||
Users need a way to view and modify their global OpenSpec settings without manually editing JSON files. The `global-config` spec provides the foundation, but there's no user-facing interface to interact with the config. A dedicated `openspec config` command provides discoverability and ease of use.
|
||||
|
||||
## What Changes
|
||||
|
||||
Add `openspec config` subcommand with the following operations:
|
||||
|
||||
```bash
|
||||
openspec config path # Show config file location
|
||||
openspec config list [--json] # Show all current settings
|
||||
openspec config get <key> # Get a specific value (raw, scriptable)
|
||||
openspec config set <key> <value> [--string] # Set a value (auto-coerce types)
|
||||
openspec config unset <key> # Remove a key (revert to default)
|
||||
openspec config reset --all [-y] # Reset everything to defaults
|
||||
openspec config edit # Open config in $EDITOR
|
||||
```
|
||||
|
||||
**Key design decisions:**
|
||||
- **Key naming**: Use camelCase to match JSON structure (e.g., `featureFlags.someFlag`)
|
||||
- **Nested keys**: Support dot notation for nested access
|
||||
- **Type coercion**: Auto-detect types by default; `--string` flag forces string storage
|
||||
- **Scriptable output**: `get` prints raw value only (no labels) for easy piping
|
||||
- **Zod validation**: Use zod for config schema validation and type safety
|
||||
- **Future-proofing**: Reserve `--scope global|project` flag for potential project-local config
|
||||
|
||||
**Example usage:**
|
||||
```bash
|
||||
$ openspec config path
|
||||
/Users/me/.config/openspec/config.json
|
||||
|
||||
$ openspec config list
|
||||
featureFlags: {}
|
||||
|
||||
$ openspec config set featureFlags.enableTelemetry false
|
||||
Set featureFlags.enableTelemetry = false
|
||||
|
||||
$ openspec config get featureFlags.enableTelemetry
|
||||
false
|
||||
|
||||
$ openspec config list --json
|
||||
{
|
||||
"featureFlags": {}
|
||||
}
|
||||
|
||||
$ openspec config unset featureFlags.enableTelemetry
|
||||
Unset featureFlags.enableTelemetry (reverted to default)
|
||||
|
||||
$ openspec config edit
|
||||
# Opens $EDITOR with config.json
|
||||
```
|
||||
|
||||
## Impact
|
||||
|
||||
- Affected specs: New `cli-config` capability
|
||||
- Affected code:
|
||||
- New `src/commands/config.ts`
|
||||
- New `src/core/config-schema.ts` (zod schema)
|
||||
- Update CLI entry point to register config command
|
||||
- Dependencies: Requires `global-config` spec (already implemented)
|
||||
@@ -0,0 +1,213 @@
|
||||
# cli-config Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Provide a CLI interface for viewing and modifying global OpenSpec configuration. Enables users to manage settings without manually editing JSON files, with support for scripting and automation.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Command Structure
|
||||
|
||||
The config command SHALL provide subcommands for all configuration operations.
|
||||
|
||||
#### Scenario: Available subcommands
|
||||
|
||||
- **WHEN** user executes `openspec config --help`
|
||||
- **THEN** display available subcommands:
|
||||
- `path` - Show config file location
|
||||
- `list` - Show all current settings
|
||||
- `get <key>` - Get a specific value
|
||||
- `set <key> <value>` - Set a value
|
||||
- `unset <key>` - Remove a key (revert to default)
|
||||
- `reset` - Reset configuration to defaults
|
||||
- `edit` - Open config in editor
|
||||
|
||||
### Requirement: Config Path
|
||||
|
||||
The config command SHALL display the config file location.
|
||||
|
||||
#### Scenario: Show config path
|
||||
|
||||
- **WHEN** user executes `openspec config path`
|
||||
- **THEN** print the absolute path to the config file
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Config List
|
||||
|
||||
The config command SHALL display all current configuration values.
|
||||
|
||||
#### Scenario: List config in human-readable format
|
||||
|
||||
- **WHEN** user executes `openspec config list`
|
||||
- **THEN** display all config values in YAML-like format
|
||||
- **AND** show nested objects with indentation
|
||||
|
||||
#### Scenario: List config as JSON
|
||||
|
||||
- **WHEN** user executes `openspec config list --json`
|
||||
- **THEN** output the complete config as valid JSON
|
||||
- **AND** output only JSON (no additional text)
|
||||
|
||||
### Requirement: Config Get
|
||||
|
||||
The config command SHALL retrieve specific configuration values.
|
||||
|
||||
#### Scenario: Get top-level key
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` with a valid top-level key
|
||||
- **THEN** print the raw value only (no labels or formatting)
|
||||
- **AND** exit with code 0
|
||||
|
||||
#### Scenario: Get nested key with dot notation
|
||||
|
||||
- **WHEN** user executes `openspec config get featureFlags.someFlag`
|
||||
- **THEN** traverse the nested structure using dot notation
|
||||
- **AND** print the value at that path
|
||||
|
||||
#### Scenario: Get non-existent key
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` with a key that does not exist
|
||||
- **THEN** print nothing (empty output)
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Get object value
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` where the value is an object
|
||||
- **THEN** print the object as JSON
|
||||
|
||||
### Requirement: Config Set
|
||||
|
||||
The config command SHALL set configuration values with automatic type coercion.
|
||||
|
||||
#### Scenario: Set string value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value>`
|
||||
- **AND** value does not match boolean or number patterns
|
||||
- **THEN** store value as a string
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Set boolean value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> true` or `openspec config set <key> false`
|
||||
- **THEN** store value as boolean (not string)
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Set numeric value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value>`
|
||||
- **AND** value is a valid number (integer or float)
|
||||
- **THEN** store value as number (not string)
|
||||
|
||||
#### Scenario: Force string with --string flag
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value> --string`
|
||||
- **THEN** store value as string regardless of content
|
||||
- **AND** this allows storing literal "true" or "123" as strings
|
||||
|
||||
#### Scenario: Set nested key
|
||||
|
||||
- **WHEN** user executes `openspec config set featureFlags.newFlag true`
|
||||
- **THEN** create intermediate objects if they don't exist
|
||||
- **AND** set the value at the nested path
|
||||
|
||||
### Requirement: Config Unset
|
||||
|
||||
The config command SHALL remove configuration overrides.
|
||||
|
||||
#### Scenario: Unset existing key
|
||||
|
||||
- **WHEN** user executes `openspec config unset <key>`
|
||||
- **AND** the key exists in the config
|
||||
- **THEN** remove the key from the config file
|
||||
- **AND** the value reverts to its default
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Unset non-existent key
|
||||
|
||||
- **WHEN** user executes `openspec config unset <key>`
|
||||
- **AND** the key does not exist in the config
|
||||
- **THEN** display message indicating key was not set
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Config Reset
|
||||
|
||||
The config command SHALL reset configuration to defaults.
|
||||
|
||||
#### Scenario: Reset all with confirmation
|
||||
|
||||
- **WHEN** user executes `openspec config reset --all`
|
||||
- **THEN** prompt for confirmation before proceeding
|
||||
- **AND** if confirmed, delete the config file or reset to defaults
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Reset all with -y flag
|
||||
|
||||
- **WHEN** user executes `openspec config reset --all -y`
|
||||
- **THEN** reset without prompting for confirmation
|
||||
|
||||
#### Scenario: Reset without --all flag
|
||||
|
||||
- **WHEN** user executes `openspec config reset` without `--all`
|
||||
- **THEN** display error indicating `--all` is required
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Config Edit
|
||||
|
||||
The config command SHALL open the config file in the user's editor.
|
||||
|
||||
#### Scenario: Open editor successfully
|
||||
|
||||
- **WHEN** user executes `openspec config edit`
|
||||
- **AND** `$EDITOR` or `$VISUAL` environment variable is set
|
||||
- **THEN** open the config file in that editor
|
||||
- **AND** create the config file with defaults if it doesn't exist
|
||||
- **AND** wait for the editor to close before returning
|
||||
|
||||
#### Scenario: No editor configured
|
||||
|
||||
- **WHEN** user executes `openspec config edit`
|
||||
- **AND** neither `$EDITOR` nor `$VISUAL` is set
|
||||
- **THEN** display error message suggesting to set `$EDITOR`
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Key Naming Convention
|
||||
|
||||
The config command SHALL use camelCase keys matching the JSON structure.
|
||||
|
||||
#### Scenario: Keys match JSON structure
|
||||
|
||||
- **WHEN** accessing configuration keys via CLI
|
||||
- **THEN** use camelCase matching the actual JSON property names
|
||||
- **AND** support dot notation for nested access (e.g., `featureFlags.someFlag`)
|
||||
|
||||
### Requirement: Schema Validation
|
||||
|
||||
The config command SHALL validate configuration writes against the config schema using zod, while allowing unknown fields for forward compatibility.
|
||||
|
||||
#### Scenario: Unknown key accepted
|
||||
|
||||
- **WHEN** user executes `openspec config set someFutureKey 123`
|
||||
- **THEN** the value is saved successfully
|
||||
- **AND** exit with code 0
|
||||
|
||||
#### Scenario: Invalid feature flag value rejected
|
||||
|
||||
- **WHEN** user executes `openspec config set featureFlags.someFlag notABoolean`
|
||||
- **THEN** display a descriptive error message
|
||||
- **AND** do not modify the config file
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Reserved Scope Flag
|
||||
|
||||
The config command SHALL reserve the `--scope` flag for future extensibility.
|
||||
|
||||
#### Scenario: Scope flag defaults to global
|
||||
|
||||
- **WHEN** user executes any config command without `--scope`
|
||||
- **THEN** operate on global configuration (default behavior)
|
||||
|
||||
#### Scenario: Project scope not yet implemented
|
||||
|
||||
- **WHEN** user executes `openspec config --scope project <subcommand>`
|
||||
- **THEN** display error message: "Project-local config is not yet implemented"
|
||||
- **AND** exit with code 1
|
||||
@@ -0,0 +1,28 @@
|
||||
## 1. Core Infrastructure
|
||||
|
||||
- [x] 1.1 Create zod schema for global config in `src/core/config-schema.ts`
|
||||
- [x] 1.2 Add utility functions for dot-notation key access (get/set nested values)
|
||||
- [x] 1.3 Add type coercion logic (auto-detect boolean/number/string)
|
||||
|
||||
## 2. Config Command Implementation
|
||||
|
||||
- [x] 2.1 Create `src/commands/config.ts` with Commander.js subcommands
|
||||
- [x] 2.2 Implement `config path` subcommand
|
||||
- [x] 2.3 Implement `config list` subcommand with `--json` flag
|
||||
- [x] 2.4 Implement `config get <key>` subcommand (raw output)
|
||||
- [x] 2.5 Implement `config set <key> <value>` with `--string` flag
|
||||
- [x] 2.6 Implement `config unset <key>` subcommand
|
||||
- [x] 2.7 Implement `config reset --all` with `-y` confirmation flag
|
||||
- [x] 2.8 Implement `config edit` subcommand (spawn $EDITOR)
|
||||
|
||||
## 3. Integration
|
||||
|
||||
- [x] 3.1 Register config command in CLI entry point
|
||||
- [x] 3.2 Update shell completion registry to include config subcommands
|
||||
|
||||
## 4. Testing
|
||||
|
||||
- [x] 4.1 Manual testing of all subcommands
|
||||
- [x] 4.2 Verify zod validation rejects invalid keys/values
|
||||
- [x] 4.3 Test nested key access with dot notation
|
||||
- [x] 4.4 Test type coercion edge cases (true/false, numbers, strings)
|
||||
@@ -0,0 +1,287 @@
|
||||
# cli-completion Specification
|
||||
|
||||
## Purpose
|
||||
Provide shell completion scripts for the OpenSpec CLI, enabling tab-completion for commands, flags, and dynamic values (change IDs, spec IDs) in supported shells. Currently supports Zsh with architecture designed for future shell expansion.
|
||||
## Requirements
|
||||
### Requirement: Native Shell Behavior Integration
|
||||
|
||||
The completion system SHALL respect and integrate with Zsh's native completion patterns and user interaction model.
|
||||
|
||||
#### Scenario: Zsh native completion
|
||||
|
||||
- **WHEN** generating Zsh completion scripts
|
||||
- **THEN** use Zsh completion system with `_arguments`, `_describe`, and `compadd`
|
||||
- **AND** completions SHALL trigger on single TAB (standard Zsh behavior)
|
||||
- **AND** display as an interactive menu that users navigate with TAB/arrow keys
|
||||
- **AND** support Oh My Zsh's enhanced menu styling automatically
|
||||
|
||||
#### Scenario: No custom UX patterns
|
||||
|
||||
- **WHEN** implementing Zsh completion
|
||||
- **THEN** do NOT attempt to customize completion trigger behavior
|
||||
- **AND** do NOT override Zsh-specific navigation patterns
|
||||
- **AND** ensure completions feel native to experienced Zsh users
|
||||
|
||||
### Requirement: Command Structure
|
||||
|
||||
The completion command SHALL follow a subcommand pattern for generating and managing completion scripts.
|
||||
|
||||
#### Scenario: Available subcommands
|
||||
|
||||
- **WHEN** user executes `openspec completion --help`
|
||||
- **THEN** display available subcommands:
|
||||
- `generate [shell]` - Generate completion script for a shell (outputs to stdout)
|
||||
- `install [shell]` - Install completion for Zsh (auto-detects or requires explicit shell)
|
||||
- `uninstall [shell]` - Remove completion for Zsh (auto-detects or requires explicit shell)
|
||||
|
||||
### Requirement: Shell Detection
|
||||
|
||||
The completion system SHALL automatically detect the user's current shell environment.
|
||||
|
||||
#### Scenario: Detecting Zsh from environment
|
||||
|
||||
- **WHEN** no shell is explicitly specified
|
||||
- **THEN** read the `$SHELL` environment variable
|
||||
- **AND** extract the shell name from the path (e.g., `/bin/zsh` → `zsh`)
|
||||
- **AND** validate the shell is `zsh`
|
||||
- **AND** throw an error if the shell is not `zsh`, with message indicating only Zsh is currently supported
|
||||
|
||||
#### Scenario: Non-Zsh shell detection
|
||||
|
||||
- **WHEN** shell path indicates bash, fish, powershell, or other non-Zsh shell
|
||||
- **THEN** throw error: "Shell '<name>' is not supported yet. Currently supported: zsh"
|
||||
|
||||
### Requirement: Completion Generation
|
||||
|
||||
The completion command SHALL generate Zsh completion scripts on demand.
|
||||
|
||||
#### Scenario: Generating Zsh completion
|
||||
|
||||
- **WHEN** user executes `openspec completion generate zsh`
|
||||
- **THEN** output a complete Zsh completion script to stdout
|
||||
- **AND** include completions for all commands: init, list, show, validate, archive, view, update, change, spec, completion
|
||||
- **AND** include all command-specific flags and options
|
||||
- **AND** use Zsh's `_arguments` and `_describe` built-in functions
|
||||
- **AND** support dynamic completion for change and spec IDs
|
||||
|
||||
### Requirement: Dynamic Completions
|
||||
|
||||
The completion system SHALL provide context-aware dynamic completions for project-specific values.
|
||||
|
||||
#### Scenario: Completing change IDs
|
||||
|
||||
- **WHEN** completing arguments for commands that accept change names (show, validate, archive)
|
||||
- **THEN** discover active changes from `openspec/changes/` directory
|
||||
- **AND** exclude archived changes in `openspec/changes/archive/`
|
||||
- **AND** return change IDs as completion suggestions
|
||||
- **AND** only provide suggestions when inside an OpenSpec-enabled project
|
||||
|
||||
#### Scenario: Completing spec IDs
|
||||
|
||||
- **WHEN** completing arguments for commands that accept spec names (show, validate)
|
||||
- **THEN** discover specs from `openspec/specs/` directory
|
||||
- **AND** return spec IDs as completion suggestions
|
||||
- **AND** only provide suggestions when inside an OpenSpec-enabled project
|
||||
|
||||
#### Scenario: Completion caching
|
||||
|
||||
- **WHEN** dynamic completions are requested
|
||||
- **THEN** cache discovered change and spec IDs for 2 seconds
|
||||
- **AND** reuse cached values for subsequent requests within cache window
|
||||
- **AND** automatically refresh cache after expiration
|
||||
|
||||
#### Scenario: Project detection
|
||||
|
||||
- **WHEN** user requests completions outside an OpenSpec project
|
||||
- **THEN** skip dynamic change/spec ID completions
|
||||
- **AND** only suggest static commands and flags
|
||||
|
||||
### Requirement: Installation Automation
|
||||
|
||||
The completion command SHALL automatically install completion scripts into shell configuration files.
|
||||
|
||||
#### Scenario: Installing for Oh My Zsh
|
||||
|
||||
- **WHEN** user executes `openspec completion install zsh`
|
||||
- **THEN** detect if Oh My Zsh is installed by checking for `$ZSH` environment variable or `~/.oh-my-zsh/` directory
|
||||
- **AND** create custom completions directory at `~/.oh-my-zsh/custom/completions/` if it doesn't exist
|
||||
- **AND** write completion script to `~/.oh-my-zsh/custom/completions/_openspec`
|
||||
- **AND** ensure `~/.oh-my-zsh/custom/completions` is in `$fpath` by updating `~/.zshrc` if needed
|
||||
- **AND** display success message with instruction to run `exec zsh` or restart terminal
|
||||
|
||||
#### Scenario: Installing for standard Zsh
|
||||
|
||||
- **WHEN** user executes `openspec completion install zsh` and Oh My Zsh is not detected
|
||||
- **THEN** create completions directory at `~/.zsh/completions/` if it doesn't exist
|
||||
- **AND** write completion script to `~/.zsh/completions/_openspec`
|
||||
- **AND** add `fpath=(~/.zsh/completions $fpath)` to `~/.zshrc` if not already present
|
||||
- **AND** add `autoload -Uz compinit && compinit` to `~/.zshrc` if not already present
|
||||
- **AND** display success message with instruction to run `exec zsh` or restart terminal
|
||||
|
||||
#### Scenario: Auto-detecting Zsh for installation
|
||||
|
||||
- **WHEN** user executes `openspec completion install` without specifying a shell
|
||||
- **THEN** detect current shell using shell detection logic
|
||||
- **AND** install completion if detected shell is Zsh
|
||||
- **AND** throw error if detected shell is not Zsh
|
||||
- **AND** display which shell was detected
|
||||
|
||||
#### Scenario: Already installed
|
||||
|
||||
- **WHEN** completion is already installed for the target shell
|
||||
- **THEN** display message indicating completion is already installed
|
||||
- **AND** offer to reinstall/update by overwriting existing files
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Uninstallation
|
||||
|
||||
The completion command SHALL remove installed completion scripts and configuration.
|
||||
|
||||
#### Scenario: Uninstalling Oh My Zsh completion
|
||||
|
||||
- **WHEN** user executes `openspec completion uninstall zsh`
|
||||
- **THEN** prompt for confirmation before proceeding (unless `--yes` flag provided)
|
||||
- **AND** if user declines, cancel uninstall and display "Uninstall cancelled."
|
||||
- **AND** if user confirms, remove `~/.oh-my-zsh/custom/completions/_openspec` if Oh My Zsh is detected
|
||||
- **AND** remove `~/.zsh/completions/_openspec` if standard Zsh setup is detected
|
||||
- **AND** remove fpath modifications from `~/.zshrc`
|
||||
- **AND** display success message
|
||||
|
||||
#### Scenario: Auto-detecting Zsh for uninstallation
|
||||
|
||||
- **WHEN** user executes `openspec completion uninstall` without specifying a shell
|
||||
- **THEN** detect current shell and uninstall completion if shell is Zsh
|
||||
- **AND** throw error if detected shell is not Zsh
|
||||
|
||||
#### Scenario: Not installed
|
||||
|
||||
- **WHEN** attempting to uninstall completion that isn't installed
|
||||
- **THEN** display error message indicating completion is not installed
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Architecture Patterns
|
||||
|
||||
The completion implementation SHALL follow clean architecture principles with TypeScript best practices.
|
||||
|
||||
#### Scenario: Shell-specific generators
|
||||
|
||||
- **WHEN** implementing completion generators
|
||||
- **THEN** create `ZshCompletionGenerator` class for Zsh
|
||||
- **AND** implement a common `CompletionGenerator` interface with methods:
|
||||
- `generate(): string` - Returns complete shell script
|
||||
- `getInstallPath(): string` - Returns target installation path
|
||||
- `getConfigFile(): string` - Returns shell configuration file path
|
||||
- **AND** design interface to be extensible for future shells (bash, fish, powershell)
|
||||
|
||||
#### Scenario: Dynamic completion providers
|
||||
|
||||
- **WHEN** implementing dynamic completions
|
||||
- **THEN** create a `CompletionProvider` class that encapsulates project discovery logic
|
||||
- **AND** implement methods:
|
||||
- `getChangeIds(): Promise<string[]>` - Discovers active change IDs
|
||||
- `getSpecIds(): Promise<string[]>` - Discovers spec IDs
|
||||
- `isOpenSpecProject(): boolean` - Checks if current directory is OpenSpec-enabled
|
||||
- **AND** implement caching with 2-second TTL using class properties
|
||||
|
||||
#### Scenario: Command registry
|
||||
|
||||
- **WHEN** defining completable commands
|
||||
- **THEN** create a centralized `CommandDefinition` type with properties:
|
||||
- `name: string` - Command name
|
||||
- `description: string` - Help text
|
||||
- `flags: FlagDefinition[]` - Available flags
|
||||
- `acceptsChangeId: boolean` - Whether command takes change ID argument
|
||||
- `acceptsSpecId: boolean` - Whether command takes spec ID argument
|
||||
- `subcommands?: CommandDefinition[]` - Nested subcommands
|
||||
- **AND** export a `COMMAND_REGISTRY` constant with all command definitions
|
||||
- **AND** generators consume this registry to ensure consistency
|
||||
|
||||
#### Scenario: Type-safe shell detection
|
||||
|
||||
- **WHEN** implementing shell detection
|
||||
- **THEN** define a `SupportedShell` type as literal type: `'zsh'`
|
||||
- **AND** implement `detectShell()` function that returns 'zsh' or throws error
|
||||
- **AND** design type to be extensible (e.g., future: `'bash' | 'zsh' | 'fish' | 'powershell'`)
|
||||
|
||||
### Requirement: Error Handling
|
||||
|
||||
The completion command SHALL provide clear error messages for common failure scenarios.
|
||||
|
||||
#### Scenario: Unsupported shell
|
||||
|
||||
- **WHEN** user requests completion for unsupported shell (bash, fish, powershell, etc.)
|
||||
- **THEN** display error message: "Shell '<name>' is not supported yet. Currently supported: zsh"
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Permission errors during installation
|
||||
|
||||
- **WHEN** installation fails due to file permission issues
|
||||
- **THEN** display clear error message indicating permission problem
|
||||
- **AND** suggest using appropriate permissions or alternative installation method
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Missing shell configuration directory
|
||||
|
||||
- **WHEN** expected shell configuration directory doesn't exist
|
||||
- **THEN** create the directory automatically (with user notification)
|
||||
- **AND** proceed with installation
|
||||
|
||||
#### Scenario: Shell not detected
|
||||
|
||||
- **WHEN** `openspec completion install` cannot detect current shell or detects non-Zsh shell
|
||||
- **THEN** display error: "Could not auto-detect shell. Please specify shell explicitly."
|
||||
- **AND** display usage hint: "Usage: openspec completion <operation> [shell]"
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Output Format
|
||||
|
||||
The completion command SHALL provide machine-parseable and human-readable output.
|
||||
|
||||
#### Scenario: Script generation output
|
||||
|
||||
- **WHEN** generating completion script to stdout
|
||||
- **THEN** output only the completion script content (no extra messages)
|
||||
- **AND** allow redirection to files: `openspec completion generate zsh > /path/to/_openspec`
|
||||
|
||||
#### Scenario: Installation success output
|
||||
|
||||
- **WHEN** installation completes successfully
|
||||
- **THEN** display formatted success message with:
|
||||
- Checkmark indicator
|
||||
- Installation location
|
||||
- Next steps (shell reload instructions)
|
||||
- **AND** use colors when terminal supports it (unless `--no-color` is set)
|
||||
|
||||
#### Scenario: Verbose installation output
|
||||
|
||||
- **WHEN** user provides `--verbose` flag during installation
|
||||
- **THEN** display detailed steps:
|
||||
- Shell detection result
|
||||
- Target file paths
|
||||
- Configuration modifications
|
||||
- File creation confirmations
|
||||
|
||||
### Requirement: Testing Support
|
||||
|
||||
The completion implementation SHALL be testable with unit and integration tests.
|
||||
|
||||
#### Scenario: Mock shell environment
|
||||
|
||||
- **WHEN** writing tests for shell detection
|
||||
- **THEN** allow overriding `$SHELL` environment variable
|
||||
- **AND** use dependency injection for file system operations
|
||||
|
||||
#### Scenario: Generator output verification
|
||||
|
||||
- **WHEN** testing completion generators
|
||||
- **THEN** verify generated scripts contain expected patterns
|
||||
- **AND** test that command registry is properly consumed
|
||||
- **AND** ensure dynamic completion placeholders are present
|
||||
|
||||
#### Scenario: Installation simulation
|
||||
|
||||
- **WHEN** testing installation logic
|
||||
- **THEN** use temporary test directories instead of actual home directories
|
||||
- **AND** verify file creation without modifying real shell configurations
|
||||
- **AND** test path resolution logic independently
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
# cli-config Specification
|
||||
|
||||
## Purpose
|
||||
Provide a user-friendly CLI interface for viewing and modifying global OpenSpec configuration settings without manually editing JSON files.
|
||||
## Requirements
|
||||
### Requirement: Command Structure
|
||||
|
||||
The config command SHALL provide subcommands for all configuration operations.
|
||||
|
||||
#### Scenario: Available subcommands
|
||||
|
||||
- **WHEN** user executes `openspec config --help`
|
||||
- **THEN** display available subcommands:
|
||||
- `path` - Show config file location
|
||||
- `list` - Show all current settings
|
||||
- `get <key>` - Get a specific value
|
||||
- `set <key> <value>` - Set a value
|
||||
- `unset <key>` - Remove a key (revert to default)
|
||||
- `reset` - Reset configuration to defaults
|
||||
- `edit` - Open config in editor
|
||||
|
||||
### Requirement: Config Path
|
||||
|
||||
The config command SHALL display the config file location.
|
||||
|
||||
#### Scenario: Show config path
|
||||
|
||||
- **WHEN** user executes `openspec config path`
|
||||
- **THEN** print the absolute path to the config file
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Config List
|
||||
|
||||
The config command SHALL display all current configuration values.
|
||||
|
||||
#### Scenario: List config in human-readable format
|
||||
|
||||
- **WHEN** user executes `openspec config list`
|
||||
- **THEN** display all config values in YAML-like format
|
||||
- **AND** show nested objects with indentation
|
||||
|
||||
#### Scenario: List config as JSON
|
||||
|
||||
- **WHEN** user executes `openspec config list --json`
|
||||
- **THEN** output the complete config as valid JSON
|
||||
- **AND** output only JSON (no additional text)
|
||||
|
||||
### Requirement: Config Get
|
||||
|
||||
The config command SHALL retrieve specific configuration values.
|
||||
|
||||
#### Scenario: Get top-level key
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` with a valid top-level key
|
||||
- **THEN** print the raw value only (no labels or formatting)
|
||||
- **AND** exit with code 0
|
||||
|
||||
#### Scenario: Get nested key with dot notation
|
||||
|
||||
- **WHEN** user executes `openspec config get featureFlags.someFlag`
|
||||
- **THEN** traverse the nested structure using dot notation
|
||||
- **AND** print the value at that path
|
||||
|
||||
#### Scenario: Get non-existent key
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` with a key that does not exist
|
||||
- **THEN** print nothing (empty output)
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Get object value
|
||||
|
||||
- **WHEN** user executes `openspec config get <key>` where the value is an object
|
||||
- **THEN** print the object as JSON
|
||||
|
||||
### Requirement: Config Set
|
||||
|
||||
The config command SHALL set configuration values with automatic type coercion.
|
||||
|
||||
#### Scenario: Set string value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value>`
|
||||
- **AND** value does not match boolean or number patterns
|
||||
- **THEN** store value as a string
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Set boolean value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> true` or `openspec config set <key> false`
|
||||
- **THEN** store value as boolean (not string)
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Set numeric value
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value>`
|
||||
- **AND** value is a valid number (integer or float)
|
||||
- **THEN** store value as number (not string)
|
||||
|
||||
#### Scenario: Force string with --string flag
|
||||
|
||||
- **WHEN** user executes `openspec config set <key> <value> --string`
|
||||
- **THEN** store value as string regardless of content
|
||||
- **AND** this allows storing literal "true" or "123" as strings
|
||||
|
||||
#### Scenario: Set nested key
|
||||
|
||||
- **WHEN** user executes `openspec config set featureFlags.newFlag true`
|
||||
- **THEN** create intermediate objects if they don't exist
|
||||
- **AND** set the value at the nested path
|
||||
|
||||
### Requirement: Config Unset
|
||||
|
||||
The config command SHALL remove configuration overrides.
|
||||
|
||||
#### Scenario: Unset existing key
|
||||
|
||||
- **WHEN** user executes `openspec config unset <key>`
|
||||
- **AND** the key exists in the config
|
||||
- **THEN** remove the key from the config file
|
||||
- **AND** the value reverts to its default
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Unset non-existent key
|
||||
|
||||
- **WHEN** user executes `openspec config unset <key>`
|
||||
- **AND** the key does not exist in the config
|
||||
- **THEN** display message indicating key was not set
|
||||
- **AND** exit with code 0
|
||||
|
||||
### Requirement: Config Reset
|
||||
|
||||
The config command SHALL reset configuration to defaults.
|
||||
|
||||
#### Scenario: Reset all with confirmation
|
||||
|
||||
- **WHEN** user executes `openspec config reset --all`
|
||||
- **THEN** prompt for confirmation before proceeding
|
||||
- **AND** if confirmed, delete the config file or reset to defaults
|
||||
- **AND** display confirmation message
|
||||
|
||||
#### Scenario: Reset all with -y flag
|
||||
|
||||
- **WHEN** user executes `openspec config reset --all -y`
|
||||
- **THEN** reset without prompting for confirmation
|
||||
|
||||
#### Scenario: Reset without --all flag
|
||||
|
||||
- **WHEN** user executes `openspec config reset` without `--all`
|
||||
- **THEN** display error indicating `--all` is required
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Config Edit
|
||||
|
||||
The config command SHALL open the config file in the user's editor.
|
||||
|
||||
#### Scenario: Open editor successfully
|
||||
|
||||
- **WHEN** user executes `openspec config edit`
|
||||
- **AND** `$EDITOR` or `$VISUAL` environment variable is set
|
||||
- **THEN** open the config file in that editor
|
||||
- **AND** create the config file with defaults if it doesn't exist
|
||||
- **AND** wait for the editor to close before returning
|
||||
|
||||
#### Scenario: No editor configured
|
||||
|
||||
- **WHEN** user executes `openspec config edit`
|
||||
- **AND** neither `$EDITOR` nor `$VISUAL` is set
|
||||
- **THEN** display error message suggesting to set `$EDITOR`
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Key Naming Convention
|
||||
|
||||
The config command SHALL use camelCase keys matching the JSON structure.
|
||||
|
||||
#### Scenario: Keys match JSON structure
|
||||
|
||||
- **WHEN** accessing configuration keys via CLI
|
||||
- **THEN** use camelCase matching the actual JSON property names
|
||||
- **AND** support dot notation for nested access (e.g., `featureFlags.someFlag`)
|
||||
|
||||
### Requirement: Schema Validation
|
||||
|
||||
The config command SHALL validate configuration writes against the config schema using zod, while rejecting unknown keys for `config set` unless explicitly overridden.
|
||||
|
||||
#### Scenario: Unknown key rejected by default
|
||||
|
||||
- **WHEN** user executes `openspec config set someFutureKey 123`
|
||||
- **THEN** display a descriptive error message indicating the key is invalid
|
||||
- **AND** do not modify the config file
|
||||
- **AND** exit with code 1
|
||||
|
||||
#### Scenario: Unknown key accepted with override
|
||||
|
||||
- **WHEN** user executes `openspec config set someFutureKey 123 --allow-unknown`
|
||||
- **THEN** the value is saved successfully
|
||||
- **AND** exit with code 0
|
||||
|
||||
#### Scenario: Invalid feature flag value rejected
|
||||
|
||||
- **WHEN** user executes `openspec config set featureFlags.someFlag notABoolean`
|
||||
- **THEN** display a descriptive error message
|
||||
- **AND** do not modify the config file
|
||||
- **AND** exit with code 1
|
||||
|
||||
### Requirement: Reserved Scope Flag
|
||||
|
||||
The config command SHALL reserve the `--scope` flag for future extensibility.
|
||||
|
||||
#### Scenario: Scope flag defaults to global
|
||||
|
||||
- **WHEN** user executes any config command without `--scope`
|
||||
- **THEN** operate on global configuration (default behavior)
|
||||
|
||||
#### Scenario: Project scope not yet implemented
|
||||
|
||||
- **WHEN** user executes `openspec config --scope project <subcommand>`
|
||||
- **THEN** display error message: "Project-local config is not yet implemented"
|
||||
- **AND** exit with code 1
|
||||
@@ -76,6 +76,12 @@ The command SHALL properly configure selected AI tools with OpenSpec-specific in
|
||||
- **THEN** create or update `CLINE.md` in the project root directory (not inside openspec/)
|
||||
- **AND** populate the managed block with a short stub that points teammates to `@/openspec/AGENTS.md`
|
||||
|
||||
#### Scenario: Configuring iFlow CLI
|
||||
|
||||
- **WHEN** iFlow CLI is selected
|
||||
- **THEN** create or update `IFLOW.md` in the project root directory (not inside openspec/)
|
||||
- **AND** populate the managed block with a short stub that points teammates to `@/openspec/AGENTS.md`
|
||||
|
||||
#### Scenario: Creating new CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md does not exist
|
||||
@@ -118,6 +124,12 @@ The command SHALL provide clear, actionable next steps upon successful initializ
|
||||
- **WHEN** initialization completes successfully
|
||||
- **THEN** include prompt: "Please explain the OpenSpec workflow from openspec/AGENTS.md and how I should work with you on this project"
|
||||
|
||||
#### Scenario: Displaying restart instruction
|
||||
- **WHEN** initialization completes successfully and tools were created or refreshed
|
||||
- **THEN** display a prominent restart instruction before the "Next steps" section
|
||||
- **AND** inform users that slash commands are loaded at startup
|
||||
- **AND** instruct users to restart their coding assistant to ensure /openspec commands appear
|
||||
|
||||
### Requirement: Exit Codes
|
||||
|
||||
The command SHALL use consistent exit codes to indicate different failure modes.
|
||||
@@ -238,6 +250,14 @@ The init command SHALL generate slash command files for supported editors using
|
||||
- **AND** wrap the OpenSpec managed markers (`<!-- OPENSPEC:START -->` / `<!-- OPENSPEC:END -->`) inside the `prompt` value so `openspec update` can safely refresh the body between markers without touching the TOML framing
|
||||
- **AND** ensure the slash-command copy matches the existing proposal/apply/archive templates used by other tools
|
||||
|
||||
#### Scenario: Generating slash commands for iFlow CLI
|
||||
- **WHEN** the user selects iFlow CLI during initialization
|
||||
- **THEN** create `.iflow/commands/openspec-proposal.md`, `.iflow/commands/openspec-apply.md`, and `.iflow/commands/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** include YAML frontmatter with `name`, `id`, `category`, and `description` fields for each command
|
||||
- **AND** wrap the generated content in OpenSpec managed markers so `openspec update` can safely refresh the commands
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for RooCode
|
||||
- **WHEN** the user selects RooCode during initialization
|
||||
- **THEN** create `.roo/commands/openspec-proposal.md`, `.roo/commands/openspec-apply.md`, and `.roo/commands/openspec-archive.md`
|
||||
|
||||
@@ -123,6 +123,13 @@ The update command SHALL refresh existing slash command files for configured too
|
||||
- **AND** replace only the content between `<!-- OPENSPEC:START -->` and `<!-- OPENSPEC:END -->` markers inside the `prompt = """` block so the TOML framing (`description`, `prompt`) stays intact
|
||||
- **AND** skip creating any missing `.toml` files during update; only pre-existing Gemini commands are refreshed
|
||||
|
||||
#### Scenario: Updating slash commands for iFlow CLI
|
||||
- **WHEN** `.iflow/commands/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** preserve the YAML frontmatter with `name`, `id`, `category`, and `description` fields
|
||||
- **AND** update only the OpenSpec-managed block between markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Missing slash command file
|
||||
- **WHEN** a tool lacks a slash command file
|
||||
- **THEN** do not create a new file during update
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# global-config Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
This spec defines how OpenSpec resolves, reads, and writes user-level global configuration. It governs the `src/core/global-config.ts` module, which provides the foundation for storing user preferences, feature flags, and settings that persist across projects. The spec ensures cross-platform compatibility by following XDG Base Directory Specification with platform-specific fallbacks, and guarantees forward/backward compatibility through schema evolution rules.
|
||||
## Requirements
|
||||
### Requirement: Global Config Directory Path
|
||||
|
||||
The system SHALL resolve the global configuration directory path following XDG Base Directory Specification with platform-specific fallbacks.
|
||||
|
||||
#### Scenario: Unix/macOS with XDG_CONFIG_HOME set
|
||||
- **WHEN** `$XDG_CONFIG_HOME` environment variable is set to `/custom/config`
|
||||
- **THEN** `getGlobalConfigDir()` returns `/custom/config/openspec`
|
||||
|
||||
#### Scenario: Unix/macOS without XDG_CONFIG_HOME
|
||||
- **WHEN** `$XDG_CONFIG_HOME` environment variable is not set
|
||||
- **AND** the platform is Unix or macOS
|
||||
- **THEN** `getGlobalConfigDir()` returns `~/.config/openspec` (expanded to absolute path)
|
||||
|
||||
#### Scenario: Windows platform
|
||||
- **WHEN** the platform is Windows
|
||||
- **AND** `%APPDATA%` is set to `C:\Users\User\AppData\Roaming`
|
||||
- **THEN** `getGlobalConfigDir()` returns `C:\Users\User\AppData\Roaming\openspec`
|
||||
|
||||
### Requirement: Global Config Loading
|
||||
|
||||
The system SHALL load global configuration from the config directory with sensible defaults when the config file does not exist or cannot be parsed.
|
||||
|
||||
#### Scenario: Config file exists and is valid
|
||||
- **WHEN** `config.json` exists in the global config directory
|
||||
- **AND** the file contains valid JSON matching the config schema
|
||||
- **THEN** `getGlobalConfig()` returns the parsed configuration
|
||||
|
||||
#### Scenario: Config file does not exist
|
||||
- **WHEN** `config.json` does not exist in the global config directory
|
||||
- **THEN** `getGlobalConfig()` returns the default configuration
|
||||
- **AND** no directory or file is created
|
||||
|
||||
#### Scenario: Config file is invalid JSON
|
||||
- **WHEN** `config.json` exists but contains invalid JSON
|
||||
- **THEN** `getGlobalConfig()` returns the default configuration
|
||||
- **AND** a warning is logged to stderr
|
||||
|
||||
### Requirement: Global Config Saving
|
||||
|
||||
The system SHALL save global configuration to the config directory, creating the directory if it does not exist.
|
||||
|
||||
#### Scenario: Save config to new directory
|
||||
- **WHEN** `saveGlobalConfig(config)` is called
|
||||
- **AND** the global config directory does not exist
|
||||
- **THEN** the directory is created
|
||||
- **AND** `config.json` is written with the provided configuration
|
||||
|
||||
#### Scenario: Save config to existing directory
|
||||
- **WHEN** `saveGlobalConfig(config)` is called
|
||||
- **AND** the global config directory already exists
|
||||
- **THEN** `config.json` is written (overwriting if exists)
|
||||
|
||||
### Requirement: Default Configuration
|
||||
|
||||
The system SHALL provide a default configuration that is used when no config file exists.
|
||||
|
||||
#### Scenario: Default config structure
|
||||
- **WHEN** no config file exists
|
||||
- **THEN** the default configuration includes an empty `featureFlags` object
|
||||
|
||||
### Requirement: Config Schema Evolution
|
||||
|
||||
The system SHALL merge loaded configuration with default values to ensure new config fields are available even when loading older config files.
|
||||
|
||||
#### Scenario: Config file missing new fields
|
||||
- **WHEN** `config.json` exists with `{ "featureFlags": {} }`
|
||||
- **AND** the current schema includes a new field `defaultAiTool`
|
||||
- **THEN** `getGlobalConfig()` returns `{ featureFlags: {}, defaultAiTool: <default> }`
|
||||
- **AND** the loaded values take precedence over defaults for fields that exist in both
|
||||
|
||||
#### Scenario: Config file has extra unknown fields
|
||||
- **WHEN** `config.json` contains fields not in the current schema
|
||||
- **THEN** the unknown fields are preserved in the returned configuration
|
||||
- **AND** no error or warning is raised
|
||||
|
||||
+7
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@fission-ai/openspec",
|
||||
"version": "0.15.0",
|
||||
"version": "0.17.0",
|
||||
"description": "AI-native system for spec-driven development",
|
||||
"keywords": [
|
||||
"openspec",
|
||||
@@ -32,11 +32,13 @@
|
||||
"files": [
|
||||
"dist",
|
||||
"bin",
|
||||
"scripts/postinstall.js",
|
||||
"!dist/**/*.test.js",
|
||||
"!dist/**/__tests__",
|
||||
"!dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"lint": "eslint src/",
|
||||
"build": "node build.js",
|
||||
"dev": "tsc --watch",
|
||||
"dev:cli": "pnpm build && node bin/openspec.js",
|
||||
@@ -44,8 +46,10 @@
|
||||
"test:watch": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest --coverage",
|
||||
"test:postinstall": "node scripts/postinstall.js",
|
||||
"prepare": "pnpm run build",
|
||||
"prepublishOnly": "pnpm run build",
|
||||
"postinstall": "node scripts/postinstall.js",
|
||||
"check:pack-version": "node scripts/pack-version-check.mjs",
|
||||
"release": "pnpm run release:ci",
|
||||
"release:ci": "pnpm run check:pack-version && pnpm exec changeset publish",
|
||||
@@ -59,7 +63,9 @@
|
||||
"@changesets/cli": "^2.27.7",
|
||||
"@types/node": "^24.2.0",
|
||||
"@vitest/ui": "^3.2.4",
|
||||
"eslint": "^9.39.2",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.50.1",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
Generated
+762
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Postinstall script for auto-installing shell completions
|
||||
*
|
||||
* This script runs automatically after npm install unless:
|
||||
* - CI=true environment variable is set
|
||||
* - OPENSPEC_NO_COMPLETIONS=1 environment variable is set
|
||||
* - dist/ directory doesn't exist (dev setup scenario)
|
||||
*
|
||||
* The script never fails npm install - all errors are caught and handled gracefully.
|
||||
*/
|
||||
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
/**
|
||||
* Check if we should skip installation
|
||||
*/
|
||||
function shouldSkipInstallation() {
|
||||
// Skip in CI environments
|
||||
if (process.env.CI === 'true' || process.env.CI === '1') {
|
||||
return { skip: true, reason: 'CI environment detected' };
|
||||
}
|
||||
|
||||
// Skip if user opted out
|
||||
if (process.env.OPENSPEC_NO_COMPLETIONS === '1') {
|
||||
return { skip: true, reason: 'OPENSPEC_NO_COMPLETIONS=1 set' };
|
||||
}
|
||||
|
||||
return { skip: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if dist/ directory exists
|
||||
*/
|
||||
async function distExists() {
|
||||
const distPath = path.join(__dirname, '..', 'dist');
|
||||
try {
|
||||
const stat = await fs.stat(distPath);
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the user's shell
|
||||
*/
|
||||
async function detectShell() {
|
||||
try {
|
||||
const { detectShell } = await import('../dist/utils/shell-detection.js');
|
||||
const result = detectShell();
|
||||
return result.shell;
|
||||
} catch (error) {
|
||||
// Fail silently if detection module doesn't exist
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install completions for the detected shell
|
||||
*/
|
||||
async function installCompletions(shell) {
|
||||
try {
|
||||
const { CompletionFactory } = await import('../dist/core/completions/factory.js');
|
||||
const { COMMAND_REGISTRY } = await import('../dist/core/completions/command-registry.js');
|
||||
|
||||
// Check if shell is supported
|
||||
if (!CompletionFactory.isSupported(shell)) {
|
||||
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate completion script
|
||||
const generator = CompletionFactory.createGenerator(shell);
|
||||
const script = generator.generate(COMMAND_REGISTRY);
|
||||
|
||||
// Install completion script
|
||||
const installer = CompletionFactory.createInstaller(shell);
|
||||
const result = await installer.install(script);
|
||||
|
||||
if (result.success) {
|
||||
// Show success message based on installation type
|
||||
if (result.isOhMyZsh) {
|
||||
console.log(`✓ Shell completions installed`);
|
||||
console.log(` Restart shell: exec zsh`);
|
||||
} else if (result.zshrcConfigured) {
|
||||
console.log(`✓ Shell completions installed and configured`);
|
||||
console.log(` Restart shell: exec zsh`);
|
||||
} else {
|
||||
console.log(`✓ Shell completions installed to ~/.zsh/completions/`);
|
||||
console.log(` Add to ~/.zshrc: fpath=(~/.zsh/completions $fpath)`);
|
||||
console.log(` Then: exec zsh`);
|
||||
}
|
||||
} else {
|
||||
// Installation failed, show tip for manual install
|
||||
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fail gracefully - show tip for manual install
|
||||
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
async function main() {
|
||||
try {
|
||||
// Check if we should skip
|
||||
const skipCheck = shouldSkipInstallation();
|
||||
if (skipCheck.skip) {
|
||||
// Silent skip - no output
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if dist/ exists (skip silently if not - expected during dev setup)
|
||||
if (!(await distExists())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Detect shell
|
||||
const shell = await detectShell();
|
||||
if (!shell) {
|
||||
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Install completions
|
||||
await installCompletions(shell);
|
||||
} catch (error) {
|
||||
// Fail gracefully - never break npm install
|
||||
// Show tip for manual install
|
||||
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
|
||||
}
|
||||
}
|
||||
|
||||
// Run main and handle any unhandled errors
|
||||
main().catch(() => {
|
||||
// Silent failure - never break npm install
|
||||
process.exit(0);
|
||||
});
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Test script for postinstall.js
|
||||
# Tests different scenarios: normal install, CI, opt-out
|
||||
|
||||
set -e
|
||||
|
||||
echo "======================================"
|
||||
echo "Testing OpenSpec Postinstall Script"
|
||||
echo "======================================"
|
||||
echo ""
|
||||
|
||||
# Save original environment
|
||||
ORIGINAL_CI="${CI:-}"
|
||||
ORIGINAL_OPENSPEC_NO_COMPLETIONS="${OPENSPEC_NO_COMPLETIONS:-}"
|
||||
|
||||
# Test 1: Normal install
|
||||
echo "Test 1: Normal install (should attempt to install completions)"
|
||||
echo "--------------------------------------"
|
||||
unset CI
|
||||
unset OPENSPEC_NO_COMPLETIONS
|
||||
node scripts/postinstall.js
|
||||
echo ""
|
||||
|
||||
# Test 2: CI environment (should skip silently)
|
||||
echo "Test 2: CI=true (should skip silently)"
|
||||
echo "--------------------------------------"
|
||||
export CI=true
|
||||
node scripts/postinstall.js
|
||||
echo "[No output expected - skipped due to CI]"
|
||||
echo ""
|
||||
|
||||
# Test 3: Opt-out flag (should skip silently)
|
||||
echo "Test 3: OPENSPEC_NO_COMPLETIONS=1 (should skip silently)"
|
||||
echo "--------------------------------------"
|
||||
unset CI
|
||||
export OPENSPEC_NO_COMPLETIONS=1
|
||||
node scripts/postinstall.js
|
||||
echo "[No output expected - skipped due to opt-out]"
|
||||
echo ""
|
||||
|
||||
# Restore original environment
|
||||
if [ -n "$ORIGINAL_CI" ]; then
|
||||
export CI="$ORIGINAL_CI"
|
||||
else
|
||||
unset CI
|
||||
fi
|
||||
|
||||
if [ -n "$ORIGINAL_OPENSPEC_NO_COMPLETIONS" ]; then
|
||||
export OPENSPEC_NO_COMPLETIONS="$ORIGINAL_OPENSPEC_NO_COMPLETIONS"
|
||||
else
|
||||
unset OPENSPEC_NO_COMPLETIONS
|
||||
fi
|
||||
|
||||
echo "======================================"
|
||||
echo "All tests completed successfully!"
|
||||
echo "======================================"
|
||||
+68
-2
@@ -3,7 +3,6 @@ import { createRequire } from 'module';
|
||||
import ora from 'ora';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { InitCommand } from '../core/init.js';
|
||||
import { AI_TOOLS } from '../core/config.js';
|
||||
import { UpdateCommand } from '../core/update.js';
|
||||
import { ListCommand } from '../core/list.js';
|
||||
@@ -13,6 +12,8 @@ import { registerSpecCommand } from '../commands/spec.js';
|
||||
import { ChangeCommand } from '../commands/change.js';
|
||||
import { ValidateCommand } from '../commands/validate.js';
|
||||
import { ShowCommand } from '../commands/show.js';
|
||||
import { CompletionCommand } from '../commands/completion.js';
|
||||
import { registerConfigCommand } from '../commands/config.js';
|
||||
|
||||
const program = new Command();
|
||||
const require = createRequire(import.meta.url);
|
||||
@@ -29,7 +30,7 @@ program.option('--no-color', 'Disable color output');
|
||||
// Apply global flags before any command runs
|
||||
program.hook('preAction', (thisCommand) => {
|
||||
const opts = thisCommand.opts();
|
||||
if (opts.noColor) {
|
||||
if (opts.color === false) {
|
||||
process.env.NO_COLOR = '1';
|
||||
}
|
||||
});
|
||||
@@ -62,6 +63,7 @@ program
|
||||
}
|
||||
}
|
||||
|
||||
const { InitCommand } = await import('../core/init.js');
|
||||
const initCommand = new InitCommand({
|
||||
tools: options?.tools,
|
||||
});
|
||||
@@ -199,6 +201,7 @@ program
|
||||
});
|
||||
|
||||
registerSpecCommand(program);
|
||||
registerConfigCommand(program);
|
||||
|
||||
// Top-level validate command
|
||||
program
|
||||
@@ -250,4 +253,67 @@ program
|
||||
}
|
||||
});
|
||||
|
||||
// Completion command with subcommands
|
||||
const completionCmd = program
|
||||
.command('completion')
|
||||
.description('Manage shell completions for OpenSpec CLI');
|
||||
|
||||
completionCmd
|
||||
.command('generate [shell]')
|
||||
.description('Generate completion script for a shell (outputs to stdout)')
|
||||
.action(async (shell?: string) => {
|
||||
try {
|
||||
const completionCommand = new CompletionCommand();
|
||||
await completionCommand.generate({ shell });
|
||||
} catch (error) {
|
||||
console.log();
|
||||
ora().fail(`Error: ${(error as Error).message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
completionCmd
|
||||
.command('install [shell]')
|
||||
.description('Install completion script for a shell')
|
||||
.option('--verbose', 'Show detailed installation output')
|
||||
.action(async (shell?: string, options?: { verbose?: boolean }) => {
|
||||
try {
|
||||
const completionCommand = new CompletionCommand();
|
||||
await completionCommand.install({ shell, verbose: options?.verbose });
|
||||
} catch (error) {
|
||||
console.log();
|
||||
ora().fail(`Error: ${(error as Error).message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
completionCmd
|
||||
.command('uninstall [shell]')
|
||||
.description('Uninstall completion script for a shell')
|
||||
.option('-y, --yes', 'Skip confirmation prompts')
|
||||
.action(async (shell?: string, options?: { yes?: boolean }) => {
|
||||
try {
|
||||
const completionCommand = new CompletionCommand();
|
||||
await completionCommand.uninstall({ shell, yes: options?.yes });
|
||||
} catch (error) {
|
||||
console.log();
|
||||
ora().fail(`Error: ${(error as Error).message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
// Hidden command for machine-readable completion data
|
||||
program
|
||||
.command('__complete <type>', { hidden: true })
|
||||
.description('Output completion data in machine-readable format (internal use)')
|
||||
.action(async (type: string) => {
|
||||
try {
|
||||
const completionCommand = new CompletionCommand();
|
||||
await completionCommand.complete({ type });
|
||||
} catch (error) {
|
||||
// Silently fail for graceful shell completion experience
|
||||
process.exitCode = 1;
|
||||
}
|
||||
});
|
||||
|
||||
program.parse();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { select } from '@inquirer/prompts';
|
||||
import { JsonConverter } from '../core/converters/json-converter.js';
|
||||
import { Validator } from '../core/validation/validator.js';
|
||||
import { ChangeParser } from '../core/parsers/change-parser.js';
|
||||
@@ -30,9 +29,10 @@ export class ChangeCommand {
|
||||
const changesPath = path.join(process.cwd(), 'openspec', 'changes');
|
||||
|
||||
if (!changeName) {
|
||||
const canPrompt = isInteractive(options?.noInteractive);
|
||||
const canPrompt = isInteractive(options);
|
||||
const changes = await this.getActiveChanges(changesPath);
|
||||
if (canPrompt && changes.length > 0) {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
const selected = await select({
|
||||
message: 'Select a change to show',
|
||||
choices: changes.map(id => ({ name: id, value: id })),
|
||||
@@ -186,9 +186,10 @@ export class ChangeCommand {
|
||||
const changesPath = path.join(process.cwd(), 'openspec', 'changes');
|
||||
|
||||
if (!changeName) {
|
||||
const canPrompt = isInteractive(options?.noInteractive);
|
||||
const canPrompt = isInteractive(options);
|
||||
const changes = await getActiveChangeIds();
|
||||
if (canPrompt && changes.length > 0) {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
const selected = await select({
|
||||
message: 'Select a change to validate',
|
||||
choices: changes.map(id => ({ name: id, value: id })),
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import ora from 'ora';
|
||||
import { CompletionFactory } from '../core/completions/factory.js';
|
||||
import { COMMAND_REGISTRY } from '../core/completions/command-registry.js';
|
||||
import { detectShell, SupportedShell } from '../utils/shell-detection.js';
|
||||
import { CompletionProvider } from '../core/completions/completion-provider.js';
|
||||
import { getArchivedChangeIds } from '../utils/item-discovery.js';
|
||||
|
||||
interface GenerateOptions {
|
||||
shell?: string;
|
||||
}
|
||||
|
||||
interface InstallOptions {
|
||||
shell?: string;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
interface UninstallOptions {
|
||||
shell?: string;
|
||||
yes?: boolean;
|
||||
}
|
||||
|
||||
interface CompleteOptions {
|
||||
type: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command for managing shell completions for OpenSpec CLI
|
||||
*/
|
||||
export class CompletionCommand {
|
||||
private completionProvider: CompletionProvider;
|
||||
|
||||
constructor() {
|
||||
this.completionProvider = new CompletionProvider();
|
||||
}
|
||||
/**
|
||||
* Resolve shell parameter or exit with error
|
||||
*
|
||||
* @param shell - The shell parameter (may be undefined)
|
||||
* @param operationName - Name of the operation (for error messages)
|
||||
* @returns Resolved shell or null if should exit
|
||||
*/
|
||||
private resolveShellOrExit(shell: string | undefined, operationName: string): SupportedShell | null {
|
||||
const normalizedShell = this.normalizeShell(shell);
|
||||
|
||||
if (!normalizedShell) {
|
||||
const detectionResult = detectShell();
|
||||
|
||||
if (detectionResult.shell && CompletionFactory.isSupported(detectionResult.shell)) {
|
||||
return detectionResult.shell;
|
||||
}
|
||||
|
||||
// Shell was detected but not supported
|
||||
if (detectionResult.detected && !detectionResult.shell) {
|
||||
console.error(`Error: Shell '${detectionResult.detected}' is not supported yet. Currently supported: ${CompletionFactory.getSupportedShells().join(', ')}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
// No shell specified and cannot auto-detect
|
||||
console.error('Error: Could not auto-detect shell. Please specify shell explicitly.');
|
||||
console.error(`Usage: openspec completion ${operationName} [shell]`);
|
||||
console.error(`Currently supported: ${CompletionFactory.getSupportedShells().join(', ')}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CompletionFactory.isSupported(normalizedShell)) {
|
||||
console.error(`Error: Shell '${normalizedShell}' is not supported yet. Currently supported: ${CompletionFactory.getSupportedShells().join(', ')}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizedShell;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate completion script and output to stdout
|
||||
*
|
||||
* @param options - Options for generation (shell type)
|
||||
*/
|
||||
async generate(options: GenerateOptions = {}): Promise<void> {
|
||||
const shell = this.resolveShellOrExit(options.shell, 'generate');
|
||||
if (!shell) return;
|
||||
|
||||
await this.generateForShell(shell);
|
||||
}
|
||||
|
||||
/**
|
||||
* Install completion script to the appropriate location
|
||||
*
|
||||
* @param options - Options for installation (shell type, verbose output)
|
||||
*/
|
||||
async install(options: InstallOptions = {}): Promise<void> {
|
||||
const shell = this.resolveShellOrExit(options.shell, 'install');
|
||||
if (!shell) return;
|
||||
|
||||
await this.installForShell(shell, options.verbose || false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall completion script from the installation location
|
||||
*
|
||||
* @param options - Options for uninstallation (shell type, yes flag)
|
||||
*/
|
||||
async uninstall(options: UninstallOptions = {}): Promise<void> {
|
||||
const shell = this.resolveShellOrExit(options.shell, 'uninstall');
|
||||
if (!shell) return;
|
||||
|
||||
await this.uninstallForShell(shell, options.yes || false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate completion script for a specific shell
|
||||
*/
|
||||
private async generateForShell(shell: SupportedShell): Promise<void> {
|
||||
const generator = CompletionFactory.createGenerator(shell);
|
||||
const script = generator.generate(COMMAND_REGISTRY);
|
||||
console.log(script);
|
||||
}
|
||||
|
||||
/**
|
||||
* Install completion script for a specific shell
|
||||
*/
|
||||
private async installForShell(shell: SupportedShell, verbose: boolean): Promise<void> {
|
||||
const generator = CompletionFactory.createGenerator(shell);
|
||||
const installer = CompletionFactory.createInstaller(shell);
|
||||
|
||||
const spinner = ora(`Installing ${shell} completion script...`).start();
|
||||
|
||||
try {
|
||||
// Generate the completion script
|
||||
const script = generator.generate(COMMAND_REGISTRY);
|
||||
|
||||
// Install it
|
||||
const result = await installer.install(script);
|
||||
|
||||
spinner.stop();
|
||||
|
||||
if (result.success) {
|
||||
console.log(`✓ ${result.message}`);
|
||||
|
||||
if (verbose && result.installedPath) {
|
||||
console.log(` Installed to: ${result.installedPath}`);
|
||||
if (result.backupPath) {
|
||||
console.log(` Backup created: ${result.backupPath}`);
|
||||
}
|
||||
if (result.zshrcConfigured) {
|
||||
console.log(` ~/.zshrc configured automatically`);
|
||||
}
|
||||
}
|
||||
|
||||
// Print instructions (only shown if .zshrc wasn't auto-configured)
|
||||
if (result.instructions && result.instructions.length > 0) {
|
||||
console.log('');
|
||||
for (const instruction of result.instructions) {
|
||||
console.log(instruction);
|
||||
}
|
||||
} else if (result.zshrcConfigured) {
|
||||
console.log('');
|
||||
console.log('Restart your shell or run: exec zsh');
|
||||
}
|
||||
} else {
|
||||
console.error(`✗ ${result.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
} catch (error) {
|
||||
spinner.stop();
|
||||
console.error(`✗ Failed to install completion script: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall completion script for a specific shell
|
||||
*/
|
||||
private async uninstallForShell(shell: SupportedShell, skipConfirmation: boolean): Promise<void> {
|
||||
const installer = CompletionFactory.createInstaller(shell);
|
||||
|
||||
// Prompt for confirmation unless --yes flag is provided
|
||||
if (!skipConfirmation) {
|
||||
const { confirm } = await import('@inquirer/prompts');
|
||||
const confirmed = await confirm({
|
||||
message: 'Remove OpenSpec configuration from ~/.zshrc?',
|
||||
default: false,
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('Uninstall cancelled.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const spinner = ora(`Uninstalling ${shell} completion script...`).start();
|
||||
|
||||
try {
|
||||
const result = await installer.uninstall();
|
||||
|
||||
spinner.stop();
|
||||
|
||||
if (result.success) {
|
||||
console.log(`✓ ${result.message}`);
|
||||
} else {
|
||||
console.error(`✗ ${result.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
} catch (error) {
|
||||
spinner.stop();
|
||||
console.error(`✗ Failed to uninstall completion script: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Output machine-readable completion data for shell consumption
|
||||
* Format: tab-separated "id\tdescription" per line
|
||||
*
|
||||
* @param options - Options specifying completion type
|
||||
*/
|
||||
async complete(options: CompleteOptions): Promise<void> {
|
||||
const type = options.type.toLowerCase();
|
||||
|
||||
try {
|
||||
switch (type) {
|
||||
case 'changes': {
|
||||
const changeIds = await this.completionProvider.getChangeIds();
|
||||
for (const id of changeIds) {
|
||||
console.log(`${id}\tactive change`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'specs': {
|
||||
const specIds = await this.completionProvider.getSpecIds();
|
||||
for (const id of specIds) {
|
||||
console.log(`${id}\tspecification`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'archived-changes': {
|
||||
const archivedIds = await getArchivedChangeIds();
|
||||
for (const id of archivedIds) {
|
||||
console.log(`${id}\tarchived change`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Invalid type - silently exit with no output for graceful shell completion failure
|
||||
process.exitCode = 1;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Silently fail for graceful shell completion experience
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize shell parameter to lowercase
|
||||
*/
|
||||
private normalizeShell(shell?: string): string | undefined {
|
||||
return shell?.toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { Command } from 'commander';
|
||||
import { spawn } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import {
|
||||
getGlobalConfigPath,
|
||||
getGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
GlobalConfig,
|
||||
} from '../core/global-config.js';
|
||||
import {
|
||||
getNestedValue,
|
||||
setNestedValue,
|
||||
deleteNestedValue,
|
||||
coerceValue,
|
||||
formatValueYaml,
|
||||
validateConfigKeyPath,
|
||||
validateConfig,
|
||||
DEFAULT_CONFIG,
|
||||
} from '../core/config-schema.js';
|
||||
|
||||
/**
|
||||
* Register the config command and all its subcommands.
|
||||
*
|
||||
* @param program - The Commander program instance
|
||||
*/
|
||||
export function registerConfigCommand(program: Command): void {
|
||||
const configCmd = program
|
||||
.command('config')
|
||||
.description('View and modify global OpenSpec configuration')
|
||||
.option('--scope <scope>', 'Config scope (only "global" supported currently)')
|
||||
.hook('preAction', (thisCommand) => {
|
||||
const opts = thisCommand.opts();
|
||||
if (opts.scope && opts.scope !== 'global') {
|
||||
console.error('Error: Project-local config is not yet implemented');
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
// config path
|
||||
configCmd
|
||||
.command('path')
|
||||
.description('Show config file location')
|
||||
.action(() => {
|
||||
console.log(getGlobalConfigPath());
|
||||
});
|
||||
|
||||
// config list
|
||||
configCmd
|
||||
.command('list')
|
||||
.description('Show all current settings')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action((options: { json?: boolean }) => {
|
||||
const config = getGlobalConfig();
|
||||
|
||||
if (options.json) {
|
||||
console.log(JSON.stringify(config, null, 2));
|
||||
} else {
|
||||
console.log(formatValueYaml(config));
|
||||
}
|
||||
});
|
||||
|
||||
// config get
|
||||
configCmd
|
||||
.command('get <key>')
|
||||
.description('Get a specific value (raw, scriptable)')
|
||||
.action((key: string) => {
|
||||
const config = getGlobalConfig();
|
||||
const value = getNestedValue(config as Record<string, unknown>, key);
|
||||
|
||||
if (value === undefined) {
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
console.log(JSON.stringify(value));
|
||||
} else {
|
||||
console.log(String(value));
|
||||
}
|
||||
});
|
||||
|
||||
// config set
|
||||
configCmd
|
||||
.command('set <key> <value>')
|
||||
.description('Set a value (auto-coerce types)')
|
||||
.option('--string', 'Force value to be stored as string')
|
||||
.option('--allow-unknown', 'Allow setting unknown keys')
|
||||
.action((key: string, value: string, options: { string?: boolean; allowUnknown?: boolean }) => {
|
||||
const allowUnknown = Boolean(options.allowUnknown);
|
||||
const keyValidation = validateConfigKeyPath(key);
|
||||
if (!keyValidation.valid && !allowUnknown) {
|
||||
const reason = keyValidation.reason ? ` ${keyValidation.reason}.` : '';
|
||||
console.error(`Error: Invalid configuration key "${key}".${reason}`);
|
||||
console.error('Use "openspec config list" to see available keys.');
|
||||
console.error('Pass --allow-unknown to bypass this check.');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const config = getGlobalConfig() as Record<string, unknown>;
|
||||
const coercedValue = coerceValue(value, options.string || false);
|
||||
|
||||
// Create a copy to validate before saving
|
||||
const newConfig = JSON.parse(JSON.stringify(config));
|
||||
setNestedValue(newConfig, key, coercedValue);
|
||||
|
||||
// Validate the new config
|
||||
const validation = validateConfig(newConfig);
|
||||
if (!validation.success) {
|
||||
console.error(`Error: Invalid configuration - ${validation.error}`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply changes and save
|
||||
setNestedValue(config, key, coercedValue);
|
||||
saveGlobalConfig(config as GlobalConfig);
|
||||
|
||||
const displayValue =
|
||||
typeof coercedValue === 'string' ? `"${coercedValue}"` : String(coercedValue);
|
||||
console.log(`Set ${key} = ${displayValue}`);
|
||||
});
|
||||
|
||||
// config unset
|
||||
configCmd
|
||||
.command('unset <key>')
|
||||
.description('Remove a key (revert to default)')
|
||||
.action((key: string) => {
|
||||
const config = getGlobalConfig() as Record<string, unknown>;
|
||||
const existed = deleteNestedValue(config, key);
|
||||
|
||||
if (existed) {
|
||||
saveGlobalConfig(config as GlobalConfig);
|
||||
console.log(`Unset ${key} (reverted to default)`);
|
||||
} else {
|
||||
console.log(`Key "${key}" was not set`);
|
||||
}
|
||||
});
|
||||
|
||||
// config reset
|
||||
configCmd
|
||||
.command('reset')
|
||||
.description('Reset configuration to defaults')
|
||||
.option('--all', 'Reset all configuration (required)')
|
||||
.option('-y, --yes', 'Skip confirmation prompts')
|
||||
.action(async (options: { all?: boolean; yes?: boolean }) => {
|
||||
if (!options.all) {
|
||||
console.error('Error: --all flag is required for reset');
|
||||
console.error('Usage: openspec config reset --all [-y]');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!options.yes) {
|
||||
const { confirm } = await import('@inquirer/prompts');
|
||||
const confirmed = await confirm({
|
||||
message: 'Reset all configuration to defaults?',
|
||||
default: false,
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('Reset cancelled.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
saveGlobalConfig({ ...DEFAULT_CONFIG });
|
||||
console.log('Configuration reset to defaults');
|
||||
});
|
||||
|
||||
// config edit
|
||||
configCmd
|
||||
.command('edit')
|
||||
.description('Open config in $EDITOR')
|
||||
.action(async () => {
|
||||
const editor = process.env.EDITOR || process.env.VISUAL;
|
||||
|
||||
if (!editor) {
|
||||
console.error('Error: No editor configured');
|
||||
console.error('Set the EDITOR or VISUAL environment variable to your preferred editor');
|
||||
console.error('Example: export EDITOR=vim');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const configPath = getGlobalConfigPath();
|
||||
|
||||
// Ensure config file exists with defaults
|
||||
if (!fs.existsSync(configPath)) {
|
||||
saveGlobalConfig({ ...DEFAULT_CONFIG });
|
||||
}
|
||||
|
||||
// Spawn editor and wait for it to close
|
||||
// Avoid shell parsing to correctly handle paths with spaces in both
|
||||
// the editor path and config path
|
||||
const child = spawn(editor, [configPath], {
|
||||
stdio: 'inherit',
|
||||
shell: false,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error(`Editor exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
child.on('error', reject);
|
||||
});
|
||||
|
||||
try {
|
||||
const rawConfig = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsedConfig = JSON.parse(rawConfig);
|
||||
const validation = validateConfig(parsedConfig);
|
||||
|
||||
if (!validation.success) {
|
||||
console.error(`Error: Invalid configuration - ${validation.error}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
console.error(`Error: Config file not found at ${configPath}`);
|
||||
} else if (error instanceof SyntaxError) {
|
||||
console.error(`Error: Invalid JSON in ${configPath}`);
|
||||
console.error(error.message);
|
||||
} else {
|
||||
console.error(`Error: Unable to validate configuration - ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { select } from '@inquirer/prompts';
|
||||
import path from 'path';
|
||||
import { isInteractive } from '../utils/interactive.js';
|
||||
import { getActiveChangeIds, getSpecIds } from '../utils/item-discovery.js';
|
||||
@@ -13,11 +12,12 @@ const SPEC_FLAG_KEYS = new Set(['requirements', 'scenarios', 'requirement']);
|
||||
|
||||
export class ShowCommand {
|
||||
async execute(itemName?: string, options: { json?: boolean; type?: string; noInteractive?: boolean; [k: string]: any } = {}): Promise<void> {
|
||||
const interactive = isInteractive(options.noInteractive);
|
||||
const interactive = isInteractive(options);
|
||||
const typeOverride = this.normalizeType(options.type);
|
||||
|
||||
if (!itemName) {
|
||||
if (interactive) {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
const type = await select<ItemType>({
|
||||
message: 'What would you like to show?',
|
||||
choices: [
|
||||
@@ -44,6 +44,7 @@ export class ShowCommand {
|
||||
}
|
||||
|
||||
private async runInteractiveByType(type: ItemType, options: { json?: boolean; noInteractive?: boolean; [k: string]: any }): Promise<void> {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
if (type === 'change') {
|
||||
const changes = await getActiveChangeIds();
|
||||
if (changes.length === 0) {
|
||||
@@ -135,5 +136,3 @@ export class ShowCommand {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import { join } from 'path';
|
||||
import { MarkdownParser } from '../core/parsers/markdown-parser.js';
|
||||
import { Validator } from '../core/validation/validator.js';
|
||||
import type { Spec } from '../core/schemas/index.js';
|
||||
import { select } from '@inquirer/prompts';
|
||||
import { isInteractive } from '../utils/interactive.js';
|
||||
import { getSpecIds } from '../utils/item-discovery.js';
|
||||
|
||||
@@ -70,9 +69,10 @@ export class SpecCommand {
|
||||
|
||||
async show(specId?: string, options: ShowOptions = {}): Promise<void> {
|
||||
if (!specId) {
|
||||
const canPrompt = isInteractive(options?.noInteractive);
|
||||
const canPrompt = isInteractive(options);
|
||||
const specIds = await getSpecIds();
|
||||
if (canPrompt && specIds.length > 0) {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
specId = await select({
|
||||
message: 'Select a spec to show',
|
||||
choices: specIds.map(id => ({ name: id, value: id })),
|
||||
@@ -204,9 +204,10 @@ export function registerSpecCommand(rootProgram: typeof program) {
|
||||
.action(async (specId: string | undefined, options: { strict?: boolean; json?: boolean; noInteractive?: boolean }) => {
|
||||
try {
|
||||
if (!specId) {
|
||||
const canPrompt = isInteractive(options?.noInteractive);
|
||||
const canPrompt = isInteractive(options);
|
||||
const specIds = await getSpecIds();
|
||||
if (canPrompt && specIds.length > 0) {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
specId = await select({
|
||||
message: 'Select a spec to validate',
|
||||
choices: specIds.map(id => ({ name: id, value: id })),
|
||||
@@ -247,4 +248,4 @@ export function registerSpecCommand(rootProgram: typeof program) {
|
||||
});
|
||||
|
||||
return specCommand;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { select } from '@inquirer/prompts';
|
||||
import ora from 'ora';
|
||||
import path from 'path';
|
||||
import { Validator } from '../core/validation/validator.js';
|
||||
@@ -29,7 +28,7 @@ interface BulkItemResult {
|
||||
|
||||
export class ValidateCommand {
|
||||
async execute(itemName: string | undefined, options: ExecuteOptions = {}): Promise<void> {
|
||||
const interactive = isInteractive(options.noInteractive);
|
||||
const interactive = isInteractive(options);
|
||||
|
||||
// Handle bulk flags first
|
||||
if (options.all || options.changes || options.specs) {
|
||||
@@ -64,6 +63,7 @@ export class ValidateCommand {
|
||||
}
|
||||
|
||||
private async runInteractiveSelector(opts: { strict: boolean; json: boolean; concurrency?: string }): Promise<void> {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
const choice = await select({
|
||||
message: 'What would you like to validate?',
|
||||
choices: [
|
||||
@@ -212,6 +212,28 @@ export class ValidateCommand {
|
||||
});
|
||||
}
|
||||
|
||||
if (queue.length === 0) {
|
||||
spinner?.stop();
|
||||
|
||||
const summary = {
|
||||
totals: { items: 0, passed: 0, failed: 0 },
|
||||
byType: {
|
||||
...(scope.changes ? { change: { items: 0, passed: 0, failed: 0 } } : {}),
|
||||
...(scope.specs ? { spec: { items: 0, passed: 0, failed: 0 } } : {}),
|
||||
},
|
||||
} as const;
|
||||
|
||||
if (opts.json) {
|
||||
const out = { items: [] as BulkItemResult[], summary, version: '1.0' };
|
||||
console.log(JSON.stringify(out, null, 2));
|
||||
} else {
|
||||
console.log('No items found to validate.');
|
||||
}
|
||||
|
||||
process.exitCode = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const results: BulkItemResult[] = [];
|
||||
let index = 0;
|
||||
let running = 0;
|
||||
@@ -301,5 +323,3 @@ function getPlannedType(index: number, changeIds: string[], specIds: string[]):
|
||||
if (specIndex >= 0 && specIndex < specIds.length) return 'spec';
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
|
||||
+4
-1
@@ -1,6 +1,5 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { select, confirm } from '@inquirer/prompts';
|
||||
import { FileSystemUtils } from '../utils/file-system.js';
|
||||
import { getTaskProgressForChange, formatTaskStatus } from '../utils/task-progress.js';
|
||||
import { Validator } from './validation/validator.js';
|
||||
@@ -125,6 +124,7 @@ export class ArchiveCommand {
|
||||
const timestamp = new Date().toISOString();
|
||||
|
||||
if (!options.yes) {
|
||||
const { confirm } = await import('@inquirer/prompts');
|
||||
const proceed = await confirm({
|
||||
message: chalk.yellow('⚠️ WARNING: Skipping validation may archive invalid specs. Continue? (y/N)'),
|
||||
default: false
|
||||
@@ -149,6 +149,7 @@ export class ArchiveCommand {
|
||||
const incompleteTasks = Math.max(progress.total - progress.completed, 0);
|
||||
if (incompleteTasks > 0) {
|
||||
if (!options.yes) {
|
||||
const { confirm } = await import('@inquirer/prompts');
|
||||
const proceed = await confirm({
|
||||
message: `Warning: ${incompleteTasks} incomplete task(s) found. Continue?`,
|
||||
default: false
|
||||
@@ -179,6 +180,7 @@ export class ArchiveCommand {
|
||||
|
||||
let shouldUpdateSpecs = true;
|
||||
if (!options.yes) {
|
||||
const { confirm } = await import('@inquirer/prompts');
|
||||
shouldUpdateSpecs = await confirm({
|
||||
message: 'Proceed with spec updates?',
|
||||
default: true
|
||||
@@ -256,6 +258,7 @@ export class ArchiveCommand {
|
||||
}
|
||||
|
||||
private async selectChange(changesDir: string): Promise<string | null> {
|
||||
const { select } = await import('@inquirer/prompts');
|
||||
// Get all directories in changes (excluding archive)
|
||||
const entries = await fs.readdir(changesDir, { withFileTypes: true });
|
||||
const changeDirs = entries
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
import { CommandDefinition, FlagDefinition } from './types.js';
|
||||
|
||||
/**
|
||||
* Common flags used across multiple commands
|
||||
*/
|
||||
const COMMON_FLAGS = {
|
||||
json: {
|
||||
name: 'json',
|
||||
description: 'Output as JSON',
|
||||
} as FlagDefinition,
|
||||
jsonValidation: {
|
||||
name: 'json',
|
||||
description: 'Output validation results as JSON',
|
||||
} as FlagDefinition,
|
||||
strict: {
|
||||
name: 'strict',
|
||||
description: 'Enable strict validation mode',
|
||||
} as FlagDefinition,
|
||||
noInteractive: {
|
||||
name: 'no-interactive',
|
||||
description: 'Disable interactive prompts',
|
||||
} as FlagDefinition,
|
||||
type: {
|
||||
name: 'type',
|
||||
description: 'Specify item type when ambiguous',
|
||||
takesValue: true,
|
||||
values: ['change', 'spec'],
|
||||
} as FlagDefinition,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Registry of all OpenSpec CLI commands with their flags and metadata.
|
||||
* This registry is used to generate shell completion scripts.
|
||||
*/
|
||||
export const COMMAND_REGISTRY: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec in your project',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'path',
|
||||
flags: [
|
||||
{
|
||||
name: 'tools',
|
||||
description: 'Configure AI tools non-interactively (e.g., "all", "none", or comma-separated tool IDs)',
|
||||
takesValue: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'update',
|
||||
description: 'Update OpenSpec instruction files',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'path',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'List items (changes by default, or specs with --specs)',
|
||||
flags: [
|
||||
{
|
||||
name: 'specs',
|
||||
description: 'List specs instead of changes',
|
||||
},
|
||||
{
|
||||
name: 'changes',
|
||||
description: 'List changes explicitly (default)',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'view',
|
||||
description: 'Display an interactive dashboard of specs and changes',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate changes and specs',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-or-spec-id',
|
||||
flags: [
|
||||
{
|
||||
name: 'all',
|
||||
description: 'Validate all changes and specs',
|
||||
},
|
||||
{
|
||||
name: 'changes',
|
||||
description: 'Validate all changes',
|
||||
},
|
||||
{
|
||||
name: 'specs',
|
||||
description: 'Validate all specs',
|
||||
},
|
||||
COMMON_FLAGS.type,
|
||||
COMMON_FLAGS.strict,
|
||||
COMMON_FLAGS.jsonValidation,
|
||||
{
|
||||
name: 'concurrency',
|
||||
description: 'Max concurrent validations (defaults to env OPENSPEC_CONCURRENCY or 6)',
|
||||
takesValue: true,
|
||||
},
|
||||
COMMON_FLAGS.noInteractive,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a change or spec',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-or-spec-id',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
COMMON_FLAGS.type,
|
||||
COMMON_FLAGS.noInteractive,
|
||||
{
|
||||
name: 'deltas-only',
|
||||
description: 'Show only deltas (JSON only, change-specific)',
|
||||
},
|
||||
{
|
||||
name: 'requirements-only',
|
||||
description: 'Alias for --deltas-only (deprecated, change-specific)',
|
||||
},
|
||||
{
|
||||
name: 'requirements',
|
||||
description: 'Show only requirements, exclude scenarios (JSON only, spec-specific)',
|
||||
},
|
||||
{
|
||||
name: 'no-scenarios',
|
||||
description: 'Exclude scenario content (JSON only, spec-specific)',
|
||||
},
|
||||
{
|
||||
name: 'requirement',
|
||||
short: 'r',
|
||||
description: 'Show specific requirement by ID (JSON only, spec-specific)',
|
||||
takesValue: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'archive',
|
||||
description: 'Archive a completed change and update main specs',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-id',
|
||||
flags: [
|
||||
{
|
||||
name: 'yes',
|
||||
short: 'y',
|
||||
description: 'Skip confirmation prompts',
|
||||
},
|
||||
{
|
||||
name: 'skip-specs',
|
||||
description: 'Skip spec update operations',
|
||||
},
|
||||
{
|
||||
name: 'no-validate',
|
||||
description: 'Skip validation (not recommended)',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'change',
|
||||
description: 'Manage OpenSpec change proposals (deprecated)',
|
||||
flags: [],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a change proposal',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-id',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
{
|
||||
name: 'deltas-only',
|
||||
description: 'Show only deltas (JSON only)',
|
||||
},
|
||||
{
|
||||
name: 'requirements-only',
|
||||
description: 'Alias for --deltas-only (deprecated)',
|
||||
},
|
||||
COMMON_FLAGS.noInteractive,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'List all active changes (deprecated)',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
{
|
||||
name: 'long',
|
||||
description: 'Show id and title with counts',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate a change proposal',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-id',
|
||||
flags: [
|
||||
COMMON_FLAGS.strict,
|
||||
COMMON_FLAGS.jsonValidation,
|
||||
COMMON_FLAGS.noInteractive,
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'spec',
|
||||
description: 'Manage OpenSpec specifications',
|
||||
flags: [],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a specification',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'spec-id',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
{
|
||||
name: 'requirements',
|
||||
description: 'Show only requirements, exclude scenarios (JSON only)',
|
||||
},
|
||||
{
|
||||
name: 'no-scenarios',
|
||||
description: 'Exclude scenario content (JSON only)',
|
||||
},
|
||||
{
|
||||
name: 'requirement',
|
||||
short: 'r',
|
||||
description: 'Show specific requirement by ID (JSON only)',
|
||||
takesValue: true,
|
||||
},
|
||||
COMMON_FLAGS.noInteractive,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'List all specifications',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
{
|
||||
name: 'long',
|
||||
description: 'Show id and title with counts',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate a specification',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'spec-id',
|
||||
flags: [
|
||||
COMMON_FLAGS.strict,
|
||||
COMMON_FLAGS.jsonValidation,
|
||||
COMMON_FLAGS.noInteractive,
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'completion',
|
||||
description: 'Manage shell completions for OpenSpec CLI',
|
||||
flags: [],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'generate',
|
||||
description: 'Generate completion script for a shell (outputs to stdout)',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'shell',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'install',
|
||||
description: 'Install completion script for a shell',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'shell',
|
||||
flags: [
|
||||
{
|
||||
name: 'verbose',
|
||||
description: 'Show detailed installation output',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'uninstall',
|
||||
description: 'Uninstall completion script for a shell',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'shell',
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'config',
|
||||
description: 'View and modify global OpenSpec configuration',
|
||||
flags: [
|
||||
{
|
||||
name: 'scope',
|
||||
description: 'Config scope (only "global" supported currently)',
|
||||
takesValue: true,
|
||||
values: ['global'],
|
||||
},
|
||||
],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'path',
|
||||
description: 'Show config file location',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'Show all current settings',
|
||||
flags: [
|
||||
COMMON_FLAGS.json,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'get',
|
||||
description: 'Get a specific value (raw, scriptable)',
|
||||
acceptsPositional: true,
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'set',
|
||||
description: 'Set a value (auto-coerce types)',
|
||||
acceptsPositional: true,
|
||||
flags: [
|
||||
{
|
||||
name: 'string',
|
||||
description: 'Force value to be stored as string',
|
||||
},
|
||||
{
|
||||
name: 'allow-unknown',
|
||||
description: 'Allow setting unknown keys',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'unset',
|
||||
description: 'Remove a key (revert to default)',
|
||||
acceptsPositional: true,
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'reset',
|
||||
description: 'Reset configuration to defaults',
|
||||
flags: [
|
||||
{
|
||||
name: 'all',
|
||||
description: 'Reset all configuration (required)',
|
||||
},
|
||||
{
|
||||
name: 'yes',
|
||||
short: 'y',
|
||||
description: 'Skip confirmation prompts',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'edit',
|
||||
description: 'Open config in $EDITOR',
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,128 @@
|
||||
import { getActiveChangeIds, getSpecIds } from '../../utils/item-discovery.js';
|
||||
|
||||
/**
|
||||
* Cache entry for completion data
|
||||
*/
|
||||
interface CacheEntry<T> {
|
||||
data: T;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides dynamic completion suggestions for OpenSpec items (changes and specs).
|
||||
* Implements a 2-second cache to avoid excessive file system operations during
|
||||
* tab completion.
|
||||
*/
|
||||
export class CompletionProvider {
|
||||
private readonly cacheTTL: number;
|
||||
private changeCache: CacheEntry<string[]> | null = null;
|
||||
private specCache: CacheEntry<string[]> | null = null;
|
||||
|
||||
/**
|
||||
* Creates a new completion provider
|
||||
*
|
||||
* @param cacheTTLMs - Cache time-to-live in milliseconds (default: 2000ms)
|
||||
* @param projectRoot - Project root directory (default: process.cwd())
|
||||
*/
|
||||
constructor(
|
||||
private readonly cacheTTLMs: number = 2000,
|
||||
private readonly projectRoot: string = process.cwd()
|
||||
) {
|
||||
this.cacheTTL = cacheTTLMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active change IDs for completion
|
||||
*
|
||||
* @returns Array of change IDs
|
||||
*/
|
||||
async getChangeIds(): Promise<string[]> {
|
||||
const now = Date.now();
|
||||
|
||||
// Check if cache is valid
|
||||
if (this.changeCache && now - this.changeCache.timestamp < this.cacheTTL) {
|
||||
return this.changeCache.data;
|
||||
}
|
||||
|
||||
// Fetch fresh data
|
||||
const changeIds = await getActiveChangeIds(this.projectRoot);
|
||||
|
||||
// Update cache
|
||||
this.changeCache = {
|
||||
data: changeIds,
|
||||
timestamp: now,
|
||||
};
|
||||
|
||||
return changeIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all spec IDs for completion
|
||||
*
|
||||
* @returns Array of spec IDs
|
||||
*/
|
||||
async getSpecIds(): Promise<string[]> {
|
||||
const now = Date.now();
|
||||
|
||||
// Check if cache is valid
|
||||
if (this.specCache && now - this.specCache.timestamp < this.cacheTTL) {
|
||||
return this.specCache.data;
|
||||
}
|
||||
|
||||
// Fetch fresh data
|
||||
const specIds = await getSpecIds(this.projectRoot);
|
||||
|
||||
// Update cache
|
||||
this.specCache = {
|
||||
data: specIds,
|
||||
timestamp: now,
|
||||
};
|
||||
|
||||
return specIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get both change and spec IDs for completion
|
||||
*
|
||||
* @returns Object with changeIds and specIds arrays
|
||||
*/
|
||||
async getAllIds(): Promise<{ changeIds: string[]; specIds: string[] }> {
|
||||
const [changeIds, specIds] = await Promise.all([
|
||||
this.getChangeIds(),
|
||||
this.getSpecIds(),
|
||||
]);
|
||||
|
||||
return { changeIds, specIds };
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all cached data
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.changeCache = null;
|
||||
this.specCache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache statistics for debugging
|
||||
*
|
||||
* @returns Cache status information
|
||||
*/
|
||||
getCacheStats(): {
|
||||
changeCache: { valid: boolean; age?: number };
|
||||
specCache: { valid: boolean; age?: number };
|
||||
} {
|
||||
const now = Date.now();
|
||||
|
||||
return {
|
||||
changeCache: {
|
||||
valid: this.changeCache !== null && now - this.changeCache.timestamp < this.cacheTTL,
|
||||
age: this.changeCache ? now - this.changeCache.timestamp : undefined,
|
||||
},
|
||||
specCache: {
|
||||
valid: this.specCache !== null && now - this.specCache.timestamp < this.cacheTTL,
|
||||
age: this.specCache ? now - this.specCache.timestamp : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { CompletionGenerator } from './types.js';
|
||||
import { ZshGenerator } from './generators/zsh-generator.js';
|
||||
import { ZshInstaller, InstallationResult } from './installers/zsh-installer.js';
|
||||
import { SupportedShell } from '../../utils/shell-detection.js';
|
||||
|
||||
/**
|
||||
* Interface for completion installers
|
||||
*/
|
||||
export interface CompletionInstaller {
|
||||
install(script: string): Promise<InstallationResult>;
|
||||
uninstall(): Promise<{ success: boolean; message: string }>;
|
||||
}
|
||||
|
||||
// Re-export InstallationResult for convenience
|
||||
export type { InstallationResult };
|
||||
|
||||
/**
|
||||
* Factory for creating completion generators and installers
|
||||
* This design makes it easy to add support for additional shells
|
||||
*/
|
||||
export class CompletionFactory {
|
||||
private static readonly SUPPORTED_SHELLS: SupportedShell[] = ['zsh'];
|
||||
|
||||
/**
|
||||
* Create a completion generator for the specified shell
|
||||
*
|
||||
* @param shell - The target shell
|
||||
* @returns CompletionGenerator instance
|
||||
* @throws Error if shell is not supported
|
||||
*/
|
||||
static createGenerator(shell: SupportedShell): CompletionGenerator {
|
||||
switch (shell) {
|
||||
case 'zsh':
|
||||
return new ZshGenerator();
|
||||
default:
|
||||
throw new Error(`Unsupported shell: ${shell}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a completion installer for the specified shell
|
||||
*
|
||||
* @param shell - The target shell
|
||||
* @returns CompletionInstaller instance
|
||||
* @throws Error if shell is not supported
|
||||
*/
|
||||
static createInstaller(shell: SupportedShell): CompletionInstaller {
|
||||
switch (shell) {
|
||||
case 'zsh':
|
||||
return new ZshInstaller();
|
||||
default:
|
||||
throw new Error(`Unsupported shell: ${shell}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a shell is supported
|
||||
*
|
||||
* @param shell - The shell to check
|
||||
* @returns true if the shell is supported
|
||||
*/
|
||||
static isSupported(shell: string): shell is SupportedShell {
|
||||
return this.SUPPORTED_SHELLS.includes(shell as SupportedShell);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of all supported shells
|
||||
*
|
||||
* @returns Array of supported shell names
|
||||
*/
|
||||
static getSupportedShells(): SupportedShell[] {
|
||||
return [...this.SUPPORTED_SHELLS];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import { CompletionGenerator, CommandDefinition, FlagDefinition } from '../types.js';
|
||||
|
||||
/**
|
||||
* Generates Zsh completion scripts for the OpenSpec CLI.
|
||||
* Follows Zsh completion system conventions using the _openspec function.
|
||||
*/
|
||||
export class ZshGenerator implements CompletionGenerator {
|
||||
readonly shell = 'zsh' as const;
|
||||
|
||||
/**
|
||||
* Generate a Zsh completion script
|
||||
*
|
||||
* @param commands - Command definitions to generate completions for
|
||||
* @returns Zsh completion script as a string
|
||||
*/
|
||||
generate(commands: CommandDefinition[]): string {
|
||||
const script: string[] = [];
|
||||
|
||||
// Header comment
|
||||
script.push('#compdef openspec');
|
||||
script.push('');
|
||||
script.push('# Zsh completion script for OpenSpec CLI');
|
||||
script.push('# Auto-generated - do not edit manually');
|
||||
script.push('');
|
||||
|
||||
// Main completion function
|
||||
script.push('_openspec() {');
|
||||
script.push(' local context state line');
|
||||
script.push(' typeset -A opt_args');
|
||||
script.push('');
|
||||
|
||||
// Generate main command argument specification
|
||||
script.push(' local -a commands');
|
||||
script.push(' commands=(');
|
||||
for (const cmd of commands) {
|
||||
const escapedDesc = this.escapeDescription(cmd.description);
|
||||
script.push(` '${cmd.name}:${escapedDesc}'`);
|
||||
}
|
||||
script.push(' )');
|
||||
script.push('');
|
||||
|
||||
// Main _arguments call
|
||||
script.push(' _arguments -C \\');
|
||||
script.push(' "1: :->command" \\');
|
||||
script.push(' "*::arg:->args"');
|
||||
script.push('');
|
||||
|
||||
// Command dispatch logic
|
||||
script.push(' case $state in');
|
||||
script.push(' command)');
|
||||
script.push(' _describe "openspec command" commands');
|
||||
script.push(' ;;');
|
||||
script.push(' args)');
|
||||
script.push(' case $words[1] in');
|
||||
|
||||
// Generate completion for each command
|
||||
for (const cmd of commands) {
|
||||
script.push(` ${cmd.name})`);
|
||||
script.push(` _openspec_${this.sanitizeFunctionName(cmd.name)}`);
|
||||
script.push(' ;;');
|
||||
}
|
||||
|
||||
script.push(' esac');
|
||||
script.push(' ;;');
|
||||
script.push(' esac');
|
||||
script.push('}');
|
||||
script.push('');
|
||||
|
||||
// Generate individual command completion functions
|
||||
for (const cmd of commands) {
|
||||
script.push(...this.generateCommandFunction(cmd));
|
||||
script.push('');
|
||||
}
|
||||
|
||||
// Add dynamic completion helper functions
|
||||
script.push(...this.generateDynamicCompletionHelpers());
|
||||
|
||||
// Register the completion function
|
||||
script.push('compdef _openspec openspec');
|
||||
script.push('');
|
||||
|
||||
return script.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a single completion function
|
||||
*
|
||||
* @param functionName - Name of the completion function
|
||||
* @param varName - Name of the local array variable
|
||||
* @param varLabel - Label for the completion items
|
||||
* @param commandLines - Command line(s) to populate the array
|
||||
* @param comment - Optional comment describing the function
|
||||
*/
|
||||
private generateCompletionFunction(
|
||||
functionName: string,
|
||||
varName: string,
|
||||
varLabel: string,
|
||||
commandLines: string[],
|
||||
comment?: string
|
||||
): string[] {
|
||||
const lines: string[] = [];
|
||||
|
||||
if (comment) {
|
||||
lines.push(comment);
|
||||
}
|
||||
|
||||
lines.push(`${functionName}() {`);
|
||||
lines.push(` local -a ${varName}`);
|
||||
|
||||
if (commandLines.length === 1) {
|
||||
lines.push(` ${commandLines[0]}`);
|
||||
} else {
|
||||
lines.push(` ${varName}=(`);
|
||||
for (let i = 0; i < commandLines.length; i++) {
|
||||
const suffix = i < commandLines.length - 1 ? ' \\' : '';
|
||||
lines.push(` ${commandLines[i]}${suffix}`);
|
||||
}
|
||||
lines.push(' )');
|
||||
}
|
||||
|
||||
lines.push(` _describe "${varLabel}" ${varName}`);
|
||||
lines.push('}');
|
||||
lines.push('');
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate dynamic completion helper functions for change and spec IDs
|
||||
*/
|
||||
private generateDynamicCompletionHelpers(): string[] {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Dynamic completion helpers');
|
||||
lines.push('');
|
||||
|
||||
// Helper function for completing change IDs
|
||||
lines.push('# Use openspec __complete to get available changes');
|
||||
lines.push('_openspec_complete_changes() {');
|
||||
lines.push(' local -a changes');
|
||||
lines.push(' while IFS=$\'\\t\' read -r id desc; do');
|
||||
lines.push(' changes+=("$id:$desc")');
|
||||
lines.push(' done < <(openspec __complete changes 2>/dev/null)');
|
||||
lines.push(' _describe "change" changes');
|
||||
lines.push('}');
|
||||
lines.push('');
|
||||
|
||||
// Helper function for completing spec IDs
|
||||
lines.push('# Use openspec __complete to get available specs');
|
||||
lines.push('_openspec_complete_specs() {');
|
||||
lines.push(' local -a specs');
|
||||
lines.push(' while IFS=$\'\\t\' read -r id desc; do');
|
||||
lines.push(' specs+=("$id:$desc")');
|
||||
lines.push(' done < <(openspec __complete specs 2>/dev/null)');
|
||||
lines.push(' _describe "spec" specs');
|
||||
lines.push('}');
|
||||
lines.push('');
|
||||
|
||||
// Helper function for completing both changes and specs
|
||||
lines.push('# Get both changes and specs');
|
||||
lines.push('_openspec_complete_items() {');
|
||||
lines.push(' local -a items');
|
||||
lines.push(' while IFS=$\'\\t\' read -r id desc; do');
|
||||
lines.push(' items+=("$id:$desc")');
|
||||
lines.push(' done < <(openspec __complete changes 2>/dev/null)');
|
||||
lines.push(' while IFS=$\'\\t\' read -r id desc; do');
|
||||
lines.push(' items+=("$id:$desc")');
|
||||
lines.push(' done < <(openspec __complete specs 2>/dev/null)');
|
||||
lines.push(' _describe "item" items');
|
||||
lines.push('}');
|
||||
lines.push('');
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate completion function for a specific command
|
||||
*/
|
||||
private generateCommandFunction(cmd: CommandDefinition): string[] {
|
||||
const funcName = `_openspec_${this.sanitizeFunctionName(cmd.name)}`;
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`${funcName}() {`);
|
||||
|
||||
// If command has subcommands, handle them
|
||||
if (cmd.subcommands && cmd.subcommands.length > 0) {
|
||||
lines.push(' local context state line');
|
||||
lines.push(' typeset -A opt_args');
|
||||
lines.push('');
|
||||
lines.push(' local -a subcommands');
|
||||
lines.push(' subcommands=(');
|
||||
|
||||
for (const subcmd of cmd.subcommands) {
|
||||
const escapedDesc = this.escapeDescription(subcmd.description);
|
||||
lines.push(` '${subcmd.name}:${escapedDesc}'`);
|
||||
}
|
||||
|
||||
lines.push(' )');
|
||||
lines.push('');
|
||||
lines.push(' _arguments -C \\');
|
||||
|
||||
// Add command flags
|
||||
for (const flag of cmd.flags) {
|
||||
lines.push(' ' + this.generateFlagSpec(flag) + ' \\');
|
||||
}
|
||||
|
||||
lines.push(' "1: :->subcommand" \\');
|
||||
lines.push(' "*::arg:->args"');
|
||||
lines.push('');
|
||||
lines.push(' case $state in');
|
||||
lines.push(' subcommand)');
|
||||
lines.push(' _describe "subcommand" subcommands');
|
||||
lines.push(' ;;');
|
||||
lines.push(' args)');
|
||||
lines.push(' case $words[1] in');
|
||||
|
||||
for (const subcmd of cmd.subcommands) {
|
||||
lines.push(` ${subcmd.name})`);
|
||||
lines.push(` _openspec_${this.sanitizeFunctionName(cmd.name)}_${this.sanitizeFunctionName(subcmd.name)}`);
|
||||
lines.push(' ;;');
|
||||
}
|
||||
|
||||
lines.push(' esac');
|
||||
lines.push(' ;;');
|
||||
lines.push(' esac');
|
||||
} else {
|
||||
// Command without subcommands
|
||||
lines.push(' _arguments \\');
|
||||
|
||||
// Add flags
|
||||
for (const flag of cmd.flags) {
|
||||
lines.push(' ' + this.generateFlagSpec(flag) + ' \\');
|
||||
}
|
||||
|
||||
// Add positional argument completion
|
||||
if (cmd.acceptsPositional) {
|
||||
const positionalSpec = this.generatePositionalSpec(cmd.positionalType);
|
||||
lines.push(' ' + positionalSpec);
|
||||
} else {
|
||||
// Remove trailing backslash from last flag
|
||||
if (lines[lines.length - 1].endsWith(' \\')) {
|
||||
lines[lines.length - 1] = lines[lines.length - 1].slice(0, -2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('}');
|
||||
|
||||
// Generate subcommand functions if they exist
|
||||
if (cmd.subcommands) {
|
||||
for (const subcmd of cmd.subcommands) {
|
||||
lines.push('');
|
||||
lines.push(...this.generateSubcommandFunction(cmd.name, subcmd));
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate completion function for a subcommand
|
||||
*/
|
||||
private generateSubcommandFunction(parentName: string, subcmd: CommandDefinition): string[] {
|
||||
const funcName = `_openspec_${this.sanitizeFunctionName(parentName)}_${this.sanitizeFunctionName(subcmd.name)}`;
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`${funcName}() {`);
|
||||
lines.push(' _arguments \\');
|
||||
|
||||
// Add flags
|
||||
for (const flag of subcmd.flags) {
|
||||
lines.push(' ' + this.generateFlagSpec(flag) + ' \\');
|
||||
}
|
||||
|
||||
// Add positional argument completion
|
||||
if (subcmd.acceptsPositional) {
|
||||
const positionalSpec = this.generatePositionalSpec(subcmd.positionalType);
|
||||
lines.push(' ' + positionalSpec);
|
||||
} else {
|
||||
// Remove trailing backslash from last flag
|
||||
if (lines[lines.length - 1].endsWith(' \\')) {
|
||||
lines[lines.length - 1] = lines[lines.length - 1].slice(0, -2);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('}');
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate flag specification for _arguments
|
||||
*/
|
||||
private generateFlagSpec(flag: FlagDefinition): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
// Handle mutually exclusive short and long forms
|
||||
if (flag.short) {
|
||||
parts.push(`'(-${flag.short} --${flag.name})'{-${flag.short},--${flag.name}}'`);
|
||||
} else {
|
||||
parts.push(`'--${flag.name}`);
|
||||
}
|
||||
|
||||
// Add description
|
||||
const escapedDesc = this.escapeDescription(flag.description);
|
||||
parts.push(`[${escapedDesc}]`);
|
||||
|
||||
// Add value completion if flag takes a value
|
||||
if (flag.takesValue) {
|
||||
if (flag.values && flag.values.length > 0) {
|
||||
// Provide specific value completions
|
||||
const valueList = flag.values.map(v => this.escapeValue(v)).join(' ');
|
||||
parts.push(`:value:(${valueList})`);
|
||||
} else {
|
||||
// Generic value placeholder
|
||||
parts.push(':value:');
|
||||
}
|
||||
}
|
||||
|
||||
// Close the quote (needed for both short and long forms)
|
||||
parts.push("'");
|
||||
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate positional argument specification
|
||||
*/
|
||||
private generatePositionalSpec(positionalType?: string): string {
|
||||
switch (positionalType) {
|
||||
case 'change-id':
|
||||
return "'*: :_openspec_complete_changes'";
|
||||
case 'spec-id':
|
||||
return "'*: :_openspec_complete_specs'";
|
||||
case 'change-or-spec-id':
|
||||
return "'*: :_openspec_complete_items'";
|
||||
case 'path':
|
||||
return "'*:path:_files'";
|
||||
case 'shell':
|
||||
return "'*:shell:(zsh)'";
|
||||
default:
|
||||
return "'*: :_default'";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in descriptions
|
||||
*/
|
||||
private escapeDescription(desc: string): string {
|
||||
return desc
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/\[/g, '\\[')
|
||||
.replace(/]/g, '\\]')
|
||||
.replace(/:/g, '\\:');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in values
|
||||
*/
|
||||
private escapeValue(value: string): string {
|
||||
return value
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/ /g, '\\ ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize command names for use in function names
|
||||
*/
|
||||
private sanitizeFunctionName(name: string): string {
|
||||
return name.replace(/-/g, '_');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { FileSystemUtils } from '../../../utils/file-system.js';
|
||||
|
||||
/**
|
||||
* Installation result information
|
||||
*/
|
||||
export interface InstallationResult {
|
||||
success: boolean;
|
||||
installedPath?: string;
|
||||
backupPath?: string;
|
||||
isOhMyZsh: boolean;
|
||||
zshrcConfigured?: boolean;
|
||||
message: string;
|
||||
instructions?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Installer for Zsh completion scripts.
|
||||
* Supports both Oh My Zsh and standard Zsh configurations.
|
||||
*/
|
||||
export class ZshInstaller {
|
||||
private readonly homeDir: string;
|
||||
|
||||
/**
|
||||
* Markers for .zshrc configuration management
|
||||
*/
|
||||
private readonly ZSHRC_MARKERS = {
|
||||
start: '# OPENSPEC:START',
|
||||
end: '# OPENSPEC:END',
|
||||
};
|
||||
|
||||
constructor(homeDir: string = os.homedir()) {
|
||||
this.homeDir = homeDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Oh My Zsh is installed
|
||||
*
|
||||
* @returns true if Oh My Zsh is detected via $ZSH env var or directory exists
|
||||
*/
|
||||
async isOhMyZshInstalled(): Promise<boolean> {
|
||||
// First check for $ZSH environment variable (standard OMZ setup)
|
||||
if (process.env.ZSH) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Fall back to checking for ~/.oh-my-zsh directory
|
||||
const ohMyZshPath = path.join(this.homeDir, '.oh-my-zsh');
|
||||
|
||||
try {
|
||||
const stat = await fs.stat(ohMyZshPath);
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the appropriate installation path for the completion script
|
||||
*
|
||||
* @returns Object with installation path and whether it's Oh My Zsh
|
||||
*/
|
||||
async getInstallationPath(): Promise<{ path: string; isOhMyZsh: boolean }> {
|
||||
const isOhMyZsh = await this.isOhMyZshInstalled();
|
||||
|
||||
if (isOhMyZsh) {
|
||||
// Oh My Zsh custom completions directory
|
||||
return {
|
||||
path: path.join(this.homeDir, '.oh-my-zsh', 'custom', 'completions', '_openspec'),
|
||||
isOhMyZsh: true,
|
||||
};
|
||||
} else {
|
||||
// Standard Zsh completions directory
|
||||
return {
|
||||
path: path.join(this.homeDir, '.zsh', 'completions', '_openspec'),
|
||||
isOhMyZsh: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Backup an existing completion file if it exists
|
||||
*
|
||||
* @param targetPath - Path to the file to backup
|
||||
* @returns Path to the backup file, or undefined if no backup was needed
|
||||
*/
|
||||
async backupExistingFile(targetPath: string): Promise<string | undefined> {
|
||||
try {
|
||||
await fs.access(targetPath);
|
||||
// File exists, create a backup
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const backupPath = `${targetPath}.backup-${timestamp}`;
|
||||
await fs.copyFile(targetPath, backupPath);
|
||||
return backupPath;
|
||||
} catch {
|
||||
// File doesn't exist, no backup needed
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to .zshrc file
|
||||
*
|
||||
* @returns Path to .zshrc
|
||||
*/
|
||||
private getZshrcPath(): string {
|
||||
return path.join(this.homeDir, '.zshrc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate .zshrc configuration content
|
||||
*
|
||||
* @param completionsDir - Directory containing completion scripts
|
||||
* @returns Configuration content
|
||||
*/
|
||||
private generateZshrcConfig(completionsDir: string): string {
|
||||
return [
|
||||
'# OpenSpec shell completions configuration',
|
||||
`fpath=("${completionsDir}" $fpath)`,
|
||||
'autoload -Uz compinit',
|
||||
'compinit',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure .zshrc to enable completions
|
||||
* Only applies to standard Zsh (not Oh My Zsh)
|
||||
*
|
||||
* @param completionsDir - Directory containing completion scripts
|
||||
* @returns true if configured successfully, false otherwise
|
||||
*/
|
||||
async configureZshrc(completionsDir: string): Promise<boolean> {
|
||||
// Check if auto-configuration is disabled
|
||||
if (process.env.OPENSPEC_NO_AUTO_CONFIG === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const zshrcPath = this.getZshrcPath();
|
||||
const config = this.generateZshrcConfig(completionsDir);
|
||||
|
||||
// Check write permissions
|
||||
const canWrite = await FileSystemUtils.canWriteFile(zshrcPath);
|
||||
if (!canWrite) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Use marker-based update
|
||||
await FileSystemUtils.updateFileWithMarkers(
|
||||
zshrcPath,
|
||||
config,
|
||||
this.ZSHRC_MARKERS.start,
|
||||
this.ZSHRC_MARKERS.end
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
// Fail gracefully - don't break installation
|
||||
console.debug(`Unable to configure .zshrc for completions: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if .zshrc has OpenSpec configuration markers
|
||||
*
|
||||
* @returns true if .zshrc exists and has markers
|
||||
*/
|
||||
private async hasZshrcConfig(): Promise<boolean> {
|
||||
try {
|
||||
const zshrcPath = this.getZshrcPath();
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
return content.includes(this.ZSHRC_MARKERS.start) && content.includes(this.ZSHRC_MARKERS.end);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if fpath configuration is needed for a given directory
|
||||
* Used to verify if Oh My Zsh (or other) completions directory is already in fpath
|
||||
*
|
||||
* @param completionsDir - Directory to check for in fpath
|
||||
* @returns true if configuration is needed, false if directory is already referenced
|
||||
*/
|
||||
private async needsFpathConfig(completionsDir: string): Promise<boolean> {
|
||||
try {
|
||||
const zshrcPath = this.getZshrcPath();
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
// Check if fpath already includes this directory
|
||||
return !content.includes(completionsDir);
|
||||
} catch (error) {
|
||||
// If we can't read .zshrc, assume config is needed
|
||||
console.debug(`Unable to read .zshrc to check fpath config: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove .zshrc configuration
|
||||
* Used during uninstallation
|
||||
*
|
||||
* @returns true if removed successfully, false otherwise
|
||||
*/
|
||||
async removeZshrcConfig(): Promise<boolean> {
|
||||
try {
|
||||
const zshrcPath = this.getZshrcPath();
|
||||
|
||||
// Check if file exists
|
||||
try {
|
||||
await fs.access(zshrcPath);
|
||||
} catch {
|
||||
// File doesn't exist, nothing to remove
|
||||
return true;
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
// Check if markers exist
|
||||
if (!content.includes(this.ZSHRC_MARKERS.start) || !content.includes(this.ZSHRC_MARKERS.end)) {
|
||||
// Markers don't exist, nothing to remove
|
||||
return true;
|
||||
}
|
||||
|
||||
// Remove content between markers (including markers)
|
||||
const lines = content.split('\n');
|
||||
const startIndex = lines.findIndex((line) => line.trim() === this.ZSHRC_MARKERS.start);
|
||||
const endIndex = lines.findIndex((line) => line.trim() === this.ZSHRC_MARKERS.end);
|
||||
|
||||
if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {
|
||||
// Invalid marker placement
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove lines between markers (inclusive)
|
||||
lines.splice(startIndex, endIndex - startIndex + 1);
|
||||
|
||||
// Remove trailing empty lines at the start if the markers were at the top
|
||||
while (lines.length > 0 && lines[0].trim() === '') {
|
||||
lines.shift();
|
||||
}
|
||||
|
||||
// Write back
|
||||
await fs.writeFile(zshrcPath, lines.join('\n'), 'utf-8');
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
// Fail gracefully
|
||||
console.debug(`Unable to remove .zshrc configuration: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the completion script
|
||||
*
|
||||
* @param completionScript - The completion script content to install
|
||||
* @returns Installation result with status and instructions
|
||||
*/
|
||||
async install(completionScript: string): Promise<InstallationResult> {
|
||||
try {
|
||||
const { path: targetPath, isOhMyZsh } = await this.getInstallationPath();
|
||||
|
||||
// Check if already installed with same content
|
||||
let isUpdate = false;
|
||||
try {
|
||||
const existingContent = await fs.readFile(targetPath, 'utf-8');
|
||||
if (existingContent === completionScript) {
|
||||
// Already installed and up to date
|
||||
return {
|
||||
success: true,
|
||||
installedPath: targetPath,
|
||||
isOhMyZsh,
|
||||
message: 'Completion script is already installed (up to date)',
|
||||
instructions: [
|
||||
'The completion script is already installed and up to date.',
|
||||
'If completions are not working, try: exec zsh',
|
||||
],
|
||||
};
|
||||
}
|
||||
// File exists but content is different - this is an update
|
||||
isUpdate = true;
|
||||
} catch (error: any) {
|
||||
// File doesn't exist or can't be read, proceed with installation
|
||||
console.debug(`Unable to read existing completion file at ${targetPath}: ${error.message}`);
|
||||
}
|
||||
|
||||
// Ensure the directory exists
|
||||
const targetDir = path.dirname(targetPath);
|
||||
await fs.mkdir(targetDir, { recursive: true });
|
||||
|
||||
// Backup existing file if updating
|
||||
const backupPath = isUpdate ? await this.backupExistingFile(targetPath) : undefined;
|
||||
|
||||
// Write the completion script
|
||||
await fs.writeFile(targetPath, completionScript, 'utf-8');
|
||||
|
||||
// Auto-configure .zshrc
|
||||
let zshrcConfigured = false;
|
||||
if (isOhMyZsh) {
|
||||
// For Oh My Zsh, verify that custom/completions is in fpath
|
||||
// If not, add it to .zshrc
|
||||
const needsConfig = await this.needsFpathConfig(targetDir);
|
||||
if (needsConfig) {
|
||||
zshrcConfigured = await this.configureZshrc(targetDir);
|
||||
}
|
||||
} else {
|
||||
// Standard Zsh always needs .zshrc configuration
|
||||
zshrcConfigured = await this.configureZshrc(targetDir);
|
||||
}
|
||||
|
||||
// Generate instructions (only if .zshrc wasn't auto-configured)
|
||||
let instructions = zshrcConfigured ? undefined : this.generateInstructions(isOhMyZsh, targetPath);
|
||||
|
||||
// Add fpath guidance for Oh My Zsh installations
|
||||
if (isOhMyZsh) {
|
||||
const fpathGuidance = this.generateOhMyZshFpathGuidance(targetDir);
|
||||
if (fpathGuidance) {
|
||||
instructions = instructions ? [...instructions, '', ...fpathGuidance] : fpathGuidance;
|
||||
}
|
||||
}
|
||||
|
||||
// Determine appropriate message based on update status
|
||||
let message: string;
|
||||
if (isUpdate) {
|
||||
message = backupPath
|
||||
? 'Completion script updated successfully (previous version backed up)'
|
||||
: 'Completion script updated successfully';
|
||||
} else {
|
||||
message = isOhMyZsh
|
||||
? 'Completion script installed successfully for Oh My Zsh'
|
||||
: zshrcConfigured
|
||||
? 'Completion script installed and .zshrc configured successfully'
|
||||
: 'Completion script installed successfully for Zsh';
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
installedPath: targetPath,
|
||||
backupPath,
|
||||
isOhMyZsh,
|
||||
zshrcConfigured,
|
||||
message,
|
||||
instructions,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
isOhMyZsh: false,
|
||||
message: `Failed to install completion script: ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Oh My Zsh fpath verification guidance
|
||||
*
|
||||
* @param completionsDir - Custom completions directory path
|
||||
* @returns Array of guidance strings, or undefined if not needed
|
||||
*/
|
||||
private generateOhMyZshFpathGuidance(completionsDir: string): string[] | undefined {
|
||||
return [
|
||||
'Note: Oh My Zsh typically auto-loads completions from custom/completions.',
|
||||
`Verify that ${completionsDir} is in your fpath by running:`,
|
||||
' echo $fpath | grep "custom/completions"',
|
||||
'',
|
||||
'If not found, completions may not work. Restart your shell to ensure changes take effect.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate user instructions for enabling completions
|
||||
*
|
||||
* @param isOhMyZsh - Whether Oh My Zsh is being used
|
||||
* @param installedPath - Path where the script was installed
|
||||
* @returns Array of instruction strings
|
||||
*/
|
||||
private generateInstructions(isOhMyZsh: boolean, installedPath: string): string[] {
|
||||
if (isOhMyZsh) {
|
||||
return [
|
||||
'Completion script installed to Oh My Zsh completions directory.',
|
||||
'Restart your shell or run: exec zsh',
|
||||
'Completions should activate automatically.',
|
||||
];
|
||||
} else {
|
||||
const completionsDir = path.dirname(installedPath);
|
||||
const zshrcPath = path.join(this.homeDir, '.zshrc');
|
||||
|
||||
return [
|
||||
'Completion script installed to ~/.zsh/completions/',
|
||||
'',
|
||||
'To enable completions, add the following to your ~/.zshrc file:',
|
||||
'',
|
||||
` # Add completions directory to fpath`,
|
||||
` fpath=(${completionsDir} $fpath)`,
|
||||
'',
|
||||
' # Initialize completion system',
|
||||
' autoload -Uz compinit',
|
||||
' compinit',
|
||||
'',
|
||||
'Then restart your shell or run: exec zsh',
|
||||
'',
|
||||
`Check if these lines already exist in ${zshrcPath} before adding.`,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall the completion script
|
||||
*
|
||||
* @returns true if uninstalled successfully, false otherwise
|
||||
*/
|
||||
async uninstall(): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
const { path: targetPath, isOhMyZsh } = await this.getInstallationPath();
|
||||
|
||||
// Try to remove completion script
|
||||
let scriptRemoved = false;
|
||||
try {
|
||||
await fs.access(targetPath);
|
||||
await fs.unlink(targetPath);
|
||||
scriptRemoved = true;
|
||||
} catch {
|
||||
// Script not installed
|
||||
}
|
||||
|
||||
// Try to remove .zshrc configuration (only for standard Zsh)
|
||||
let zshrcWasPresent = false;
|
||||
let zshrcCleaned = false;
|
||||
if (!isOhMyZsh) {
|
||||
zshrcWasPresent = await this.hasZshrcConfig();
|
||||
if (zshrcWasPresent) {
|
||||
zshrcCleaned = await this.removeZshrcConfig();
|
||||
}
|
||||
}
|
||||
|
||||
if (!scriptRemoved && !zshrcWasPresent) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Completion script is not installed',
|
||||
};
|
||||
}
|
||||
|
||||
const messages: string[] = [];
|
||||
if (scriptRemoved) {
|
||||
messages.push(`Completion script removed from ${targetPath}`);
|
||||
}
|
||||
if (zshrcCleaned && !isOhMyZsh) {
|
||||
messages.push('Removed OpenSpec configuration from ~/.zshrc');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: messages.join('. '),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to uninstall completion script: ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if completion script is currently installed
|
||||
*
|
||||
* @returns true if the completion script exists
|
||||
*/
|
||||
async isInstalled(): Promise<boolean> {
|
||||
try {
|
||||
const { path: targetPath } = await this.getInstallationPath();
|
||||
await fs.access(targetPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get information about the current installation
|
||||
*
|
||||
* @returns Installation status information
|
||||
*/
|
||||
async getInstallationInfo(): Promise<{
|
||||
installed: boolean;
|
||||
path?: string;
|
||||
isOhMyZsh?: boolean;
|
||||
}> {
|
||||
const installed = await this.isInstalled();
|
||||
|
||||
if (!installed) {
|
||||
return { installed: false };
|
||||
}
|
||||
|
||||
const { path: targetPath, isOhMyZsh } = await this.getInstallationPath();
|
||||
|
||||
return {
|
||||
installed: true,
|
||||
path: targetPath,
|
||||
isOhMyZsh,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { SupportedShell } from '../../utils/shell-detection.js';
|
||||
|
||||
/**
|
||||
* Definition of a command-line flag/option
|
||||
*/
|
||||
export interface FlagDefinition {
|
||||
/**
|
||||
* Flag name without dashes (e.g., "json", "strict", "no-interactive")
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* Short flag name without dash (e.g., "y" for "-y")
|
||||
*/
|
||||
short?: string;
|
||||
|
||||
/**
|
||||
* Human-readable description of what the flag does
|
||||
*/
|
||||
description: string;
|
||||
|
||||
/**
|
||||
* Whether the flag takes an argument value
|
||||
*/
|
||||
takesValue?: boolean;
|
||||
|
||||
/**
|
||||
* Possible values for the flag (for completion suggestions)
|
||||
*/
|
||||
values?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Definition of a CLI command
|
||||
*/
|
||||
export interface CommandDefinition {
|
||||
/**
|
||||
* Command name (e.g., "init", "validate", "show")
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* Human-readable description of the command
|
||||
*/
|
||||
description: string;
|
||||
|
||||
/**
|
||||
* Flags/options supported by this command
|
||||
*/
|
||||
flags: FlagDefinition[];
|
||||
|
||||
/**
|
||||
* Subcommands (e.g., "change show", "spec validate")
|
||||
*/
|
||||
subcommands?: CommandDefinition[];
|
||||
|
||||
/**
|
||||
* Whether this command accepts a positional argument (e.g., item name, path)
|
||||
*/
|
||||
acceptsPositional?: boolean;
|
||||
|
||||
/**
|
||||
* Type of positional argument for dynamic completion
|
||||
* - 'change-id': Complete with active change IDs
|
||||
* - 'spec-id': Complete with spec IDs
|
||||
* - 'change-or-spec-id': Complete with both changes and specs
|
||||
* - 'path': Complete with file paths
|
||||
* - 'shell': Complete with supported shell names
|
||||
* - undefined: No specific completion
|
||||
*/
|
||||
positionalType?: 'change-id' | 'spec-id' | 'change-or-spec-id' | 'path' | 'shell';
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for shell-specific completion script generators
|
||||
*/
|
||||
export interface CompletionGenerator {
|
||||
/**
|
||||
* The shell type this generator targets
|
||||
*/
|
||||
readonly shell: SupportedShell;
|
||||
|
||||
/**
|
||||
* Generate the completion script content
|
||||
*
|
||||
* @param commands - Command definitions to generate completions for
|
||||
* @returns The shell-specific completion script as a string
|
||||
*/
|
||||
generate(commands: CommandDefinition[]): string;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Zod schema for global OpenSpec configuration.
|
||||
* Uses passthrough() to preserve unknown fields for forward compatibility.
|
||||
*/
|
||||
export const GlobalConfigSchema = z
|
||||
.object({
|
||||
featureFlags: z
|
||||
.record(z.string(), z.boolean())
|
||||
.optional()
|
||||
.default({}),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type GlobalConfigType = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
/**
|
||||
* Default configuration values.
|
||||
*/
|
||||
export const DEFAULT_CONFIG: GlobalConfigType = {
|
||||
featureFlags: {},
|
||||
};
|
||||
|
||||
const KNOWN_TOP_LEVEL_KEYS = new Set(Object.keys(DEFAULT_CONFIG));
|
||||
|
||||
/**
|
||||
* Validate a config key path for CLI set operations.
|
||||
* Unknown top-level keys are rejected unless explicitly allowed by the caller.
|
||||
*/
|
||||
export function validateConfigKeyPath(path: string): { valid: boolean; reason?: string } {
|
||||
const rawKeys = path.split('.');
|
||||
|
||||
if (rawKeys.length === 0 || rawKeys.some((key) => key.trim() === '')) {
|
||||
return { valid: false, reason: 'Key path must not be empty' };
|
||||
}
|
||||
|
||||
const rootKey = rawKeys[0];
|
||||
if (!KNOWN_TOP_LEVEL_KEYS.has(rootKey)) {
|
||||
return { valid: false, reason: `Unknown top-level key "${rootKey}"` };
|
||||
}
|
||||
|
||||
if (rootKey === 'featureFlags') {
|
||||
if (rawKeys.length > 2) {
|
||||
return { valid: false, reason: 'featureFlags values are booleans and do not support nested keys' };
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
if (rawKeys.length > 1) {
|
||||
return { valid: false, reason: `"${rootKey}" does not support nested keys` };
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a nested value from an object using dot notation.
|
||||
*
|
||||
* @param obj - The object to access
|
||||
* @param path - Dot-separated path (e.g., "featureFlags.someFlag")
|
||||
* @returns The value at the path, or undefined if not found
|
||||
*/
|
||||
export function getNestedValue(obj: Record<string, unknown>, path: string): unknown {
|
||||
const keys = path.split('.');
|
||||
let current: unknown = obj;
|
||||
|
||||
for (const key of keys) {
|
||||
if (current === null || current === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof current !== 'object') {
|
||||
return undefined;
|
||||
}
|
||||
current = (current as Record<string, unknown>)[key];
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a nested value in an object using dot notation.
|
||||
* Creates intermediate objects as needed.
|
||||
*
|
||||
* @param obj - The object to modify (mutated in place)
|
||||
* @param path - Dot-separated path (e.g., "featureFlags.someFlag")
|
||||
* @param value - The value to set
|
||||
*/
|
||||
export function setNestedValue(obj: Record<string, unknown>, path: string, value: unknown): void {
|
||||
const keys = path.split('.');
|
||||
let current: Record<string, unknown> = obj;
|
||||
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (current[key] === undefined || current[key] === null || typeof current[key] !== 'object') {
|
||||
current[key] = {};
|
||||
}
|
||||
current = current[key] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const lastKey = keys[keys.length - 1];
|
||||
current[lastKey] = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a nested value from an object using dot notation.
|
||||
*
|
||||
* @param obj - The object to modify (mutated in place)
|
||||
* @param path - Dot-separated path (e.g., "featureFlags.someFlag")
|
||||
* @returns true if the key existed and was deleted, false otherwise
|
||||
*/
|
||||
export function deleteNestedValue(obj: Record<string, unknown>, path: string): boolean {
|
||||
const keys = path.split('.');
|
||||
let current: Record<string, unknown> = obj;
|
||||
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (current[key] === undefined || current[key] === null || typeof current[key] !== 'object') {
|
||||
return false;
|
||||
}
|
||||
current = current[key] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const lastKey = keys[keys.length - 1];
|
||||
if (lastKey in current) {
|
||||
delete current[lastKey];
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a string value to its appropriate type.
|
||||
* - "true" / "false" -> boolean
|
||||
* - Numeric strings -> number
|
||||
* - Everything else -> string
|
||||
*
|
||||
* @param value - The string value to coerce
|
||||
* @param forceString - If true, always return the value as a string
|
||||
* @returns The coerced value
|
||||
*/
|
||||
export function coerceValue(value: string, forceString: boolean = false): string | number | boolean {
|
||||
if (forceString) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// Boolean coercion
|
||||
if (value === 'true') {
|
||||
return true;
|
||||
}
|
||||
if (value === 'false') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Number coercion - must be a valid finite number
|
||||
const num = Number(value);
|
||||
if (!isNaN(num) && isFinite(num) && value.trim() !== '') {
|
||||
return num;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a value for YAML-like display.
|
||||
*
|
||||
* @param value - The value to format
|
||||
* @param indent - Current indentation level
|
||||
* @returns Formatted string
|
||||
*/
|
||||
export function formatValueYaml(value: unknown, indent: number = 0): string {
|
||||
const indentStr = ' '.repeat(indent);
|
||||
|
||||
if (value === null || value === undefined) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (typeof value === 'boolean' || typeof value === 'number') {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length === 0) {
|
||||
return '[]';
|
||||
}
|
||||
return value.map((item) => `${indentStr}- ${formatValueYaml(item, indent + 1)}`).join('\n');
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
const entries = Object.entries(value as Record<string, unknown>);
|
||||
if (entries.length === 0) {
|
||||
return '{}';
|
||||
}
|
||||
return entries
|
||||
.map(([key, val]) => {
|
||||
const formattedVal = formatValueYaml(val, indent + 1);
|
||||
if (typeof val === 'object' && val !== null && Object.keys(val).length > 0) {
|
||||
return `${indentStr}${key}:\n${formattedVal}`;
|
||||
}
|
||||
return `${indentStr}${key}: ${formattedVal}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a configuration object against the schema.
|
||||
*
|
||||
* @param config - The configuration to validate
|
||||
* @returns Validation result with success status and optional error message
|
||||
*/
|
||||
export function validateConfig(config: unknown): { success: boolean; error?: string } {
|
||||
try {
|
||||
GlobalConfigSchema.parse(config);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
const zodError = error as z.ZodError;
|
||||
const messages = zodError.issues.map((e) => `${e.path.join('.')}: ${e.message}`);
|
||||
return { success: false, error: messages.join('; ') };
|
||||
}
|
||||
return { success: false, error: 'Unknown validation error' };
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -17,25 +17,25 @@ export interface AIToolOption {
|
||||
}
|
||||
|
||||
export const AI_TOOLS: AIToolOption[] = [
|
||||
{ name: 'Amazon Q Developer', value: 'amazon-q', available: true, successLabel: 'Amazon Q Developer' },
|
||||
{ name: 'Antigravity', value: 'antigravity', available: true, successLabel: 'Antigravity' },
|
||||
{ name: 'Auggie (Augment CLI)', value: 'auggie', available: true, successLabel: 'Auggie' },
|
||||
{ name: 'Claude Code', value: 'claude', available: true, successLabel: 'Claude Code' },
|
||||
{ name: 'Cline', value: 'cline', available: true, successLabel: 'Cline' },
|
||||
{ name: 'RooCode', value: 'roocode', available: true, successLabel: 'RooCode' },
|
||||
{ name: 'Codex', value: 'codex', available: true, successLabel: 'Codex' },
|
||||
{ name: 'CodeBuddy Code (CLI)', value: 'codebuddy', available: true, successLabel: 'CodeBuddy Code' },
|
||||
{ name: 'CoStrict', value: 'costrict', available: true, successLabel: 'CoStrict' },
|
||||
{ name: 'Crush', value: 'crush', available: true, successLabel: 'Crush' },
|
||||
{ name: 'Cursor', value: 'cursor', available: true, successLabel: 'Cursor' },
|
||||
{ name: 'Factory Droid', value: 'factory', available: true, successLabel: 'Factory Droid' },
|
||||
{ name: 'Gemini CLI', value: 'gemini', available: true, successLabel: 'Gemini CLI' },
|
||||
{ name: 'iFlow', value: 'iflow', available: true, successLabel: 'iFlow' },
|
||||
{ name: 'OpenCode', value: 'opencode', available: true, successLabel: 'OpenCode' },
|
||||
{ name: 'Kilo Code', value: 'kilocode', available: true, successLabel: 'Kilo Code' },
|
||||
{ name: 'Qoder (CLI)', value: 'qoder', available: true, successLabel: 'Qoder' },
|
||||
{ name: 'Antigravity', value: 'antigravity', available: true, successLabel: 'Antigravity' },
|
||||
{ name: 'Windsurf', value: 'windsurf', available: true, successLabel: 'Windsurf' },
|
||||
{ name: 'Codex', value: 'codex', available: true, successLabel: 'Codex' },
|
||||
{ name: 'GitHub Copilot', value: 'github-copilot', available: true, successLabel: 'GitHub Copilot' },
|
||||
{ name: 'Amazon Q Developer', value: 'amazon-q', available: true, successLabel: 'Amazon Q Developer' },
|
||||
{ name: 'iFlow', value: 'iflow', available: true, successLabel: 'iFlow' },
|
||||
{ name: 'Kilo Code', value: 'kilocode', available: true, successLabel: 'Kilo Code' },
|
||||
{ name: 'OpenCode', value: 'opencode', available: true, successLabel: 'OpenCode' },
|
||||
{ name: 'Qoder (CLI)', value: 'qoder', available: true, successLabel: 'Qoder' },
|
||||
{ name: 'Qwen Code', value: 'qwen', available: true, successLabel: 'Qwen Code' },
|
||||
{ name: 'RooCode', value: 'roocode', available: true, successLabel: 'RooCode' },
|
||||
{ name: 'Windsurf', value: 'windsurf', available: true, successLabel: 'Windsurf' },
|
||||
{ name: 'AGENTS.md (works with Amp, VS Code, …)', value: 'agents', available: false, successLabel: 'your AGENTS.md-compatible assistant' }
|
||||
];
|
||||
|
||||
@@ -11,7 +11,6 @@ const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
|
||||
const FRONTMATTER: Record<SlashCommandId, string> = {
|
||||
proposal: `---
|
||||
agent: build
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
---
|
||||
The user has requested the following change proposal. Use the openspec instructions to create their change proposal.
|
||||
@@ -20,7 +19,6 @@ The user has requested the following change proposal. Use the openspec instructi
|
||||
</UserRequest>
|
||||
`,
|
||||
apply: `---
|
||||
agent: build
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
---
|
||||
The user has requested to implement the following change proposal. Find the change proposal and follow the instructions below. If you're not sure or if ambiguous, ask for clarification from the user.
|
||||
@@ -29,7 +27,6 @@ The user has requested to implement the following change proposal. Find the chan
|
||||
</UserRequest>
|
||||
`,
|
||||
archive: `---
|
||||
agent: build
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
---
|
||||
<ChangeId>
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
|
||||
// Constants
|
||||
export const GLOBAL_CONFIG_DIR_NAME = 'openspec';
|
||||
export const GLOBAL_CONFIG_FILE_NAME = 'config.json';
|
||||
|
||||
// TypeScript interfaces
|
||||
export interface GlobalConfig {
|
||||
featureFlags?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG: GlobalConfig = {
|
||||
featureFlags: {}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the global configuration directory path following XDG Base Directory Specification.
|
||||
*
|
||||
* - All platforms: $XDG_CONFIG_HOME/openspec/ if XDG_CONFIG_HOME is set
|
||||
* - Unix/macOS fallback: ~/.config/openspec/
|
||||
* - Windows fallback: %APPDATA%/openspec/
|
||||
*/
|
||||
export function getGlobalConfigDir(): string {
|
||||
// XDG_CONFIG_HOME takes precedence on all platforms when explicitly set
|
||||
const xdgConfigHome = process.env.XDG_CONFIG_HOME;
|
||||
if (xdgConfigHome) {
|
||||
return path.join(xdgConfigHome, GLOBAL_CONFIG_DIR_NAME);
|
||||
}
|
||||
|
||||
const platform = os.platform();
|
||||
|
||||
if (platform === 'win32') {
|
||||
// Windows: use %APPDATA%
|
||||
const appData = process.env.APPDATA;
|
||||
if (appData) {
|
||||
return path.join(appData, GLOBAL_CONFIG_DIR_NAME);
|
||||
}
|
||||
// Fallback for Windows if APPDATA is not set
|
||||
return path.join(os.homedir(), 'AppData', 'Roaming', GLOBAL_CONFIG_DIR_NAME);
|
||||
}
|
||||
|
||||
// Unix/macOS fallback: ~/.config
|
||||
return path.join(os.homedir(), '.config', GLOBAL_CONFIG_DIR_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path to the global config file.
|
||||
*/
|
||||
export function getGlobalConfigPath(): string {
|
||||
return path.join(getGlobalConfigDir(), GLOBAL_CONFIG_FILE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the global configuration from disk.
|
||||
* Returns default configuration if file doesn't exist or is invalid.
|
||||
* Merges loaded config with defaults to ensure new fields are available.
|
||||
*/
|
||||
export function getGlobalConfig(): GlobalConfig {
|
||||
const configPath = getGlobalConfigPath();
|
||||
|
||||
try {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return { ...DEFAULT_CONFIG };
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
// Merge with defaults (loaded values take precedence)
|
||||
return {
|
||||
...DEFAULT_CONFIG,
|
||||
...parsed,
|
||||
// Deep merge featureFlags
|
||||
featureFlags: {
|
||||
...DEFAULT_CONFIG.featureFlags,
|
||||
...(parsed.featureFlags || {})
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
// Log warning for parse errors, but not for missing files
|
||||
if (error instanceof SyntaxError) {
|
||||
console.error(`Warning: Invalid JSON in ${configPath}, using defaults`);
|
||||
}
|
||||
return { ...DEFAULT_CONFIG };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the global configuration to disk.
|
||||
* Creates the config directory if it doesn't exist.
|
||||
*/
|
||||
export function saveGlobalConfig(config: GlobalConfig): void {
|
||||
const configDir = getGlobalConfigDir();
|
||||
const configPath = getGlobalConfigPath();
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', 'utf-8');
|
||||
}
|
||||
+9
-1
@@ -1,2 +1,10 @@
|
||||
// Core OpenSpec logic will be implemented here
|
||||
export {};
|
||||
export {
|
||||
GLOBAL_CONFIG_DIR_NAME,
|
||||
GLOBAL_CONFIG_FILE_NAME,
|
||||
type GlobalConfig,
|
||||
getGlobalConfigDir,
|
||||
getGlobalConfigPath,
|
||||
getGlobalConfig,
|
||||
saveGlobalConfig
|
||||
} from './global-config.js';
|
||||
@@ -862,6 +862,22 @@ export class InitCommand {
|
||||
)
|
||||
);
|
||||
|
||||
// Show restart instruction if any tools were configured
|
||||
if (created.length > 0 || refreshed.length > 0) {
|
||||
console.log();
|
||||
console.log(PALETTE.white('Important: Restart your IDE'));
|
||||
console.log(
|
||||
PALETTE.midGray(
|
||||
'Slash commands are loaded at startup. Please restart your coding assistant'
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
PALETTE.midGray(
|
||||
'to ensure the new /openspec commands appear in your command palette.'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Get the selected tool name(s) for display
|
||||
const toolName = this.formatToolNames(selectedTools);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import { promises as fs, constants as fsConstants } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
function isMarkerOnOwnLine(content: string, markerIndex: number, markerLength: number): boolean {
|
||||
@@ -93,10 +93,24 @@ export class FileSystemUtils {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (stats.mode & 0o222) !== 0;
|
||||
// On Windows, stats.mode doesn't reliably indicate write permissions.
|
||||
// Use fs.access with W_OK to check actual write permissions cross-platform.
|
||||
try {
|
||||
await fs.access(filePath, fsConstants.W_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return true;
|
||||
// File doesn't exist; check if we can write to the parent directory
|
||||
const parentDir = path.dirname(filePath);
|
||||
try {
|
||||
await fs.access(parentDir, fsConstants.W_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
console.debug(`Unable to determine write permissions for ${filePath}: ${error.message}`);
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
export function isInteractive(noInteractiveFlag?: boolean): boolean {
|
||||
if (noInteractiveFlag) return false;
|
||||
type InteractiveOptions = {
|
||||
/**
|
||||
* Explicit "disable prompts" flag passed by internal callers.
|
||||
*/
|
||||
noInteractive?: boolean;
|
||||
/**
|
||||
* Commander-style negated option: `--no-interactive` sets this to false.
|
||||
*/
|
||||
interactive?: boolean;
|
||||
};
|
||||
|
||||
function resolveNoInteractive(value?: boolean | InteractiveOptions): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
return value?.noInteractive === true || value?.interactive === false;
|
||||
}
|
||||
|
||||
export function isInteractive(value?: boolean | InteractiveOptions): boolean {
|
||||
if (resolveNoInteractive(value)) return false;
|
||||
if (process.env.OPEN_SPEC_INTERACTIVE === '0') return false;
|
||||
return !!process.stdin.isTTY;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -43,3 +43,24 @@ export async function getSpecIds(root: string = process.cwd()): Promise<string[]
|
||||
return result.sort();
|
||||
}
|
||||
|
||||
export async function getArchivedChangeIds(root: string = process.cwd()): Promise<string[]> {
|
||||
const archivePath = path.join(root, 'openspec', 'changes', 'archive');
|
||||
try {
|
||||
const entries = await fs.readdir(archivePath, { withFileTypes: true });
|
||||
const result: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
|
||||
const proposalPath = path.join(archivePath, entry.name, 'proposal.md');
|
||||
try {
|
||||
await fs.access(proposalPath);
|
||||
result.push(entry.name);
|
||||
} catch {
|
||||
// skip directories without proposal.md
|
||||
}
|
||||
}
|
||||
return result.sort();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Supported shell types for completion generation
|
||||
*/
|
||||
export type SupportedShell = 'zsh' | 'bash' | 'fish' | 'powershell';
|
||||
|
||||
/**
|
||||
* Result of shell detection
|
||||
*/
|
||||
export interface ShellDetectionResult {
|
||||
/** The detected shell if supported, otherwise undefined */
|
||||
shell: SupportedShell | undefined;
|
||||
/** The raw shell name detected (even if unsupported), or undefined if nothing detected */
|
||||
detected: string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects the current user's shell based on environment variables
|
||||
*
|
||||
* @returns Detection result with supported shell and raw detected name
|
||||
*/
|
||||
export function detectShell(): ShellDetectionResult {
|
||||
// Try SHELL environment variable first (Unix-like systems)
|
||||
const shellPath = process.env.SHELL;
|
||||
|
||||
if (shellPath) {
|
||||
const shellName = shellPath.toLowerCase();
|
||||
|
||||
if (shellName.includes('zsh')) {
|
||||
return { shell: 'zsh', detected: 'zsh' };
|
||||
}
|
||||
if (shellName.includes('bash')) {
|
||||
return { shell: 'bash', detected: 'bash' };
|
||||
}
|
||||
if (shellName.includes('fish')) {
|
||||
return { shell: 'fish', detected: 'fish' };
|
||||
}
|
||||
|
||||
// Shell detected but not supported
|
||||
// Extract shell name from path (e.g., /bin/tcsh -> tcsh)
|
||||
const match = shellPath.match(/\/([^/]+)$/);
|
||||
const detectedName = match ? match[1] : shellPath;
|
||||
return { shell: undefined, detected: detectedName };
|
||||
}
|
||||
|
||||
// Check for PowerShell on Windows
|
||||
// PSModulePath is a reliable PowerShell-specific environment variable
|
||||
if (process.env.PSModulePath || process.platform === 'win32') {
|
||||
const comspec = process.env.COMSPEC?.toLowerCase();
|
||||
|
||||
// If PSModulePath exists, we're definitely in PowerShell
|
||||
if (process.env.PSModulePath) {
|
||||
return { shell: 'powershell', detected: 'powershell' };
|
||||
}
|
||||
|
||||
// On Windows without PSModulePath, we might be in cmd.exe
|
||||
if (comspec?.includes('cmd.exe')) {
|
||||
return { shell: undefined, detected: 'cmd.exe' };
|
||||
}
|
||||
}
|
||||
|
||||
return { shell: undefined, detected: undefined };
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { CompletionCommand } from '../../src/commands/completion.js';
|
||||
import * as shellDetection from '../../src/utils/shell-detection.js';
|
||||
|
||||
// Mock the shell detection module
|
||||
vi.mock('../../src/utils/shell-detection.js', () => ({
|
||||
detectShell: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the ZshInstaller
|
||||
vi.mock('../../src/core/completions/installers/zsh-installer.js', () => ({
|
||||
ZshInstaller: vi.fn().mockImplementation(() => ({
|
||||
install: vi.fn().mockResolvedValue({
|
||||
success: true,
|
||||
installedPath: '/home/user/.oh-my-zsh/completions/_openspec',
|
||||
isOhMyZsh: true,
|
||||
message: 'Completion script installed successfully for Oh My Zsh',
|
||||
instructions: [
|
||||
'Completion script installed to Oh My Zsh completions directory.',
|
||||
'Restart your shell or run: exec zsh',
|
||||
'Completions should activate automatically.',
|
||||
],
|
||||
}),
|
||||
uninstall: vi.fn().mockResolvedValue({
|
||||
success: true,
|
||||
message: 'Completion script removed from /home/user/.oh-my-zsh/completions/_openspec',
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('CompletionCommand', () => {
|
||||
let command: CompletionCommand;
|
||||
let consoleLogSpy: any;
|
||||
let consoleErrorSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new CompletionCommand();
|
||||
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
process.exitCode = 0;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleLogSpy.mockRestore();
|
||||
consoleErrorSpy.mockRestore();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('generate subcommand', () => {
|
||||
it('should generate Zsh completion script to stdout', async () => {
|
||||
await command.generate({ shell: 'zsh' });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalled();
|
||||
const output = consoleLogSpy.mock.calls[0][0];
|
||||
expect(output).toContain('#compdef openspec');
|
||||
expect(output).toContain('_openspec() {');
|
||||
});
|
||||
|
||||
it('should auto-detect Zsh shell when no shell specified', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: 'zsh', detected: 'zsh' });
|
||||
|
||||
await command.generate({});
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalled();
|
||||
const output = consoleLogSpy.mock.calls[0][0];
|
||||
expect(output).toContain('#compdef openspec');
|
||||
});
|
||||
|
||||
it('should show error when shell cannot be auto-detected', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: undefined });
|
||||
|
||||
await command.generate({});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
'Error: Could not auto-detect shell. Please specify shell explicitly.'
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should show error for unsupported shell', async () => {
|
||||
await command.generate({ shell: 'bash' });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
"Error: Shell 'bash' is not supported yet. Currently supported: zsh"
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle shell parameter case-insensitively', async () => {
|
||||
await command.generate({ shell: 'ZSH' });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalled();
|
||||
const output = consoleLogSpy.mock.calls[0][0];
|
||||
expect(output).toContain('#compdef openspec');
|
||||
});
|
||||
});
|
||||
|
||||
describe('install subcommand', () => {
|
||||
it('should install Zsh completion script', async () => {
|
||||
await command.install({ shell: 'zsh' });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Completion script installed successfully')
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('should show verbose output when --verbose flag is provided', async () => {
|
||||
await command.install({ shell: 'zsh', verbose: true });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Installed to:')
|
||||
);
|
||||
});
|
||||
|
||||
it('should auto-detect Zsh shell when no shell specified', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: 'zsh', detected: 'zsh' });
|
||||
|
||||
await command.install({});
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Completion script installed successfully')
|
||||
);
|
||||
});
|
||||
|
||||
it('should show error when shell cannot be auto-detected', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: undefined });
|
||||
|
||||
await command.install({});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
'Error: Could not auto-detect shell. Please specify shell explicitly.'
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should show error for unsupported shell', async () => {
|
||||
await command.install({ shell: 'fish' });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
"Error: Shell 'fish' is not supported yet. Currently supported: zsh"
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should display installation instructions', async () => {
|
||||
await command.install({ shell: 'zsh' });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Restart your shell or run: exec zsh')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uninstall subcommand', () => {
|
||||
it('should uninstall Zsh completion script', async () => {
|
||||
await command.uninstall({ shell: 'zsh', yes: true });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Completion script removed')
|
||||
);
|
||||
expect(process.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('should auto-detect Zsh shell when no shell specified', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: 'zsh', detected: 'zsh' });
|
||||
|
||||
await command.uninstall({ yes: true });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Completion script removed')
|
||||
);
|
||||
});
|
||||
|
||||
it('should show error when shell cannot be auto-detected', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: undefined });
|
||||
|
||||
await command.uninstall({ yes: true });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
'Error: Could not auto-detect shell. Please specify shell explicitly.'
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should show error for unsupported shell', async () => {
|
||||
await command.uninstall({ shell: 'powershell', yes: true });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
"Error: Shell 'powershell' is not supported yet. Currently supported: zsh"
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should handle installation failures gracefully', async () => {
|
||||
const { ZshInstaller } = await import('../../src/core/completions/installers/zsh-installer.js');
|
||||
vi.mocked(ZshInstaller).mockImplementationOnce(() => ({
|
||||
install: vi.fn().mockResolvedValue({
|
||||
success: false,
|
||||
isOhMyZsh: false,
|
||||
message: 'Permission denied',
|
||||
}),
|
||||
uninstall: vi.fn(),
|
||||
isInstalled: vi.fn(),
|
||||
getInstallationInfo: vi.fn(),
|
||||
isOhMyZshInstalled: vi.fn(),
|
||||
getInstallationPath: vi.fn(),
|
||||
backupExistingFile: vi.fn(),
|
||||
} as any));
|
||||
|
||||
const cmd = new CompletionCommand();
|
||||
await cmd.install({ shell: 'zsh' });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Permission denied')
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle uninstallation failures gracefully', async () => {
|
||||
const { ZshInstaller } = await import('../../src/core/completions/installers/zsh-installer.js');
|
||||
vi.mocked(ZshInstaller).mockImplementationOnce(() => ({
|
||||
install: vi.fn(),
|
||||
uninstall: vi.fn().mockResolvedValue({
|
||||
success: false,
|
||||
message: 'Completion script is not installed',
|
||||
}),
|
||||
isInstalled: vi.fn(),
|
||||
getInstallationInfo: vi.fn(),
|
||||
isOhMyZshInstalled: vi.fn(),
|
||||
getInstallationPath: vi.fn(),
|
||||
backupExistingFile: vi.fn(),
|
||||
} as any));
|
||||
|
||||
const cmd = new CompletionCommand();
|
||||
await cmd.uninstall({ shell: 'zsh', yes: true });
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Completion script is not installed')
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shell detection integration', () => {
|
||||
it('should show appropriate error when detected shell is unsupported', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: 'bash' });
|
||||
|
||||
await command.generate({});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
"Error: Shell 'bash' is not supported yet. Currently supported: zsh"
|
||||
);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('should respect explicit shell parameter over auto-detection', async () => {
|
||||
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: 'bash' });
|
||||
|
||||
await command.generate({ shell: 'zsh' });
|
||||
|
||||
expect(consoleLogSpy).toHaveBeenCalled();
|
||||
const output = consoleLogSpy.mock.calls[0][0];
|
||||
expect(output).toContain('#compdef openspec');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
|
||||
describe('config command integration', () => {
|
||||
// These tests use real file system operations with XDG_CONFIG_HOME override
|
||||
let tempDir: string;
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create unique temp directory for each test
|
||||
tempDir = path.join(os.tmpdir(), `openspec-config-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
// Save original env and set XDG_CONFIG_HOME
|
||||
originalEnv = { ...process.env };
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
|
||||
// Spy on console.error
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original env
|
||||
process.env = originalEnv;
|
||||
|
||||
// Clean up temp directory
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
// Restore spies
|
||||
consoleErrorSpy.mockRestore();
|
||||
|
||||
// Reset module cache to pick up new XDG_CONFIG_HOME
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('should use XDG_CONFIG_HOME for config path', async () => {
|
||||
const { getGlobalConfigPath } = await import('../../src/core/global-config.js');
|
||||
const configPath = getGlobalConfigPath();
|
||||
expect(configPath).toBe(path.join(tempDir, 'openspec', 'config.json'));
|
||||
});
|
||||
|
||||
it('should save and load config correctly', async () => {
|
||||
const { getGlobalConfig, saveGlobalConfig } = await import('../../src/core/global-config.js');
|
||||
|
||||
saveGlobalConfig({ featureFlags: { test: true } });
|
||||
const config = getGlobalConfig();
|
||||
expect(config.featureFlags).toEqual({ test: true });
|
||||
});
|
||||
|
||||
it('should return defaults when config file does not exist', async () => {
|
||||
const { getGlobalConfig, getGlobalConfigPath } = await import('../../src/core/global-config.js');
|
||||
|
||||
const configPath = getGlobalConfigPath();
|
||||
// Make sure config doesn't exist
|
||||
if (fs.existsSync(configPath)) {
|
||||
fs.unlinkSync(configPath);
|
||||
}
|
||||
|
||||
const config = getGlobalConfig();
|
||||
expect(config.featureFlags).toEqual({});
|
||||
});
|
||||
|
||||
it('should preserve unknown fields', async () => {
|
||||
const { getGlobalConfig, getGlobalConfigDir } = await import('../../src/core/global-config.js');
|
||||
|
||||
const configDir = getGlobalConfigDir();
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(configDir, 'config.json'), JSON.stringify({
|
||||
featureFlags: {},
|
||||
customField: 'preserved',
|
||||
}));
|
||||
|
||||
const config = getGlobalConfig();
|
||||
expect((config as Record<string, unknown>).customField).toBe('preserved');
|
||||
});
|
||||
|
||||
it('should handle invalid JSON gracefully', async () => {
|
||||
const { getGlobalConfig, getGlobalConfigDir } = await import('../../src/core/global-config.js');
|
||||
|
||||
const configDir = getGlobalConfigDir();
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(configDir, 'config.json'), '{ invalid json }');
|
||||
|
||||
const config = getGlobalConfig();
|
||||
// Should return defaults
|
||||
expect(config.featureFlags).toEqual({});
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid JSON'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('config command shell completion registry', () => {
|
||||
it('should have config command in registry', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
expect(configCmd).toBeDefined();
|
||||
expect(configCmd?.description).toBe('View and modify global OpenSpec configuration');
|
||||
});
|
||||
|
||||
it('should have all config subcommands in registry', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
const subcommandNames = configCmd?.subcommands?.map((s) => s.name) ?? [];
|
||||
|
||||
expect(subcommandNames).toContain('path');
|
||||
expect(subcommandNames).toContain('list');
|
||||
expect(subcommandNames).toContain('get');
|
||||
expect(subcommandNames).toContain('set');
|
||||
expect(subcommandNames).toContain('unset');
|
||||
expect(subcommandNames).toContain('reset');
|
||||
expect(subcommandNames).toContain('edit');
|
||||
});
|
||||
|
||||
it('should have --json flag on list subcommand', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
const listCmd = configCmd?.subcommands?.find((s) => s.name === 'list');
|
||||
const flagNames = listCmd?.flags?.map((f) => f.name) ?? [];
|
||||
|
||||
expect(flagNames).toContain('json');
|
||||
});
|
||||
|
||||
it('should have --string flag on set subcommand', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
const setCmd = configCmd?.subcommands?.find((s) => s.name === 'set');
|
||||
const flagNames = setCmd?.flags?.map((f) => f.name) ?? [];
|
||||
|
||||
expect(flagNames).toContain('string');
|
||||
expect(flagNames).toContain('allow-unknown');
|
||||
});
|
||||
|
||||
it('should have --all and -y flags on reset subcommand', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
const resetCmd = configCmd?.subcommands?.find((s) => s.name === 'reset');
|
||||
const flagNames = resetCmd?.flags?.map((f) => f.name) ?? [];
|
||||
|
||||
expect(flagNames).toContain('all');
|
||||
expect(flagNames).toContain('yes');
|
||||
});
|
||||
|
||||
it('should have --scope flag on config command', async () => {
|
||||
const { COMMAND_REGISTRY } = await import('../../src/core/completions/command-registry.js');
|
||||
|
||||
const configCmd = COMMAND_REGISTRY.find((cmd) => cmd.name === 'config');
|
||||
const flagNames = configCmd?.flags?.map((f) => f.name) ?? [];
|
||||
|
||||
expect(flagNames).toContain('scope');
|
||||
});
|
||||
});
|
||||
|
||||
describe('config key validation', () => {
|
||||
it('rejects unknown top-level keys', async () => {
|
||||
const { validateConfigKeyPath } = await import('../../src/core/config-schema.js');
|
||||
expect(validateConfigKeyPath('unknownKey').valid).toBe(false);
|
||||
});
|
||||
|
||||
it('allows feature flag keys', async () => {
|
||||
const { validateConfigKeyPath } = await import('../../src/core/config-schema.js');
|
||||
expect(validateConfigKeyPath('featureFlags.someFlag').valid).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects deeply nested feature flag keys', async () => {
|
||||
const { validateConfigKeyPath } = await import('../../src/core/config-schema.js');
|
||||
expect(validateConfigKeyPath('featureFlags.someFlag.extra').valid).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { CompletionProvider } from '../../../src/core/completions/completion-provider.js';
|
||||
|
||||
describe('CompletionProvider', () => {
|
||||
let testDir: string;
|
||||
let provider: CompletionProvider;
|
||||
|
||||
beforeEach(async () => {
|
||||
testDir = path.join(os.tmpdir(), `openspec-test-${randomUUID()}`);
|
||||
await fs.mkdir(testDir, { recursive: true });
|
||||
provider = new CompletionProvider(2000, testDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.rm(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('getChangeIds', () => {
|
||||
it('should return empty array when no changes exist', async () => {
|
||||
const changeIds = await provider.getChangeIds();
|
||||
expect(changeIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return active change IDs', async () => {
|
||||
// Create openspec/changes directory structure
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
// Create some changes
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-2', 'proposal.md'), '# Change 2');
|
||||
|
||||
const changeIds = await provider.getChangeIds();
|
||||
expect(changeIds).toEqual(['change-1', 'change-2']);
|
||||
});
|
||||
|
||||
it('should exclude archive directory', async () => {
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
// Create active change
|
||||
await fs.mkdir(path.join(changesDir, 'active-change'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'active-change', 'proposal.md'), '# Active');
|
||||
|
||||
// Create archived change
|
||||
await fs.mkdir(path.join(changesDir, 'archive', 'old-change'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'archive', 'old-change', 'proposal.md'), '# Old');
|
||||
|
||||
const changeIds = await provider.getChangeIds();
|
||||
expect(changeIds).toEqual(['active-change']);
|
||||
});
|
||||
|
||||
it('should cache results for the TTL duration', async () => {
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
// First call
|
||||
const firstResult = await provider.getChangeIds();
|
||||
expect(firstResult).toEqual(['change-1']);
|
||||
|
||||
// Add another change
|
||||
await fs.mkdir(path.join(changesDir, 'change-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-2', 'proposal.md'), '# Change 2');
|
||||
|
||||
// Second call should return cached result (still only change-1)
|
||||
const secondResult = await provider.getChangeIds();
|
||||
expect(secondResult).toEqual(['change-1']);
|
||||
});
|
||||
|
||||
it('should refresh cache after TTL expires', async () => {
|
||||
// Use a very short TTL for testing
|
||||
const shortTTLProvider = new CompletionProvider(50, testDir);
|
||||
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
// First call
|
||||
const firstResult = await shortTTLProvider.getChangeIds();
|
||||
expect(firstResult).toEqual(['change-1']);
|
||||
|
||||
// Add another change
|
||||
await fs.mkdir(path.join(changesDir, 'change-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-2', 'proposal.md'), '# Change 2');
|
||||
|
||||
// Wait for cache to expire
|
||||
await new Promise(resolve => setTimeout(resolve, 60));
|
||||
|
||||
// Should now see both changes
|
||||
const secondResult = await shortTTLProvider.getChangeIds();
|
||||
expect(secondResult).toEqual(['change-1', 'change-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSpecIds', () => {
|
||||
it('should return empty array when no specs exist', async () => {
|
||||
const specIds = await provider.getSpecIds();
|
||||
expect(specIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return spec IDs', async () => {
|
||||
const specsDir = path.join(testDir, 'openspec', 'specs');
|
||||
await fs.mkdir(specsDir, { recursive: true });
|
||||
|
||||
// Create some specs
|
||||
await fs.mkdir(path.join(specsDir, 'spec-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-1', 'spec.md'), '# Spec 1');
|
||||
|
||||
await fs.mkdir(path.join(specsDir, 'spec-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-2', 'spec.md'), '# Spec 2');
|
||||
|
||||
const specIds = await provider.getSpecIds();
|
||||
expect(specIds).toEqual(['spec-1', 'spec-2']);
|
||||
});
|
||||
|
||||
it('should cache results for the TTL duration', async () => {
|
||||
const specsDir = path.join(testDir, 'openspec', 'specs');
|
||||
await fs.mkdir(specsDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(specsDir, 'spec-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-1', 'spec.md'), '# Spec 1');
|
||||
|
||||
// First call
|
||||
const firstResult = await provider.getSpecIds();
|
||||
expect(firstResult).toEqual(['spec-1']);
|
||||
|
||||
// Add another spec
|
||||
await fs.mkdir(path.join(specsDir, 'spec-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-2', 'spec.md'), '# Spec 2');
|
||||
|
||||
// Second call should return cached result
|
||||
const secondResult = await provider.getSpecIds();
|
||||
expect(secondResult).toEqual(['spec-1']);
|
||||
});
|
||||
|
||||
it('should refresh cache after TTL expires', async () => {
|
||||
const shortTTLProvider = new CompletionProvider(50, testDir);
|
||||
|
||||
const specsDir = path.join(testDir, 'openspec', 'specs');
|
||||
await fs.mkdir(specsDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(specsDir, 'spec-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-1', 'spec.md'), '# Spec 1');
|
||||
|
||||
const firstResult = await shortTTLProvider.getSpecIds();
|
||||
expect(firstResult).toEqual(['spec-1']);
|
||||
|
||||
// Add another spec
|
||||
await fs.mkdir(path.join(specsDir, 'spec-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'spec-2', 'spec.md'), '# Spec 2');
|
||||
|
||||
// Wait for cache to expire
|
||||
await new Promise(resolve => setTimeout(resolve, 60));
|
||||
|
||||
const secondResult = await shortTTLProvider.getSpecIds();
|
||||
expect(secondResult).toEqual(['spec-1', 'spec-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllIds', () => {
|
||||
it('should return both change and spec IDs', async () => {
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
const specsDir = path.join(testDir, 'openspec', 'specs');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
await fs.mkdir(specsDir, { recursive: true });
|
||||
|
||||
// Create a change
|
||||
await fs.mkdir(path.join(changesDir, 'my-change'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'my-change', 'proposal.md'), '# Change');
|
||||
|
||||
// Create a spec
|
||||
await fs.mkdir(path.join(specsDir, 'my-spec'), { recursive: true });
|
||||
await fs.writeFile(path.join(specsDir, 'my-spec', 'spec.md'), '# Spec');
|
||||
|
||||
const result = await provider.getAllIds();
|
||||
expect(result).toEqual({
|
||||
changeIds: ['my-change'],
|
||||
specIds: ['my-spec'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should return empty arrays when no items exist', async () => {
|
||||
const result = await provider.getAllIds();
|
||||
expect(result).toEqual({
|
||||
changeIds: [],
|
||||
specIds: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearCache', () => {
|
||||
it('should clear all cached data', async () => {
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
// Populate cache
|
||||
await provider.getChangeIds();
|
||||
|
||||
// Clear cache
|
||||
provider.clearCache();
|
||||
|
||||
// Add new change
|
||||
await fs.mkdir(path.join(changesDir, 'change-2'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-2', 'proposal.md'), '# Change 2');
|
||||
|
||||
// Should see new data immediately
|
||||
const result = await provider.getChangeIds();
|
||||
expect(result).toEqual(['change-1', 'change-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCacheStats', () => {
|
||||
it('should report invalid cache when empty', () => {
|
||||
const stats = provider.getCacheStats();
|
||||
expect(stats.changeCache.valid).toBe(false);
|
||||
expect(stats.specCache.valid).toBe(false);
|
||||
expect(stats.changeCache.age).toBeUndefined();
|
||||
expect(stats.specCache.age).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should report valid cache after data is fetched', async () => {
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
await provider.getChangeIds();
|
||||
|
||||
const stats = provider.getCacheStats();
|
||||
expect(stats.changeCache.valid).toBe(true);
|
||||
expect(stats.changeCache.age).toBeDefined();
|
||||
expect(stats.changeCache.age).toBeLessThan(100);
|
||||
});
|
||||
|
||||
it('should report invalid cache after TTL expires', async () => {
|
||||
const shortTTLProvider = new CompletionProvider(50, testDir);
|
||||
|
||||
const changesDir = path.join(testDir, 'openspec', 'changes');
|
||||
await fs.mkdir(changesDir, { recursive: true });
|
||||
|
||||
await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
|
||||
await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');
|
||||
|
||||
await shortTTLProvider.getChangeIds();
|
||||
|
||||
// Wait for cache to expire
|
||||
await new Promise(resolve => setTimeout(resolve, 60));
|
||||
|
||||
const stats = shortTTLProvider.getCacheStats();
|
||||
expect(stats.changeCache.valid).toBe(false);
|
||||
expect(stats.changeCache.age).toBeGreaterThan(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should use default TTL of 2000ms', async () => {
|
||||
const defaultProvider = new CompletionProvider();
|
||||
expect(defaultProvider).toBeDefined();
|
||||
// We can verify this behavior by checking cache stats after waiting
|
||||
});
|
||||
|
||||
it('should accept custom TTL', async () => {
|
||||
const customProvider = new CompletionProvider(5000, testDir);
|
||||
expect(customProvider).toBeDefined();
|
||||
});
|
||||
|
||||
it('should use process.cwd() as default project root', () => {
|
||||
const defaultProvider = new CompletionProvider();
|
||||
expect(defaultProvider).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,381 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ZshGenerator } from '../../../../src/core/completions/generators/zsh-generator.js';
|
||||
import { CommandDefinition } from '../../../../src/core/completions/types.js';
|
||||
|
||||
describe('ZshGenerator', () => {
|
||||
let generator: ZshGenerator;
|
||||
|
||||
beforeEach(() => {
|
||||
generator = new ZshGenerator();
|
||||
});
|
||||
|
||||
describe('interface compliance', () => {
|
||||
it('should have shell property set to "zsh"', () => {
|
||||
expect(generator.shell).toBe('zsh');
|
||||
});
|
||||
|
||||
it('should implement generate method', () => {
|
||||
expect(typeof generator.generate).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generate', () => {
|
||||
it('should generate valid zsh completion script with header', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('#compdef openspec');
|
||||
expect(script).toContain('# Zsh completion script for OpenSpec CLI');
|
||||
expect(script).toContain('_openspec() {');
|
||||
});
|
||||
|
||||
it('should include all commands in the command list', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate specs',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a spec',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'init:Initialize OpenSpec'");
|
||||
expect(script).toContain("'validate:Validate specs'");
|
||||
expect(script).toContain("'show:Show a spec'");
|
||||
});
|
||||
|
||||
it('should generate command completion functions', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate specs',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('_openspec_init() {');
|
||||
expect(script).toContain('_openspec_validate() {');
|
||||
});
|
||||
|
||||
it('should handle commands with flags', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate specs',
|
||||
flags: [
|
||||
{
|
||||
name: 'strict',
|
||||
description: 'Enable strict mode',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
description: 'Output as JSON',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('--strict');
|
||||
expect(script).toContain('[Enable strict mode]');
|
||||
expect(script).toContain('--json');
|
||||
expect(script).toContain('[Output as JSON]');
|
||||
});
|
||||
|
||||
it('should handle flags with short options', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a spec',
|
||||
flags: [
|
||||
{
|
||||
name: 'requirement',
|
||||
short: 'r',
|
||||
description: 'Show specific requirement',
|
||||
takesValue: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'(-r --requirement)'{-r,--requirement}'[Show specific requirement]:value:'");
|
||||
expect(script).toContain('[Show specific requirement]');
|
||||
});
|
||||
|
||||
it('should handle flags that take values', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate specs',
|
||||
flags: [
|
||||
{
|
||||
name: 'type',
|
||||
description: 'Specify item type',
|
||||
takesValue: true,
|
||||
values: ['change', 'spec'],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('--type');
|
||||
expect(script).toContain('[Specify item type]');
|
||||
expect(script).toContain(':value:(change spec)');
|
||||
});
|
||||
|
||||
it('should handle flags with takesValue but no specific values', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate specs',
|
||||
flags: [
|
||||
{
|
||||
name: 'concurrency',
|
||||
description: 'Max concurrent validations',
|
||||
takesValue: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('--concurrency');
|
||||
expect(script).toContain('[Max concurrent validations]');
|
||||
expect(script).toContain(':value:');
|
||||
});
|
||||
|
||||
it('should handle commands with subcommands', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'change',
|
||||
description: 'Manage changes',
|
||||
flags: [],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show a change',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'list',
|
||||
description: 'List changes',
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'show:Show a change'");
|
||||
expect(script).toContain("'list:List changes'");
|
||||
expect(script).toContain('_openspec_change_show() {');
|
||||
expect(script).toContain('_openspec_change_list() {');
|
||||
});
|
||||
|
||||
it('should handle positional arguments for change-id', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'archive',
|
||||
description: 'Archive a change',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-id',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'*: :_openspec_complete_changes'");
|
||||
});
|
||||
|
||||
it('should handle positional arguments for spec-id', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'show-spec',
|
||||
description: 'Show a spec',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'spec-id',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'*: :_openspec_complete_specs'");
|
||||
});
|
||||
|
||||
it('should handle positional arguments for change-or-spec-id', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'show',
|
||||
description: 'Show an item',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'change-or-spec-id',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'*: :_openspec_complete_items'");
|
||||
});
|
||||
|
||||
it('should handle positional arguments for paths', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize OpenSpec',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'path',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("'*:path:_files'");
|
||||
});
|
||||
|
||||
it('should escape special characters in descriptions', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'test',
|
||||
description: "Test with 'quotes' and [brackets] and back\\slash and colon:",
|
||||
flags: [
|
||||
{
|
||||
name: 'flag',
|
||||
description: "Special chars: 'quotes' [brackets] back\\slash colon:",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain("\\'quotes\\'");
|
||||
expect(script).toContain('\\[brackets\\]');
|
||||
expect(script).toContain('\\\\slash');
|
||||
expect(script).toContain('\\:');
|
||||
});
|
||||
|
||||
it('should sanitize command names with hyphens for function names', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'my-command',
|
||||
description: 'A hyphenated command',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('_openspec_my_command() {');
|
||||
});
|
||||
|
||||
it('should handle complex nested subcommands with flags', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'spec',
|
||||
description: 'Manage specs',
|
||||
flags: [],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate a spec',
|
||||
acceptsPositional: true,
|
||||
positionalType: 'spec-id',
|
||||
flags: [
|
||||
{
|
||||
name: 'strict',
|
||||
description: 'Enable strict mode',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
description: 'Output as JSON',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('_openspec_spec() {');
|
||||
expect(script).toContain('_openspec_spec_validate() {');
|
||||
expect(script).toContain('--strict');
|
||||
expect(script).toContain('--json');
|
||||
expect(script).toContain("'*: :_openspec_complete_specs'");
|
||||
});
|
||||
|
||||
it('should generate script that ends with compdef registration', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'init',
|
||||
description: 'Initialize',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script.trim().endsWith('compdef _openspec openspec')).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle empty command list', () => {
|
||||
const commands: CommandDefinition[] = [];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('#compdef openspec');
|
||||
expect(script).toContain('_openspec() {');
|
||||
});
|
||||
|
||||
it('should handle commands with no flags', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'view',
|
||||
description: 'Display dashboard',
|
||||
flags: [],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
expect(script).toContain('_openspec_view() {');
|
||||
expect(script).toContain('_arguments');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,748 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { ZshInstaller } from '../../../../src/core/completions/installers/zsh-installer.js';
|
||||
|
||||
describe('ZshInstaller', () => {
|
||||
let testHomeDir: string;
|
||||
let installer: ZshInstaller;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create a temporary home directory for testing
|
||||
testHomeDir = path.join(os.tmpdir(), `openspec-zsh-test-${randomUUID()}`);
|
||||
await fs.mkdir(testHomeDir, { recursive: true });
|
||||
installer = new ZshInstaller(testHomeDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up test directory
|
||||
await fs.rm(testHomeDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('isOhMyZshInstalled', () => {
|
||||
it('should return false when Oh My Zsh is not installed', async () => {
|
||||
const isInstalled = await installer.isOhMyZshInstalled();
|
||||
expect(isInstalled).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when Oh My Zsh directory exists', async () => {
|
||||
// Create .oh-my-zsh directory
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
const isInstalled = await installer.isOhMyZshInstalled();
|
||||
expect(isInstalled).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when .oh-my-zsh exists but is a file', async () => {
|
||||
// Create .oh-my-zsh as a file instead of directory
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.writeFile(ohMyZshPath, 'not a directory');
|
||||
|
||||
const isInstalled = await installer.isOhMyZshInstalled();
|
||||
expect(isInstalled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInstallationPath', () => {
|
||||
it('should return Oh My Zsh path when Oh My Zsh is installed', async () => {
|
||||
// Create .oh-my-zsh directory
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
const result = await installer.getInstallationPath();
|
||||
|
||||
expect(result.isOhMyZsh).toBe(true);
|
||||
expect(result.path).toBe(path.join(testHomeDir, '.oh-my-zsh', 'custom', 'completions', '_openspec'));
|
||||
});
|
||||
|
||||
it('should return standard Zsh path when Oh My Zsh is not installed', async () => {
|
||||
const result = await installer.getInstallationPath();
|
||||
|
||||
expect(result.isOhMyZsh).toBe(false);
|
||||
expect(result.path).toBe(path.join(testHomeDir, '.zsh', 'completions', '_openspec'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('backupExistingFile', () => {
|
||||
it('should return undefined when file does not exist', async () => {
|
||||
const nonExistentPath = path.join(testHomeDir, 'nonexistent.txt');
|
||||
const backupPath = await installer.backupExistingFile(nonExistentPath);
|
||||
|
||||
expect(backupPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should create backup when file exists', async () => {
|
||||
const filePath = path.join(testHomeDir, 'test.txt');
|
||||
await fs.writeFile(filePath, 'original content');
|
||||
|
||||
const backupPath = await installer.backupExistingFile(filePath);
|
||||
|
||||
expect(backupPath).toBeDefined();
|
||||
expect(backupPath).toContain('.backup-');
|
||||
|
||||
// Verify backup file exists and has correct content
|
||||
const backupContent = await fs.readFile(backupPath!, 'utf-8');
|
||||
expect(backupContent).toBe('original content');
|
||||
});
|
||||
|
||||
it('should create backup with timestamp in filename', async () => {
|
||||
const filePath = path.join(testHomeDir, 'test.txt');
|
||||
await fs.writeFile(filePath, 'content');
|
||||
|
||||
const backupPath = await installer.backupExistingFile(filePath);
|
||||
|
||||
expect(backupPath).toMatch(/\.backup-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('install', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {\n echo "test"\n}\n';
|
||||
|
||||
it('should install to Oh My Zsh path when Oh My Zsh is present', async () => {
|
||||
// Create .oh-my-zsh directory
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.isOhMyZsh).toBe(true);
|
||||
expect(result.installedPath).toBe(path.join(ohMyZshPath, 'custom', 'completions', '_openspec'));
|
||||
expect(result.message).toContain('Oh My Zsh');
|
||||
|
||||
// Verify file was created with correct content
|
||||
const content = await fs.readFile(result.installedPath!, 'utf-8');
|
||||
expect(content).toBe(testScript);
|
||||
});
|
||||
|
||||
it('should install to standard Zsh path when Oh My Zsh is not present', async () => {
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.isOhMyZsh).toBe(false);
|
||||
expect(result.installedPath).toBe(path.join(testHomeDir, '.zsh', 'completions', '_openspec'));
|
||||
|
||||
// Verify file was created
|
||||
const content = await fs.readFile(result.installedPath!, 'utf-8');
|
||||
expect(content).toBe(testScript);
|
||||
});
|
||||
|
||||
it('should create necessary directories if they do not exist', async () => {
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
// Verify directory structure was created
|
||||
const completionsDir = path.dirname(result.installedPath!);
|
||||
const stat = await fs.stat(completionsDir);
|
||||
expect(stat.isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
it('should backup existing file before overwriting', async () => {
|
||||
const targetPath = path.join(testHomeDir, '.zsh', 'completions', '_openspec');
|
||||
await fs.mkdir(path.dirname(targetPath), { recursive: true });
|
||||
await fs.writeFile(targetPath, 'old script');
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.backupPath).toBeDefined();
|
||||
expect(result.backupPath).toContain('.backup-');
|
||||
|
||||
// Verify backup has old content
|
||||
const backupContent = await fs.readFile(result.backupPath!, 'utf-8');
|
||||
expect(backupContent).toBe('old script');
|
||||
|
||||
// Verify new file has new content
|
||||
const newContent = await fs.readFile(targetPath, 'utf-8');
|
||||
expect(newContent).toBe(testScript);
|
||||
});
|
||||
|
||||
it('should include fpath verification guidance for Oh My Zsh', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.instructions).toBeDefined();
|
||||
expect(result.instructions!.length).toBeGreaterThan(0);
|
||||
// Should include guidance about verifying fpath for Oh My Zsh
|
||||
expect(result.instructions!.join(' ')).toContain('fpath');
|
||||
expect(result.instructions!.join(' ')).toContain('custom/completions');
|
||||
});
|
||||
|
||||
it('should include fpath instructions for standard Zsh when auto-config is disabled', async () => {
|
||||
const originalEnv = process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = '1';
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.instructions).toBeDefined();
|
||||
expect(result.instructions!.join('\n')).toContain('fpath');
|
||||
expect(result.instructions!.join('\n')).toContain('.zshrc');
|
||||
expect(result.instructions!.join('\n')).toContain('compinit');
|
||||
|
||||
// Restore env
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
} else {
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle installation errors gracefully', async () => {
|
||||
// Create installer with non-existent/invalid home directory
|
||||
// Use a path that will fail on both Unix and Windows
|
||||
const invalidPath = process.platform === 'win32'
|
||||
? 'Z:\\nonexistent\\invalid\\path' // Non-existent drive letter on Windows
|
||||
: '/root/invalid/nonexistent/path'; // Permission-denied path on Unix
|
||||
const invalidInstaller = new ZshInstaller(invalidPath);
|
||||
|
||||
const result = await invalidInstaller.install(testScript);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('Failed to install');
|
||||
});
|
||||
|
||||
it('should detect already-installed completion with identical content', async () => {
|
||||
// First installation
|
||||
const firstResult = await installer.install(testScript);
|
||||
expect(firstResult.success).toBe(true);
|
||||
|
||||
// Second installation with same script
|
||||
const secondResult = await installer.install(testScript);
|
||||
|
||||
expect(secondResult.success).toBe(true);
|
||||
expect(secondResult.message).toContain('already installed');
|
||||
expect(secondResult.message).toContain('up to date');
|
||||
expect(secondResult.backupPath).toBeUndefined();
|
||||
expect(secondResult.instructions).toBeDefined();
|
||||
expect(secondResult.instructions!.join(' ')).toContain('already installed');
|
||||
});
|
||||
|
||||
it('should update completion when content differs', async () => {
|
||||
// First installation
|
||||
const firstScript = '#compdef openspec\n_openspec() {\n echo "version 1"\n}\n';
|
||||
const firstResult = await installer.install(firstScript);
|
||||
expect(firstResult.success).toBe(true);
|
||||
|
||||
// Second installation with different script
|
||||
const secondScript = '#compdef openspec\n_openspec() {\n echo "version 2"\n}\n';
|
||||
const secondResult = await installer.install(secondScript);
|
||||
|
||||
expect(secondResult.success).toBe(true);
|
||||
expect(secondResult.message).toContain('updated successfully');
|
||||
expect(secondResult.message).toContain('backed up');
|
||||
expect(secondResult.backupPath).toBeDefined();
|
||||
|
||||
// Verify new content was written
|
||||
const content = await fs.readFile(secondResult.installedPath!, 'utf-8');
|
||||
expect(content).toBe(secondScript);
|
||||
|
||||
// Verify backup has old content
|
||||
const backupContent = await fs.readFile(secondResult.backupPath!, 'utf-8');
|
||||
expect(backupContent).toBe(firstScript);
|
||||
});
|
||||
|
||||
it('should handle paths with spaces in .zshrc config', async () => {
|
||||
// Create a test home directory with spaces
|
||||
const testHomeDirWithSpaces = path.join(os.tmpdir(), `openspec zsh test ${randomUUID()}`);
|
||||
await fs.mkdir(testHomeDirWithSpaces, { recursive: true });
|
||||
const installerWithSpaces = new ZshInstaller(testHomeDirWithSpaces);
|
||||
|
||||
try {
|
||||
const result = await installerWithSpaces.install(testScript);
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
// Check if .zshrc was created (when auto-config is enabled)
|
||||
const zshrcPath = path.join(testHomeDirWithSpaces, '.zshrc');
|
||||
try {
|
||||
const zshrcContent = await fs.readFile(zshrcPath, 'utf-8');
|
||||
// Verify the path is quoted in fpath
|
||||
expect(zshrcContent).toContain(`fpath=("${path.dirname(result.installedPath!)}" $fpath)`);
|
||||
} catch {
|
||||
// .zshrc might not exist if auto-config was disabled
|
||||
}
|
||||
} finally {
|
||||
// Clean up
|
||||
await fs.rm(testHomeDirWithSpaces, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('uninstall', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {}\n';
|
||||
|
||||
it('should remove installed completion script', async () => {
|
||||
// Install first
|
||||
await installer.install(testScript);
|
||||
|
||||
// Verify it's installed
|
||||
const beforeUninstall = await installer.isInstalled();
|
||||
expect(beforeUninstall).toBe(true);
|
||||
|
||||
// Uninstall
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('removed');
|
||||
|
||||
// Verify it's gone
|
||||
const afterUninstall = await installer.isInstalled();
|
||||
expect(afterUninstall).toBe(false);
|
||||
});
|
||||
|
||||
it('should return failure when script and .zshrc config are not installed', async () => {
|
||||
// Don't create .zshrc or completion script - nothing to remove
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.message).toContain('not installed');
|
||||
});
|
||||
|
||||
it('should remove from correct location for Oh My Zsh', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
await installer.install(testScript);
|
||||
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain(path.join('.oh-my-zsh', 'custom', 'completions', '_openspec'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('isInstalled', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {}\n';
|
||||
|
||||
it('should return false when not installed', async () => {
|
||||
const isInstalled = await installer.isInstalled();
|
||||
expect(isInstalled).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when installed', async () => {
|
||||
await installer.install(testScript);
|
||||
|
||||
const isInstalled = await installer.isInstalled();
|
||||
expect(isInstalled).toBe(true);
|
||||
});
|
||||
|
||||
it('should check correct location for Oh My Zsh', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
await installer.install(testScript);
|
||||
|
||||
const isInstalled = await installer.isInstalled();
|
||||
expect(isInstalled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInstallationInfo', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {}\n';
|
||||
|
||||
it('should return not installed when script does not exist', async () => {
|
||||
const info = await installer.getInstallationInfo();
|
||||
|
||||
expect(info.installed).toBe(false);
|
||||
expect(info.path).toBeUndefined();
|
||||
expect(info.isOhMyZsh).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return installation info when installed', async () => {
|
||||
await installer.install(testScript);
|
||||
|
||||
const info = await installer.getInstallationInfo();
|
||||
|
||||
expect(info.installed).toBe(true);
|
||||
expect(info.path).toBeDefined();
|
||||
expect(info.path).toContain('_openspec');
|
||||
expect(info.isOhMyZsh).toBe(false);
|
||||
});
|
||||
|
||||
it('should indicate Oh My Zsh when installed there', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
await installer.install(testScript);
|
||||
|
||||
const info = await installer.getInstallationInfo();
|
||||
|
||||
expect(info.installed).toBe(true);
|
||||
expect(info.isOhMyZsh).toBe(true);
|
||||
expect(info.path).toContain('.oh-my-zsh');
|
||||
});
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should use provided home directory', () => {
|
||||
const customInstaller = new ZshInstaller('/custom/home');
|
||||
expect(customInstaller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should use os.homedir() by default', () => {
|
||||
const defaultInstaller = new ZshInstaller();
|
||||
expect(defaultInstaller).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('configureZshrc', () => {
|
||||
const completionsDir = '/test/.zsh/completions';
|
||||
|
||||
it('should create .zshrc with markers and config when file does not exist', async () => {
|
||||
const result = await installer.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(content).toContain('# OPENSPEC:START');
|
||||
expect(content).toContain('# OPENSPEC:END');
|
||||
expect(content).toContain('# OpenSpec shell completions configuration');
|
||||
expect(content).toContain(`fpath=("${completionsDir}" $fpath)`);
|
||||
expect(content).toContain('autoload -Uz compinit');
|
||||
expect(content).toContain('compinit');
|
||||
});
|
||||
|
||||
it('should prepend markers and config when .zshrc exists without markers', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
await fs.writeFile(zshrcPath, '# My custom zsh config\nalias ll="ls -la"\n');
|
||||
|
||||
const result = await installer.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(content).toContain('# OPENSPEC:START');
|
||||
expect(content).toContain('# OPENSPEC:END');
|
||||
expect(content).toContain('# My custom zsh config');
|
||||
expect(content).toContain('alias ll="ls -la"');
|
||||
|
||||
// Config should be before existing content
|
||||
const configIndex = content.indexOf('# OPENSPEC:START');
|
||||
const aliasIndex = content.indexOf('alias ll');
|
||||
expect(configIndex).toBeLessThan(aliasIndex);
|
||||
});
|
||||
|
||||
it('should update config between markers when .zshrc has existing markers', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const initialContent = [
|
||||
'# OPENSPEC:START',
|
||||
'# Old config',
|
||||
'fpath=(/old/path $fpath)',
|
||||
'# OPENSPEC:END',
|
||||
'',
|
||||
'# My custom config',
|
||||
].join('\n');
|
||||
|
||||
await fs.writeFile(zshrcPath, initialContent);
|
||||
|
||||
const result = await installer.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(content).toContain('# OPENSPEC:START');
|
||||
expect(content).toContain('# OPENSPEC:END');
|
||||
expect(content).toContain(`fpath=("${completionsDir}" $fpath)`);
|
||||
expect(content).not.toContain('# Old config');
|
||||
expect(content).not.toContain('/old/path');
|
||||
expect(content).toContain('# My custom config');
|
||||
});
|
||||
|
||||
it('should preserve user content outside markers', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const userContent = [
|
||||
'# My zsh config',
|
||||
'export PATH="/custom/path:$PATH"',
|
||||
'',
|
||||
'# OPENSPEC:START',
|
||||
'# Old OpenSpec config',
|
||||
'# OPENSPEC:END',
|
||||
'',
|
||||
'alias ls="ls -G"',
|
||||
].join('\n');
|
||||
|
||||
await fs.writeFile(zshrcPath, userContent);
|
||||
|
||||
const result = await installer.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(content).toContain('# My zsh config');
|
||||
expect(content).toContain('export PATH="/custom/path:$PATH"');
|
||||
expect(content).toContain('alias ls="ls -G"');
|
||||
expect(content).toContain(`fpath=("${completionsDir}" $fpath)`);
|
||||
expect(content).not.toContain('# Old OpenSpec config');
|
||||
});
|
||||
|
||||
it('should return false when OPENSPEC_NO_AUTO_CONFIG is set', async () => {
|
||||
const originalEnv = process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = '1';
|
||||
|
||||
const result = await installer.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(false);
|
||||
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const exists = await fs.access(zshrcPath).then(() => true).catch(() => false);
|
||||
expect(exists).toBe(false);
|
||||
|
||||
// Restore env
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
} else {
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle write permission errors gracefully', async () => {
|
||||
// Create installer with path that can't be written
|
||||
// Use a path that will fail on both Unix and Windows
|
||||
const invalidPath = process.platform === 'win32'
|
||||
? 'Z:\\nonexistent\\invalid\\path' // Non-existent drive letter on Windows
|
||||
: '/root/invalid/path'; // Permission-denied path on Unix
|
||||
const invalidInstaller = new ZshInstaller(invalidPath);
|
||||
|
||||
const result = await invalidInstaller.configureZshrc(completionsDir);
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeZshrcConfig', () => {
|
||||
it('should return true when .zshrc does not exist', async () => {
|
||||
const result = await installer.removeZshrcConfig();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true when .zshrc exists but has no markers', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
await fs.writeFile(zshrcPath, '# My custom config\nalias ll="ls -la"\n');
|
||||
|
||||
const result = await installer.removeZshrcConfig();
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
// Content should be unchanged
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
expect(content).toBe('# My custom config\nalias ll="ls -la"\n');
|
||||
});
|
||||
|
||||
it('should remove markers and config when present', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const content = [
|
||||
'# My config',
|
||||
'',
|
||||
'# OPENSPEC:START',
|
||||
'# OpenSpec shell completions configuration',
|
||||
'fpath=(~/.zsh/completions $fpath)',
|
||||
'autoload -Uz compinit',
|
||||
'compinit',
|
||||
'# OPENSPEC:END',
|
||||
'',
|
||||
'alias ll="ls -la"',
|
||||
].join('\n');
|
||||
|
||||
await fs.writeFile(zshrcPath, content);
|
||||
|
||||
const result = await installer.removeZshrcConfig();
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const newContent = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(newContent).not.toContain('# OPENSPEC:START');
|
||||
expect(newContent).not.toContain('# OPENSPEC:END');
|
||||
expect(newContent).not.toContain('OpenSpec shell completions');
|
||||
expect(newContent).toContain('# My config');
|
||||
expect(newContent).toContain('alias ll="ls -la"');
|
||||
});
|
||||
|
||||
it('should remove leading empty lines when markers were at top', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const content = [
|
||||
'# OPENSPEC:START',
|
||||
'# OpenSpec config',
|
||||
'# OPENSPEC:END',
|
||||
'',
|
||||
'# User config below',
|
||||
].join('\n');
|
||||
|
||||
await fs.writeFile(zshrcPath, content);
|
||||
|
||||
const result = await installer.removeZshrcConfig();
|
||||
|
||||
expect(result).toBe(true);
|
||||
|
||||
const newContent = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
// Should not start with empty lines
|
||||
expect(newContent).toBe('# User config below');
|
||||
});
|
||||
|
||||
it('should handle invalid marker placement gracefully', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
|
||||
// End marker before start marker
|
||||
await fs.writeFile(zshrcPath, '# OPENSPEC:END\n# OPENSPEC:START\n');
|
||||
|
||||
const result = await installer.removeZshrcConfig();
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when only one marker is present', async () => {
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
await fs.writeFile(zshrcPath, '# OPENSPEC:START\nsome config\n');
|
||||
|
||||
const result = await installer.removeZshrcConfig();
|
||||
|
||||
// Should return true (markers don't exist as a pair)
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('install with .zshrc auto-configuration', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {}\n';
|
||||
|
||||
it('should auto-configure .zshrc for standard Zsh', async () => {
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.zshrcConfigured).toBe(true);
|
||||
|
||||
// Verify .zshrc was created
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
|
||||
expect(content).toContain('# OPENSPEC:START');
|
||||
expect(content).toContain('fpath=');
|
||||
expect(content).toContain('compinit');
|
||||
});
|
||||
|
||||
it('should configure .zshrc for Oh My Zsh when fpath is missing', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.isOhMyZsh).toBe(true);
|
||||
// Should configure .zshrc if fpath doesn't already include the directory
|
||||
expect(result.zshrcConfigured).toBe(true);
|
||||
|
||||
// Verify .zshrc was created with fpath configuration
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
const exists = await fs.access(zshrcPath).then(() => true).catch(() => false);
|
||||
expect(exists).toBe(true);
|
||||
|
||||
if (exists) {
|
||||
const content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
expect(content).toContain('fpath=');
|
||||
// Check for custom/completions or custom\completions (Windows path separator)
|
||||
expect(content).toMatch(/custom[/\\]completions/);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not include manual instructions when .zshrc was auto-configured', async () => {
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.zshrcConfigured).toBe(true);
|
||||
expect(result.instructions).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include instructions when .zshrc auto-config fails', async () => {
|
||||
const originalEnv = process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = '1';
|
||||
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.zshrcConfigured).toBe(false);
|
||||
expect(result.instructions).toBeDefined();
|
||||
expect(result.instructions!.join('\n')).toContain('fpath');
|
||||
|
||||
// Restore env
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
} else {
|
||||
process.env.OPENSPEC_NO_AUTO_CONFIG = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
it('should update success message when .zshrc is configured', async () => {
|
||||
const result = await installer.install(testScript);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('.zshrc configured');
|
||||
});
|
||||
});
|
||||
|
||||
describe('uninstall with .zshrc cleanup', () => {
|
||||
const testScript = '#compdef openspec\n_openspec() {}\n';
|
||||
|
||||
it('should remove .zshrc config when uninstalling', async () => {
|
||||
// Install first (which creates .zshrc config)
|
||||
await installer.install(testScript);
|
||||
|
||||
// Verify .zshrc was configured
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
let content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
expect(content).toContain('# OPENSPEC:START');
|
||||
|
||||
// Uninstall
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Removed OpenSpec configuration from ~/.zshrc');
|
||||
|
||||
// Verify .zshrc config was removed
|
||||
content = await fs.readFile(zshrcPath, 'utf-8');
|
||||
expect(content).not.toContain('# OPENSPEC:START');
|
||||
});
|
||||
|
||||
it('should not remove .zshrc config for Oh My Zsh users', async () => {
|
||||
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
|
||||
await fs.mkdir(ohMyZshPath, { recursive: true });
|
||||
|
||||
await installer.install(testScript);
|
||||
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).not.toContain('.zshrc');
|
||||
});
|
||||
|
||||
it('should succeed even if only .zshrc config is removed', async () => {
|
||||
// Manually create .zshrc config without installing completion script
|
||||
const zshrcPath = path.join(testHomeDir, '.zshrc');
|
||||
await fs.writeFile(zshrcPath, '# OPENSPEC:START\nconfig\n# OPENSPEC:END\n');
|
||||
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Removed OpenSpec configuration from ~/.zshrc');
|
||||
});
|
||||
|
||||
it('should include both messages when removing script and .zshrc', async () => {
|
||||
await installer.install(testScript);
|
||||
|
||||
const result = await installer.uninstall();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toContain('Completion script removed');
|
||||
expect(result.message).toContain('Removed OpenSpec configuration from ~/.zshrc');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,340 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import {
|
||||
getNestedValue,
|
||||
setNestedValue,
|
||||
deleteNestedValue,
|
||||
coerceValue,
|
||||
formatValueYaml,
|
||||
validateConfig,
|
||||
GlobalConfigSchema,
|
||||
DEFAULT_CONFIG,
|
||||
} from '../../src/core/config-schema.js';
|
||||
|
||||
describe('config-schema', () => {
|
||||
describe('getNestedValue', () => {
|
||||
it('should get a top-level value', () => {
|
||||
const obj = { foo: 'bar' };
|
||||
expect(getNestedValue(obj, 'foo')).toBe('bar');
|
||||
});
|
||||
|
||||
it('should get a nested value with dot notation', () => {
|
||||
const obj = { a: { b: { c: 'deep' } } };
|
||||
expect(getNestedValue(obj, 'a.b.c')).toBe('deep');
|
||||
});
|
||||
|
||||
it('should return undefined for non-existent path', () => {
|
||||
const obj = { foo: 'bar' };
|
||||
expect(getNestedValue(obj, 'baz')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined for non-existent nested path', () => {
|
||||
const obj = { a: { b: 'value' } };
|
||||
expect(getNestedValue(obj, 'a.b.c')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when traversing through null', () => {
|
||||
const obj = { a: null };
|
||||
expect(getNestedValue(obj as Record<string, unknown>, 'a.b')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when traversing through primitive', () => {
|
||||
const obj = { a: 'string' };
|
||||
expect(getNestedValue(obj, 'a.b')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get object values', () => {
|
||||
const obj = { a: { b: 'value' } };
|
||||
expect(getNestedValue(obj, 'a')).toEqual({ b: 'value' });
|
||||
});
|
||||
|
||||
it('should handle array values', () => {
|
||||
const obj = { arr: [1, 2, 3] };
|
||||
expect(getNestedValue(obj, 'arr')).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setNestedValue', () => {
|
||||
it('should set a top-level value', () => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
setNestedValue(obj, 'foo', 'bar');
|
||||
expect(obj.foo).toBe('bar');
|
||||
});
|
||||
|
||||
it('should set a nested value', () => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
setNestedValue(obj, 'a.b.c', 'deep');
|
||||
expect((obj.a as Record<string, unknown>).b).toEqual({ c: 'deep' });
|
||||
});
|
||||
|
||||
it('should create intermediate objects', () => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
setNestedValue(obj, 'x.y.z', 'value');
|
||||
expect(obj).toEqual({ x: { y: { z: 'value' } } });
|
||||
});
|
||||
|
||||
it('should overwrite existing values', () => {
|
||||
const obj: Record<string, unknown> = { a: 'old' };
|
||||
setNestedValue(obj, 'a', 'new');
|
||||
expect(obj.a).toBe('new');
|
||||
});
|
||||
|
||||
it('should overwrite primitive with object when setting nested path', () => {
|
||||
const obj: Record<string, unknown> = { a: 'string' };
|
||||
setNestedValue(obj, 'a.b', 'value');
|
||||
expect(obj.a).toEqual({ b: 'value' });
|
||||
});
|
||||
|
||||
it('should preserve other keys when setting nested value', () => {
|
||||
const obj: Record<string, unknown> = { a: { existing: 'keep' } };
|
||||
setNestedValue(obj, 'a.new', 'added');
|
||||
expect(obj.a).toEqual({ existing: 'keep', new: 'added' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteNestedValue', () => {
|
||||
it('should delete a top-level key', () => {
|
||||
const obj: Record<string, unknown> = { foo: 'bar', baz: 'qux' };
|
||||
const result = deleteNestedValue(obj, 'foo');
|
||||
expect(result).toBe(true);
|
||||
expect(obj).toEqual({ baz: 'qux' });
|
||||
});
|
||||
|
||||
it('should delete a nested key', () => {
|
||||
const obj: Record<string, unknown> = { a: { b: 'value', c: 'keep' } };
|
||||
const result = deleteNestedValue(obj, 'a.b');
|
||||
expect(result).toBe(true);
|
||||
expect(obj.a).toEqual({ c: 'keep' });
|
||||
});
|
||||
|
||||
it('should return false for non-existent key', () => {
|
||||
const obj: Record<string, unknown> = { foo: 'bar' };
|
||||
const result = deleteNestedValue(obj, 'baz');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for non-existent nested path', () => {
|
||||
const obj: Record<string, unknown> = { a: { b: 'value' } };
|
||||
const result = deleteNestedValue(obj, 'a.c');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when intermediate path does not exist', () => {
|
||||
const obj: Record<string, unknown> = { a: 'string' };
|
||||
const result = deleteNestedValue(obj, 'a.b.c');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('coerceValue', () => {
|
||||
it('should coerce "true" to boolean true', () => {
|
||||
expect(coerceValue('true')).toBe(true);
|
||||
});
|
||||
|
||||
it('should coerce "false" to boolean false', () => {
|
||||
expect(coerceValue('false')).toBe(false);
|
||||
});
|
||||
|
||||
it('should coerce integer string to number', () => {
|
||||
expect(coerceValue('42')).toBe(42);
|
||||
});
|
||||
|
||||
it('should coerce float string to number', () => {
|
||||
expect(coerceValue('3.14')).toBe(3.14);
|
||||
});
|
||||
|
||||
it('should coerce negative number string to number', () => {
|
||||
expect(coerceValue('-10')).toBe(-10);
|
||||
});
|
||||
|
||||
it('should keep regular strings as strings', () => {
|
||||
expect(coerceValue('hello')).toBe('hello');
|
||||
});
|
||||
|
||||
it('should keep strings that start with numbers but are not numbers', () => {
|
||||
expect(coerceValue('123abc')).toBe('123abc');
|
||||
});
|
||||
|
||||
it('should keep empty string as string', () => {
|
||||
expect(coerceValue('')).toBe('');
|
||||
});
|
||||
|
||||
it('should keep whitespace-only string as string', () => {
|
||||
expect(coerceValue(' ')).toBe(' ');
|
||||
});
|
||||
|
||||
it('should force string when forceString is true', () => {
|
||||
expect(coerceValue('true', true)).toBe('true');
|
||||
expect(coerceValue('42', true)).toBe('42');
|
||||
expect(coerceValue('hello', true)).toBe('hello');
|
||||
});
|
||||
|
||||
it('should not coerce Infinity to number (not finite)', () => {
|
||||
// Infinity is not a useful config value, so we keep it as string
|
||||
expect(coerceValue('Infinity')).toBe('Infinity');
|
||||
});
|
||||
|
||||
it('should handle scientific notation', () => {
|
||||
expect(coerceValue('1e10')).toBe(1e10);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatValueYaml', () => {
|
||||
it('should format null as "null"', () => {
|
||||
expect(formatValueYaml(null)).toBe('null');
|
||||
});
|
||||
|
||||
it('should format undefined as "null"', () => {
|
||||
expect(formatValueYaml(undefined)).toBe('null');
|
||||
});
|
||||
|
||||
it('should format boolean as string', () => {
|
||||
expect(formatValueYaml(true)).toBe('true');
|
||||
expect(formatValueYaml(false)).toBe('false');
|
||||
});
|
||||
|
||||
it('should format number as string', () => {
|
||||
expect(formatValueYaml(42)).toBe('42');
|
||||
expect(formatValueYaml(3.14)).toBe('3.14');
|
||||
});
|
||||
|
||||
it('should format string as-is', () => {
|
||||
expect(formatValueYaml('hello')).toBe('hello');
|
||||
});
|
||||
|
||||
it('should format empty array as "[]"', () => {
|
||||
expect(formatValueYaml([])).toBe('[]');
|
||||
});
|
||||
|
||||
it('should format empty object as "{}"', () => {
|
||||
expect(formatValueYaml({})).toBe('{}');
|
||||
});
|
||||
|
||||
it('should format object with key-value pairs', () => {
|
||||
const result = formatValueYaml({ foo: 'bar' });
|
||||
expect(result).toBe('foo: bar');
|
||||
});
|
||||
|
||||
it('should format nested objects with indentation', () => {
|
||||
const result = formatValueYaml({ a: { b: 'value' } });
|
||||
expect(result).toContain('a:');
|
||||
expect(result).toContain('b: value');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateConfig', () => {
|
||||
it('should accept valid config with featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: { test: true } });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept empty featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: {} });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept config without featureFlags (uses default)', () => {
|
||||
const result = validateConfig({});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept unknown fields (passthrough)', () => {
|
||||
const result = validateConfig({ featureFlags: {}, unknownField: 'value' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept unknown fields with various types', () => {
|
||||
const result = validateConfig({
|
||||
featureFlags: {},
|
||||
futureStringField: 'value',
|
||||
futureNumberField: 123,
|
||||
futureObjectField: { nested: 'data' },
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject non-boolean values in featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: { test: 'string' } });
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBeDefined();
|
||||
});
|
||||
|
||||
it('should include path in error message for invalid featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: { someFlag: 'notABoolean' } });
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('featureFlags');
|
||||
});
|
||||
|
||||
it('should reject non-object featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: 'string' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('should reject number values in featureFlags', () => {
|
||||
const result = validateConfig({ featureFlags: { flag: 123 } });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config set simulation', () => {
|
||||
// These tests simulate the full config set flow: coerce value → set nested → validate
|
||||
|
||||
it('should accept setting unknown top-level key (forward compatibility)', () => {
|
||||
const config: Record<string, unknown> = { featureFlags: {} };
|
||||
const value = coerceValue('123');
|
||||
setNestedValue(config, 'someFutureKey', value);
|
||||
|
||||
const result = validateConfig(config);
|
||||
expect(result.success).toBe(true);
|
||||
expect(config.someFutureKey).toBe(123);
|
||||
});
|
||||
|
||||
it('should reject setting non-boolean to featureFlags', () => {
|
||||
const config: Record<string, unknown> = { featureFlags: {} };
|
||||
const value = coerceValue('notABoolean'); // stays as string
|
||||
setNestedValue(config, 'featureFlags.someFlag', value);
|
||||
|
||||
const result = validateConfig(config);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('featureFlags');
|
||||
});
|
||||
|
||||
it('should accept setting boolean to featureFlags', () => {
|
||||
const config: Record<string, unknown> = { featureFlags: {} };
|
||||
const value = coerceValue('true'); // coerces to boolean
|
||||
setNestedValue(config, 'featureFlags.newFlag', value);
|
||||
|
||||
const result = validateConfig(config);
|
||||
expect(result.success).toBe(true);
|
||||
expect((config.featureFlags as Record<string, unknown>).newFlag).toBe(true);
|
||||
});
|
||||
|
||||
it('should create featureFlags object when setting nested flag', () => {
|
||||
const config: Record<string, unknown> = {};
|
||||
const value = coerceValue('false');
|
||||
setNestedValue(config, 'featureFlags.experimental', value);
|
||||
|
||||
const result = validateConfig(config);
|
||||
expect(result.success).toBe(true);
|
||||
expect((config.featureFlags as Record<string, unknown>).experimental).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobalConfigSchema', () => {
|
||||
it('should parse valid config', () => {
|
||||
const result = GlobalConfigSchema.safeParse({ featureFlags: { test: true } });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should provide defaults for missing featureFlags', () => {
|
||||
const result = GlobalConfigSchema.parse({});
|
||||
expect(result.featureFlags).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('DEFAULT_CONFIG', () => {
|
||||
it('should have empty featureFlags', () => {
|
||||
expect(DEFAULT_CONFIG.featureFlags).toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
|
||||
import {
|
||||
getGlobalConfigDir,
|
||||
getGlobalConfigPath,
|
||||
getGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
GLOBAL_CONFIG_DIR_NAME,
|
||||
GLOBAL_CONFIG_FILE_NAME
|
||||
} from '../../src/core/global-config.js';
|
||||
|
||||
describe('global-config', () => {
|
||||
let tempDir: string;
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create temp directory for tests
|
||||
tempDir = path.join(os.tmpdir(), `openspec-global-config-test-${Date.now()}`);
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
// Save original env
|
||||
originalEnv = { ...process.env };
|
||||
|
||||
// Spy on console.error for warning tests
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original env
|
||||
process.env = originalEnv;
|
||||
|
||||
// Clean up temp directory
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
// Restore console.error
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe('constants', () => {
|
||||
it('should export correct directory name', () => {
|
||||
expect(GLOBAL_CONFIG_DIR_NAME).toBe('openspec');
|
||||
});
|
||||
|
||||
it('should export correct file name', () => {
|
||||
expect(GLOBAL_CONFIG_FILE_NAME).toBe('config.json');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalConfigDir', () => {
|
||||
it('should use XDG_CONFIG_HOME when set', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
|
||||
const result = getGlobalConfigDir();
|
||||
|
||||
expect(result).toBe(path.join(tempDir, 'openspec'));
|
||||
});
|
||||
|
||||
it('should fall back to ~/.config on Unix/macOS without XDG_CONFIG_HOME', () => {
|
||||
delete process.env.XDG_CONFIG_HOME;
|
||||
|
||||
const result = getGlobalConfigDir();
|
||||
|
||||
// On non-Windows, should use ~/.config/openspec
|
||||
if (os.platform() !== 'win32') {
|
||||
expect(result).toBe(path.join(os.homedir(), '.config', 'openspec'));
|
||||
}
|
||||
});
|
||||
|
||||
it('should use APPDATA on Windows when XDG_CONFIG_HOME is not set', () => {
|
||||
// This test only makes sense conceptually - we can't change os.platform()
|
||||
// But we can verify the APPDATA logic by checking the code path
|
||||
if (os.platform() === 'win32') {
|
||||
delete process.env.XDG_CONFIG_HOME;
|
||||
const appData = process.env.APPDATA;
|
||||
if (appData) {
|
||||
const result = getGlobalConfigDir();
|
||||
expect(result).toBe(path.join(appData, 'openspec'));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalConfigPath', () => {
|
||||
it('should return path to config.json in config directory', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
|
||||
const result = getGlobalConfigPath();
|
||||
|
||||
expect(result).toBe(path.join(tempDir, 'openspec', 'config.json'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalConfig', () => {
|
||||
it('should return defaults when config file does not exist', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
|
||||
const config = getGlobalConfig();
|
||||
|
||||
expect(config).toEqual({ featureFlags: {} });
|
||||
});
|
||||
|
||||
it('should not create directory when reading non-existent config', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
|
||||
getGlobalConfig();
|
||||
|
||||
expect(fs.existsSync(configDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('should load valid config from file', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
featureFlags: { testFlag: true, anotherFlag: false }
|
||||
}));
|
||||
|
||||
const config = getGlobalConfig();
|
||||
|
||||
expect(config.featureFlags).toEqual({ testFlag: true, anotherFlag: false });
|
||||
});
|
||||
|
||||
it('should return defaults for invalid JSON', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, '{ invalid json }');
|
||||
|
||||
const config = getGlobalConfig();
|
||||
|
||||
expect(config).toEqual({ featureFlags: {} });
|
||||
});
|
||||
|
||||
it('should log warning for invalid JSON', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, '{ invalid json }');
|
||||
|
||||
getGlobalConfig();
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Invalid JSON')
|
||||
);
|
||||
});
|
||||
|
||||
it('should preserve unknown fields from config file', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
featureFlags: { x: true },
|
||||
unknownField: 'preserved',
|
||||
futureOption: 123
|
||||
}));
|
||||
|
||||
const config = getGlobalConfig();
|
||||
|
||||
expect((config as any).unknownField).toBe('preserved');
|
||||
expect((config as any).futureOption).toBe(123);
|
||||
});
|
||||
|
||||
it('should merge loaded config with defaults', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
// Config with only some fields
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
featureFlags: { customFlag: true }
|
||||
}));
|
||||
|
||||
const config = getGlobalConfig();
|
||||
|
||||
// Should have the custom flag
|
||||
expect(config.featureFlags?.customFlag).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveGlobalConfig', () => {
|
||||
it('should create directory if it does not exist', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
|
||||
saveGlobalConfig({ featureFlags: { test: true } });
|
||||
|
||||
expect(fs.existsSync(configDir)).toBe(true);
|
||||
});
|
||||
|
||||
it('should write config to file', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configPath = path.join(tempDir, 'openspec', 'config.json');
|
||||
|
||||
saveGlobalConfig({ featureFlags: { myFlag: true } });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.featureFlags.myFlag).toBe(true);
|
||||
});
|
||||
|
||||
it('should overwrite existing config file', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configDir = path.join(tempDir, 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
// Create initial config
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({ featureFlags: { old: true } }));
|
||||
|
||||
// Overwrite
|
||||
saveGlobalConfig({ featureFlags: { new: true } });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.featureFlags.new).toBe(true);
|
||||
expect(parsed.featureFlags.old).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should write formatted JSON with trailing newline', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const configPath = path.join(tempDir, 'openspec', 'config.json');
|
||||
|
||||
saveGlobalConfig({ featureFlags: {} });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
expect(content).toContain('\n');
|
||||
expect(content.endsWith('\n')).toBe(true);
|
||||
});
|
||||
|
||||
it('should round-trip config correctly', () => {
|
||||
process.env.XDG_CONFIG_HOME = tempDir;
|
||||
const originalConfig = {
|
||||
featureFlags: { flag1: true, flag2: false }
|
||||
};
|
||||
|
||||
saveGlobalConfig(originalConfig);
|
||||
const loadedConfig = getGlobalConfig();
|
||||
|
||||
expect(loadedConfig.featureFlags).toEqual(originalConfig.featureFlags);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -492,21 +492,21 @@ describe('InitCommand', () => {
|
||||
expect(await fileExists(openCodeArchive)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(openCodeProposal, 'utf-8');
|
||||
expect(proposalContent).toContain('agent: build');
|
||||
expect(proposalContent).not.toContain('agent:');
|
||||
expect(proposalContent).toContain(
|
||||
'description: Scaffold a new OpenSpec change and validate strictly.'
|
||||
);
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
|
||||
const applyContent = await fs.readFile(openCodeApply, 'utf-8');
|
||||
expect(applyContent).toContain('agent: build');
|
||||
expect(applyContent).not.toContain('agent:');
|
||||
expect(applyContent).toContain(
|
||||
'description: Implement an approved OpenSpec change and keep tasks in sync.'
|
||||
);
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(openCodeArchive, 'utf-8');
|
||||
expect(archiveContent).toContain('agent: build');
|
||||
expect(archiveContent).not.toContain('agent:');
|
||||
expect(archiveContent).toContain(
|
||||
'description: Archive a deployed OpenSpec change and update specs.'
|
||||
);
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { detectShell, SupportedShell } from '../../src/utils/shell-detection.js';
|
||||
|
||||
describe('shell-detection', () => {
|
||||
let originalShell: string | undefined;
|
||||
let originalPSModulePath: string | undefined;
|
||||
let originalComspec: string | undefined;
|
||||
let originalPlatform: NodeJS.Platform;
|
||||
|
||||
beforeEach(() => {
|
||||
// Save original environment
|
||||
originalShell = process.env.SHELL;
|
||||
originalPSModulePath = process.env.PSModulePath;
|
||||
originalComspec = process.env.COMSPEC;
|
||||
originalPlatform = process.platform;
|
||||
|
||||
// Clear environment for clean testing
|
||||
delete process.env.SHELL;
|
||||
delete process.env.PSModulePath;
|
||||
delete process.env.COMSPEC;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original environment
|
||||
if (originalShell !== undefined) {
|
||||
process.env.SHELL = originalShell;
|
||||
} else {
|
||||
delete process.env.SHELL;
|
||||
}
|
||||
if (originalPSModulePath !== undefined) {
|
||||
process.env.PSModulePath = originalPSModulePath;
|
||||
} else {
|
||||
delete process.env.PSModulePath;
|
||||
}
|
||||
if (originalComspec !== undefined) {
|
||||
process.env.COMSPEC = originalComspec;
|
||||
} else {
|
||||
delete process.env.COMSPEC;
|
||||
}
|
||||
Object.defineProperty(process, 'platform', {
|
||||
value: originalPlatform,
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectShell', () => {
|
||||
it('should detect zsh from SHELL environment variable', () => {
|
||||
process.env.SHELL = '/bin/zsh';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('zsh');
|
||||
expect(result.detected).toBe('zsh');
|
||||
});
|
||||
|
||||
it('should detect zsh from various zsh paths', () => {
|
||||
const zshPaths = [
|
||||
'/usr/bin/zsh',
|
||||
'/usr/local/bin/zsh',
|
||||
'/opt/homebrew/bin/zsh',
|
||||
'/home/user/.local/bin/zsh',
|
||||
];
|
||||
|
||||
for (const path of zshPaths) {
|
||||
process.env.SHELL = path;
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('zsh');
|
||||
expect(result.detected).toBe('zsh');
|
||||
}
|
||||
});
|
||||
|
||||
it('should detect bash from SHELL environment variable', () => {
|
||||
process.env.SHELL = '/bin/bash';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('bash');
|
||||
expect(result.detected).toBe('bash');
|
||||
});
|
||||
|
||||
it('should detect bash from various bash paths', () => {
|
||||
const bashPaths = [
|
||||
'/usr/bin/bash',
|
||||
'/usr/local/bin/bash',
|
||||
'/opt/homebrew/bin/bash',
|
||||
'/home/user/.local/bin/bash',
|
||||
];
|
||||
|
||||
for (const path of bashPaths) {
|
||||
process.env.SHELL = path;
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('bash');
|
||||
expect(result.detected).toBe('bash');
|
||||
}
|
||||
});
|
||||
|
||||
it('should detect fish from SHELL environment variable', () => {
|
||||
process.env.SHELL = '/usr/bin/fish';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('fish');
|
||||
expect(result.detected).toBe('fish');
|
||||
});
|
||||
|
||||
it('should detect fish from various fish paths', () => {
|
||||
const fishPaths = [
|
||||
'/bin/fish',
|
||||
'/usr/local/bin/fish',
|
||||
'/opt/homebrew/bin/fish',
|
||||
'/home/user/.local/bin/fish',
|
||||
];
|
||||
|
||||
for (const path of fishPaths) {
|
||||
process.env.SHELL = path;
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('fish');
|
||||
expect(result.detected).toBe('fish');
|
||||
}
|
||||
});
|
||||
|
||||
it('should be case-insensitive when detecting shell', () => {
|
||||
process.env.SHELL = '/BIN/ZSH';
|
||||
let result = detectShell();
|
||||
expect(result.shell).toBe('zsh');
|
||||
|
||||
process.env.SHELL = '/USR/BIN/BASH';
|
||||
result = detectShell();
|
||||
expect(result.shell).toBe('bash');
|
||||
|
||||
process.env.SHELL = '/USR/BIN/FISH';
|
||||
result = detectShell();
|
||||
expect(result.shell).toBe('fish');
|
||||
});
|
||||
|
||||
it('should detect PowerShell from PSModulePath environment variable', () => {
|
||||
process.env.PSModulePath = 'C:\\Program Files\\PowerShell\\Modules';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('powershell');
|
||||
expect(result.detected).toBe('powershell');
|
||||
});
|
||||
|
||||
it('should detect PowerShell on Windows platform with PSModulePath', () => {
|
||||
Object.defineProperty(process, 'platform', {
|
||||
value: 'win32',
|
||||
});
|
||||
process.env.PSModulePath = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBe('powershell');
|
||||
expect(result.detected).toBe('powershell');
|
||||
});
|
||||
|
||||
it('should return detected name for unsupported shell', () => {
|
||||
process.env.SHELL = '/bin/tcsh';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBeUndefined();
|
||||
expect(result.detected).toBe('tcsh');
|
||||
});
|
||||
|
||||
it('should return undefined when SHELL is not set and not on Windows', () => {
|
||||
Object.defineProperty(process, 'platform', {
|
||||
value: 'linux',
|
||||
});
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBeUndefined();
|
||||
expect(result.detected).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return detected name for cmd.exe on Windows', () => {
|
||||
Object.defineProperty(process, 'platform', {
|
||||
value: 'win32',
|
||||
});
|
||||
process.env.COMSPEC = 'C:\\Windows\\System32\\cmd.exe';
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBeUndefined();
|
||||
expect(result.detected).toBe('cmd.exe');
|
||||
});
|
||||
|
||||
it('should return undefined when no shell information is available', () => {
|
||||
const result = detectShell();
|
||||
expect(result.shell).toBeUndefined();
|
||||
expect(result.detected).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SupportedShell type', () => {
|
||||
it('should accept valid shell types', () => {
|
||||
const shells: SupportedShell[] = ['zsh', 'bash', 'fish', 'powershell'];
|
||||
expect(shells).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user