Skip to content

Commit 932b9ec

Browse files
committed
Merge pull request #70 from timrogers/copilot/fix-4a5d6a32-927f-4cf5-be0f-269b8b06a70d
feat!: specify claude dir with `CLAUDE_CONFIG_DIR` and remove `-p`/`--path` option
2 parents 36c02fd + ae3cbe7 commit 932b9ec

11 files changed

Lines changed: 133 additions & 26 deletions

File tree

‎.github/workflows/ci.yaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ jobs:
1616
- run: bun install --frozen-lockfile
1717
- run: bun lint
1818
- run: bun typecheck
19+
- name: Create default Claude directory for tests
20+
run: mkdir -p $HOME/.claude
1921
- run: bun test
2022

2123
npm-publish-dry-run-and-upload-pkg-pr-now:

‎README.md‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,9 @@ ccusage daily
129129
# Filter by date range
130130
ccusage daily --since 20250525 --until 20250530
131131

132-
# Use custom Claude data directory
133-
ccusage daily --path /custom/path/to/.claude
132+
# Set CLAUDE_CONFIG_DIR environment variable for custom data directory
133+
export CLAUDE_CONFIG_DIR="/custom/path/to/.claude"
134+
ccusage daily
134135

135136
# Output in JSON format
136137
ccusage daily --json
@@ -164,6 +165,10 @@ ccusage monthly --since 20250101 --until 20250531
164165
# Use custom Claude data directory
165166
ccusage monthly --path /custom/path/to/.claude
166167

168+
# Or set CLAUDE_CONFIG_DIR environment variable
169+
export CLAUDE_CONFIG_DIR="/custom/path/to/.claude"
170+
ccusage monthly
171+
167172
# Output in JSON format
168173
ccusage monthly --json
169174

@@ -191,8 +196,9 @@ ccusage session
191196
# Filter sessions by last activity date
192197
ccusage session --since 20250525
193198

194-
# Combine filters
195-
ccusage session --since 20250525 --until 20250530 --path /custom/path
199+
# Combine filters with environment variable
200+
export CLAUDE_CONFIG_DIR="/custom/path"
201+
ccusage session --since 20250525 --until 20250530
196202

197203
# Output in JSON format
198204
ccusage session --json
@@ -216,7 +222,6 @@ All commands support the following options:
216222

217223
- `-s, --since <date>`: Filter from date (YYYYMMDD format)
218224
- `-u, --until <date>`: Filter until date (YYYYMMDD format)
219-
- `-p, --path <path>`: Custom path to Claude data directory (default: `~/.claude`)
220225
- `-j, --json`: Output results in JSON format instead of table
221226
- `-m, --mode <mode>`: Cost calculation mode: `auto` (default), `calculate`, or `display`
222227
- `-o, --order <order>`: Sort order: `desc` (newest first, default) or `asc` (oldest first).
@@ -232,6 +237,21 @@ All commands support the following options:
232237
- **`calculate`**: Always calculates costs from token counts using model pricing, ignores any pre-calculated `costUSD` values
233238
- **`display`**: Always uses pre-calculated `costUSD` values only, shows $0.00 for entries without pre-calculated costs
234239

240+
#### Environment Variable Support
241+
242+
The tool supports the `CLAUDE_CONFIG_DIR` environment variable to specify the Claude data directory:
243+
244+
```bash
245+
# Set the environment variable to use a custom Claude directory
246+
export CLAUDE_CONFIG_DIR="/path/to/custom/claude/directory"
247+
ccusage daily
248+
249+
# The environment variable determines the Claude data directory
250+
ccusage daily
251+
```
252+
253+
The tool will use the path specified in the `CLAUDE_CONFIG_DIR` environment variable, or fall back to the default `~/.claude` directory if not set.
254+
235255
### MCP (Model Context Protocol) Support
236256

237257
Exposes usage data through Model Context Protocol for integration with other tools:

‎bun.lock‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"fs-fixture": "^2.8.0",
6262
"gunshi": "^0.26.3",
6363
"lint-staged": "^16.1.0",
64+
"path-type": "^6.0.0",
6465
"picocolors": "^1.1.1",
6566
"publint": "^0.3.12",
6667
"simple-git-hooks": "^2.13.0",

