create-cwa 2.0.0-alpha.46 → 2.0.0-alpha.48

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
@@ -27,6 +27,24 @@ If you start the stack, the CLI runs the project's `bin/up`: it waits until the
27
27
  ## Options
28
28
 
29
29
  - `--ref <tag or branch>`: the template version to download. By default `create-cwa` X downloads the template tagged `vX`, so an install is reproducible. `--ref main` gets the latest unreleased template.
30
+ - `--template-dir <path>`: copy the template from a local checkout instead of downloading it: the files git tracks (or would track), minus `export-ignore` paths, like a download. The manifest's excludes and feature stripping apply as usual. Can't be combined with `--ref`.
31
+
32
+ Each of these answers its question, so it isn't asked:
33
+
34
+ - `--pipeline <github|gitlab|none>`: the CI/CD pipeline.
35
+ - `--features <list>`: comma-separated feature ids (`navigation`, `html-content`, `image`, `blog`, `nested-pages`, `forms`), `all` or `none`. Features another one needs are still added.
36
+ - `--fixtures` / `--no-fixtures`: include the sample pages, or not.
37
+ - `--start` / `--no-start`: run `bin/up` once the project is created, or not. With `--start`, a check that fails (Docker not running, a port taken) stops the CLI before anything is created.
38
+ - `--install-deps` / `--no-install-deps`: `pnpm install` in `app/` on this machine; only when the stack isn't started.
39
+
40
+ For unattended runs:
41
+
42
+ - `-y`, `--yes`: take the default for every question no flag answers: GitHub Actions, no features, fixtures, start the stack (when Docker is there and the checks pass), no host install. The project name has no default, so it's still asked for when not given.
43
+ - `--ci`: never prompt (implies `--yes`). A missing or invalid project name is an error, and a failed `bin/up` makes the CLI exit 1. For example:
44
+
45
+ ```sh
46
+ npx create-cwa my-app --ci --pipeline none --features all --no-start
47
+ ```
30
48
 
31
49
  ## Privacy
32
50
 
package/dist/index.js CHANGED
@@ -15,20 +15,120 @@ const REPO = 'components-web-app/components-web-app';
15
15
  // tag vX, so an install is reproducible. `--ref <branch|tag>` overrides it, for
16
16
  // example `--ref main` for the latest unreleased template.
17
17
  const CLI_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
18
+ const USAGE = `Usage: create-cwa [project-name] [options]
19
+
20
+ Without options every question is asked. A flag answers its question, so it isn't asked.
21
+
22
+ Options:
23
+ --ref <tag|branch> template version to download (default v${CLI_VERSION})
24
+ --template-dir <path> copy the template from a local checkout instead of downloading it
25
+ --pipeline <id> CI/CD pipeline: github, gitlab or none
26
+ --features <list> comma-separated features, "all" or "none"
27
+ --fixtures, --no-fixtures include the sample pages, or not
28
+ --start, --no-start run bin/up once the project is created, or not
29
+ --install-deps, --no-install-deps
30
+ pnpm install in app/ on this machine (only when the stack isn't started)
31
+ -y, --yes take the default for every question no flag answers
32
+ --ci never prompt (implies --yes); a missing project name is an error
33
+ -h, --help show this help`;
34
+ class UsageError extends Error {
35
+ }
36
+ const VALUE_FLAGS = ['--ref', '--template-dir', '--pipeline', '--features'];
37
+ // Flags for unattended runs (#215); with none given, every question is asked as before.
18
38
  function parseArgs(argv) {
19
39
  const args = argv.slice(2);
20
- let ref = `v${CLI_VERSION}`;
40
+ const opts = { ref: `v${CLI_VERSION}`, refGiven: false, yes: false, ci: false, help: false };
21
41
  const positional = [];
22
42
  for (let i = 0; i < args.length; i++) {
23
- const arg = args[i];
24
- if (arg === '--ref' && args[i + 1])
25
- ref = args[++i];
26
- else if (arg.startsWith('--ref='))
27
- ref = arg.slice('--ref='.length);
28
- else
29
- positional.push(arg);
30
- }
31
- return { projectName: positional[0], ref };
43
+ let arg = args[i];
44
+ let value;
45
+ const eq = arg.indexOf('=');
46
+ if (arg.startsWith('--') && eq > 0) {
47
+ value = arg.slice(eq + 1);
48
+ arg = arg.slice(0, eq);
49
+ if (!VALUE_FLAGS.includes(arg))
50
+ throw new UsageError(`${arg} takes no value`);
51
+ }
52
+ else if (VALUE_FLAGS.includes(arg)) {
53
+ value = args[i + 1];
54
+ if (value === undefined || value.startsWith('-'))
55
+ throw new UsageError(`${arg} needs a value`);
56
+ i++;
57
+ }
58
+ switch (arg) {
59
+ case '--':
60
+ break;
61
+ case '--ref':
62
+ opts.ref = value;
63
+ opts.refGiven = true;
64
+ break;
65
+ case '--template-dir':
66
+ opts.templateDir = value;
67
+ break;
68
+ case '--pipeline':
69
+ opts.pipeline = value;
70
+ break;
71
+ case '--features':
72
+ opts.features = value.split(',').map((f) => f.trim()).filter(Boolean);
73
+ break;
74
+ case '--fixtures':
75
+ case '--no-fixtures':
76
+ opts.fixtures = arg === '--fixtures';
77
+ break;
78
+ case '--start':
79
+ case '--no-start':
80
+ opts.start = arg === '--start';
81
+ break;
82
+ case '--install-deps':
83
+ case '--no-install-deps':
84
+ opts.installDeps = arg === '--install-deps';
85
+ break;
86
+ case '-y':
87
+ case '--yes':
88
+ opts.yes = true;
89
+ break;
90
+ case '--ci':
91
+ opts.ci = true;
92
+ opts.yes = true;
93
+ break;
94
+ case '-h':
95
+ case '--help':
96
+ opts.help = true;
97
+ break;
98
+ default:
99
+ if (arg.startsWith('-'))
100
+ throw new UsageError(`Unknown option ${arg}`);
101
+ positional.push(arg);
102
+ }
103
+ }
104
+ if (positional.length > 1)
105
+ throw new UsageError(`Unexpected argument "${positional[1]}"`);
106
+ if (opts.templateDir && opts.refGiven)
107
+ throw new UsageError("--ref and --template-dir can't be used together");
108
+ if (opts.start && opts.installDeps) {
109
+ throw new UsageError('--install-deps is only for a stack that isn\'t started: the app container installs its own');
110
+ }
111
+ opts.projectName = positional[0];
112
+ return opts;
113
+ }
114
+ function fail(message) {
115
+ cancel(message);
116
+ process.exit(1);
117
+ }
118
+ // A spinner when someone is watching, plain log lines under --ci.
119
+ function progress(plain) {
120
+ return plain ? { start: (msg) => log.step(msg), stop: (msg) => log.info(msg) } : spinner();
121
+ }
122
+ async function readLocalManifest(templateDir) {
123
+ const path = join(resolve(templateDir), 'cwa-manifest.json');
124
+ if (!existsSync(path))
125
+ throw new Error(`No CWA template in "${templateDir}": ${path} is missing.`);
126
+ try {
127
+ return JSON.parse(await readFile(path, 'utf-8'));
128
+ }
129
+ catch {
130
+ throw new Error(`${path} is not valid JSON.`);
131
+ }
32
132
  }
