clocktopus 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,18 +49,44 @@ That's it. Start/stop timers from the Home tab.
49
49
 
50
50
  ### Commands
51
51
 
52
- | Command | Description |
53
- | ------------------------- | --------------------------------------- |
54
- | `clocktopus dash` | Start dashboard (foreground) |
55
- | `clocktopus serve` | Start dashboard as background daemon |
56
- | `clocktopus serve:stop` | Stop the dashboard daemon |
57
- | `clocktopus serve:logs` | View dashboard daemon logs |
58
- | `clocktopus start` | Start a timer (interactive) |
59
- | `clocktopus stop` | Stop the current timer |
60
- | `clocktopus status` | Check timer status |
61
- | `clocktopus monitor` | Start idle monitor as background daemon |
62
- | `clocktopus monitor:stop` | Stop the idle monitor |
63
- | `clocktopus monitor:logs` | View idle monitor logs |
52
+ | Command | Description |
53
+ | ------------------------------- | ------------------------------------------ |
54
+ | `clocktopus dash` | Start dashboard (foreground) |
55
+ | `clocktopus serve` | Start dashboard as background daemon |
56
+ | `clocktopus serve:stop` | Stop the dashboard daemon |
57
+ | `clocktopus serve:logs` | View dashboard daemon logs |
58
+ | `clocktopus start` | Start a timer (interactive) |
59
+ | `clocktopus stop` | Stop the current timer |
60
+ | `clocktopus status` | Check timer status |
61
+ | `clocktopus monitor` | Start idle monitor as background daemon |
62
+ | `clocktopus monitor:stop` | Stop the idle monitor |
63
+ | `clocktopus monitor:logs` | View idle monitor logs |
64
+ | `clocktopus hook:install` | Install global git post-checkout hook |
65
+ | `clocktopus hook:uninstall` | Remove the global git post-checkout hook |
66
+ | `clocktopus hook:install-husky` | Add `.husky/post-checkout` in current repo |
67
+
68
+ ### Git post-checkout hook
69
+
70
+ Auto-prompt to start a timer when you `git checkout` a branch. Extracts Jira tickets from branch names (e.g. `feature/RST-100-login` → `RST-100`), fetches the ticket summary from Jira as the default description, and maps to a Clockify project.
71
+
72
+ ```bash
73
+ clocktopus hook:install
74
+ ```
75
+
76
+ Installs a global hook at `~/.clocktopus/hooks/post-checkout` and sets `git config --global core.hooksPath` + `init.templateDir`.
77
+
78
+ **Opt out per repo:** `touch .clocktopus-ignore` at the repo root.
79
+ **Opt out per session:** `export CLOCKTOPUS_HOOK_DISABLE=1`.
80
+
81
+ #### Husky users
82
+
83
+ Husky sets a **local** `core.hooksPath`, which overrides the global one — so the hook won't fire in husky repos by default. Inside each husky-enabled repo, run:
84
+
85
+ ```bash
86
+ clocktopus hook:install-husky
87
+ ```
88
+
89
+ This writes `.husky/post-checkout` that chains to the global hook. Commit it so teammates get it too.
64
90
 
65
91
  ### Desktop App (macOS)
66
92
 
package/dist/index.js CHANGED
@@ -60,17 +60,14 @@ program
60
60
  .option('-j, --jira <ticket>', 'Jira ticket number')
61
61
  .option('--no-billable', 'Mark the time entry as non-billable')
62
62
  .action(async (message, options) => {
63
+ const { startTimer } = await import('./lib/start-timer.js');
63
64
  if (!isClockifyEnabled()) {
64
65
  if (!options.jira) {
65
66
  console.error(chalk.red('Jira-only mode requires --jira <ticket>.'));
66
67
  process.exit(1);
67
68
  }
68
- const { v4: uuidv4 } = await import('uuid');
69
- const { logSessionStart } = await import('./lib/db.js');
70
- const sessionId = uuidv4();
71
- const startedAt = new Date().toISOString();
72
69
  const description = (message && String(message).trim()) || options.jira;
73
- logSessionStart(sessionId, null, description, startedAt, options.jira);
70
+ await startTimer({ description, ticket: options.jira, projectId: null, billable: options.billable });
74
71
  console.log(chalk.green(`Timer started for ${chalk.bold(options.jira)} (Jira-only mode).`));
75
72
  return;
76
73
  }
@@ -78,7 +75,6 @@ program
78
75
  let projects = await clockify.getProjects(workspaceId);
79
76
  let localProjects = await getLocalProjects();
80
77
  if (localProjects.length === 0) {
81
- // If local-projects.json is empty or doesn't exist, populate it with all project IDs and names
82
78
  const allProjects = projects.map((p) => ({ id: p.id, name: p.name }));
83
79
  const localProjectsPath = path.join(__dirname, '../data/local-projects.json');
84
80
  fs.writeFileSync(localProjectsPath, JSON.stringify(allProjects, null, 2), 'utf8');
@@ -101,11 +97,14 @@ program
101
97
  choices: projects.map((p) => ({ name: p.name, value: p.id })),
102
98
  },
103
99
  ]);
