TimeWarp.Amuru
3.0.0-beta.9
Prefix Reserved
See the version list below for details.
dotnet add package TimeWarp.Amuru --version 3.0.0-beta.9
NuGet\Install-Package TimeWarp.Amuru -Version 3.0.0-beta.9
<PackageReference Include="TimeWarp.Amuru" Version="3.0.0-beta.9" />
<PackageVersion Include="TimeWarp.Amuru" Version="3.0.0-beta.9" />
<PackageReference Include="TimeWarp.Amuru" />
paket add TimeWarp.Amuru --version 3.0.0-beta.9
#r "nuget: TimeWarp.Amuru, 3.0.0-beta.9"
#:package TimeWarp.Amuru@3.0.0-beta.9
#addin nuget:?package=TimeWarp.Amuru&version=3.0.0-beta.9&prerelease
#tool nuget:?package=TimeWarp.Amuru&version=3.0.0-beta.9&prerelease
<p align="center"><img src="assets/mascot/amuru-hero.png" alt="Amuru, the TimeWarp Amuru mascot" width="240" /></p>
<img src="https://raw.githubusercontent.com/TimeWarpEngineering/timewarpengineering.github.io/refs/heads/master/images/LogoNoMarginNoShadow.svg" alt="logo" height="120" style="float: right" />
TimeWarp.Amuru
Amuru means "command" in Swahili
TimeWarp.Amuru is a fluent API library for elegant command-line execution in C#. It transforms shell scripting into a type-safe, IntelliSense-friendly experience with a simple static Builder() method, async operations, and shell-like error handling.
Designed for modern C# developers, TimeWarp.Amuru brings the power of shell scripting directly into your C# code. Whether you're building automation tools, DevOps scripts, or integrating command-line tools into your applications, TimeWarp.Amuru provides the elegant, type-safe API you need.
Why TimeWarp.Amuru?
- Zero Learning Curve: If you know C#, you already know how to use TimeWarp.Amuru
- IntelliSense Everything: Full IDE support with autocomplete, parameter hints, and documentation
- Type Safety: Catch errors at compile-time, not runtime
- No String Escaping Hell: Use C# arrays and parameters naturally
- Native AOT Ready: Both packages declare and validate AOT/trimming compatibility
- JSON-RPC 2.0: Request and response over a child process, with
System.Text.Jsonand no Newtonsoft.Json dependency - Built for .NET 11: Modern C# features and first-class file-based app (runfile) support
- Script or Library: Use it in quick scripts or production applications
Give a Star! ⭐
If you find this project useful, please give it a star. Thanks!
Installation
# Core library: process execution, mocking, native file and text operations
dotnet add package TimeWarp.Amuru
# Optional: fluent builders for dotnet/gh/git/fzf plus repo services
dotnet add package TimeWarp.Amuru.Tools
This readme documents the 2.0 API, first available in 2.0.0. See the 2.0 release notes. The package version is 3.0.0-beta.4. See the 3.0.0-beta.4 release notes.
Or reference in your C# runfile:
#:package TimeWarp.Amuru@<latest-version>
Both packages share the TimeWarp.Amuru namespace — adding the Tools reference lights up DotNet.*, Git.*, and Fzf.* with no code changes.
Optional: CLI Tools
# Global CLI tool with additional utilities (private package)
dotnet tool install --global TimeWarp.Ganda --source https://nuget.pkg.github.com/TimeWarpEngineering/index.json
See the Ganda repository for details.
Quick Start
#!/usr/bin/dotnet --
#:package TimeWarp.Amuru
using TimeWarp.Amuru;
using static System.Console;
// Default behavior - stream to console (like bash/PowerShell)
await Shell.Builder("npm").WithArguments("install").RunAsync();
// Capture output when needed
CommandOutput result = await Shell.Builder("git").WithArguments("status").CaptureAsync();
if (result.Success)
{
WriteLine($"Git says: {result.Stdout}");
}
// Stream large files without memory issues
await foreach (string line in Shell.Builder("tail").WithArguments("-f", "/var/log/app.log").StreamStdoutAsync())
{
WriteLine($"Log: {line}");
}
// Chain commands with pipelines
CommandOutput found = await Shell.Builder("find")
.WithArguments(".", "-name", "*.cs")
.Pipe("grep", "async")
.CaptureAsync();
WriteLine($"Found {found.GetLines().Length} async lines");
// Work with CommandOutput
CommandOutput output = await Shell.Builder("docker").WithArguments("ps").CaptureAsync();
WriteLine($"Exit code: {output.ExitCode}");
WriteLine($"Success: {output.Success}");
WriteLine($"Stdout: {output.Stdout}");
WriteLine($"Stderr: {output.Stderr}");
WriteLine($"Combined: {output.Combined}");
// Use the fluent builder API for complex commands
CommandOutput log = await Shell.Builder("git")
.WithArguments("log", "--oneline", "-n", "10")
.WithWorkingDirectory("/my/repo")
.CaptureAsync(cancellationToken);
// Provide standard input to commands
CommandOutput grepResult = await Shell.Builder("grep")
.WithArguments("pattern")
.WithStandardInput("line1\nline2 with pattern\nline3")
.CaptureAsync();
// Full interactive mode for stream-based tools (fzf, REPLs)
await Shell.Builder("fzf").PassthroughAsync();
// TUI applications (vim, nano, edit) need true TTY passthrough
await Shell.Builder("vim")
.WithArguments("myfile.txt")
.TtyPassthroughAsync();
Tool Builders (TimeWarp.Amuru.Tools)
// Global dotnet options
CommandOutput sdks = await DotNet.WithListSdks().CaptureAsync();
CommandOutput version = await DotNet.WithVersion().CaptureAsync();
// Base builder for custom arguments
CommandOutput custom = await DotNet.Builder()
.WithArguments("--list-runtimes")
.CaptureAsync();
// Build and test with streaming output
await DotNet.Build()
.WithConfiguration("Release")
.RunAsync();
await DotNet.Test()
.WithFilter("Category=Unit")
.RunAsync();
// Git operations with typed results
string? repoRoot = Git.FindRoot();
GitWorktreeListResult listed = await Git.WorktreeListPorcelainAsync("/my/repo");
IReadOnlyList<WorktreeEntry> worktrees = listed.Success
? Git.ParseWorktreeList(listed.Porcelain ?? "")
: [];
// GitHub CLI with a span per call (see "GitHub CLI Spans")
GhRunListResult runs = await Gh.Run().List()
.WithRepo("TimeWarpEngineering/timewarp-amuru")
.WithWorkflow("workflow.yml")
.WithLimit(5)
.ListRunsAsync();
// Interactive selection with Fzf
string selectedFile = await Fzf.Builder()
.FromInput("file1.txt", "file2.txt", "file3.txt")
.WithPreview("cat {}")
.SelectAsync();
Key Features
- Shell-Like Default:
RunAsync()streams to console just like bash/PowerShell - Explicit Capture:
CaptureAsync()for when you need to process output - Memory-Efficient Streaming:
IAsyncEnumerablefor large data without buffering - One Result Type:
CommandOutputwith Stdout, Stderr, Combined, ExitCode, Success, and RunTime — from every execution mode - Shell-Like Error Handling: non-zero exit codes are values, not exceptions; strict validation is one opt-in call away
- Built-In Command Mocking:
CommandMockwith strict-by-default matching — tests can never silently run real commands - Pipeline Support: Chain commands with Unix-like pipe semantics
- Standard Input Support: Provide stdin to commands with
.WithStandardInput()(text) or.WithStandardInputFile()(a file, streamed) - Stdout Tee:
.WithStandardOutputTee(path)copies stdout to a file byte for byte as it arrives, while the normal capture still works - NO CACHING Philosophy: Like shells, commands run fresh every time
- Cancellation Support: Full CancellationToken support throughout
- Per-command timeout: a child that exits during the grace period keeps its own exit code; if the grace period elapses,
WithTimeoutreportsTimedOutand exit 124. A descendant that holds a pipe is cut off at the armed deadline with the child's code. A caller cancellation token still cancels - Cross-Platform: Works on Windows, Linux, and macOS (including
.csscript execution on Windows via the dotnet host) - Interactive Commands:
PassthroughAsync()for stream-based tools,TtyPassthroughAsync()for TUI apps (vim, nano),SelectAsync()for selection tools - .NET 11 Script Support: AppContext extensions and ScriptContext for file-based apps
- Native text:
SelectString(grep) andReplaceInFiles(in-place replace) underTimeWarp.Amuru.Native.Text, withGrep/Sedbash aliases. See Native text commands
Output Handling
Core API Methods
// RunAsync() - Default shell behavior, streams to console
await Shell.Builder("npm").WithArguments("install").RunAsync();
// Returns: exit code (int)
// CaptureAsync() - Silent execution with full output capture
CommandOutput result = await Shell.Builder("git").WithArguments("status").CaptureAsync();
// Returns: CommandOutput; no console output
// RunAndCaptureAsync() - Stream to console AND capture
CommandOutput logged = await Shell.Builder("dotnet").WithArguments("build").RunAndCaptureAsync();
// PassthroughAsync() - Stream-based interactive tools (fzf, REPLs)
CommandOutput fzfResult = await Shell.Builder("fzf").PassthroughAsync();
// TtyPassthroughAsync() - True TTY for TUI applications (vim, nano, edit)
CommandOutput vimResult = await Shell.Builder("vim").WithArguments("file.txt").TtyPassthroughAsync();
// SelectAsync() - Selection tools (shows UI on stderr, captures stdout selection)
string selected = await Shell.Builder("fzf").SelectAsync();
The CommandOutput Type
CommandOutput output = await Shell.Builder("docker").WithArguments("ps").CaptureAsync();
// Access individual streams
Console.WriteLine($"Stdout: {output.Stdout}");
Console.WriteLine($"Stderr: {output.Stderr}");
Console.WriteLine($"Combined: {output.Combined}"); // Captured in arrival order
// Check status
Console.WriteLine($"Exit code: {output.ExitCode}");
Console.WriteLine($"Success: {output.Success}"); // ExitCode == 0
Console.WriteLine($"Runtime: {output.RunTime}");
// Line processing (interior blank lines preserved; no trailing empty entry)
foreach (string line in output.GetLines())
{
ProcessLine(line);
}
// Or line-level access with source-stream metadata
foreach (OutputLine line in output.OutputLines)
{
Console.WriteLine($"{(line.IsError ? "ERR" : "OUT")}: {line.Text}");
}
// Pretty-print a result with status coloring
output.WriteToConsole();
Streaming Large Data
// Stream lines as they arrive (no buffering)
await foreach (string line in Shell.Builder("tail")
.WithArguments("-f", "/var/log/app.log")
.StreamStdoutAsync(cancellationToken))
{
Console.WriteLine($"Log: {line}");
}
Method Comparison
| Method | Console Output | Captures | Returns | Primary Use Case |
|---|---|---|---|---|
RunAsync() |
✅ Real-time | ❌ | Exit code | Default scripting |
CaptureAsync() |
❌ Silent | ✅ All streams | CommandOutput | Process output |
RunAndCaptureAsync() |
✅ Real-time | ✅ All streams | CommandOutput | Logging + capture |
PassthroughAsync() |
✅ Piped | ❌ | CommandOutput | Stream-based interactive |
TtyPassthroughAsync() |
✅ TTY | ❌ | CommandOutput | TUI apps (vim, nano) |
SelectAsync() |
✅ UI only | ✅ Selection | string | Selection tools |
StreamStdoutAsync() |
❌ | ✅ As stream | IAsyncEnumerable | Large data |
Design Philosophy: NO CACHING
TimeWarp.Amuru intentionally does NOT cache command results:
// Shells don't cache - neither do we
await Shell.Builder("date").RunAsync(); // Shows current time
await Shell.Builder("date").RunAsync(); // Shows NEW current time
// If you need caching, it's trivial in C#:
private static CommandOutput? cachedResult;
CommandOutput result = cachedResult ??= await Shell.Builder("expensive-command").CaptureAsync();
Error Handling
TimeWarp.Amuru handles failure the way shells do: a non-zero exit code is a value you inspect, not an exception.
Default Behavior (Never Throws on Exit Codes)
CommandOutput result = await Shell.Builder("ls").WithArguments("/nonexistent").CaptureAsync();
if (!result.Success)
{
Console.WriteLine($"Command failed with exit code: {result.ExitCode}");
Console.WriteLine($"Error: {result.Stderr}");
}
Strict Validation (Opt-in Throwing)
// Throws on any non-zero exit code
await Shell.Builder("git")
.WithArguments("push")
.WithZeroExitCodeValidation()
.RunAsync();
Commands That Never Ran
An empty/invalid command or a failed pipeline composition never throws, but it is never mistaken for success either — it reports CommandResult.NeverRanExitCode (-1):
CommandOutput result = await Shell.Builder("").CaptureAsync();
// result.Success == false, result.ExitCode == CommandResult.NeverRanExitCode
Note: a missing executable (e.g. a typo'd command name) still throws at execution time — that is an environment error, not an exit code.
Cancellation and Timeouts
// With explicit cancellation token
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(30));
await Shell.Builder("long-running-command").RunAsync(cts.Token);
// Per-command limit. Default validation reports the timeout instead of throwing.
CommandOutput output = await Shell.Builder("long-running-command")
.WithTimeout(TimeSpan.FromSeconds(30))
.CaptureAsync();
// output.TimedOut is true and output.ExitCode is 124 when the grace period elapses.
// A child that exits during the grace period keeps its own exit code and TimedOut stays false.
Trace Context Propagation
When Activity.Current is set at the moment a command starts, Amuru sets TRACEPARENT (and TRACESTATE when the activity has one) on the child process, so the child's spans join your trace. Every launch path does this, including pipelines, TtyPassthroughAsync, and AsJsonRpcClient. There is nothing to call. With no current activity, the child keeps whatever TRACEPARENT your process inherited.
A value you set wins. To opt a child out, remove the variables:
await Shell.Builder("tool")
.WithEnvironmentVariable("TRACEPARENT", null)
.WithEnvironmentVariable("TRACESTATE", null)
.RunAsync();
GitHub CLI Spans
gh emits no OpenTelemetry of its own. The Gh builders in TimeWarp.Amuru.Tools open one span per execution (RunAsync, CaptureAsync, RunAndCaptureAsync, PassthroughAsync, and the typed methods) on the ActivitySource named Gh.ActivitySourceName (TimeWarp.Amuru.Gh). Subscribe to it, for example in Nuru's UseTelemetry activity sources, and each gh call shows up as a child of your span, with TRACEPARENT naming it.
| Builder | Command |
|---|---|
Gh.Run().List() / .Download(runId) |
gh run list / gh run download |
Gh.Api(endpoint) |
gh api |
Gh.Auth().Token() / .Status() |
gh auth token / gh auth status |
Gh.Issue().List() / .Create() |
gh issue list / gh issue create |
Gh.Pr().View() / .Checks() / .Create() / .Merge() |
gh pr view / checks / create / merge |
Gh.Release().List() / .Create(tag) |
gh release list / gh release create |
WithRepo, WithJson, WithJq, and WithLimit are on the builders whose gh command takes them. WithArgument appends a flag a builder does not model.
The span is named gh <verb> <sub-verb> (gh run list, gh api) and carries gh.command, gh.repo (when WithRepo is set), gh.api.endpoint (the path only, no query string or host), gh.exit_code, and gh.elapsed_ms. A non-zero exit sets Error status. Arguments, field values, bodies, stdout (the auth token output), and exception text never reach the span. Build() returns the CommandResult without a span.
GhAuthStatus auth = await Gh.Auth().Status().GetStatusAsync(); // SignedIn, Host, Login
GhPullRequestViewResult pr = await Gh.Pr().View("42").ViewPullRequestAsync();
CommandOutput artifacts = await Gh.Api("repos/{owner}/{repo}/actions/runs/123/artifacts").CaptureAsync();
ListRunsAsync, ViewPullRequestAsync, and GetStatusAsync return typed results; every other call returns the raw CommandOutput.
Analyzers
TimeWarp.Amuru ships a Roslyn analyzer (analyzers/dotnet/cs), so every consumer gets these
diagnostics at compile time. They fire on Shell.Builder(...) and Shell.Run(...) when the
executable is a string literal or a constant. A computed executable is not reported.
| Id | Default | Reports |
|---|---|---|
AMURU0001 |
error | dotnet with a verb that has a typed builder, for example Use DotNet.Run() (TimeWarp.Amuru.Tools) instead of Shell.Builder("dotnet") with "run". When the verb cannot be read, the message names the DotNet.* builders. Also gh with a command a Gh builder covers (gh run list → Gh.Run().List()); the sub-verb must be the second argument, and other gh commands are not reported. |
AMURU0002 |
warning | dotnet with a verb that has no typed builder yet. File a task in timewarp-amuru for one. For a local tool (dotnet fixie), the message also points at DotNet.Tool().Run(...). |
AMURU0003 |
info | git with the exact command line an existing Git.* helper runs, for example git worktree add <path> <branch> → Git.WorktreeAddAsync(). Another flag, ref, remote, or extra argument is a different operation and is not reported, and neither is a call whose arguments the analyzer cannot see in full (a spread, an array variable, a builder stored for later). |
The typed builders live in TimeWarp.Amuru.Tools. A project that references only
TimeWarp.Amuru adds that package to fix the diagnostic. The verb-to-builder table is
TypedBuilderTable in source/timewarp-amuru-analyzers; a test fails when it drifts from the
public DotNet or Gh surface.
Change a severity per repository in .editorconfig:
[*.cs]
# Make the git hint a warning in this repo.
dotnet_diagnostic.AMURU0003.severity = warning
Where a raw shell is the point, suppress the one call and say why:
// The nested dotnet run is the tool's own command line; DotNet.Tool() does not cover it yet.
#pragma warning disable AMURU0001
await Shell.Builder("dotnet").WithArguments("tool", "run", "x", "--", "dotnet", "run").RunAsync();
#pragma warning restore AMURU0001
Testing and Mocking
CommandMock (Recommended)
CommandMock intercepts command execution in-process — no mock executables needed. It is strict by default: a command with no matching setup throws instead of silently running the real thing.
using TimeWarp.Amuru.Testing;
using (CommandMock.Enable())
{
CommandMock.Setup("git", "status")
.Returns("On branch main\nnothing to commit");
CommandOutput output = await Shell.Builder("git").WithArguments("status").CaptureAsync();
// output.Stdout == "On branch main\nnothing to commit" — no real git ran
CommandMock.VerifyCalled("git", "status");
}
// Simulate failures and exceptions
using (CommandMock.Enable())
{
CommandMock.Setup("git", "push").ReturnsError("remote: Permission denied", 128);
CommandMock.Setup("flaky-tool").Throws(new TimeoutException("simulated"));
CommandMock.Setup("slow-tool").Delays(TimeSpan.FromSeconds(2));
// ...
}
// Mixed mocked + real commands (opt out of strict mode)
using (CommandMock.Enable(MockBehavior.Loose))
{
CommandMock.Setup("deploy-tool").Returns("deployed");
// unmocked commands fall through to real execution
}
Mocking is scoped per async context (parallel tests stay isolated) and covers every execution mode — run, capture, streaming, select, and passthrough. Pipe compositions are the documented exception (use loose mode).
CliConfiguration (Path Overrides)
For cases where you want a real replacement executable, redirect a command process-wide:
CliConfiguration.SetCommandPath("fzf", "/tmp/mock-bin/fzf");
// ... code using fzf now runs the replacement ...
CliConfiguration.Reset();
API: SetCommandPath, ClearCommandPath, Reset, HasCustomPath, AllCommandPaths. Overrides are process-global by design — use CommandMock for per-test isolation.
.NET 11 File-Based App Support
TimeWarp.Amuru provides specialized support for .NET 11 file-based apps (single-file C# scripts):
- AppContext Extensions —
AppContext.EntryPointFilePath()/EntryPointFileDirectoryPath()without magic strings - ScriptContext — scoped working-directory management with cleanup on dispose or process exit (contexts nest safely)
.csas a command —Shell.Builder("script.cs")runs another runfile (shebang on Unix, dotnet host on Windows)
📖 See the documentation for detailed usage guides and examples.
Architecture
- Static Entry Point: Minimal ceremony with
Shell.Builder()/Shell.Run() - Two Packages, One Namespace:
TimeWarp.Amuru(core) andTimeWarp.Amuru.Tools(tool builders); both ship together at one version - Shell Semantics: exit codes are values; composition never throws; nothing is cached
- Predictable Error Handling: never-ran, non-zero-exit, and environment failures are all distinguishable
- Opt-in Complexity: Advanced features available when needed
See our Architectural Decision Records for detailed design rationale.
Documentation
- Documentation overview - Entry point to conceptual, developer, and user docs
- Native text commands -
SelectStringandReplaceInFiles - Migration Guide - Guide for migrating from older versions
- command-extensions.cs - Collocated command construction design documentation
- command-result.cs - Collocated command execution design documentation
- Samples - Compiling example scripts referenced against the live source
Unlicense
This project is licensed under the Unlicense.
Related Packages
- TimeWarp.Amuru.Tools - Fluent dotnet/git/fzf builders and repo services on top of this library
- TimeWarp.Multiavatar - Avatar generation library (repository)
- TimeWarp.Ganda - Shell toolkit CLI (private, separate repository)
Contributing
Your contributions are welcome! Before starting any work, please open a discussion.
See our Kanban board for current development tasks and priorities.
Contact
If you have an issue and don't receive a timely response, feel free to reach out on our Discord server.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- CliWrap (>= 3.10.5)
- TimeWarp.Ramani (>= 1.0.0-beta.24)
- TimeWarp.Terminal (>= 2.0.0-beta.2)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on TimeWarp.Amuru:
| Package | Downloads |
|---|---|
|
TimeWarp.Nuru
Route-based CLI framework for .NET - batteries included with telemetry, REPL, and shell completion |
|
|
TimeWarp.Jaribu
Lightweight testing helpers for single-file C# programs and scripts. Jaribu (Swahili: test/trial) provides TestRunner pattern and assertion helpers for executable .cs files. |
|
|
TimeWarp.Amuru.Tools
Fluent builders for common CLI tools (dotnet, gh, git, fzf) plus TimeWarp repo services, built on TimeWarp.Amuru |
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on TimeWarp.Amuru:
| Repository | Stars |
|---|---|
|
TimeWarpEngineering/timewarp-nuru
Route-based CLI framework for .NET - Nuru means 'light' in Swahili
|
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.0-beta.10 | 290 | 11/18/2026 |
| 3.0.0-beta.9 | 218 | 11/18/2026 |
| 3.0.0-beta.5 | 472 | 11/15/2026 |
| 3.0.0-beta.4 | 93 | 11/15/2026 |
| 3.0.0-beta.3 | 76 | 11/15/2026 |
| 3.0.0-beta.2 | 1,162 | 11/9/2026 |
| 3.0.0-beta.1 | 483 | 11/1/2026 |
| 2.0.0 | 2,972 | 10/14/2026 |
| 2.0.0-beta.2 | 521 | 10/6/2026 |
| 2.0.0-beta.1 | 587 | 10/5/2026 |
| 1.1.1 | 502 | 9/23/2026 |
| 1.1.0 | 127 | 9/23/2026 |
| 1.0.0 | 3,816 | 7/5/2026 |
| 1.0.0-beta.35 | 118 | 7/5/2026 |
| 1.0.0-beta.34 | 855 | 5/27/2026 |
| 1.0.0-beta.33 | 129 | 5/13/2026 |
| 1.0.0-beta.32 | 3,925 | 4/26/2026 |
| 1.0.0-beta.31 | 91 | 4/25/2026 |
| 1.0.0-beta.30 | 98 | 4/14/2026 |
| 1.0.0-beta.29 | 111 | 4/13/2026 |