recovery-owner-probe.dhover×155all
#!/usr/bin/env dub
/+ dub.sdl:
    name "recovery-owner-probe"
    targetPath "../../../build"
    dependency "sparkles:base" path="../../.."
    dependency "sparkles:recovery" path="../../.."
    dependency "sparkles:test-utils" path="../../.."
    dflags "-preview=in" "-preview=dip1000"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
/// Kill a task-owned process after its durable checkpoint and reclaim its archive.
module 
(module) recovery_owner_probe

Kill a task-owned process after its durable checkpoint and reclaim its archive.

recovery_owner_probe
;
import
(package) core
core
.
(package) core.sys
sys
.
(package) core.sys.posix
posix
.
(module) core.sys.posix.signal

D header file for POSIX.

Source

core/sys/posix/signal.d

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseBoost License 1.0@authorsSean Kelly, Alex Rønne Petersen@standardsThe Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
signal
:
(alias constant) recovery_owner_probe.SIGKILL = int core.sys.posix.signal.SIGKILL = 9
SIGKILL
;
import
(package) std
std
.
(module) std.file

Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module std.stdio.

Category Functions
General exists isDir isFile isSymlink rename thisExePath
Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir
Files append copy read readText remove slurp write
Symlinks symlink readLink
Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes
Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged
Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace

Source

std/file.d

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) recovery_owner_probe.readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))

Reads and validates (using validate) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.

@paramS the string type of the file@paramname string or range of characters representing the file name@returnsArray of characters read.@throwsFileException if there is an error reading the file, UTFException on UTF decoding error.@seeread for reading a binary file.
readText
,
(alias) recovery_owner_probe.thisExePath = string std.file.thisExePath() @trusted

Returns the full path of the current executable.

@returnsThe path of the executable as a string.@throwsException
thisExePath
;
import
(package) std
std
.
(module) std.process

Functions for starting and interacting with other processes, and for working with the current process' execution environment.

Process handling

  • `spawnProcess` spawns a new `process`, optionally assigning it an
        

    arbitrary set of standard input, output, and error streams. The function returns immediately, leaving the child process to execute in parallel with its parent. All other functions in this module that spawn processes are built around spawnProcess.

  • `wait` makes the parent `process` wait for a child `process` to
        

    terminate. In general one should always do this, to avoid child processes becoming "zombies" when the parent process exits. Scope guards are perfect for this – see the spawnProcess documentation for examples. tryWait is similar to wait, but does not block if the process has not yet terminated.

  • `pipeProcess` also spawns a child `process` which runs
        

    in parallel with its parent. However, instead of taking arbitrary streams, it automatically creates a set of pipes that allow the parent to communicate with the child through the child's standard input, output, and/or error streams. This function corresponds roughly to C's popen function.

  • `execute` starts a new `process` and waits for it
        

    to complete before returning. Additionally, it captures the process' standard output and error streams and returns the output of these as a string.

  • `spawnShell`, `pipeShell` and `executeShell` work like
        

    spawnProcess, pipeProcess and execute, respectively, except that they take a single command string and run it through the current user's default command interpreter. executeShell corresponds roughly to C's system function.

  • `kill` attempts to terminate a running `process`.
    
    

The following table compactly summarises the different process creation functions and how they relate to each other:

Runs program directly
Runs shell command
Low-level process creation
spawnProcess
spawnShell
Automatic input/output redirection using pipes
pipeProcess
pipeShell
Execute and wait for completion, collect output
execute
executeShell

Other functionality

  • `pipe` is used to create unidirectional pipes.
    
  • `environment` is an interface through which the current `process`'
        

    environment variables can be read and manipulated.

  • `escapeShellCommand` and `escapeShellFileName` are useful
        

    for constructing shell command lines in a portable way.

Source

std/process.d

Note

Most of the functionality in this module is not available on iOS, tvOS and watchOS. The only functions available on those platforms are: environment, thisProcessID and thisThreadID.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(alias) recovery_owner_probe.execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@parammaxOutput The maximum number of bytes of output that should be captured.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsAn std.typecons.Tuple!(int, "status", string, "output").@throws

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
,
(alias) recovery_owner_probe.kill = void std.process.kill(std.process.Pid pid)

Attempts to terminate the process associated with pid.

The effect of this function, as well as the meaning of codeOrSignal, is highly platform dependent. Details are given below. Common to all platforms is that this function only initiates termination of the process, and returns immediately. It does not wait for the process to end, nor does it guarantee that the process does in fact get terminated.

Always call wait to wait for a process to complete, even if kill has been called on it.

