-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
639 lines (555 loc) · 25.7 KB
/
Program.cs
File metadata and controls
639 lines (555 loc) · 25.7 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
using McMaster.Extensions.CommandLineUtils;
using Figgle;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Runtime.InteropServices;
namespace solrevdev.seedfolder;
// Template metadata structure for future extensibility
internal record TemplateFile(string ResourceName, string FileName, string Description = "");
// Enum for supported project types
internal enum ProjectType
{
Dotnet,
Node,
Python,
Ruby,
Markdown,
Universal
}
internal static class Program
{
public static async Task<int> Main(string[] args)
{
var folderName = "";
var projectType = ProjectType.Markdown; // Default to markdown
var templateExplicitlySpecified = false;
var isDryRun = false;
var isForce = false;
var isQuiet = false;
if (args?.Length > 0)
{
var argIndex = 0;
while (argIndex < args.Length)
{
var arg = args[argIndex].ToLower(CultureInfo.InvariantCulture);
// Handle flags
if (arg is "--help" or "-h" or "-?")
{
ShowHelp();
return 0;
}
if (arg is "--version" or "-v")
{
ShowVersion();
return 0;
}
if (arg is "--list-templates" or "--list")
{
ShowTemplates();
return 0;
}
if (arg is "--dry-run" or "--dry")
{
isDryRun = true;
argIndex++;
continue;
}
if (arg is "--force" or "-f")
{
isForce = true;
argIndex++;
continue;
}
if (arg is "--quiet" or "-q")
{
isQuiet = true;
argIndex++;
continue;
}
if (arg is "--template" or "--type" or "-t")
{
templateExplicitlySpecified = true;
if (argIndex + 1 >= args.Length)
{
WriteLine("▲ Error: --template requires a template type.", ConsoleColor.DarkRed);
WriteLine("▲ Available types: dotnet, node, python, ruby, markdown, universal", ConsoleColor.DarkYellow);
return 1;
}
var templateArg = args[argIndex + 1].ToLower(CultureInfo.InvariantCulture);
if (!TryParseProjectType(templateArg, out projectType))
{
WriteLine($"▲ Error: Unknown template type '{args[argIndex + 1]}'.", ConsoleColor.DarkRed);
WriteLine("▲ Available template types:", ConsoleColor.DarkYellow);
WriteLine(" dotnet - .NET project with standard dotfiles", ConsoleColor.DarkYellow);
WriteLine(" node - Node.js project with package.json", ConsoleColor.DarkYellow);
WriteLine(" python - Python project with requirements.txt", ConsoleColor.DarkYellow);
WriteLine(" ruby - Ruby project with Gemfile", ConsoleColor.DarkYellow);
WriteLine(" markdown - Documentation project with README", ConsoleColor.DarkYellow);
WriteLine(" universal - Basic project with minimal files", ConsoleColor.DarkYellow);
WriteLine("▲ Use --list-templates to see all available templates and their files.", ConsoleColor.Cyan);
return 1;
}
argIndex += 2;
// Get folder name if provided
if (argIndex < args.Length)
{
folderName = args[argIndex];
argIndex++;
}
if (!isQuiet)
WriteLine($"▲ Using template type: {projectType}");
break;
}
else
{
// This is the folder name
folderName = args[argIndex];
argIndex++;
break;
}
}
}
if (!isQuiet)
{
ShowHeader();
WriteLine($"▲ Running in the path {Directory.GetCurrentDirectory()}");
}
var sb = new StringBuilder();
if (string.IsNullOrWhiteSpace(folderName))
{
// Interactive template selection - only prompt if no template was explicitly specified
if (!templateExplicitlySpecified)
{
if (!isQuiet)
{
WriteLine("▲ Available project templates:");
WriteLine(" 1. markdown - Documentation project with README");
WriteLine(" 2. dotnet - .NET project with standard dotfiles");
WriteLine(" 3. node - Node.js project with package.json");
WriteLine(" 4. python - Python project with requirements.txt");
WriteLine(" 5. ruby - Ruby project with Gemfile");
WriteLine(" 6. universal - Basic project with minimal files");
WriteLine("");
}
var templateChoice = Prompt.GetString("▲ Select template type (1-6) or press Enter for markdown", "1");
projectType = templateChoice switch
{
"2" or "dotnet" => ProjectType.Dotnet,
"3" or "node" => ProjectType.Node,
"4" or "python" => ProjectType.Python,
"5" or "ruby" => ProjectType.Ruby,
"6" or "universal" => ProjectType.Universal,
_ => ProjectType.Markdown
};
if (!isQuiet)
WriteLine($"▲ Selected template: {projectType}");
}
var prefixWithDate = Prompt.GetYesNo("▲ Do you want to prefix the folder with the date?", defaultAnswer: true);
if (prefixWithDate)
{
sb.Append(DateTime.Now.Year).Append('-').AppendFormat("{0:d2}", DateTime.Now.Month).Append('-').AppendFormat("{0:d2}", DateTime.Now.Day);
sb.Append('_');
}
folderName = Prompt.GetString("▲ What do you want the folder to be named?");
}
// Validate and sanitize folder name
if (string.IsNullOrWhiteSpace(folderName))
{
WriteLine("▲ Error: You must enter a folder name.", ConsoleColor.DarkRed);
return 1;
}
folderName = RemoveSpaces(folderName);
folderName = SafeNameForFileSystem(folderName);
if (string.IsNullOrWhiteSpace(folderName))
{
WriteLine("▲ Error: Folder name contains only invalid characters.", ConsoleColor.DarkRed);
return 1;
}
sb.Append(folderName);
var finalFolderName = sb.ToString();
// Check if directory already exists
if (Directory.Exists(finalFolderName))
{
if (!isForce)
{
WriteLine($"▲ Error: Directory '{finalFolderName}' already exists.", ConsoleColor.DarkRed);
WriteLine("▲ Use --force to overwrite existing directory.", ConsoleColor.DarkYellow);
return 1;
}
else if (!isQuiet)
{
WriteLine($"▲ Warning: Directory '{finalFolderName}' exists, will overwrite files.", ConsoleColor.DarkYellow);
}
}
// Define template files based on project type
var templateFiles = GetTemplateFiles(projectType);
if (isDryRun)
{
WriteLine($"▲ DRY RUN: Would create directory '{finalFolderName}' with template '{projectType}'", ConsoleColor.Cyan);
WriteLine("▲ Files that would be created:", ConsoleColor.Cyan);
foreach (var templateFile in templateFiles)
{
var destinationPath = Path.Combine(finalFolderName, templateFile.FileName);
WriteLine($" • {destinationPath}", ConsoleColor.Cyan);
}
WriteLine("▲ Use without --dry-run to actually create the files.", ConsoleColor.Cyan);
return 0;
}
// Create directory with enhanced error handling
if (!isQuiet)
WriteLine($"▲ Creating the directory {finalFolderName}");
try
{
Directory.CreateDirectory(finalFolderName);
}
catch (UnauthorizedAccessException)
{
WriteLine($"▲ Error: Permission denied creating directory '{finalFolderName}'.", ConsoleColor.DarkRed);
WriteLine("▲ Please check that you have write permissions to this location.", ConsoleColor.DarkYellow);
return 1;
}
catch (DirectoryNotFoundException)
{
WriteLine($"▲ Error: Parent directory path not found for '{finalFolderName}'.", ConsoleColor.DarkRed);
WriteLine("▲ Please ensure the parent directory exists.", ConsoleColor.DarkYellow);
return 1;
}
catch (PathTooLongException)
{
WriteLine($"▲ Error: Directory path is too long: '{finalFolderName}'.", ConsoleColor.DarkRed);
WriteLine("▲ Please use a shorter folder name or path.", ConsoleColor.DarkYellow);
return 1;
}
catch (Exception ex)
{
WriteLine($"▲ Error creating directory: {ex.Message}", ConsoleColor.DarkRed);
WriteLine("▲ Please check your permissions and try again.", ConsoleColor.DarkYellow);
return 1;
}
// Validate disk space before creating files
if (!ValidateDiskSpace(finalFolderName))
{
WriteLine("▲ Error: Insufficient disk space to create project files.", ConsoleColor.DarkRed);
WriteLine("▲ Please free up disk space and try again.", ConsoleColor.DarkYellow);
return 1;
}
// Copy template files using cross-platform path handling with progress indicators
var fileCount = templateFiles.Length;
for (int i = 0; i < fileCount; i++)
{
var templateFile = templateFiles[i];
var destinationPath = Path.Combine(finalFolderName, templateFile.FileName);
if (!isQuiet)
{
var progress = $"[{i + 1}/{fileCount}]";
WriteLine($"▲ {progress} Copying {templateFile.FileName}");
}
try
{
await WriteFileAsync(templateFile.ResourceName, destinationPath).ConfigureAwait(false);
if (!isQuiet)
WriteLine($" ✅ Created {destinationPath}", ConsoleColor.DarkGreen);
}
catch (UnauthorizedAccessException)
{
WriteLine($"▲ Error: Permission denied writing {templateFile.FileName}.", ConsoleColor.DarkRed);
WriteLine($"▲ Please check write permissions for '{destinationPath}'.", ConsoleColor.DarkYellow);
WriteLine($"▲ Failed at file {i + 1} of {fileCount}. Some files may have been created.", ConsoleColor.DarkYellow);
return 1;
}
catch (DirectoryNotFoundException)
{
WriteLine($"▲ Error: Directory not found for {templateFile.FileName}.", ConsoleColor.DarkRed);
WriteLine($"▲ The directory may have been deleted during operation.", ConsoleColor.DarkYellow);
WriteLine($"▲ Failed at file {i + 1} of {fileCount}. Some files may have been created.", ConsoleColor.DarkYellow);
return 1;
}
catch (IOException ioEx)
{
WriteLine($"▲ Error: I/O error writing {templateFile.FileName}: {ioEx.Message}", ConsoleColor.DarkRed);
WriteLine($"▲ This could be due to disk space, file locks, or permission issues.", ConsoleColor.DarkYellow);
WriteLine($"▲ Failed at file {i + 1} of {fileCount}. Some files may have been created.", ConsoleColor.DarkYellow);
return 1;
}
catch (Exception ex)
{
WriteLine($"▲ Error copying {templateFile.FileName}: {ex.Message}", ConsoleColor.DarkRed);
WriteLine($"▲ Failed at file {i + 1} of {fileCount}. Some files may have been created.", ConsoleColor.DarkYellow);
return 1;
}
}
if (!isQuiet)
{
WriteLine("▲ Done!", ConsoleColor.DarkGreen);
WriteLine($"▲ Successfully created {fileCount} files in '{finalFolderName}' using {projectType} template.", ConsoleColor.DarkGreen);
WriteLine("");
ShowGitSetupInstructions(finalFolderName);
}
return 0;
}
private static bool TryParseProjectType(string input, out ProjectType projectType)
{
projectType = input switch
{
"dotnet" or "net" or "csharp" => ProjectType.Dotnet,
"node" or "nodejs" or "javascript" or "js" => ProjectType.Node,
"python" or "py" => ProjectType.Python,
"ruby" or "rb" => ProjectType.Ruby,
"markdown" or "md" or "docs" => ProjectType.Markdown,
"universal" or "basic" or "minimal" => ProjectType.Universal,
_ => ProjectType.Dotnet
};
return input is "dotnet" or "net" or "csharp" or "node" or "nodejs" or "javascript" or "js"
or "python" or "py" or "ruby" or "rb" or "markdown" or "md" or "docs"
or "universal" or "basic" or "minimal";
}
private static TemplateFile[] GetTemplateFiles(ProjectType projectType)
{
return projectType switch
{
ProjectType.Node => GetNodeTemplate(),
ProjectType.Python => GetPythonTemplate(),
ProjectType.Ruby => GetRubyTemplate(),
ProjectType.Markdown => GetMarkdownTemplate(),
ProjectType.Universal => GetUniversalTemplate(),
_ => GetDotnetTemplate()
};
}
private static TemplateFile[] GetDotnetTemplate()
{
return new TemplateFile[]
{
new("dockerignore", ".dockerignore", "Docker ignore patterns"),
new("editorconfig-dotnet", ".editorconfig", "Editor configuration for .NET"),
new("gitattributes", ".gitattributes", "Git attributes"),
new("gitignore", ".gitignore", "Git ignore patterns"),
new("prettierignore", ".prettierignore", "Prettier ignore patterns"),
new("prettierrc", ".prettierrc", "Prettier configuration"),
new("omnisharp.json", "omnisharp.json", "OmniSharp configuration")
};
}
private static TemplateFile[] GetNodeTemplate()
{
return new TemplateFile[]
{
new("package.json", "package.json", "Node.js package configuration"),
new("index.js", "index.js", "Main application entry point"),
new("gitignore-node", ".gitignore", "Node.js specific git ignore patterns"),
new("gitattributes-node", ".gitattributes", "Git attributes for Node.js projects"),
new("editorconfig-node", ".editorconfig", "Editor configuration for Node.js"),
new("prettierignore", ".prettierignore", "Prettier ignore patterns"),
new("prettierrc", ".prettierrc", "Prettier configuration")
};
}
private static TemplateFile[] GetPythonTemplate()
{
return new TemplateFile[]
{
new("main.py", "main.py", "Main application entry point"),
new("requirements.txt", "requirements.txt", "Python dependencies"),
new("gitignore-python", ".gitignore", "Python specific git ignore patterns"),
new("gitattributes-python", ".gitattributes", "Git attributes for Python projects"),
new("editorconfig-python", ".editorconfig", "Editor configuration for Python")
};
}
private static TemplateFile[] GetRubyTemplate()
{
return new TemplateFile[]
{
new("Gemfile", "Gemfile", "Ruby dependencies"),
new("main.rb", "main.rb", "Main application entry point"),
new("gitignore-ruby", ".gitignore", "Ruby specific git ignore patterns"),
new("gitattributes-ruby", ".gitattributes", "Git attributes for Ruby projects"),
new("editorconfig-ruby", ".editorconfig", "Editor configuration for Ruby")
};
}
private static TemplateFile[] GetMarkdownTemplate()
{
return new TemplateFile[]
{
new("README.md", "README.md", "Project documentation"),
new("gitignore-markdown", ".gitignore", "Documentation specific git ignore patterns"),
new("gitattributes-markdown", ".gitattributes", "Git attributes for documentation projects"),
new("editorconfig-markdown", ".editorconfig", "Editor configuration for Markdown")
};
}
private static TemplateFile[] GetUniversalTemplate()
{
return new TemplateFile[]
{
new("README.md", "README.md", "Project documentation"),
new("gitignore", ".gitignore", "Basic git ignore patterns"),
new("gitattributes-universal", ".gitattributes", "Git attributes for universal projects"),
new("editorconfig-universal", ".editorconfig", "Editor configuration for universal projects")
};
}
private static TemplateFile[] GetDefaultTemplate()
{
return GetDotnetTemplate();
}
private static void ShowTemplates()
{
WriteLine("▲ Available project templates:");
WriteLine("");
var templates = new[]
{
("markdown", "Documentation project with README", GetMarkdownTemplate()),
("dotnet", "Dotnet project with standard dotfiles", GetDotnetTemplate()),
("node", "Node.js project with package.json", GetNodeTemplate()),
("python", "Python project with requirements.txt", GetPythonTemplate()),
("ruby", "Ruby project with Gemfile", GetRubyTemplate()),
("universal", "Basic project with minimal files", GetUniversalTemplate())
};
foreach (var (name, description, files) in templates)
{
WriteLine($" {name,-12} - {description}");
foreach (var file in files)
{
WriteLine($" • {file.FileName,-20} {file.Description}");
}
WriteLine("");
}
WriteLine("▲ Usage examples:");
WriteLine(" seedfolder --template node myproject");
WriteLine(" seedfolder -t python myapp");
WriteLine(" seedfolder --type ruby mygem");
}
private static void ShowVersion()
{
var version = typeof(Program).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "Unknown";
WriteLine($"▲ seedfolder version {version}");
}
private static void ShowHelp()
{
var version = typeof(Program).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "Unknown";
WriteLine($"▲ seedfolder version {version}");
WriteLine("");
const string help = @"▲ Usage: seedfolder [options] [folderName]
Options:
--help, -h, -? Show this help message
--version, -v Show version information
--list-templates Show available template files
--template, --type, -t Specify project template type
--dry-run, --dry Preview operations without creating files
--force, -f Overwrite existing directory and files
--quiet, -q Suppress output (useful for scripting)
Arguments:
folderName Name of the folder to create (optional)
Template Types:
dotnet .NET project with standard dotfiles
node Node.js project with package.json
python Python project with requirements.txt
ruby Ruby project with Gemfile
markdown Documentation project with README (default)
universal Basic project with minimal files
If no folder name is provided, seedfolder will interactively ask for the folder name
and whether to prefix it with the current date.
Examples:
seedfolder # Interactive mode with template selection
seedfolder myproject # Create 'myproject' folder with markdown template
seedfolder --template node myapp # Create Node.js project
seedfolder -t python ""my project"" # Create Python project (spaces converted to dashes)
seedfolder --type ruby mygem # Create Ruby project
seedfolder --dry-run -t node myapp # Preview Node.js project creation
seedfolder --force myproject # Overwrite existing 'myproject' directory
seedfolder --quiet -t python myapp # Create Python project with no output";
WriteLine(help);
}
private static void WriteLine(string text, ConsoleColor color = default)
{
if (color == default)
{
Console.WriteLine(text);
}
else
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
}
private static async Task WriteFileAsync(string filename, string destination)
{
var assembly = Assembly.GetEntryAssembly();
var resourceName = $"solrevdev.seedfolder.Data.{filename}";
var resourceStream = assembly?.GetManifestResourceStream(resourceName);
if (resourceStream == null)
{
throw new InvalidOperationException($"Could not find embedded resource: {resourceName}");
}
using var reader = new StreamReader(resourceStream, Encoding.UTF8);
var fileContents = await reader.ReadToEndAsync().ConfigureAwait(false);
// Ensure destination directory exists
var destinationDir = Path.GetDirectoryName(destination);
if (!string.IsNullOrEmpty(destinationDir) && !Directory.Exists(destinationDir))
{
Directory.CreateDirectory(destinationDir);
}
await File.WriteAllTextAsync(destination, fileContents).ConfigureAwait(false);
}
private static void ShowHeader()
{
var programTitle = FiggleFonts.Standard.Render("seedfolder");
WriteLine(programTitle, ConsoleColor.DarkGreen);
AppendBlankLines();
}
private static void AppendBlankLines(int howMany = 2)
{
for (var i = 0; i <= howMany; i++)
{
WriteLine("");
}
}
private static string RemoveSpaces(string name, char replacement = '-') => name.Replace(' ', replacement);
private static string SafeNameForFileSystem(string name, char replace = '-')
{
if (string.IsNullOrWhiteSpace(name))
return string.Empty;
var invalids = Path.GetInvalidFileNameChars();
var result = new string(name.Select(c => invalids.Contains(c) ? replace : c).ToArray());
// Remove any leading/trailing dashes and handle edge cases
result = result.Trim(replace);
// Ensure we don't end up with an empty string after cleaning
return string.IsNullOrWhiteSpace(result) ? string.Empty : result;
}
private static bool ValidateDiskSpace(string directoryPath)
{
try
{
var drive = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(directoryPath)) ?? Directory.GetCurrentDirectory());
// Check if we have at least 10MB of free space (conservative estimate)
const long minimumSpaceRequired = 10 * 1024 * 1024; // 10MB in bytes
return drive.AvailableFreeSpace >= minimumSpaceRequired;
}
catch
{
// If we can't determine disk space, assume we have enough (better to try and fail gracefully)
return true;
}
}
private static void ShowGitSetupInstructions(string folderName)
{
WriteLine("▲ To initialize git and make your first commit, copy and paste these commands:", ConsoleColor.Cyan);
WriteLine("");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Windows commands
WriteLine($"cd \"{folderName}\"", ConsoleColor.DarkYellow);
WriteLine("git init", ConsoleColor.DarkYellow);
WriteLine("git lfs install 2>nul || echo Git LFS not available", ConsoleColor.DarkYellow);
WriteLine("git add .", ConsoleColor.DarkYellow);
WriteLine("git commit -m \"feat: initial commit\"", ConsoleColor.DarkYellow);
}
else
{
// Unix-like systems (Linux, macOS)
WriteLine($"cd \"{folderName}\"", ConsoleColor.DarkYellow);
WriteLine("git init", ConsoleColor.DarkYellow);
WriteLine("git lfs install 2>/dev/null || echo \"Git LFS not available\"", ConsoleColor.DarkYellow);
WriteLine("git add .", ConsoleColor.DarkYellow);
WriteLine("git commit -m \"feat: initial commit\"", ConsoleColor.DarkYellow);
}
WriteLine("");
}
}