tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add tazel new, tazel init, and tazel git add commands
- Commit
afbfbd857208eeec2c77646ce83fe6aa40d137ba- Author
- Leitwolf11 ·
- Parents
0934dd359916
Changes
CHANGELOG.md | 4 + docs/commands.md | 3 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 3 +- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 12 + src/Progmasoft.Tazel/Cli/CommandTypes.cs | 9 + src/Progmasoft.Tazel/Cli/Commands.cs | 3 + src/Progmasoft.Tazel/Cli/GitCommands.cs | 173 ++++++++++++++ src/Progmasoft.Tazel/Cli/Help.cs | 20 ++ src/Progmasoft.Tazel/Cli/NewInitCommands.cs | 254 +++++++++++++++++++++ .../Cli/ShellCompletion.FishPowerShell.cs | 3 + src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 11 +- src/Progmasoft.Tazel/Program.cs | 2 +- tests/Progmasoft.Tazel.Tests/NewInitAndGitTests.cs | 149 ++++++++++++ 13 files changed, 643 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c69b3b2..38582ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- `tazel new <name> [--force]` and `tazel init [--force]` interactively create `MODULE.csx` (with SPDX license + validation), `.gitignore` (`/.tazel`), and a local Git repository. +- `tazel git add` stages the module's files with system `git`, respecting `.gitignore`. + - `tazel version` now supports `-V`/`--verbose` and `-o`/`--output text|json`. - `tazel clean` now supports `--dry-run` (lists directories and byte sizes without deleting). - `tazel package` now supports `--list`, `--allow-dirty`, and `-o`/`--output-dir <dir>`. diff --git a/docs/commands.md b/docs/commands.md index fccc8a1..eb72e1b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -12,6 +12,9 @@ | `tazel query <expression>` | answers about the targets and what they depend on | | `tazel cquery <expression>` | the same, for the platform and mode of the command | | `tazel aquery <expression>` | prints the actions of the targets | +| `tazel new <name> [--force]` | interactively creates a new module in `<name>/` (`MODULE.csx`, `.gitignore`, `git init`) | +| `tazel init [--force]` | interactively initializes a module in the current directory | +| `tazel git add` | stages the module's files with system `git`, respecting `.gitignore` | | `tazel fetch` | downloads and checks the modules and plugins the module depends on, without building | | `tazel vendor` | copies the modules of Tazel Portal Modules and their indexes into `vendor/` | | `tazel portal-modules search\|info [-e] [--] <module\|group:module>` | searches Tazel Portal Modules, or shows one module | diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 25644d5..78d3598 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -20,7 +20,7 @@ internal static class CommandLine { /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = - ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "fetch", "vendor", "clean", "package", "custom", "portal-modules", "cache", "explain", "version", "help", "license", "shell-completion", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery"]; @@ -38,6 +38,7 @@ internal static class CommandLine new("output-dir", OptionKind.Value, null, "tool", "package"), new("remote", OptionKind.Flag, null, "cache"), new("dry-run", OptionKind.Flag, null, "clean"), + new("force", OptionKind.Flag, null, "new", "init"), new("list", OptionKind.Flag, null, "package"), new("allow-dirty", OptionKind.Flag, null, "package"), new("verbose", OptionKind.Flag, null, "version"), diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index c75182f..afab24c 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -22,6 +22,9 @@ internal static class CommandMakers ["query"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.Query), ["cquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.CQuery), ["aquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.AQuery), + ["new"] = MakeNew, + ["init"] = (scanned, output) => Bare(scanned, new InitCommand(output, scanned.Has("force"))), + ["git"] = MakeGit, ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("short"), scanned.Has("long")), ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), @@ -57,6 +60,15 @@ internal static class CommandMakers return command; } + private static Command MakeNew(ScannedCommand scanned, OutputOptions output) => scanned.Positional is [var name] + ? new NewCommand(output, name, scanned.Has("force")) + : throw new CommandLineException("tazel new takes one directory name, such as tazel new my-project"); + + private static Command MakeGit(ScannedCommand scanned, OutputOptions output) => scanned.Positional is ["add"] + ? new GitAddCommand(output) + : throw new CommandLineException("tazel git takes add: tazel git add" + + (scanned.Positional.Count > 0 && Suggestions.Nearest(scanned.Positional[0], ["add"]) is { } near ? $"; did you mean {near}?" : "")); + private static Command MakeRun(ScannedCommand scanned, OutputOptions output) { var positional = scanned.Positional; diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 412f943..d973708 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -156,6 +156,15 @@ internal sealed record PortalModulesCommand(OutputOptions Output, PortalAction A internal sealed record DaemonCommand(OutputOptions Output, string Action) : Command(Output); +/// <summary><c>tazel new <name> [--force]</c>: creates a new module in a new directory.</summary> +internal sealed record NewCommand(OutputOptions Output, string Name, bool Force) : Command(Output); + +/// <summary><c>tazel init [--force]</c>: initializes a module in the current working directory.</summary> +internal sealed record InitCommand(OutputOptions Output, bool Force) : Command(Output); + +/// <summary><c>tazel git add</c>: stages the module's files with system <c>git</c>.</summary> +internal sealed record GitAddCommand(OutputOptions Output) : Command(Output); + /// <summary><c>tazel cache keygen</c>: a key pair for signing the results of a remote cache.</summary> internal sealed record CacheKeygenCommand(OutputOptions Output, Cache.SigningAlgorithm Algorithm) : Command(Output); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 8438922..eaa6dbd 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -44,6 +44,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector VendorCommand => VendorAsync(cancel), PortalModulesCommand portal => PortalModulesAsync(portal, cancel), PackageCommand package => PackageAsync(package), + GitAddCommand => new GitCommands(reporter, workingDirectory).AddAsync(TazelVersion), + NewCommand create => Task.FromResult(new NewInitCommands(reporter, workingDirectory).New(create.Name, create.Force)), + InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), CustomCommandLine custom => CustomAsync(custom, cancel), CacheCheckCommand check => CacheCheckAsync(check, cancel), ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), diff --git a/src/Progmasoft.Tazel/Cli/GitCommands.cs b/src/Progmasoft.Tazel/Cli/GitCommands.cs new file mode 100644 index 0000000..e6f1ffb --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/GitCommands.cs @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel git add</c>: stages module files with system <c>git</c>, respecting <c>.gitignore</c>.</summary> +internal sealed class GitCommands(Reporter reporter, string workingDirectory) +{ + private static readonly string[] RootMetadataFiles = + [ + ModuleFiles.ModuleFile, + "tazel_options.txt", + "tazel_custom.txt", + "tazel_envs.txt", + "tazel_registries.txt", + "LOCK.sqlite3", + ".tazelignore", + ".gitignore", + ]; + + /// <summary>Collects the module's files inside the module root and stages them via <c>git add --</c>.</summary> + public async Task<int> AddAsync(Version tazelVersion) + { + var workspace = await Workspace.LoadAsync( + workingDirectory, new BuildContext(BuildMode.Debug, Host.Platform), tazelVersion, reporter.Status).ConfigureAwait(false); + var root = Path.GetFullPath(workspace.Main.Root); + var files = CollectModuleFiles(workspace, root); + if (files.Count == 0) + { + reporter.Status("nothing to stage"); + return 0; + } + + return StageFiles(root, files); + } + + /// <summary>Returns the sorted relative paths of all files belonging to the main module inside <paramref name="root"/>.</summary> + internal static List<string> CollectModuleFiles(Workspace workspace, string root) + { + var collected = new SortedSet<string>(StringComparer.Ordinal); + foreach (var file in RootMetadataFiles) + { + AddIfInside(collected, root, Path.Combine(root, file)); + } + + foreach (var package in workspace.Packages.Where(p => p.Repository is null)) + { + var pkgDir = string.IsNullOrEmpty(package.Path) ? root : Path.Combine(root, package.Path); + AddIfInside(collected, root, Path.Combine(pkgDir, ModuleFiles.BuildFile)); + } + + foreach (var target in workspace.Targets.Values.Where(t => t.Label.Package.Repository is null)) + { + CollectTargetFiles(collected, root, target); + } + + return [.. collected]; + } + + private static void CollectTargetFiles(SortedSet<string> collected, string root, ProjectTarget target) + { + if (target.Settings is CCSettings cc) + { + AddResolved(collected, root, FileSets.Resolve(cc.Sources, target.PackageDirectory, root, target.Place)); + AddResolved(collected, root, FileSets.Resolve(cc.Headers, target.PackageDirectory, root, target.Place)); + AddResolved(collected, root, FileSets.Resolve(cc.TextualHeaders, target.PackageDirectory, root, target.Place)); + } + + if (target.Settings is ZigModuleSettings zig) + { + if (zig.Sources.Items.Count > 0) + { + AddResolved(collected, root, FileSets.Resolve(zig.Sources, target.PackageDirectory, root, target.Place)); + } + + if (!string.IsNullOrWhiteSpace(zig.RootSourceFile)) + { + AddIfInside(collected, root, Path.Combine(target.PackageDirectory, zig.RootSourceFile)); + } + } + + if (target.Settings is ZigCompiledSettings zigCompiled) + { + AddResolved(collected, root, FileSets.Resolve(zigCompiled.CSources, target.PackageDirectory, root, target.Place)); + } + + if (target.Settings is IRunSettings run) + { + AddResolved(collected, root, FileSets.Resolve(run.RuntimeData, target.PackageDirectory, root, target.Place)); + } + } + + private static void AddResolved(SortedSet<string> collected, string root, IEnumerable<string> relativePaths) + { + foreach (var relative in relativePaths) + { + AddIfInside(collected, root, Path.Combine(root, relative)); + } + } + + private static void AddIfInside(SortedSet<string> collected, string root, string fullPath) + { + var resolved = Path.GetFullPath(fullPath); + if (!File.Exists(resolved)) + { + return; + } + + var relative = Path.GetRelativePath(root, resolved).Replace('\\', '/'); + if (relative == ".." || relative.StartsWith("../", StringComparison.Ordinal) || Path.IsPathRooted(relative)) + { + return; + } + + collected.Add(relative); + } + + private int StageFiles(string root, List<string> files) + { + var startInfo = new ProcessStartInfo("git") + { + WorkingDirectory = root, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + startInfo.ArgumentList.Add("add"); + startInfo.ArgumentList.Add("--"); + foreach (var file in files) + { + startInfo.ArgumentList.Add(file); + } + + try + { + using var process = Process.Start(startInfo); + if (process is null) + { + reporter.Error(ErrorCodes.Project, "failed to start git add"); + return 1; + } + + var stderr = process.StandardError.ReadToEnd(); + process.WaitForExit(); + if (process.ExitCode != 0 && !stderr.Contains("ignored by one of your .gitignore", StringComparison.OrdinalIgnoreCase)) + { + reporter.Error(ErrorCodes.Project, $"git add failed (exit {process.ExitCode}): {stderr.Trim()}"); + return 1; + } + + reporter.Success($"staged {files.Count} module file(s) with git add"); + return 0; + } + catch (Win32Exception) + { + reporter.Error(ErrorCodes.Project, "git was not found on PATH; install git to run tazel git add"); + return 1; + } + } +} diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 83a736e..6fd0612 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -335,6 +335,26 @@ internal static class Help tazel shell-completion fish > ~/.config/fish/completions/tazel.fish tazel shell-completion powershell | Out-String | Invoke-Expression """), + ["new"] = new("tazel new <name> [--force]: interactively creates a new module in a new directory.", """ + tazel new <name> [--force] + + Creates <name>/, asks for MODULE.csx fields interactively, writes MODULE.csx and .gitignore (with /.tazel), + and initializes a local Git repository with system git. Requires an interactive terminal. + --force allow an existing non-empty directory and replace MODULE.csx + """), + ["init"] = new("tazel init [--force]: interactively initializes a module in the current directory.", """ + tazel init [--force] + + Asks for MODULE.csx fields interactively, writes MODULE.csx and .gitignore (with /.tazel), and initializes + a local Git repository if none exists. Requires an interactive terminal. + --force replace an existing MODULE.csx and keep existing .gitignore/.git + """), + ["git"] = new("tazel git add: stages the module's files with system git.", """ + tazel git add + + Stages MODULE.csx, reachable BUILD.csx files, target sources/headers/data, configuration files, LOCK.sqlite3, + .tazelignore and .gitignore using system git add -- <paths>, respecting .gitignore. + """), }; private const string GlobalOptions = """ diff --git a/src/Progmasoft.Tazel/Cli/NewInitCommands.cs b/src/Progmasoft.Tazel/Cli/NewInitCommands.cs new file mode 100644 index 0000000..5bb2b7a --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/NewInitCommands.cs @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using NuGet.Versioning; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; +using Spectre.Console; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Implements <c>tazel new</c> and <c>tazel init</c>: interactive module creation and local Git setup.</summary> +internal sealed class NewInitCommands( + Reporter reporter, + string workingDirectory, + Func<string, string?, string>? prompter = null, + bool? interactiveOverride = null) +{ + private const string IgnoreEntry = "/.tazel"; + + /// <summary>Creates a new module in a new directory <paramref name="name"/>.</summary> + public int New(string name, bool force) + { + if (string.IsNullOrWhiteSpace(name) || name.Contains(Path.DirectorySeparatorChar, StringComparison.Ordinal) || + name.Contains(Path.AltDirectorySeparatorChar, StringComparison.Ordinal) || name is "." or "..") + { + throw new CommandLineException($"'{name}' is not a valid directory name for tazel new"); + } + + var directory = Path.GetFullPath(Path.Combine(workingDirectory, name)); + if (Directory.Exists(directory) && Directory.EnumerateFileSystemEntries(directory).Any() && !force) + { + reporter.Error(ErrorCodes.Project, + $"directory '{name}' already exists and is not empty; pass --force to overwrite MODULE.csx"); + return 1; + } + + return CreateModule(directory, name, force); + } + + /// <summary>Initializes a module in the current working directory.</summary> + public int Init(bool force) + { + var directory = Path.GetFullPath(workingDirectory); + var manifest = Path.Combine(directory, ModuleFiles.ModuleFile); + if (File.Exists(manifest) && !force) + { + reporter.Error(ErrorCodes.Project, + $"{ModuleFiles.ModuleFile} already exists in {directory}; pass --force to replace it"); + return 1; + } + + var defaultName = Path.GetFileName(directory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); + return CreateModule(directory, string.IsNullOrWhiteSpace(defaultName) ? "module" : defaultName, force); + } + + private int CreateModule(string directory, string defaultName, bool force) + { + var interactive = interactiveOverride ?? !Console.IsInputRedirected; + if (!interactive) + { + reporter.Error(ErrorCodes.Project, + "tazel new and tazel init require an interactive terminal on standard input"); + return 1; + } + + var group = AskValidated("Group", "com.example", ValidateGroup); + var name = AskValidated("Name", defaultName, ValidateName); + var version = AskValidated("Version", "0.1.0", ValidateVersion); + var description = AskOptional("Description"); + var authorsRaw = AskOptional("Authors (comma-separated)"); + var license = AskValidated("License (SPDX expression)", "MIT", ValidateLicense); + var readme = AskOptional("Readme (optional, e.g. README.md)"); + + Directory.CreateDirectory(directory); + var manifestPath = Path.Combine(directory, ModuleFiles.ModuleFile); + File.WriteAllText(manifestPath, RenderModule(group, name, version, description, authorsRaw, license, readme), new UTF8Encoding(false)); + + WriteGitIgnore(Path.Combine(directory, ".gitignore"), force); + + if (!Directory.Exists(Path.Combine(directory, ".git"))) + { + if (!RunGitInit(directory)) + { + return 1; + } + } + + reporter.Success($"initialized Tazel module {group}:{name} {version} in {directory}"); + return 0; + } + + private string AskValidated(string label, string defaultValue, Func<string, string?> validate) + { + while (true) + { + var answer = Prompt(label, defaultValue).Trim(); + var error = validate(answer); + if (error is null) + { + return answer; + } + + reporter.Warning(error); + } + } + + private string AskOptional(string label) => Prompt(label, "").Trim(); + + private string Prompt(string label, string? defaultValue) + { + if (prompter is not null) + { + return prompter(label, defaultValue); + } + + var prompt = new TextPrompt<string>(Markup.Escape(label) + ":").AllowEmpty(); + if (!string.IsNullOrEmpty(defaultValue)) + { + prompt.DefaultValue(defaultValue); + } + + return reporter.Console.Prompt(prompt); + } + + private static void WriteGitIgnore(string path, bool force) + { + if (force && File.Exists(path)) + { + var lines = File.ReadAllLines(path); + if (!lines.Any(line => line.Trim() == IgnoreEntry)) + { + var existing = File.ReadAllText(path); + var prefix = existing.Length > 0 && !existing.EndsWith('\n') ? "\n" : ""; + File.AppendAllText(path, prefix + IgnoreEntry + "\n", new UTF8Encoding(false)); + } + + return; + } + + File.WriteAllText(path, IgnoreEntry + "\n", new UTF8Encoding(false)); + } + + private bool RunGitInit(string directory) + { + try + { + using var process = Process.Start(new ProcessStartInfo("git", "init") + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }); + if (process is null) + { + reporter.Error(ErrorCodes.Project, "failed to start git init"); + return false; + } + + var stderr = process.StandardError.ReadToEnd(); + process.WaitForExit(); + if (process.ExitCode != 0) + { + reporter.Error(ErrorCodes.Project, $"git init failed (exit {process.ExitCode}): {stderr.Trim()}"); + return false; + } + + return true; + } + catch (Win32Exception) + { + reporter.Error(ErrorCodes.Project, "git was not found on PATH; install git to run tazel new/init"); + return false; + } + } + + private static string? ValidateGroup(string value) => + string.IsNullOrWhiteSpace(value) || value.StartsWith('.') || value.EndsWith('.') || value.Contains("..", StringComparison.Ordinal) || + !value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_') + ? "group must contain ASCII letters, digits, '.', '-' or '_' with no leading/trailing dots" + : null; + + private static string? ValidateName(string value) => + string.IsNullOrWhiteSpace(value) || !value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.') + ? "name must contain ASCII letters, digits, '-', '_' or '.'" + : null; + + private static string? ValidateVersion(string value) => + NuGetVersion.TryParse(value, out _) ? null : $"'{value}' is not a valid semantic version (e.g. 0.1.0)"; + + private static string? ValidateLicense(string value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return "license must be a valid SPDX license expression (e.g. MIT)"; + } + + try + { + SpdxLicenses.Check(value, ModuleFiles.ModuleFile); + return null; + } + catch (Project.LicenseException error) + { + return error.Message; + } + catch (ProjectException error) + { + return error.Message; + } + } + + private static string RenderModule( + string group, string name, string version, string description, string authorsRaw, string license, string readme) + { + var sb = new StringBuilder(); + sb.AppendLine("using Progmasoft.Tazel.Dsl.Module.Prelude;"); + sb.AppendLine(); + sb.AppendLine("module = Module.Define(new()"); + sb.AppendLine("{"); + sb.Append(" Group = ").Append(Quote(group)).AppendLine(","); + sb.Append(" Name = ").Append(Quote(name)).AppendLine(","); + sb.Append(" Version = ").Append(Quote(version)).AppendLine(","); + if (!string.IsNullOrWhiteSpace(description)) + { + sb.Append(" Description = ").Append(Quote(description)).AppendLine(","); + } + + var authors = authorsRaw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (authors.Length > 0) + { + sb.Append(" Authors = [").Append(string.Join(", ", authors.Select(Quote))).AppendLine("],"); + } + + sb.Append(" License = ").Append(Quote(license)).AppendLine(","); + if (!string.IsNullOrWhiteSpace(readme)) + { + sb.Append(" Readme = ").Append(Quote(readme)).AppendLine(","); + } + + sb.AppendLine("});"); + return sb.ToString(); + } + + private static string Quote(string value) => + "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\""; +} diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs index 710ead7..d7837e9 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs @@ -93,6 +93,9 @@ internal static class FishPowerShellCompletions sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage' -l no-cache -d 'Bypass cache'"); AppendFishValueOption(sb, "__fish_seen_subcommand_from query cquery aquery", "output", "label label_kind", "Output format"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from clean' -l expunge -d 'Remove all of .tazel'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from clean' -l dry-run -d 'Preview removals without deleting'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from new init' -l force -d 'Overwrite existing MODULE.csx'"); + sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd git' -a 'add'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l short -d 'Short help'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l long -d 'Detailed help'"); sb.AppendLine($"complete -c tazel -n '__tazel_needs_subcmd help' -a '{string.Join(' ', CommandLine.Commands)}'"); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index 7281b0d..40e0612 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -60,6 +60,9 @@ internal static class ShellCompletion ("query", "Query the target graph"), ("cquery", "Query targets for a platform and mode"), ("aquery", "Print actions of targets"), + ("new", "Create a new Tazel module"), + ("init", "Initialize a Tazel module in the current directory"), + ("git", "Stage module files with git"), ("fetch", "Download and verify dependencies"), ("vendor", "Copy dependencies into vendor/"), ("clean", "Remove build outputs"), @@ -234,7 +237,13 @@ internal static class ShellCompletion words="$words --output {{buildFlags}}" ;; clean) - words="$words --expunge" + words="$words --expunge --dry-run" + ;; + new|init) + words="$words --force" + ;; + git) + if [[ -z "$subcmd" ]]; then words="$words add"; fi ;; help) words="$words --short --long" diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 2fedcf6..5da8ecd 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -126,7 +126,7 @@ internal static class Program /// </summary> private static void ApplyDotnetSettings(Command command, string directory) { - if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand) + if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand or NewCommand or InitCommand) { return; } diff --git a/tests/Progmasoft.Tazel.Tests/NewInitAndGitTests.cs b/tests/Progmasoft.Tazel.Tests/NewInitAndGitTests.cs new file mode 100644 index 0000000..887dfaf --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/NewInitAndGitTests.cs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class NewInitAndGitTests +{ + [Fact] + public void CommandLineParsesNewInitAndGitAdd() + { + var create = Assert.IsType<NewCommand>(CommandLine.Parse(["new", "demo", "--force"])); + Assert.Equal("demo", create.Name); + Assert.True(create.Force); + + var init = Assert.IsType<InitCommand>(CommandLine.Parse(["init"])); + Assert.False(init.Force); + + Assert.IsType<GitAddCommand>(CommandLine.Parse(["git", "add"])); + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["new"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["git", "push"])); + } + + [Fact] + public void NewAndInitRefuseNonInteractiveInput() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-new-tty-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + using var writer = new StringWriter(); + using var reporter = new Reporter(MessageFormat.RichStdio, writer, When.Never, quiet: false, When.Never); + var commands = new NewInitCommands(reporter, dir, interactiveOverride: false); + Assert.Equal(1, commands.Init(false)); + Assert.Contains("interactive terminal", writer.ToString(), StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void NewCreatesModuleGitIgnoreAndGitRepoAndRepromptsInvalidLicense() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-new-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + var answers = new Queue<string>([ + "com.example", + "greeter", + "0.1.0", + "Sample module", + "Alice, Bob", + "NOT-A-VALID-SPDX", + "MIT", + "README.md", + ]); + using var writer = new StringWriter(); + using var reporter = new Reporter(MessageFormat.RichStdio, writer, When.Never, quiet: false, When.Never); + var commands = new NewInitCommands(reporter, dir, (_, _) => answers.Dequeue(), interactiveOverride: true); + + Assert.Equal(0, commands.New("greeter", false)); + var projectDir = Path.Combine(dir, "greeter"); + var manifest = File.ReadAllText(Path.Combine(projectDir, "MODULE.csx")); + Assert.Contains("Group = \"com.example\"", manifest, StringComparison.Ordinal); + Assert.Contains("Name = \"greeter\"", manifest, StringComparison.Ordinal); + Assert.Contains("License = \"MIT\"", manifest, StringComparison.Ordinal); + Assert.Contains("Authors = [\"Alice\", \"Bob\"]", manifest, StringComparison.Ordinal); + Assert.Equal("/.tazel\n", File.ReadAllText(Path.Combine(projectDir, ".gitignore"))); + Assert.True(Directory.Exists(Path.Combine(projectDir, ".git"))); + Assert.False(File.Exists(Path.Combine(projectDir, "BUILD.csx"))); + Assert.False(Directory.Exists(Path.Combine(projectDir, "src"))); + + // Without --force, existing non-empty directory is refused. + Assert.Equal(1, commands.New("greeter", false)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task GitAddStagesModuleFilesAndRespectsGitIgnore() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-git-add-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + RunGit(dir, "init"); + await File.WriteAllTextAsync(Path.Combine(dir, ".gitignore"), "/.tazel\nignored.txt\n", TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "ignored.txt"), "skip me\n", TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "MODULE.csx"), + "using Progmasoft.Tazel.Dsl.Module.Prelude;\nmodule = Module.Define(new() { Group = \"com.example\", Name = \"gitdemo\", Version = \"0.1.0\", License = \"MIT\" });\n", + TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "BUILD.csx"), + "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.Executable(\"app\", new() { Sources = [\"main.c\"] });\n", + TestContext.Current.CancellationToken); + await File.WriteAllTextAsync(Path.Combine(dir, "main.c"), "int main(void) { return 0; }\n", TestContext.Current.CancellationToken); + + using var writer = new StringWriter(); + var status = await Program.RunAsync(["--color", "never", "git", "add"], dir, writer, TestContext.Current.CancellationToken); + Assert.Equal(0, status); + + var staged = RunGit(dir, "diff", "--cached", "--name-only"); + Assert.Contains("MODULE.csx", staged, StringComparison.Ordinal); + Assert.Contains("BUILD.csx", staged, StringComparison.Ordinal); + Assert.Contains("main.c", staged, StringComparison.Ordinal); + Assert.Contains(".gitignore", staged, StringComparison.Ordinal); + Assert.DoesNotContain("ignored.txt", staged, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static string RunGit(string directory, params string[] args) + { + var psi = new ProcessStartInfo("git") + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (var arg in args) + { + psi.ArgumentList.Add(arg); + } + + using var process = Process.Start(psi)!; + var stdout = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + Assert.Equal(0, process.ExitCode); + return stdout; + } +}