Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/api/copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ export async function copy(basePath, options = {}) {
// Copy to clipboard if explicitly requested
if (options.clipboard) {
try {
await Clipboard.copy(output);
await Clipboard.copyText(output);
} catch (error) {
// Don't fail the operation if clipboard copy fails
result.stats.clipboardError = error.message;
Expand Down
56 changes: 31 additions & 25 deletions src/utils/clipboard.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { execSync } from 'child_process';
import { execSync, spawnSync } from 'child_process';
import process from 'process';
import url from 'url';
import path from 'path';
Expand Down Expand Up @@ -27,9 +27,21 @@ class Clipboard {
static async copyFileReference(filePath) {
if (process.platform === 'win32') {
try {
// Use PowerShell to copy the file reference on Windows
const command = `powershell -Command "Set-Clipboard -Path '${filePath.replace(/'/g, "''")}'"`;
execSync(command, { stdio: 'pipe' });
// Use Windows Forms SetFileDropList via Base64-encoded PowerShell command.
// This bypasses all shell quoting (Base64 encoding) and path glob expansion
// (StringCollection is passed to SetFileDropList without any wildcard interpretation).
// Single quotes are doubled for the PS single-quoted string literal.
const psPath = filePath.replace(/'/g, "''");
const psCommand = [
'Add-Type -AssemblyName System.Windows.Forms',
'$fc = New-Object System.Collections.Specialized.StringCollection',
`[void]$fc.Add('${psPath}')`,
'[System.Windows.Forms.Clipboard]::SetFileDropList($fc)',
].join('; ');
const encoded = Buffer.from(psCommand, 'utf16le').toString('base64');
execSync(`powershell -NoProfile -NonInteractive -EncodedCommand ${encoded}`, {
stdio: 'pipe',
});
} catch (error) {
logger.debug(
'Failed to copy file reference using PowerShell, falling back to text:',
Expand All @@ -48,17 +60,13 @@ class Clipboard {
}
} else if (process.platform === 'darwin') {
try {
// Use AppleScript to copy file reference
// Use AppleScript to copy file reference. spawnSync passes the script as a
// direct argument (no shell), so single quotes in filePath are safe.
const escapedFilePath = filePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const script = `
set aFile to POSIX file "${escapedFilePath}"
tell app "Finder" to set the clipboard to aFile
`.trim();
const script = `set aFile to POSIX file "${escapedFilePath}"
tell app "Finder" to set the clipboard to aFile`;

execSync(`osascript -e '${script}'`, {
encoding: 'utf8',
stdio: 'pipe',
});
spawnSync('osascript', ['-e', script], { encoding: 'utf8', stdio: 'pipe' });
} catch (error) {
logger.debug('Failed to copy file reference, falling back to text:', error.message);
// Fallback to copying path as text
Expand All @@ -78,30 +86,28 @@ class Clipboard {
static async revealInFinder(filePath) {
if (process.platform === 'win32') {
try {
execSync(`explorer /select,"${filePath}"`, { stdio: 'pipe' });
// Use spawnSync with array args to avoid cmd.exe interpreting &, |, <, >, ^ in paths
spawnSync('explorer', [`/select,${filePath}`], { stdio: 'pipe' });
} catch (error) {
logger.debug('Failed to reveal file in Explorer:', error.message);
}
} else if (process.platform === 'linux') {
try {
// Use xdg-open to open the parent directory
// Use spawnSync with array args to avoid shell interpreting $, ", ` in paths
const dir = path.dirname(filePath);
execSync(`xdg-open "${dir}"`, { stdio: 'pipe' });
spawnSync('xdg-open', [dir], { stdio: 'pipe' });
} catch (error) {
logger.debug('Failed to reveal file with xdg-open:', error.message);
}
} else if (process.platform === 'darwin') {
try {
const escapedFilePath = filePath.replace(/"/g, '"');
const script = `
tell application "Finder" to reveal POSIX file "${escapedFilePath}"
tell application "Finder" to activate
`.trim();
// Use AppleScript to reveal file. spawnSync passes the script as a direct
// argument (no shell), so single quotes in filePath are safe.
const escapedFilePath = filePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const script = `tell application "Finder" to reveal POSIX file "${escapedFilePath}"
tell application "Finder" to activate`;

execSync(`osascript -e '${script}'`, {
encoding: 'utf8',
stdio: 'pipe',
});
spawnSync('osascript', ['-e', script], { encoding: 'utf8', stdio: 'pipe' });
} catch (error) {
logger.debug('Failed to reveal file in Finder:', error.message);
}
Expand Down
20 changes: 13 additions & 7 deletions tests/setup-global-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,19 @@ jest.mock('../src/utils/logger.js', () => ({
logger: mockLogger,
}));

// Mock clipboardy to prevent ESM import issues
jest.mock('clipboardy', () => ({
write: jest.fn().mockResolvedValue(undefined),
read: jest.fn().mockResolvedValue(''),
writeSync: jest.fn(),
readSync: jest.fn().mockReturnValue(''),
}));
// Mock clipboardy to prevent ESM import issues.
// The mock object is set as its own `.default` so that dynamic ESM imports
// (`const { default: clipboardy } = await import('clipboardy')`) resolve correctly.
jest.mock('clipboardy', () => {
const mock = {
write: jest.fn().mockResolvedValue(undefined),
read: jest.fn().mockResolvedValue(''),
writeSync: jest.fn(),
readSync: jest.fn().mockReturnValue(''),
};
mock.default = mock;
return mock;
});

// Mock fs-extra (comprehensive mock with all functions)
jest.mock('fs-extra', () => {
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/api/copy.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Unmock fs-extra for these tests to use real filesystem
jest.unmock('fs-extra');

import Clipboard from '../../../src/utils/clipboard.js';

import { copy } from '../../../src/api/copy.js';
import { ValidationError } from '../../../src/utils/errors.js';
import fs from 'fs-extra';
Expand Down Expand Up @@ -153,6 +155,28 @@ describe('copy()', () => {

expect(result.output).toBeDefined();
});

it('should call Clipboard.copyText with formatted output when clipboard: true', async () => {
const spy = jest.spyOn(Clipboard, 'copyText').mockResolvedValueOnce();

const result = await copy(testDir, { clipboard: true });

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(result.output);
spy.mockRestore();
});

it('should succeed and record clipboardError when Clipboard.copyText throws', async () => {
const spy = jest
.spyOn(Clipboard, 'copyText')
.mockRejectedValueOnce(new Error('clipboard unavailable'));

const result = await copy(testDir, { clipboard: true });

expect(result.output).toBeDefined();
expect(result.stats.clipboardError).toBe('clipboard unavailable');
spy.mockRestore();
});
});

describe('Dry run', () => {
Expand Down
Loading
Loading