Windows specific

The process will be forcefully and abruptly terminated. If codeOrSignal is specified, it must be a nonnegative number which will be used as the exit code of the process. If not, the process wil exit with code 1. Do not use codeOrSignal = 259, as this is a special value (aka. STILL_ACTIVE) used by Windows to signal that a process has in fact not terminated yet.

auto pid = spawnProcess("some_app");
kill(pid, 10);
assert(wait(pid) == 10);

POSIX specific

A signal will be sent to the process, whose value is given by codeOrSignal. Depending on the signal sent, this may or may not terminate the process. Symbolic constants for various POSIX signals are defined in core.sys.posix.signal, which corresponds to the signal.h POSIX header. If codeOrSignal is omitted, the SIGTERM signal will be sent. (This matches the behaviour of the _kill shell command.)

import core.sys.posix.signal : SIGKILL;
auto pid = spawnProcess("some_app");
kill(pid, SIGKILL);
assert(wait(pid) == -SIGKILL); // Negative return value on POSIX!
@throwsProcessException on error (e.g. if codeOrSignal is invalid). or on attempt to kill detached process. Note that failure to terminate the process is considered a "normal" outcome, not an error.
kill
,
(alias) recovery_owner_probe.pipeProcess = std.process.ProcessPipes std.process.pipeProcess(scope const(char[])[] args, std.process.Redirect redirect = Redirect.all, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char)[] workDir = null) @safe

Starts a new process, creating pipes to redirect its standard input, output and/or error streams.

pipeProcess and pipeShell are convenient wrappers around spawnProcess and spawnShell, respectively, and automate the task of redirecting one or more of the child process' standard streams through pipes. Like the functions they wrap, these functions return immediately, leaving the child process to execute in parallel with the invoking process. It is recommended to always call wait on the returned ProcessPipes.pid, as detailed in the documentation for wait.

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

Example

// my_application writes to stdout and might write to stderr
auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
scope(exit) wait(pipes.pid);

// Store lines of output.
string[] output;
foreach (line; pipes.stdout.byLine) output ~= line.idup;

// Store lines of errors.
string[] errors;
foreach (line; pipes.stderr.byLine) errors ~= line.idup;


// sendmail expects to read from stdin
pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin);
pipes.stdin.writeln("To: you");
pipes.stdin.writeln("From: me");
pipes.stdin.writeln("Subject: dlang");
pipes.stdin.writeln("");
pipes.stdin.writeln(message);

// a single period tells sendmail we are finished
pipes.stdin.writeln(".");

// but at this point sendmail might not see it, we need to flush
pipes.stdin.flush();

// sendmail happens to exit on ".", but some you have to close the file:
pipes.stdin.close();

// otherwise this wait will wait forever
wait(pipes.pid);

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramredirect Flags that determine which streams are redirected, and how. See Redirect for an overview of available flags.@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsA ProcessPipes object which contains File handles that communicate with the redirected streams of the child process, along with a Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to redirect any of the streams.

pipeProcess
,
(enum) std.process.Redirect

Flags that can be passed to pipeProcess and pipeShell to specify which of the child process' standard streams are redirected. Use bitwise OR to combine flags.

Redirect
,
(alias) recovery_owner_probe.tryWait = std.typecons.Tuple!(bool, "terminated", int, "status") std.process.tryWait(std.process.Pid pid) @safe

A non-blocking version of wait.

If the process associated with pid has already terminated, tryWait has the exact same effect as wait. In this case, it returns a tuple where the terminated field is set to true and the status field has the same interpretation as the return value of wait.

If the process has not yet terminated, this function differs from wait in that does not wait for this to happen, but instead returns immediately. The terminated field of the returned tuple will then be set to false, while the status field will always be 0 (zero). wait or tryWait should then be called again on the same Pid at some later time; not only to get the exit code, but also to avoid the process becoming a "zombie" when it finally terminates. (See wait for details).

Example

auto pid = spawnProcess("dmd myapp.d");
scope(exit) wait(pid);
...
auto dmd = tryWait(pid);
if (dmd.terminated)
{
    if (dmd.status == 0) writeln("Compilation succeeded!");
    else writeln("Compilation failed");
}
else writeln("Still compiling...");
...

Note that in this example, the first wait call will have no effect if the process has already terminated by the time tryWait is called. In the opposite case, however, the scope statement ensures that we always wait for the process if it hasn't terminated by the time we reach the end of the scope.

