Progmasoft Git

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 tazel_envs.txt and give its values to project files

- tazel_envs.txt sits beside the MODULE.csx of a module and is read with the
  lexer of tazel_custom.txt: name: value, where a value is a string, a
  program started directly ("program" "argument"), or a line for /bin/sh on
  Linux, macOS and the BSDs and cmd.exe on Windows, s("line"); a ; after a
  value is optional.
- GetEnvironment.From(name) of Progmasoft.Tazel.Dsl.Environment gives
  MODULE.csx and BUILD.csx files a value, or null for a name the file does not
  have. A program or line runs when its value is first asked for, once per
  command, in the module root with Tazel's environment; what it prints, less
  the line endings at its end, is the value, and a program that fails stops the
  project file that asked, with the line of the entry.
- A value is not an environment variable: it reaches no shell, no program and
  not Tazel's own environment.
- Tests for the reader, its errors and the values; a fuzz target for the
  reader with a seed; docs in commands.md.
Commit
5a2e5c4203e4c6b2322fad75ee8e3651ae1c0e78
Author
Leitwolf11 ·
Parents
d9f2cee387e5

Files · Download .tar.gz

Changes

 .github/workflows/fuzzing.yml                      |   2 +-
 CHANGELOG.md                                       |   2 +-
 docs/README.md                                     |   2 +-
 docs/architecture.md                               |   1 +
 docs/commands.md                                   |  28 +++
 docs/development.md                                |   2 +-
 fuzz/Progmasoft.Tazel.Fuzz/Program.cs              |   3 +-
 fuzz/corpus/envs/sample                            |   6 +
 .../Environment/GetEnvironment.cs                  |  48 +++++
 src/Progmasoft.Tazel/Driver/Processes.cs           |  43 +++++
 src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs         | 203 +++++++++++++++++++++
 src/Progmasoft.Tazel/Project/Workspace.cs          |  28 ++-
 tests/Progmasoft.Tazel.Tests/EnvsTests.cs          | 102 +++++++++++
 13 files changed, 461 insertions(+), 9 deletions(-)

diff --git a/.github/workflows/fuzzing.yml b/.github/workflows/fuzzing.yml
index 6fb61e5..dfe4575 100644
--- a/.github/workflows/fuzzing.yml
+++ b/.github/workflows/fuzzing.yml
@@ -26,7 +26,7 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        target: [custom, options, label, depfile, command-line]
+        target: [custom, options, envs, label, depfile, command-line]
     steps:
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
         with:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb1d7f2..4330104 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ The first version of Tazel, written in C# for .NET 10.
   `--feature`, `--no-feature` and the options for the compilers and the linker.
 - An action cache by content, depfiles for headers, parallel actions, runfiles, sharded and flaky tests.
 - Reproducible `.tazel.tar.xz` archives of modules, and dependencies on them checked by SHA-256.
-- `tazel_options.txt` (with `platform:`) and `tazel_custom.txt`.
+- `tazel_options.txt` (with `platform:`), `tazel_custom.txt`, and `tazel_envs.txt` with `GetEnvironment.From`.
 - `tazel coverage` (LLVM source-based, an LCOV report), `tazel query`, `cquery` and `aquery`, `tazel fetch`,
   `tazel vendor`, and `tazel portal-modules search` and `info`; `tazel help --long`.
 - Modules of Tazel Portal Modules as dependencies: each at the highest version asked for, checked by SHA-256,
diff --git a/docs/README.md b/docs/README.md
index 5a18f01..80d40a6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,7 +7,7 @@
 | --- | --- |
 | [Project files](project-files.md) | `MODULE.csx`, `BUILD.csx` and toolchains, with every setting |
 | [Plugins](plugins.md) | making, packing and loading plugins, and their build steps |
