-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
398 lines (341 loc) · 10.9 KB
/
Copy pathindex.js
File metadata and controls
398 lines (341 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { Command } = require("commander");
const chalk = require("chalk");
const inquirer = require("inquirer");
const cliProgress = require("cli-progress");
// Configuration
let config = {};
try {
config = require("./sync-config.json");
} catch (error) {
console.log(
chalk.yellow("⚠️ No config file found, using default exclusions")
);
config = {
defaultExclusions: [".git", "node_modules", ".DS_Store"],
customExclusions: [],
};
}
const program = new Command();
// CLI Setup
program
.name("folder-sync")
.description("Sync folder structures between source and target directories")
.version("1.0.0")
.argument("<source>", "Source directory path")
.argument("<target>", "Target directory path")
.option("-d, --dry-run", "Preview changes without executing")
.option("-v, --verbose", "Show detailed output")
.option("-a, --auto", "Auto-create all missing folders without prompting")
.action(async (source, target, options) => {
try {
await syncFolders(source, target, options);
} catch (error) {
console.error(chalk.red("❌ Error:"), error.message);
process.exit(1);
}
});
// Main sync function
async function syncFolders(sourcePath, targetPath, options) {
// Validate paths
console.log(chalk.blue("🔍 Validating paths..."));
if (!fs.existsSync(sourcePath)) {
throw new Error(`Source directory does not exist: ${sourcePath}`);
}
if (!fs.existsSync(targetPath)) {
console.log(
chalk.yellow(`⚠️ Target directory does not exist: ${targetPath}`)
);
const { createTarget } = await inquirer.prompt([
{
type: "confirm",
name: "createTarget",
message: "Would you like to create the target directory?",
default: true,
},
]);
if (createTarget) {
if (!options.dryRun) {
fs.mkdirSync(targetPath, { recursive: true });
console.log(chalk.green(`✅ Created target directory: ${targetPath}`));
} else {
console.log(
chalk.blue(`📋 Would create target directory: ${targetPath}`)
);
}
} else {
throw new Error("Cannot proceed without target directory");
}
}
// Get exclusion patterns
const exclusions = [...config.defaultExclusions, ...config.customExclusions];
// Scan directories
console.log(chalk.blue("📁 Scanning source directory..."));
const sourceFolders = await scanDirectory(sourcePath, exclusions);
console.log(chalk.blue("📁 Scanning target directory..."));
const targetFolders = await scanDirectory(targetPath, exclusions);
// Find missing folders
const missingFolders = findMissingFolders(
sourceFolders,
targetFolders,
sourcePath,
targetPath
);
if (missingFolders.length === 0) {
console.log(chalk.green("✅ All folders are already synchronized!"));
return;
}
// Display missing folders
console.log(
chalk.yellow(
`\n📂 Found ${missingFolders.length} missing folders in target:`
)
);
missingFolders.forEach((folder, index) => {
const depth = folder.relativePath.split(path.sep).length - 1;
const indent = " ".repeat(depth);
const color = getColorForDepth(depth);
console.log(chalk[color](`${indent}[${index + 1}] ${folder.relativePath}`));
});
let selectedFolders = [];
if (options.auto) {
selectedFolders = missingFolders;
console.log(
chalk.blue("\n🚀 Auto mode: All missing folders will be created")
);
} else {
// Interactive selection
selectedFolders = await selectFolders(missingFolders);
}
if (selectedFolders.length === 0) {
console.log(chalk.yellow("👋 No folders selected. Exiting..."));
return;
}
// Handle dependencies (auto-select parent folders)
const finalSelection = handleDependencies(selectedFolders, missingFolders);
// Show final confirmation
if (!options.auto) {
console.log(chalk.cyan("\n📋 Folders to be created:"));
finalSelection.forEach((folder, index) => {
const fullPath = path.join(targetPath, folder.relativePath);
console.log(chalk.white(` ${index + 1}. ${fullPath}`));
});
const { confirm } = await inquirer.prompt([
{
type: "confirm",
name: "confirm",
message: `Create ${finalSelection.length} folder(s)?`,
default: true,
},
]);
if (!confirm) {
console.log(chalk.yellow("👋 Operation cancelled."));
return;
}
}
// Create folders
await createFolders(finalSelection, targetPath, options);
// Summary
console.log(
chalk.green(`\n🎉 Successfully processed ${finalSelection.length} folders!`)
);
if (options.dryRun) {
console.log(
chalk.blue("📋 This was a dry run - no actual changes were made.")
);
}
}
// Scan directory for folders
async function scanDirectory(dirPath, exclusions) {
const folders = [];
function scanRecursively(currentPath, relativePath = "") {
try {
const items = fs.readdirSync(currentPath);
for (const item of items) {
const itemPath = path.join(currentPath, item);
const itemRelativePath = path.join(relativePath, item);
// Skip excluded patterns
if (
exclusions.some((pattern) => {
if (pattern.includes("*")) {
const regex = new RegExp(pattern.replace(/\*/g, ".*"));
return regex.test(item);
}
return item === pattern || itemRelativePath.includes(pattern);
})
) {
continue;
}
const stats = fs.statSync(itemPath);
if (stats.isDirectory()) {
folders.push({
name: item,
fullPath: itemPath,
relativePath: itemRelativePath,
});
// Recursively scan subdirectories
scanRecursively(itemPath, itemRelativePath);
}
}
} catch (error) {
console.warn(
chalk.yellow(
`⚠️ Warning: Could not scan ${currentPath}: ${error.message}`
)
);
}
}
scanRecursively(dirPath);
return folders;
}
// Find missing folders
function findMissingFolders(
sourceFolders,
targetFolders,
sourcePath,
targetPath
) {
const targetRelativePaths = new Set(targetFolders.map((f) => f.relativePath));
return sourceFolders.filter((sourceFolder) => {
return !targetRelativePaths.has(sourceFolder.relativePath);
});
}
// Interactive folder selection
async function selectFolders(missingFolders) {
console.log(chalk.cyan("\n🎯 Select folders to create:"));
console.log(
chalk.gray(
" Use arrow keys to navigate, space to toggle, enter to confirm"
)
);
const choices = missingFolders.map((folder, index) => {
const depth = folder.relativePath.split(path.sep).length - 1;
const indent = " ".repeat(depth);
return {
name: `${indent}${folder.relativePath}`,
value: folder,
checked: true,
};
});
const { selectedFolders } = await inquirer.prompt([
{
type: "checkbox",
name: "selectedFolders",
message: "Select folders to create:",
choices: choices,
pageSize: 15,
},
]);
// Also allow manual number input
if (selectedFolders.length === 0) {
const { manualSelection } = await inquirer.prompt([
{
type: "input",
name: "manualSelection",
message: "Or enter folder numbers separated by commas (e.g., 1,3,5):",
validate: (input) => {
if (!input.trim()) return true; // Allow empty for no selection
const numbers = input.split(",").map((n) => parseInt(n.trim()));
const invalid = numbers.some(
(n) => isNaN(n) || n < 1 || n > missingFolders.length
);
return invalid
? `Please enter valid numbers between 1 and ${missingFolders.length}`
: true;
},
},
]);
if (manualSelection.trim()) {
const indices = manualSelection
.split(",")
.map((n) => parseInt(n.trim()) - 1);
return indices.map((i) => missingFolders[i]);
}
}
return selectedFolders;
}
// Handle dependencies (ensure parent folders are included)
function handleDependencies(selectedFolders, allMissingFolders) {
const selectedPaths = new Set(selectedFolders.map((f) => f.relativePath));
const result = [...selectedFolders];
// For each selected folder, ensure all parent folders are included
selectedFolders.forEach((folder) => {
const pathParts = folder.relativePath.split(path.sep);
// Check each parent path
for (let i = 1; i < pathParts.length; i++) {
const parentPath = pathParts.slice(0, i).join(path.sep);
if (!selectedPaths.has(parentPath)) {
// Find the parent folder in missing folders
const parentFolder = allMissingFolders.find(
(f) => f.relativePath === parentPath
);
if (parentFolder) {
result.push(parentFolder);
selectedPaths.add(parentPath);
}
}
}
});
// Sort by path depth to create parent folders first
return result.sort((a, b) => {
const depthA = a.relativePath.split(path.sep).length;
const depthB = b.relativePath.split(path.sep).length;
return depthA - depthB;
});
}
// Create folders with progress
async function createFolders(folders, targetPath, options) {
if (options.dryRun) {
console.log(chalk.blue("\n📋 Dry run - folders that would be created:"));
folders.forEach((folder, index) => {
const fullPath = path.join(targetPath, folder.relativePath);
console.log(chalk.white(` ${index + 1}. ${fullPath}`));
});
return;
}
console.log(chalk.blue("\n🚀 Creating folders..."));
const progressBar = new cliProgress.SingleBar({
format:
"Progress |" +
chalk.cyan("{bar}") +
"| {percentage}% | {value}/{total} folders | {folder}",
barCompleteChar: "\u2588",
barIncompleteChar: "\u2591",
hideCursor: true,
});
progressBar.start(folders.length, 0, { folder: "" });
let created = 0;
let errors = 0;
for (let i = 0; i < folders.length; i++) {
const folder = folders[i];
const fullPath = path.join(targetPath, folder.relativePath);
progressBar.update(i + 1, { folder: folder.relativePath });
try {
fs.mkdirSync(fullPath, { recursive: true });
created++;
if (options.verbose) {
console.log(`\n${chalk.green("✅")} Created: ${fullPath}`);
}
} catch (error) {
errors++;
console.log(
`\n${chalk.red("❌")} Error creating ${fullPath}: ${error.message}`
);
}
// Small delay for visual effect
await new Promise((resolve) => setTimeout(resolve, 50));
}
progressBar.stop();
console.log(
chalk.green(`\n📊 Summary: ${created} created, ${errors} errors`)
);
}
// Get color based on folder depth
function getColorForDepth(depth) {
const colors = ["cyan", "yellow", "green", "magenta", "blue", "white"];
return colors[depth % colors.length];
}
// Parse command line arguments
program.parse();