@returnsAn std.typecons.Tuple!(bool, "terminated", int, "status").@throwsProcessException on failure or on attempt to wait for detached process.
tryWait
,
(alias) recovery_owner_probe.wait = int std.process.wait(std.process.Pid pid) @safe

Waits for the process associated with pid to terminate, and returns its exit status.

In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with Config.detached flag). Otherwise, they may become "zombies" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them.

If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same Pid it will always return the same value.

POSIX specific

If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the core.sys.posix.signal module (which corresponds to the signal.h POSIX header).

Example

See the spawnProcess documentation.

@throwsProcessException on failure or on attempt to wait for detached process.@seetryWait, for a non-blocking function.
wait
;
import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.

There are three layers of I/O:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
stdio
:
(alias template) recovery_owner_probe.readln = std.stdio.readln(S = string)(dchar terminator = '\n') if (isSomeString!S)

Read line from stdin.

This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the ``readln(buf) version, which may offer better performance as it can reuse its read buffer.

Note

String terminators are not supported due to ambiguity with readln(buf) below.

Example

Reads stdin and writes it to stdout.

import std.stdio;

void main()
{
    string line;
    while ((line = readln()) !is null)
        write(line);
}
@returnsThe line that was read, including the line terminator character.@paramS Template parameter; the type of the allocated buffer, and the type returned. Defaults to string.@paramterminator Line terminator (by default, '\n').@throwsStdioException on I/O error, or UnicodeException on Unicode conversion error.
readln
, stderr,
(alias) recovery_owner_probe.stdout = std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @system
stdout
,
(alias template) recovery_owner_probe.writeln = std.stdio.writeln(T...)(T args)

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
;
import
(package) std
std
.
(module) std.string

String handling functions.

Category Functions
Searching
column
indexOf
indexOfAny
indexOfNeither
lastIndexOf
lastIndexOfAny
lastIndexOfNeither
Comparison
isNumeric
Mutation
capitalize
Pruning and Filling
center
chomp
chompPrefix
chop
detabber
detab
entab
entabber
leftJustify
outdent
rightJustify
strip
stripLeft
stripRight
wrap
Substitution
abbrev
soundex
soundexer
succ
tr
translate
Miscellaneous
assumeUTF
fromStringz
lineSplitter
representation
splitLines
toStringz
Objects of types string, wstring, and dstring are value types
and cannot be mutated element-by-element. For using mutation during building
strings, use char[], wchar[], or dchar[]. The xxxstring
types are preferable because they don't exhibit undesired aliasing, thus
making code more robust.

The following functions are publicly imported:

Module Functions
Publicly imported functions
std.algorithm
cmp, std,algorithm,comparison
count, std,algorithm,searching
endsWith, std,algorithm,searching
startsWith, std,algorithm,searching
std.array
join, std,array
replace, std,array
replaceInPlace, std,array
split, std,array
empty, std,array
std.format
format, std,format
sformat, std,format
std.uni
icmp, std,uni
toLower, std,uni
toLowerInPlace, std,uni
toUpper, std,uni
toUpperInPlace, std,uni
There is a rich set of functions for string handling defined in other modules.
Functions related to Unicode and ASCII are found in std.uni
and std.ascii, respectively. Other functions that have a
wider generality than just strings can be found in std.algorithm
and std.range.

Source

std/string.d

@seestd.algorithm and std.range for generic range algorithms , std.ascii for functions that work with ASCII strings , std.uni for functions that work with unicode strings@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis
string
:
(alias template) recovery_owner_probe.strip = std.string.strip(Range)(Range str) if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range))

Strips both leading and trailing whitespace (as defined by isWhite) or as specified in the second argument.

@paramstr string or random access range of characters@paramchars string of characters to be stripped@paramleftChars string of leading characters to be stripped@paramrightChars string of trailing characters to be stripped@returnsslice of str stripped of leading and trailing whitespace or characters as specified in the second argument.@seeGeneric stripping on ranges: strip
strip
;
import
(package) sparkles
sparkles
.
(package) sparkles.recovery
recovery
.
(module) sparkles.recovery.archive

Numbered immutable generation files in a recovery archive.

A generation is one opaque payload under a canonical name: 20 decimal digits and the layout's suffix (00000000000000000007.session). An append never replaces a file: it is a create-only atomic write through the capability VFS that syncs the directory (VFO9), so an earlier generation stays readable until a newer one is durably acknowledged. Reads accept only a regular file, never through a link (VFO12). Pruning keeps the newest valid generations at or below an acknowledged cutoff and leaves damaged, unsupported, linked and newer entries alone. A retirement marker records that a generation was adopted elsewhere without touching its bytes.

