tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Read only BUILD.csx, take labels alone in Depends; add tazel limited-time C#
- Commit
7b1cda50620edb0242dd94997b3e71ae3e1361de- Author
- Leitwolf11 ·
- Parents
bacbcbb7a0fc
Changes
CHANGELOG.md | 5 + README.md | 4 +- docs/project-files.md | 35 +++- src/Progmasoft.Tazel.Dsl/Common/References.cs | 16 +- src/Progmasoft.Tazel/Cli/CommandLine.cs | 9 +- src/Progmasoft.Tazel/Cli/Commands.cs | 32 +++ src/Progmasoft.Tazel/Cli/Help.cs | 10 + src/Progmasoft.Tazel/Project/CsxMigration.cs | 232 +++++++++++++++++++++ src/Progmasoft.Tazel/Project/ModuleFiles.cs | 20 +- src/Progmasoft.Tazel/Project/ScriptHost.cs | 8 + tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs | 4 +- tests/Progmasoft.Tazel.Tests/MigrationTests.cs | 201 ++++++++++++++++++ tests/Progmasoft.Tazel.Tests/PlannerTests.cs | 6 +- .../Progmasoft.Tazel.Tests/QueryAndPortalTests.cs | 6 +- tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs | 2 +- 15 files changed, 557 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd5a87f..6722245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ ## Unreleased +- Breaking: a package's project file is `BUILD.csx` and nothing else; a directory with `BUILD.tzl`, `BUILD.tazel`, + `BUILD` or `Tazel.build` stops the build with a message. `Depends` takes labels only, such as `"//:math"`; the value a + declaration returns is no longer taken. `tazel limited-time C#`, until 1.0.0, renames those files and writes the + targets `Depends` named by their variables as labels, without running any project file. + - Building for DragonFly BSD with zig says that zig brings no libc for it, instead of zig's own error, and what does build for it. Tests build Zig, C and C++ for FreeBSD and OpenBSD with zig and check that the files are theirs. diff --git a/README.md b/README.md index a5c13bf..0542bdd 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,11 @@ var math = CC.StaticLibrary("math", new() CC.Executable("greeter", new() { Sources = ["src/main.cpp"], - Depends = [math], + Depends = ["//:math"], RuntimeData = ["assets/messages.txt"] }); -CC.Test("math_test", new() { Sources = ["tests/math_test.cpp"], Depends = [math] }); +CC.Test("math_test", new() { Sources = ["tests/math_test.cpp"], Depends = ["//:math"] }); ``` ```text diff --git a/docs/project-files.md b/docs/project-files.md index a2ae9ae..0711b4f 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -8,8 +8,9 @@ a `MODULE.csx` of its own is another module and is not part of this one. Both fi the C# scripting of Roslyn; nothing else needs to be installed. Every project file sees `Progmasoft.Tazel.Dsl.Common` (platforms, `Glob`, `Visibility`, `TestSize`, sizes) without a `using`. -A package's project file is the first of `BUILD.csx`, `BUILD.tzl`, `BUILD.tazel`, `BUILD` and `Tazel.build` that it -has, looked up case-sensitively; all of them are C# scripts. +A package's project file is `BUILD.csx`, looked up case-sensitively on every system; no other name is one. A +directory whose project file has an earlier name (`BUILD.tzl`, `BUILD.tazel`, `BUILD` or `Tazel.build`) stops the build +with a message; `tazel limited-time C#` renames them, until Tazel 1.0.0 (below). ## MODULE.csx @@ -92,7 +93,7 @@ CC.SharedLibrary("greeter_shared", new() CC.Executable("greeter", new() { Sources = ["src/main.cpp"], - Depends = [math, ":greeter_shared"], + Depends = ["//:math", ":greeter_shared"], LinkerOptions = Build.Mode == BuildMode.Release ? ["-s"] : [], LinkingMode = LinkingMode.PreferStatic, // PreferShared, FullyStatic RuntimeData = ["assets/messages.txt"], @@ -104,7 +105,7 @@ CC.Executable("greeter", new() CC.Test("math_test", new() { Sources = ["tests/math_test.cpp"], - Depends = [math, "@catch3//:main"], + Depends = ["//:math", "@catch3//:main"], TestSize = TestSize.Small, // Small, Medium, Large, Enormous: 1, 5, 15, 60 minutes Timeout = TimeSpan.FromMinutes(2), Flaky = false, // true: a failure runs again, up to three times @@ -256,3 +257,29 @@ Zig.Toolchain("zig", new() them names a compiler that targets them (zig cc does, wrapped in a script that adds `-target aarch64-freebsd`). zig has no libc for DragonFly BSD: for `DragonFlyBSDAmd64` it builds static libraries, and linking needs a CC toolchain whose compiler has a DragonFly sysroot. + +## From earlier project files + +Until Tazel 1.0.0, `tazel limited-time C#` moves a tree of modules to what Tazel reads now, and is removed in 1.0.0: + +- every project file named `BUILD.tzl`, `BUILD.tazel`, `BUILD` or `Tazel.build` below the working directory becomes + `BUILD.csx`; +- in every `BUILD.csx`, a target that `Depends` names by its variable is written as its label, and the variable is left + out when nothing else uses it: + +```cs +// before +var mathematics = CC.StaticLibrary("math", new() { Sources = ["math.cpp"] }); +CC.Executable("app", new() { Sources = ["main.cpp"], Depends = [mathematics] }); + +// after +CC.StaticLibrary("math", new() { Sources = ["math.cpp"] }); +CC.Executable("app", new() { Sources = ["main.cpp"], Depends = ["//:math"] }); +``` + +It reads the files with Roslyn and runs none of them, and it walks every directory below the working directory but +hidden ones (`.tazel`, `.git`) and links, through nested modules too, each package labelled from its own module's +root. It checks everything before it writes anything: two project files in one directory, or a target named in a way +that is not a variable set by a declaration of the same file (a method's result, a variable of another kind), is +reported and changes no file. Run again, it finds nothing to do; after an interrupted run, a `BUILD.csx` that already +holds what the earlier file becomes is kept and the earlier file removed. diff --git a/src/Progmasoft.Tazel.Dsl/Common/References.cs b/src/Progmasoft.Tazel.Dsl/Common/References.cs index 6308e38..eda8ffb 100644 --- a/src/Progmasoft.Tazel.Dsl/Common/References.cs +++ b/src/Progmasoft.Tazel.Dsl/Common/References.cs @@ -37,7 +37,7 @@ public enum TestSize Enormous, } -/// <summary>A target a project file declared; <c>Depends</c> takes it as well as its label.</summary> +/// <summary>A target a project file declared. <c>Depends</c> takes its label, not this value.</summary> public sealed class Target { internal Target(string label) => Label = label; @@ -49,7 +49,7 @@ public sealed class Target public override string ToString() => Label; } -/// <summary>A target that another depends on: its label, or the value its declaration returned.</summary> +/// <summary>A target that another depends on, by its label.</summary> public sealed class TargetReference { private TargetReference(string label) => Label = label; @@ -60,9 +60,6 @@ public sealed class TargetReference /// <summary>A label.</summary> public static implicit operator TargetReference(string label) => FromLabel(label); - /// <summary>A declared target.</summary> - public static implicit operator TargetReference(Target target) => FromTarget(target); - /// <summary>A label.</summary> public static TargetReference FromLabel(string label) { @@ -70,18 +67,11 @@ public sealed class TargetReference return new TargetReference(label); } - /// <summary>A declared target.</summary> - public static TargetReference FromTarget(Target target) - { - ArgumentNullException.ThrowIfNull(target); - return new TargetReference(target.Label); - } - /// <inheritdoc/> public override string ToString() => Label; } -/// <summary>The targets a target depends on: <c>["//:math", math]</c>.</summary> +/// <summary>The targets a target depends on, by their labels: <c>["//:math", ":util", "@dep//:x"]</c>.</summary> [CollectionBuilder(typeof(TargetReferences), nameof(Create))] public sealed class TargetReferences : IEnumerable<TargetReference> { diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 4275886..77d3e4c 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -98,6 +98,9 @@ internal sealed record FetchCommand(OutputOptions Output) : Command(Output); internal sealed record ExplainCommand(OutputOptions Output, string Code, bool Long) : Command(Output); +/// <summary><c>tazel limited-time C#</c>: the migration to BUILD.csx and labels in Depends, until Tazel 1.0.0.</summary> +internal sealed record MigrateCommand(OutputOptions Output) : Command(Output); + internal sealed record VendorCommand(OutputOptions Output) : Command(Output); /// <summary>Searching Tazel Portal Modules, or the versions of one module.</summary> @@ -126,7 +129,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", - "portal-modules", "cache", "explain", "version", "help", "dotnet"]; + "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time"]; private enum Kind { @@ -279,6 +282,10 @@ internal static class CommandLine ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") : new CustomCommandLine(output, scanned.Positional), ["version"] = (scanned, output) => Bare(scanned, new VersionCommand(output)), + // The one word after it is case-sensitive: C#, as the language is written. + ["limited-time"] = (scanned, output) => scanned.Positional is ["C#"] + ? new MigrateCommand(output) + : throw new CommandLineException("tazel limited-time takes one word, C#: tazel limited-time C#"), ["dotnet"] = MakeDaemon, ["cache"] = MakeCache, }; diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index fdf0324..57bf47c 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -61,6 +61,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case ExplainCommand explain: Explain(explain); return 0; + case MigrateCommand: + return Migrate(); case CleanCommand clean: return Clean(clean.Expunge); case CacheKeygenCommand keygen: @@ -119,6 +121,36 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector } } + /// <summary> + /// tazel limited-time C#: renames the project files of earlier names below the working directory to BUILD.csx and + /// writes the targets Depends names by their variables as labels; nothing is written when anything is wrong. + /// </summary> + private int Migrate() + { + var result = Project.CsxMigration.Run(workingDirectory); + if (result.Problems.Count > 0) + { + reporter.Error(ErrorCodes.Project, $"nothing was changed:\n{string.Join('\n', result.Problems)}", + "fix these and run tazel limited-time C# again", "Measure twice, cut once; Tazel measured and put the saw down."); + return 1; + } + + foreach (var renamed in result.Renamed) + { + reporter.Plain($"renamed {renamed}"); + } + + foreach (var rewritten in result.Rewritten) + { + reporter.Plain($"wrote the Depends of {rewritten} as labels"); + } + + reporter.Success(result.Renamed.Count + result.Rewritten.Count == 0 + ? "nothing to change: every project file is BUILD.csx and names its dependencies by label" + : $"changed {result.Renamed.Count + result.Rewritten.Count} project file{(result.Renamed.Count + result.Rewritten.Count == 1 ? "" : "s")}"); + return 0; + } + private int Clean(bool expunge) { var root = ModuleFiles.FindRoot(workingDirectory); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index b6977b8..986b5c3 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -165,6 +165,16 @@ internal static class Help the name, and what follows is arguments, which <1>, <2>... and <*> take. Everything after custom belongs to the command, its options too. """), + ["limited-time"] = new("tazel limited-time C#: moves project files to BUILD.csx and labels in Depends; removed in 1.0.0.", """ + tazel limited-time C# + + Until Tazel 1.0.0, and removed in 1.0.0. Below the working directory, renames every project file named + BUILD.tzl, BUILD.tazel, BUILD or Tazel.build to BUILD.csx, and in every BUILD.csx writes the targets that + Depends names by a variable as their labels: Depends = [math] becomes Depends = ["//:math"]. A variable + nothing else uses is left out, its declaration kept. The files are read, never run. Everything is checked + first: two project files in one directory, or a target Depends names in a way that is not a variable of a + declaration of the same file, changes nothing. "C#" is written as here, case and all. + """), ["explain"] = new("tazel explain <code> [--long]: what an error code means and how to fix it.", """ tazel explain <code> [--long] diff --git a/src/Progmasoft.Tazel/Project/CsxMigration.cs b/src/Progmasoft.Tazel/Project/CsxMigration.cs new file mode 100644 index 0000000..33b3b62 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/CsxMigration.cs @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Progmasoft.Tazel.Dsl.Build.Prelude; + +namespace Progmasoft.Tazel.Project; + +/// <summary>What <c>tazel limited-time C#</c> changed, or would have changed and could not.</summary> +internal sealed record MigrationResult(IReadOnlyList<string> Renamed, IReadOnlyList<string> Rewritten, IReadOnlyList<string> Problems); + +/// <summary> +/// <c>tazel limited-time C#</c>, until Tazel 1.0.0: renames the project files of earlier names to <c>BUILD.csx</c> +/// and writes the targets that <c>Depends</c> names by their variables as labels. It reads the files with Roslyn and +/// runs none of them. Everything is checked before anything is written, so a problem changes no file; a second run +/// finds nothing to do. +/// </summary> +internal static class CsxMigration +{ + /// <summary>The names a package's project file had before only <c>BUILD.csx</c> was one.</summary> + public static IReadOnlyList<string> LegacyNames { get; } = ["BUILD.tzl", "BUILD.tazel", "BUILD", "Tazel.build"]; + + // The families whose declarations return a Target, and so may be named by a variable in Depends. + private static readonly HashSet<string> Families = new(StringComparer.Ordinal) { "CC", "ObjectiveC", "Zig" }; + + /// <summary>Migrates every package below <paramref name="directory"/>, in every module there.</summary> + public static MigrationResult Run(string directory, bool write = true) + { + var start = Path.GetFullPath(directory); + var problems = new List<string>(); + var plans = new List<(string? Legacy, string Target, string Text, bool Changed)>(); + foreach (var packageDirectory in Directories(start)) + { + var names = new HashSet<string>( + Directory.EnumerateFiles(packageDirectory).Select(Path.GetFileName).OfType<string>(), StringComparer.Ordinal); + var legacy = LegacyNames.Where(names.Contains).ToList(); + var shown = Shown(start, packageDirectory); + var csx = Path.Combine(packageDirectory, "BUILD.csx"); + if (legacy.Count > 1) + { + problems.Add($"{shown}: {string.Join(" and ", legacy)} are both here; keep one, and run this again"); + continue; + } + + var source = legacy.Count == 1 ? Path.Combine(packageDirectory, legacy[0]) : names.Contains("BUILD.csx") ? csx : null; + if (source is null) + { + continue; + } + + var text = File.ReadAllText(source); + var rewritten = Rewrite(text, Package(packageDirectory), Shown(start, source), problems); + if (legacy.Count == 1 && names.Contains("BUILD.csx")) + { + // What an interrupted run leaves: BUILD.csx already holds what this file becomes. + if (rewritten is not null && File.ReadAllText(csx) == rewritten) + { + plans.Add((source, csx, rewritten, Changed: false)); + } + else + { + problems.Add($"{shown}: {legacy[0]} and BUILD.csx are both here; keep one, and run this again"); + } + + continue; + } + + if (rewritten is not null && (legacy.Count == 1 || rewritten != text)) + { + plans.Add((legacy.Count == 1 ? source : null, csx, rewritten, rewritten != text || legacy.Count == 1)); + } + } + + if (problems.Count > 0 || !write) + { + return Result(start, plans, problems); + } + + foreach (var (legacy, target, text, changed) in plans) + { + if (changed) + { + var partial = target + ".partial"; + File.WriteAllText(partial, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + File.Move(partial, target, overwrite: legacy is null); + } + + if (legacy is not null) + { + File.Delete(legacy); + } + } + + return Result(start, plans, problems); + } + + private static MigrationResult Result( + string start, List<(string? Legacy, string Target, string Text, bool Changed)> plans, List<string> problems) => + new(plans.Where(plan => plan.Legacy is not null).Select(plan => $"{Shown(start, plan.Legacy!)} -> BUILD.csx").ToList(), + plans.Where(plan => plan.Legacy is null).Select(plan => Shown(start, plan.Target)).ToList(), + problems); + + // The directories below start, without hidden ones (.tazel, .git), the stores of fetched modules, or links. + private static IEnumerable<string> Directories(string start) + { + var pending = new Stack<string>([start]); + while (pending.Count > 0) + { + var directory = pending.Pop(); + yield return directory; + foreach (var child in new DirectoryInfo(directory).EnumerateDirectories().OrderByDescending(d => d.Name, StringComparer.Ordinal)) + { + if (!child.Name.StartsWith('.') && child.LinkTarget is null) + { + pending.Push(child.FullName); + } + } + } + } + + // The package path of a directory: from the nearest MODULE.csx at or above it. + private static string Package(string packageDirectory) + { + var root = ModuleFiles.FindRoot(packageDirectory); + var relative = Path.GetRelativePath(root, packageDirectory).Replace('\\', '/'); + return relative == "." ? "" : relative; + } + + private static string Shown(string start, string path) + { + var relative = Path.GetRelativePath(start, path).Replace('\\', '/'); + return relative == "." ? "./" : relative; + } + + /// <summary> + /// <paramref name="text"/> with every target that <c>Depends</c> names by a variable named by its label, and the + /// variables nothing else uses left out; null, with the reasons in <paramref name="problems"/>, when a reference + /// cannot be resolved. + /// </summary> + internal static string? Rewrite(string text, string package, string shown, List<string> problems) + { + var options = ScriptHost.BaseOptions.WithFilePath(shown).WithFileEncoding(Encoding.UTF8); + var compilation = CSharpScript.Create(text, options, typeof(BuildGlobals)).GetCompilation(); + var tree = compilation.SyntaxTrees.Single(); + var model = compilation.GetSemanticModel(tree); + var root = tree.GetRoot(); + var changes = new List<TextChange>(); + var replaced = new Dictionary<ISymbol, int>(SymbolEqualityComparer.Default); + var failed = false; + + foreach (var element in DependsElements(root)) + { + var type = model.GetTypeInfo(element).Type; + if (type is null || type.SpecialType == SpecialType.System_String || type.Name != "Target") + { + continue; + } + + var line = element.GetLocation().GetLineSpan().StartLinePosition.Line + 1; + if (element is not IdentifierNameSyntax identifier || + model.GetSymbolInfo(identifier).Symbol is not { } symbol || + DeclaredName(symbol) is not { } name) + { + problems.Add($"{shown}:{line}: Depends names '{element}', which is not a variable a declaration of this " + + "file set; write the label of the target instead"); + failed = true; + continue; + } + + changes.Add(new TextChange(element.Span, Literal($"//{package}:{name}"))); + replaced[symbol] = replaced.GetValueOrDefault(symbol) + 1; + } + + if (failed) + { + return null; + } + + // A variable that only Depends used is left out: its declaration stays, as a statement of its own. + foreach (var (symbol, count) in replaced) + { + var uses = root.DescendantNodes().OfType<IdentifierNameSyntax>() + .Count(name => name.Identifier.ValueText == symbol.Name && + SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(name).Symbol, symbol)); + if (uses == count && Declarator(symbol) is { Parent: VariableDeclarationSyntax { Variables.Count: 1 } declaration } declarator) + { + changes.Add(new TextChange(TextSpan.FromBounds(declaration.SpanStart, declarator.Initializer!.Value.SpanStart), "")); + } + } + + return changes.Count == 0 ? text : SourceText.From(text).WithChanges(changes).ToString(); + } + + // The elements of every Depends = [...] (and Depends = new() {...}) in object initializers. + private static IEnumerable<ExpressionSyntax> DependsElements(SyntaxNode root) => + root.DescendantNodes().OfType<AssignmentExpressionSyntax>() + .Where(assignment => assignment.Left is IdentifierNameSyntax { Identifier.ValueText: "Depends" }) + .SelectMany(assignment => assignment.Right switch + { + CollectionExpressionSyntax collection => collection.Elements.OfType<ExpressionElementSyntax>().Select(e => e.Expression), + _ => [], + }); + + // The name in the first argument of the declaration a variable was set to: CC.StaticLibrary("math", ...). + private static string? DeclaredName(ISymbol symbol) + { + if (Declarator(symbol)?.Initializer?.Value is not InvocationExpressionSyntax + { + Expression: MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax family }, + ArgumentList.Arguments: [{ Expression: LiteralExpressionSyntax literal }, ..], + } || !Families.Contains(family.Identifier.ValueText) || !literal.IsKind(SyntaxKind.StringLiteralExpression)) + { + return null; + } + + return literal.Token.ValueText; + } + + private static VariableDeclaratorSyntax? Declarator(ISymbol symbol) => + symbol.DeclaringSyntaxReferences.Select(reference => reference.GetSyntax()).OfType<VariableDeclaratorSyntax>().FirstOrDefault(); + + private static string Literal(string text) => SymbolDisplay.FormatLiteral(text, quote: true); +} diff --git a/src/Progmasoft.Tazel/Project/ModuleFiles.cs b/src/Progmasoft.Tazel/Project/ModuleFiles.cs index 0150b40..e544316 100644 --- a/src/Progmasoft.Tazel/Project/ModuleFiles.cs +++ b/src/Progmasoft.Tazel/Project/ModuleFiles.cs @@ -17,9 +17,8 @@ internal static class ModuleFiles /// <summary>The directory below the root where Tazel keeps what it makes.</summary> public const string StateDirectory = ".tazel"; - /// <summary>The names a package's project file may have, in the order they are looked for; the first wins.</summary> - public static IReadOnlyList<string> BuildFileNames { get; } = - ["BUILD.csx", "BUILD.tzl", "BUILD.tazel", "BUILD", "Tazel.build"]; + /// <summary>The name of a package's project file, the only one: case-sensitive on every system.</summary> + public const string BuildFile = "BUILD.csx"; /// <summary>The root of the module <paramref name="directory"/> is in: the nearest directory with a MODULE.csx.</summary> public static string FindRoot(string directory) @@ -41,7 +40,20 @@ internal static class ModuleFiles // The lookup is case-sensitive on every system, so build.csx is not a project file anywhere. var names = new HashSet<string>( Directory.EnumerateFiles(directory).Select(Path.GetFileName).OfType<string>(), StringComparer.Ordinal); - return BuildFileNames.FirstOrDefault(names.Contains) is { } name ? Path.Combine(directory, name) : null; + if (names.Contains(BuildFile)) + { + return Path.Combine(directory, BuildFile); + } + + // A file of an earlier name would leave its targets out without a word; it is refused instead. + if (CsxMigration.LegacyNames.FirstOrDefault(names.Contains) is { } legacy) + { + throw new ProjectException( + $"{Path.Combine(directory, legacy)}: a project file is named BUILD.csx and nothing else; rename it, or let " + + "tazel limited-time C# rename it and write its Depends as labels"); + } + + return null; } /// <summary> diff --git a/src/Progmasoft.Tazel/Project/ScriptHost.cs b/src/Progmasoft.Tazel/Project/ScriptHost.cs index fccfde7..3641c9e 100644 --- a/src/Progmasoft.Tazel/Project/ScriptHost.cs +++ b/src/Progmasoft.Tazel/Project/ScriptHost.cs @@ -179,6 +179,14 @@ internal static class ScriptHost .Append(diagnostic.GetMessage(System.Globalization.CultureInfo.InvariantCulture)).Append('\n'); } + // A target's variable in Depends, as earlier versions of Tazel took it: say what to write instead. + if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error && + d.GetMessage(System.Globalization.CultureInfo.InvariantCulture).Contains("Common.Target' to", StringComparison.Ordinal))) + { + text.Append("Depends takes the labels of targets, such as \"//:math\", not their variables; ") + .Append("tazel limited-time C# writes them as labels\n"); + } + return text.ToString().TrimEnd('\n'); } diff --git a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs index 0b427fa..1eef287 100644 --- a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs +++ b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs @@ -23,12 +23,12 @@ public sealed class BuildCommandTests CC.Executable("app", new() { Sources = ["main.cpp", "half.c"], - Depends = [math], + Depends = ["//:math"], CCompilerOptions = ["-DONLY_C"], CppCompilerOptions = ["-DONLY_CXX"], RuntimeData = ["data.txt"], }); - CC.Test("math_test", new() { Sources = ["math_test.cpp"], Depends = [math], ShardCount = 2 }); + CC.Test("math_test", new() { Sources = ["math_test.cpp"], Depends = ["//:math"], ShardCount = 2 }); CC.Test("failing", new() { Sources = ["failing.cpp"], Tags = ["manual"] }); """; diff --git a/tests/Progmasoft.Tazel.Tests/MigrationTests.cs b/tests/Progmasoft.Tazel.Tests/MigrationTests.cs new file mode 100644 index 0000000..de93832 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/MigrationTests.cs @@ -0,0 +1,201 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class MigrationTests +{ + private const string Prelude = "using Progmasoft.Tazel.Dsl.Build.Prelude;\n"; + + private static TemporaryModule Module() => new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile); + + private static string Read(TemporaryModule module, string path) => + File.ReadAllText(Path.Combine(module.Root, path)).ReplaceLineEndings("\n"); + + [Fact] + public void WritesTheExampleOfTheSpecification() + { + using var module = Module().Write("BUILD.tzl", Prelude + """ + var mathematics = CC.StaticLibrary("math", new() + { + Sources = ["math.cpp"] + }); + CC.Executable("app", new() + { + Sources = ["main.cpp"], + Depends = [mathematics] + }); + """); + var result = CsxMigration.Run(module.Root); + Assert.Empty(result.Problems); + Assert.Equal(["BUILD.tzl -> BUILD.csx"], result.Renamed); + Assert.False(File.Exists(Path.Combine(module.Root, "BUILD.tzl"))); + Assert.Equal(Prelude + """ + CC.StaticLibrary("math", new() + { + Sources = ["math.cpp"] + }); + CC.Executable("app", new() + { + Sources = ["main.cpp"], + Depends = ["//:math"] + }); + """, Read(module, "BUILD.csx")); + } + + [Theory] + [InlineData("BUILD.tzl")] + [InlineData("BUILD.tazel")] + [InlineData("BUILD")] + [InlineData("Tazel.build")] + public void RenamesEachEarlierName(string name) + { + using var module = Module().Write($"lib/{name}", Prelude + "CC.StaticLibrary(\"core\", new());\n"); + var result = CsxMigration.Run(module.Root); + Assert.Equal([$"lib/{name} -> BUILD.csx"], result.Renamed); + Assert.Equal(Prelude + "CC.StaticLibrary(\"core\", new());\n", Read(module, "lib/BUILD.csx")); + } + + [Fact] + public void KeepsAVariableThatIsUsedElsewhereAndLabelsFromThePackage() + { + using var module = Module().Write("lib/BUILD.csx", Prelude + """ + var core = CC.StaticLibrary("core", new() { Visibility = Visibility.Public }); + var util = CC.StaticLibrary("util", new() { Depends = [core, "//:math"] }); + CC.Test("util_test", new() { Depends = [util, core] }); + System.Console.WriteLine(core.Label); + """); + var result = CsxMigration.Run(module.Root); + Assert.Equal(["lib/BUILD.csx"], result.Rewritten); + Assert.Equal(Prelude + """ + var core = CC.StaticLibrary("core", new() { Visibility = Visibility.Public }); + CC.StaticLibrary("util", new() { Depends = ["//lib:core", "//:math"] }); + CC.Test("util_test", new() { Depends = ["//lib:util", "//lib:core"] }); + System.Console.WriteLine(core.Label); + """, Read(module, "lib/BUILD.csx")); + } + + [Fact] + public void ARunAfterTheFirstChangesNothing() + { + using var module = Module().Write("BUILD", Prelude + "var a = CC.StaticLibrary(\"a\", new());\nCC.Executable(\"b\", new() { Depends = [a] });\n"); + Assert.Single(CsxMigration.Run(module.Root).Renamed); + var once = Read(module, "BUILD.csx"); + var again = CsxMigration.Run(module.Root); + Assert.Empty(again.Renamed); + Assert.Empty(again.Rewritten); + Assert.Empty(again.Problems); + Assert.Equal(once, Read(module, "BUILD.csx")); + } + + [Fact] + public void ATargetNamedOtherwiseThanByItsVariableChangesNoFile() + { + using var module = Module() + .Write("lib/BUILD.tzl", Prelude + "CC.StaticLibrary(\"x\", new());\n") + .Write("BUILD.csx", Prelude + """ + Target Pick() => CC.StaticLibrary("a", new()); + CC.Executable("b", new() { Depends = [Pick()] }); + """); + var result = CsxMigration.Run(module.Root); + Assert.Contains(result.Problems, problem => problem.Contains("BUILD.csx:3: Depends names 'Pick()'", StringComparison.Ordinal)); + Assert.True(File.Exists(Path.Combine(module.Root, "lib", "BUILD.tzl"))); + Assert.False(File.Exists(Path.Combine(module.Root, "lib", "BUILD.csx"))); + } + + [Fact] + public void TwoProjectFilesInOneDirectoryChangeNoFile() + { + using var module = Module() + .Write("a/BUILD", Prelude + "CC.StaticLibrary(\"x\", new());\n") + .Write("a/BUILD.tzl", Prelude + "CC.StaticLibrary(\"y\", new());\n") + .Write("b/BUILD.tazel", Prelude + "CC.StaticLibrary(\"z\", new());\n") + .Write("b/BUILD.csx", Prelude + "CC.StaticLibrary(\"w\", new());\n"); + var result = CsxMigration.Run(module.Root); + Assert.Contains("a: BUILD.tzl and BUILD are both here; keep one, and run this again", result.Problems); + Assert.Contains("b: BUILD.tazel and BUILD.csx are both here; keep one, and run this again", result.Problems); + Assert.True(File.Exists(Path.Combine(module.Root, "a", "BUILD"))); + Assert.Equal(Prelude + "CC.StaticLibrary(\"w\", new());\n", Read(module, "b/BUILD.csx")); + } + + [Fact] + public void AfterAnInterruptedRunTheEarlierFileGoes() + { + using var module = Module() + .Write("BUILD.tzl", Prelude + "CC.StaticLibrary(\"a\", new());\n") + .Write("BUILD.csx", Prelude + "CC.StaticLibrary(\"a\", new());\n"); + var result = CsxMigration.Run(module.Root); + Assert.Empty(result.Problems); + Assert.False(File.Exists(Path.Combine(module.Root, "BUILD.tzl"))); + } + + [Fact] + public void LabelsANestedModuleFromItsOwnRootAndSkipsHiddenDirectories() + { + using var module = Module() + .Write("dep/MODULE.csx", TemporaryModule.ModuleFile) + .Write("dep/lib/BUILD.tzl", Prelude + "var a = CC.StaticLibrary(\"a\", new());\nCC.Executable(\"b\", new() { Depends = [a] });\n") + .Write(".tazel/external/x/BUILD", "not C# at all"); + var result = CsxMigration.Run(module.Root); + Assert.Equal(["dep/lib/BUILD.tzl -> BUILD.csx"], result.Renamed); + Assert.Contains("Depends = [\"//lib:a\"]", Read(module, "dep/lib/BUILD.csx"), StringComparison.Ordinal); + Assert.True(File.Exists(Path.Combine(module.Root, ".tazel", "external", "x", "BUILD"))); + } + + [Fact] + public async Task ABuildRefusesAnEarlierNameAndSaysHowToMove() + { + using var module = Module().Write("lib/BUILD.tzl", Prelude + "CC.StaticLibrary(\"a\", new());\n"); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.Equal(1, status); + Assert.Contains("a project file is named BUILD.csx and nothing else", output, StringComparison.Ordinal); + Assert.Contains("tazel limited-time C#", output, StringComparison.Ordinal); + } + + [Fact] + public async Task ATargetVariableInDependsSaysToWriteItsLabel() + { + using var module = Module().Write("BUILD.csx", Prelude + "var a = CC.StaticLibrary(\"a\", new());\nCC.Executable(\"b\", new() { Depends = [a] });\n"); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.Equal(1, status); + Assert.Contains("Depends takes the labels of targets, such as \"//:math\", not their variables", output, StringComparison.Ordinal); + } + + [Fact] + public async Task TheCommandMigratesAndThenFindsNothing() + { + using var module = Module().Write("BUILD", Prelude + "var a = CC.StaticLibrary(\"a\", new());\nCC.Executable(\"b\", new() { Depends = [a] });\n"); + var (status, output) = await module.TazelAsync(".", "limited-time", "C#"); + Assert.True(status == 0, output); + Assert.Contains("renamed BUILD -> BUILD.csx", output, StringComparison.Ordinal); + (status, output) = await module.TazelAsync(".", "limited-time", "C#"); + Assert.Equal(0, status); + Assert.Contains("nothing to change", output, StringComparison.Ordinal); + // What it wrote loads: //:b depends on //:a by its label. + (status, output) = await module.TazelAsync(".", "query", "deps(//:b)"); + Assert.True(status == 0, output); + Assert.Contains("//:a", output, StringComparison.Ordinal); + } + + [Theory] + [InlineData("c#")] + [InlineData("CSharp")] + public void TheWordIsCSharpAsWritten(string word) + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["limited-time", word])); + Assert.Contains("tazel limited-time C#", error.Message, StringComparison.Ordinal); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["limited-time"])); + Assert.IsType<MigrateCommand>(CommandLine.Parse(["limited-time", "C#"])); + } + + [Fact] + public void TheHelpSaysItGoesIn100() => + Assert.Contains("removed in 1.0.0", Help.Text("limited-time", false), StringComparison.Ordinal); +} diff --git a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs index 3e1e388..52da6dc 100644 --- a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs +++ b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs @@ -72,7 +72,7 @@ public sealed class PlannerTests CC.SharedLibrary("shared", new() { Sources = ["src/shared.c"], - Depends = [math], + Depends = ["//:math"], CCompilerOptions = ["-std=c17"], LibraryVersion = new Version(1, 2, 0), Features = [CC.Enable("lto"), CC.Disable("warnings")], @@ -80,7 +80,7 @@ public sealed class PlannerTests CC.Executable("app", new() { Sources = ["src/main.cc"], - Depends = [":shared", math], + Depends = [":shared", "//:math"], LinkingMode = LinkingMode.PreferStatic, }); Zig.Module("core", new() { RootSourceFile = "zig/core.zig" }); @@ -88,7 +88,7 @@ public sealed class PlannerTests { RootSourceFile = "zig/main.zig", ModuleImports = new Dictionary<string, string> { ["core"] = ":core" }, - Depends = [math], + Depends = ["//:math"], CSources = ["zig/shim.c"], CCompilerOptions = ["-std=c17"], LinkCStandardLibrary = true, diff --git a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs index 80d2a2d..7bdb741 100644 --- a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs +++ b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs @@ -23,9 +23,9 @@ public sealed class QueryTests private const string Build = """ using Progmasoft.Tazel.Dsl.Build.Prelude; var core = CC.StaticLibrary("core", new() { Sources = ["core.c"], Visibility = Visibility.Module }); - var util = CC.StaticLibrary("util", new() { Sources = ["util.c"], Depends = [core], Visibility = Visibility.Module }); - CC.Executable("app", new() { Sources = ["main.c"], Depends = [util] }); - CC.Test("util_test", new() { Sources = ["test.c"], Depends = [util] }); + var util = CC.StaticLibrary("util", new() { Sources = ["util.c"], Depends = ["//:core"], Visibility = Visibility.Module }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = ["//:util"] }); + CC.Test("util_test", new() { Sources = ["test.c"], Depends = ["//:util"] }); ObjectiveC.StaticLibrary("mac", new()); """; diff --git a/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs b/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs index 951d088..6aabbb0 100644 --- a/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs +++ b/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs @@ -23,7 +23,7 @@ public sealed class WorkspaceTests module.Write("MODULE.csx", TemporaryModule.ModuleFile) .Write("BUILD.csx", Prelude + """ var core = CC.StaticLibrary("core", new() { Sources = ["core.c"], Visibility = Visibility.Module }); - CC.Executable("app", new() { Sources = ["main.c"], Depends = [core, "//lib:util"] }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = ["//:core", "//lib:util"] }); """) .Write("core.c", "").Write("main.c", "") .Write("lib/BUILD.csx", Prelude + """