CLI tools and system access
Build a command-line tool: read its arguments and environment, find the
user’s config directories, run child processes and log what happens. The
bricks live in std/sys (process, cli, env, sys, sysinfo) and in std/system/log.
How argv is laid out
Before any helper, it helps to see what the runtime hands main. The
program name always sits at index 0, and every token the user typed
follows it:
command line: axle build --verbose src/main.axle
│ │ │ │
argv index: 0 1 2 3
process::argc() == 4 (count includes the program name)
process::argAt(3) == "src/main.axle"
process::argAt(9) → throws IndexOutOfBoundsException Everything below is a view over that vector: process returns it raw, cli interprets flags inside it.
Command-line arguments
use std::sys::process;
fn main() : i32 ! IndexOutOfBoundsException {
let n : i32 = process::argc();
let prog : string = process::programName();
let mut i : i32 = 0;
while (i < n) {
let a : string = process::argAt(i);
// … inspect a …
i = i + 1;
}
return 0;
} | Function | Returns | Notes |
|---|---|---|
process::argc() | i32 | number of tokens, including the program name |
process::argAt(i) | string | the i-th token; throws IndexOutOfBoundsException out of range |
process::programName() | string | the same value as argAt(0), named for clarity |
Flag and option parsing
std/sys/cli ships small helpers for ad-hoc parsing:
use std::sys::cli;
fn main() : i32 {
if (cli::argParseFlag("verbose")) {
// -verbose / --verbose mode
}
if (cli::argHasOption("input")) {
let path : string = cli::argParseOption("input");
// …
}
let firstPos : i32 = cli::argFirstPositional();
// firstPos is the index of the first non-flag argument, or -1
return 0;
} Pass the bare name: "verbose", not "--verbose". The helpers add the
dashes themselves:
| Helper | Matches | Does not match |
|---|---|---|
argParseFlag(name) | --name or -name, as a separate token | --name=value (that is an option) |
argHasOption(name) | --name=value, -name=value, or --name value (value in the next token) | a flag with no value |
argParseOption(name) | the value of the option, in either spelling above | any other token |
argFirstPositional() | index of the first token that does not start with - | — returns -1 when there is none |
Note
argFirstPositional()skips only the flags themselves. An option written in the separated form (--config app.toml) leavesapp.tomllooking like a positional, soargFirstPositional()can return the index of an option’s value. Check options first, or walkargAtyourself.
For a real CLI with subcommands, build a dispatcher on top of process::argc and process::argAt: they give you the raw vector, and the
helpers above only answer the questions listed in the table.
Environment variables
use std::sys::process;
fn main() : i32 ! IllegalStateException {
let term : string = process::getEnv("TERM"); // "" if absent
if (process::hasEnv("DEBUG")) {
// explicit presence check: useful for "set but empty"
}
process::setEnv("MY_APP_KEY", "value");
let fallback : string = process::envOrDefault("PORT", "8080");
process::unsetEnv("OLD_VAR");
return 0;
} getEnv(key) returns "" for a missing variable. Combine it with hasEnv to tell “missing” apart from “present but empty”. envOrDefault(key, fallback) does the usual two-step in one call.
setEnv and unsetEnv change the process-wide environment, and child
processes started afterwards inherit the change.
Standard paths
use std::sys::env;
fn main() : i32 ! IOException {
let home : string = env::homeDir(); // /home/user, C:\Users\user, /Users/user
let temp : string = env::tempDir(); // /tmp, %TEMP%, /var/folders/...
let config : string = env::configDir(); // $XDG_CONFIG_HOME / %APPDATA% / ~/Library/...
let cache : string = env::cacheDir();
let data : string = env::dataDir();
let exe : string = env::currentExe(); // absolute path of the running binary
return 0;
} Use these instead of hard-coded paths: each one follows the convention of
the host, so there is no if (sys::osName() == "Linux") ladder to maintain.
Each returns "" when the host names no such convention. None of them
carries a trailing separator, so join with Path or with sys::fileSeparator() rather than assuming one is there. A variable set to
the empty string counts as unset: it names no directory, so the next
fallback is used.
Process introspection
use std::sys::process;
fn main() : i32 ! IOException {
let pid : i64 = process::pid();
let parent : i64 = process::parentPid();
let cwd : string = process::cwd();
process::chdir("/tmp"); // throws IOException
println(pid.toString() + parent.toString() + cwd);
return 0;
} chdir changes the working directory of the current process only. pid, parentPid and argc, hasEnv are in the prelude, so they also
resolve without the use line.
OS info
use std::sys;
fn main() : i32 {
let name : string = sys::osName(); // "Linux" / "Windows" / "macOS"
let arch : string = sys::osArch(); // "x86_64" / "aarch64"
let nl : string = sys::lineSeparator(); // "\n" or "\r\n"
let sep : string = sys::fileSeparator(); // "/" or "\\"
let psep : string = sys::pathSeparator(); // ":" or ";"
return 0;
} lineSeparator() is the platform-native newline. Use it when writing files
for human readers; for protocols and config parsers, hard-code "\n" so
the consumer does not get a surprise.
Host facts: std/sys/sysinfo
std/sys/sysinfo answers questions about the machine itself:
use std::sys::sysinfo::cpuCount;
use std::sys::sysinfo::hostname;
use std::sys::sysinfo::totalMemory;
fn main() : i32 ! UnsupportedOperationException {
let cores : i32 = cpuCount();
let host : string = hostname();
let ram : i64 = totalMemory(); // throws where the host does not report it
return cores;
} | Function | Returns | Notes |
|---|---|---|
cpuCount() | i32 | logical CPUs |
pageSize() | i64 | memory page size in bytes |
hostname() | string | the machine name |
username() | string | the user running the process |
exePath() | string | absolute path of the running binary |
totalMemory() | i64 | throws UnsupportedOperationException on hosts that do not report it |
availableMemory() | i64 | same contract as totalMemory() |
Exit codes
fn sanityCheckFailed() : bool {
return false;
}
fn main() : i32 {
if (sanityCheckFailed()) {
exit(2); // explicit exit code
}
return 0;
} Returning a non-zero i32 from main and calling exit(code) both set the
process status. exit is in the prelude. Reach for it when you want to stop
from deep inside the call stack.
process::abort() raises SIGABRT. It does not flush buffers and does not
run destructors or defer blocks, so use it only when continuing would be
worse than stopping uncleanly. Otherwise prefer exit.
Sleeping and timing
fn work() : void {
}
fn main() : i32 {
sleep(500); // milliseconds
let start : i64 = nanoTime(); // monotonic
work();
let elapsedNs : i64 = nanoTime() - start;
println(elapsedNs.toString());
return 0;
} now(), nanoTime(), sleep(ms) and exit(code) are in the prelude.
sleep(ms) called from a task parks that task on a timer, so the other
tasks of its carrier run through the pause. Called outside any task (in main, or in a Thread::run body) it pauses the calling thread. Because
it parks, an async fn may not call it (E0767). An async fn that
needs to wait uses a timer the event loop can interleave instead: await Async::sleep(ms), see Async I/O.
See numeric & time for LocalDateTime and wall-clock
formatting.
Running a child process
use std::sys::process::ProcessBuilder;
use std::sys::process::Process;
fn main() : i32 ! IOException {
let pb : ProcessBuilder = new ProcessBuilder("ls")
.addArg("-la")
.addArg("/tmp")
.inheritIO(); // forwards child stdio to our stdout/stderr
let p : Process = pb.start();
defer p.close(); // kills the child if still running, then releases it
let exitCode : i32 = p.waitFor();
return exitCode;
} A child goes through three states, and each builder call sits before the first of them:
ProcessBuilder ──start()──▶ running ──waitFor()──▶ exited ──close()──▶ released
(addArg, setEnv, │ │
setDirectory, inheritIO) │ destroy() │ exitValue()
▼ ▼
killed (SIGKILL) status available ProcessBuilder is fluent: each setter returns the same builder. start() launches the child and yields a Process handle.
Capturing stdout and stderr
Drop inheritIO() to capture the output instead:
use std::sys::process::Process;
use std::sys::process::ProcessBuilder;
fn main() : i32 ! IOException {
let p : Process = new ProcessBuilder("git")
.addArg("rev-parse")
.addArg("HEAD")
.start();
defer p.close();
let exitCode : i32 = p.waitFor();
let sha : string = p.getStdout();
let err : string = p.getStderr();
println(sha + err);
return exitCode;
} Read the output after waitFor(). Capture is meant for small outputs: a
child that prints a lot while you are not reading it is not drained by a
streaming reader, because there is no streaming API (see the Limits table).
Setting the child’s env and directory
use std::sys::process::Process;
use std::sys::process::ProcessBuilder;
fn main() : i32 ! IOException {
let p : Process = new ProcessBuilder("./run.sh")
.setDirectory("/var/app")
.setEnv("CONFIG", "/etc/app.conf")
.setEnv("DEBUG", "1")
.start();
defer p.close();
return p.waitFor();
} setDirectory sets the child’s working directory; the parent’s is
unaffected. setEnv adds to the environment the child inherits.
Terminating a child
use std::sys::process::Process;
use std::sys::process::ProcessBuilder;
fn main() : i32 ! IOException {
let p : Process = new ProcessBuilder("longRunning").start();
defer p.close();
if (p.isAlive()) {
p.destroy(); // forcible kill: SIGKILL on Unix
}
return 0;
} destroy() terminates the child forcibly (SIGKILL on Unix; the child gets
no chance to clean up). close() is the same act as destroy(), so defer p.close() gives you “kill on scope exit”.
Overlapping two children
waitFor() waits until the child exits. From a task it parks that task
while a runtime worker reaps the child, so the carrier keeps running its
other tasks; outside a task it blocks the thread. An async fn may not call
it (E0767).
The children themselves run in parallel because the OS schedules them. Start every child first and wait afterwards:
use std::sys::process::Process;
use std::sys::process::ProcessBuilder;
fn main() : i32 ! IOException {
let a : Process = new ProcessBuilder("./build.sh").inheritIO().start();
defer a.close();
let b : Process = new ProcessBuilder("./lint.sh").inheritIO().start();
defer b.close();
return a.waitFor() + b.waitFor(); // both ran while we reaped the first
} Both children are launched before either is reaped, so the two commands run
side by side. Wrapping each waitFor() in a spawn would give each wait a
task of its own, so the two waits overlap inside the runtime as well.
Logging
use std::system::log; // bind the module: call everything through log::
use std::system::log::LogLevel; // the enum type, needed to name a level
fn main() : i32 {
log::setLevel(LogLevel::INFO); // TRACE / DEBUG / INFO / WARN / ERROR
log::trace("very chatty"); // suppressed below INFO
log::debug("variable details"); // suppressed
log::info("starting up");
log::warn("config file missing: using defaults");
log::error("connection failed");
if (log::isEnabled(LogLevel::DEBUG)) {
// build an expensive debug message only if debug is on
}
return 0;
} Bind the module once with use std::system::log; and reach every function
through log::. The extra use line imports the LogLevel enum type, which
you need to spell a level (LogLevel::INFO).
Each call writes one line to stderr, with a millisecond timestamp and the
level prefix. Levels are the LogLevel enum: TRACE = 0, DEBUG = 10, INFO = 20, WARN = 30, ERROR = 40.
| Call | Effect |
|---|---|
log::setLevel(LogLevel::INFO) | set the process-wide threshold (default INFO) |
log::getLevel() | read the current LogLevel back |
log::trace/debug/info/warn/error(msg) | emit at that level; dropped below the threshold |
log::isEnabled(LogLevel::DEBUG) | true if a call at that level would emit |
Calls below the threshold are dropped before the message is formatted.
Conditional expensive logging
use std::system::log;
use std::system::log::LogLevel;
use std::text::StringBuilder;
fn main() : i32 {
if (log::isEnabled(LogLevel::DEBUG)) {
let sb : StringBuilder = new StringBuilder();
sb.append("dump: ");
// … expensive serialization …
log::debug(sb.toString());
}
return 0;
} log::debug(msg) receives its argument already built: the level gate is
inside the helper, so the argument is evaluated before the call decides to
drop it. Guard expensive message-building with an explicit log::isEnabled check.
System properties
A small key/value store for runtime configuration:
use std::sys;
fn main() : i32 {
if (sys::hasProperty("axle.profile")) {
let p : string = sys::getProperty("axle.profile");
// …
}
sys::setProperty("my.key", "value");
return 0;
} Properties are process-local and not persisted. They are closer to
environment variables in spirit, but they are kept apart so that user code
can store its own defaults without colliding with the OS environment.
Child processes do not inherit them; use process::setEnv for that.
Putting it together: a small CLI skeleton
use std::sys::process;
use std::sys::cli;
use std::sys::env;
use std::system::log;
use std::system::log::LogLevel;
fn main() : i32 ! IOException, IndexOutOfBoundsException {
if (cli::argParseFlag("help")) {
printHelp();
return 0;
}
let mut level : LogLevel = LogLevel::INFO;
if (cli::argParseFlag("verbose")) { level = LogLevel::DEBUG; }
if (cli::argParseFlag("quiet")) { level = LogLevel::WARN; }
log::setLevel(level);
let cfg : string = cli::argHasOption("config")
? cli::argParseOption("config")
: env::configDir() + "/myapp/config.toml";
log::info("loading config from " + cfg);
let firstPos : i32 = cli::argFirstPositional();
if (firstPos < 0) {
log::error("no positional argument");
return 1;
}
let target : string = process::argAt(firstPos);
return runCommand(target);
}
fn printHelp() : void {
// emit a usage string to stdout
}
fn runCommand(name : string) : i32 {
return 0;
} The skeleton reads its flags first, configures logging, resolves a config path and then dispatches on the first positional argument. Each part is one of the sections above.
Limits / Uncabled
| Feature | State | Workaround |
|---|---|---|
| Streaming a child’s output while it runs | Not provided: Process exposes getStdout() and getStderr() after the child exits | inheritIO() to forward the output, or capture after waitFor() for small outputs |
| Starting a child with an empty environment | No API: setEnv only adds to the inherited environment | Wrap the command in a script that clears what it needs to |
Full argument parsing (subcommands, typed values, --help generation) | Not provided; cli only answers flag, option and first-positional questions | Build a dispatcher on process::argc and process::argAt |
| Options with separated values counted as positionals | argFirstPositional() does not know which flags take a value | Test options with argHasOption / argParseOption first, or walk argAt yourself |
| Log output to a file or a custom sink | Not provided: std/system/log writes to stderr only | Redirect stderr in the shell, or log through your own writer |
process::abort() with cleanup | Not provided: no flushing, no destructors, no defer blocks | Use exit(code) where cleanup matters |
See also
std/sysreferencestd/sys/clireference: flag parsingstd/sys/envreference: standard dirsstd/sys/processreference: pid, argv, chdirstd/system/logreference: logging- Error handling:
IOExceptionpatterns - Files and I/O: file operations to combine with paths
- Concept index: every CLI and system concept cross-linked