archive
:
(alias) recovery_owner_probe.appendGeneration = sparkles.base.expected.Expected!(WriteReceipt, string, Abort) sparkles.recovery.archive.appendGeneration(string directory, ulong generation, scope const(char)[] bytes, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safe

Append bytes as generation, never replacing a file. The caller supplies an existing private directory whose creation is already durable, and retains earlier durable generations until this one is acknowledged durable.

appendGeneration
,
(alias) recovery_owner_probe.readGeneration = sparkles.base.expected.Expected!(string, string, Abort) sparkles.recovery.archive.readGeneration(string directory, ulong generation, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safe

The payload of generation, read only from a regular file.

readGeneration
;
import
(package) sparkles
sparkles
.
(package) sparkles.recovery
recovery
.
(module) sparkles.recovery.directory

Private, durable archive directories with process-shared ownership leases.

A LeasedDirectory is one archive: a private directory created under a base directory with a random name, synced up to a durable namespace root, and held with an exclusive flock for as long as its owner lives. Another process claims it only after the owner closes it or dies, so a crashed session's archive is recovered without two instances writing to it. Linux only, for now: elsewhere every call reports unavailable.

directory
:
(enum) sparkles.recovery.directory.DirectoryIssueKind

Why a lease was not granted.

DirectoryIssueKind
,
(class) sparkles.recovery.directory.LeasedDirectory

One archive's directory lock. Keep this owner alive until its storage work has stopped, then close it explicitly. Other processes can claim an archive only after its owner closes or terminates. Creation and claim serialize against the base directory lock so a half-initialized archive cannot be claimed.

LeasedDirectory
;
import
(package) sparkles
sparkles
.
(package) sparkles.test_utils
test_utils
.
(module) sparkles.test_utils.tmpfs
tmpfs
:
(struct) sparkles.test_utils.tmpfs.TmpFS

A scratch directory for a test, removed when the instance goes out of scope.

There are two ways to get one, and the difference is who owns the directory:

create makes a fresh, uniquely named directory and owns it: the whole tree — files written through this instance or behind its back, subdirectories, everything — is removed with the instance. This is what a test wants almost every time. share attaches to a directory that already exists and does not own it: only the files this instance wrote are removed, and the directory outlives it. This is for a test that deliberately has two fixtures over one tree, or one that must not delete what another made.

Ownership is decided by which constructor ran, never by what a later call happened to find on disk — so it cannot be forgotten, and a test that writes into dir() through the code under test rather than through this fixture still gets its tree cleaned up.

One instance is not thread-safe: writeFileAt appends to its file list and the destructor reads it. That is the intended shape — one fixture per test, used from the test's own thread — and create itself is safe to call concurrently. Sharing a single instance across threads needs the caller's own synchronization.

On POSIX, fixture writers are close-on-exec from the instant they open. An unrelated child executing concurrently cannot retain a writer after its exec and keep an executable fixture ETXTBSY after the parent's write has completed. This applies to both writeFile and writeFileAt.

Removal is best effort and never throws. A destructor that throws during unwinding replaces the assertion that actually failed with a cleanup error, and on Windows that is not hypothetical — git leaves read-only objects behind that make recursive removal fail.

TmpFS
;
int
int D main(string[] args) @system
main
(
(alias) object.string = string
string
[]
(parameter) string[] args
args
) @system
{ if (
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 1)
{ auto
(local variable) sparkles.test_utils.tmpfs.TmpFS fixture
fixture
=
(struct) sparkles.test_utils.tmpfs.TmpFS

A scratch directory for a test, removed when the instance goes out of scope.

There are two ways to get one, and the difference is who owns the directory:

create makes a fresh, uniquely named directory and owns it: the whole tree — files written through this instance or behind its back, subdirectories, everything — is removed with the instance. This is what a test wants almost every time. share attaches to a directory that already exists and does not own it: only the files this instance wrote are removed, and the directory outlives it. This is for a test that deliberately has two fixtures over one tree, or one that must not delete what another made.

Ownership is decided by which constructor ran, never by what a later call happened to find on disk — so it cannot be forgotten, and a test that writes into dir() through the code under test rather than through this fixture still gets its tree cleaned up.

One instance is not thread-safe: writeFileAt appends to its file list and the destructor reads it. That is the intended shape — one fixture per test, used from the test's own thread — and create itself is safe to call concurrently. Sharing a single instance across threads needs the caller's own synchronization.

On POSIX, fixture writers are close-on-exec from the instant they open. An unrelated child executing concurrently cannot retain a writer after its exec and keep an executable fixture ETXTBSY after the parent's write has completed. This applies to both writeFile and writeFileAt.

Removal is best effort and never throws. A destructor that throws during unwinding replaces the assertion that actually failed with a cleanup error, and on Windows that is not hypothetical — git leaves read-only objects behind that make recursive removal fail.

TmpFS
.
sparkles.test_utils.tmpfs.TmpFS sparkles.test_utils.tmpfs.TmpFS.create(string prefix = __FUNCTION__, string basePath = tempDir()) @safe

Creates a fresh scratch directory and returns the fixture that owns it.

prefix names the fixture for a human reading /tmp; it does not have to be unique. The directory actually used appends a random token and a process-wide ordinal, which makes three problems impossible rather than merely unlikely:

Two concurrent runs of one suite — two worktrees, two agents, a CI matrix sharing a runner — cannot share a directory and delete each other's fixtures mid-test. A crashed run cannot leave a directory behind for the next run to inherit and read a previous run's files from. The token is random rather than the process id for exactly this case: pids are recycled, so ``prefix-<pid>-1 recurs and would collide with the leftovers of a run that died holding the same pid. Two fixtures in one test function cannot collide, so neither needs an artificial prefix to tell them apart.

The directory exists when this returns, so a test may hand dir() to the code under test immediately; whatever that code puts there is removed with the fixture.

prefix defaults to the calling function. That is a good name when the call sits in the test; from a shared helper it names the helper, which is merely less informative — no longer a correctness problem.

create
();
const
(local variable) const(string) source
source
=
(local variable) sparkles.test_utils.tmpfs.TmpFS fixture
fixture
.
string sparkles.test_utils.tmpfs.TmpFS.writeFile(string contents, uint suffix = 0u) @safe
writeFile
("disk bytes");
auto
(local variable) std.process.ProcessPipes owner
owner
=
std.process.ProcessPipes std.process.pipeProcess(scope const(char[])[] args, std.process.Redirect redirect = Redirect.all, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char)[] workDir = null) @safe

Starts a new process, creating pipes to redirect its standard input, output and/or error streams.

pipeProcess and pipeShell are convenient wrappers around spawnProcess and spawnShell, respectively, and automate the task of redirecting one or more of the child process' standard streams through pipes. Like the functions they wrap, these functions return immediately, leaving the child process to execute in parallel with the invoking process. It is recommended to always call wait on the returned ProcessPipes.pid, as detailed in the documentation for wait.

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

Example

// my_application writes to stdout and might write to stderr
auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
scope(exit) wait(pipes.pid);

// Store lines of output.
string[] output;
foreach (line; pipes.stdout.byLine) output ~= line.idup;

// Store lines of errors.
string[] errors;
foreach (line; pipes.stderr.byLine) errors ~= line.idup;


// sendmail expects to read from stdin
pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin);
pipes.stdin.writeln("To: you");
pipes.stdin.writeln("From: me");
pipes.stdin.writeln("Subject: dlang");
pipes.stdin.writeln("");
pipes.stdin.writeln(message);

// a single period tells sendmail we are finished
pipes.stdin.writeln(".");

// but at this point sendmail might not see it, we need to flush
pipes.stdin.flush();

// sendmail happens to exit on ".", but some you have to close the file:
pipes.stdin.close();

// otherwise this wait will wait forever
wait(pipes.pid);

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramredirect Flags that determine which streams are redirected, and how. See Redirect for an overview of available flags.@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsA ProcessPipes object which contains File handles that communicate with the redirected streams of the child process, along with a Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to redirect any of the streams.

pipeProcess
([
string std.file.thisExePath() @trusted

Returns the full path of the current executable.

Examples

import std.path : isAbsolute;
auto path = thisExePath();

assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
@returnsThe path of the executable as a string.@throwsException
thisExePath
, "owner",
(local variable) sparkles.test_utils.tmpfs.TmpFS fixture
fixture
.
string sparkles.test_utils.tmpfs.TmpFS.dir() const pure nothrow @nogc @safe

The scratch directory's path. It exists for as long as the instance does (and, for share, for as long as its real owner keeps it).

dir
],
(enum) std.process.Redirect

Flags that can be passed to pipeProcess and pipeShell to specify which of the child process' standard streams are redirected. Use bitwise OR to combine flags.

Redirect
.
(enum value) std.process.Redirect.stdin = 1

Redirect the standard input, output or error streams, respectively.

stdin
|
(enum) std.process.Redirect

Flags that can be passed to pipeProcess and pipeShell to specify which of the child process' standard streams are redirected. Use bitwise OR to combine flags.

Redirect
.
(enum value) std.process.Redirect.stdout = 2

Redirect the standard input, output or error streams, respectively.

stdout
);
scope (exit) { if (!
std.typecons.Tuple!(bool, "terminated", int, "status") std.process.tryWait(std.process.Pid pid) @safe

A non-blocking version of wait.

If the process associated with pid has already terminated, tryWait has the exact same effect as wait. In this case, it returns a tuple where the terminated field is set to true and the status field has the same interpretation as the return value of wait.

If the process has not yet terminated, this function differs from wait in that does not wait for this to happen, but instead returns immediately. The terminated field of the returned tuple will then be set to false, while the status field will always be 0 (zero). wait or tryWait should then be called again on the same Pid at some later time; not only to get the exit code, but also to avoid the process becoming a "zombie" when it finally terminates. (See wait for details).

Example

auto pid = spawnProcess("dmd myapp.d");
scope(exit) wait(pid);
...
auto dmd = tryWait(pid);
if (dmd.terminated)
{
    if (dmd.status == 0) writeln("Compilation succeeded!");
    else writeln("Compilation failed");
}
else writeln("Still compiling...");
...

Note that in this example, the first wait call will have no effect if the process has already terminated by the time tryWait is called. In the opposite case, however, the scope statement ensures that we always wait for the process if it hasn't terminated by the time we reach the end of the scope.

@returnsAn std.typecons.Tuple!(bool, "terminated", int, "status").@throwsProcessException on failure or on attempt to wait for detached process.
tryWait
(
(local variable) std.process.ProcessPipes owner
owner
.
std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safe

The Pid of the child process.

pid
).terminated)
void std.process.kill(std.process.Pid pid, int codeOrSignal)
kill
(
(local variable) std.process.ProcessPipes owner
owner
.
std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safe

The Pid of the child process.

pid
,
(constant) int core.sys.posix.signal.SIGKILL = 9
SIGKILL
);
int std.process.wait(std.process.Pid pid) @safe

Waits for the process associated with pid to terminate, and returns its exit status.

In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with Config.detached flag). Otherwise, they may become "zombies" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them.

If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same Pid it will always return the same value.

POSIX specific

If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the core.sys.posix.signal module (which corresponds to the signal.h POSIX header).

Example

See the spawnProcess documentation.

@throwsProcessException on failure or on attempt to wait for detached process.@seetryWait, for a non-blocking function.
wait
(
(local variable) std.process.ProcessPipes owner
owner
.
std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safe

The Pid of the child process.

pid
);
} const
(local variable) const(string) path
path
=
(local variable) std.process.ProcessPipes owner
owner
.
std.stdio.File std.process.ProcessPipes.stdout() nothrow @property @safe

An File that allows reading from the child process' standard output stream.

@throwsError if the child process' standard output stream hasn't been redirected.
stdout
.
string std.stdio.File.readln!string(dchar terminator = '\n') @safe

Read line from the file handle and return it as a specified type.

This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the File.readln(buf) version, which may offer better performance as it can reuse its read buffer.

Note

String terminators are not supported due to ambiguity with readln(buf) below.

Example

// Reads `stdin` and writes it to `stdout`.
import std.stdio;

void main()
{
    string line;
    while ((line = stdin.readln()) !is null)
        write(line);
}
@paramS Template parameter; the type of the allocated buffer, and the type returned. Defaults to string.@paramterminator Line terminator (by default, '\n').@returnsThe line that was read, including the line terminator character.@throwsStdioException on I/O error, or UnicodeException on Unicode conversion error.
readln
().
string std.string.strip!string(string str) pure nothrow @nogc @safe

Strips both leading and trailing whitespace (as defined by isWhite) or as specified in the second argument.

Examples

import std.uni : lineSep, paraSep;
assert(strip("     hello world     ") ==
       "hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
       "hello world");
assert(strip("hello world") ==
       "hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
       "hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
       "hello world");
@paramstr string or random access range of characters@paramchars string of characters to be stripped@paramleftChars string of leading characters to be stripped@paramrightChars string of trailing characters to be stripped@returnsslice of str stripped of leading and trailing whitespace or characters as specified in the second argument.@seeGeneric stripping on ranges: strip
strip
;
assert(
(local variable) const(string) path
path
.
(field) ulong const(string).length
length
, "Owner exited before acknowledging its checkpoint.");
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) busy
busy
=
std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@parammaxOutput The maximum number of bytes of output that should be captured.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsAn std.typecons.Tuple!(int, "status", string, "output").@throws

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
([
string std.file.thisExePath() @trusted

Returns the full path of the current executable.

Examples

import std.path : isAbsolute;
auto path = thisExePath();

assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
@returnsThe path of the executable as a string.@throwsException
thisExePath
, "claim",
(local variable) const(string) path
path
]);
assert(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) busy
busy
.status == 3,
(field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0
busy
.output);
void std.process.kill(std.process.Pid pid, int codeOrSignal)
kill
(
(local variable) std.process.ProcessPipes owner
owner
.
std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safe

The Pid of the child process.

pid
,
(constant) int core.sys.posix.signal.SIGKILL = 9
SIGKILL
);
int std.process.wait(std.process.Pid pid) @safe