104
- const entry = await clockify.startTimer(workspaceId, selectedProjectId, message, options.jira, options.billable);
105
- if (entry) {
106
- const projectName = projects.find((p) => p.id === selectedProjectId)?.name;
107
- console.log(chalk.green(`Timer started for project: ${chalk.bold(projectName)}`));
108
- }
100
+ await startTimer({
101
+ description: message || options.jira || '',
102
+ ticket: options.jira ?? null,
103
+ projectId: selectedProjectId,
104
+ billable: options.billable,
105
+ });
106
+ const projectName = projects.find((p) => p.id === selectedProjectId)?.name;
107
+ console.log(chalk.green(`Timer started for project: ${chalk.bold(projectName)}`));
109
108
  });
110
109
  program
111
110
  .command('stop')
@@ -464,4 +463,60 @@ program
464
463
  console.log(chalk.yellow('Dashboard is not running.'));
465
464
  }
466
465
  });
466
+ program
467
+ .command('hook:install')
468
+ .description('Install global git post-checkout hook (prompts to start timer on branch switch).')
469
+ .action(async () => {
470
+ const { installHook } = await import('./lib/hook-install.js');
471
+ await installHook();
472
+ console.log(chalk.green('Clocktopus post-checkout hook installed globally.'));
473
+ console.log(chalk.gray(' Disable per-repo: touch .clocktopus-ignore'));
474
+ console.log(chalk.gray(' Disable per-session: export CLOCKTOPUS_HOOK_DISABLE=1'));
475
+ console.log(chalk.gray(' Uninstall: clocktopus hook:uninstall'));
476
+ console.log();
477
+ console.log(chalk.yellow('Husky users: local core.hooksPath overrides global.'));
478
+ console.log(chalk.gray(' Inside each husky repo, run: clocktopus hook:install-husky'));
479
+ });
480
+ program
481
+ .command('hook:uninstall')
482
+ .description('Remove the global git post-checkout hook.')
483
+ .action(async () => {
484
+ const { uninstallHook } = await import('./lib/hook-install.js');
485
+ await uninstallHook();
486
+ console.log(chalk.green('Clocktopus post-checkout hook removed.'));
487
+ });
488
+ program
489
+ .command('hook:install-husky')
490
+ .description('Write a .husky/post-checkout in the current repo that chains to the global hook.')
491
+ .action(async () => {
492
+ const { installHuskyHook } = await import('./lib/husky-install.js');
493
+ const result = installHuskyHook(process.cwd());
494
+ if (result.installed) {
495
+ console.log(chalk.green(`Husky post-checkout installed at ${result.path}.`));
496
+ console.log(chalk.gray(' Commit it so teammates using husky get it too.'));
497
+ return;
498
+ }
499
+ if (result.reason === 'no-husky-dir') {
500
+ console.error(chalk.red('No .husky/ directory found. Run from the root of a husky-enabled repo.'));
501
+ process.exit(1);
502
+ }
503
+ if (result.reason === 'already-exists') {
504
+ console.log(chalk.yellow(`Existing ${result.path} left alone.`));
505
+ console.log(chalk.gray(' Add this line manually: exec ~/.clocktopus/hooks/post-checkout "$@"'));
506
+ }
507
+ });
508
+ program
509
+ .command('hook:prompt <branch>')
510
+ .description('(internal) Prompt to start a timer after git checkout.')
511
+ .action(async (branch) => {
512
+ const { runHookPrompt } = await import('./lib/hook-prompt.js');
513
+ try {
514
+ await runHookPrompt(branch, { cwd: process.cwd() });
515
+ }
516
+ catch (e) {
517
+ const msg = e instanceof Error ? e.message : String(e);
518
+ console.error(chalk.red(`Hook prompt failed: ${msg}`));
519
+ process.exit(0); // never block git checkout
520
+ }
521
+ });
467
522
  program.parse(process.argv);
