@coding-with-hassan/devkit 1.3.0 → 1.5.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.
@@ -1,18 +1,22 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
+ import { TRANSITION_EVENTS } from '../config.js';
4
5
  import { parseEnv } from '../env-block.js';
5
6
 
6
7
  /**
7
8
  * Jira adapter. On `worktree:create`: whoever starts the work owns the ticket, so the
8
9
  * issue is assigned to the current user regardless of status, and a `To Do` issue moves
9
- * to `In Progress`. Best effort throughout — every failure is a `note:`.
10
+ * to `In Progress`. After that the ticket follows its PR: `transitionTicket` moves it to
11
+ * the status `tracker.transitions` names for the event (`prOpened`, `merged`), unless it
12
+ * is already there or further. Best effort throughout — every failure is a `note:`.
10
13
  *
11
14
  * Credentials: `JIRA_EMAIL`, `JIRA_API_TOKEN` and optionally `JIRA_URL` (or `JIRA_BASE_URL`)
12
15
  * from the environment, else from `~/.config/jira/env` (KEY=value lines).
13
16
  */
14
17
 
15
18
  export const JIRA_ENV_FILE = join(homedir(), '.config', 'jira', 'env');
19
+ const CREDENTIALS_HINT = `set JIRA_EMAIL/JIRA_API_TOKEN/JIRA_URL or ${JIRA_ENV_FILE}`;
16
20
 
17
21
  /** Pure: pick credentials from the process env, falling back to the env file's text. */