Waits for the process associated with pid to terminate, and returns its exit status.

In general one should always wait for child processes to terminate before exiting the parent process unless the process was spawned as detached (that was spawned with Config.detached flag). Otherwise, they may become "zombies" – processes that are defunct, yet still occupy a slot in the OS process table. You should not and must not wait for detached processes, since you don't own them.

If the process has already terminated, this function returns directly. The exit code is cached, so that if wait() is called multiple times on the same Pid it will always return the same value.

POSIX specific

If the process is terminated by a signal, this function returns a negative number whose absolute value is the signal number. Since POSIX restricts normal exit codes to the range 0-255, a negative return value will always indicate termination by signal. Signal codes are defined in the core.sys.posix.signal module (which corresponds to the signal.h POSIX header).

Example

See the spawnProcess documentation.

@throwsProcessException on failure or on attempt to wait for detached process.@seetryWait, for a non-blocking function.
wait
(
(local variable) std.process.ProcessPipes owner
owner
.
std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safe

The Pid of the child process.

pid
);
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) reclaimed
reclaimed
=
std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@parammaxOutput The maximum number of bytes of output that should be captured.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsAn std.typecons.Tuple!(int, "status", string, "output").@throws

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
([
string std.file.thisExePath() @trusted

Returns the full path of the current executable.

Examples

import std.path : isAbsolute;
auto path = thisExePath();

assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
@returnsThe path of the executable as a string.@throwsException
thisExePath
, "claim",
(local variable) const(string) path
path
]);
assert(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) reclaimed
reclaimed
.status == 0,
(field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0
reclaimed
.output);
assert(
string std.file.readText!(string, const(string))(ref const(string) name) @safe

Reads and validates (using validate) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.

Examples

Read file with UTF-8 text.

write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
@paramS the string type of the file@paramname string or range of characters representing the file name@returnsArray of characters read.@throwsFileException if there is an error reading the file, UTFException on UTF decoding error.@seeread for reading a binary file.
readText
(
(local variable) const(string) source
source
) == "disk bytes");
void std.stdio.writeln!string(string __param_0) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("active lease refused; killed owner reclaimed; durable payload recovered");
return 0; } if (
(parameter) string[] args
args
[1] == "owner")
{ assert(
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 3);
auto
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
=
(class) sparkles.recovery.directory.LeasedDirectory

One archive's directory lock. Keep this owner alive until its storage work has stopped, then close it explicitly. Other processes can claim an archive only after its owner closes or terminates. Creation and claim serialize against the base directory lock so a half-initialized archive cannot be claimed.

LeasedDirectory
.
sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) sparkles.recovery.directory.LeasedDirectory.create(string base, string durableRoot) nothrow @safe