‎src/commands/daily.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
createTotalsObject,
88
getTotalTokens,
99
} from '../calculate-cost.ts';
10-
import { loadDailyUsageData } from '../data-loader.ts';
10+
import { getDefaultClaudePath, loadDailyUsageData } from '../data-loader.ts';
1111
import { detectMismatches, printMismatchReport } from '../debug.ts';
1212
import { log, logger } from '../logger.ts';
1313
import { sharedCommandConfig } from '../shared-args.internal.ts';
@@ -25,7 +25,7 @@ export const dailyCommand = define({
2525
const dailyData = await loadDailyUsageData({
2626
since: ctx.values.since,
2727
until: ctx.values.until,
28-
claudePath: ctx.values.path,
28+
claudePath: getDefaultClaudePath(),
2929
mode: ctx.values.mode,
3030
order: ctx.values.order,
3131
});
@@ -45,7 +45,7 @@ export const dailyCommand = define({
4545

4646
// Show debug information if requested
4747
if (ctx.values.debug && !ctx.values.json) {
48-
const mismatchStats = await detectMismatches(ctx.values.path);
48+
const mismatchStats = await detectMismatches(getDefaultClaudePath());
4949
printMismatchReport(mismatchStats, ctx.values.debugSamples);
5050
}
5151

‎src/commands/mcp.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { define } from 'gunshi';
2+
import { getDefaultClaudePath } from '../data-loader.ts';
23
import { logger } from '../logger.ts';
34
import { createMcpServer } from '../mcp.ts';
45
import { sharedArgs } from '../shared-args.internal.ts';
@@ -7,7 +8,6 @@ export const mcpCommand = define({
78
name: 'mcp',
89
description: 'Show usage report for MCP',
910
args: {
10-
path: sharedArgs.path,
1111
mode: sharedArgs.mode,
1212
type: {
1313
type: 'enum',
@@ -23,14 +23,14 @@ export const mcpCommand = define({
2323
},
2424
},
2525
async run(ctx) {
26-
const { type, mode, path, port } = ctx.values;
26+
const { type, mode, port } = ctx.values;
2727
// disable info logging
2828
if (type === 'stdio') {
2929
logger.level = 0;
3030
}
3131

3232
const server = createMcpServer({
33-
claudePath: path,
33+
claudePath: getDefaultClaudePath(),
3434
mode,
3535
});
3636

‎src/commands/monthly.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
createTotalsObject,
88
getTotalTokens,
99
} from '../calculate-cost.ts';
10-
import { loadMonthlyUsageData } from '../data-loader.ts';
10+
import { getDefaultClaudePath, loadMonthlyUsageData } from '../data-loader.ts';
1111
import { detectMismatches, printMismatchReport } from '../debug.ts';
1212
import { log, logger } from '../logger.ts';
1313
import { sharedCommandConfig } from '../shared-args.internal.ts';
@@ -25,7 +25,7 @@ export const monthlyCommand = define({
2525
const monthlyData = await loadMonthlyUsageData({
2626
since: ctx.values.since,
2727
until: ctx.values.until,
28-
claudePath: ctx.values.path,
28+
claudePath: getDefaultClaudePath(),
2929
mode: ctx.values.mode,
3030
order: ctx.values.order,
3131
});
@@ -56,7 +56,7 @@ export const monthlyCommand = define({
5656

5757
// Show debug information if requested
5858
if (ctx.values.debug && !ctx.values.json) {
59-
const mismatchStats = await detectMismatches(ctx.values.path);
59+
const mismatchStats = await detectMismatches(getDefaultClaudePath());
6060
printMismatchReport(mismatchStats, ctx.values.debugSamples);
6161
}
6262

‎src/commands/session.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
createTotalsObject,
88
getTotalTokens,
99
} from '../calculate-cost.ts';
10-
import { loadSessionData } from '../data-loader.ts';
10+
import { getDefaultClaudePath, loadSessionData } from '../data-loader.ts';
1111
import { detectMismatches, printMismatchReport } from '../debug.ts';
1212
import { log, logger } from '../logger.ts';
1313
import { sharedCommandConfig } from '../shared-args.internal.ts';
@@ -25,7 +25,7 @@ export const sessionCommand = define({
2525
const sessionData = await loadSessionData({
2626
since: ctx.values.since,
2727
until: ctx.values.until,
28-
claudePath: ctx.values.path,
28+
claudePath: getDefaultClaudePath(),
2929
mode: ctx.values.mode,
3030
order: ctx.values.order,
3131
});
@@ -45,7 +45,7 @@ export const sessionCommand = define({
4545

4646
// Show debug information if requested
4747
if (ctx.values.debug && !ctx.values.json) {
48-
const mismatchStats = await detectMismatches(ctx.values.path);
48+
const mismatchStats = await detectMismatches(getDefaultClaudePath());
4949
printMismatchReport(mismatchStats, ctx.values.debugSamples);
5050
}
5151

‎src/data-loader.test.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import { describe, expect, test } from 'bun:test';
1+
import { homedir } from 'node:os';
2+
import { join } from 'node:path';
3+
import process from 'node:process';
4+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
25
import { createFixture } from 'fs-fixture';
36
import {
47
calculateCostForEntry,
58
formatDate,
9+
getDefaultClaudePath,
610
loadDailyUsageData,
711
loadMonthlyUsageData,
812
loadSessionData,
@@ -29,6 +33,74 @@ describe('formatDate', () => {
2933
});
3034
});
3135

36+
describe('getDefaultClaudePath', () => {
37+
const originalEnv = process.env.CLAUDE_CONFIG_DIR;
38+
39+
beforeEach(() => {
40+
// Clean up env var before each test
41+
delete process.env.CLAUDE_CONFIG_DIR;
42+
});
43+
44+
afterEach(() => {
45+
// Restore original environment
46+
if (originalEnv != null) {
47+
process.env.CLAUDE_CONFIG_DIR = originalEnv;
48+
}
49+
else {
50+
delete process.env.CLAUDE_CONFIG_DIR;
51+
}
52+
});
53+
54+
test('returns CLAUDE_CONFIG_DIR when environment variable is set', async () => {
55+
await using fixture = await createFixture({
56+
claude: {},
57+
});
58+
process.env.CLAUDE_CONFIG_DIR = fixture.path;
59+
60+
expect(getDefaultClaudePath()).toBe(fixture.path);
61+
});
62+
63+
test('returns default path when CLAUDE_CONFIG_DIR is not set', () => {
64+
// Ensure CLAUDE_CONFIG_DIR is not set
65+
delete process.env.CLAUDE_CONFIG_DIR;
66+
67+
// Test that it returns the default path (which ends with .claude)
68+
const actualPath = getDefaultClaudePath();
69+
expect(actualPath).toMatch(/\.claude$/);
70+
expect(actualPath).toContain(homedir());
71+
});
72+
73+
test('returns default path with trimmed CLAUDE_CONFIG_DIR', async () => {
74+
await using fixture = await createFixture({
75+
claude: {},
76+
});
77+
// Test with extra spaces
78+
process.env.CLAUDE_CONFIG_DIR = ` ${fixture.path} `;
79+
80+
expect(getDefaultClaudePath()).toBe(fixture.path);
81+
});
82+
83+
test('throws an error when CLAUDE_CONFIG_DIR is not a directory', async () => {
84+
await using fixture = await createFixture();
85+
process.env.CLAUDE_CONFIG_DIR = join(fixture.path, 'not-a-directory');
86+
87+
expect(() => getDefaultClaudePath()).toThrow(/Claude data directory does not exist/);
88+
});
89+
90+
test('throws an error when CLAUDE_CONFIG_DIR does not exist', async () => {
91+
process.env.CLAUDE_CONFIG_DIR = '/nonexistent/path/that/does/not/exist';
92+
93+
expect(() => getDefaultClaudePath()).toThrow(/Claude data directory does not exist/);
94+
});
95+
96+
test('throws an error when default path does not exist', () => {
97+
// Set to a non-existent path
98+
process.env.CLAUDE_CONFIG_DIR = '/nonexistent/path/.claude';
99+
100+
expect(() => getDefaultClaudePath()).toThrow(/Claude data directory does not exist/);
101+
});
102+
});
103+
32104
describe('loadDailyUsageData', () => {
33105
test('returns empty array when no files found', async () => {
34106
await using fixture = await createFixture({

‎src/data-loader.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,34 @@ import type { CostMode, SortOrder } from './types.internal.ts';
22
import { readFile } from 'node:fs/promises';
33
import { homedir } from 'node:os';
44
import path from 'node:path';
5+
import process from 'node:process';
56
import { unreachable } from '@core/errorutil';
67
import { groupBy } from 'es-toolkit'; // TODO: after node20 is deprecated, switch to native Object.groupBy
78
import { sort } from 'fast-sort';
9+
import { isDirectorySync } from 'path-type';
810
import { glob } from 'tinyglobby';
911
import * as v from 'valibot';
1012
import { logger } from './logger.ts';
1113
import {
1214
PricingFetcher,
1315
} from './pricing-fetcher.ts';
1416

17+
const DEFAULT_CLAUDE_CODE_PATH = path.join(homedir(), '.claude');
18+
19+
/**
20+
* Default path for Claude data directory
21+
* Uses environment variable CLAUDE_CONFIG_DIR if set, otherwise defaults to ~/.claude
22+
*/
1523
export function getDefaultClaudePath(): string {
16-
return path.join(homedir(), '.claude');
24+
const envClaudeCodePath = process.env.CLAUDE_CONFIG_DIR?.trim() ?? DEFAULT_CLAUDE_CODE_PATH;
25+
if (!isDirectorySync(envClaudeCodePath)) {
26+
throw new Error(
27+
` Claude data directory does not exist: ${envClaudeCodePath}.
28+
Please set CLAUDE_CONFIG_DIR to a valid path, or ensure ${DEFAULT_CLAUDE_CODE_PATH} exists.
29+
`.trim(),
30+
);
31+
}
32+
return envClaudeCodePath;
1733
}
1834

1935
export const UsageDataSchema = v.object({

0 commit comments

Comments
 (0)