-| [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt` and `tazel_custom.txt` |
+| [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` |
 | [Architecture](architecture.md) | the projects of the solution and how a build runs |
 | [Development](development.md) | building, testing, fuzzing and benchmarking Tazel, and its CI |
 | [Reference](reference/index.md) | the C# types of the project files, made with DocFX |
diff --git a/docs/architecture.md b/docs/architecture.md
index 2eec2df..f801f0a 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -29,6 +29,7 @@
 | `Progmasoft.Tazel.Output` | prints through Spectre.Console |
 | `Progmasoft.Tazel.Dsl.Custom`, `.Lexer`, `.Parser` | `tazel_custom.txt` |
 | `Progmasoft.Tazel.Dsl.Options` | `tazel_options.txt`, with the lexer of `tazel_custom.txt` |
+| `Progmasoft.Tazel.Dsl.Envs` | `tazel_envs.txt` and the values `GetEnvironment.From` reads, with the same lexer |
 
 ## A build
 
diff --git a/docs/commands.md b/docs/commands.md
index 485a936..6d25599 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -146,3 +146,31 @@ tazel portal-modules info --exact -- com.example:json
 with their push dates and dependencies; without `-e` the group may be left out unless the name is a module of more
 than one group. `--` ends the options, so a query may start with a dash.
 
+## tazel_envs.txt
+
+```text
+# comment
+<# comment #>
+
+example-version: '0.1.0'
+example-output: ("rustc" "--help")
+shell-expansion: s(`$HOME`)
+```
+
+`tazel_envs.txt` sits beside the `MODULE.csx` of a module and names values that its `MODULE.csx` and `BUILD.csx`
+files read:
+
+```cs
+using Progmasoft.Tazel.Dsl.Environment;
+
+var exampleVersion = GetEnvironment.From("example-version"); // "0.1.0"; null for a name the file does not have
+```
+
+- It is read with the lexer of `tazel_custom.txt`: the same comments and strings; a `;` after a value is optional.
+- A string is the value as written. `("program" "argument")` starts a program directly, each string one argument;
+  `s("line")` gives one line to `/bin/sh` on Linux, macOS and the BSDs and to `cmd.exe` on Windows. Their value is
+  what they print, less the line endings at its end. A program runs when its value is first asked for, once per
+  command, in the root of the module with Tazel's environment; one that fails stops the project file that asked.
+- A value is not an environment variable: it reaches no shell, no program Tazel runs and not Tazel itself; only
+  `GetEnvironment.From` reads it.
+
diff --git a/docs/development.md b/docs/development.md
index 3115880..ee850ba 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -27,7 +27,7 @@ change is right, move it over the stored one and commit it. A test without a sto
 
 ## Fuzzing
 
-The readers of what users write (`tazel_custom.txt`, `tazel_options.txt`, labels, depfiles, command lines) are fuzz
+The readers of what users write (`tazel_custom.txt`, `tazel_options.txt`, `tazel_envs.txt`, labels, depfiles, command lines) are fuzz
 targets. With [libfuzzer-dotnet](https://github.com/Metalnem/libfuzzer-dotnet):
 
 ```text
diff --git a/fuzz/Progmasoft.Tazel.Fuzz/Program.cs b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs
index 70cd6f4..ddd3a5f 100644
--- a/fuzz/Progmasoft.Tazel.Fuzz/Program.cs
+++ b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs
@@ -22,7 +22,7 @@ namespace Progmasoft.Tazel.Fuzz;
 public static class Program
 {
     /// <summary>The fuzz targets by name.</summary>
-    public static readonly string[] Targets = ["custom", "options", "label", "depfile", "command-line"];
+    public static readonly string[] Targets = ["custom", "options", "envs", "label", "depfile", "command-line"];
 
     /// <summary>Runs one target on the inputs libFuzzer gives.</summary>
     public static void Main(string[] arguments)
@@ -32,6 +32,7 @@ public static class Program
         {
             "custom" => text => Refused<CustomCommandsException>(() => CustomParser.Parse(text)),
             "options" => text => Refused<TazelOptionsException>(() => TazelOptionsFile.Parse(text)),
+            "envs" => text => Refused<CustomCommandsException>(() => Dsl.Envs.TazelEnvsFile.Parse(text)),
             "label" => text => Refused<LabelException>(() => Labels.Selection(text, PackageId.Root)),
             "depfile" => text => Depfiles.Inputs(text),
             "command-line" => text => Refused<CommandLineException>(() => CommandLine.Parse(text.Split('\n'))),
diff --git a/fuzz/corpus/envs/sample b/fuzz/corpus/envs/sample
new file mode 100644
index 0000000..a4e3338
--- /dev/null
+++ b/fuzz/corpus/envs/sample
@@ -0,0 +1,6 @@
+# comment
+<# comment #>
+
+example-version: '0.1.0'
+example-output: ("rustc" "--help")
+shell-expension: s(`$HOME`)
diff --git a/src/Progmasoft.Tazel.Dsl/Environment/GetEnvironment.cs b/src/Progmasoft.Tazel.Dsl/Environment/GetEnvironment.cs
new file mode 100644
index 0000000..4a5b570
--- /dev/null
+++ b/src/Progmasoft.Tazel.Dsl/Environment/GetEnvironment.cs
@@ -0,0 +1,48 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Threading;
+
+namespace Progmasoft.Tazel.Dsl.Environment;
+
+/// <summary>
+/// The values of <c>tazel_envs.txt</c>, beside the MODULE.csx of the module the project file belongs to. A value is not
+/// an environment variable: it reaches no shell, no program Tazel runs and not Tazel itself; only this class reads it.
+/// </summary>
+public static class GetEnvironment
+{
+    /// <summary>The value named <paramref name="name"/>, or null when <c>tazel_envs.txt</c> has no such name.</summary>
+    public static string? From(string name)
+    {
+        ArgumentNullException.ThrowIfNull(name);
+        return EnvironmentValues.Current?.Get(name);
+    }
+}
+
+/// <summary>Where the values of the running project file come from; Tazel sets it while the file runs.</summary>
+internal interface IEnvironmentValues
+{
+    string? Get(string name);
+}
+
+/// <summary>The values of the project file that is running.</summary>
+internal static class EnvironmentValues
+{
+    private static readonly AsyncLocal<IEnvironmentValues?> CurrentValues = new();
+
+    public static IEnvironmentValues? Current => CurrentValues.Value;
+
+    /// <summary>Makes <paramref name="values"/> those of the running file until the result is disposed.</summary>
+    public static IDisposable Enter(IEnvironmentValues? values)
+    {
+        var previous = CurrentValues.Value;
+        CurrentValues.Value = values;
+        return new Restore(() => CurrentValues.Value = previous);
+    }
+
+    private sealed class Restore(Action undo) : IDisposable
+    {
+        public void Dispose() => undo();
+    }
+}
diff --git a/src/Progmasoft.Tazel/Driver/Processes.cs b/src/Progmasoft.Tazel/Driver/Processes.cs
index a0cee24..196e9ab 100644
--- a/src/Progmasoft.Tazel/Driver/Processes.cs
+++ b/src/Progmasoft.Tazel/Driver/Processes.cs
@@ -94,6 +94,49 @@ internal static class Processes
         return new ProcessResult(process.ExitCode, Text(output));
     }
 
+    /// <summary>Runs <paramref name="command"/> and keeps what it prints apart from its errors.</summary>
+    public static async Task<(int ExitCode, string Output, string Errors)> CaptureAsync(
+        IReadOnlyList<string> command, string directory, IReadOnlyDictionary<string, string> environment, CancellationToken cancel)
+    {
+        ArgumentNullException.ThrowIfNull(command);
+        ArgumentNullException.ThrowIfNull(environment);
+        var start = new ProcessStartInfo(command[0])
+        {
+            WorkingDirectory = directory,
+            RedirectStandardOutput = true,
+            RedirectStandardError = true,
+            RedirectStandardInput = true,
+            UseShellExecute = false,
+            CreateNoWindow = true,
+        };
+        for (var i = 1; i < command.Count; i++)
+        {
+            start.ArgumentList.Add(command[i]);
+        }
+
+        start.Environment.Clear();
+        foreach (var (name, value) in environment)
+        {
+            start.Environment[name] = value;
+        }
+
+        using var process = new Process { StartInfo = start };
+        try
+        {
+            process.Start();
+        }
+        catch (Win32Exception error)
+        {
+            return (-1, "", $"{command[0]} could not be started: {error.Message}");
+        }
+
+        process.StandardInput.Close();
+        var output = process.StandardOutput.ReadToEndAsync(cancel);
+        var errors = process.StandardError.ReadToEndAsync(cancel);
+        await process.WaitForExitAsync(cancel).ConfigureAwait(false);
+        return (process.ExitCode, await output.ConfigureAwait(false), await errors.ConfigureAwait(false));
+    }
+
     /// <summary>Runs <paramref name="command"/> with the terminal of Tazel, as <c>tazel run</c> does.</summary>
     public static int RunAttached(IReadOnlyList<string> command, string directory, IReadOnlyDictionary<string, string> environment)
     {
diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs
new file mode 100644
index 0000000..87703c2
--- /dev/null
+++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs
@@ -0,0 +1,203 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using Progmasoft.Tazel.Driver;
+using Progmasoft.Tazel.Dsl.Custom;
+using Progmasoft.Tazel.Dsl.Custom.Lexer;
+using Progmasoft.Tazel.Dsl.Environment;
+
+namespace Progmasoft.Tazel.Dsl.Envs;
+
+/// <summary>A value of <c>tazel_envs.txt</c>: a string, the output of a program, or the output of a shell line.</summary>
+public abstract record EnvValue
+{
+    /// <summary>A string, as written.</summary>
+    /// <param name="Value">The string.</param>
+    public sealed record Text(string Value) : EnvValue;
+
+    /// <summary><c>("program" "argument")</c>: a program started directly; the value is what it prints.</summary>
+    /// <param name="Arguments">The program and its arguments, each string one argument.</param>
+    public sealed record Program(IReadOnlyList<string> Arguments) : EnvValue;
+
+    /// <summary><c>s("line")</c>: a line for /bin/sh, or cmd.exe on Windows; the value is what it prints.</summary>
+    /// <param name="Line">The line.</param>
+    public sealed record Shell(string Line) : EnvValue;
+}
+
+/// <summary>One entry of <c>tazel_envs.txt</c>, with where it is.</summary>
+/// <param name="Name">Its name.</param>
+/// <param name="Value">Its value.</param>
+/// <param name="Line">The line it is on.</param>
+public sealed record EnvEntry(string Name, EnvValue Value, int Line);
+
+/// <summary>
+/// Reads <c>tazel_envs.txt</c> with the lexer of <c>tazel_custom.txt</c> and <c>tazel_options.txt</c>: the same comments
+/// and strings, <c>name: value</c> one after another, a <c>;</c> after a value optional.
+/// </summary>
+public static class TazelEnvsFile
+{
+    /// <summary>The file, beside the MODULE.csx of a module.</summary>
+    public const string FileName = "tazel_envs.txt";
+
+    /// <summary>The entries of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary>
+    public static IReadOnlyList<EnvEntry> Parse(string text, string file = FileName)
+    {
+        var tokens = new CustomLexer(text, file).Tokens();
+        var entries = new List<EnvEntry>();
+        var names = new HashSet<string>(StringComparer.Ordinal);
+        var i = 0;
+        while (i < tokens.Count)
+        {
+            var name = Take(TokenKind.Name, "the name of a value");
+            if (!names.Add(name.Text))
+            {
+                throw Fail(name, $"'{name.Text}' is set twice");
+            }
+
+            Take(TokenKind.Colon, $"':' after {name.Text}");
+            EnvValue value;
+            if (Peek() is { Kind: TokenKind.String } literal)
+            {
+                i++;
+                value = new EnvValue.Text(literal.Text);
+            }
+            else if (Peek() is { Kind: TokenKind.Name, Text: "s" })
+            {
+                i++;
+                var open = Take(TokenKind.Open, "'(' after s");
+                var strings = Strings();
+                Take(TokenKind.Close, "')' after the line of s(...)");
+                value = strings.Count == 1
+                    ? new EnvValue.Shell(strings[0])
+                    : throw Fail(open, "s(...) takes one string, the whole line: s(`$HOME`)");
+            }
+            else if (Peek() is { Kind: TokenKind.Open })
+            {
+                var open = Take(TokenKind.Open, "'('");
+                var strings = Strings();
+                Take(TokenKind.Close, "')' after the strings of a program");
+                value = strings.Count > 0
+                    ? new EnvValue.Program(strings)
+                    : throw Fail(open, "a program names at least itself: (\"rustc\" \"--help\")");
+            }
+            else
+            {
+                throw Fail(Peek() ?? name, $"expected the value of {name.Text}: a string, (\"program\" \"argument\") or s(\"line\")");
+            }
+
+            entries.Add(new EnvEntry(name.Text, value, name.Line));
+            if (Peek() is { Kind: TokenKind.Semicolon })
+            {
+                i++;
+            }
+        }
+
+        return entries;
+
+        Token? Peek() => i < tokens.Count ? tokens[i] : null;
+
+        Token Take(TokenKind kind, string wanted)
+        {
+            if (Peek() is not { } token || token.Kind != kind)
+            {
+                throw Fail(Peek() ?? tokens[^1], $"expected {wanted}");
+            }
+
+            i++;
+            return token;
+        }
+
+        List<string> Strings()
+        {
+            var strings = new List<string>();
+            while (Peek() is { Kind: TokenKind.String } token)
+            {
+                i++;
+                strings.Add(token.Text);
+            }
+
+            if (Peek() is { Kind: TokenKind.Placeholder } placeholder)
+            {
+                throw Fail(placeholder, "a value of tazel_envs.txt takes no <N> or <*>");
+            }
+
+            return strings;
+        }
+
+        CustomCommandsException Fail(Token token, string message) => new($"{file}:{token.Line}:{token.Column}: {message}");
+    }
+}
+
+/// <summary>
+/// The values of one module's <c>tazel_envs.txt</c>, for <see cref="GetEnvironment.From"/>. A program or shell line runs
+/// when its value is first asked for, once per command, with Tazel's environment in the root of the module; its output,
+/// less the line endings at its end, is the value. A program that fails stops the project file that asked.
+/// </summary>
+internal sealed class ModuleEnvironment : IEnvironmentValues
+{
+    private readonly Dictionary<string, EnvEntry> _entries;
+    private readonly ConcurrentDictionary<string, Lazy<string>> _values = new(StringComparer.Ordinal);
+    private readonly string _root;
+    private readonly string _shown;
+
+    private ModuleEnvironment(string root, string shown, IReadOnlyList<EnvEntry> entries)
+    {
+        _root = root;
+        _shown = shown;
+        _entries = entries.ToDictionary(entry => entry.Name, StringComparer.Ordinal);
+    }
+
+    /// <summary>The values of the module at <paramref name="root"/>, or null when it has no <c>tazel_envs.txt</c>.</summary>
+    public static ModuleEnvironment? Load(string root, string shown)
+    {
+        var file = Path.Combine(root, TazelEnvsFile.FileName);
+        return File.Exists(file) ? new ModuleEnvironment(root, shown, TazelEnvsFile.Parse(File.ReadAllText(file), shown)) : null;
+    }
+
+    public string? Get(string name)
+    {
+        if (!_entries.TryGetValue(name, out var entry))
+        {
+            return null;
+        }
+
+        return _values.GetOrAdd(name, _ => new Lazy<string>(() => Evaluate(entry), LazyThreadSafetyMode.ExecutionAndPublication))
+            .Value;
+    }
+
+    private string Evaluate(EnvEntry entry)
+    {
+        IReadOnlyList<string> command;
+        switch (entry.Value)
+        {
+            case EnvValue.Text text:
+                return text.Value;
+            case EnvValue.Shell shell:
+                command = OperatingSystem.IsWindows()
+                    ? [System.Environment.GetEnvironmentVariable("ComSpec") ?? "cmd.exe", "/d", "/s", "/c", $"\"{shell.Line}\""]
+                    : ["/bin/sh", "-c", shell.Line];
+                break;
+            default:
+                var program = ((EnvValue.Program)entry.Value).Arguments;
+                var found = Host.Which(program[0]) ?? throw new DslException(
+                    $"{_shown}:{entry.Line}: the program '{program[0]}' of {entry.Name} is not found");
+                command = [found, .. program.Skip(1)];
+                break;
+        }
+
+        var result = Processes.CaptureAsync(command, _root, Processes.Inherited(), CancellationToken.None).GetAwaiter().GetResult();
+        if (result.ExitCode != 0)
+        {
+            throw new DslException(
+                $"{_shown}:{entry.Line}: {entry.Name} ran {command[0]}, which failed with {result.ExitCode}: {result.Errors.Trim()}");
+        }
+
+        return result.Output.TrimEnd('\r', '\n');
+    }
+}
diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs
index 519d6e7..6a8a4fc 100644
--- a/src/Progmasoft.Tazel/Project/Workspace.cs
+++ b/src/Progmasoft.Tazel/Project/Workspace.cs
@@ -19,8 +19,12 @@ namespace Progmasoft.Tazel.Project;
 internal sealed record ModuleInfo(string Group, string Name, NuGetVersion Version, ModuleDefinition Definition);
 
 /// <summary>A module whose MODULE.csx ran: the main one, or a dependency by the name its labels use.</summary>
-internal sealed class LoadedModule(string root, string? repository, ModuleGlobals globals, ModuleInfo info)
+internal sealed class LoadedModule(
+    string root, string? repository, ModuleGlobals globals, ModuleInfo info, Dsl.Envs.ModuleEnvironment? environment)
 {
+    /// <summary>The values of its <c>tazel_envs.txt</c>, or null when it has none.</summary>
+    public Dsl.Envs.ModuleEnvironment? Environment { get; } = environment;
+
     public string Root { get; } = root;
 
     public string? Repository { get; } = repository;
@@ -123,8 +127,22 @@ internal sealed class Workspace
         var file = Path.Combine(root, ModuleFiles.ModuleFile);
         var shown = repository is null ? ModuleFiles.ModuleFile : $"@{repository}//{ModuleFiles.ModuleFile}";
         var globals = new ModuleGlobals();
-        await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals)
-            .ConfigureAwait(false);
+        var envsShown = repository is null ? Dsl.Envs.TazelEnvsFile.FileName : $"@{repository}//{Dsl.Envs.TazelEnvsFile.FileName}";
+        Dsl.Envs.ModuleEnvironment? environment;
+        try
+        {
+            environment = Dsl.Envs.ModuleEnvironment.Load(root, envsShown);
+        }
+        catch (Dsl.Custom.CustomCommandsException error)
+        {
+            throw new ProjectException(error.Message, error);
+        }
+
+        using (Dsl.Environment.EnvironmentValues.Enter(environment))
+        {
+            await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals)
+                .ConfigureAwait(false);
+        }
         var definition = globals.module?.Definition
             ?? throw new ProjectException($"{shown} sets no module: module = Module.Define(new() {{ ... }});");
         if (!Labels.IsName(definition.Name))
@@ -149,7 +167,8 @@ internal sealed class Workspace
                 $"{shown} builds with Tazel {compatibility}; this is Tazel {tazelVersion.ToString(3)}");
         }
 
-        return new LoadedModule(root, repository, globals, new ModuleInfo(definition.Group, definition.Name, version, definition));
+        return new LoadedModule(root, repository, globals, new ModuleInfo(definition.Group, definition.Name, version, definition),
+            environment);
     }
 
     private static bool IsGroup(string group) =>
@@ -248,6 +267,7 @@ internal sealed class Workspace
             var scope = new DeclarationScope(package.Path, shown);
             var code = await File.ReadAllTextAsync(package.File).ConfigureAwait(false);
             using (Declarations.Enter(scope))
+            using (Dsl.Environment.EnvironmentValues.Enter(module.Environment))
             {
                 await ScriptHost.RunAsync(code, shown, new BuildGlobals(build), environment).ConfigureAwait(false);
             }
diff --git a/tests/Progmasoft.Tazel.Tests/EnvsTests.cs b/tests/Progmasoft.Tazel.Tests/EnvsTests.cs
new file mode 100644
index 0000000..9716016
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/EnvsTests.cs
@@ -0,0 +1,102 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.Dsl.Custom;
+using Progmasoft.Tazel.Dsl.Envs;
+using Progmasoft.Tazel.Project;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class EnvsTests
+{
+    private const string Sample = """
+        # comment
+        <# comment #>
+
+        example-version: '0.1.0'
+        example-output: ("rustc" "--help")
+        shell-expension: s(`$HOME`)
+        """;
+
+    [Fact]
+    public void ReadsTheThreeKindsOfValue()
+    {
+        var entries = TazelEnvsFile.Parse(Sample);
+        Assert.Equal(["example-version", "example-output", "shell-expension"], entries.Select(e => e.Name));
+        Assert.Equal(new EnvValue.Text("0.1.0"), entries[0].Value);
+        Assert.Equal(["rustc", "--help"], Assert.IsType<EnvValue.Program>(entries[1].Value).Arguments);
+        Assert.Equal(new EnvValue.Shell("$HOME"), entries[2].Value);
+        Assert.Equal(6, entries[2].Line);
+    }
+
+    [Fact]
+    public void ASemicolonAfterAValueIsAllowed() =>
+        Assert.Equal(2, TazelEnvsFile.Parse("a: 'x'; b: \"y\"").Count);
+
+    [Theory]
+    [InlineData("a: 'x'\na: 'y'", "'a' is set twice")]
+    [InlineData("a 'x'", "expected ':' after a")]
+    [InlineData("a: ()", "a program names at least itself")]
+    [InlineData("a: s('x' 'y')", "s(...) takes one string")]
+    [InlineData("a: ('echo' <1>)", "takes no <N> or <*>")]
+    [InlineData("a: b", "expected the value of a")]
+    [InlineData("a: 'x", "has no closing '")]
+    public void RefusesWhatIsWrongWithItsPlace(string text, string message)
+    {
+        var error = Assert.Throws<CustomCommandsException>(() => TazelEnvsFile.Parse(text));
+        Assert.Contains(message, error.Message, StringComparison.Ordinal);
+        Assert.StartsWith("tazel_envs.txt:", error.Message, StringComparison.Ordinal);
+    }
+
+    private const string Build = """
+        using System;
+        using Progmasoft.Tazel.Dsl.Build.Prelude;
+        using Progmasoft.Tazel.Dsl.Environment;
+        var version = GetEnvironment.From("example-version") ?? "none";
+        var shell = GetEnvironment.From("from-shell") ?? "none";
+        var program = GetEnvironment.From("from-program") ?? "none";
+        var missing = GetEnvironment.From("missing") is null ? "null" : "set";
+        var notAVariable = Environment.GetEnvironmentVariable("example-version") is null ? "not-a-variable" : "a-variable";
+        CC.StaticLibrary($"lib-{version}-{shell}-{(program == "none" ? "none" : "ran")}-{missing}-{notAVariable}", new());
+        """;
+
+    [Fact]
+    public async Task ProjectFilesReadTheValuesWithGetEnvironment()
+    {
+        using var module = new TemporaryModule()
+            .Write("MODULE.csx", TemporaryModule.ModuleFile)
+            .Write("BUILD.csx", Build)
+            .Write("tazel_envs.txt", """
+                example-version: '0.1.0'
+                from-shell: s('echo shell-said')
+                from-program: ("dotnet" "--version")
+                """);
+        var workspace = await module.LoadAsync();
+        var name = workspace.Targets.Keys.Single().Name;
+        Assert.Equal("lib-0.1.0-shell-said-ran-null-not-a-variable", name);
+    }
+
+    [Fact]
+    public async Task WithoutTheFileEveryValueIsNull()
+    {
+        using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Build);
+        var workspace = await module.LoadAsync();
+        Assert.Equal("lib-none-none-none-null-not-a-variable", workspace.Targets.Keys.Single().Name);
+    }
+
+    [Fact]
+    public async Task AProgramThatFailsStopsTheFileThatAsked()
+    {
+        using var module = new TemporaryModule()
+            .Write("MODULE.csx", TemporaryModule.ModuleFile)
+            .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Environment;\nvar x = GetEnvironment.From(\"broken\");")
+            .Write("tazel_envs.txt", "broken: s('exit 3')\n");
+        var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync());
+        Assert.Contains("tazel_envs.txt:1: broken ran", error.Message, StringComparison.Ordinal);
+        Assert.Contains("failed with 3", error.Message, StringComparison.Ordinal);
+    }
+}