Make a private archive under an existing, already durable namespace root. Sync the created subtree up to that root before publishing it. A platform supplies the root: initialization must not open inaccessible ancestors outside an Android application's private namespace.

create
(
(parameter) string[] args
args
[2],
(parameter) string[] args
args
[2]);
assert(
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
bool sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).hasValue!()() const pure nothrow @nogc @property @safe

Checks if Expected has value

hasValue
);
scope (exit)
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
void sparkles.recovery.directory.LeasedDirectory.close() nothrow @nogc @safe

Releases the lease; idempotent.

close
();
const
(local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) written
written
=
sparkles.base.expected.Expected!(WriteReceipt, string, Abort) sparkles.recovery.archive.appendGeneration(string directory, ulong generation, scope const(char)[] bytes, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safe

Append bytes as generation, never replacing a file. The caller supplies an existing private directory whose creation is already durable, and retains earlier durable generations until this one is acknowledged durable.

appendGeneration
(
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safe

The archive's absolute path.

path
, 1, "unsaved text");
assert(
(local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) written
written
.
bool sparkles.base.expected.Expected!(sparkles.recovery.archive.WriteReceipt, string, sparkles.base.expected.Abort).hasValue!()() const pure nothrow @nogc @property @safe

Checks if Expected has value

hasValue
&&
(local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) written
written
.
inout(sparkles.recovery.archive.WriteReceipt) sparkles.base.expected.Expected!(sparkles.recovery.archive.WriteReceipt, string, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
(field) bool sparkles.recovery.archive.WriteReceipt.durable

the directory sync after the commit succeeded

durable
);
void std.stdio.writeln!string(string __param_0) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
(
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safe

The archive's absolute path.

path
);
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @system
stdout
.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @system
flush
();
string std.stdio.readln!string(dchar terminator = '\n') @system

Read line from stdin.

This version manages its own read buffer, which means one memory allocation per call. If you are not retaining a reference to the read data, consider the ``readln(buf) version, which may offer better performance as it can reuse its read buffer.

Note

String terminators are not supported due to ambiguity with readln(buf) below.

Example

Reads stdin and writes it to stdout.

import std.stdio;

void main()
{
    string line;
    while ((line = readln()) !is null)
        write(line);
}
@returnsThe line that was read, including the line terminator character.@paramS Template parameter; the type of the allocated buffer, and the type returned. Defaults to string.@paramterminator Line terminator (by default, '\n').@throwsStdioException on I/O error, or UnicodeException on Unicode conversion error.
readln
(); // Parent holds this pipe open until killing this task-owned process.
return 0; } assert(
(parameter) string[] args
args
[1] == "claim" &&
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 3);
auto
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
=
(class) sparkles.recovery.directory.LeasedDirectory

One archive's directory lock. Keep this owner alive until its storage work has stopped, then close it explicitly. Other processes can claim an archive only after its owner closes or terminates. Creation and claim serialize against the base directory lock so a half-initialized archive cannot be claimed.

LeasedDirectory
.
sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) sparkles.recovery.directory.LeasedDirectory.claim(string path) nothrow @safe

