@opencrvs/create-countryconfig 2.1.0-rc.d7bd264 → 2.1.0-rc.d987aec

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.
Files changed (2) hide show
  1. package/index.js +412 -59
  2. package/package.json +5 -2
package/index.js CHANGED
@@ -11,93 +11,446 @@
11
11
  * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
12
12
  */
13
13
 
14
- const { execSync } = require('child_process')
15
14
  const path = require('path')
16
15
  const fs = require('fs')
16
+ const { execSync } = require('child_process')
17
+ const readline = require('readline/promises')
18
+ const degit = require('degit').default
17
19
 
18
- const COUNTRYCONFIG_REPO_URL =
19
- 'https://github.com/opencrvs/opencrvs-countryconfig.git'
20
+ const INFRASTRUCTURE_REPOSITORY = 'opencrvs/infrastructure'
21
+ const CORE_REPOSITORY = 'opencrvs/opencrvs-core'
22
+ const COUNTRYCONFIG_TEMPLATE_REPOSITORY_SUBPATH =
23
+ 'packages/countryconfig-template'
24
+
25
+ const CORE_REPO_URL = 'https://github.com/' + CORE_REPOSITORY + '.git'
20
26
  const INFRASTRUCTURE_REPO_URL =
21
- 'https://github.com/opencrvs/infrastructure.git'
27
+ 'https://github.com/' + INFRASTRUCTURE_REPOSITORY + '.git'
28
+
29
+ const { version } = JSON.parse(
30
+ fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8')
31
+ )
32
+
33
+ function joinValues(values, separator) {
34
+ return values
35
+ .filter((value) => !!value)
36
+ .join(separator)
37
+ .trim()
38
+ }
39
+
40
+ function tagExists(repoUrl, tag) {
41
+ try {
42
+ execSync(
43
+ 'git ls-remote --exit-code --tags ' + repoUrl + ' refs/tags/' + tag,
44
+ { stdio: 'pipe' }
45
+ )
46
+ return true
47
+ } catch (err) {
48
+ return false
49
+ }
50
+ }
51
+
52
+ function branchExists(repoUrl, branch) {
53
+ try {
54
+ execSync(
55
+ 'git ls-remote --exit-code --heads ' + repoUrl + ' refs/heads/' + branch,
56
+ { stdio: 'pipe' }
57
+ )
58
+ return true
59
+ } catch (err) {
60
+ return false
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Release tags (e.g. "v2.1.0"), highest first. Delegates the version-aware
66
+ * ordering to git itself rather than hand-parsing semver, then filters down
67
+ * to strict "vX.Y.Z" tags - `--sort=-version:refname` alone still leaves in
68
+ * non-release refs (e.g. "vtesting", "v2.0.0-beta") and peeled annotated-tag
69
+ * lines ("refs/tags/v2.0.0^{}").
70
+ */
71
+ function listReleaseTags(repoUrl) {
72
+ const output = execSync(
73
+ 'git ls-remote --tags --sort=-version:refname ' + repoUrl,
74
+ { encoding: 'utf-8' }
75
+ )
76
+
77
+ return output
78
+ .split('\n')
79
+ .map((line) => line.split('\t')[1])
80
+ .filter(Boolean)
81
+ .map((ref) => ref.replace('refs/tags/', ''))
82
+ .filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag))
83
+ }
84
+
85
+ /**
86
+ * The highest release tag present in *both* repositories - used as the
87
+ * fallback when the version-specific tag can't be found in one or both, so
88
+ * scaffolding still lands on a real, matched release rather than develop.
89
+ */
90
+ function getLatestCommonReleaseTag() {
91
+ const infrastructureTags = new Set(listReleaseTags(INFRASTRUCTURE_REPO_URL))
92
+ return (
93
+ listReleaseTags(CORE_REPO_URL).find((tag) => infrastructureTags.has(tag)) ||
94
+ null
95
+ )
96
+ }
97
+
98
+ /**
99
+ * A prerelease-shaped own version (e.g. "2.1.0-rc.f5ea803", what npm resolves
100
+ * `@next` to - a build published from every push to a branch) never has a
101
+ * matching release tag, so it's resolved as a branch instead. Its base
102
+ * version (stripped of the "-rc.<sha>" suffix) tells apart two different
103
+ * situations: an RC for a version already being stabilized on its own
104
+ * "release/X.Y.Z" branch (e.g. "2.0.1-rc.*" while a patch release is in
105
+ * progress) versus an RC for a version that hasn't been branched off yet and
106
+ * only exists on develop (e.g. "2.1.0-rc.*" while that release branch hasn't
107
+ * been cut). Scaffold from the release branch when it exists in both
108
+ * repositories, otherwise fall back to develop.
109
+ *
110
+ * Otherwise, the own "X.Y.Z" version - whether resolved via npm's `latest`
111
+ * dist-tag (bare invocation) or an explicit `@X.Y.Z` pin - scaffolds from the
112
+ * matching "vX.Y.Z" tag when it exists in both repositories. If it doesn't
113
+ * (e.g. `latest` lagging behind the repos, or a pin that predates one repo's
114
+ * tagging), fall back to the highest release tag common to both, rather than
115
+ * a mismatched pairing of one tagged repo at that version and another repo
116
+ * at a different release. Exits with an error if no matching release tag
117
+ * exists in both repositories.
118
+ */
119
+ function resolveRef() {
120
+ if (version.includes('-')) {
121
+ const releaseBranch = 'release/' + version.split('-')[0]
122
+ if (
123
+ branchExists(CORE_REPO_URL, releaseBranch) &&
124
+ branchExists(INFRASTRUCTURE_REPO_URL, releaseBranch)
125
+ ) {
126
+ return releaseBranch
127
+ }
128
+ return 'develop'
129
+ }
22
130
 
23
- const projectName = process.argv[2]
131
+ const tag = 'v' + version
132
+ if (
133
+ tagExists(CORE_REPO_URL, tag) &&
134
+ tagExists(INFRASTRUCTURE_REPO_URL, tag)
135
+ ) {
136
+ return tag
137
+ }
138
+
139
+ const latestCommonTag = getLatestCommonReleaseTag()
140
+ if (latestCommonTag) {
141
+ console.warn(
142
+ '\nWarning: tag "' +
143
+ tag +
144
+ '" was not found in both repositories; falling back to the latest ' +
145
+ 'available release, ' +
146
+ latestCommonTag +
147
+ '.'
148
+ )
149
+ return latestCommonTag
150
+ }
24
151
 
25
- if (!projectName) {
26
152
  console.error(
27
- 'Please specify a project name:\n\n npm create @opencrvs/countryconfig <project-name>\n'
153
+ '\nError: no matching release tag was found in both the core and ' +
154
+ 'infrastructure repositories.'
28
155
  )
29
156
  process.exit(1)
30
157
  }
31
158
 
32
- const countryconfigDirName = projectName + '-countryconfig'
33
- const infrastructureDirName = projectName + '-infrastructure'
159
+ /**
160
+ * Clones a repository from GitHub to a target directory.
161
+ *
162
+ * @param {*} param0 repository - The repository to clone (e.g., 'opencrvs/opencrvs-core').
163
+ * @param {*} param0 repositorySubPath - The subpath within the repository to clone (optional). Otherwise the entire repository will be cloned.
164
+ * @param {*} param0 branch - The branch to clone (optional). Defaults to the default branch if not specified.
165
+ *
166
+ * @param {*} targetDir - The target directory where the repository will be cloned.
167
+ */
168
+ async function cloneRepository(
169
+ { repository, repositorySubPath, branch },
170
+ targetDir
171
+ ) {
172
+ const repositoryPath = joinValues([repository, repositorySubPath], '/')
173
+ const fullPath = joinValues([repositoryPath, branch], '#')
174
+
175
+ console.log(`Cloning repository from ${fullPath} to ${targetDir}...`)
34
176
 
35
- const countryconfigTargetDir = path.resolve(process.cwd(), countryconfigDirName)
36
- const infrastructureTargetDir = path.resolve(process.cwd(), infrastructureDirName)
177
+ const emitter = degit(fullPath, {
178
+ mode: 'git'
179
+ })
37
180
 
38
- if (fs.existsSync(countryconfigTargetDir)) {
39
- console.error('Error: Directory "' + countryconfigDirName + '" already exists.')
40
- process.exit(1)
181
+ await emitter.clone(targetDir)
182
+ console.log(`Copied files from ${fullPath} to ${targetDir} succesfully.`)
41
183
  }
42
184
 
43
- if (fs.existsSync(infrastructureTargetDir)) {
44
- console.error('Error: Directory "' + infrastructureDirName + '" already exists.')
45
- process.exit(1)
185
+ function ensureTargetDirectoryDoesNotExist(directoryName) {
186
+ const targetDirectoryPath = path.resolve(process.cwd(), directoryName)
187
+
188
+ if (fs.existsSync(targetDirectoryPath)) {
189
+ console.error(
190
+ 'Error: Directory already exists in path "' + targetDirectoryPath + '".'
191
+ )
192
+ process.exit(1)
193
+ }
46
194
  }
47
195
 
48
- console.log('\nScaffolding OpenCRVS country config in ./' + countryconfigDirName + '...\n')
196
+ /**
197
+ * Asks whether to enable telemetry. Defaults to yes, and answers yes without
198
+ * prompting when not attached to a terminal (e.g. non-interactive scaffolding).
199
+ */
200
+ async function promptEnableTelemetry() {
201
+ if (!process.stdin.isTTY) {
202
+ return true
203
+ }
49
204
 
50
- try {
51
- execSync('git clone --depth 1 ' + COUNTRYCONFIG_REPO_URL + ' ' + countryconfigDirName, { stdio: 'inherit' })
52
- } catch (err) {
53
- console.error('Failed to clone the country config repository:', err.message)
54
- process.exit(1)
205
+ const rl = readline.createInterface({
206
+ input: process.stdin,
207
+ output: process.stdout
208
+ })
209
+ try {
210
+ const answer = (
211
+ await rl.question(
212
+ '\nEnable anonymous usage telemetry to help improve OpenCRVS? Only ' +
213
+ 'aggregate metrics are shared — no personal or protected data. [Y/n] '
214
+ )
215
+ )
216
+ .trim()
217
+ .toLowerCase()
218
+ return answer === '' || answer === 'y' || answer === 'yes'
219
+ } finally {
220
+ rl.close()
221
+ }
55
222
  }
56
223
 
57
- try {
58
- fs.rmSync(path.join(countryconfigTargetDir, '.git'), { recursive: true, force: true })
59
- } catch (err) {
60
- console.error('Failed to remove .git directory from country config:', err.message)
61
- process.exit(1)
224
+ /**
225
+ * Prompts for a single line of input, re-asking until `validate` accepts the
226
+ * trimmed answer. `validate` returns an error message string when the answer is
227
+ * invalid, or a falsy value when it is accepted. Exits when not attached to a
228
+ * terminal, since a mandatory value cannot be gathered non-interactively.
229
+ */
230
+ async function promptRequired(question, validate) {
231
+ if (!process.stdin.isTTY) {
232
+ console.error(
233
+ '\nError: interactive input is required to set the organisation name and country code.'
234
+ )
235
+ process.exit(1)
236
+ }
237
+
238
+ const rl = readline.createInterface({
239
+ input: process.stdin,
240
+ output: process.stdout
241
+ })
242
+ try {
243
+ while (true) {
244
+ const answer = (await rl.question(question)).trim()
245
+ const error = validate(answer)
246
+ if (!error) {
247
+ return answer
248
+ }
249
+ console.error(error)
250
+ }
251
+ } finally {
252
+ rl.close()
253
+ }
62
254
  }
63
255
 
64
- const pkgPath = path.join(countryconfigTargetDir, 'package.json')
65
- if (fs.existsSync(pkgPath)) {
256
+ /**
257
+ * Prompts for the organisation name reported with telemetry. Mandatory.
258
+ */
259
+ function promptOrganisation() {
260
+ return promptRequired('\nOrganisation running this instance: ', (answer) =>
261
+ answer === '' ? 'Please enter an organisation name.' : undefined
262
+ )
263
+ }
264
+
265
+ /**
266
+ * Prompts for the alpha-3 ISO country code reported with telemetry, re-asking
267
+ * until a valid three-letter code is given. Mandatory.
268
+ */
269
+ async function promptCountryCode() {
270
+ const answer = await promptRequired(
271
+ '\nAlpha-3 ISO country code of this instance (e.g. "GBR"): ',
272
+ (value) =>
273
+ /^[A-Za-z]{3}$/.test(value)
274
+ ? undefined
275
+ : 'Please enter a three-letter alpha-3 ISO country code (e.g. "GBR").'
276
+ )
277
+ return answer.toUpperCase()
278
+ }
279
+
280
+ /**
281
+ * Flips the `TELEMETRY_ENABLED` env var default in the cloned country config's
282
+ * environment to `true`. The template ships it defaulting to `false`.
283
+ */
284
+ function enableTelemetryInEnvironment(targetPath) {
285
+ const environmentPath = path.join(targetPath, 'src', 'environment.ts')
286
+ if (!fs.existsSync(environmentPath)) {
287
+ console.warn(
288
+ '\nWarning: could not find src/environment.ts; telemetry default not changed.'
289
+ )
290
+ return
291
+ }
292
+
293
+ const original = fs.readFileSync(environmentPath, 'utf-8')
294
+ const updated = original.replace(
295
+ /(TELEMETRY_ENABLED:\s*bool\(\{[\s\S]*?default:\s*)false/,
296
+ '$1true'
297
+ )
298
+
299
+ if (updated === original) {
300
+ console.warn(
301
+ '\nWarning: could not update the TELEMETRY_ENABLED default in src/environment.ts.'
302
+ )
303
+ return
304
+ }
305
+
306
+ fs.writeFileSync(environmentPath, updated)
307
+ console.log('\nTelemetry enabled (TELEMETRY_ENABLED now defaults to true).')
308
+ }
309
+
310
+ /**
311
+ * Replaces the string `default` of an envalid `str({ ... })` field in the
312
+ * cloned country config's environment. Returns the updated source, or the
313
+ * original source (with a warning) when the field could not be located.
314
+ */
315
+ function setEnvironmentStringDefault(source, key, value) {
316
+ const pattern = new RegExp(
317
+ `(${key}:\\s*str\\(\\{[\\s\\S]*?default:\\s*)'[^']*'`
318
+ )
319
+ // Escape for a single-quoted TS string literal, and use a function replacer
320
+ // so `$` in the value is not treated as a replacement pattern.
321
+ const literal = "'" + value.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"
322
+ const updated = source.replace(pattern, (_, prefix) => prefix + literal)
323
+
324
+ if (updated === source) {
325
+ console.warn(
326
+ `\nWarning: could not update the ${key} default in src/environment.ts.`
327
+ )
328
+ }
329
+
330
+ return updated
331
+ }
332
+
333
+ /**
334
+ * Writes the given organisation name and alpha-3 country code as the defaults
335
+ * for the `ORGANISATION` and `COUNTRY_CODE` env vars in the cloned country
336
+ * config's environment.
337
+ */
338
+ function setTelemetryIdentityInEnvironment(
339
+ targetPath,
340
+ { organisation, countryCode }
341
+ ) {
342
+ const environmentPath = path.join(targetPath, 'src', 'environment.ts')
343
+ if (!fs.existsSync(environmentPath)) {
344
+ console.warn(
345
+ '\nWarning: could not find src/environment.ts; organisation and country code defaults not changed.'
346
+ )
347
+ return
348
+ }
349
+
350
+ let source = fs.readFileSync(environmentPath, 'utf-8')
351
+ source = setEnvironmentStringDefault(source, 'ORGANISATION', organisation)
352
+ source = setEnvironmentStringDefault(source, 'COUNTRY_CODE', countryCode)
353
+ fs.writeFileSync(environmentPath, source)
354
+ }
355
+
356
+ function updatePackageJsonName(targetPath, newName) {
357
+ console.log('\nUpdating package.json with project name: ' + newName + '\n')
358
+
359
+ const pkgPath = path.join(targetPath, 'package.json')
360
+ if (fs.existsSync(pkgPath)) {
361
+ try {
362
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
363
+ pkg.name = newName
364
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
365
+ } catch (err) {
366
+ console.error('\nFailed to update package.json:', err.message)
367
+ process.exit(1)
368
+ }
369
+ } else {
370
+ console.warn(
371
+ '\nWarning: No package.json found in the targetPath: ' +
372
+ targetPath +
373
+ '. Project name was not updated.'
374
+ )
375
+ }
376
+ }
377
+
378
+ async function main() {
379
+ const projectName = process.argv[2]
380
+
381
+ if (!projectName) {
382
+ console.error(
383
+ 'Please specify a project name:\n\n npm create @opencrvs/countryconfig <project-name>\n'
384
+ )
385
+ process.exit(1)
386
+ }
387
+
388
+ const countryconfigDirName = projectName + '-countryconfig'
389
+ const countryconfigTargetPath = path.resolve(
390
+ process.cwd(),
391
+ countryconfigDirName
392
+ )
393
+ const infrastructureDirName = projectName + '-infrastructure'
394
+ const infrastructureTargetPath = path.resolve(
395
+ process.cwd(),
396
+ infrastructureDirName
397
+ )
398
+
399
+ ensureTargetDirectoryDoesNotExist(countryconfigDirName)
400
+ ensureTargetDirectoryDoesNotExist(infrastructureDirName)
401
+
402
+ const ref = resolveRef()
403
+
404
+ // Gather all answers up front so the operator isn't interrupted mid-clone.
405
+ const organisation = await promptOrganisation()
406
+ const countryCode = await promptCountryCode()
407
+ const telemetryEnabled = await promptEnableTelemetry()
408
+
66
409
  try {
67
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
68
- pkg.name = countryconfigDirName
69
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
410
+ await cloneRepository(
411
+ {
412
+ repository: CORE_REPOSITORY,
413
+ repositorySubPath: COUNTRYCONFIG_TEMPLATE_REPOSITORY_SUBPATH,
414
+ branch: ref
415
+ },
416
+ countryconfigTargetPath
417
+ )
70
418
  } catch (err) {
71
- console.error('Failed to update package.json:', err.message)
419
+ console.error('\nFailed to clone country config template:', err.message)
72
420
  process.exit(1)
73
421
  }
74
- } else {
75
- console.warn('Warning: No package.json found in the cloned country config repository. Project name was not updated.')
76
- }
77
422
 
78
- console.log('\nScaffolding OpenCRVS infrastructure in ./' + infrastructureDirName + '...\n')
423
+ updatePackageJsonName(countryconfigTargetPath, countryconfigDirName)
79
424
 
80
- try {
81
- execSync('git clone --depth 1 ' + INFRASTRUCTURE_REPO_URL + ' ' + infrastructureDirName, { stdio: 'inherit' })
82
- } catch (err) {
83
- console.error('Failed to clone the infrastructure repository:', err.message)
84
- process.exit(1)
85
- }
425
+ try {
426
+ await cloneRepository(
427
+ { repository: INFRASTRUCTURE_REPOSITORY, branch: ref },
428
+ infrastructureTargetPath
429
+ )
430
+ } catch (err) {
431
+ console.error('Failed to clone the infrastructure repository:', err.message)
432
+ process.exit(1)
433
+ }
86
434
 
87
- try {
88
- fs.rmSync(path.join(infrastructureTargetDir, '.git'), { recursive: true, force: true })
89
- } catch (err) {
90
- console.error('Failed to remove .git directory from infrastructure:', err.message)
91
- process.exit(1)
435
+ setTelemetryIdentityInEnvironment(countryconfigTargetPath, {
436
+ organisation,
437
+ countryCode
438
+ })
439
+
440
+ if (telemetryEnabled) {
441
+ enableTelemetryInEnvironment(countryconfigTargetPath)
442
+ }
443
+
444
+ console.log('\nDone! Your project has been set up in two directories:\n')
445
+ console.log(' ./' + countryconfigDirName + ' -- country configuration')
446
+ console.log(' ./' + infrastructureDirName + ' -- server infrastructure\n')
447
+ console.log('To get started with the country config:\n')
448
+ console.log(' cd ' + countryconfigDirName)
449
+ console.log(' git init')
450
+ console.log(' tilt up\n')
451
+ console.log('To get started with the infrastructure:\n')
452
+ console.log(' cd ' + infrastructureDirName)
453
+ console.log(' git init\n')
92
454
  }
93
455
 
94
- console.log('\nDone! Your project has been set up in two directories:\n')
95
- console.log(' ./' + countryconfigDirName + ' -- country configuration')
96
- console.log(' ./' + infrastructureDirName + ' -- server infrastructure\n')
97
- console.log('To get started with the country config:\n')
98
- console.log(' cd ' + countryconfigDirName)
99
- console.log(' git init')
100
- console.log(' npm install\n')
101
- console.log('To get started with the infrastructure:\n')
102
- console.log(' cd ' + infrastructureDirName)
103
- console.log(' git init\n')
456
+ main()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencrvs/create-countryconfig",
3
- "version": "2.1.0-rc.d7bd264",
3
+ "version": "2.1.0-rc.d987aec",
4
4
  "description": "Scaffold a new OpenCRVS country configuration",
5
5
  "bin": {
6
6
  "create-countryconfig": "./index.js"
@@ -17,5 +17,8 @@
17
17
  "countryconfig",
18
18
  "create"
19
19
  ],
20
- "license": "MPL-2.0"
20
+ "license": "MPL-2.0",
21
+ "dependencies": {
22
+ "degit": "^3.6.5"
23
+ }
21
24
  }