Skip to content
Open
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
3 changes: 3 additions & 0 deletions src/cli/cliRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ const semanticSuggestionMap: Record<string, string[]> = {
print: ['--stdout'],
console: ['--stdout'],
terminal: ['--stdout'],
plain: ['--no-color'],
monochrome: ['--no-color'],
pipe: ['--stdin'],
};

Expand Down Expand Up @@ -74,6 +76,7 @@ export const run = async () => {
)
.option('--stdin', 'Read file paths from stdin, one per line (specified files are processed directly)')
.option('--copy', 'Copy the generated output to system clipboard after processing')
.option('--no-color', 'Disable colored output (also respects NO_COLOR env variable, see https://no-color.org)')
.option(
'--token-count-tree [threshold]',
'Show file tree with token counts; optional threshold to show only files with ≥N tokens (e.g., --token-count-tree 100)',
Expand Down
6 changes: 6 additions & 0 deletions src/cli/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,10 @@ export interface CliOptions extends OptionValues {
topFilesLen?: number;
verbose?: boolean;
quiet?: boolean;

// Color Options
// The --no-color flag is handled by picocolors which checks process.argv.
// This property exists for Commander type compatibility and for propagating
// color settings to worker processes.
color?: boolean;
}
3 changes: 2 additions & 1 deletion src/shared/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,9 @@ class RepomixLogger {
}

private formatArgs(args: unknown[]): string {
const useColors = pc.isColorSupported;
return args
.map((arg) => (typeof arg === 'object' ? util.inspect(arg, { depth: null, colors: true }) : arg))
.map((arg) => (typeof arg === 'object' ? util.inspect(arg, { depth: null, colors: useColors }) : arg))
.join(' ');
}
}
Expand Down
15 changes: 12 additions & 3 deletions src/shared/processConcurrency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ export const createWorkerPool = (options: WorkerOptions): Tinypool => {
);

const startTime = process.hrtime.bigint();
const noColorEnabled = Boolean(process.env.NO_COLOR) || process.argv.includes('--no-color');
const childProcessEnv = { ...process.env };
if (noColorEnabled) {
// Ensure child workers do not inherit FORCE_COLOR when NO_COLOR is active.
delete childProcessEnv.FORCE_COLOR;
}

const pool = new Tinypool({
filename: workerPath,
Expand All @@ -88,14 +94,17 @@ export const createWorkerPool = (options: WorkerOptions): Tinypool => {
// Only add env for child_process workers
...(runtime === 'child_process' && {
env: {
...process.env,
...childProcessEnv,
// Pass worker type as environment variable for child_process workers
// This is needed because workerData is not directly accessible in child_process runtime
REPOMIX_WORKER_TYPE: workerType,
// Pass log level as environment variable for child_process workers
REPOMIX_LOG_LEVEL: logger.getLogLevel().toString(),
// Ensure color support in child_process workers
FORCE_COLOR: process.env.FORCE_COLOR || (process.stdout.isTTY ? '1' : '0'),
// Propagate color settings to child_process workers
// Respect NO_COLOR env var and --no-color flag; only set FORCE_COLOR when colors are enabled
...(noColorEnabled
? { NO_COLOR: '1' }
: { FORCE_COLOR: process.env.FORCE_COLOR || (process.stdout.isTTY ? '1' : '0') }),
// Pass terminal capabilities
TERM: process.env.TERM || 'xterm-256color',
},
Expand Down
11 changes: 11 additions & 0 deletions tests/cli/cliRun.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,17 @@ describe('cliRun', () => {
});
});

describe('no-color mode', () => {
test('should accept --no-color flag without error', async () => {
const options: CliOptions = {
color: false,
};

await expect(runCli(['.'], process.cwd(), options)).resolves.not.toThrow();
expect(defaultAction.runDefaultAction).toHaveBeenCalled();
});
});

describe('stdout mode', () => {
const originalIsTTY = process.stdout.isTTY;

Expand Down
10 changes: 10 additions & 0 deletions tests/shared/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ vi.mock('picocolors', () => ({
dim: vi.fn((str) => `DIM:${str}`),
blue: vi.fn((str) => `BLUE:${str}`),
gray: vi.fn((str) => `GRAY:${str}`),
isColorSupported: true,
},
}));

Expand Down Expand Up @@ -110,4 +111,13 @@ describe('logger', () => {
logger.info('Multiple', 'arguments', 123);
expect(console.log).toHaveBeenCalledWith('CYAN:Multiple arguments 123');
});

describe('color support in formatArgs', () => {
it('should pass pc.isColorSupported to util.inspect for object formatting', () => {
const obj = { key: 'value' };
logger.info('Test:', obj);
// When isColorSupported is true (mock), util.inspect should use colors
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('CYAN:Test: '));
});
});
Comment on lines +115 to +122
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This test is a good start, but it only indirectly verifies the behavior by checking the final console.log output. To make the test more robust and specific, you could spy on util.inspect and assert that it's called with the correct colors option. This would directly test the logic in formatArgs. You could also test the case where colors are disabled to ensure util.inspect is called with colors: false.

});
107 changes: 106 additions & 1 deletion tests/shared/processConcurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ describe('processConcurrency', () => {
},
env: expect.objectContaining({
REPOMIX_LOG_LEVEL: '2',
FORCE_COLOR: expect.any(String),
TERM: expect.any(String),
}),
});
Expand Down Expand Up @@ -167,4 +166,110 @@ describe('processConcurrency', () => {
expect(taskRunner).toHaveProperty('cleanup');
});
});