Claim an abandoned archive; an active archive returns a typed busy outcome.

claim
(
(parameter) string[] args
args
[2]);
if (
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
bool sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).hasError!()() const pure nothrow @nogc @property @safe

Checks if Expected has error

hasError
)
{ if (
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.DirectoryIssue) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).error() inout pure nothrow @nogc @property ref @safe

Returns the error value. May only be called when hasValue returns false.

If there is no error value, it calls hook's onAccessEmptyError.

It returns E.init when hook doesn't provide onAccessEmptyError.

Note

Error is returned by reference only when hook provides onAccessEmptyError. Otherwise the E.init fallback forces it to be returned by value (a copy).

error
.
(field) sparkles.recovery.directory.DirectoryIssueKind sparkles.recovery.directory.DirectoryIssue.kind
kind
==
(enum) sparkles.recovery.directory.DirectoryIssueKind

Why a lease was not granted.

DirectoryIssueKind
.
(enum value) sparkles.recovery.directory.DirectoryIssueKind.busy = cast(ubyte)0u

another live owner holds it

busy
) return 3;
stderr.
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @system
writeln
(
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.DirectoryIssue) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).error() inout pure nothrow @nogc @property ref @safe

Returns the error value. May only be called when hasValue returns false.

If there is no error value, it calls hook's onAccessEmptyError.

It returns E.init when hook doesn't provide onAccessEmptyError.

Note

Error is returned by reference only when hook provides onAccessEmptyError. Otherwise the E.init fallback forces it to be returned by value (a copy).

error
.
(field) string sparkles.recovery.directory.DirectoryIssue.message
message
);
return 2; } scope (exit)
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
void sparkles.recovery.directory.LeasedDirectory.close() nothrow @nogc @safe

Releases the lease; idempotent.

close
();
assert(
sparkles.base.expected.Expected!(string, string, Abort) sparkles.recovery.archive.readGeneration(string directory, ulong generation, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safe

The payload of generation, read only from a regular file.

readGeneration
(
(local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directory
directory
.
inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
.
string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safe

The archive's absolute path.

path
, 1).
inout(string) sparkles.base.expected.Expected!(string, string, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safe

Returns the expected value if there is one.

With default Abort hook, it asserts when there is no value. It calls hook's onAccessEmptyValue otherwise.

It returns T.init when hook doesn't provide onAccessEmptyValue.

Note

Value is returned by reference only when hook provides onAccessEmptyValue. Otherwise the T.init fallback forces it to be returned by value (a copy).

value
== "unsaved text");
return 0; }