🪝Hooks: Exclude .clinerules/hooks/ files from Rules feature (#7202)

* Exclude .clinerules/hooks/ files from Rules feature

* Escape whitespace in paths correctly when discovering hooks/ directories
This commit is contained in:
CandiedUniverse authored and GitHub committed 2025-10-31 10:18:51 -07:00
1 parent c7afb61e28
commit 36022438cb
8 files changed
+442 -29

No files matched your search

+19 -19
View File
@@ -3,7 +3,7 @@
## Overview
Cline hooks allow you to execute custom scripts at specific points in the agentic workflow. Hooks can be placed in either:
- **Global hooks directory**: `~/Documents/Cline/Rules/Hooks/` (applies to all workspaces)
- **Global hooks directory**: `~/Documents/Cline/Hooks/` (applies to all workspaces)
- **Workspace hooks directory**: `.clinerules/hooks/` (applies to specific workspace)
Hooks run automatically when enabled.
@@ -20,50 +20,50 @@ Hooks run automatically when enabled.
### TaskStart Hook
- **When**: Runs when a NEW task is started (not when resuming)
- **Purpose**: Initialize task context, validate task requirements, set up environment
- **Global Location**: `~/Documents/Cline/Rules/Hooks/TaskStart` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/TaskStart` (all platforms)
- **Workspace Location**: `.clinerules/hooks/TaskStart` (all platforms)
### TaskResume Hook
- **When**: Runs when an EXISTING task is resumed (after user clicks resume button)
- **Purpose**: Validate resumed task state, restore context, check for changes since last run
- **Global Location**: `~/Documents/Cline/Rules/Hooks/TaskResume` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/TaskResume` (all platforms)
- **Workspace Location**: `.clinerules/hooks/TaskResume` (all platforms)
### TaskCancel Hook
- **When**: Runs when a task is cancelled by the user (only if there's actual active work or work was started)
- **Purpose**: Clean up resources, log cancellation, save state
- **Global Location**: `~/Documents/Cline/Rules/Hooks/TaskCancel` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/TaskCancel` (all platforms)
- **Workspace Location**: `.clinerules/hooks/TaskCancel` (all platforms)
- **Note**: This hook is NOT cancellable and will complete even if the task is being aborted
### TaskComplete Hook
- **When**: Runs when a task is marked as complete
- **Purpose**: Log completion status, perform final cleanup, generate reports
- **Global Location**: `~/Documents/Cline/Rules/Hooks/TaskComplete` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/TaskComplete` (all platforms)
- **Workspace Location**: `.clinerules/hooks/TaskComplete` (all platforms)
### UserPromptSubmit Hook
- **When**: Runs when the user submits a prompt/message (initial task, resume, or feedback)
- **Purpose**: Validate user input, preprocess prompts, add context to user messages
- **Global Location**: `~/Documents/Cline/Rules/Hooks/UserPromptSubmit` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/UserPromptSubmit` (all platforms)
- **Workspace Location**: `.clinerules/hooks/UserPromptSubmit` (all platforms)
### PreToolUse Hook
- **When**: Runs BEFORE a tool is executed
- **Purpose**: Validate parameters, block execution, or add context
- **Global Location**: `~/Documents/Cline/Rules/Hooks/PreToolUse` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/PreToolUse` (all platforms)
- **Workspace Location**: `.clinerules/hooks/PreToolUse` (all platforms)
### PostToolUse Hook
- **When**: Runs AFTER a tool completes
- **Purpose**: Observe results, track patterns, or add context
- **Global Location**: `~/Documents/Cline/Rules/Hooks/PostToolUse` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/PostToolUse` (all platforms)
- **Workspace Location**: `.clinerules/hooks/PostToolUse` (all platforms)
### PreCompact Hook
- **When**: Runs BEFORE the conversation context is compacted/truncated
- **Purpose**: Observe compaction events, log context management, track token usage
- **Global Location**: `~/Documents/Cline/Rules/Hooks/PreCompact` (all platforms)
- **Global Location**: `~/Documents/Cline/Hooks/PreCompact` (all platforms)
- **Workspace Location**: `.clinerules/hooks/PreCompact` (all platforms)
## Cross-Platform Hook Format
@@ -92,16 +92,16 @@ This means:
**On Unix/Linux/macOS:**
```bash
# Create hook file
nano ~/Documents/Cline/Rules/Hooks/PreToolUse
nano ~/Documents/Cline/Hooks/PreToolUse
# Make executable
chmod +x ~/Documents/Cline/Rules/Hooks/PreToolUse
chmod +x ~/Documents/Cline/Hooks/PreToolUse
```
**On Windows:**
```batch
REM Create hook file (note: no file extension)
notepad %USERPROFILE%\Documents\Cline\Rules\Hooks\PreToolUse
notepad %USERPROFILE%\Documents\Cline\Hooks\PreToolUse
```
## Context Injection Timing
@@ -328,7 +328,7 @@ echo '{"cancel": false}'
Cline supports two levels of hooks:
### Global Hooks
- **Location**: `~/Documents/Cline/Rules/Hooks/` (macOS/Linux) or `%USERPROFILE%\Documents\Cline\Rules\Hooks\` (Windows)
- **Location**: `~/Documents/Cline/Hooks/` (macOS/Linux) or `%USERPROFILE%\Documents\Cline\Hooks\` (Windows)
- **Scope**: Apply to ALL workspaces and projects
- **Use Case**: Organization-wide policies, personal preferences, universal validations
- **Priority**: Order not guaranteed when combined with workspace hooks
@@ -355,17 +355,17 @@ When multiple hooks exist (global and/or workspace):
### Setting Up Global Hooks
1. The global hooks directory is automatically created at:
- macOS/Linux: `~/Documents/Cline/Rules/Hooks/`
- Windows: `%USERPROFILE%\Documents\Cline\Rules\Hooks\`
- macOS/Linux: `~/Documents/Cline/Hooks/`
- Windows: `%USERPROFILE%\Documents\Cline\Hooks\`
2. Add your hook script:
```bash
# Unix/Linux/macOS
nano ~/Documents/Cline/Rules/Hooks/PreToolUse
chmod +x ~/Documents/Cline/Rules/Hooks/PreToolUse
nano ~/Documents/Cline/Hooks/PreToolUse
chmod +x ~/Documents/Cline/Hooks/PreToolUse
# Windows
notepad %USERPROFILE%\Documents\Cline\Rules\Hooks\PreToolUse
notepad %USERPROFILE%\Documents\Cline\Hooks\PreToolUse
```
3. Enable hooks in Cline settings
@@ -375,7 +375,7 @@ When multiple hooks exist (global and/or workspace):
**Global Hook** (applies to all projects):
```bash
#!/usr/bin/env bash
# ~/Documents/Cline/Rules/Hooks/PreToolUse
# ~/Documents/Cline/Hooks/PreToolUse
# Universal rule: Never delete package.json
input=$(cat)
tool_name=$(echo "$input" | jq -r '.preToolUse.toolName')
@@ -40,7 +40,10 @@ export const getLocalClineRules = async (cwd: string, toggles: ClineRulesToggles
if (await fileExistsAtPath(clineRulesFilePath)) {
if (await isDirectory(clineRulesFilePath)) {
try {
const rulesFilePaths = await readDirectory(clineRulesFilePath, [[".clinerules", "workflows"]])
const rulesFilePaths = await readDirectory(clineRulesFilePath, [
[".clinerules", "workflows"],
[".clinerules", "hooks"],
])
const rulesFilesTotalContent = await getRuleFilesTotalContent(rulesFilePaths, cwd, toggles)
if (rulesFilesTotalContent) {
@@ -84,6 +87,7 @@ export async function refreshClineRulesToggles(
const localClineRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.clineRules)
const updatedLocalToggles = await synchronizeRuleToggles(localClineRulesFilePath, localClineRulesToggles, "", [
[".clinerules", "workflows"],
[".clinerules", "hooks"],
])
controller.stateManager.setWorkspaceState("localClineRulesToggles", updatedLocalToggles)
+3 -1
View File
@@ -1,6 +1,7 @@
import { ChildProcess, spawn } from "child_process"
import { EventEmitter } from "events"
import { HookProcessRegistry } from "./HookProcessRegistry"
import { escapeShellPath } from "./shell-escape"
// Maximum total output size (stdout + stderr combined)
const MAX_HOOK_OUTPUT_SIZE = 1024 * 1024 // 1MB
@@ -101,7 +102,8 @@ export class HookProcess extends EventEmitter {
// This is the git-style approach: the shell interprets the shebang line
// and executes the appropriate interpreter (bash, node, python, etc.)
// On Unix: detached=true creates a process group, allowing us to kill all children
this.childProcess = spawn(this.scriptPath, [], {
const escapedScriptPath = escapeShellPath(this.scriptPath)
this.childProcess = spawn(escapedScriptPath, [], {
stdio: ["pipe", "pipe", "pipe"],
shell: true, // Use shell on all platforms for shebang interpretation
detached: process.platform !== "win32", // Create process group on Unix
@@ -0,0 +1,285 @@
import { describe, it } from "mocha"
import "should"
import { escapeShellPath } from "../shell-escape"
describe("Shell Path Escaping", () => {
const originalPlatform = process.platform
// Helper to temporarily set platform
const setPlatform = (platform: NodeJS.Platform) => {
Object.defineProperty(process, "platform", {
value: platform,
writable: true,
configurable: true,
})
}
// Restore platform after tests
after(() => {
Object.defineProperty(process, "platform", {
value: originalPlatform,
writable: true,
configurable: true,
})
})
describe("Unix/Linux/macOS path escaping", () => {
before(() => {
setPlatform("darwin") // macOS, but same escaping as Linux
})
it("should handle paths without special characters", () => {
const path = "/Users/user/Documents/Cline/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Documents/Cline/Hooks/PreToolUse'")
})
it("should handle paths with spaces", () => {
const path = "/Users/user/My Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/My Project/Hooks/PreToolUse'")
})
it("should handle paths with multiple spaces", () => {
const path = "/Users/user/My Test Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/My Test Project/Hooks/PreToolUse'")
})
it("should handle paths with single quotes", () => {
const path = "/Users/user/Test's Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
// Single quote is escaped as '\'' (close quote, escaped quote, open quote)
escaped.should.equal("'/Users/user/Test'\\''s Project/Hooks/PreToolUse'")
})
it("should handle paths with multiple single quotes", () => {
const path = "/Users/user/Test's Project's Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test'\\''s Project'\\''s Hooks/PreToolUse'")
})
it("should handle paths with double quotes", () => {
const path = '/Users/user/Test "Quoted" Project/Hooks/PreToolUse'
const escaped = escapeShellPath(path)
// Double quotes are safe inside single quotes
escaped.should.equal("'/Users/user/Test \"Quoted\" Project/Hooks/PreToolUse'")
})
it("should handle paths with special shell characters", () => {
const path = "/Users/user/Test$Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
// Special characters like $ are safe inside single quotes
escaped.should.equal("'/Users/user/Test$Project/Hooks/PreToolUse'")
})
it("should handle paths with backticks", () => {
const path = "/Users/user/Test`Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
// Backticks are safe inside single quotes
escaped.should.equal("'/Users/user/Test`Project/Hooks/PreToolUse'")
})
it("should handle paths with parentheses", () => {
const path = "/Users/user/Test (Project)/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test (Project)/Hooks/PreToolUse'")
})
it("should handle paths with ampersands", () => {
const path = "/Users/user/Test & Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test & Project/Hooks/PreToolUse'")
})
it("should handle paths with semicolons", () => {
const path = "/Users/user/Test;Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test;Project/Hooks/PreToolUse'")
})
it("should handle paths with pipes", () => {
const path = "/Users/user/Test|Project/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test|Project/Hooks/PreToolUse'")
})
it("should handle global hooks directory with spaces", () => {
const path = "/Users/user name/Documents/Cline/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user name/Documents/Cline/Hooks/PreToolUse'")
})
it("should handle workspace hooks with spaces in root", () => {
const path = "/Users/user/My Example Project/.clinerules/hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/My Example Project/.clinerules/hooks/PreToolUse'")
})
it("should handle paths with newlines (edge case)", () => {
const path = "/Users/user/Test\nProject/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
// Newlines are safe inside single quotes
escaped.should.equal("'/Users/user/Test\nProject/Hooks/PreToolUse'")
})
it("should handle paths with tabs", () => {
const path = "/Users/user/Test\tProject/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Test\tProject/Hooks/PreToolUse'")
})
})
describe("Windows path escaping", () => {
before(() => {
setPlatform("win32")
})
it("should handle paths without special characters", () => {
const path = "C:\\Users\\user\\Documents\\Cline\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\Documents\\Cline\\Hooks\\PreToolUse"')
})
it("should handle paths with spaces", () => {
const path = "C:\\Users\\user\\My Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\My Project\\Hooks\\PreToolUse"')
})
it("should handle paths with multiple spaces", () => {
const path = "C:\\Users\\user\\My Test Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\My Test Project\\Hooks\\PreToolUse"')
})
it("should handle paths with double quotes", () => {
const path = 'C:\\Users\\user\\Test "Quoted" Project\\Hooks\\PreToolUse'
const escaped = escapeShellPath(path)
// Double quotes are escaped by doubling them
escaped.should.equal('"C:\\Users\\user\\Test ""Quoted"" Project\\Hooks\\PreToolUse"')
})
it("should handle paths with backslashes before quotes", () => {
const path = 'C:\\Users\\user\\Test\\"Project\\Hooks\\PreToolUse'
const escaped = escapeShellPath(path)
// Backslash before quote needs to be doubled, then quote is doubled
escaped.should.equal('"C:\\Users\\user\\Test\\\\""Project\\Hooks\\PreToolUse"')
})
it("should handle paths with single quotes", () => {
const path = "C:\\Users\\user\\Test's Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
// Single quotes are safe inside double quotes on Windows
escaped.should.equal('"C:\\Users\\user\\Test\'s Project\\Hooks\\PreToolUse"')
})
it("should handle paths with special characters", () => {
const path = "C:\\Users\\user\\Test$Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
// Most special characters are safe inside double quotes on Windows
escaped.should.equal('"C:\\Users\\user\\Test$Project\\Hooks\\PreToolUse"')
})
it("should handle paths with parentheses", () => {
const path = "C:\\Users\\user\\Test (Project)\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\Test (Project)\\Hooks\\PreToolUse"')
})
it("should handle paths with ampersands", () => {
const path = "C:\\Users\\user\\Test & Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\Test & Project\\Hooks\\PreToolUse"')
})
it("should handle global hooks directory with spaces", () => {
const path = "C:\\Users\\user name\\Documents\\Cline\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user name\\Documents\\Cline\\Hooks\\PreToolUse"')
})
it("should handle workspace hooks with spaces in root", () => {
const path = "C:\\Users\\user\\My Example Project\\.clinerules\\hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\user\\My Example Project\\.clinerules\\hooks\\PreToolUse"')
})
it("should handle UNC paths with spaces", () => {
const path = "\\\\server\\share\\My Project\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"\\\\server\\share\\My Project\\Hooks\\PreToolUse"')
})
})
describe("Real-world scenarios", () => {
it("should handle typical macOS global hooks path with space in username", () => {
setPlatform("darwin")
const path = "/Users/John Doe/Documents/Cline/Hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/John Doe/Documents/Cline/Hooks/PreToolUse'")
})
it("should handle typical Windows global hooks path with space in username", () => {
setPlatform("win32")
const path = "C:\\Users\\John Doe\\Documents\\Cline\\Hooks\\PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal('"C:\\Users\\John Doe\\Documents\\Cline\\Hooks\\PreToolUse"')
})
it("should handle workspace with company name and spaces", () => {
setPlatform("darwin")
const path = "/Users/user/Projects/ACME Corp Project/.clinerules/hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Projects/ACME Corp Project/.clinerules/hooks/PreToolUse'")
})
it("should handle workspace with version numbers and spaces", () => {
setPlatform("darwin")
const path = "/Users/user/Projects/My Project v2.0/.clinerules/hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Projects/My Project v2.0/.clinerules/hooks/PreToolUse'")
})
it("should handle workspace with mixed special characters", () => {
setPlatform("darwin")
const path = "/Users/user/Projects/Test's (New) Project v2.0/.clinerules/hooks/PreToolUse"
const escaped = escapeShellPath(path)
escaped.should.equal("'/Users/user/Projects/Test'\\''s (New) Project v2.0/.clinerules/hooks/PreToolUse'")
})
})
describe("Multi-root workspace scenarios", () => {
it("should handle multiple roots with spaces (macOS)", () => {
setPlatform("darwin")
const roots = [
"/Users/user/My Frontend Project/.clinerules/hooks/PreToolUse",
"/Users/user/My Backend Project/.clinerules/hooks/PreToolUse",
"/Users/user/Shared Utils/.clinerules/hooks/PreToolUse",
]
const escaped = roots.map(escapeShellPath)
escaped.should.deepEqual([
"'/Users/user/My Frontend Project/.clinerules/hooks/PreToolUse'",
"'/Users/user/My Backend Project/.clinerules/hooks/PreToolUse'",
"'/Users/user/Shared Utils/.clinerules/hooks/PreToolUse'",
])
})
it("should handle multiple roots with spaces (Windows)", () => {
setPlatform("win32")
const roots = [
"C:\\Users\\user\\My Frontend Project\\.clinerules\\hooks\\PreToolUse",
"C:\\Users\\user\\My Backend Project\\.clinerules\\hooks\\PreToolUse",
"C:\\Users\\user\\Shared Utils\\.clinerules\\hooks\\PreToolUse",
]
const escaped = roots.map(escapeShellPath)
escaped.should.deepEqual([
'"C:\\Users\\user\\My Frontend Project\\.clinerules\\hooks\\PreToolUse"',
'"C:\\Users\\user\\My Backend Project\\.clinerules\\hooks\\PreToolUse"',
'"C:\\Users\\user\\Shared Utils\\.clinerules\\hooks\\PreToolUse"',
])
})
})
})
+2 -2
View File
@@ -400,7 +400,7 @@ class StdioHookRunner<Name extends HookName> extends HookRunner<Name> {
/**
* Combines multiple hook runners and executes them in parallel.
*
* Used in multi-root workspaces where both global hooks (from ~/Documents/Cline/Rules/Hooks/)
* Used in multi-root workspaces where both global hooks (from ~/Documents/Cline/Hooks/)
* and workspace-specific hooks (from each workspace's .clinerules/hooks/) exist for the
* same hook type.
*
@@ -537,7 +537,7 @@ export class HookFactory {
/**
* @returns A list of paths to scripts for the given hook name.
* Includes both global hooks (from ~/Documents/Cline/Rules/Hooks/) and workspace hooks
* Includes both global hooks (from ~/Documents/Cline/Hooks/) and workspace hooks
* (from .clinerules/hooks/ in each workspace root).
*/
private static async findHookScripts(hookName: HookName): Promise<string[]> {
+67
View File
@@ -0,0 +1,67 @@
/**
* Platform-specific shell escaping utilities for hook script paths.
* Ensures paths with spaces and special characters work correctly when
* executed through a shell (shell: true in spawn).
*/
/**
* Escapes a path for safe use in a Windows shell command.
* Handles spaces, quotes, and other special characters.
*
* Windows shell (cmd.exe) rules:
* - Wrap path in double quotes
* - Escape double quotes by doubling them ("")
* - Backslashes before quotes need to be doubled
*
* @param path The file path to escape
* @returns The escaped path safe for Windows shell execution
*/
function escapeWindowsShellPath(path: string): string {
// Escape backslashes that precede quotes
let escaped = path.replace(/\\"/g, '\\\\"')
// Escape standalone double quotes by doubling them
escaped = escaped.replace(/"/g, '""')
// Wrap in double quotes
return `"${escaped}"`
}
/**
* Escapes a path for safe use in a Unix shell command (sh, bash, zsh).
* Handles spaces, quotes, apostrophes, and other special characters.
*
* Unix shell rules:
* - Wrap path in single quotes (safest for most characters)
* - Single quotes inside path are escaped as '\''
* (close quote, escaped quote, open quote)
*
* @param path The file path to escape
* @returns The escaped path safe for Unix shell execution
*/
function escapeUnixShellPath(path: string): string {
// Replace single quotes with '\'' (close quote, escaped quote, open quote)
const escaped = path.replace(/'/g, "'\\''")
// Wrap in single quotes
return `'${escaped}'`
}
/**
* Escapes a file path for safe shell execution on any platform.
* This is critical when using spawn() with shell: true and paths that
* may contain spaces or special characters.
*
* Use cases:
* - Global hooks directory: ~/Documents/Cline/Hooks/
* - Workspace hooks: /path/to/My Project/.clinerules/hooks/
* - Multi-root workspaces: each root's .clinerules/hooks/
*
* Examples:
* - "/Users/user/My Project/hooks/PreToolUse" → "'/Users/user/My Project/hooks/PreToolUse'"
* - "C:\Users\user\My Project\hooks\PreToolUse" → '"C:\Users\user\My Project\hooks\PreToolUse"'
* - "/path/with 'quotes'/hooks/PreToolUse" → "'/path/with '\''quotes'\'' /hooks/PreToolUse'"
*
* @param path The file path to escape
* @returns The escaped path safe for shell execution on the current platform
*/
export function escapeShellPath(path: string): string {
return process.platform === "win32" ? escapeWindowsShellPath(path) : escapeUnixShellPath(path)
}
+4 -6
View File
@@ -107,16 +107,14 @@ export async function ensureMcpServersDirectoryExists(): Promise<string> {
}
export async function ensureHooksDirectoryExists(): Promise<string> {
const rulesDir = await ensureRulesDirectoryExists()
const clineHooksDir = path.join(rulesDir, "Hooks")
const userDocumentsPath = await getDocumentsPath()
const clineHooksDir = path.join(userDocumentsPath, "Cline", "Hooks")
try {
await fs.mkdir(clineHooksDir, { recursive: true })
return clineHooksDir
} catch (_error) {
// If mkdir fails, return a fallback path based on the Rules directory fallback
// This matches the pattern of other ensure*DirectoryExists functions
return path.join(rulesDir, "Hooks")
return path.join(os.homedir(), "Documents", "Cline", "Hooks") // in case creating a directory in documents fails for whatever reason (e.g. permissions) - this is fine because we will fail gracefully with a path that does not exist
}
return clineHooksDir
}
export async function ensureSettingsDirectoryExists(): Promise<string> {
+57
View File
@@ -256,4 +256,61 @@ describe("Filesystem Utilities", () => {
multiExcludeFiles.sort().should.deepEqual(rootOnlyFiles.sort())
})
it("should exclude .clinerules/hooks directory specifically", async () => {
// Create a test directory structure
const clinerulesDirTest = path.join(tmpDir, "clinerules-hooks-test")
const clinerulesDirPath = path.join(clinerulesDirTest, ".clinerules")
// Create .clinerules directory and root files
await fs.mkdir(clinerulesDirPath, { recursive: true })
await fs.writeFile(path.join(clinerulesDirPath, "config.json"), "{}")
await fs.writeFile(path.join(clinerulesDirPath, "settings.js"), "// settings")
// Create .clinerules/workflows directory and files
const workflowsDirPath = path.join(clinerulesDirPath, "workflows")
await fs.mkdir(workflowsDirPath, { recursive: true })
await fs.writeFile(path.join(workflowsDirPath, "workflow1.js"), "// workflow1")
// Create .clinerules/hooks directory and files
const hooksDirPath = path.join(clinerulesDirPath, "hooks")
await fs.mkdir(hooksDirPath, { recursive: true })
await fs.writeFile(path.join(hooksDirPath, "PreToolUse"), "#!/usr/bin/env bash")
await fs.writeFile(path.join(hooksDirPath, "PostToolUse"), "#!/usr/bin/env bash")
// Get all files WITHOUT exclusion
const allFiles = await readDirectory(clinerulesDirPath)
// Verify all files are included
allFiles.length.should.equal(5) // 2 in root + 1 in workflows + 2 in hooks
allFiles.some((file) => file.includes("PreToolUse")).should.be.true()
allFiles.some((file) => file.includes("PostToolUse")).should.be.true()
// Get files WITH hooks directory excluded
const filteredFiles = await readDirectory(clinerulesDirPath, [[".clinerules", "hooks"]])
// Verify hooks files are excluded but others remain
filteredFiles.length.should.equal(3) // 2 in root + 1 in workflows
const expectedFiles = [
path.resolve(clinerulesDirPath, "config.json"),
path.resolve(clinerulesDirPath, "settings.js"),
path.resolve(workflowsDirPath, "workflow1.js"),
]
filteredFiles.sort().should.deepEqual(expectedFiles.sort())
// Test with multiple exclusions (both workflows and hooks)
const multiExcludeFiles = await readDirectory(clinerulesDirPath, [
[".clinerules", "workflows"],
[".clinerules", "hooks"],
])
// Verify both workflows and hooks directories are excluded
multiExcludeFiles.length.should.equal(2) // only the 2 files in root
const rootOnlyFiles = [path.resolve(clinerulesDirPath, "config.json"), path.resolve(clinerulesDirPath, "settings.js")]
multiExcludeFiles.sort().should.deepEqual(rootOnlyFiles.sort())
})
})