@ggdna/dna-plan 3.4.0 → 4.1.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.
@@ -0,0 +1,909 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * @license
5
+ * Copyright (c) dnaCopyrightHolder
6
+ *
7
+ * Use of this source code is governed by terms that can be
8
+ * found in the LICENSE file in the root of this package.
9
+ */
10
+
11
+ // Syncs the user stories of a PM repo with Jira, in both directions.
12
+ // Only stories go to Jira; tickets stay in the repo.
13
+ //
14
+ // Usage: node scripts/jira-sync.js <command> [files...] [options]
15
+ //
16
+ // status what is new, changed or in conflict; changes nothing
17
+ // pull shows what changed in Jira and the stories that exist
18
+ // only in Jira; --write takes over sprint and lead
19
+ // push [files] creates and updates the stories in Jira; without
20
+ // files every story that is new or changed in the repo;
21
+ // --write sends it, --resolved <file> marks a story
22
+ // whose Jira changes were worked into the file
23
+ //
24
+ // Options: --repo <dir> (default: the current directory), --write,
25
+ // --resolved <file> (repeatable). The settings are in jira.jsonc at the
26
+ // root of the repo, the token in the environment variable JIRA_TOKEN.
27
+
28
+ import fs from 'fs';
29
+ import path from 'path';
30
+ import crypto from 'crypto';
31
+
32
+ // .............................................................................
33
+ // Command line
34
+
35
+ function parseArgs(argv) {
36
+ const args = { command: argv[0], files: [], resolved: [], write: false };
37
+ for (let i = 1; i < argv.length; i++) {
38
+ const a = argv[i];
39
+ if (a === '--write') args.write = true;
40
+ else if (a === '--repo') args.repo = value(argv, i++);
41
+ else if (a === '--resolved') args.resolved.push(value(argv, i++));
42
+ else if (a.startsWith('--')) fail(`Unknown option ${a}.`);
43
+ else args.files.push(a);
44
+ }
45
+ return args;
46
+ }
47
+
48
+ function value(argv, i) {
49
+ const v = argv[i + 1];
50
+ if (v === undefined || v.startsWith('--')) fail(`${argv[i]} needs a value.`);
51
+ return v;
52
+ }
53
+
54
+ function escapeRe(text) {
55
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
+ }
57
+
58
+ function fail(message) {
59
+ const error = new Error(message);
60
+ error.isUserError = true;
61
+ throw error;
62
+ }
63
+
64
+ // .............................................................................
65
+ // Settings
66
+
67
+ const defaults = {
68
+ issueType: 'Story',
69
+ language: null,
70
+ sprint: null,
71
+ repoBranch: 'main',
72
+ fields: { acceptanceCriteria: null, sprint: null, estimate: null },
73
+ sections: {
74
+ status: 'Status',
75
+ acceptanceCriteria: 'Acceptance criteria',
76
+ description: ['Story', 'Not yet', 'Tickets', 'Contributes to', 'Questions'],
77
+ },
78
+ statusFields: {
79
+ jira: 'Jira',
80
+ status: 'Status',
81
+ sprint: 'Sprint',
82
+ lead: 'Lead',
83
+ estimate: 'Estimate',
84
+ },
85
+ statuses: {},
86
+ footer: 'Source: {link} in the project management repo.',
87
+ };
88
+
89
+ // Reads JSON with // and /* */ comments and trailing commas
90
+ function parseJsonc(text) {
91
+ let out = '';
92
+ let inString = false;
93
+ for (let i = 0; i < text.length; i++) {
94
+ const c = text[i];
95
+ if (inString) {
96
+ out += c;
97
+ if (c === '\\') out += text[++i];
98
+ else if (c === '"') inString = false;
99
+ } else if (c === '"') {
100
+ inString = true;
101
+ out += c;
102
+ } else if (c === '/' && text[i + 1] === '/') {
103
+ while (i < text.length && text[i] !== '\n') i++;
104
+ out += '\n';
105
+ } else if (c === '/' && text[i + 1] === '*') {
106
+ i = text.indexOf('*/', i + 2) + 1;
107
+ } else out += c;
108
+ }
109
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
110
+ }
111
+
112
+ function loadConfig(root) {
113
+ const file = path.join(root, 'jira.jsonc');
114
+ if (!fs.existsSync(file))
115
+ fail(
116
+ `${file} is missing. Create it as the Jira sync guide ` +
117
+ '(doc/en/guides/jira-sync-guide.md) says.',
118
+ );
119
+ const own = parseJsonc(fs.readFileSync(file, 'utf8'));
120
+ const config = {
121
+ ...defaults,
122
+ ...own,
123
+ fields: { ...defaults.fields, ...own.fields },
124
+ sections: { ...defaults.sections, ...own.sections },
125
+ statusFields: { ...defaults.statusFields, ...own.statusFields },
126
+ };
127
+ for (const key of ['baseUrl', 'project', 'label', 'repoUrl'])
128
+ if (!config[key]) fail(`jira.jsonc: "${key}" is missing.`);
129
+ if (process.env.JIRA_URL) config.baseUrl = process.env.JIRA_URL;
130
+ config.baseUrl = config.baseUrl.replace(/\/+$/, '');
131
+ return config;
132
+ }
133
+
134
+ // .............................................................................
135
+ // The repo
136
+
137
+ function languages(root) {
138
+ const pm = path.join(root, 'pm');
139
+ if (!fs.existsSync(pm)) fail(`${root} has no pm folder; is it a PM repo?`);
140
+ return fs
141
+ .readdirSync(pm)
142
+ .filter((d) => fs.statSync(path.join(pm, d)).isDirectory());
143
+ }
144
+
145
+ function currentQuarter(root, lang) {
146
+ const dir = path.join(root, 'pm', lang);
147
+ const quarters = fs
148
+ .readdirSync(dir)
149
+ .filter((d) => /^\d{4}-Q[1-4]$/.test(d))
150
+ .sort();
151
+ if (!quarters.length) fail(`pm/${lang} has no quarter folder.`);
152
+ return quarters[quarters.length - 1];
153
+ }
154
+
155
+ function posix(p) {
156
+ return p.split(path.sep).join('/');
157
+ }
158
+
159
+ class Repo {
160
+ constructor(root, config) {
161
+ this.root = root;
162
+ this.config = config;
163
+ this.langs = languages(root);
164
+ this.lang = config.language ?? this.langs[0];
165
+ if (!this.langs.includes(this.lang))
166
+ fail(`jira.jsonc: language "${this.lang}" has no folder pm/${this.lang}.`);
167
+ this.quarter = currentQuarter(root, this.lang);
168
+ }
169
+
170
+ storiesDir(lang = this.lang) {
171
+ return posix(path.join('pm', lang, this.quarter, 'stories'));
172
+ }
173
+
174
+ stories() {
175
+ const dir = path.join(this.root, this.storiesDir());
176
+ if (!fs.existsSync(dir)) return [];
177
+ return fs
178
+ .readdirSync(dir)
179
+ .filter((f) => f.endsWith('.md') && !f.startsWith('000-'))
180
+ .sort()
181
+ .map((f) => this.readStory(`${this.storiesDir()}/${f}`));
182
+ }
183
+
184
+ readStory(file) {
185
+ const text = fs.readFileSync(path.join(this.root, file), 'utf8');
186
+ return parseStory(file, text, this.config);
187
+ }
188
+
189
+ copies(basename) {
190
+ return this.langs
191
+ .map((lang) => `${this.storiesDir(lang)}/${basename}`)
192
+ .filter((f) => fs.existsSync(path.join(this.root, f)));
193
+ }
194
+
195
+ read(file) {
196
+ return fs.readFileSync(path.join(this.root, file), 'utf8');
197
+ }
198
+
199
+ write(file, text) {
200
+ fs.writeFileSync(path.join(this.root, file), text);
201
+ }
202
+
203
+ // The markdown files that may link a story: the current quarter of
204
+ // every language and the READMEs; older quarters are never changed
205
+ markdownFiles() {
206
+ const out = [];
207
+ const walk = (dir) => {
208
+ if (!fs.existsSync(path.join(this.root, dir))) return;
209
+ for (const e of fs.readdirSync(path.join(this.root, dir), {
210
+ withFileTypes: true,
211
+ })) {
212
+ const rel = `${dir}/${e.name}`;
213
+ if (e.isDirectory()) walk(rel);
214
+ else if (e.name.endsWith('.md')) out.push(rel);
215
+ }
216
+ };
217
+ for (const lang of this.langs) walk(`pm/${lang}/${this.quarter}`);
218
+ for (const f of fs.readdirSync(this.root))
219
+ if (/^README(\.[a-z]+)?\.md$/.test(f)) out.push(f);
220
+ return out;
221
+ }
222
+
223
+ // The Jira name of each person, from team/people.md
224
+ people(lang = this.lang) {
225
+ const file = path.join(this.root, 'pm', lang, this.quarter, 'team', 'people.md');
226
+ const map = {};
227
+ if (!fs.existsSync(file)) return map;
228
+ let name = null;
229
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
230
+ const h = line.match(/^## (.+?)\s*$/);
231
+ if (h) name = h[1];
232
+ const j = line.match(/^- Jira:\s*(\S+)/);
233
+ if (j && name) map[name] = j[1];
234
+ }
235
+ return map;
236
+ }
237
+
238
+ link(file, target = path.posix.basename(file)) {
239
+ if (/^[a-z]+:/i.test(target)) return target;
240
+ const rel = target.split('#')[0];
241
+ if (!rel) return null;
242
+ const abs = path.posix.normalize(
243
+ path.posix.join(path.posix.dirname(file), rel),
244
+ );
245
+ const { repoUrl, repoBranch } = this.config;
246
+ if (/dev\.azure\.com|visualstudio\.com/.test(repoUrl))
247
+ return `${repoUrl}?path=/${abs}&version=GB${repoBranch}&_a=preview`;
248
+ return `${repoUrl.replace(/\.git$/, '')}/blob/${repoBranch}/${abs}`;
249
+ }
250
+ }
251
+
252
+ // .............................................................................
253
+ // Stories
254
+
255
+ function parseStory(file, text, config) {
256
+ const lines = text.split(/\r?\n/);
257
+ const head = (lines[0] ?? '').match(/^# ([^:]+): (.*)$/);
258
+ if (!head)
259
+ fail(`${file}: the first line must be "# <number>: <title>", it is "${lines[0]}".`);
260
+ const sections = {};
261
+ let current = null;
262
+ for (const line of lines.slice(1)) {
263
+ const h = line.match(/^## (.*?)\s*$/);
264
+ if (h) {
265
+ current = h[1];
266
+ sections[current] = [];
267
+ } else if (current) sections[current].push(line);
268
+ }
269
+ for (const k of Object.keys(sections))
270
+ sections[k] = sections[k].join('\n').trim();
271
+ const status = statusTable(sections[config.sections.status] ?? '');
272
+ const jiraValue = status[config.statusFields.jira] ?? '';
273
+ const key = jiraValue.match(new RegExp(`\\b${config.project}-\\d+\\b`))?.[0] ?? null;
274
+ return {
275
+ file,
276
+ basename: path.posix.basename(file),
277
+ number: head[1],
278
+ title: head[2],
279
+ sections,
280
+ status,
281
+ key,
282
+ text,
283
+ };
284
+ }
285
+
286
+ function statusTable(md) {
287
+ const fields = {};
288
+ for (const line of md.split('\n')) {
289
+ const m = line.match(/^\|\s*([^|]+?):\s*\|\s*(.*?)\s*\|\s*$/);
290
+ if (m) fields[m[1]] = m[2];
291
+ }
292
+ return fields;
293
+ }
294
+
295
+ // Sets a row of the status table; null when the table has no such row
296
+ function setStatusField(text, field, value) {
297
+ const re = new RegExp(
298
+ `^(\\|\\s*${escapeRe(field)}:\\s*\\|\\s*)(.*?)(\\s*\\|\\s*)$`,
299
+ 'm',
300
+ );
301
+ if (!re.test(text)) return null;
302
+ return text.replace(re, (_, a, _old, c) => `${a}${value}${c}`);
303
+ }
304
+
305
+ function hash(value) {
306
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
307
+ return crypto.createHash('sha256').update(text).digest('hex').slice(0, 16);
308
+ }
309
+
310
+ // .............................................................................
311
+ // Markdown to Jira wiki markup
312
+
313
+ function inline(md, link) {
314
+ return md
315
+ .replace(/\\\|/g, '&#124;')
316
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, text, target) => {
317
+ const url = link(target);
318
+ return url ? `[${text.replace(/\|/g, '-')}|${url}]` : text;
319
+ })
320
+ .replace(/`([^`]+)`/g, '{{$1}}')
321
+ .replace(/\*\*([^*]+)\*\*/g, '*$1*');
322
+ }
323
+
324
+ // One line per paragraph, list item or table row
325
+ function blocks(md) {
326
+ const out = [];
327
+ for (const line of md.split('\n')) {
328
+ const starts =
329
+ /^\s*([-*]|\d+\.) /.test(line) ||
330
+ /^\s*[|>]/.test(line) ||
331
+ line.trim() === '' ||
332
+ out.length === 0 ||
333
+ out[out.length - 1].trim() === '';
334
+ if (starts) out.push(line);
335
+ else out[out.length - 1] += ' ' + line.trim();
336
+ }
337
+ return out;
338
+ }
339
+
340
+ function toWiki(md, link) {
341
+ const out = [];
342
+ let quote = null;
343
+ const flushQuote = () => {
344
+ if (quote !== null) out.push(`{quote}${inline(quote, link)}{quote}`);
345
+ quote = null;
346
+ };
347
+ for (const line of blocks(md)) {
348
+ const q = line.match(/^>\s?(.*)$/);
349
+ if (q) {
350
+ quote = quote === null ? q[1] : `${quote} ${q[1]}`;
351
+ continue;
352
+ }
353
+ flushQuote();
354
+ if (line.trim() === '') {
355
+ out.push('');
356
+ continue;
357
+ }
358
+ const item = line.match(/^(\s*)(?:[-*]|\d+\.) (\[([ xX])\] )?(.*)$/);
359
+ if (item) {
360
+ const depth = Math.floor(item[1].length / 2) + 1;
361
+ const box = item[2] ? (item[3] === ' ' ? '☐ ' : '☑ ') : '';
362
+ out.push(`${'*'.repeat(depth)} ${box}${inline(item[4], link)}`);
363
+ continue;
364
+ }
365
+ if (/^\s*\|/.test(line)) {
366
+ if (/^\s*\|[\s|:-]+\|\s*$/.test(line)) continue;
367
+ const cells = line
368
+ .trim()
369
+ .replace(/^\|/, '')
370
+ .replace(/\|$/, '')
371
+ .split(/(?<!\\)\|/)
372
+ .map((c) => inline(c.trim(), link) || ' ');
373
+ const header = !out.length || !out[out.length - 1].startsWith('|');
374
+ out.push(header ? `||${cells.join('||')}||` : `|${cells.join('|')}|`);
375
+ continue;
376
+ }
377
+ out.push(inline(line.trim(), link));
378
+ }
379
+ flushQuote();
380
+ return out.join('\n').trim();
381
+ }
382
+
383
+ // .............................................................................
384
+ // Jira text back to Markdown, as a draft for the person who works it in
385
+
386
+ function wikiToMarkdown(wiki) {
387
+ return wiki
388
+ .replace(/^h([1-6])\.\s*/gm, (_, n) => `${'#'.repeat(Number(n))} `)
389
+ .replace(/\{quote\}([\s\S]*?)\{quote\}/g, (_, t) =>
390
+ t
391
+ .trim()
392
+ .split('\n')
393
+ .map((l) => `> ${l}`)
394
+ .join('\n'),
395
+ )
396
+ .replace(/^(\*+) /gm, (_, s) => `${' '.repeat(s.length - 1)}- `)
397
+ .replace(/^(\s*- )☐ /gm, '$1[ ] ')
398
+ .replace(/^(\s*- )☑ /gm, '$1[x] ')
399
+ .replace(/\[([^|\]]+)\|([^\]]+)\]/g, '[$1]($2)')
400
+ .replace(/\{\{([^}]+)\}\}/g, '`$1`')
401
+ .replace(/^\|\|(.*)\|\|\s*$/gm, (_, h) => {
402
+ const cells = h.split('||');
403
+ return `| ${cells.join(' | ')} |\n|${cells.map(() => ' --- |').join('')}`;
404
+ })
405
+ .replace(/&#124;/g, '\\|');
406
+ }
407
+
408
+ function htmlToMarkdown(html) {
409
+ return html
410
+ .replace(/<br\s*\/?>/gi, '\n')
411
+ .replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi, (_, n, t) => `\n${'#'.repeat(Number(n))} ${t}\n`)
412
+ .replace(/<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi, (_, t) => `\n> ${t.trim()}\n`)
413
+ .replace(/<li[^>]*>/gi, '\n- ')
414
+ .replace(/<a [^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, '[$2]($1)')
415
+ .replace(/<(strong|b)>([\s\S]*?)<\/\1>/gi, '**$2**')
416
+ .replace(/<(code|tt)>([\s\S]*?)<\/\1>/gi, '`$2`')
417
+ .replace(/<\/(p|div|ul|ol|tr|table)>/gi, '\n')
418
+ .replace(/<t[hd][^>]*>/gi, ' | ')
419
+ .replace(/<[^>]+>/g, '')
420
+ .replace(/&nbsp;/g, ' ')
421
+ .replace(/&amp;/g, '&')
422
+ .replace(/&lt;/g, '<')
423
+ .replace(/&gt;/g, '>')
424
+ .replace(/&quot;/g, '"')
425
+ .replace(/\n{3,}/g, '\n\n')
426
+ .trim();
427
+ }
428
+
429
+ function toMarkdown(text) {
430
+ if (!text) return '';
431
+ return /^\s*</.test(text) ? htmlToMarkdown(text) : wikiToMarkdown(text);
432
+ }
433
+
434
+ // .............................................................................
435
+ // Jira
436
+
437
+ class Jira {
438
+ constructor(config) {
439
+ this.config = config;
440
+ this.token = process.env.JIRA_TOKEN;
441
+ if (!this.token)
442
+ fail(
443
+ 'JIRA_TOKEN is not set. Create a personal access token in Jira ' +
444
+ '(profile → Personal Access Tokens) and set it, see ' +
445
+ 'doc/en/guides/jira-sync-guide.md.',
446
+ );
447
+ }
448
+
449
+ async call(method, route, body) {
450
+ const url = `${this.config.baseUrl}/rest/api/2${route}`;
451
+ let res;
452
+ try {
453
+ res = await fetch(url, {
454
+ method,
455
+ headers: {
456
+ Authorization: `Bearer ${this.token}`,
457
+ 'Content-Type': 'application/json',
458
+ Accept: 'application/json',
459
+ },
460
+ body: body === undefined ? undefined : JSON.stringify(body),
461
+ });
462
+ } catch (e) {
463
+ fail(`Jira at ${this.config.baseUrl} is not reachable: ${e.message}. Check baseUrl in jira.jsonc and the network.`);
464
+ }
465
+ const text = await res.text();
466
+ if (res.status === 401)
467
+ fail('Jira rejected the token (401). Create a new personal access token and set JIRA_TOKEN.');
468
+ if (res.status === 404 && method === 'GET') return null;
469
+ if (!res.ok)
470
+ fail(`Jira answered ${method} ${route} with ${res.status}: ${text.slice(0, 400)}`);
471
+ return text ? JSON.parse(text) : null;
472
+ }
473
+
474
+ fieldList() {
475
+ const f = this.config.fields;
476
+ return ['summary', 'description', 'status', 'assignee', 'labels', f.acceptanceCriteria, f.sprint]
477
+ .filter(Boolean)
478
+ .join(',');
479
+ }
480
+
481
+ async issue(key) {
482
+ return this.call('GET', `/issue/${key}?fields=${this.fieldList()}`);
483
+ }
484
+
485
+ async labelled() {
486
+ const jql = `project = "${this.config.project}" AND labels = "${this.config.label}" ORDER BY key`;
487
+ const out = [];
488
+ for (let start = 0; ; start += 100) {
489
+ const page = await this.call(
490
+ 'GET',
491
+ `/search?jql=${encodeURIComponent(jql)}&startAt=${start}&maxResults=100&fields=${this.fieldList()}`,
492
+ );
493
+ out.push(...page.issues);
494
+ if (start + page.issues.length >= page.total || !page.issues.length) break;
495
+ }
496
+ return out;
497
+ }
498
+
499
+ async property(key) {
500
+ const p = await this.call('GET', `/issue/${key}/properties/pmRepo`);
501
+ return p?.value ?? null;
502
+ }
503
+
504
+ async setProperty(key, value) {
505
+ await this.call('PUT', `/issue/${key}/properties/pmRepo`, value);
506
+ }
507
+
508
+ // Walks the issue along the statuses of path, one transition each;
509
+ // false when a step is not offered
510
+ async transitionTo(key, path) {
511
+ const issue = await this.call('GET', `/issue/${key}?fields=status`);
512
+ const current = issue.fields.status.name;
513
+ const at = path.lastIndexOf(current);
514
+ if (at === path.length - 1) return true;
515
+ for (const target of path.slice(at + 1)) {
516
+ const { transitions } = await this.call('GET', `/issue/${key}/transitions`);
517
+ const t = transitions.find((x) => x.to.name === target);
518
+ if (!t) return false;
519
+ await this.call('POST', `/issue/${key}/transitions`, { transition: { id: t.id } });
520
+ }
521
+ return true;
522
+ }
523
+ }
524
+
525
+ // What the sync compares on the Jira side
526
+ function jiraSnapshot(issue, config) {
527
+ const f = issue.fields;
528
+ const sprints = (config.fields.sprint ? f[config.fields.sprint] ?? [] : []).map((s) => {
529
+ if (typeof s === 'object') return { id: s.id, name: s.name };
530
+ return {
531
+ id: Number(s.match(/id=(\d+)/)?.[1]),
532
+ name: s.match(/name=([^,\]]*)/)?.[1],
533
+ };
534
+ });
535
+ return {
536
+ summary: f.summary ?? '',
537
+ status: f.status?.name ?? '',
538
+ assignee: f.assignee?.name ?? f.assignee?.accountId ?? null,
539
+ sprint: sprints.length ? sprints[sprints.length - 1] : null,
540
+ description: hash(f.description ?? ''),
541
+ acceptanceCriteria: config.fields.acceptanceCriteria
542
+ ? hash(f[config.fields.acceptanceCriteria] ?? '')
543
+ : null,
544
+ };
545
+ }
546
+
547
+ // The hash of a snapshot: a sprint counts by its id, so a renamed or
548
+ // started sprint changes nothing
549
+ function snapshotHash(snapshot) {
550
+ return hash({ ...snapshot, sprint: snapshot.sprint?.id ?? null });
551
+ }
552
+
553
+ // .............................................................................
554
+ // Building the issue fields from a story
555
+
556
+ function issueFields(repo, story) {
557
+ const { config } = repo;
558
+ const link = (target) => repo.link(story.file, target);
559
+ const description = [];
560
+ for (const name of config.sections.description) {
561
+ const md = story.sections[name];
562
+ if (md) description.push(`h2. ${name}`, '', toWiki(md, link), '');
563
+ }
564
+ description.push(
565
+ '----',
566
+ config.footer.replace('{link}', `[${story.basename}|${repo.link(story.file)}]`),
567
+ );
568
+ const fields = {
569
+ summary: story.title,
570
+ description: description.join('\n'),
571
+ };
572
+ const ac = story.sections[config.sections.acceptanceCriteria];
573
+ if (config.fields.acceptanceCriteria) fields[config.fields.acceptanceCriteria] = toWiki(ac ?? '', link);
574
+ else if (ac) fields.description = `h2. ${config.sections.acceptanceCriteria}\n\n${toWiki(ac, link)}\n\n${fields.description}`;
575
+ // No lead clears the assignee; a lead without a Jira name leaves it
576
+ const lead = leadName(story, config);
577
+ const jiraName = lead && repo.people()[lead];
578
+ if (jiraName) fields.assignee = { name: jiraName };
579
+ else if (!lead) fields.assignee = null;
580
+ if (config.fields.estimate) {
581
+ const n = parseFloat((story.status[config.statusFields.estimate] ?? '').replace(',', '.'));
582
+ if (!Number.isNaN(n)) fields[config.fields.estimate] = n;
583
+ }
584
+ return fields;
585
+ }
586
+
587
+ function leadName(story, config) {
588
+ const v = (story.status[config.statusFields.lead] ?? '').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').trim();
589
+ return v && !/^(offen|open|n\. ?n\.|-)$/i.test(v) ? v : null;
590
+ }
591
+
592
+ // The Jira statuses to walk to for the status of the story: one status,
593
+ // or a path when Jira offers no direct transition
594
+ function targetStatus(story, config) {
595
+ const value = story.status[config.statusFields.status];
596
+ const target = value ? config.statuses[value] : null;
597
+ if (!target) return null;
598
+ return Array.isArray(target) ? target : [target];
599
+ }
600
+
601
+ // .............................................................................
602
+ // Comparing both sides
603
+
604
+ async function compare(repo, jira) {
605
+ const stories = repo.stories();
606
+ const issues = await jira.labelled();
607
+ const byKey = new Map(issues.map((i) => [i.key, i]));
608
+ // One round trip for all keyed stories, not one after the other
609
+ const keyed = stories.filter((s) => s.key);
610
+ const fetched = await Promise.all(
611
+ keyed.map(async (s) => ({
612
+ issue: byKey.get(s.key) ?? (await jira.issue(s.key)),
613
+ prop: await jira.property(s.key),
614
+ })),
615
+ );
616
+ const byStory = new Map(keyed.map((s, i) => [s, fetched[i]]));
617
+ const result = [];
618
+ for (const story of stories) {
619
+ if (!story.key) {
620
+ result.push({ state: 'new in repo', story });
621
+ continue;
622
+ }
623
+ const { issue, prop } = byStory.get(story);
624
+ byKey.delete(story.key);
625
+ if (!issue) {
626
+ result.push({ state: 'missing in Jira', story });
627
+ continue;
628
+ }
629
+ const snapshot = jiraSnapshot(issue, repo.config);
630
+ const repoChanged = !prop || prop.repoHash !== hash(story.text);
631
+ const jiraChanged = !prop || prop.jiraHash !== snapshotHash(snapshot);
632
+ const state = !prop
633
+ ? 'not linked yet'
634
+ : repoChanged && jiraChanged
635
+ ? 'conflict'
636
+ : repoChanged
637
+ ? 'changed in repo'
638
+ : jiraChanged
639
+ ? 'changed in Jira'
640
+ : 'in sync';
641
+ result.push({ state, story, issue, prop, snapshot });
642
+ }
643
+ for (const issue of byKey.values())
644
+ result.push({ state: 'new in Jira', issue, snapshot: jiraSnapshot(issue, repo.config) });
645
+ return result;
646
+ }
647
+
648
+ function describe(entry) {
649
+ const name = entry.story ? entry.story.basename : entry.issue.key;
650
+ const key = entry.story?.key ?? entry.issue?.key ?? entry.story?.number ?? '—';
651
+ return `${entry.state.padEnd(16)} ${key.padEnd(10)} ${name}`;
652
+ }
653
+
654
+ // .............................................................................
655
+ // status
656
+
657
+ async function status(repo, jira) {
658
+ const entries = await compare(repo, jira);
659
+ if (!entries.length) console.log('No stories in the repo and none in Jira.');
660
+ for (const e of entries) console.log(describe(e));
661
+ return entries;
662
+ }
663
+
664
+ // .............................................................................
665
+ // pull
666
+
667
+ function changesInJira(entry, config) {
668
+ const before = entry.prop?.jira ?? {};
669
+ const now = entry.snapshot;
670
+ const changes = [];
671
+ for (const k of ['summary', 'status', 'assignee']) if (before[k] !== now[k]) changes.push(k);
672
+ if ((before.sprint?.id ?? null) !== (now.sprint?.id ?? null)) changes.push('sprint');
673
+ if (before.description !== now.description) changes.push('description');
674
+ if (config.fields.acceptanceCriteria && before.acceptanceCriteria !== now.acceptanceCriteria)
675
+ changes.push('acceptanceCriteria');
676
+ return changes;
677
+ }
678
+
679
+ function sprintName(sprint) {
680
+ return sprint?.name?.replace(/^Sprint\s+/i, '') ?? null;
681
+ }
682
+
683
+ function printIssueText(issue, config, parts) {
684
+ const f = issue.fields;
685
+ if (parts.includes('description')) {
686
+ console.log(' --- description in Jira, as Markdown:');
687
+ console.log(indent(toMarkdown(f.description ?? '')));
688
+ }
689
+ if (parts.includes('acceptanceCriteria') && config.fields.acceptanceCriteria) {
690
+ console.log(` --- ${config.sections.acceptanceCriteria} in Jira, as Markdown:`);
691
+ console.log(indent(toMarkdown(f[config.fields.acceptanceCriteria] ?? '')));
692
+ }
693
+ }
694
+
695
+ function indent(text) {
696
+ return text
697
+ .split('\n')
698
+ .map((l) => ` ${l}`)
699
+ .join('\n');
700
+ }
701
+
702
+ async function pull(repo, jira, write) {
703
+ const entries = await compare(repo, jira);
704
+ const { config } = repo;
705
+ const relevant = entries.filter((e) =>
706
+ ['changed in Jira', 'conflict', 'new in Jira', 'not linked yet'].includes(e.state),
707
+ );
708
+ if (!relevant.length) console.log('Nothing changed in Jira.');
709
+ const reverse = Object.fromEntries(Object.entries(repo.people()).map(([n, j]) => [j, n]));
710
+ for (const e of relevant) {
711
+ console.log(`\n${describe(e)}`);
712
+ if (e.state === 'new in Jira' || e.state === 'not linked yet') {
713
+ const f = e.issue.fields;
714
+ console.log(` summary: ${f.summary}`);
715
+ console.log(` status: ${f.status?.name}, assignee: ${e.snapshot.assignee ?? '—'}, sprint: ${sprintName(e.snapshot.sprint) ?? '—'}`);
716
+ printIssueText(e.issue, config, ['description', 'acceptanceCriteria']);
717
+ continue;
718
+ }
719
+ const changes = changesInJira(e, config);
720
+ for (const c of changes.filter((c) => ['summary', 'status', 'assignee', 'sprint'].includes(c))) {
721
+ const before = c === 'sprint' ? sprintName(e.prop.jira?.sprint) : e.prop.jira?.[c];
722
+ const now = c === 'sprint' ? sprintName(e.snapshot.sprint) : e.snapshot[c];
723
+ console.log(` ${c}: ${before ?? '—'} → ${now ?? '—'}`);
724
+ }
725
+ printIssueText(e.issue, config, changes);
726
+ if (!write) continue;
727
+ const updates = {};
728
+ if (changes.includes('sprint') && e.snapshot.sprint) updates.sprint = sprintName(e.snapshot.sprint);
729
+ if (changes.includes('assignee') && e.snapshot.assignee && reverse[e.snapshot.assignee])
730
+ updates.lead = reverse[e.snapshot.assignee];
731
+ if (!Object.keys(updates).length) continue;
732
+ let written = 0;
733
+ for (const file of repo.copies(e.story.basename)) {
734
+ const before = repo.read(file);
735
+ let text = before;
736
+ const set = (field, value) => {
737
+ const next = setStatusField(text, field, value);
738
+ if (next === null) console.log(` ✗ ${file} has no row "${field}:" in its status table`);
739
+ else text = next;
740
+ };
741
+ if (updates.sprint) {
742
+ const old = statusTable(text)[config.statusFields.sprint] ?? '';
743
+ const rest = old.includes(',') ? old.slice(old.indexOf(',')) : '';
744
+ set(config.statusFields.sprint, `${updates.sprint}${rest}`);
745
+ }
746
+ if (updates.lead) set(config.statusFields.lead, updates.lead);
747
+ if (text === before) continue;
748
+ repo.write(file, text);
749
+ written++;
750
+ }
751
+ console.log(` ✓ took over ${Object.keys(updates).join(' and ')} into ${written} file(s)`);
752
+ }
753
+ if (relevant.length)
754
+ console.log(
755
+ '\nWork the remaining changes into every language copy of the story, then push it with ' +
756
+ '--resolved <file>.',
757
+ );
758
+ return entries;
759
+ }
760
+
761
+ // .............................................................................
762
+ // push
763
+
764
+ // Gives a new story the number Jira gave it: file name, title line, field
765
+ // Jira and every link to it, in every language
766
+ function renumber(repo, story, key) {
767
+ const { config } = repo;
768
+ const slug = story.basename.replace(/^[^-]+-/, '');
769
+ const newBase = `${key.toLowerCase()}-${slug}`;
770
+ const browse = `${config.baseUrl}/browse/${key}`;
771
+ for (const file of repo.copies(story.basename)) {
772
+ let text = repo.read(file);
773
+ text = text.replace(/^# [^:]+: /, `# ${key}: `);
774
+ text = setStatusField(text, config.statusFields.jira, `[${key}](${browse})`) ?? text;
775
+ repo.write(file, text);
776
+ fs.renameSync(path.join(repo.root, file), path.join(repo.root, path.posix.dirname(file), newBase));
777
+ }
778
+ const num = escapeRe(story.number);
779
+ const old = escapeRe(story.basename);
780
+ for (const file of repo.markdownFiles()) {
781
+ const text = repo.read(file);
782
+ if (!text.includes(story.basename)) continue;
783
+ const next = text
784
+ .replace(new RegExp(`\\[${num}\\]\\(([^)]*)${old}`, 'g'), `[${key}]($1${newBase}`)
785
+ .replace(
786
+ new RegExp(`^\\|(\\s*)${num}(\\s*)\\| (\\[.*\\]\\([^)]*${old})`, 'gm'),
787
+ `|$1${key}$2| $3`,
788
+ )
789
+ .replaceAll(story.basename, newBase);
790
+ repo.write(file, next);
791
+ }
792
+ return `${repo.storiesDir()}/${newBase}`;
793
+ }
794
+
795
+ async function sendStory(repo, jira, story, issueKey) {
796
+ const { config } = repo;
797
+ const fields = issueFields(repo, story);
798
+ await jira.call('PUT', `/issue/${issueKey}`, { fields });
799
+ const target = targetStatus(story, config);
800
+ let note = '';
801
+ if (target && !(await jira.transitionTo(issueKey, target)))
802
+ note =
803
+ ` (Jira offers no way to "${target[target.length - 1]}"; move it in ` +
804
+ 'Jira, or give its path in "statuses" of jira.jsonc)';
805
+ await jira.call('POST', `/issue/${issueKey}/remotelink`, {
806
+ globalId: `pm-repo:${config.label}:${issueKey}`,
807
+ object: { url: repo.link(story.file), title: `${config.label}: ${story.basename}` },
808
+ });
809
+ const issue = await jira.issue(issueKey);
810
+ const snapshot = jiraSnapshot(issue, config);
811
+ await jira.setProperty(issueKey, {
812
+ repo: config.repoUrl,
813
+ path: story.file,
814
+ repoHash: hash(repo.read(story.file)),
815
+ jiraHash: snapshotHash(snapshot),
816
+ jira: snapshot,
817
+ syncedAt: new Date().toISOString(),
818
+ });
819
+ return note;
820
+ }
821
+
822
+ async function push(repo, jira, args) {
823
+ const entries = await compare(repo, jira);
824
+ const { config } = repo;
825
+ const wanted = args.files.map((f) => path.posix.basename(posix(f)));
826
+ const resolved = args.resolved.map((f) => path.posix.basename(posix(f)));
827
+ // Named files and resolved stories only; without any, everything that
828
+ // is new or changed in the repo
829
+ const named = [...wanted, ...resolved];
830
+ const selected = entries.filter((e) => {
831
+ if (!e.story) return false;
832
+ if (named.length) return named.includes(e.story.basename);
833
+ return ['new in repo', 'changed in repo'].includes(e.state);
834
+ });
835
+ for (const w of named)
836
+ if (!entries.some((e) => e.story?.basename === w)) fail(`${w} is not a story of ${repo.storiesDir()}.`);
837
+ if (!selected.length) {
838
+ console.log('Nothing to push.');
839
+ return entries;
840
+ }
841
+ let blocked = false;
842
+ for (const e of selected) {
843
+ const isResolved = resolved.includes(e.story.basename);
844
+ const needsResolve = ['conflict', 'changed in Jira', 'not linked yet'].includes(e.state);
845
+ if (needsResolve && !isResolved) {
846
+ console.log(`✗ ${describe(e)} — work in the changes from Jira first (pull), then push with --resolved`);
847
+ blocked = true;
848
+ continue;
849
+ }
850
+ if (e.state === 'missing in Jira') {
851
+ console.log(`✗ ${describe(e)} — the issue does not exist; check the field ${config.statusFields.jira}`);
852
+ blocked = true;
853
+ continue;
854
+ }
855
+ if (e.state === 'in sync' && !isResolved) {
856
+ console.log(` ${describe(e)} — nothing to send`);
857
+ continue;
858
+ }
859
+ const action = e.state === 'new in repo' ? 'create' : 'update';
860
+ if (!args.write) {
861
+ console.log(`→ ${action} ${describe(e)}`);
862
+ continue;
863
+ }
864
+ let story = e.story;
865
+ let key = story.key;
866
+ if (action === 'create') {
867
+ const fields = {
868
+ project: { key: config.project },
869
+ issuetype: { name: config.issueType },
870
+ summary: story.title,
871
+ labels: [config.label],
872
+ };
873
+ if (config.sprint && config.fields.sprint) fields[config.fields.sprint] = config.sprint;
874
+ key = (await jira.call('POST', '/issue', { fields })).key;
875
+ const file = renumber(repo, story, key);
876
+ story = repo.readStory(file);
877
+ } else {
878
+ const labels = e.issue.fields.labels;
879
+ if (labels && !labels.includes(config.label))
880
+ await jira.call('PUT', `/issue/${key}`, { update: { labels: [{ add: config.label }] } });
881
+ }
882
+ const note = await sendStory(repo, jira, story, key);
883
+ console.log(`✓ ${action === 'create' ? 'created' : 'updated'} ${key} ${story.basename}${note}`);
884
+ }
885
+ if (!args.write) console.log('\nDry run. Add --write to send it.');
886
+ if (blocked) process.exitCode = 1;
887
+ return entries;
888
+ }
889
+
890
+ // .............................................................................
891
+ // Main
892
+
893
+ async function main() {
894
+ const args = parseArgs(process.argv.slice(2));
895
+ if (!['status', 'pull', 'push'].includes(args.command))
896
+ fail('Usage: node scripts/jira-sync.js status | pull [--write] | push [files] [--resolved <file>] [--write]');
897
+ const root = path.resolve(args.repo ?? '.');
898
+ const config = loadConfig(root);
899
+ const repo = new Repo(root, config);
900
+ const jira = new Jira(config);
901
+ if (args.command === 'status') await status(repo, jira);
902
+ if (args.command === 'pull') await pull(repo, jira, args.write);
903
+ if (args.command === 'push') await push(repo, jira, args);
904
+ }
905
+
906
+ main().catch((e) => {
907
+ console.error(e.isUserError ? `✗ ${e.message}` : e.stack);
908
+ process.exitCode = 1;
909
+ });