describe('color propagation to worker processes', () => {
beforeEach(() => {
vi.mocked(os).availableParallelism = vi.fn().mockReturnValue(4);
vi.mocked(Tinypool).mockImplementation(function (this: unknown) {
(this as Record<string, unknown>).run = vi.fn();
(this as Record<string, unknown>).destroy = vi.fn();
return this as Tinypool;
});
});

it('should propagate NO_COLOR to worker when NO_COLOR env is set', () => {
const originalNoColor = process.env.NO_COLOR;
process.env.NO_COLOR = '1';
try {
createWorkerPool({ numOfTasks: 100, workerType: 'fileProcess', runtime: 'child_process' });

expect(Tinypool).toHaveBeenCalledWith(
expect.objectContaining({
env: expect.objectContaining({
NO_COLOR: '1',
}),
}),
);
} finally {
if (originalNoColor === undefined) {
delete process.env.NO_COLOR;
} else {
process.env.NO_COLOR = originalNoColor;
}
}
});

it('should propagate NO_COLOR to worker when --no-color is in argv', () => {
const originalArgv = process.argv;
process.argv = [...originalArgv, '--no-color'];
try {
createWorkerPool({ numOfTasks: 100, workerType: 'fileProcess', runtime: 'child_process' });

expect(Tinypool).toHaveBeenCalledWith(
expect.objectContaining({
env: expect.objectContaining({
NO_COLOR: '1',
}),
}),
);
} finally {
process.argv = originalArgv;
}
});

it('should set FORCE_COLOR when colors are not disabled', () => {
const originalNoColor = process.env.NO_COLOR;
delete process.env.NO_COLOR;
const originalArgv = process.argv;
process.argv = originalArgv.filter((arg) => arg !== '--no-color');
try {
createWorkerPool({ numOfTasks: 100, workerType: 'fileProcess', runtime: 'child_process' });

expect(Tinypool).toHaveBeenCalledWith(
expect.objectContaining({
env: expect.objectContaining({
FORCE_COLOR: expect.any(String),
}),
}),
);
} finally {
if (originalNoColor !== undefined) {
process.env.NO_COLOR = originalNoColor;
}
process.argv = originalArgv;
}
});

it('should not leak FORCE_COLOR when NO_COLOR is enabled', () => {
const originalNoColor = process.env.NO_COLOR;
const originalForceColor = process.env.FORCE_COLOR;
process.env.NO_COLOR = '1';
process.env.FORCE_COLOR = '1';
try {
createWorkerPool({ numOfTasks: 100, workerType: 'fileProcess', runtime: 'child_process' });

expect(Tinypool).toHaveBeenCalledWith(
expect.objectContaining({
env: expect.objectContaining({
NO_COLOR: '1',
}),
}),
);

const callArgs = vi.mocked(Tinypool).mock.calls.at(-1)?.[0];
expect(callArgs?.env?.FORCE_COLOR).toBeUndefined();
} finally {
if (originalNoColor === undefined) {
delete process.env.NO_COLOR;
} else {
process.env.NO_COLOR = originalNoColor;
}
if (originalForceColor === undefined) {
delete process.env.FORCE_COLOR;
} else {
process.env.FORCE_COLOR = originalForceColor;
}
}
});
});
Comment on lines +170 to +274
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To improve test isolation and reduce repetitive code, consider managing the global state (process.env.NO_COLOR and process.argv) using beforeEach and afterEach hooks for this describe block. You can save the original values in beforeEach and restore them in afterEach. This would make the tests cleaner and less prone to state leakage between tests, as you wouldn't need the try...finally blocks in each test.

Comment on lines +170 to +274
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing test coverage for FORCE_COLOR leak when NO_COLOR is active.

The three new tests cover the positive propagation cases, but there is no test verifying that a pre-existing FORCE_COLOR in the parent environment is absent from the child env when NO_COLOR should take effect. This is precisely the defect described in the processConcurrency.ts comment above — the test suite would not catch it.

Add a fourth test:

🧪 Suggested additional test
+    it('should not carry FORCE_COLOR into worker when NO_COLOR is active', () => {
+      const originalNoColor = process.env.NO_COLOR;
+      const originalForceColor = process.env.FORCE_COLOR;
+      process.env.NO_COLOR = '1';
+      process.env.FORCE_COLOR = '1'; // simulate CI/parent setting FORCE_COLOR
+      try {
+        createWorkerPool({ numOfTasks: 100, workerType: 'fileProcess', runtime: 'child_process' });
+
+        const callArgs = vi.mocked(Tinypool).mock.calls[0][0] as { env: Record<string, string> };
+        expect(callArgs.env.NO_COLOR).toBe('1');
+        expect(callArgs.env.FORCE_COLOR).toBeUndefined();
+      } finally {
+        if (originalNoColor === undefined) delete process.env.NO_COLOR;
+        else process.env.NO_COLOR = originalNoColor;
+        if (originalForceColor === undefined) delete process.env.FORCE_COLOR;
+        else process.env.FORCE_COLOR = originalForceColor;
+      }
+    });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/shared/processConcurrency.test.ts` around lines 170 - 242, Add a test
in processConcurrency.test.ts that ensures when NO_COLOR is active (either via
process.env.NO_COLOR = '1' or via '--no-color' in process.argv) any pre-existing
FORCE_COLOR in the parent env is not passed to workers: set
process.env.FORCE_COLOR = '1' before calling createWorkerPool, set NO_COLOR (or
argv) so the code should drop FORCE_COLOR, call createWorkerPool, and assert
Tinypool was called with env not containing FORCE_COLOR (or containing NO_COLOR
and not FORCE_COLOR). Use the existing test patterns and restore process.env and
process.argv afterward; reference createWorkerPool and Tinypool to locate where
to add the assertion.

});