@@ -0,0 +1,7 @@
1
+ const TICKET_REGEX = /([A-Za-z][A-Za-z0-9]+-\d+)/;
2
+ export function extractTicket(branch) {
3
+ if (!branch)
4
+ return null;
5
+ const match = branch.match(TICKET_REGEX);
6
+ return match ? match[1].toUpperCase() : null;
7
+ }
@@ -0,0 +1,16 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ const MARKER_FILE = '.clocktopus-ignore';
4
+ export function isRepoIgnored(cwd) {
5
+ if (process.env.CLOCKTOPUS_HOOK_DISABLE === '1')
6
+ return true;
7
+ let dir = path.resolve(cwd);
8
+ while (true) {
9
+ if (fs.existsSync(path.join(dir, MARKER_FILE)))
10
+ return true;
11
+ const parent = path.dirname(dir);
12
+ if (parent === dir)
13
+ return false;
14
+ dir = parent;
15
+ }
16
+ }
@@ -0,0 +1,35 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { execSync } from 'child_process';
4
+ import { getHookPaths } from './hook-paths.js';
5
+ import { POST_CHECKOUT_SCRIPT } from './hook-script.js';
6
+ function writeHookScript(target) {
7
+ fs.mkdirSync(path.dirname(target), { recursive: true });
8
+ fs.writeFileSync(target, POST_CHECKOUT_SCRIPT, { mode: 0o755 });
9
+ }
10
+ export async function installHook() {
11
+ const p = getHookPaths();
12
+ writeHookScript(p.hookScript);
13
+ writeHookScript(p.templateHookScript);
14
+ execSync(`git config --global core.hooksPath "${p.hooksDir}"`, { stdio: 'ignore' });
15
+ execSync(`git config --global init.templateDir "${p.templateDir}"`, { stdio: 'ignore' });
16
+ }
17
+ export async function uninstallHook() {
18
+ const p = getHookPaths();
19
+ try {
20
+ fs.rmSync(p.hookScript, { force: true });
21
+ }
22
+ catch { }
23
+ try {
24
+ fs.rmSync(p.templateHookScript, { force: true });
25
+ }
26
+ catch { }
27
+ try {
28
+ execSync('git config --global --unset core.hooksPath', { stdio: 'ignore' });
29
+ }
30
+ catch { }
31
+ try {
32
+ execSync('git config --global --unset init.templateDir', { stdio: 'ignore' });
33
+ }
34
+ catch { }
35
+ }
@@ -0,0 +1,14 @@
1
+ import * as os from 'os';
2
+ import * as path from 'path';
3
+ export function getHookPaths() {
4
+ const rootDir = path.join(os.homedir(), '.clocktopus');
5
+ const hooksDir = path.join(rootDir, 'hooks');
6
+ const templateDir = path.join(rootDir, 'git-template');
7
+ return {
8
+ rootDir,
9
+ hooksDir,
10
+ hookScript: path.join(hooksDir, 'post-checkout'),
11
+ templateDir,
12
+ templateHookScript: path.join(templateDir, 'hooks', 'post-checkout'),
13
+ };
14
+ }
@@ -0,0 +1,102 @@
1
+ import inquirer from 'inquirer';
2
+ import chalk from 'chalk';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { extractTicket } from './branch-parser.js';
7
+ import { isRepoIgnored as realIsRepoIgnored } from './hook-ignore.js';
8
+ import { isClockifyEnabled as realIsClockifyEnabled } from './credentials.js';
9
+ import { getJiraSummary as realGetJiraSummary } from './jira-summary.js';
10
+ import { getOpenSession as realGetOpenSession } from './db.js';
11
+ import { matchProjectByTicket } from './project-matcher.js';
12
+ import { startTimer as realStartTimer } from './start-timer.js';
13
+ function defaultReadProjects() {
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = path.dirname(__filename);
16
+ const p = path.join(__dirname, '../data/local-projects.json');
17
+ try {
18
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ }
24
+ export async function runHookPrompt(branch, opts) {
25
+ const d = opts.deps ?? {};
26
+ const isRepoIgnored = d.isRepoIgnored ?? realIsRepoIgnored;
27
+ const isClockifyEnabled = d.isClockifyEnabled ?? realIsClockifyEnabled;
28
+ const getJiraSummary = d.getJiraSummary ?? realGetJiraSummary;
29
+ const getOpenSession = d.getOpenSession ?? realGetOpenSession;
30
+ const readProjects = d.readProjects ?? defaultReadProjects;
31
+ const prompt = d.prompt ?? ((qs) => inquirer.prompt(qs));
32
+ const startTimer = d.startTimer ?? realStartTimer;
33
+ if (isRepoIgnored(opts.cwd)) {
34
+ return { started: false, ticket: null, projectId: null, description: null, reason: 'ignored' };
35
+ }
36
+ let ticket = extractTicket(branch);
37
+ const openSession = getOpenSession();
38
+ if (openSession) {
39
+ const answer = await prompt([
40
+ {
41
+ type: 'confirm',
42
+ name: 'continueAnyway',
43
+ message: `A timer is already running. Stop it manually first, then re-checkout. Continue anyway?`,
44
+ default: false,
45
+ },
46
+ ]);
47
+ if (!answer.continueAnyway) {
48
+ return { started: false, ticket, projectId: null, description: null, reason: 'declined' };
49
+ }
50
+ }
51
+ const promptMsg = ticket
52
+ ? `Start timer for ${chalk.bold(ticket)} (branch: ${branch})?`
53
+ : `Start timer for branch ${chalk.bold(branch)}?`;
54
+ const confirmAnswer = await prompt([{ type: 'confirm', name: 'confirmStart', message: promptMsg, default: true }]);
55
+ if (!confirmAnswer.confirmStart) {
56
+ return { started: false, ticket, projectId: null, description: null, reason: 'declined' };
57
+ }
58
+ if (!ticket) {
59
+ const ticketAnswer = await prompt([{ type: 'input', name: 'ticket', message: 'Enter ticket (empty to skip):' }]);
60
+ const entered = typeof ticketAnswer.ticket === 'string' ? ticketAnswer.ticket : '';
61
+ ticket = entered.trim() ? entered.trim().toUpperCase() : null;
62
+ }
63
+ let defaultDescription = branch;
64
+ if (ticket) {
65
+ const summary = await getJiraSummary(ticket);
66
+ if (summary)
67
+ defaultDescription = summary;
68
+ else
69
+ defaultDescription = ticket;
70
+ }
71
+ const descAnswer = await prompt([
72
+ { type: 'input', name: 'description', message: 'Description:', default: defaultDescription },
73
+ ]);
74
+ const description = String(descAnswer.description);
75
+ let projectId = null;
76
+ if (isClockifyEnabled()) {
77
+ const projects = readProjects();
78
+ const matched = matchProjectByTicket(ticket, projects);
79
+ if (matched) {
80
+ projectId = matched.id;
81
+ console.log(chalk.gray(` Auto-selected project: ${matched.name}`));
82
+ }
83
+ else if (projects.length > 0) {
84
+ const picked = await prompt([
85
+ {
86
+ type: 'list',
87
+ name: 'projectId',
88
+ message: 'Which project?',
89
+ choices: projects.map((p) => ({ name: p.name, value: p.id })),
90
+ },
91
+ ]);
92
+ projectId = String(picked.projectId);
93
+ }
94
+ else {
95
+ console.log(chalk.yellow('No local projects configured. Run `clocktopus start` once to populate.'));
96
+ return { started: false, ticket, projectId: null, description, reason: 'no-ticket' };
97
+ }
98
+ }
99
+ await startTimer({ description, ticket, projectId, billable: true });
100
+ console.log(chalk.green(`Timer started${ticket ? ` for ${chalk.bold(ticket)}` : ''}.`));
101
+ return { started: true, ticket, projectId, description };
102
+ }
@@ -0,0 +1,29 @@
1
+ export const POST_CHECKOUT_SCRIPT = `#!/bin/sh
2
+ # Clocktopus post-checkout hook — auto-installed by \`clocktopus hook:install\`
3
+ # Fires only on branch checkout (flag "1"), not on file checkout.
4
+
5
+ if [ "$3" != "1" ]; then
6
+ exit 0
7
+ fi
8
+
9
+ # Require an attached tty; otherwise the prompt has nowhere to render.
10
+ if ! [ -t 0 ] || ! [ -t 1 ]; then
11
+ exit 0
12
+ fi
13
+
14
+ # Respect user opt-out.
15
+ if [ "$CLOCKTOPUS_HOOK_DISABLE" = "1" ]; then
16
+ exit 0
17
+ fi
18
+
19
+ branch=$(git symbolic-ref --short HEAD 2>/dev/null) || exit 0
20
+ [ -z "$branch" ] && exit 0
21
+
22
+ # Resolve clocktopus binary; silently skip if not installed globally.
23
+ if ! command -v clocktopus >/dev/null 2>&1; then
24
+ exit 0
25
+ fi
26
+
27
+ clocktopus hook:prompt "$branch" </dev/tty >/dev/tty 2>&1 || true
28
+ exit 0
29
+ `;
@@ -0,0 +1,21 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { getHookPaths } from './hook-paths.js';
4
+ export function huskyHookBody() {
5
+ const { hookScript } = getHookPaths();
6
+ return `#!/bin/sh
7
+ exec ${hookScript} "$@"
8
+ `;
9
+ }
10
+ export function installHuskyHook(cwd) {
11
+ const huskyDir = path.join(cwd, '.husky');
12
+ if (!fs.existsSync(huskyDir) || !fs.statSync(huskyDir).isDirectory()) {
13
+ return { installed: false, reason: 'no-husky-dir' };
14
+ }
15
+ const target = path.join(huskyDir, 'post-checkout');
16
+ if (fs.existsSync(target)) {
17
+ return { installed: false, reason: 'already-exists', path: target };
18
+ }
19
+ fs.writeFileSync(target, huskyHookBody(), { mode: 0o755 });
20
+ return { installed: true, path: target };
21
+ }
@@ -0,0 +1,11 @@
1
+ import { getJiraTicket } from './jira.js';
2
+ export async function getJiraSummary(key) {
3
+ try {
4
+ const issue = (await getJiraTicket(key));
5
+ const summary = issue?.fields?.summary;
6
+ return summary && summary.trim() ? summary.trim() : null;
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
@@ -0,0 +1,14 @@
1
+ export function matchProjectByTicket(ticket, projects) {
2
+ if (!ticket)
3
+ return null;
4
+ const prefix = ticket.split('-')[0]?.toUpperCase();
5
+ if (!prefix)
6
+ return null;
7
+ for (const p of projects) {
8
+ if (!p.ticketPrefixes)
9
+ continue;
10
+ if (p.ticketPrefixes.some((tp) => tp.toUpperCase() === prefix))
11
+ return p;
12
+ }
13
+ return null;
14
+ }
@@ -0,0 +1,30 @@
1
+ import { isClockifyEnabled } from './credentials.js';
2
+ export async function startTimer(input) {
3
+ if (!isClockifyEnabled()) {
4
+ if (!input.ticket) {
5
+ throw new Error('Jira-only mode: ticket required');
6
+ }
7
+ const { v4: uuidv4 } = await import('uuid');
8
+ const { logSessionStart } = await import('./db.js');
9
+ const sessionId = uuidv4();
10
+ const startedAt = new Date().toISOString();
11
+ const description = input.description?.trim() || input.ticket;
12
+ logSessionStart(sessionId, null, description, startedAt, input.ticket);
13
+ return { mode: 'jira-only', ticket: input.ticket, projectId: null, description };
14
+ }
15
+ if (!input.projectId) {
16
+ throw new Error('Clockify mode: projectId required');
17
+ }
18
+ const { Clockify } = await import('../clockify.js');
19
+ const clockify = new Clockify();
20
+ const user = await clockify.getUser();
21
+ if (!user)
22
+ throw new Error('Clockify auth failed');
23
+ await clockify.startTimer(user.defaultWorkspace, input.projectId, input.description, input.ticket ?? undefined, input.billable);
24
+ return {
25
+ mode: 'clockify',
26
+ ticket: input.ticket,
27
+ projectId: input.projectId,
28
+ description: input.description,
29
+ };
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clocktopus",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "description": "Time-tracking automation for Clockify with idle monitoring, Jira integration, Google Calendar sync, CLI, web dashboard, and desktop app.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",