18
22
  export function resolveJiraCredentials(env, fileText, baseUrlFromConfig) {
@@ -29,11 +33,37 @@ function unquote(obj) {
29
33
  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v.replace(/^(['"])(.*)\1$/, '$2')]));
30
34
  }
31
35
 
36
+ const sameStatus = (a, b) => typeof a === 'string' && typeof b === 'string' && a.trim().toLowerCase() === b.trim().toLowerCase();
37
+
38
+ /**
39
+ * Pure: the transition that lands on the status named `target`, out of the payload of
40
+ * `GET /issue/<key>/transitions` (the transitions available to the ticket right now).
41
+ * `null` when the workflow offers none from the ticket's current status.
42
+ */
43
+ export function pickTransition(payload, target) {
44
+ return (payload?.transitions ?? []).find((t) => sameStatus(t.to?.name, target)) ?? null;
45
+ }
46
+
47
+ /**
48
+ * Pure: where a ticket stands relative to the target status of `event` — `'before'`,
49
+ * `'at'` or `'past'`. Only `'before'` is moved. Past means a done status, or the target
50
+ * status of a later event: a workflow that allows every transition would otherwise let a
51
+ * late `prOpened` pull a ticket back out of `Acceptance`.
52
+ */
53
+ export function ticketStanding({ event, targets, status }) {
54
+ if (sameStatus(status.name, targets[event])) return 'at';
55
+ if (status.category === 'done') return 'past';
56
+ const later = TRANSITION_EVENTS.slice(TRANSITION_EVENTS.indexOf(event) + 1);
57
+ return later.some((e) => sameStatus(status.name, targets[e])) ? 'past' : 'before';
58
+ }
59
+
32
60
  export function loadJiraCredentials(tracker) {
33
61
  const text = existsSync(JIRA_ENV_FILE) ? readFileSync(JIRA_ENV_FILE, 'utf8') : null;
34
62
  return resolveJiraCredentials(process.env, text, tracker.baseUrl);
35
63
  }
36
64
 
65
+ const isComplete = (creds) => Boolean(creds.email && creds.token && creds.baseUrl);
66
+
37
67
  async function api(creds, method, path, body) {
38
68
  const res = await fetch(`${creds.baseUrl}/rest/api/3${path}`, {
39
69
  method,
@@ -50,11 +80,115 @@ async function api(creds, method, path, body) {
50
80
  return text ? JSON.parse(text) : null;
51
81
  }
52
82
 
83
+ const SEARCH_FIELDS = ['summary', 'status', 'issuetype', 'parent', 'issuelinks'];
84
+ const SEARCH_PAGE_SIZE = 100;
85
+ const STATUS_BY_CATEGORY = { new: 'todo', indeterminate: 'in-progress', done: 'done' };
86
+
87
+ /** Pure: every issue of the project that is not done. */
88
+ export const jiraOpenJql = (project) => `project = "${project}" AND statusCategory != Done ORDER BY key ASC`;
89
+
90
+ /** Pure: the issues with these keys, whatever their project or status. */
91
+ export const jiraKeysJql = (keys) => `key in (${keys.map((k) => `"${k}"`).join(', ')})`;
92
+
93
+ /** Pure: one page of `POST /search/jql`; the token of the previous page asks for the next. */
94
+ export function jiraSearchBody(jql, nextPageToken) {
95
+ return { jql, fields: SEARCH_FIELDS, maxResults: SEARCH_PAGE_SIZE, ...(nextPageToken ? { nextPageToken } : {}) };
96
+ }
97
+
98
+ /** Issue type level: 1 and up is an epic (or above), 0 a ticket, -1 a sub-task. */
99
+ const hierarchyLevel = (issue) => issue.fields?.issuetype?.hierarchyLevel ?? (issue.fields?.issuetype?.subtask ? -1 : 0);
100
+ const isBlocks = (link) => /^blocks$/i.test(link.type?.name ?? '');
101
+
102
+ /** The `Blocks` links of one issue as edges plus the linked issue as Jira embeds it (no parent). */
103
+ function blockingLinks(issue) {
104
+ return (issue.fields?.issuelinks ?? []).filter(isBlocks).flatMap((link) => {
105
+ if (link.inwardIssue) return [{ from: link.inwardIssue.key, to: issue.key, linked: link.inwardIssue }];
106
+ if (link.outwardIssue) return [{ from: issue.key, to: link.outwardIssue.key, linked: link.outwardIssue }];
107
+ return [];
108
+ });
109
+ }
110
+
111
+ /** Pure: the keys that block one of `issues` without being among them, in key order. */
112
+ export function jiraMissingReferences(issues) {
113
+ const have = new Set(issues.map((i) => i.key));
114
+ const blockers = issues.flatMap((i) => blockingLinks(i).filter((l) => l.to === i.key).map((l) => l.from));
115
+ return [...new Set(blockers.filter((key) => !have.has(key)))].sort();
116
+ }
117
+
118
+ /**
119
+ * Pure: the open issues plus their blockers — as the second search returned them, else as
120
+ * the link embeds them (status known, epic not).
121
+ */
122
+ export function jiraWithBlockers(open, fetched) {
123
+ const have = new Set([...open, ...fetched].map((issue) => issue.key));
124
+ const embedded = new Map(open.flatMap((issue) => blockingLinks(issue).map((link) => [link.linked.key, link.linked])));
125
+ return [...open, ...fetched, ...jiraMissingReferences(open).filter((key) => !have.has(key)).map((key) => embedded.get(key))];
126
+ }
127
+
128
+ const statusOf = (issue) => STATUS_BY_CATEGORY[issue.fields?.status?.statusCategory?.key] ?? 'todo';
129
+
130
+ /**
131
+ * Pure: Jira issues as the ticket graph's input. Status category comes from the status's own
132
+ * category, so a project's custom statuses need no mapping. Epics (and anything above) become
133
+ * the groups, known from their own issue or from a child naming them as parent; sub-tasks are
134
+ * left out — the chart is about tickets. A link is reported by both of its issues: one edge.
135
+ */
136
+ export function jiraTicketData(issues) {
137
+ const epics = new Map();
138
+ const tickets = [];
139
+ const edges = new Map();
140
+ for (const issue of issues) {
141
+ const level = hierarchyLevel(issue);
142
+ if (level >= 1) epics.set(issue.key, { key: issue.key, title: issue.fields.summary, status: statusOf(issue) });
143
+ if (level !== 0) continue;
144
+ const parent = issue.fields.parent ?? null;
145
+ if (parent && !epics.has(parent.key)) epics.set(parent.key, { key: parent.key, title: parent.fields?.summary ?? '', status: statusOf(parent) });
146
+ tickets.push({ key: issue.key, title: issue.fields.summary, status: statusOf(issue), epic: parent?.key ?? null });
147
+ for (const { from, to } of blockingLinks(issue)) edges.set(`${from}\n${to}`, { from, to });
148
+ }
149
+ return { tickets, epics: [...epics.values()], edges: [...edges.values()] };
150
+ }
151
+
152
+ /** Every issue a JQL query matches, page by page. */
153
+ async function search(creds, jql) {
154
+ const issues = [];
155
+ let token = null;
156
+ do {
157
+ const page = (await api(creds, 'POST', '/search/jql', jiraSearchBody(jql, token))) ?? {};
158
+ issues.push(...(page.issues ?? []));
159
+ token = page.nextPageToken ?? null;
160
+ } while (token);
161
+ return issues;
162
+ }
163
+
53
164
  export const jiraAdapter = {
165
+ /**
166
+ * The project's issues that are not done, plus the issues blocking them (done ones, other
167
+ * projects' ones) in a second search so they come with their epic. A blocker that search
168
+ * does not return is taken as the link embeds it: status known, epic not.
169
+ */
170
+ async readTickets({ tracker, note }) {
171
+ const creds = loadJiraCredentials(tracker);
172
+ if (!isComplete(creds)) {
173
+ throw new Error(`Jira credentials unavailable — ${CREDENTIALS_HINT}`);
174
+ }
175
+ const open = await search(creds, jiraOpenJql(tracker.project));
176
+ const missing = jiraMissingReferences(open);
177
+ const fetched = [];
178
+ for (let i = 0; i < missing.length; i += SEARCH_PAGE_SIZE) {
179
+ try {
180
+ fetched.push(...(await search(creds, jiraKeysJql(missing.slice(i, i + SEARCH_PAGE_SIZE)))));
181
+ } catch (e) {
182
+ note(`reading the blocking issues failed (${e.message}) — they are drawn without their epic`);
183
+ }
184
+ }
185
+ return jiraTicketData(jiraWithBlockers(open, fetched));
186
+ },
187
+
54
188
  async startTicket({ key, tracker, log, note }) {
55
189
  const creds = loadJiraCredentials(tracker);
56
- if (!creds.email || !creds.token || !creds.baseUrl) {
57
- note(`Jira credentials unavailable (set JIRA_EMAIL/JIRA_API_TOKEN/JIRA_URL or ${JIRA_ENV_FILE}) — assign ${key} to yourself and move it to In Progress`);
190
+ if (!isComplete(creds)) {
191
+ note(`Jira credentials unavailable (${CREDENTIALS_HINT}) — assign ${key} to yourself and move it to In Progress`);
58
192
  return;
59
193
  }
60
194
  let me = null;
@@ -82,8 +216,7 @@ export const jiraAdapter = {
82
216
  }
83
217
  let transitionId = null;
84
218
  try {
85
- const { transitions = [] } = (await api(creds, 'GET', `/issue/${key}/transitions`)) ?? {};
86
- transitionId = transitions.find((t) => t.to?.name === 'In Progress')?.id ?? null;
219
+ transitionId = pickTransition(await api(creds, 'GET', `/issue/${key}/transitions`), 'In Progress')?.id ?? null;
87
220
  } catch {
88
221
  transitionId = null;
89
222
  }
@@ -98,4 +231,48 @@ export const jiraAdapter = {
98
231
  note(`transitioning ${key} failed (${e.message}) — move it to In Progress yourself`);
99
232
  }
100
233
  },
234
+
235
+ async transitionTicket({ key, event, tracker, log, note }) {
236
+ const target = tracker.transitions?.[event] ?? null;
237
+ if (!target) {
238
+ log(`Jira: the '${event}' transition is off — leaving ${key} alone`);
239
+ return;
240
+ }
241
+ const byHand = `move ${key} to ${target} yourself`;
242
+ const creds = loadJiraCredentials(tracker);
243
+ if (!isComplete(creds)) {
244
+ note(`Jira credentials unavailable (${CREDENTIALS_HINT}) — ${byHand}`);
245
+ return;
246
+ }
247
+ let status = null;
248
+ try {
249
+ const current = (await api(creds, 'GET', `/issue/${key}?fields=status`))?.fields?.status;
250
+ status = { name: current?.name ?? null, category: current?.statusCategory?.key ?? null };
251
+ } catch (e) {
252
+ note(`reading the status of ${key} failed (${e.message}) — ${byHand}`);
253
+ return;
254
+ }
255
+ const standing = ticketStanding({ event, targets: tracker.transitions, status });
256
+ if (standing !== 'before') {
257
+ log(`Jira: ${key} is ${standing === 'at' ? `already '${status.name}'` : `'${status.name}', past ${target}`} — leaving its status alone`);
258
+ return;
259
+ }
260
+ let transition = null;
261
+ try {
262
+ transition = pickTransition(await api(creds, 'GET', `/issue/${key}/transitions`), target);
263
+ } catch (e) {
264
+ note(`reading the transitions of ${key} failed (${e.message}) — ${byHand}`);
265
+ return;
266
+ }
267
+ if (!transition) {
268
+ note(`${key} has no transition from '${status.name}' to ${target} — ${byHand}`);
269
+ return;
270
+ }
271
+ try {
272
+ await api(creds, 'POST', `/issue/${key}/transitions`, { transition: { id: transition.id } });
273
+ log(`Jira: ${key} → ${target}`);
274
+ } catch (e) {
275
+ note(`transitioning ${key} failed (${e.message}) — ${byHand}`);
276
+ }
277
+ },
101
278
  };
@@ -2,13 +2,13 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFile
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
3
  import { loadProfiles } from './compose.js';
4
4
  import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
5
- import { expandEnv, imageTag, imageTagInputs, sanitizeName } from './derive.js';
5
+ import { expandEnv, imageTag, imageTagInputs, sanitizeName, ticketKeyFromBranch } from './derive.js';
6
6
  import { managedValues, parseEnv, writeManagedBlock } from './env-block.js';
7
7
  import { commandExists, run } from './exec.js';
8
8
  import * as git from './git.js';
9
9
  import { withLock } from './locks.js';
10
10
  import * as stack from './stack.js';
11
- import { startTicket } from './tracker/index.js';
11
+ import { startTicket, transitionTicket } from './tracker/index.js';
12
12
  import { listProjects } from './workspace.js';
13
13
 
14
14
  /**
@@ -502,7 +502,10 @@ export async function cmdRemove(ctx, name, { keepData = false, force = false } =
502
502
  ctx.log(`removed ${dir} (branch kept — delete it with: git branch -D ${basename(dir)})`);
503
503
  }
504
504
 
505
- /** `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle). */
505
+ /**
506
+ * `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle) and
507
+ * report the merge to the tracker for the ticket of each one it removed.
508
+ */
506
509
  export async function cmdPrune(ctx, { dryRun = false } = {}) {
507
510
  if (!commandExists('gh')) {
508
511
  ctx.note('gh not installed — cannot check PR states, skipping prune');
@@ -539,12 +542,16 @@ export async function cmdPrune(ctx, { dryRun = false } = {}) {
539
542
  continue;
540
543
  }
541
544
  ctx.log(`prune: ${entry.name}: PR merged — removing worktree, containers, volumes, and branch`);
545
+ const key = ticketKeyFromBranch(branch, ctx.tracker);
542
546
  if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: true });
543
547
  if (await git.worktreeRemove(ctx.mainRoot, dir)) {
544
548
  await git.branchDelete(ctx.mainRoot, branch);
545
549
  removed.push(entry.name);
550
+ await transitionTicket({ key, event: 'merged', tracker: ctx.tracker, log: ctx.log, note: ctx.note });
546
551
  } else {
547
- ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}`);
552
+ // The ticket only moves with the worktree prune removes; this one is left to the developer.
553
+ const move = key && ctx.tracker.transitions?.merged ? ` && hassan-devkit tracker:transition ${key} merged` : '';
554
+ ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}${move}`);
548
555
  }
549
556
  }
550
557
  if (!dryRun) pruneImages(ctx);
package/src/index.js CHANGED
@@ -6,10 +6,12 @@ import { registerI18n } from './commands/i18n.js';
6
6
  import { registerInit } from './commands/init.js';
7
7
  import { registerConfig } from './commands/config.js';
8
8
  import { registerWorktree } from './commands/worktree.js';
9
+ import { registerTracker } from './commands/tracker.js';
9
10
  import { registerCi } from './commands/ci.js';
10
11
  import { registerClaude } from './commands/claude.js';
11
12
  import { registerFormat } from './commands/format.js';
12
13
  import { registerTestCases } from './commands/test-cases.js';
14
+ import { registerTickets } from './commands/tickets.js';
13
15
 
14
16
  export function run(argv) {
15
17
  const cli = cac('hassan-devkit');
@@ -17,10 +19,12 @@ export function run(argv) {
17
19
  registerInit(cli);
18
20
  registerConfig(cli);
19
21
  registerWorktree(cli);
22
+ registerTracker(cli);
20
23
  registerCi(cli);
21
24
  registerClaude(cli);
22
25
  registerFormat(cli);
23
26
  registerTestCases(cli);
27
+ registerTickets(cli);
24
28
  registerDocker(cli);
25
29
  registerDb(cli);
26
30
  registerHooks(cli);