33
133
  async function fetchManifest(ref) {
34
134
  let res;
@@ -86,31 +186,72 @@ function validateProjectName(value) {
86
186
  }
87
187
  return undefined;
88
188
  }
89
- async function askQuestions(manifest, targetArg) {
189
+ // Each answer comes from its flag, else the default under --yes (what Enter picks), else a prompt (#215).
190
+ async function askQuestions(manifest, opts) {
90
191
  const question = (id) => manifest.questions.find((q) => q.id === id);
91
192
  const nameQuestion = question('projectName');
92
- const projectName = checkCancel(await text({
93
- message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
94
- placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
95
- initialValue: targetArg ?? '',
96
- validate: validateProjectName,
97
- }));
193
+ let projectName;
194
+ if (opts.yes && opts.projectName !== undefined) {
195
+ const error = validateProjectName(opts.projectName);
196
+ if (error)
197
+ fail(`Project name "${opts.projectName}": ${error}`);
198
+ projectName = opts.projectName;
199
+ }
200
+ else if (opts.ci) {
201
+ fail('--ci needs the project name: create-cwa <project-name> --ci');
202
+ }
203
+ else {
204
+ projectName = checkCancel(await text({
205
+ message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
206
+ placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
207
+ initialValue: opts.projectName ?? '',
208
+ validate: validateProjectName,
209
+ }));
210
+ }
98
211
  const ciQuestion = question('ci');
99
- const ci = checkCancel(await select({
100
- message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
101
- options: ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
102
- { value: 'github', label: 'GitHub Actions' },
103
- { value: 'gitlab', label: 'GitLab CI' },
104
- { value: 'none', label: 'None' },
105
- ],
106
- }));
212
+ const ciOptions = ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
213
+ { value: 'github', label: 'GitHub Actions' },
214
+ { value: 'gitlab', label: 'GitLab CI' },
215
+ { value: 'none', label: 'None' },
216
+ ];
217
+ let ci;
218
+ if (opts.pipeline !== undefined) {
219
+ if (!ciOptions.some((c) => c.value === opts.pipeline)) {
220
+ fail(`--pipeline ${opts.pipeline}: choose one of ${ciOptions.map((c) => c.value).join(', ')}`);
221
+ }
222
+ ci = opts.pipeline;
223
+ }
224
+ else if (opts.yes) {
225
+ ci = ciOptions[0].value;
226
+ }
227
+ else {
228
+ ci = checkCancel(await select({
229
+ message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
230
+ options: ciOptions,
231
+ }));
232
+ }
107
233
  const featuresQuestion = question('features');
108
234
  const featureChoices = featuresQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [];
109
- const features = checkCancel(await multiselect({
110
- message: withHint(`${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`, featuresQuestion?.hint),
111
- options: featureChoices,
112
- required: false,
113
- }));
235
+ let features;
236
+ if (opts.features !== undefined) {
237
+ const all = featureChoices.map((c) => c.value);
238
+ const flag = opts.features;
239
+ features = flag.length === 1 && flag[0] === 'all' ? all : flag.length === 1 && flag[0] === 'none' ? [] : flag;
240
+ const unknown = features.filter((f) => !all.includes(f));
241
+ if (unknown.length) {
242
+ fail(`--features: unknown ${unknown.join(', ')}. Choose from ${all.join(', ')}, or "all" or "none"`);
243
+ }
244
+ }
245
+ else if (opts.yes) {
246
+ features = [];
247
+ }
248
+ else {
249
+ features = checkCancel(await multiselect({
250
+ message: withHint(`${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`, featuresQuestion?.hint),
251
+ options: featureChoices,
252
+ required: false,
253
+ }));
254
+ }
114
255
  // Auto-include required features
115
256
  const resolved = new Set(features);
116
257
  for (const feat of features) {
@@ -124,14 +265,73 @@ async function askQuestions(manifest, targetArg) {
124
265
  note(`Also enabling: ${added.join(', ')} (required by selected features)`, 'Dependencies');
125
266
  }
126
267
  const fixturesQuestion = question('fixtures');
127
- const fixtures = checkCancel(await confirm({
128
- message: withHint(fixturesQuestion?.message ?? 'Include database fixtures for selected features?', fixturesQuestion?.hint),
129
- initialValue: fixturesQuestion?.default ?? true,
130
- }));
268
+ const fixtures = opts.fixtures ??
269
+ (opts.yes
270
+ ? (fixturesQuestion?.default ?? true)
271
+ : checkCancel(await confirm({
272
+ message: withHint(fixturesQuestion?.message ?? 'Include database fixtures for selected features?', fixturesQuestion?.hint),
273
+ initialValue: fixturesQuestion?.default ?? true,
274
+ })));
131
275
  return { projectName: projectName.trim(), ci, features: [...resolved], fixtures };
132
276
  }
