@garyr/pt-cli 0.39.1 → 0.40.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,784 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import inquirer from 'inquirer';
4
+ import { loadConfig, saveConfig, shouldExclude, shouldIgnore, shouldExcludeFile, getDefaultPostConfig } from '../config.js';
5
+ import chalk from 'chalk';
6
+ import { downloadAndExtract } from '../remote.js';
7
+ function getNewFolders(storedStructure, targetPath, ignorePatterns) {
8
+ const added = [];
9
+ const getStructureMap = (nodes) => {
10
+ const map = new Map();
11
+ for (const node of nodes) {
12
+ map.set(node.name, node);
13
+ }
14
+ return map;
15
+ };
16
+ const storedMap = getStructureMap(storedStructure);
17
+ const targetStructure = extractStructure(targetPath, targetPath, ignorePatterns);
18
+ const targetMap = getStructureMap(targetStructure);
19
+ // Find only new folders
20
+ for (const [name, targetNode] of targetMap) {
21
+ if (!storedMap.has(name)) {
22
+ added.push(targetNode);
23
+ }
24
+ }
25
+ return { added };
26
+ }
27
+ function getNewFiles(storedTemplate, targetPath) {
28
+ const newFiles = [];
29
+ // Get current files in target
30
+ const currentFiles = fs.readdirSync(targetPath, { withFileTypes: true })
31
+ .filter(e => e.isFile())
32
+ .map(e => e.name);
33
+ // Get files from stored template
34
+ const storedFiles = storedTemplate.copy_files?.map(f => f.src) || [];
35
+ // Find only new files
36
+ for (const file of currentFiles) {
37
+ if (!storedFiles.includes(file)) {
38
+ newFiles.push(file);
39
+ }
40
+ }
41
+ return { newFiles };
42
+ }
43
+ function getNewVariables(storedVariables, targetPath) {
44
+ const newVariables = [];
45
+ // Get variables from target directory
46
+ const targetVars = findVariablesInFiles(targetPath, targetPath);
47
+ const storedVarMap = new Set(storedVariables.map(v => v.name));
48
+ // Find only new variables
49
+ for (const varName of targetVars) {
50
+ if (!storedVarMap.has(varName)) {
51
+ newVariables.push({
52
+ name: varName,
53
+ prompt: `Enter ${varName}:`,
54
+ required: true
55
+ });
56
+ }
57
+ }
58
+ return { newVariables };
59
+ }
60
+ export async function update(sourcePath, templateName, options = {}) {
61
+ // Determine if additive mode is disabled
62
+ const isFullMode = options.noDiff;
63
+ let resolvedPath;
64
+ // Phase 1: Remote Check
65
+ if (sourcePath.startsWith('http')) {
66
+ console.log(chalk.cyan(`Downloading remote template from: ${sourcePath}...`));
67
+ try {
68
+ resolvedPath = await downloadAndExtract(sourcePath, options.json || false, options.allowUntrusted || false);
69
+ }
70
+ catch (err) {
71
+ if (err.message === 'Download cancelled by user due to untrusted source') {
72
+ console.log(chalk.yellow('Download cancelled. Exiting.'));
73
+ process.exit(0);
74
+ }
75
+ throw err;
76
+ }
77
+ }
78
+ else {
79
+ resolvedPath = path.resolve(sourcePath);
80
+ }
81
+ if (!fs.existsSync(resolvedPath)) {
82
+ console.error(chalk.red(`Error: Path "${resolvedPath}" does not exist.`));
83
+ process.exit(1);
84
+ }
85
+ const config = loadConfig();
86
+ if (!config.templates[templateName]) {
87
+ console.error(chalk.red(`Template "${templateName}" not found.`));
88
+ process.exit(1);
89
+ }
90
+ // Check for template configuration JSON file (.pt-template.json or template.json)
91
+ let fileTemplateConfig = {};
92
+ const jsonConfigPaths = [
93
+ path.join(resolvedPath, '.pt-template.json'),
94
+ path.join(resolvedPath, 'template.json')
95
+ ];
96
+ for (const jPath of jsonConfigPaths) {
97
+ if (fs.existsSync(jPath)) {
98
+ try {
99
+ const fileContent = fs.readFileSync(jPath, 'utf-8');
100
+ fileTemplateConfig = JSON.parse(fileContent);
101
+ if (!options.json)
102
+ console.log(chalk.cyan(`Auto-detected template configurations from ${path.basename(jPath)}`));
103
+ break;
104
+ }
105
+ catch (e) {
106
+ console.warn(chalk.yellow(`Warning: Failed to parse ${path.basename(jPath)}: ${e.message}`));
107
+ }
108
+ }
109
+ }
110
+ // Check for .info.md
111
+ let infoName = '';
112
+ let infoDesc = '';
113
+ const infoPath = path.join(resolvedPath, '.info.md');
114
+ if (fs.existsSync(infoPath)) {
115
+ const infoContent = fs.readFileSync(infoPath, 'utf-8');
116
+ const lines = infoContent.split('\n');
117
+ for (const line of lines) {
118
+ if (line.startsWith('# ')) {
119
+ infoName = line.substring(2).trim();
120
+ }
121
+ else if (line.trim() !== '' && !infoDesc && !line.startsWith('#')) {
122
+ infoDesc = line.trim();
123
+ }
124
+ }
125
+ }
126
+ let description = config.templates[templateName].description || '';
127
+ let templateRoot = config.templates[templateName].templateRoot || resolvedPath;
128
+ if (!options.yes && !options.json) {
129
+ const answers = await inquirer.prompt([
130
+ {
131
+ type: 'input',
132
+ name: 'description',
133
+ message: 'Template description:',
134
+ default: description
135
+ },
136
+ {
137
+ type: 'input',
138
+ name: 'templateRoot',
139
+ message: 'Template root folder:',
140
+ default: templateRoot
141
+ }
142
+ ]);
143
+ description = answers.description;
144
+ templateRoot = answers.templateRoot;
145
+ if (!fs.existsSync(templateRoot)) {
146
+ console.error(chalk.red(`Error: Template root path "${templateRoot}" does not exist.`));
147
+ process.exit(1);
148
+ }
149
+ }
150
+ else {
151
+ if (options.desc) {
152
+ description = options.desc;
153
+ }
154
+ else if (fileTemplateConfig.description) {
155
+ description = fileTemplateConfig.description;
156
+ }
157
+ else if (infoDesc) {
158
+ description = infoDesc;
159
+ }
160
+ templateRoot = resolvedPath;
161
+ }
162
+ const cliIgnore = options.ignore ? options.ignore.split(',').map((s) => s.trim()).filter(Boolean) : [];
163
+ const ignorePatterns = [...(config.ignore || []), ...cliIgnore];
164
+ // Detect variables from files
165
+ const detectedVars = findVariablesInFiles(resolvedPath, resolvedPath, ignorePatterns);
166
+ if (detectedVars.length > 0 && !options.json) {
167
+ console.log(chalk.cyan(`Auto-detected ${detectedVars.length} variable(s): ${detectedVars.join(', ')}`));
168
+ }
169
+ let variables = [];
170
+ // During updates, merge existing template variables with JSON file variables
171
+ if (config.templates[templateName].variables) {
172
+ variables = [...config.templates[templateName].variables];
173
+ }
174
+ // Then add JSON variables (overwrite/update existing ones with same name)
175
+ if (fileTemplateConfig.variables && Array.isArray(fileTemplateConfig.variables)) {
176
+ for (const v of fileTemplateConfig.variables) {
177
+ const existingIndex = variables.findIndex(existing => existing.name === v.name);
178
+ if (existingIndex !== -1) {
179
+ // Update existing variable with JSON values (but preserve other fields)
180
+ variables[existingIndex] = { ...variables[existingIndex], ...v };
181
+ }
182
+ else {
183
+ // Add new variable
184
+ variables.push({ ...v });
185
+ }
186
+ }
187
+ }
188
+ // Add detected variables if not already present
189
+ for (const varName of detectedVars) {
190
+ if (!variables.some(v => v.name === varName)) {
191
+ variables.push({
192
+ name: varName,
193
+ prompt: `Enter ${varName}:`,
194
+ required: true
195
+ });
196
+ }
197
+ }
198
+ // Variable handling - additive mode
199
+ if (!isFullMode) {
200
+ // Additive mode: only present new variables for selection
201
+ const variableDiff = getNewVariables(config.templates[templateName].variables || [], resolvedPath);
202
+ // Also include default/global variables that are not already in the template
203
+ const globalVarsToPrompt = [];
204
+ if (config.variables && Array.isArray(config.variables)) {
205
+ for (const v of config.variables) {
206
+ if (!variables.some(existing => existing.name === v.name) &&
207
+ !variableDiff.newVariables.some(existing => existing.name === v.name)) {
208
+ globalVarsToPrompt.push({ ...v });
209
+ }
210
+ }
211
+ }
212
+ const combinedNewVars = [...variableDiff.newVariables, ...globalVarsToPrompt];
213
+ if (combinedNewVars.length > 0) {
214
+ console.log(chalk.cyan(`\n📊 New Variables:`));
215
+ console.log(chalk.green(` + ${combinedNewVars.length} new variable(s): ${combinedNewVars.map(v => v.name).join(', ')}`));
216
+ // Show interactive checkbox for new variables
217
+ if (!options.yes && !options.json) {
218
+ const { selectedVars } = await inquirer.prompt({
219
+ type: 'checkbox',
220
+ name: 'selectedVars',
221
+ message: 'Select variables to include (space to toggle):',
222
+ loop: false,
223
+ theme: {
224
+ icon: {
225
+ checked: chalk.green('[x] '),
226
+ unchecked: '[ ] ',
227
+ }
228
+ },
229
+ choices: combinedNewVars.map(v => ({
230
+ name: v.name,
231
+ checked: true // Auto-select by default
232
+ }))
233
+ });
234
+ // Only add selected variables
235
+ variables.push(...combinedNewVars.filter(v => selectedVars.includes(v.name)));
236
+ }
237
+ else {
238
+ // In --yes or --json mode, auto-add all
239
+ variables.push(...combinedNewVars);
240
+ }
241
+ }
242
+ else {
243
+ console.log(chalk.cyan("No new variables detected"));
244
+ }
245
+ }
246
+ else {
247
+ // Full mode: original behavior with optional default/global variables prompt
248
+ const globalVarsToPrompt = [];
249
+ if (config.variables && Array.isArray(config.variables)) {
250
+ for (const v of config.variables) {
251
+ if (!variables.some(existing => existing.name === v.name)) {
252
+ globalVarsToPrompt.push({ ...v });
253
+ }
254
+ }
255
+ }
256
+ if (globalVarsToPrompt.length > 0) {
257
+ if (!options.yes && !options.json) {
258
+ const { selectedGlobals } = await inquirer.prompt({
259
+ type: 'checkbox',
260
+ name: 'selectedGlobals',
261
+ message: 'Select default/global variables to include (space to toggle):',
262
+ loop: false,
263
+ theme: {
264
+ icon: {
265
+ checked: chalk.green('[x] '),
266
+ unchecked: '[ ] ',
267
+ }
268
+ },
269
+ choices: globalVarsToPrompt.map(v => ({ name: v.name, checked: true }))
270
+ });
271
+ variables.push(...globalVarsToPrompt.filter(v => selectedGlobals.includes(v.name)));
272
+ }
273
+ else {
274
+ variables.push(...globalVarsToPrompt);
275
+ }
276
+ }
277
+ let hasMoreVariables = false;
278
+ if (!options.yes && !options.json) {
279
+ const message = variables.length > 0
280
+ ? `Detected/Existing variables: ${variables.map(v => v.name).join(', ')}. Define more?`
281
+ : 'Define template variables (e.g., client_name, project_type)?';
282
+ const response = await inquirer.prompt({
283
+ type: 'confirm',
284
+ name: 'hasMoreVariables',
285
+ message: message,
286
+ default: false
287
+ });
288
+ hasMoreVariables = response.hasMoreVariables;
289
+ }
290
+ if (hasMoreVariables) {
291
+ const { variableDefs } = await inquirer.prompt({
292
+ type: 'input',
293
+ name: 'variableDefs',
294
+ message: 'Define additional variables as comma-separated names:',
295
+ });
296
+ if (variableDefs) {
297
+ const additionalVars = variableDefs.split(',').map((v) => v.trim()).filter(Boolean);
298
+ for (const v of additionalVars) {
299
+ if (!variables.some(existing => existing.name === v)) {
300
+ variables.push({
301
+ name: v,
302
+ prompt: `Enter ${v}:`,
303
+ required: true
304
+ });
305
+ }
306
+ }
307
+ }
308
+ }
309
+ }
310
+ // 1. Structure (skeleton) - Additive mode
311
+ let folders = [];
312
+ if (!isFullMode) {
313
+ // Additive mode: only add new folders
314
+ const structureDiff = getNewFolders(config.templates[templateName].folders, resolvedPath, ignorePatterns);
315
+ if (structureDiff.added.length > 0) {
316
+ console.log(chalk.cyan(`\n📊 New Folders:`));
317
+ console.log(chalk.green(` + ${structureDiff.added.length} new folder(s): ${structureDiff.added.map(f => f.name).join(', ')}`));
318
+ // Show interactive checkbox for new folders
319
+ if (!options.yes && !options.json) {
320
+ const { selectedFolders } = await inquirer.prompt({
321
+ type: 'checkbox',
322
+ name: 'selectedFolders',
323
+ message: 'Select folders to include in template structure (space to toggle):',
324
+ loop: false,
325
+ theme: {
326
+ icon: {
327
+ checked: chalk.green('[x] '),
328
+ unchecked: '[ ] ',
329
+ }
330
+ },
331
+ choices: structureDiff.added.map(f => ({
332
+ name: f.name,
333
+ checked: true // Auto-select by default
334
+ }))
335
+ });
336
+ // Only add selected folders
337
+ folders = [...config.templates[templateName].folders, ...structureDiff.added.filter(f => selectedFolders.includes(f.name))];
338
+ }
339
+ else {
340
+ // In --yes or --json mode, auto-add all
341
+ folders = [...config.templates[templateName].folders, ...structureDiff.added];
342
+ }
343
+ }
344
+ else {
345
+ console.log(chalk.cyan("No new folders detected"));
346
+ folders = config.templates[templateName].folders;
347
+ }
348
+ }
349
+ else {
350
+ // Full mode: original behavior
351
+ folders = fileTemplateConfig.folders && Array.isArray(fileTemplateConfig.folders)
352
+ ? fileTemplateConfig.folders
353
+ : extractStructure(resolvedPath, resolvedPath, ignorePatterns);
354
+ }
355
+ // 2. Content Selection (Root only) - Additive mode
356
+ const rootEntries = fs.readdirSync(resolvedPath, { withFileTypes: true })
357
+ .filter(e => !shouldExclude(resolvedPath, path.join(resolvedPath, e.name), ignorePatterns))
358
+ .filter(e => !shouldIgnore(e.name, e.name, ignorePatterns));
359
+ const rootFiles = rootEntries.filter(e => e.isFile()).map(e => e.name);
360
+ const rootDirs = rootEntries.filter(e => e.isDirectory()).map(e => e.name);
361
+ let selectedFiles = [];
362
+ let selectedFolders = [];
363
+ let selectedStructure = [];
364
+ if (!isFullMode) {
365
+ // Additive mode for files and folders
366
+ // Start with existing files and folders, preserving their substitute_variables settings
367
+ const existingCopyFiles = config.templates[templateName].copy_files || [];
368
+ selectedFiles = existingCopyFiles.map(f => f.src);
369
+ const fileDiff = getNewFiles(config.templates[templateName], resolvedPath);
370
+ if (fileDiff.newFiles.length > 0) {
371
+ console.log(chalk.cyan(`\n📊 New Files:`));
372
+ console.log(chalk.green(` + ${fileDiff.newFiles.length} new file(s): ${fileDiff.newFiles.join(', ')}`));
373
+ // Show interactive checkbox for new files
374
+ if (!options.yes && !options.json) {
375
+ const { selectedFileChoices } = await inquirer.prompt({
376
+ type: 'checkbox',
377
+ name: 'selectedFileChoices',
378
+ message: 'Select files to include (space to toggle):',
379
+ loop: false,
380
+ theme: {
381
+ icon: {
382
+ checked: chalk.green('[x] '),
383
+ unchecked: '[ ] ',
384
+ }
385
+ },
386
+ choices: fileDiff.newFiles.map(f => ({
387
+ name: f,
388
+ checked: true // Auto-select by default
389
+ }))
390
+ });
391
+ // Only add selected files
392
+ selectedFiles.push(...fileDiff.newFiles.filter(f => selectedFileChoices.includes(f)));
393
+ }
394
+ else {
395
+ // In --yes or --json mode, auto-add all
396
+ selectedFiles.push(...fileDiff.newFiles);
397
+ }
398
+ }
399
+ else {
400
+ console.log(chalk.cyan("No new files detected"));
401
+ }
402
+ // For folders, use additive mode logic
403
+ // Always preserve existing folders first
404
+ selectedStructure = config.templates[templateName].folders?.map(f => f.name) || [];
405
+ selectedFolders = selectedStructure.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p));
406
+ if (rootDirs.length > 0) {
407
+ const structureDiff = getNewFolders(config.templates[templateName].folders, resolvedPath, ignorePatterns);
408
+ if (structureDiff.added.length > 0) {
409
+ // Auto-select added folders for structure
410
+ selectedStructure = [...new Set([...selectedStructure, ...structureDiff.added.map(f => f.name)])];
411
+ // Auto-select for recursive copy if they're in the standard list
412
+ selectedFolders = selectedStructure.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p));
413
+ }
414
+ else {
415
+ // Keep existing folders
416
+ selectedFolders = selectedStructure.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p));
417
+ }
418
+ }
419
+ else {
420
+ // Keep existing folders
421
+ selectedFolders = selectedStructure.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p));
422
+ }
423
+ }
424
+ else {
425
+ // Full mode: original behavior
426
+ if (options.yes || options.json) {
427
+ // If --yes, auto-select the defaults
428
+ selectedFiles = rootFiles.filter(f => ['.makerc', 'readme.md', 'README.md', '.gitattributes', '.gitignore', 'Makefile', 'makefile', 'package.json'].some(p => f.toLowerCase() === p.toLowerCase()));
429
+ selectedStructure = rootDirs; // Include all folders in structure
430
+ selectedFolders = rootDirs.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p)); // Only copy specific ones recursively
431
+ }
432
+ else {
433
+ if (rootFiles.length > 0) {
434
+ const filesResponse = await inquirer.prompt({
435
+ type: 'checkbox',
436
+ name: 'selectedFiles',
437
+ message: 'Select root files to include as boilerplate:',
438
+ loop: false,
439
+ theme: {
440
+ icon: {
441
+ checked: chalk.green('[x] '),
442
+ unchecked: '[ ] ',
443
+ }
444
+ },
445
+ choices: rootFiles.map(f => ({
446
+ name: f,
447
+ checked: ['.makerc', 'readme.md', 'README.md', '.gitattributes', '.gitignore', 'Makefile', 'makefile', 'package.json'].some(p => f.toLowerCase() === p.toLowerCase())
448
+ }))
449
+ });
450
+ selectedFiles = filesResponse.selectedFiles;
451
+ }
452
+ else {
453
+ selectedFiles = [];
454
+ }
455
+ if (rootDirs.length > 0) {
456
+ const foldersResponse = await inquirer.prompt({
457
+ type: 'checkbox',
458
+ name: 'selectedStructure',
459
+ message: 'Select folders to include in the template structure (skeleton):',
460
+ loop: false,
461
+ theme: {
462
+ icon: {
463
+ checked: chalk.green('[x] '),
464
+ unchecked: '[ ] ',
465
+ }
466
+ },
467
+ choices: rootDirs.map(d => ({
468
+ name: d,
469
+ checked: true // Include all in structure by default
470
+ }))
471
+ });
472
+ selectedStructure = foldersResponse.selectedStructure;
473
+ }
474
+ else {
475
+ selectedStructure = [];
476
+ }
477
+ if (selectedStructure.length > 0) {
478
+ const copyFoldersResponse = await inquirer.prompt({
479
+ type: 'checkbox',
480
+ name: 'selectedFolders',
481
+ message: 'Select folders to copy RECURSIVELY as boilerplate (with contents):',
482
+ loop: false,
483
+ theme: {
484
+ icon: {
485
+ checked: chalk.green('[x] '),
486
+ unchecked: '[ ] ',
487
+ }
488
+ },
489
+ choices: selectedStructure.map((d) => ({
490
+ name: d,
491
+ checked: ['APP', 'scripts', 'bin'].some(p => d === p)
492
+ }))
493
+ });
494
+ selectedFolders = copyFoldersResponse.selectedFolders;
495
+ }
496
+ else {
497
+ selectedFolders = [];
498
+ }
499
+ }
500
+ }
501
+ const copy_files = [];
502
+ if (fileTemplateConfig.copy_files && Array.isArray(fileTemplateConfig.copy_files)) {
503
+ copy_files.push(...fileTemplateConfig.copy_files);
504
+ }
505
+ else {
506
+ const existingCopyFiles = config.templates[templateName].copy_files || [];
507
+ const existingMap = new Map();
508
+ for (const entry of existingCopyFiles) {
509
+ existingMap.set(entry.src, entry);
510
+ }
511
+ const addedSrcs = new Set();
512
+ for (const f of selectedFiles) {
513
+ if (addedSrcs.has(f))
514
+ continue;
515
+ addedSrcs.add(f);
516
+ if (existingMap.has(f)) {
517
+ copy_files.push(existingMap.get(f));
518
+ }
519
+ else {
520
+ copy_files.push({ src: f, dest: f, substitute_variables: true });
521
+ }
522
+ }
523
+ for (const d of selectedFolders) {
524
+ if (addedSrcs.has(d))
525
+ continue;
526
+ addedSrcs.add(d);
527
+ if (existingMap.has(d)) {
528
+ copy_files.push(existingMap.get(d));
529
+ }
530
+ else {
531
+ copy_files.push({ src: d, dest: d, substitute_variables: true });
532
+ }
533
+ }
534
+ }
535
+ const templateConfig = {
536
+ description: description,
537
+ templateRoot: templateRoot,
538
+ folders: fileTemplateConfig.folders ? folders : folders.filter(f => selectedStructure.includes(f.name)),
539
+ copy_files: copy_files,
540
+ variables: variables.length > 0 ? variables : undefined
541
+ };
542
+ // Check for post_config scripts
543
+ let postConfigTasks = [];
544
+ if (fileTemplateConfig.post_config && Array.isArray(fileTemplateConfig.post_config)) {
545
+ postConfigTasks = [...fileTemplateConfig.post_config];
546
+ }
547
+ else {
548
+ const shPath = path.join(resolvedPath, 'post_config.sh');
549
+ const batPath = path.join(resolvedPath, 'post_config.bat');
550
+ if (fs.existsSync(shPath)) {
551
+ const lines = fs.readFileSync(shPath, 'utf-8').split('\n');
552
+ let currentDesc = '';
553
+ for (const line of lines) {
554
+ if (line.startsWith('echo "Running: ')) {
555
+ currentDesc = line.substring(15, line.length - 1).replace(/"$/, '');
556
+ }
557
+ else if (line.trim() && !line.startsWith('#') && !line.startsWith('echo ')) {
558
+ postConfigTasks.push({ command: line.trim(), description: currentDesc || line.trim() });
559
+ currentDesc = '';
560
+ }
561
+ }
562
+ }
563
+ else if (fs.existsSync(batPath)) {
564
+ const lines = fs.readFileSync(batPath, 'utf-8').split('\n');
565
+ let currentDesc = '';
566
+ for (const line of lines) {
567
+ if (line.startsWith('echo Running: ')) {
568
+ currentDesc = line.substring(14).trim();
569
+ }
570
+ else if (line.trim() && !line.startsWith('::') && !line.startsWith('@echo') && !line.startsWith('echo ')) {
571
+ postConfigTasks.push({ command: line.trim(), description: currentDesc || line.trim() });
572
+ currentDesc = '';
573
+ }
574
+ }
575
+ }
576
+ }
577
+ if (postConfigTasks.length > 0) {
578
+ templateConfig.post_config = postConfigTasks;
579
+ if (!options.json && !fileTemplateConfig.post_config)
580
+ console.log(chalk.cyan(`Auto-detected ${postConfigTasks.length} post_config action(s) from script.`));
581
+ }
582
+ // Handle default_post_config tasks
583
+ const defaultPostConfig = getDefaultPostConfig(config);
584
+ const defaultApplicableTasks = defaultPostConfig.filter(t => !t.type || t.type === templateName);
585
+ if (defaultApplicableTasks.length > 0) {
586
+ let selectedTaskNames = [];
587
+ if (options.yes || options.json) {
588
+ selectedTaskNames = defaultApplicableTasks.map(t => t.command || t.script || '');
589
+ }
590
+ else {
591
+ const choices = [];
592
+ for (const t of defaultApplicableTasks) {
593
+ const cmd = t.command || t.script || '(no command)';
594
+ const desc = t.description ? ` (${t.description})` : '';
595
+ choices.push({
596
+ name: `${cmd}${desc}`,
597
+ value: cmd,
598
+ checked: t.checked !== false
599
+ });
600
+ }
601
+ const response = await inquirer.prompt({
602
+ type: 'checkbox',
603
+ name: 'selected',
604
+ message: 'Select default post-config tasks to include in this template:',
605
+ loop: false,
606
+ theme: {
607
+ icon: {
608
+ checked: chalk.green('[x] '),
609
+ unchecked: '[ ] ',
610
+ }
611
+ },
612
+ choices
613
+ });
614
+ selectedTaskNames = response.selected || [];
615
+ }
616
+ if (selectedTaskNames.length > 0) {
617
+ if (!templateConfig.post_config)
618
+ templateConfig.post_config = [];
619
+ for (const t of defaultApplicableTasks) {
620
+ const cmd = t.command || t.script || '';
621
+ if (selectedTaskNames.includes(cmd)) {
622
+ const alreadyExists = templateConfig.post_config.some(existing => existing.command === t.command && existing.script === t.script);
623
+ if (!alreadyExists) {
624
+ templateConfig.post_config.push(t);
625
+ }
626
+ }
627
+ }
628
+ }
629
+ }
630
+ // 3. Detect executables at root
631
+ const detectedExecutables = [];
632
+ for (const file of rootFiles) {
633
+ const fullPath = path.join(resolvedPath, file);
634
+ if (isExecutable(fullPath, file)) {
635
+ detectedExecutables.push(file);
636
+ }
637
+ }
638
+ const existingPostCopy = config.templates[templateName].post_copy || [];
639
+ let post_copy = [...existingPostCopy];
640
+ if (fileTemplateConfig.post_copy && Array.isArray(fileTemplateConfig.post_copy)) {
641
+ for (const pc of fileTemplateConfig.post_copy) {
642
+ if (!post_copy.some(existing => existing.src === pc.src)) {
643
+ post_copy.push(pc);
644
+ }
645
+ }
646
+ }
647
+ const newExecutables = detectedExecutables.filter(file => !post_copy.some(existing => existing.src === file));
648
+ if (newExecutables.length > 0) {
649
+ if (!options.json) {
650
+ console.log(chalk.cyan("\nAuto-detected " + newExecutables.length + " new executable file(s) at root:"));
651
+ for (const file of newExecutables) {
652
+ console.log(chalk.gray(" - " + file));
653
+ }
654
+ }
655
+ let addPostCopy = true;
656
+ if (!options.yes && !options.json) {
657
+ const response = await inquirer.prompt({
658
+ type: 'confirm',
659
+ name: 'addPostCopy',
660
+ message: 'Add these to post_copy (auto-chmod)?',
661
+ default: true
662
+ });
663
+ addPostCopy = response.addPostCopy;
664
+ }
665
+ if (addPostCopy) {
666
+ for (const file of newExecutables) {
667
+ post_copy.push({ src: file, dest: file });
668
+ }
669
+ }
670
+ }
671
+ if (post_copy.length > 0) {
672
+ templateConfig.post_copy = post_copy;
673
+ const postCopySrcs = post_copy.map(f => f.src);
674
+ templateConfig.copy_files = templateConfig.copy_files?.filter(cf => !postCopySrcs.includes(cf.src));
675
+ }
676
+ if (options.json) {
677
+ const output = {
678
+ name: templateName,
679
+ ...templateConfig
680
+ };
681
+ // Force the application to wait until every single byte of this JSON string
682
+ // safely clears the operating system's pipe buffer before letting the process die.
683
+ process.stdout.write(JSON.stringify(output, null, 2) + '\n', () => {
684
+ process.exit(0);
685
+ });
686
+ return;
687
+ }
688
+ config.templates[templateName] = templateConfig;
689
+ saveConfig(config);
690
+ console.log(chalk.green(`\n✓ Template saved as "${templateName}"`));
691
+ }
692
+ function isExecutable(fullPath, fileName) {
693
+ if (shouldExcludeFile(fileName))
694
+ return false;
695
+ const ext = path.extname(fileName).toLowerCase();
696
+ if (['.sh', '.py', '.bash', '.bat', '.cmd'].includes(ext))
697
+ return true;
698
+ if (fileName.toLowerCase() === 'makefile')
699
+ return true;
700
+ try {
701
+ const stat = fs.statSync(fullPath);
702
+ return !!(stat.mode & 0o111);
703
+ }
704
+ catch {
705
+ return false;
706
+ }
707
+ }
708
+ function extractStructure(dirPath, rootPath, ignorePatterns) {
709
+ let nodes = [];
710
+ try {
711
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
712
+ for (const entry of entries) {
713
+ const fullPath = path.join(dirPath, entry.name);
714
+ const relativePath = path.relative(rootPath, fullPath);
715
+ // Only include directories in the structure skeleton
716
+ const isDirectory = entry.isDirectory() || (entry.isSymbolicLink() && fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory());
717
+ if (!isDirectory)
718
+ continue;
719
+ if (shouldIgnore(entry.name, relativePath, ignorePatterns))
720
+ continue;
721
+ if (shouldExclude(dirPath, fullPath))
722
+ continue;
723
+ const children = extractStructure(fullPath, rootPath, ignorePatterns);
724
+ let info = "";
725
+ const gitkeepPath = path.join(fullPath, '.gitkeep.md');
726
+ const infoPath = path.join(fullPath, '.info.md');
727
+ if (fs.existsSync(infoPath))
728
+ info = fs.readFileSync(infoPath, 'utf-8').trim();
729
+ else if (fs.existsSync(gitkeepPath))
730
+ info = fs.readFileSync(gitkeepPath, 'utf-8').trim();
731
+ nodes.push({ name: entry.name, info: info, children: children });
732
+ }
733
+ }
734
+ catch (e) { }
735
+ return nodes;
736
+ }
737
+ /**
738
+ * Scan text files in top-level and 1st-level subdirectories for {{ variable_name }} placeholders.
739
+ */
740
+ function findVariablesInFiles(dirPath, rootPath, ignorePatterns) {
741
+ const variables = new Set();
742
+ const regex = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
743
+ const textExtensions = ['.md', '.txt', '.makerc', '.json', '.yaml', '.yml', '.ini', '.conf', '.config', '.sh', '.py', '.js', '.ts', '.html', '.css', '.makefile'];
744
+ const scan = (currentPath, depth) => {
745
+ if (depth > 1)
746
+ return; // Top level (0) and 1st level subfolders (1)
747
+ try {
748
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
749
+ for (const entry of entries) {
750
+ const fullPath = path.join(currentPath, entry.name);
751
+ const relativePath = path.relative(rootPath, fullPath);
752
+ if (entry.isDirectory()) {
753
+ if (shouldIgnore(entry.name, relativePath, ignorePatterns))
754
+ continue;
755
+ if (shouldExclude(currentPath, fullPath))
756
+ continue;
757
+ scan(fullPath, depth + 1);
758
+ }
759
+ else if (entry.isFile()) {
760
+ const ext = path.extname(entry.name).toLowerCase();
761
+ const isMakefile = entry.name.toLowerCase() === 'makefile';
762
+ if (textExtensions.includes(ext) || isMakefile || ext === '') {
763
+ try {
764
+ const content = fs.readFileSync(fullPath, 'utf-8');
765
+ let match;
766
+ regex.lastIndex = 0;
767
+ while ((match = regex.exec(content)) !== null) {
768
+ variables.add(match[1]);
769
+ }
770
+ }
771
+ catch (e) {
772
+ // Skip files that can't be read or aren't text
773
+ }
774
+ }
775
+ }
776
+ }
777
+ }
778
+ catch (e) {
779
+ // Ignore directory read errors
780
+ }
781
+ };
782
+ scan(dirPath, 0);
783
+ return Array.from(variables);
784
+ }