@garyr/pt-cli 0.39.1 → 0.40.1

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,785 @@
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 copy_files entries as the base (preserves all settings including substitute_variables)
367
+ const existingCopyFiles = config.templates[templateName].copy_files || [];
368
+ // selectedFiles here is only used to track new file names to append
369
+ let newSelectedFiles = [];
370
+ let newSelectedFolderDirs = [];
371
+ const fileDiff = getNewFiles(config.templates[templateName], resolvedPath);
372
+ if (fileDiff.newFiles.length > 0) {
373
+ console.log(chalk.cyan(`\n📊 New Files:`));
374
+ console.log(chalk.green(` + ${fileDiff.newFiles.length} new file(s): ${fileDiff.newFiles.join(', ')}`));
375
+ // Show interactive checkbox for new files
376
+ if (!options.yes && !options.json) {
377
+ const { selectedFileChoices } = await inquirer.prompt({
378
+ type: 'checkbox',
379
+ name: 'selectedFileChoices',
380
+ message: 'Select files to include (space to toggle):',
381
+ loop: false,
382
+ theme: {
383
+ icon: {
384
+ checked: chalk.green('[x] '),
385
+ unchecked: '[ ] ',
386
+ }
387
+ },
388
+ choices: fileDiff.newFiles.map(f => ({
389
+ name: f,
390
+ checked: true // Auto-select by default
391
+ }))
392
+ });
393
+ newSelectedFiles = fileDiff.newFiles.filter(f => selectedFileChoices.includes(f));
394
+ }
395
+ else {
396
+ // In --yes or --json mode, auto-add all
397
+ newSelectedFiles = [...fileDiff.newFiles];
398
+ }
399
+ }
400
+ else {
401
+ console.log(chalk.cyan("No new files detected"));
402
+ }
403
+ // For folders, use additive mode logic
404
+ // Preserve existing folder structure
405
+ selectedStructure = config.templates[templateName].folders?.map(f => f.name) || [];
406
+ // Seed selectedFolders from existing copy_files directory entries (not a hardcoded list)
407
+ selectedFolders = existingCopyFiles
408
+ .filter(f => rootDirs.includes(f.src))
409
+ .map(f => f.src);
410
+ if (rootDirs.length > 0) {
411
+ const structureDiff = getNewFolders(config.templates[templateName].folders, resolvedPath, ignorePatterns);
412
+ if (structureDiff.added.length > 0) {
413
+ // Auto-select added folders for structure
414
+ selectedStructure = [...new Set([...selectedStructure, ...structureDiff.added.map(f => f.name)])];
415
+ // For new dirs, auto-select for recursive copy if they match the standard list
416
+ newSelectedFolderDirs = structureDiff.added
417
+ .filter(f => ['APP', 'scripts', 'bin'].some(p => f.name === p))
418
+ .map(f => f.name);
419
+ }
420
+ }
421
+ // Merge: existing folder copy_files + newly selected dirs
422
+ selectedFolders = [...new Set([...selectedFolders, ...newSelectedFolderDirs])];
423
+ // Also carry forward file names for use in copy_files construction below
424
+ selectedFiles = [...existingCopyFiles.filter(f => !rootDirs.includes(f.src)).map(f => f.src), ...newSelectedFiles];
425
+ }
426
+ else {
427
+ // Full mode: original behavior
428
+ if (options.yes || options.json) {
429
+ // If --yes, auto-select the defaults
430
+ selectedFiles = rootFiles.filter(f => ['.makerc', 'readme.md', 'README.md', '.gitattributes', '.gitignore', 'Makefile', 'makefile', 'package.json'].some(p => f.toLowerCase() === p.toLowerCase()));
431
+ selectedStructure = rootDirs; // Include all folders in structure
432
+ selectedFolders = rootDirs.filter(d => ['APP', 'scripts', 'bin'].some(p => d === p)); // Only copy specific ones recursively
433
+ }
434
+ else {
435
+ if (rootFiles.length > 0) {
436
+ const filesResponse = await inquirer.prompt({
437
+ type: 'checkbox',
438
+ name: 'selectedFiles',
439
+ message: 'Select root files to include as boilerplate:',
440
+ loop: false,
441
+ theme: {
442
+ icon: {
443
+ checked: chalk.green('[x] '),
444
+ unchecked: '[ ] ',
445
+ }
446
+ },
447
+ choices: rootFiles.map(f => ({
448
+ name: f,
449
+ checked: ['.makerc', 'readme.md', 'README.md', '.gitattributes', '.gitignore', 'Makefile', 'makefile', 'package.json'].some(p => f.toLowerCase() === p.toLowerCase())
450
+ }))
451
+ });
452
+ selectedFiles = filesResponse.selectedFiles;
453
+ }
454
+ else {
455
+ selectedFiles = [];
456
+ }
457
+ if (rootDirs.length > 0) {
458
+ const foldersResponse = await inquirer.prompt({
459
+ type: 'checkbox',
460
+ name: 'selectedStructure',
461
+ message: 'Select folders to include in the template structure (skeleton):',
462
+ loop: false,
463
+ theme: {
464
+ icon: {
465
+ checked: chalk.green('[x] '),
466
+ unchecked: '[ ] ',
467
+ }
468
+ },
469
+ choices: rootDirs.map(d => ({
470
+ name: d,
471
+ checked: true // Include all in structure by default
472
+ }))
473
+ });
474
+ selectedStructure = foldersResponse.selectedStructure;
475
+ }
476
+ else {
477
+ selectedStructure = [];
478
+ }
479
+ if (selectedStructure.length > 0) {
480
+ const copyFoldersResponse = await inquirer.prompt({
481
+ type: 'checkbox',
482
+ name: 'selectedFolders',
483
+ message: 'Select folders to copy RECURSIVELY as boilerplate (with contents):',
484
+ loop: false,
485
+ theme: {
486
+ icon: {
487
+ checked: chalk.green('[x] '),
488
+ unchecked: '[ ] ',
489
+ }
490
+ },
491
+ choices: selectedStructure.map((d) => ({
492
+ name: d,
493
+ checked: ['APP', 'scripts', 'bin'].some(p => d === p)
494
+ }))
495
+ });
496
+ selectedFolders = copyFoldersResponse.selectedFolders;
497
+ }
498
+ else {
499
+ selectedFolders = [];
500
+ }
501
+ }
502
+ }
503
+ const copy_files = [];
504
+ if (fileTemplateConfig.copy_files && Array.isArray(fileTemplateConfig.copy_files)) {
505
+ copy_files.push(...fileTemplateConfig.copy_files);
506
+ }
507
+ else if (!isFullMode) {
508
+ // Additive mode: start directly from the existing copy_files to preserve all settings,
509
+ // then append only brand-new entries (never rebuild from scratch).
510
+ const existingCopyFiles = config.templates[templateName].copy_files || [];
511
+ const existingSrcs = new Set(existingCopyFiles.map(e => e.src));
512
+ // Begin with all existing entries untouched
513
+ copy_files.push(...existingCopyFiles);
514
+ // Append new files that were selected by the user
515
+ for (const f of selectedFiles) {
516
+ if (existingSrcs.has(f))
517
+ continue; // already present, skip
518
+ copy_files.push({ src: f, dest: f, substitute_variables: true });
519
+ }
520
+ // Append new directory entries that were selected
521
+ for (const d of selectedFolders) {
522
+ if (existingSrcs.has(d))
523
+ continue; // already present, skip
524
+ copy_files.push({ src: d, dest: d, substitute_variables: true });
525
+ }
526
+ }
527
+ else {
528
+ // Full mode: build from scratch using the selected files/folders
529
+ for (const f of selectedFiles) {
530
+ copy_files.push({ src: f, dest: f, substitute_variables: true });
531
+ }
532
+ for (const d of selectedFolders) {
533
+ copy_files.push({ src: d, dest: d, substitute_variables: true });
534
+ }
535
+ }
536
+ const templateConfig = {
537
+ description: description,
538
+ templateRoot: templateRoot,
539
+ folders: fileTemplateConfig.folders ? folders : folders.filter(f => selectedStructure.includes(f.name)),
540
+ copy_files: copy_files,
541
+ variables: variables.length > 0 ? variables : undefined
542
+ };
543
+ // Check for post_config scripts
544
+ let postConfigTasks = [];
545
+ if (fileTemplateConfig.post_config && Array.isArray(fileTemplateConfig.post_config)) {
546
+ postConfigTasks = [...fileTemplateConfig.post_config];
547
+ }
548
+ else {
549
+ const shPath = path.join(resolvedPath, 'post_config.sh');
550
+ const batPath = path.join(resolvedPath, 'post_config.bat');
551
+ if (fs.existsSync(shPath)) {
552
+ const lines = fs.readFileSync(shPath, 'utf-8').split('\n');
553
+ let currentDesc = '';
554
+ for (const line of lines) {
555
+ if (line.startsWith('echo "Running: ')) {
556
+ currentDesc = line.substring(15, line.length - 1).replace(/"$/, '');
557
+ }
558
+ else if (line.trim() && !line.startsWith('#') && !line.startsWith('echo ')) {
559
+ postConfigTasks.push({ command: line.trim(), description: currentDesc || line.trim() });
560
+ currentDesc = '';
561
+ }
562
+ }
563
+ }
564
+ else if (fs.existsSync(batPath)) {
565
+ const lines = fs.readFileSync(batPath, 'utf-8').split('\n');
566
+ let currentDesc = '';
567
+ for (const line of lines) {
568
+ if (line.startsWith('echo Running: ')) {
569
+ currentDesc = line.substring(14).trim();
570
+ }
571
+ else if (line.trim() && !line.startsWith('::') && !line.startsWith('@echo') && !line.startsWith('echo ')) {
572
+ postConfigTasks.push({ command: line.trim(), description: currentDesc || line.trim() });
573
+ currentDesc = '';
574
+ }
575
+ }
576
+ }
577
+ }
578
+ if (postConfigTasks.length > 0) {
579
+ templateConfig.post_config = postConfigTasks;
580
+ if (!options.json && !fileTemplateConfig.post_config)
581
+ console.log(chalk.cyan(`Auto-detected ${postConfigTasks.length} post_config action(s) from script.`));
582
+ }
583
+ // Handle default_post_config tasks
584
+ const defaultPostConfig = getDefaultPostConfig(config);
585
+ const defaultApplicableTasks = defaultPostConfig.filter(t => !t.type || t.type === templateName);
586
+ if (defaultApplicableTasks.length > 0) {
587
+ let selectedTaskNames = [];
588
+ if (options.yes || options.json) {
589
+ selectedTaskNames = defaultApplicableTasks.map(t => t.command || t.script || '');
590
+ }
591
+ else {
592
+ const choices = [];
593
+ for (const t of defaultApplicableTasks) {
594
+ const cmd = t.command || t.script || '(no command)';
595
+ const desc = t.description ? ` (${t.description})` : '';
596
+ choices.push({
597
+ name: `${cmd}${desc}`,
598
+ value: cmd,
599
+ checked: t.checked !== false
600
+ });
601
+ }
602
+ const response = await inquirer.prompt({
603
+ type: 'checkbox',
604
+ name: 'selected',
605
+ message: 'Select default post-config tasks to include in this template:',
606
+ loop: false,
607
+ theme: {
608
+ icon: {
609
+ checked: chalk.green('[x] '),
610
+ unchecked: '[ ] ',
611
+ }
612
+ },
613
+ choices
614
+ });
615
+ selectedTaskNames = response.selected || [];
616
+ }
617
+ if (selectedTaskNames.length > 0) {
618
+ if (!templateConfig.post_config)
619
+ templateConfig.post_config = [];
620
+ for (const t of defaultApplicableTasks) {
621
+ const cmd = t.command || t.script || '';
622
+ if (selectedTaskNames.includes(cmd)) {
623
+ const alreadyExists = templateConfig.post_config.some(existing => existing.command === t.command && existing.script === t.script);
624
+ if (!alreadyExists) {
625
+ templateConfig.post_config.push(t);
626
+ }
627
+ }
628
+ }
629
+ }
630
+ }
631
+ // 3. Detect executables at root
632
+ const detectedExecutables = [];
633
+ for (const file of rootFiles) {
634
+ const fullPath = path.join(resolvedPath, file);
635
+ if (isExecutable(fullPath, file)) {
636
+ detectedExecutables.push(file);
637
+ }
638
+ }
639
+ const existingPostCopy = config.templates[templateName].post_copy || [];
640
+ let post_copy = [...existingPostCopy];
641
+ if (fileTemplateConfig.post_copy && Array.isArray(fileTemplateConfig.post_copy)) {
642
+ for (const pc of fileTemplateConfig.post_copy) {
643
+ if (!post_copy.some(existing => existing.src === pc.src)) {
644
+ post_copy.push(pc);
645
+ }
646
+ }
647
+ }
648
+ const newExecutables = detectedExecutables.filter(file => !post_copy.some(existing => existing.src === file));
649
+ if (newExecutables.length > 0) {
650
+ if (!options.json) {
651
+ console.log(chalk.cyan("\nAuto-detected " + newExecutables.length + " new executable file(s) at root:"));
652
+ for (const file of newExecutables) {
653
+ console.log(chalk.gray(" - " + file));
654
+ }
655
+ }
656
+ let addPostCopy = true;
657
+ if (!options.yes && !options.json) {
658
+ const response = await inquirer.prompt({
659
+ type: 'confirm',
660
+ name: 'addPostCopy',
661
+ message: 'Add these to post_copy (auto-chmod)?',
662
+ default: true
663
+ });
664
+ addPostCopy = response.addPostCopy;
665
+ }
666
+ if (addPostCopy) {
667
+ for (const file of newExecutables) {
668
+ post_copy.push({ src: file, dest: file });
669
+ }
670
+ }
671
+ }
672
+ if (post_copy.length > 0) {
673
+ templateConfig.post_copy = post_copy;
674
+ const postCopySrcs = post_copy.map(f => f.src);
675
+ templateConfig.copy_files = templateConfig.copy_files?.filter(cf => !postCopySrcs.includes(cf.src));
676
+ }
677
+ if (options.json) {
678
+ const output = {
679
+ name: templateName,
680
+ ...templateConfig
681
+ };
682
+ // Force the application to wait until every single byte of this JSON string
683
+ // safely clears the operating system's pipe buffer before letting the process die.
684
+ process.stdout.write(JSON.stringify(output, null, 2) + '\n', () => {
685
+ process.exit(0);
686
+ });
687
+ return;
688
+ }
689
+ config.templates[templateName] = templateConfig;
690
+ saveConfig(config);
691
+ console.log(chalk.green(`\n✓ Template saved as "${templateName}"`));
692
+ }
693
+ function isExecutable(fullPath, fileName) {
694
+ if (shouldExcludeFile(fileName))
695
+ return false;
696
+ const ext = path.extname(fileName).toLowerCase();
697
+ if (['.sh', '.py', '.bash', '.bat', '.cmd'].includes(ext))
698
+ return true;
699
+ if (fileName.toLowerCase() === 'makefile')
700
+ return true;
701
+ try {
702
+ const stat = fs.statSync(fullPath);
703
+ return !!(stat.mode & 0o111);
704
+ }
705
+ catch {
706
+ return false;
707
+ }
708
+ }
709
+ function extractStructure(dirPath, rootPath, ignorePatterns) {
710
+ let nodes = [];
711
+ try {
712
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
713
+ for (const entry of entries) {
714
+ const fullPath = path.join(dirPath, entry.name);
715
+ const relativePath = path.relative(rootPath, fullPath);
716
+ // Only include directories in the structure skeleton
717
+ const isDirectory = entry.isDirectory() || (entry.isSymbolicLink() && fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory());
718
+ if (!isDirectory)
719
+ continue;
720
+ if (shouldIgnore(entry.name, relativePath, ignorePatterns))
721
+ continue;
722
+ if (shouldExclude(dirPath, fullPath))
723
+ continue;
724
+ const children = extractStructure(fullPath, rootPath, ignorePatterns);
725
+ let info = "";
726
+ const gitkeepPath = path.join(fullPath, '.gitkeep.md');
727
+ const infoPath = path.join(fullPath, '.info.md');
728
+ if (fs.existsSync(infoPath))
729
+ info = fs.readFileSync(infoPath, 'utf-8').trim();
730
+ else if (fs.existsSync(gitkeepPath))
731
+ info = fs.readFileSync(gitkeepPath, 'utf-8').trim();
732
+ nodes.push({ name: entry.name, info: info, children: children });
733
+ }
734
+ }
735
+ catch (e) { }
736
+ return nodes;
737
+ }
738
+ /**
739
+ * Scan text files in top-level and 1st-level subdirectories for {{ variable_name }} placeholders.
740
+ */
741
+ function findVariablesInFiles(dirPath, rootPath, ignorePatterns) {
742
+ const variables = new Set();
743
+ const regex = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
744
+ const textExtensions = ['.md', '.txt', '.makerc', '.json', '.yaml', '.yml', '.ini', '.conf', '.config', '.sh', '.py', '.js', '.ts', '.html', '.css', '.makefile'];
745
+ const scan = (currentPath, depth) => {
746
+ if (depth > 1)
747
+ return; // Top level (0) and 1st level subfolders (1)
748
+ try {
749
+ const entries = fs.readdirSync(currentPath, { withFileTypes: true });
750
+ for (const entry of entries) {
751
+ const fullPath = path.join(currentPath, entry.name);
752
+ const relativePath = path.relative(rootPath, fullPath);
753
+ if (entry.isDirectory()) {
754
+ if (shouldIgnore(entry.name, relativePath, ignorePatterns))
755
+ continue;
756
+ if (shouldExclude(currentPath, fullPath))
757
+ continue;
758
+ scan(fullPath, depth + 1);
759
+ }
760
+ else if (entry.isFile()) {
761
+ const ext = path.extname(entry.name).toLowerCase();
762
+ const isMakefile = entry.name.toLowerCase() === 'makefile';
763
+ if (textExtensions.includes(ext) || isMakefile || ext === '') {
764
+ try {
765
+ const content = fs.readFileSync(fullPath, 'utf-8');
766
+ let match;
767
+ regex.lastIndex = 0;
768
+ while ((match = regex.exec(content)) !== null) {
769
+ variables.add(match[1]);
770
+ }
771
+ }
772
+ catch (e) {
773
+ // Skip files that can't be read or aren't text
774
+ }
775
+ }
776
+ }
777
+ }
778
+ }
779
+ catch (e) {
780
+ // Ignore directory read errors
781
+ }
782
+ };
783
+ scan(dirPath, 0);
784
+ return Array.from(variables);
785
+ }