133
- async function downloadRepo(manifest, ref, tempDir) {
134
- const s = spinner();
277
+ // Files a download would contain: what git tracks or would track, minus export-ignore paths (GitHub's tarball honours them).
278
+ function templateFiles(src) {
279
+ const ls = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
280
+ cwd: src,
281
+ encoding: 'utf8',
282
+ });
283
+ if (ls.status !== 0)
284
+ return null;
285
+ const files = ls.stdout.split('\0').filter((f) => f && existsSync(join(src, f)));
286
+ const paths = new Set();
287
+ for (const file of files) {
288
+ const parts = file.split('/');
289
+ for (let i = 1; i <= parts.length; i++)
290
+ paths.add(parts.slice(0, i).join('/'));
291
+ }
292
+ const attr = spawnSync('git', ['check-attr', '-z', '--stdin', 'export-ignore'], {
293
+ cwd: src,
294
+ input: [...paths].join('\0'),
295
+ encoding: 'utf8',
296
+ });
297
+ if (attr.status !== 0)
298
+ return null;
299
+ const out = attr.stdout.split('\0');
300
+ const ignored = new Set();
301
+ for (let i = 0; i + 2 < out.length; i += 3) {
302
+ if (out[i + 2] === 'set')
303
+ ignored.add(out[i]);
304
+ }
305
+ return files.filter((file) => {
306
+ const parts = file.split('/');
307
+ for (let i = 1; i <= parts.length; i++)
308
+ if (ignored.has(parts.slice(0, i).join('/')))
309
+ return false;
310
+ return true;
311
+ });
312
+ }
313
+ // --template-dir (#215): a local checkout instead of the download; excludes and stripping still apply after.
314
+ async function copyTemplateDir(templateDir, tempDir, plain) {
315
+ const src = resolve(templateDir);
316
+ const s = progress(plain);
317
+ s.start(`Copying template from ${src}...`);
318
+ const files = templateFiles(src);
319
+ if (files) {
320
+ for (const file of files) {
321
+ await fse.copy(join(src, file), join(tempDir, file), { dereference: false });
322
+ }
323
+ }
324
+ else {
325
+ // Not a git checkout: everything but dependencies and VCS data.
326
+ const skip = new Set(['.git', 'node_modules', 'vendor']);
327
+ await fse.copy(src, tempDir, {
328
+ filter: (path) => !path.slice(src.length).split(/[\\/]/).some((part) => skip.has(part)),
329
+ });
330
+ }
331
+ s.stop('Template copied.');
332
+ }
333
+ async function downloadRepo(manifest, ref, tempDir, plain) {
334
+ const s = progress(plain);
135
335
  s.start(`Downloading template (${ref})...`);
136
336
  try {
137
337
  await downloadTemplate(`github:${manifest.repo}#${ref}`, {
@@ -268,68 +468,96 @@ async function moveToTarget(tempDir, targetDir) {
268
468
  // Decides, before anything is downloaded, whether to start the stack and whether to
269
469
  // install app/ dependencies on the host. The host install shares app/node_modules with
270
470
  // the app container, so it's only offered when the stack isn't started now (#204).
271
- async function askSetup() {
471
+ // --start fails when the stack can't be started; without it (prompted or --yes) the project is created anyway (#215).
472
+ async function askSetup(opts) {
272
473
  let startDocker = false;
273
474
  if (commandExists('docker')) {
274
- startDocker = checkCancel(await confirm({
275
- message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
276
- initialValue: true,
277
- }));
475
+ startDocker =
476
+ opts.start ??
477
+ (opts.yes ||
478
+ checkCancel(await confirm({
479
+ message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
480
+ initialValue: true,
481
+ })));
482
+ }
483
+ else if (opts.start) {
484
+ fail('--start: docker not found. Install Docker Desktop (or Docker Engine with the compose plugin).');
278
485
  }
279
486
  else {
280
487
  log.warn('docker not found. Install Docker Desktop, then run `bin/up` in the project.');
281
488
  }
282
489
  if (startDocker) {
283
- const s = spinner();
490
+ const s = progress(opts.ci);
284
491
  s.start('Checking Docker and ports...');
285
492
  const result = await preflight();
286
493
  s.stop('Docker checked.');
287
- if (!result.dockerRunning) {
288
- log.warn('Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).');
289
- startDocker = false;
290
- }
291
- else if (result.takenPorts.length) {
292
- log.warn(result.takenPorts.join('\n\n'));
293
- startDocker = false;
294
- }
494
+ const problem = !result.dockerRunning
495
+ ? 'Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).'
496
+ : result.takenPorts.join('\n\n');
295
497
  if (result.memoryWarning)
296
498
  log.warn(result.memoryWarning);
297
- if (!startDocker) {
499
+ if (problem) {
500
+ if (opts.start)
501
+ fail(`--start: ${problem}`);
502
+ log.warn(problem);
298
503
  log.info('The project will be created without starting Docker. Run `bin/up` in it once that is fixed.');
504
+ startDocker = false;
299
505
  }
300
506
  return { startDocker, installDeps: false };
301
507
  }
302
508
  let installDeps = false;
303
509
  if (commandExists('pnpm')) {
304
- installDeps = checkCancel(await confirm({
305
- message: withHint('Install app/ dependencies on this machine?', 'only for editor types; the app container installs its own on first start'),
306
- initialValue: false,
307
- }));
510
+ installDeps =
511
+ opts.installDeps ??
512
+ (!opts.yes &&
513
+ checkCancel(await confirm({
514
+ message: withHint('Install app/ dependencies on this machine?', 'only for editor types; the app container installs its own on first start'),
515
+ initialValue: false,
516
+ })));
517
+ }
518
+ else if (opts.installDeps) {
519
+ fail('--install-deps: pnpm not found.');
308
520
  }
309
521
  return { startDocker, installDeps };
310
522
  }
311
523
  async function main() {
524
+ let args;
525
+ try {
526
+ args = parseArgs(process.argv);
527
+ }
528
+ catch (err) {
529
+ if (!(err instanceof UsageError))
530
+ throw err;
531
+ console.error(`create-cwa: ${err.message}\n\n${USAGE}`);
532
+ process.exit(2);
533
+ }
534
+ if (args.help) {
535
+ console.log(USAGE);
536
+ return;
537
+ }
312
538
  intro(`create-cwa ${CLI_VERSION} — Components Web App scaffolder`);
313
539
  log.warn('CWA is a prerelease: expect breaking changes between versions (see CHANGELOG.md on GitHub).\n' +
314
540
  'create-cwa collects no telemetry; it only downloads the template from GitHub.');
315
- const args = parseArgs(process.argv);
316
- const s = spinner();
317
- s.start('Fetching manifest...');
541
+ const s = progress(args.ci);
542
+ s.start(args.templateDir ? `Reading the manifest in ${args.templateDir}...` : 'Fetching manifest...');
318
543
  let manifest;
319
544
  try {
320
- manifest = await fetchManifest(args.ref);
545
+ manifest = args.templateDir ? await readLocalManifest(args.templateDir) : await fetchManifest(args.ref);
321
546
  s.stop('Manifest loaded.');
322
547
  }
323
548
  catch (err) {
324
549
  s.stop(err.message);
325
550
  process.exit(1);
326
551
  }
327
- const answers = await askQuestions(manifest, args.projectName);
328
- const setup = await askSetup();
552
+ const answers = await askQuestions(manifest, args);
553
+ const setup = await askSetup(args);
329
554
  const targetDir = resolve(process.cwd(), answers.projectName);
330
555
  const tempDir = join(tmpdir(), `cwa-${randomBytes(6).toString('hex')}`);
331
- await downloadRepo(manifest, args.ref, tempDir);
332
- const s2 = spinner();
556
+ if (args.templateDir)
557
+ await copyTemplateDir(args.templateDir, tempDir, args.ci);
558
+ else
559
+ await downloadRepo(manifest, args.ref, tempDir, args.ci);
560
+ const s2 = progress(args.ci);
333
561
  s2.start('Configuring project...');
334
562
  try {
335
563
  await removeExcluded(tempDir, manifest.alwaysExclude);
@@ -375,6 +603,8 @@ async function main() {
375
603
  log.step('Running: pnpm install (in app/)');
376
604
  if (!run('pnpm', ['install'], join(targetDir, 'app'))) {
377
605
  log.warn('pnpm install failed. Run it manually inside app/.');
606
+ if (args.ci)
607
+ process.exitCode = 1;
378
608
  }
379
609
  }
380
610
  // bin/up is POSIX sh; Windows without sh (no WSL or Git Bash) gets the steps instead (#206).
@@ -386,11 +616,16 @@ async function main() {
386
616
  ready = run('sh', ['bin/up'], targetDir);
387
617
  if (!ready)
388
618
  log.warn('bin/up failed (see above). Fix it, then run bin/up again in the project directory.');
619
+ // Under --ci a failed start fails the run (#215).
620
+ if (!ready && args.ci)
621
+ process.exitCode = 1;
389
622
  }
390
623
  else {
391
624
  log.step('Running: docker compose up -d --wait');
392
625
  if (!run('docker', ['compose', 'up', '-d', '--wait'], targetDir)) {
393
626
  log.warn('docker compose up -d --wait failed. Run it again in the project directory.');
627
+ if (args.ci)
628
+ process.exitCode = 1;
394
629
  }
395
630
  }
396
631
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-cwa",
3
- "version": "2.0.0-alpha.46",
3
+ "version": "2.0.0-alpha.48",
4
4
  "description": "Create a new CWA (Components Web App) project",
5
5
  "type": "module",
6
6
  "bin": {
package/smoke.sh ADDED
@@ -0,0 +1,54 @@
1
+ #!/bin/sh
2
+ # Template CI only (#215): creates a project from this checkout with the built CLI, starts it through bin/up and checks the login.
3
+ # Usage: packages/create-cwa/smoke.sh <work dir> (SMOKE_FEATURES: all|none|a,b; SMOKE_FIXTURES: true|false)
4
+ # Needs node and pnpm (or a built dist/), git, docker with compose, and free ports 80, 443, 3001, 5432 and 8025.
5
+ set -u
6
+
7
+ ROOT=$(cd "$(dirname "$0")/../.." && pwd)
8
+ WORK=${1:?usage: smoke.sh <work dir>}
9
+ FEATURES=${SMOKE_FEATURES:-all}
10
+ FIXTURES=${SMOKE_FIXTURES:-true}
11
+ NAME=cwa-smoke
12
+ PROJECT="$WORK/$NAME"
13
+ # The images' first build, composer and pnpm installs on a CI runner take longer than a laptop's default 900 s.
14
+ export CWA_UP_TIMEOUT="${CWA_UP_TIMEOUT:-1800}"
15
+
16
+ fail() {
17
+ [ -z "${GITHUB_ACTIONS:-}" ] || echo "::error::create-cwa smoke: $*"
18
+ echo "create-cwa smoke failed: $*" >&2
19
+ [ "$(pwd)" != "$PROJECT" ] || docker compose logs --no-color --tail 80 php app >&2
20
+ exit 1
21
+ }
22
+
23
+ if [ ! -f "$ROOT/packages/create-cwa/dist/index.js" ]; then
24
+ (cd "$ROOT/packages/create-cwa" && pnpm install --frozen-lockfile && pnpm run build) || fail "couldn't build the CLI"
25
+ fi
26
+
27
+ [ ! -e "$PROJECT" ] || fail "$PROJECT already exists"
28
+ mkdir -p "$WORK" || exit 1
29
+ # CI checkouts can belong to another user than the one running git here (GitLab's dind job, GitHub containers).
30
+ if [ -n "${CI:-}" ]; then git config --global --add safe.directory "$ROOT"; fi
31
+
32
+ [ "$FIXTURES" = true ] && fixtures=--fixtures || fixtures=--no-fixtures
33
+ cd "$WORK" || exit 1
34
+ echo "==> create-cwa $NAME --ci --template-dir $ROOT --pipeline none --features $FEATURES $fixtures --start"
35
+ # The exit status goes through a file: POSIX sh has no pipefail.
36
+ { node "$ROOT/packages/create-cwa/bin/create-cwa.js" "$NAME" --ci --template-dir "$ROOT" \
37
+ --pipeline none --features "$FEATURES" "$fixtures" --start 2>&1; echo $? > "$WORK/status"; } | tee "$WORK/create-cwa.log"
38
+ status=$(cat "$WORK/status")
39
+ [ "$status" = 0 ] || fail "create-cwa exited $status (bin/up's output is above)"
40
+
41
+ grep -q 'Sign in: https://localhost/login' "$WORK/create-cwa.log" || fail "bin/up didn't print the login URL"
42
+ grep -q 'Admin: admin / admin' "$WORK/create-cwa.log" || fail "bin/up didn't print the admin login"
43
+
44
+ cd "$PROJECT" || exit 1
45
+ # From inside php, as bin/up does: the published ports are on the Docker host, which isn't this machine under dind.
46
+ login=$(docker compose exec -T php curl -fsSk --max-time 60 --resolve localhost:443:127.0.0.1 https://localhost/login) \
47
+ || fail "https://localhost/login didn't answer 200"
48
+ echo "$login" | grep -q 'type="password"' || fail "https://localhost/login has no password field"
49
+
50
+ code=$(docker compose exec -T php curl -sk --max-time 30 --resolve localhost:443:127.0.0.1 -o /dev/null -w '%{http_code}' \
51
+ -H 'Content-Type: application/json' -d '{"username":"admin","password":"admin"}' https://localhost/_api/login | tr -d '\r')
52
+ [ "$code" = 204 ] || fail "signing in as admin / admin answered $code, not 204"
53
+
54
+ echo "create-cwa smoke passed: features $FEATURES, fixtures $FIXTURES"
package/src/index.ts CHANGED
@@ -33,17 +33,132 @@ const CLI_VERSION: string = JSON.parse(
33
33
  readFileSync(new URL('../package.json', import.meta.url), 'utf8')
34
34
  ).version
35
35
 
36
- function parseArgs(argv: string[]): { projectName?: string; ref: string } {
36
+ interface CliOptions {
37
+ projectName?: string
38
+ ref: string
39
+ refGiven: boolean
40
+ yes: boolean
41
+ ci: boolean
42
+ templateDir?: string
43
+ pipeline?: string
44
+ features?: string[]
45
+ fixtures?: boolean
46
+ start?: boolean
47
+ installDeps?: boolean
48
+ help: boolean
49
+ }
50
+
51
+ const USAGE = `Usage: create-cwa [project-name] [options]
52
+
53
+ Without options every question is asked. A flag answers its question, so it isn't asked.
54
+
55
+ Options:
56
+ --ref <tag|branch> template version to download (default v${CLI_VERSION})
57
+ --template-dir <path> copy the template from a local checkout instead of downloading it
58
+ --pipeline <id> CI/CD pipeline: github, gitlab or none
59
+ --features <list> comma-separated features, "all" or "none"
60
+ --fixtures, --no-fixtures include the sample pages, or not
61
+ --start, --no-start run bin/up once the project is created, or not
62
+ --install-deps, --no-install-deps
63
+ pnpm install in app/ on this machine (only when the stack isn't started)
64
+ -y, --yes take the default for every question no flag answers
65
+ --ci never prompt (implies --yes); a missing project name is an error
66
+ -h, --help show this help`
67
+
68
+ class UsageError extends Error {}
69
+
70
+ const VALUE_FLAGS = ['--ref', '--template-dir', '--pipeline', '--features']
71
+
72
+ // Flags for unattended runs (#215); with none given, every question is asked as before.
73
+ function parseArgs(argv: string[]): CliOptions {
37
74
  const args = argv.slice(2)
38
- let ref = `v${CLI_VERSION}`
75
+ const opts: CliOptions = { ref: `v${CLI_VERSION}`, refGiven: false, yes: false, ci: false, help: false }
39
76
  const positional: string[] = []
40
77
  for (let i = 0; i < args.length; i++) {
41
- const arg = args[i]
42
- if (arg === '--ref' && args[i + 1]) ref = args[++i]
43
- else if (arg.startsWith('--ref=')) ref = arg.slice('--ref='.length)
44
- else positional.push(arg)
78
+ let arg = args[i]
79
+ let value: string | undefined
80
+ const eq = arg.indexOf('=')
81
+ if (arg.startsWith('--') && eq > 0) {
82
+ value = arg.slice(eq + 1)
83
+ arg = arg.slice(0, eq)
84
+ if (!VALUE_FLAGS.includes(arg)) throw new UsageError(`${arg} takes no value`)
85
+ } else if (VALUE_FLAGS.includes(arg)) {
86
+ value = args[i + 1]
87
+ if (value === undefined || value.startsWith('-')) throw new UsageError(`${arg} needs a value`)
88
+ i++
89
+ }
90
+ switch (arg) {
91
+ case '--':
92
+ break
93
+ case '--ref':
94
+ opts.ref = value as string
95
+ opts.refGiven = true
96
+ break
97
+ case '--template-dir':
98
+ opts.templateDir = value
99
+ break
100
+ case '--pipeline':
101
+ opts.pipeline = value
102
+ break
103
+ case '--features':
104
+ opts.features = (value as string).split(',').map((f) => f.trim()).filter(Boolean)
105
+ break
106
+ case '--fixtures':
107
+ case '--no-fixtures':
108
+ opts.fixtures = arg === '--fixtures'
109
+ break
110
+ case '--start':
111
+ case '--no-start':
112
+ opts.start = arg === '--start'
113
+ break
114
+ case '--install-deps':
115
+ case '--no-install-deps':
116
+ opts.installDeps = arg === '--install-deps'
117
+ break
118
+ case '-y':
119
+ case '--yes':
120
+ opts.yes = true
121
+ break
122
+ case '--ci':
123
+ opts.ci = true
124
+ opts.yes = true
125
+ break
126
+ case '-h':
127
+ case '--help':
128
+ opts.help = true
129
+ break
130
+ default:
131
+ if (arg.startsWith('-')) throw new UsageError(`Unknown option ${arg}`)
132
+ positional.push(arg)
133
+ }
134
+ }
135
+ if (positional.length > 1) throw new UsageError(`Unexpected argument "${positional[1]}"`)
136
+ if (opts.templateDir && opts.refGiven) throw new UsageError("--ref and --template-dir can't be used together")
137
+ if (opts.start && opts.installDeps) {
138
+ throw new UsageError('--install-deps is only for a stack that isn\'t started: the app container installs its own')
139
+ }
140
+ opts.projectName = positional[0]
141
+ return opts
142
+ }
143
+
144
+ function fail(message: string): never {
145
+ cancel(message)
146
+ process.exit(1)
147
+ }
148
+
149
+ // A spinner when someone is watching, plain log lines under --ci.
150
+ function progress(plain: boolean): { start(msg: string): void; stop(msg: string): void } {
151
+ return plain ? { start: (msg) => log.step(msg), stop: (msg) => log.info(msg) } : spinner()
152
+ }
153
+
154
+ async function readLocalManifest(templateDir: string): Promise<Manifest> {
155
+ const path = join(resolve(templateDir), 'cwa-manifest.json')
156
+ if (!existsSync(path)) throw new Error(`No CWA template in "${templateDir}": ${path} is missing.`)
157
+ try {
158
+ return JSON.parse(await readFile(path, 'utf-8')) as Manifest
159
+ } catch {
160
+ throw new Error(`${path} is not valid JSON.`)
45
161
  }
46
- return { projectName: positional[0], ref }
47
162
  }
48
163
 
49
164
  async function fetchManifest(ref: string): Promise<Manifest> {
@@ -108,46 +223,80 @@ function validateProjectName(value: string | undefined): string | undefined {
108
223
  return undefined
109
224
  }
110
225
 
111
- async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Answers> {
226
+ // Each answer comes from its flag, else the default under --yes (what Enter picks), else a prompt (#215).
227
+ async function askQuestions(manifest: Manifest, opts: CliOptions): Promise<Answers> {
112
228
  const question = (id: string): ManifestQuestion | undefined =>
113
229
  manifest.questions.find((q) => q.id === id)
114
230
 
115
231
  const nameQuestion = question('projectName')
116
- const projectName = checkCancel(
117
- await text({
118
- message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
119
- placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
120
- initialValue: targetArg ?? '',
121
- validate: validateProjectName,
122
- })
123
- ) as string
232
+ let projectName: string
233
+ if (opts.yes && opts.projectName !== undefined) {
234
+ const error = validateProjectName(opts.projectName)
235
+ if (error) fail(`Project name "${opts.projectName}": ${error}`)
236
+ projectName = opts.projectName
237
+ } else if (opts.ci) {
238
+ fail('--ci needs the project name: create-cwa <project-name> --ci')
239
+ } else {
240
+ projectName = checkCancel(
241
+ await text({
242
+ message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
243
+ placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
244
+ initialValue: opts.projectName ?? '',
245
+ validate: validateProjectName,
246
+ })
247
+ ) as string
248
+ }
124
249
 
125
250
  const ciQuestion = question('ci')
126
- const ci = checkCancel(
127
- await select({
128
- message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
129
- options: ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
130
- { value: 'github', label: 'GitHub Actions' },
131
- { value: 'gitlab', label: 'GitLab CI' },
132
- { value: 'none', label: 'None' },
133
- ],
134
- })
135
- ) as string
251
+ const ciOptions = ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
252
+ { value: 'github', label: 'GitHub Actions' },
253
+ { value: 'gitlab', label: 'GitLab CI' },
254
+ { value: 'none', label: 'None' },
255
+ ]
256
+ let ci: string
257
+ if (opts.pipeline !== undefined) {
258
+ if (!ciOptions.some((c) => c.value === opts.pipeline)) {
259
+ fail(`--pipeline ${opts.pipeline}: choose one of ${ciOptions.map((c) => c.value).join(', ')}`)
260
+ }
261
+ ci = opts.pipeline
262
+ } else if (opts.yes) {
263
+ ci = ciOptions[0].value
264
+ } else {
265
+ ci = checkCancel(
266
+ await select({
267
+ message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
268
+ options: ciOptions,
269
+ })
270
+ ) as string
271
+ }
136
272
 
137
273
  const featuresQuestion = question('features')
138
274
  const featureChoices =
139
275
  featuresQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? []
140
276
 
141
- const features = checkCancel(
142
- await multiselect({
143
- message: withHint(
144
- `${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`,
145
- featuresQuestion?.hint
146
- ),
147
- options: featureChoices,
148
- required: false,
149
- })
150
- ) as string[]
277
+ let features: string[]
278
+ if (opts.features !== undefined) {
279
+ const all = featureChoices.map((c) => c.value)
280
+ const flag = opts.features
281
+ features = flag.length === 1 && flag[0] === 'all' ? all : flag.length === 1 && flag[0] === 'none' ? [] : flag
282
+ const unknown = features.filter((f) => !all.includes(f))
283
+ if (unknown.length) {
284
+ fail(`--features: unknown ${unknown.join(', ')}. Choose from ${all.join(', ')}, or "all" or "none"`)
285
+ }
286
+ } else if (opts.yes) {
287
+ features = []
288
+ } else {
289
+ features = checkCancel(
290
+ await multiselect({
291
+ message: withHint(
292
+ `${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`,
293
+ featuresQuestion?.hint
294
+ ),
295
+ options: featureChoices,
296
+ required: false,
297
+ })
298
+ ) as string[]
299
+ }
151
300
 
152
301
  // Auto-include required features
153
302
  const resolved = new Set(features)
@@ -165,21 +314,77 @@ async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Ans
165
314
  }
166
315
 
167
316
  const fixturesQuestion = question('fixtures')
168
- const fixtures = checkCancel(
169
- await confirm({
170
- message: withHint(
171
- fixturesQuestion?.message ?? 'Include database fixtures for selected features?',
172
- fixturesQuestion?.hint
173
- ),
174
- initialValue: fixturesQuestion?.default ?? true,
175
- })
176
- ) as boolean
317
+ const fixtures =
318
+ opts.fixtures ??
319
+ (opts.yes
320
+ ? (fixturesQuestion?.default ?? true)
321
+ : (checkCancel(
322
+ await confirm({
323
+ message: withHint(
324
+ fixturesQuestion?.message ?? 'Include database fixtures for selected features?',
325
+ fixturesQuestion?.hint
326
+ ),
327
+ initialValue: fixturesQuestion?.default ?? true,
328
+ })
329
+ ) as boolean))
177
330
 
178
331
  return { projectName: projectName.trim(), ci, features: [...resolved], fixtures }
179
332
  }
180
333
 
181
- async function downloadRepo(manifest: Manifest, ref: string, tempDir: string): Promise<void> {
182
- const s = spinner()
334
+ // Files a download would contain: what git tracks or would track, minus export-ignore paths (GitHub's tarball honours them).
335
+ function templateFiles(src: string): string[] | null {
336
+ const ls = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
337
+ cwd: src,
338
+ encoding: 'utf8',
339
+ })
340
+ if (ls.status !== 0) return null
341
+ const files = ls.stdout.split('\0').filter((f) => f && existsSync(join(src, f)))
342
+
343
+ const paths = new Set<string>()
344
+ for (const file of files) {
345
+ const parts = file.split('/')
346
+ for (let i = 1; i <= parts.length; i++) paths.add(parts.slice(0, i).join('/'))
347
+ }
348
+ const attr = spawnSync('git', ['check-attr', '-z', '--stdin', 'export-ignore'], {
349
+ cwd: src,
350
+ input: [...paths].join('\0'),
351
+ encoding: 'utf8',
352
+ })
353
+ if (attr.status !== 0) return null
354
+ const out = attr.stdout.split('\0')
355
+ const ignored = new Set<string>()
356
+ for (let i = 0; i + 2 < out.length; i += 3) {
357
+ if (out[i + 2] === 'set') ignored.add(out[i])
358
+ }
359
+ return files.filter((file) => {
360
+ const parts = file.split('/')
361
+ for (let i = 1; i <= parts.length; i++) if (ignored.has(parts.slice(0, i).join('/'))) return false
362
+ return true
363
+ })
364
+ }
365
+
366
+ // --template-dir (#215): a local checkout instead of the download; excludes and stripping still apply after.
367
+ async function copyTemplateDir(templateDir: string, tempDir: string, plain: boolean): Promise<void> {
368
+ const src = resolve(templateDir)
369
+ const s = progress(plain)
370
+ s.start(`Copying template from ${src}...`)
371
+ const files = templateFiles(src)
372
+ if (files) {
373
+ for (const file of files) {
374
+ await fse.copy(join(src, file), join(tempDir, file), { dereference: false })
375
+ }
376
+ } else {
377
+ // Not a git checkout: everything but dependencies and VCS data.
378
+ const skip = new Set(['.git', 'node_modules', 'vendor'])
379
+ await fse.copy(src, tempDir, {
380
+ filter: (path) => !path.slice(src.length).split(/[\\/]/).some((part) => skip.has(part)),
381
+ })
382
+ }
383
+ s.stop('Template copied.')
384
+ }
385
+
386
+ async function downloadRepo(manifest: Manifest, ref: string, tempDir: string, plain: boolean): Promise<void> {
387
+ const s = progress(plain)
183
388
  s.start(`Downloading template (${ref})...`)
184
389
  try {
185
390
  await downloadTemplate(`github:${manifest.repo}#${ref}`, {
@@ -336,80 +541,103 @@ async function moveToTarget(tempDir: string, targetDir: string): Promise<void> {
336
541
  // Decides, before anything is downloaded, whether to start the stack and whether to
337
542
  // install app/ dependencies on the host. The host install shares app/node_modules with
338
543
  // the app container, so it's only offered when the stack isn't started now (#204).
339
- async function askSetup(): Promise<{ startDocker: boolean; installDeps: boolean }> {
544
+ // --start fails when the stack can't be started; without it (prompted or --yes) the project is created anyway (#215).
545
+ async function askSetup(opts: CliOptions): Promise<{ startDocker: boolean; installDeps: boolean }> {
340
546
  let startDocker = false
341
547
  if (commandExists('docker')) {
342
- startDocker = checkCancel(
343
- await confirm({
344
- message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
345
- initialValue: true,
346
- })
347
- ) as boolean
548
+ startDocker =
549
+ opts.start ??
550
+ (opts.yes ||
551
+ (checkCancel(
552
+ await confirm({
553
+ message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
554
+ initialValue: true,
555
+ })
556
+ ) as boolean))
557
+ } else if (opts.start) {
558
+ fail('--start: docker not found. Install Docker Desktop (or Docker Engine with the compose plugin).')
348
559
  } else {
349
560
  log.warn('docker not found. Install Docker Desktop, then run `bin/up` in the project.')
350
561
  }
351
562
 
352
563
  if (startDocker) {
353
- const s = spinner()
564
+ const s = progress(opts.ci)
354
565
  s.start('Checking Docker and ports...')
355
566
  const result = await preflight()
356
567
  s.stop('Docker checked.')
357
- if (!result.dockerRunning) {
358
- log.warn('Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).')
359
- startDocker = false
360
- } else if (result.takenPorts.length) {
361
- log.warn(result.takenPorts.join('\n\n'))
362
- startDocker = false
363
- }
568
+ const problem = !result.dockerRunning
569
+ ? 'Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).'
570
+ : result.takenPorts.join('\n\n')
364
571
  if (result.memoryWarning) log.warn(result.memoryWarning)
365
- if (!startDocker) {
572
+ if (problem) {
573
+ if (opts.start) fail(`--start: ${problem}`)
574
+ log.warn(problem)
366
575
  log.info('The project will be created without starting Docker. Run `bin/up` in it once that is fixed.')
576
+ startDocker = false
367
577
  }
368
578
  return { startDocker, installDeps: false }
369
579
  }
370
580
 
371
581
  let installDeps = false
372
582
  if (commandExists('pnpm')) {
373
- installDeps = checkCancel(
374
- await confirm({
375
- message: withHint(
376
- 'Install app/ dependencies on this machine?',
377
- 'only for editor types; the app container installs its own on first start'
378
- ),
379
- initialValue: false,
380
- })
381
- ) as boolean
583
+ installDeps =
584
+ opts.installDeps ??
585
+ (!opts.yes &&
586
+ (checkCancel(
587
+ await confirm({
588
+ message: withHint(
589
+ 'Install app/ dependencies on this machine?',
590
+ 'only for editor types; the app container installs its own on first start'
591
+ ),
592
+ initialValue: false,
593
+ })
594
+ ) as boolean))
595
+ } else if (opts.installDeps) {
596
+ fail('--install-deps: pnpm not found.')
382
597
  }
383
598
  return { startDocker, installDeps }
384
599
  }
385
600
 
386
601
  async function main(): Promise<void> {
602
+ let args: CliOptions
603
+ try {
604
+ args = parseArgs(process.argv)
605
+ } catch (err) {
606
+ if (!(err instanceof UsageError)) throw err
607
+ console.error(`create-cwa: ${err.message}\n\n${USAGE}`)
608
+ process.exit(2)
609
+ }
610
+ if (args.help) {
611
+ console.log(USAGE)
612
+ return
613
+ }
614
+
387
615
  intro(`create-cwa ${CLI_VERSION} — Components Web App scaffolder`)
388
616
  log.warn(
389
617
  'CWA is a prerelease: expect breaking changes between versions (see CHANGELOG.md on GitHub).\n' +
390
618
  'create-cwa collects no telemetry; it only downloads the template from GitHub.'
391
619
  )
392
620
 
393
- const args = parseArgs(process.argv)
394
- const s = spinner()
395
- s.start('Fetching manifest...')
621
+ const s = progress(args.ci)
622
+ s.start(args.templateDir ? `Reading the manifest in ${args.templateDir}...` : 'Fetching manifest...')
396
623
  let manifest: Manifest
397
624
  try {
398
- manifest = await fetchManifest(args.ref)
625
+ manifest = args.templateDir ? await readLocalManifest(args.templateDir) : await fetchManifest(args.ref)
399
626
  s.stop('Manifest loaded.')
400
627
  } catch (err) {
401
628
  s.stop((err as Error).message)
402
629
  process.exit(1)
403
630
  }
404
631
 
405
- const answers = await askQuestions(manifest, args.projectName)
406
- const setup = await askSetup()
632
+ const answers = await askQuestions(manifest, args)
633
+ const setup = await askSetup(args)
407
634
  const targetDir = resolve(process.cwd(), answers.projectName)
408
635
  const tempDir = join(tmpdir(), `cwa-${randomBytes(6).toString('hex')}`)
409
636
 
410
- await downloadRepo(manifest, args.ref, tempDir)
637
+ if (args.templateDir) await copyTemplateDir(args.templateDir, tempDir, args.ci)
638
+ else await downloadRepo(manifest, args.ref, tempDir, args.ci)
411
639
 
412
- const s2 = spinner()
640
+ const s2 = progress(args.ci)
413
641
  s2.start('Configuring project...')
414
642
 
415
643
  try {
@@ -465,6 +693,7 @@ async function main(): Promise<void> {
465
693
  log.step('Running: pnpm install (in app/)')
466
694
  if (!run('pnpm', ['install'], join(targetDir, 'app'))) {
467
695
  log.warn('pnpm install failed. Run it manually inside app/.')
696
+ if (args.ci) process.exitCode = 1
468
697
  }
469
698
  }
470
699
 
@@ -476,10 +705,13 @@ async function main(): Promise<void> {
476
705
  log.step('Running: bin/up')
477
706
  ready = run('sh', ['bin/up'], targetDir)
478
707
  if (!ready) log.warn('bin/up failed (see above). Fix it, then run bin/up again in the project directory.')
708
+ // Under --ci a failed start fails the run (#215).
709
+ if (!ready && args.ci) process.exitCode = 1
479
710
  } else {
480
711
  log.step('Running: docker compose up -d --wait')
481
712
  if (!run('docker', ['compose', 'up', '-d', '--wait'], targetDir)) {
482
713
  log.warn('docker compose up -d --wait failed. Run it again in the project directory.')
714
+ if (args.ci) process.exitCode = 1
483
715
  }
484
716
  }
485
717
  }