native-close-probe.dhover×486 error×32all
#!/usr/bin/env dub
/+ dub.sdl:
    name "editor-native-close-probe"
    dependency "sparkles:wsi" path="../../.."
    dependency "sparkles:ui" path="../../.."
    dependency "sparkles:wired" path="../../.."
    dependency "sparkles:recovery" path="../../.."
    dflags "-I$PACKAGE_DIR/../src" "-i=session_archive" "-i=session_record" "-i=document_files"
    targetPath "../build"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
/// Exercise native process recovery and dirty-close decisions on a private X11 server.
module 
(module) editor_native_close_probe

Exercise native process recovery and dirty-close decisions on a private X11 server.

editor_native_close_probe
;
import
(module) xcb_native
xcb_native
;
C preprocess command `cpp` failed for file `/home/runner/work/sparkles/sparkles/libs/wsi/src/xcb_native.c`, exit status 1
import
(package) core
core
.
(package) core.stdc
stdc
.
(module) core.stdc.stdlib

D header file for C99.

pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html, stdlib.h

Source

core/stdc/stdlib.d

@copyrightCopyright Sean Kelly 2005 - 2014.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly@standardsISO/IEC 9899:1999 (E)
stdlib
:
(alias) editor_native_close_probe.free = void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
;
import
(package) core
core
.
(module) core.thread

The thread module provides support for thread creation and management.

Source

core/thread/package.d

@copyrightCopyright Sean Kelly 2005 - 2012.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
thread
:
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
;
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) editor_native_close_probe.SIGKILL = int core.sys.posix.signal.SIGKILL = 9
SIGKILL
;
import
(package) core
core
.
(module) core.time

Module containing core time functionality, such as Duration (which represents a duration of time) or MonoTime (which represents a timestamp of the system's monotonic clock).

Various functions take a string (or strings) to represent a unit of time (e.g. convert!("days", "hours")(numDays)). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There are a few functions that also allow "nsecs", but very little actually has precision greater than hnsecs.

Symbol Description
Types
Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).
TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides.
MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides.
Functions
convert Generic way of converting between two time units.
dur Allows constructing a Duration from the given time units with the given length.
weeks days hours

minutes seconds msecs

usecs hnsecs nsecs | Convenience aliases for dur. | | abs | Returns the absolute value of a duration. |

From Duration
From TickDuration
From units
To Duration
tickDuration.to, std,conv!Duration()
dur!"msecs"(5) or 5.msecs()

| To TickDuration | duration.to, std,conv!TickDuration() |

  • | TickDuration.from!"msecs"(msecs) |

| To units | duration.total!"days" | tickDuration.msecs | convert!("days", "msecs")(msecs) |

Source

core/time.d

@copyrightCopyright 2010 - 2012@licenseBoost License 1.0.@authorsJonathan M Davis and Kato Shoichi
time
:
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
, seconds, msecs;
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
:
(struct) std.process.Config

Options that control the behaviour of process creation functions in this module. Most options only apply to spawnProcess and spawnShell.

Example

auto logFile = File("myapp_error.log", "w");

// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
                        Config.retainStderr | Config.suppressConsole);
scope(exit)
{
    auto exitCode = wait(pid);
    logFile.writeln("myapp exited with code ", exitCode);
    logFile.close();
}
Config
,
(alias) editor_native_close_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) editor_native_close_probe.spawnProcess = std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safe

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. It is recommended to always call wait on the returned Pid unless the process was spawned with Config.detached flag, as detailed in the documentation for wait.

Command line

There are four overloads of this function. The first two take an array of strings, args, which should contain the program name as the zeroth element and any command-line arguments in subsequent elements. The third and fourth versions are included for convenience, and may be used when there are no command-line arguments. They take a single string, program, which specifies the program name.

Unless a directory is specified in args[0] or program, spawnProcess will search for the program in a platform-dependent manner. On POSIX systems, it will look for the executable in the directories listed in the PATH environment variable, in the order they are listed. On Windows, it will search for the executable in the following sequence:

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. The 32-bit Windows system directory.

  4. The 16-bit Windows system directory.

  5. The Windows directory.

  6. The directories listed in the PATH environment variable.

// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs.  The scope guard
// ensures that the process is waited for at the end of the scope.
...

// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
    writeln("Compilation failed!");

Environment variables

By default, the child process inherits the environment of the parent process, along with any additional variables specified in the env parameter. If the same variable exists in both the parent's environment and in env, the latter takes precedence.

If the Config.newEnv flag is set in config, the child process will not inherit the parent's environment. Its entire environment will then be determined by env.

wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));

Standard streams

The optional arguments stdin, stdout and stderr may be used to assign arbitrary File objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. The default is for the child process to inherit the standard streams of its parent.

// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
                        std.stdio.stdin,
                        std.stdio.stdout,
                        logFile);
if (wait(pid) != 0)
    writeln("Compilation failed. See errors.log for details.");

Note that if you pass a File object that is not one of the standard input/output/error streams of the parent process, that stream will by default be closed in the parent process when this function returns. See the Config documentation below for information about how to disable this behaviour.

Beware of buffering issues when passing File objects to spawnProcess. The child process will inherit the low-level raw read/write offset associated with the underlying file descriptor, but it will not be aware of any buffered data. In cases where this matters (e.g. when a file should be aligned before being passed on to the child process), it may be a good idea to use unbuffered streams, or at least ensure all relevant buffers are flushed.

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements.@paramstdin The standard input stream of the child process. This can be any File that is opened for reading. By default the child process inherits the parent's input stream.@paramstdout The standard output stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's output stream.@paramstderr The standard error stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's error stream.@paramenv Additional environment variables for the child process.@paramconfig Flags that control process creation. See Config for an overview of available flags.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@returnsA Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to pass one of the streams to the child process (Windows only).

RangeError if args is empty.

spawnProcess
,
(alias) editor_native_close_probe.thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d", thisProcessID);
thisProcessID
,
(alias) editor_native_close_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) editor_native_close_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) editor_native_close_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
:
(struct) std.stdio.File

Encapsulates a FILE*. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulating FILE* values directly is unsafe and error-prone in many ways. The File type ensures safe manipulation, automatic file closing, and a lot of convenience.

The underlying FILE* handle is maintained in a reference-counted manner, such that as soon as the last File variable bound to a given FILE* goes out of scope, the underlying FILE* is automatically closed.

Example

// test.d
import std.stdio;

void main(string[] args)
{
    auto f = File("test.txt", "w"); // open for writing
    f.write("Hello");
    if (args.length > 1)
    {
        auto g = f; // now g and f write to the same file
                    // internal reference count is 2
        g.write(", ", args[1]);
        // g exits scope, reference count decreases to 1
    }
    f.writeln("!");
    // f exits scope, reference count falls to zero,
    // underlying `FILE*` is closed.
}

% rdmd test.d Jimmy % cat test.txt Hello, Jimmy! % _

File
, stdin,
(alias template) editor_native_close_probe.write = std.stdio.write(T...)(T args) if (!is(T[0] : File))

Writes its arguments in text format to standard output (without a trailing newline).

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++)
    {
         write("Input ", count, ": ", line, "\n");
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
write
,
(alias template) editor_native_close_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.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) editor_native_close_probe.baseName = std.path.baseName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)

Note

This function only strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use stripExtension. To obtain the filename without leading directories and without an extension, combine the functions like this:

assert(baseName(stripExtension("dir/file.ext")) == "file");
@paramcs Whether or not suffix matching is case-sensitive.@parampath A path name. It can be a string, or any random-access range of characters.@paramsuffix An optional suffix to be removed from the file name.@returns

The name of the file in the path name, without any leading directory and with an optional suffix chopped off.

If suffix is specified, it will be compared to path using filenameCmp!cs, where cs is an optional template parameter determining whether the comparison is case sensitive or not. See the filenameCmp documentation for details.

@standardsThis function complies with the POSIX requirements for the 'basename' shell utility (with suitable adaptations for Windows paths).
baseName
,
(alias template) editor_native_close_probe.buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
,
(alias template) editor_native_close_probe.dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

@parampath A path name.@returnsA slice of path or ".".@standardsThis function complies with the POSIX requirements for the 'dirname' shell utility (with suitable adaptations for Windows paths).
dirName
;
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) editor_native_close_probe.dirEntries = std.file.dirEntries(bool useDIP1000 = dip1000Enabled)(string path, SpanMode mode, bool followSymlink = true)

Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

Note

The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Example

// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

To handle subdirectories with denied read permission, use SpanMode.shallow:

void scan(string path)
{
    foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
    {
        try
        {
            writeln(entry.name);
            if (entry.isDir)
                scan(entry.name);
        }
        catch (FileException fe) { continue; } // ignore
    }
}

scan("");
@paramuseDIP1000 used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.@parampath The directory to iterate over. If empty, the current directory will be iterated.@parampattern Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under globMatch.@parammode Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).@paramfollowSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over.@returnsAn input range of DirEntry.@throws
  • FileException if the path directory does not exist or read permission is denied.

  • FileException if mode is not shallow and a subdirectory cannot be read.

dirEntries
,
(alias template) editor_native_close_probe.mkdir = std.file.mkdir(R)(R pathname) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Make a new directory pathname.

@parampathname the path of the directory to make@throwsFileException on POSIX or WindowsException on Windows if an error occured.
mkdir
,
(alias template) editor_native_close_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) editor_native_close_probe.rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

Remove directory and all of its content and subdirectories, recursively.

@parampathname the path of the directory to completely remove@paramde The DirEntry to remove@throwsFileException if there is an error (including if the given file is not a directory).
rmdirRecurse
,
(enum) std.file.SpanMode

Dictates directory spanning policy for dirEntries (see below).

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;

alias removeRoot = (return scope e) => e.relativePath(root);

assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    [buildPath("animals", "cat"), "animals"]));

assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["animals", buildPath("animals", "cat")]));

root.buildPath("plants").mkdir;

assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
    ["animals", "plants"]));
SpanMode
,
(alias) editor_native_close_probe.tempDir = string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
,
(alias) editor_native_close_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.uuid

A UUID, or Universally unique identifier, is intended to uniquely identify information in a distributed environment without significant central coordination. It can be used to tag objects with very short lifetimes, or to reliably identify very persistent objects across a network.

Category Functions

| Parsing UUIDs | parseUUID UUID UUIDParsingException uuidRegex |

| Generating UUIDs | sha1UUID randomUUID md5UUID timestampRandomUUID |

| Using UUIDs | <a href="#uuidVersion">UUID.uuidVersion</a>&nbsp; <a href="#variant">UUID.variant</a>&nbsp; <a href="#toString">UUID.toString</a>&nbsp; <a href="#data">UUID.data</a>&nbsp; <a href="#swap">UUID.swap</a>&nbsp; <a href="#opEquals">UUID.opEquals</a>&nbsp; <a href="#opCmp">UUID.opCmp</a>&nbsp; <a href="#toHash">UUID.toHash</a>&nbsp; |

| UUID namespaces | dnsNamespace urlNamespace oidNamespace x500Namespace |

UUIDs have many applications. Some examples follow: Databases may use UUIDs to identify rows or records in order to ensure that they are unique across different databases, or for publication/subscription services. Network messages may be identified with a UUID to ensure that different parts of a message are put back together again. Distributed computing may use UUIDs to identify a remote procedure call. Transactions and classes involved in serialization may be identified by UUIDs. Microsoft's component object model (COM) uses UUIDs to distinguish different software component interfaces. UUIDs are inserted into documents from Microsoft Office programs. UUIDs identify audio or video streams in the Advanced Systems Format (ASF). UUIDs are also a basis for OIDs (object identifiers), and URNs (uniform resource name).

An attractive feature of UUIDs when compared to alternatives is their relative small size, of 128 bits, or 16 bytes. Another is that the creation of UUIDs does not require a centralized authority.

When UUIDs are generated by one of the defined mechanisms, they are either guaranteed to be unique, different from all other generated UUIDs (that is, it has never been generated before and it will never be generated again), or it is extremely likely to be unique (depending on the mechanism).

For efficiency, UUID is implemented as a struct. UUIDs are therefore empty if not explicitly initialized. An UUID is empty if <a href="#empty">UUID.empty</a> is true. Empty UUIDs are equal to UUID.init, which is a UUID with all 16 bytes set to 0. Use UUID's constructors or the UUID generator functions to get an initialized UUID.

This is a port of boost.uuid from the Boost project with some minor additions and API changes for a more D-like API.

Source

std/uuid.d

Examples

import std.uuid;

UUID[] ids;
ids ~= randomUUID();
ids ~= md5UUID("test.name.123");
ids ~= sha1UUID("test.name.123");

foreach (entry; ids)
{
    assert(entry.variant == UUID.Variant.rfc4122);
}
assert(ids[0].uuidVersion == UUID.Version.randomNumberBased);
assert(ids[1].toString() == "22390768-cced-325f-8f0f-cfeaa19d0ccd");
assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207,
    234, 161, 157, 12, 205]);
UUID id;
assert(id.empty);
@standardsRFC 4122@seehttp://en.wikipedia.org/wiki/Universally_unique_identifier@copyrightCopyright Johannes Pfau 2011 - .@licenseBoost License 1.0.@authorsJohannes Pfau
uuid
:
(alias) editor_native_close_probe.randomUUID = std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safe

This function generates a random number based UUID from a random number generator.

This function is not supported at compile time.

Warning

This function must not be used for cryptographic purposes. UUIDs generated by this function do not have sufficient randomness for all use cases. This especially applies to the overload that accepts a caller-provided RNG. At the moment, Phobos does not provide a cryptographically-secure pseudo-random number generator (CSPRNG) that could be supplied to this function.

While the function overload with no parameters will attempt to use the system CSPRNG where available and implemented, there are no guarantees. See unpredictableSeed for details.

@bugsIssue #9881 - Randomness in UUID generation is insufficient@paramrandomGen uniform RNG@seeisUniformRNG
randomUUID
;
import
(package) std
std
.
(module) std.conv

A one-stop shop for converting values from one type to another.

Category Functions
Generic asOriginalType castFrom parse to toChars bitCast
Strings text wtext dtext writeText writeWText writeDText hexString
Numeric octal roundTo signed unsigned
Exceptions ConvException ConvOverflowException

Source

std/conv.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara
conv
:
(alias template) editor_native_close_probe.text = std.conv.text(T...)(T args) if (T.length > 0)

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
;
import
(module) session_archive

The editor's session generations: its record schema over sparkles:recovery's numbered immutable archive. The layout keeps the names archives already on disk use (<20 digits>.session, adopted-<20 digits>).

session_archive
:
(alias) editor_native_close_probe.readSessionGeneration = sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safe

Validate the complete immutable record and its identity before returning recovered contents.

readSessionGeneration
,
(alias) editor_native_close_probe.sessionGenerationOfName = ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safe

Recognize a canonical positive generation filename; zero means an unrelated entry.

sessionGenerationOfName
;
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 || (
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 2
&& (
(parameter) string[] args
args
[1] == "--clipboard" ||
(parameter) string[] args
args
[1] == "--clipboard-withdrawal")))
{ auto
(local variable) string[] command
command
= ["xvfb-run", "-a",
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
, "--private-server"];
if (
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 2)
(local variable) string[] command
command
~=
(parameter) string[] args
args
[1];
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
=
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
(
(local variable) string[] command
command
);
void std.stdio.write!string(string __param_0) @safe

Writes its arguments in text format to standard output (without a trailing newline).

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++)
    {
         write("Input ", count, ": ", line, "\n");
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
write
(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.output);
return
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) result
result
.status;
} assert((
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 2 ||
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 3) &&
(parameter) string[] args
args
[1] == "--private-server");
auto
(local variable) _error_ connection
connection
= xcb_connect(null, null);
undefined identifier `xcb_connect`
assert(connection !is null && !xcb_connection_has_error(connection));
undefined identifier `xcb_connection_has_error`
scope (exit) xcb_disconnect(connection);
undefined identifier `xcb_disconnect`
const
(local variable) const(_error_) root
root
= xcb_setup_roots_iterator(xcb_get_setup(connection)).data.
(field) _error_ xcb_setup_roots_iterator(xcb_get_setup(connection)).data.root
root
;
undefined identifier `xcb_setup_roots_iterator`
uint
uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @system
atom
(
(alias) object.string = string
string
(parameter) string name
name
) @system
{ auto
(local variable) _error_ reply
reply
= xcb_intern_atom_reply(connection,
undefined identifier `xcb_intern_atom_reply`
xcb_intern_atom(connection, 0, cast(ushort) name.
name.length
length
, name.ptr), null);
assert(reply !is null); scope (exit)
void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
(reply);
return reply.
(field) _error_ reply.atom
atom
;
} const
(local variable) const(uint) nameAtom
nameAtom
=
uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @system
atom
("_NET_WM_NAME");
const
(local variable) const(string) state
state
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Examples

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
assert(myFile.readText == "hello");
@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
, "editor-native-state-" ~
std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safe

This function generates a random number based UUID from a random number generator.

This function is not supported at compile time.

Warning

This function must not be used for cryptographic purposes. UUIDs generated by this function do not have sufficient randomness for all use cases. This especially applies to the overload that accepts a caller-provided RNG. At the moment, Phobos does not provide a cryptographically-secure pseudo-random number generator (CSPRNG) that could be supplied to this function.

While the function overload with no parameters will attempt to use the system CSPRNG where available and implemented, there are no guarantees. See unpredictableSeed for details.

@bugsIssue #9881 - Randomness in UUID generation is insufficient@paramrandomGen uniform RNG@seeisUniformRNG
randomUUID
().
string std.uuid.UUID.toString() const pure nothrow @trusted

Return the UUID as a string in the canonical form.

Examples

immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46";
auto id = UUID(str);
assert(id.toString() == str);
toString
());
void std.file.mkdir!string(string pathname) @safe

Make a new directory pathname.

@parampathname the path of the directory to make@throwsFileException on POSIX or WindowsException on Windows if an error occured.
mkdir
(
(local variable) const(string) state
state
);
scope (exit)
void std.file.rmdirRecurse(scope const(char)[] pathname) @safe

Remove directory and all of its content and subdirectories, recursively.

@parampathname the path of the directory to completely remove@paramde The DirEntry to remove@throwsFileException if there is an error (including if the given file is not a directory).
rmdirRecurse
(
(local variable) const(string) state
state
);
auto
(local variable) std.stdio.File log
log
=
(struct) std.stdio.File

Encapsulates a FILE*. Generally D does not attempt to provide thin wrappers over equivalent functions in the C standard library, but manipulating FILE* values directly is unsafe and error-prone in many ways. The File type ensures safe manipulation, automatic file closing, and a lot of convenience.

The underlying FILE* handle is maintained in a reference-counted manner, such that as soon as the last File variable bound to a given FILE* goes out of scope, the underlying FILE* is automatically closed.

Example

// test.d
import std.stdio;

void main(string[] args)
{
    auto f = File("test.txt", "w"); // open for writing
    f.write("Hello");
    if (args.length > 1)
    {
        auto g = f; // now g and f write to the same file
                    // internal reference count is 2
        g.write(", ", args[1]);
        // g exits scope, reference count decreases to 1
    }
    f.writeln("!");
    // f exits scope, reference count falls to zero,
    // underlying `FILE*` is closed.
}

% rdmd test.d Jimmy % cat test.txt Hello, Jimmy! % _

File
(
std.stdio.File std.stdio.File.this(string name, scope const(char)[] stdioOpenmode = "rb") ref @safe

Constructor taking the name of the file to open and the open mode.

Copying one File object to another results in the two File objects referring to the same underlying file.

The destructor automatically closes the file as soon as no File object refers to it anymore.

@paramname range or string representing the file name@paramstdioOpenmode range or string represting the open mode (with the same semantics as in the C standard library fopen function)@throwsErrnoException if the file could not be opened.
buildPath
(
string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Examples

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
assert(myFile.readText == "hello");
@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
,
string std.conv.text!(string, int, string)(string __param_0, int __param_1, string __param_2) pure nothrow @safe

Convenience functions for converting one or more arguments of any type into text (the three character widths).

text
("editor-native-close-",
int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d", thisProcessID);
thisProcessID
, ".log")), "w");
const
(local variable) const(string) editor
editor
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(__FILE_FULL_PATH__.
string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

Examples

assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");

version (Windows)
{
    assert(dirName(`dir\`) == `.`);
    assert(dirName(`dir\\\`) == `.`);
    assert(dirName(`dir\file`) == `dir`);
    assert(dirName(`dir\\\file`) == `dir`);
    assert(dirName(`dir\subdir\`) == `dir`);
    assert(dirName(`\dir\file`) == `\dir`);
    assert(dirName(`\file`) == `\`);
    assert(dirName(`\`) == `\`);
    assert(dirName(`\\\`) == `\`);
    assert(dirName(`d:`) == `d:`);
    assert(dirName(`d:file`) == `d:`);
    assert(dirName(`d:\`) == `d:\`);
    assert(dirName(`d:\file`) == `d:\`);
    assert(dirName(`d:\dir\file`) == `d:\dir`);
    assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
    assert(dirName(`\\server\share\file`) == `\\server\share`);
    assert(dirName(`\\server\share\`) == `\\server\share`);
    assert(dirName(`\\server\share`) == `\\server\share`);
}
@parampath A path name.@returnsA slice of path or ".".@standardsThis function complies with the POSIX requirements for the 'dirname' shell utility (with suitable adaptations for Windows paths).
dirName
.
string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Returns the parent directory of path. On Windows, this includes the drive letter if present. If path is a relative path and the parent directory is the current working directory, returns ".".

Examples

assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");

version (Windows)
{
    assert(dirName(`dir\`) == `.`);
    assert(dirName(`dir\\\`) == `.`);
    assert(dirName(`dir\file`) == `dir`);
    assert(dirName(`dir\\\file`) == `dir`);
    assert(dirName(`dir\subdir\`) == `dir`);
    assert(dirName(`\dir\file`) == `\dir`);
    assert(dirName(`\file`) == `\`);
    assert(dirName(`\`) == `\`);
    assert(dirName(`\\\`) == `\`);
    assert(dirName(`d:`) == `d:`);
    assert(dirName(`d:file`) == `d:`);
    assert(dirName(`d:\`) == `d:\`);
    assert(dirName(`d:\file`) == `d:\`);
    assert(dirName(`d:\dir\file`) == `d:\dir`);
    assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
    assert(dirName(`\\server\share\file`) == `\\server\share`);
    assert(dirName(`\\server\share\`) == `\\server\share`);
    assert(dirName(`\\server\share`) == `\\server\share`);
}
@parampath A path name.@returnsA slice of path or ".".@standardsThis function complies with the POSIX requirements for the 'dirname' shell utility (with suitable adaptations for Windows paths).
dirName
, "build", "editor");
auto
(local variable) std.process.Pid child
child
=
std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safe

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. It is recommended to always call wait on the returned Pid unless the process was spawned with Config.detached flag, as detailed in the documentation for wait.

Command line

There are four overloads of this function. The first two take an array of strings, args, which should contain the program name as the zeroth element and any command-line arguments in subsequent elements. The third and fourth versions are included for convenience, and may be used when there are no command-line arguments. They take a single string, program, which specifies the program name.

Unless a directory is specified in args`[0]` or `program`, spawnProcess`` will search for the program in a platform-dependent manner. On POSIX systems, it will look for the executable in the directories listed in the PATH environment variable, in the order they are listed. On Windows, it will search for the executable in the following sequence:

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. The 32-bit Windows system directory.

  4. The 16-bit Windows system directory.

  5. The Windows directory.

  6. The directories listed in the PATH environment variable.

// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs.  The scope guard
// ensures that the process is waited for at the end of the scope.
...

// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
    writeln("Compilation failed!");

Environment variables

By default, the child process inherits the environment of the parent process, along with any additional variables specified in the env parameter. If the same variable exists in both the parent's environment and in env, the latter takes precedence.

If the Config.newEnv flag is set in config, the child process will not inherit the parent's environment. Its entire environment will then be determined by env.

wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));

Standard streams

The optional arguments stdin, stdout and stderr may be used to assign arbitrary File objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. The default is for the child process to inherit the standard streams of its parent.

// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
                        std.stdio.stdin,
                        std.stdio.stdout,
                        logFile);
if (wait(pid) != 0)
    writeln("Compilation failed. See errors.log for details.");

Note that if you pass a File object that is not one of the standard input/output/error streams of the parent process, that stream will by default be closed in the parent process when this function returns. See the Config documentation below for information about how to disable this behaviour.

Beware of buffering issues when passing File objects to spawnProcess. The child process will inherit the low-level raw read/write offset associated with the underlying file descriptor, but it will not be aware of any buffered data. In cases where this matters (e.g. when a file should be aligned before being passed on to the child process), it may be a good idea to use unbuffered streams, or at least ensure all relevant buffers are flushed.

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements.@paramstdin The standard input stream of the child process. This can be any File that is opened for reading. By default the child process inherits the parent's input stream.@paramstdout The standard output stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's output stream.@paramstderr The standard error stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's error stream.@paramenv Additional environment variables for the child process.@paramconfig Flags that control process creation. See Config for an overview of available flags.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@returnsA Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to pass one of the streams to the child process (Windows only).

RangeError if args is empty.

spawnProcess
([
(local variable) const(string) editor
editor
,
"--gui", "--window-system", "x11", "--state-dir",
(local variable) const(string) state
state
], stdin,
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdin"() nothrow @nogc @property ref @system
log
,
(local variable) std.stdio.File log
log
,
null,
(struct) std.process.Config

Options that control the behaviour of process creation functions in this module. Most options only apply to spawnProcess and spawnShell.

Example

auto logFile = File("myapp_error.log", "w");

// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
                        Config.retainStderr | Config.suppressConsole);
scope(exit)
{
    auto exitCode = wait(pid);
    logFile.writeln("myapp exited with code ", exitCode);
    logFile.close();
}
Config
.
(constant) std.process.Config std.process.Config.retainStdout = Config(Flags.retainStdout, null, null)

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

retainStdout
|
std.process.Config std.process.Config.opBinary!"|"(std.process.Config other) pure nothrow @nogc @safe

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

Config
.
(constant) std.process.Config std.process.Config.retainStderr = Config(Flags.retainStderr, null, null)

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

retainStderr
);
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.Pid child
child
).terminated)
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
(
(local variable) std.process.Pid child
child
);
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.Pid child
child
);
} uint
(local variable) uint window
window
;
void
void editor_native_close_probe.main.findWindow() nothrow @system
findWindow
() @system
{
(local variable) uint window
window
= 0;
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 15.seconds;
while (!
(local variable) uint window
window
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
deadline
)
{ auto
(local variable) _error_ reply
reply
= xcb_query_tree_reply(connection, xcb_query_tree(connection, root), null);
undefined identifier `xcb_query_tree_reply`
assert(reply !is null); scope (exit)
void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
(reply);
foreach (
(parameter) candidate
candidate
; xcb_query_tree_children(reply)[0 .. xcb_query_tree_children_length(reply)])
undefined identifier `xcb_query_tree_children`
{ auto
_error_ property
property
= xcb_get_property_reply(connection,
xcb_get_property(connection, 0, candidate, nameAtom, XCB_GET_PROPERTY_TYPE_ANY, 0, 100), null); if (property is null) continue; scope (exit) free(property); const
_error_ length
length
= xcb_get_property_value_length(property);
const
_error_ name
name
= (cast(const(char)*) xcb_get_property_value(property))[0 .. length];
if (name == "Sparkles Editor") { window = candidate; break; } } assert(!
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.Pid child
child
).terminated, "Editor exited before its window appeared: " ~
string std.file.readText!(string, string)(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) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(20.msecs);
} assert(
(local variable) uint window
window
, "Editor window did not appear.");
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(400.msecs);
}
void editor_native_close_probe.main.findWindow() nothrow @system
findWindow
();
void
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(ubyte
(parameter) ubyte code
code
, ushort
(parameter) ushort modifiers
modifiers
= 0) @system
{ xcb_key_press_event_t
(local variable) _error_ event
event
;
undefined identifier `xcb_key_press_event_t`
event.response_type = XCB_KEY_PRESS; event.detail = code; event.
event.root
root
= root;
event.
event.event
event
= window;
event.same_screen = 1; event.
event.state
state
= modifiers;
xcb_send_event(connection, 0, window, XCB_EVENT_MASK_KEY_PRESS, cast(const(char)*) &event);
undefined identifier `xcb_send_event`
event.response_type = XCB_KEY_RELEASE; xcb_send_event(connection, 0, window, XCB_EVENT_MASK_KEY_RELEASE, cast(const(char)*) &event);
undefined identifier `xcb_send_event`
xcb_flush(connection);
undefined identifier `xcb_flush`
} void
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @system
closeWindow
() @system
{ xcb_client_message_event_t
(local variable) _error_ event
event
;
undefined identifier `xcb_client_message_event_t`
event.response_type = XCB_CLIENT_MESSAGE; event.format = 32; event.
event.window
window
= window;
event.type = atom("WM_PROTOCOLS"); event.data.data32[0] = atom("WM_DELETE_WINDOW"); xcb_send_event(connection, 0, window, XCB_EVENT_MASK_NO_EVENT, cast(const(char)*) &event);
undefined identifier `xcb_send_event`
xcb_flush(connection);
undefined identifier `xcb_flush`
}
(alias) object.string = string
string
(local variable) string latestDrafts
latestDrafts
;
ulong
(local variable) ulong observedGeneration
observedGeneration
;
bool
bool editor_native_close_probe.main.hasDraft(string expected) @system
hasDraft
(
(alias) object.string = string
string
(parameter) string expected
expected
) @system
{ foreach (
(local variable) std.file.DirEntry archive
archive
;
std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safe

Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

Note

The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Example

// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

To handle subdirectories with denied read permission, use SpanMode.shallow:

void scan(string path)
{
    foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
    {
        try
        {
            writeln(entry.name);
            if (entry.isDir)
                scan(entry.name);
        }
        catch (FileException fe) { continue; } // ignore
    }
}

scan("");

Examples

Duplicate functionality of D1's std.file.listdir():

string[] listdir(string pathname)
{
    import std.algorithm.iteration : map, filter;
    import std.array : array;
    import std.path : baseName;

    return dirEntries(pathname, SpanMode.shallow)
        .filter!(a => a.isFile)
        .map!((return a) => baseName(a.name))
        .array;
}

// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
    import std.stdio : writefln;

    string[] files = listdir(args[1]);
    writefln("%s", files);
}
@paramuseDIP1000 used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.@parampath The directory to iterate over. If empty, the current directory will be iterated.@parampattern Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under globMatch.@parammode Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).@paramfollowSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over.@returnsAn input range of DirEntry.@throws
  • FileException if the path directory does not exist or read permission is denied.

  • FileException if mode is not shallow and a subdirectory cannot be read.

dirEntries
(
(local variable) const(string) state
state
,
(enum) std.file.SpanMode

Dictates directory spanning policy for dirEntries (see below).

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;

alias removeRoot = (return scope e) => e.relativePath(root);

assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    [buildPath("animals", "cat"), "animals"]));

assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["animals", buildPath("animals", "cat")]));

root.buildPath("plants").mkdir;

assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
    ["animals", "plants"]));
SpanMode
.
(enum value) std.file.SpanMode.shallow = 0

Only spans one directory.

shallow
))
{ if (!
(local variable) std.file.DirEntry archive
archive
.
bool std.file.DirEntry.isDir() @property scope @safe
isDir
||
(local variable) std.file.DirEntry archive
archive
.
bool std.file.DirEntry.isSymlink() @property scope @safe
isSymlink
) continue;
foreach (
(local variable) std.file.DirEntry file
file
;
std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safe

Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

Note

The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Example

// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

To handle subdirectories with denied read permission, use SpanMode.shallow:

void scan(string path)
{
    foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
    {
        try
        {
            writeln(entry.name);
            if (entry.isDir)
                scan(entry.name);
        }
        catch (FileException fe) { continue; } // ignore
    }
}

scan("");

Examples

Duplicate functionality of D1's std.file.listdir():

string[] listdir(string pathname)
{
    import std.algorithm.iteration : map, filter;
    import std.array : array;
    import std.path : baseName;

    return dirEntries(pathname, SpanMode.shallow)
        .filter!(a => a.isFile)
        .map!((return a) => baseName(a.name))
        .array;
}

// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
    import std.stdio : writefln;

    string[] files = listdir(args[1]);
    writefln("%s", files);
}
@paramuseDIP1000 used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.@parampath The directory to iterate over. If empty, the current directory will be iterated.@parampattern Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under globMatch.@parammode Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).@paramfollowSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over.@returnsAn input range of DirEntry.@throws
  • FileException if the path directory does not exist or read permission is denied.

  • FileException if mode is not shallow and a subdirectory cannot be read.

dirEntries
(
(local variable) std.file.DirEntry archive
archive
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
,
(enum) std.file.SpanMode

Dictates directory spanning policy for dirEntries (see below).

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;

alias removeRoot = (return scope e) => e.relativePath(root);

assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    [buildPath("animals", "cat"), "animals"]));

assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["animals", buildPath("animals", "cat")]));

root.buildPath("plants").mkdir;

assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
    ["animals", "plants"]));
SpanMode
.
(enum value) std.file.SpanMode.shallow = 0

Only spans one directory.

shallow
))
{ const
(local variable) const(ulong) generation
generation
=
ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safe

Recognize a canonical positive generation filename; zero means an unrelated entry.

sessionGenerationOfName
(
string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Note

This function only strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use stripExtension. To obtain the filename without leading directories and without an extension, combine the functions like this:

assert(baseName(stripExtension("dir/file.ext")) == "file");
@paramcs Whether or not suffix matching is case-sensitive.@parampath A path name. It can be a string, or any random-access range of characters.@paramsuffix An optional suffix to be removed from the file name.@returns

The name of the file in the path name, without any leading directory and with an optional suffix chopped off.

If suffix is specified, it will be compared to path using filenameCmp!cs, where cs is an optional template parameter determining whether the comparison is case sensitive or not. See the filenameCmp documentation for details.

@standardsThis function complies with the POSIX requirements for the 'basename' shell utility (with suitable adaptations for Windows paths).
baseName
(
(local variable) std.file.DirEntry file
file
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
));
if (!
(local variable) const(ulong) generation
generation
) continue;
const
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
=
sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safe

Validate the complete immutable record and its identity before returning recovered contents.

Examples

A newer generation and a refused duplicate leave earlier dirty contents recoverable.

version (Posix) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("The native POSIX archive adapter is not available.");
}
import sparkles.test_utils.tmpfs : TmpFS;
import std.file : readText;
auto fixture = TmpFS.create();
const source = fixture.writeFile("disk");
SessionRecord record;
record.generation = 1;
record.active = 7;
record.tabs = [SessionTab(id: 7, path: source, name: "draft", content: "dirty\r\n",
    savedContent: "disk", selections: [SessionSelection(0, 0)])];
const first = appendSessionGeneration(fixture.dir, record);
assert(first.hasValue && first.value.durable);
record.generation = 2;
record.tabs[0].content = "newer\r\n";
const second = appendSessionGeneration(fixture.dir, record);
assert(second.hasValue && second.value.durable);
record.generation = 1;
assert(appendSessionGeneration(fixture.dir, record).hasError);
const old = readSessionGeneration(fixture.dir, 1);
const latest = readSessionGeneration(fixture.dir, 2);
assert(old.hasValue && old.value.tabs[0].content == "dirty\r\n");
assert(latest.hasValue && latest.value.tabs[0].content == "newer\r\n");
assert((() @trusted => readText(source))() == "disk");

Retention preserves damaged and future generations while bounding older valid files.

version (linux) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("The native recovery archive currently requires Linux.");
}
import sparkles.recovery.directory : SessionDirectory = LeasedDirectory;
import sparkles.test_utils.tmpfs : TmpFS;
import std.conv : text;
import std.file : write;
auto fixture = TmpFS.create();
auto directory = SessionDirectory.create(buildPath(fixture.dir, "archives"), fixture.dir);
assert(directory.hasValue);
scope (exit) directory.value.close();
SessionRecord record;
record.active = 7;
record.tabs = [SessionTab(id: 7, name: "draft", selections: [SessionSelection(0, 0)])];
foreach (generation; 1UL .. 6UL)
{
    record.generation = generation;
    record.tabs[0].content = text(generation);
    assert(appendSessionGeneration(directory.value.path, record).hasValue);
}
(() @trusted { write(buildPath(directory.value.path, "00000000000000000002.session"), "damaged"); })();
const report = pruneSessionArchive(directory.value, 4);
assert(report.removed.length == 1 && report.removed[0] == 1 && report.issues.length == 1);
assert(readSessionGeneration(directory.value.path, 1).hasError);
assert(readSessionGeneration(directory.value.path, 3).hasValue);
assert(readSessionGeneration(directory.value.path, 4).hasValue);
assert(readSessionGeneration(directory.value.path, 5).hasValue);
import std.file : readText;
assert((() @trusted => readText(buildPath(directory.value.path, "00000000000000000002.session")))() == "damaged");
readSessionGeneration
(
(local variable) std.file.DirEntry archive
archive
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
,
(local variable) const(ulong) generation
generation
);
if (
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
bool sparkles.base.expected.Expected!(session_record.SessionRecord, string, sparkles.base.expected.Abort).hasError!()() const pure nothrow @nogc @property @safe

Checks if Expected has error

hasError
) continue;
if (
(local variable) const(ulong) generation
generation
>=
(local variable) ulong observedGeneration
observedGeneration
)
{
(local variable) ulong observedGeneration
observedGeneration
=
(local variable) const(ulong) generation
generation
;
(local variable) string latestDrafts
latestDrafts
= "";
foreach (
(parameter) const(session_record.SessionTab) tab
tab
;
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabs
tabs
)
(local variable) string latestDrafts
latestDrafts
~= "[" ~
(local variable) const(session_record.SessionTab) tab
tab
.
(field) string session_record.SessionTab.content
content
~ "]";
} foreach (
(parameter) const(session_record.SessionTab) tab
tab
;
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabs
tabs
) if (
(local variable) const(session_record.SessionTab) tab
tab
.
(field) string session_record.SessionTab.content
content
==
(parameter) string expected
expected
) return true;
} } return false; } void
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
(
(alias) object.string = string
string
(parameter) string expected
expected
) @system
{ const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
bool editor_native_close_probe.main.hasDraft(string expected) @system
hasDraft
(
(parameter) string expected
expected
) &&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
deadline
)
{ assert(!
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.Pid child
child
).terminated,
(field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0
readText
(
(local variable) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs);
} assert(
bool editor_native_close_probe.main.hasDraft(string expected) @system
hasDraft
(
(parameter) string expected
expected
), "Expected recovery contents were not checkpointed: " ~
(parameter) string expected
expected
~ "; latest private-fixture tabs: " ~
(local variable) string latestDrafts
latestDrafts
~ "\n" ~
string std.file.readText!(string, string)(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) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
} if (
(parameter) string[] args
args
.
(field) ulong string[].length
length
== 3 && (
(parameter) string[] args
args
[2] == "--clipboard" ||
(parameter) string[] args
args
[2] == "--clipboard-withdrawal"))
{ const
(local variable) const(uint) clipboard
clipboard
=
uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @system
atom
("CLIPBOARD"),
(local variable) const(uint) targets
targets
=
uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @system
atom
("TARGETS"),
(local variable) const(uint) utf8
utf8
=
uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @system
atom
("UTF8_STRING");
const
(local variable) const(_error_) owner
owner
= xcb_generate_id(connection);
undefined identifier `xcb_generate_id`
xcb_create_window(connection, 0, owner, root, -1, -1, 1, 1, 0,
undefined identifier `xcb_create_window`
XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, 0, null); xcb_set_selection_owner(connection, owner, clipboard, XCB_CURRENT_TIME);
undefined identifier `xcb_set_selection_owner`
xcb_flush(connection);
undefined identifier `xcb_flush`
xcb_selection_request_event_t[]
(local variable) _error_ requests
requests
;
undefined identifier `xcb_selection_request_event_t`
bool
(local variable) bool advertised
advertised
;
void
editor_native_close_probe.main.answer
answer
(in xcb_selection_request_event_t
(parameter) xcb_selection_request_event_t request
request
,
(alias) object.string = string
string
(parameter) string value
value
, bool advertise = false)
undefined identifier `xcb_selection_request_event_t`
{ const
_error_ property
property
= request.
request.property
property
== XCB_NONE ? request.target : request.
request.property
property
;
if (advertise) { uint[2]
_error_ supported
supported
= [targets, utf8];
xcb_change_property(connection, XCB_PROP_MODE_REPLACE, request.requestor, property, XCB_ATOM_ATOM, 32, 2, supported.ptr); } else xcb_change_property(connection, XCB_PROP_MODE_REPLACE, request.requestor, property, utf8, 8, cast(uint) value.
value.length
length
, value.ptr);
xcb_selection_notify_event_t
_error_ response
response
;
response.response_type = XCB_SELECTION_NOTIFY; response.
response.time
time
= request.
request.time
time
;
response.requestor = request.requestor; response.selection = request.selection; response.target = request.target; response.
response.property
property
= property;
xcb_send_event(connection, 0, request.requestor, XCB_EVENT_MASK_NO_EVENT, cast(const(char)*) &response); xcb_flush(connection); } void
void editor_native_close_probe.main.pump() pure nothrow @nogc @safe
pump
()
{ while (auto
(local variable) _error_ event
event
= xcb_poll_for_event(connection))
undefined identifier `xcb_poll_for_event`
{ scope (exit)
void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
(event);
if ((event.response_type & 0x7F) != XCB_SELECTION_REQUEST) continue;
undefined identifier `XCB_SELECTION_REQUEST`
const
(local variable) const(_error_) request
request
= *cast(xcb_selection_request_event_t*) event;
undefined identifier `xcb_selection_request_event_t`
if (request.target ==
(local variable) const(uint) targets
targets
) { answer(request, "", true);
(local variable) bool advertised
advertised
= true; }
else { assert(request.target ==
(local variable) const(uint) utf8
utf8
); requests ~= request; }
} } const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) offerDeadline
offerDeadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
(local variable) bool advertised
advertised
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
offerDeadline
) {
void editor_native_close_probe.main.pump() pure nothrow @nogc @safe
pump
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs); }
assert(
(local variable) bool advertised
advertised
, "The native backend did not discover the private clipboard offer.");
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
void
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safe
awaitRequest
(
(alias) object.size_t = ulong
size_t
(parameter) ulong count
count
)
{ const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (requests.
(field) _error_ requests.length
length
<
(parameter) ulong count
count
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
)
{ assert(!
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.Pid child
child
).terminated,
(field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0
readText
(
(local variable) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
void editor_native_close_probe.main.pump() pure nothrow @nogc @safe
pump
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs);
} assert(requests.
(field) _error_ requests.length
length
==
(parameter) ulong count
count
, text("Expected ", count,
" native clipboard requests, received ", requests.
requests.length
length
, '.'));
}
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(55, XCB_MOD_MASK_CONTROL); // Ctrl+V in the first tab; hold its reply.
undefined identifier `XCB_MOD_MASK_CONTROL`
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safe
awaitRequest
(1);
const
(local variable) const(bool) withdrawn
withdrawn
=
(parameter) string[] args
args
[2] == "--clipboard-withdrawal";
if (
(local variable) const(bool) withdrawn
withdrawn
)
foreach (
(local variable) int iteration
iteration
; 0 .. 8)
{ const
(local variable) const(_error_) replacement
replacement
= xcb_generate_id(connection);
undefined identifier `xcb_generate_id`
xcb_create_window(connection, 0, replacement, root, -1, -1, 1, 1, 0,
undefined identifier `xcb_create_window`
XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, 0, null);
(local variable) bool advertised
advertised
= false;
xcb_set_selection_owner(connection, replacement, clipboard, XCB_CURRENT_TIME);
undefined identifier `xcb_set_selection_owner`
xcb_flush(connection);
undefined identifier `xcb_flush`
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) replacementDeadline
replacementDeadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
(local variable) bool advertised
advertised
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
replacementDeadline
)
{
void editor_native_close_probe.main.pump() pure nothrow @nogc @safe
pump
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs); }
assert(
(local variable) bool advertised
advertised
, "The replacement provider was not discovered.");
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
if (
(local variable) int iteration
iteration
!= 7)
{
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(55, XCB_MOD_MASK_CONTROL);
undefined identifier `XCB_MOD_MASK_CONTROL`
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safe
awaitRequest
(
(local variable) int iteration
iteration
+ 2);
} }
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(57, XCB_MOD_MASK_CONTROL); // Ctrl+N creates a second tab.
undefined identifier `XCB_MOD_MASK_CONTROL`
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(55, XCB_MOD_MASK_CONTROL);
undefined identifier `XCB_MOD_MASK_CONTROL`
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safe
awaitRequest
(
(local variable) const(bool) withdrawn
withdrawn
? 9 : 2);
if (
(local variable) const(bool) withdrawn
withdrawn
)
{ answer(requests[0], "STALE PROVIDER"); answer(requests[1], "ANOTHER STALE PROVIDER"); // This later key is an X11 ordering barrier. Its checkpoint must // not contain bytes from the withdrawn transfer, even briefly.
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(53); // x
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
("x");
answer(requests[$ - 1], "from B");
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
("xfrom B");
} else { answer(requests[1], "from B");
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
("from B");
answer(requests[0], "from A"); } bool
(local variable) bool paired
paired
;
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) pairDeadline
pairDeadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
(local variable) bool paired
paired
&&
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
pairDeadline
)
{ foreach (
(local variable) std.file.DirEntry archive
archive
;
std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safe

Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

Note

The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Example

// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

To handle subdirectories with denied read permission, use SpanMode.shallow:

void scan(string path)
{
    foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
    {
        try
        {
            writeln(entry.name);
            if (entry.isDir)
                scan(entry.name);
        }
        catch (FileException fe) { continue; } // ignore
    }
}

scan("");

Examples

Duplicate functionality of D1's std.file.listdir():

string[] listdir(string pathname)
{
    import std.algorithm.iteration : map, filter;
    import std.array : array;
    import std.path : baseName;

    return dirEntries(pathname, SpanMode.shallow)
        .filter!(a => a.isFile)
        .map!((return a) => baseName(a.name))
        .array;
}

// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
    import std.stdio : writefln;

    string[] files = listdir(args[1]);
    writefln("%s", files);
}
@paramuseDIP1000 used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.@parampath The directory to iterate over. If empty, the current directory will be iterated.@parampattern Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under globMatch.@parammode Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).@paramfollowSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over.@returnsAn input range of DirEntry.@throws
  • FileException if the path directory does not exist or read permission is denied.

  • FileException if mode is not shallow and a subdirectory cannot be read.

dirEntries
(
(local variable) const(string) state
state
,
(enum) std.file.SpanMode

Dictates directory spanning policy for dirEntries (see below).

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;

alias removeRoot = (return scope e) => e.relativePath(root);

assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    [buildPath("animals", "cat"), "animals"]));

assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["animals", buildPath("animals", "cat")]));

root.buildPath("plants").mkdir;

assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
    ["animals", "plants"]));
SpanMode
.
(enum value) std.file.SpanMode.shallow = 0

Only spans one directory.

shallow
))
{ if (!
(local variable) std.file.DirEntry archive
archive
.
bool std.file.DirEntry.isDir() @property scope @safe
isDir
) continue;
foreach (
(local variable) std.file.DirEntry file
file
;
std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safe

Returns an input range of DirEntry that lazily iterates a given directory, also provides two ways of foreach iteration. The iteration variable can be of type string if only the name is needed, or DirEntry if additional details are needed. The span mode dictates how the directory is traversed. The name of each iterated directory entry contains the absolute or relative path (depending on pathname).

Note

The order of returned directory entries is as it is provided by the operating system / filesystem, and may not follow any particular sorting.

Example

// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
    remove(name);
}

// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
    writeln(name);
}

// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
    writeln(e.name, "\t", e.size);
}

// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
    writeln(d.name);

// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
    string cmd = "dmd -c "  ~ d.name;
    writeln(cmd);
    std.process.executeShell(cmd);
}

// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
    writeln(d.name);

To handle subdirectories with denied read permission, use SpanMode.shallow:

void scan(string path)
{
    foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
    {
        try
        {
            writeln(entry.name);
            if (entry.isDir)
                scan(entry.name);
        }
        catch (FileException fe) { continue; } // ignore
    }
}

scan("");

Examples

Duplicate functionality of D1's std.file.listdir():

string[] listdir(string pathname)
{
    import std.algorithm.iteration : map, filter;
    import std.array : array;
    import std.path : baseName;

    return dirEntries(pathname, SpanMode.shallow)
        .filter!(a => a.isFile)
        .map!((return a) => baseName(a.name))
        .array;
}

// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
    import std.stdio : writefln;

    string[] files = listdir(args[1]);
    writefln("%s", files);
}
@paramuseDIP1000 used to instantiate this function separately for code with and without -preview=dip1000 compiler switch, because it affects the ABI of this function. Set automatically - don't touch.@parampath The directory to iterate over. If empty, the current directory will be iterated.@parampattern Optional string with wildcards, such as "*.d". When present, it is used to filter the results by their file name. The supported wildcard strings are described under globMatch.@parammode Whether the directory's sub-directories should be iterated in depth-first post-order (depth), depth-first pre-order (breadth), or not at all (shallow).@paramfollowSymlink Whether symbolic links which point to directories should be treated as directories and their contents iterated over.@returnsAn input range of DirEntry.@throws
  • FileException if the path directory does not exist or read permission is denied.

  • FileException if mode is not shallow and a subdirectory cannot be read.

dirEntries
(
(local variable) std.file.DirEntry archive
archive
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
,
(enum) std.file.SpanMode

Dictates directory spanning policy for dirEntries (see below).

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;

auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;

root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;

alias removeRoot = (return scope e) => e.relativePath(root);

assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
    [buildPath("animals", "cat"), "animals"]));

assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
    ["animals", buildPath("animals", "cat")]));

root.buildPath("plants").mkdir;

assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
    ["animals", "plants"]));
SpanMode
.
(enum value) std.file.SpanMode.shallow = 0

Only spans one directory.

shallow
))
{ const
(local variable) const(ulong) generation
generation
=
ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safe

Recognize a canonical positive generation filename; zero means an unrelated entry.

sessionGenerationOfName
(
string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safe

Note

This function only strips away the specified suffix, which doesn't necessarily have to represent an extension. To remove the extension from a path, regardless of what the extension is, use stripExtension. To obtain the filename without leading directories and without an extension, combine the functions like this:

assert(baseName(stripExtension("dir/file.ext")) == "file");
@paramcs Whether or not suffix matching is case-sensitive.@parampath A path name. It can be a string, or any random-access range of characters.@paramsuffix An optional suffix to be removed from the file name.@returns

The name of the file in the path name, without any leading directory and with an optional suffix chopped off.

If suffix is specified, it will be compared to path using filenameCmp!cs, where cs is an optional template parameter determining whether the comparison is case sensitive or not. See the filenameCmp documentation for details.

@standardsThis function complies with the POSIX requirements for the 'basename' shell utility (with suitable adaptations for Windows paths).
baseName
(
(local variable) std.file.DirEntry file
file
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
));
if (!
(local variable) const(ulong) generation
generation
) continue;
const
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
=
sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safe

Validate the complete immutable record and its identity before returning recovered contents.

Examples

A newer generation and a refused duplicate leave earlier dirty contents recoverable.

version (Posix) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("The native POSIX archive adapter is not available.");
}
import sparkles.test_utils.tmpfs : TmpFS;
import std.file : readText;
auto fixture = TmpFS.create();
const source = fixture.writeFile("disk");
SessionRecord record;
record.generation = 1;
record.active = 7;
record.tabs = [SessionTab(id: 7, path: source, name: "draft", content: "dirty\r\n",
    savedContent: "disk", selections: [SessionSelection(0, 0)])];
const first = appendSessionGeneration(fixture.dir, record);
assert(first.hasValue && first.value.durable);
record.generation = 2;
record.tabs[0].content = "newer\r\n";
const second = appendSessionGeneration(fixture.dir, record);
assert(second.hasValue && second.value.durable);
record.generation = 1;
assert(appendSessionGeneration(fixture.dir, record).hasError);
const old = readSessionGeneration(fixture.dir, 1);
const latest = readSessionGeneration(fixture.dir, 2);
assert(old.hasValue && old.value.tabs[0].content == "dirty\r\n");
assert(latest.hasValue && latest.value.tabs[0].content == "newer\r\n");
assert((() @trusted => readText(source))() == "disk");

Retention preserves damaged and future generations while bounding older valid files.

version (linux) {}
else
{
    import sparkles.test_runner.skip : skipTest;
    skipTest("The native recovery archive currently requires Linux.");
}
import sparkles.recovery.directory : SessionDirectory = LeasedDirectory;
import sparkles.test_utils.tmpfs : TmpFS;
import std.conv : text;
import std.file : write;
auto fixture = TmpFS.create();
auto directory = SessionDirectory.create(buildPath(fixture.dir, "archives"), fixture.dir);
assert(directory.hasValue);
scope (exit) directory.value.close();
SessionRecord record;
record.active = 7;
record.tabs = [SessionTab(id: 7, name: "draft", selections: [SessionSelection(0, 0)])];
foreach (generation; 1UL .. 6UL)
{
    record.generation = generation;
    record.tabs[0].content = text(generation);
    assert(appendSessionGeneration(directory.value.path, record).hasValue);
}
(() @trusted { write(buildPath(directory.value.path, "00000000000000000002.session"), "damaged"); })();
const report = pruneSessionArchive(directory.value, 4);
assert(report.removed.length == 1 && report.removed[0] == 1 && report.issues.length == 1);
assert(readSessionGeneration(directory.value.path, 1).hasError);
assert(readSessionGeneration(directory.value.path, 3).hasValue);
assert(readSessionGeneration(directory.value.path, 4).hasValue);
assert(readSessionGeneration(directory.value.path, 5).hasValue);
import std.file : readText;
assert((() @trusted => readText(buildPath(directory.value.path, "00000000000000000002.session")))() == "damaged");
readSessionGeneration
(
(local variable) std.file.DirEntry archive
archive
.
string std.file.DirEntry.name() const pure nothrow @property return scope @safe
name
,
(local variable) const(ulong) generation
generation
);
if (
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
bool sparkles.base.expected.Expected!(session_record.SessionRecord, 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!(SessionRecord, string, Abort)) record
record
.
inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabs
tabs
.
(field) ulong const(session_record.SessionTab[]).length
length
== 2
&&
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabs
tabs
[0].
(field) string session_record.SessionTab.content
content
== (
(local variable) const(bool) withdrawn
withdrawn
? "" : "from A")
&&
(local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) record
record
.
inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabs
tabs
[1].
(field) string session_record.SessionTab.content
content
== (
(local variable) const(bool) withdrawn
withdrawn
? "xfrom B" : "from B"))
(local variable) bool paired
paired
= true;
} }
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs);
} assert(
(local variable) bool paired
paired
, "Out-of-order native clipboard replies did not retain their requesting tabs.");
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @system
closeWindow
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
if (!
(local variable) const(bool) withdrawn
withdrawn
)
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(40);
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(40);
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
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.Pid child
child
).terminated &&
(field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
deadline
)
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(10.msecs);
assert(
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.Pid child
child
).terminated &&
(field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0
tryWait
(
(local variable) std.process.Pid child
child
).status == 0,
(field) int std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_1
readText
(
(local variable) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
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) const(bool) withdrawn
withdrawn
? "withdrawn X11 clipboard replies did not reach a replacement transfer"
: "out-of-order native X11 clipboard replies retained their requesting tabs"); return 0; }
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(38); // Xvfb's default XKB map: a.
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
("a");
void std.process.kill(std.process.Pid pid, int codeOrSignal)
kill
(
(local variable) std.process.Pid child
child
,
(constant) int core.sys.posix.signal.SIGKILL = 9
SIGKILL
); // Only the process owned by this probe.
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.Pid child
child
);
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
(local variable) std.process.Pid child
child
=
std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safe

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. It is recommended to always call wait on the returned Pid unless the process was spawned with Config.detached flag, as detailed in the documentation for wait.

Command line

There are four overloads of this function. The first two take an array of strings, args, which should contain the program name as the zeroth element and any command-line arguments in subsequent elements. The third and fourth versions are included for convenience, and may be used when there are no command-line arguments. They take a single string, program, which specifies the program name.

Unless a directory is specified in args`[0]` or `program`, spawnProcess`` will search for the program in a platform-dependent manner. On POSIX systems, it will look for the executable in the directories listed in the PATH environment variable, in the order they are listed. On Windows, it will search for the executable in the following sequence:

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. The 32-bit Windows system directory.

  4. The 16-bit Windows system directory.

  5. The Windows directory.

  6. The directories listed in the PATH environment variable.

// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs.  The scope guard
// ensures that the process is waited for at the end of the scope.
...

// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
    writeln("Compilation failed!");

Environment variables

By default, the child process inherits the environment of the parent process, along with any additional variables specified in the env parameter. If the same variable exists in both the parent's environment and in env, the latter takes precedence.

If the Config.newEnv flag is set in config, the child process will not inherit the parent's environment. Its entire environment will then be determined by env.

wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));

Standard streams

The optional arguments stdin, stdout and stderr may be used to assign arbitrary File objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. The default is for the child process to inherit the standard streams of its parent.

// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
                        std.stdio.stdin,
                        std.stdio.stdout,
                        logFile);
if (wait(pid) != 0)
    writeln("Compilation failed. See errors.log for details.");

Note that if you pass a File object that is not one of the standard input/output/error streams of the parent process, that stream will by default be closed in the parent process when this function returns. See the Config documentation below for information about how to disable this behaviour.

Beware of buffering issues when passing File objects to spawnProcess. The child process will inherit the low-level raw read/write offset associated with the underlying file descriptor, but it will not be aware of any buffered data. In cases where this matters (e.g. when a file should be aligned before being passed on to the child process), it may be a good idea to use unbuffered streams, or at least ensure all relevant buffers are flushed.

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements.@paramstdin The standard input stream of the child process. This can be any File that is opened for reading. By default the child process inherits the parent's input stream.@paramstdout The standard output stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's output stream.@paramstderr The standard error stream of the child process. This can be any File that is opened for writing. By default the child process inherits the parent's error stream.@paramenv Additional environment variables for the child process.@paramconfig Flags that control process creation. See Config for an overview of available flags.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@returnsA Pid object that corresponds to the spawned process.@throws

ProcessException on failure to start the process.

StdioException on failure to pass one of the streams to the child process (Windows only).

RangeError if args is empty.

spawnProcess
([
(local variable) const(string) editor
editor
,
"--gui", "--window-system", "x11", "--state-dir",
(local variable) const(string) state
state
], stdin,
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdin"() nothrow @nogc @property ref @system
log
,
(local variable) std.stdio.File log
log
,
null,
(struct) std.process.Config

Options that control the behaviour of process creation functions in this module. Most options only apply to spawnProcess and spawnShell.

Example

auto logFile = File("myapp_error.log", "w");

// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
                        Config.retainStderr | Config.suppressConsole);
scope(exit)
{
    auto exitCode = wait(pid);
    logFile.writeln("myapp exited with code ", exitCode);
    logFile.close();
}
Config
.
(constant) std.process.Config std.process.Config.retainStdout = Config(Flags.retainStdout, null, null)

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

retainStdout
|
std.process.Config std.process.Config.opBinary!"|"(std.process.Config other) pure nothrow @nogc @safe

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

Config
.
(constant) std.process.Config std.process.Config.retainStderr = Config(Flags.retainStderr, null, null)

For backwards compatibility, and cases when only flags need to be specified in the Config, these allow building Config instances using flag names only.

retainStderr
);
void editor_native_close_probe.main.findWindow() nothrow @system
findWindow
();
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(70); // F4, R: the shared Restore command.
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(27);
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(36); // Enter accepts the offer.
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(56); // b continues editing at the restored caret.
void editor_native_close_probe.main.awaitDraft(string expected) @system
awaitDraft
("ab");
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @system
closeWindow
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(250.msecs);
assert(!
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.Pid child
child
).terminated, "Native close discarded dirty text.");
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(9); // Escape cancels the close decision.
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(150.msecs);
assert(!
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.Pid child
child
).terminated);
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @system
closeWindow
();
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(250.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @system
key
(40); // d explicitly discards the dirty document.
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadline
deadline
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
+ 5.seconds;
while (!
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.Pid child
child
).terminated &&
(field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.

On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.

Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.

currTime
<
int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safe

Compares this MonoTime with the given MonoTime.

@returns| this &lt; rhs | &lt; 0 | | this == rhs | 0 | | this &gt; rhs | &gt; 0 |
deadline
)
(class) core.thread.osthread.Thread

This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Thread
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(20.msecs);
assert(
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.Pid child
child
).terminated, "Discard did not approve native close.");
assert(
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.Pid child
child
).status == 0,
(field) int std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_1
readText
(
(local variable) std.stdio.File log
log
.
string std.stdio.File.name() const pure nothrow @property return @safe

Returns the name last used to initialize this File, if any.

Some functions that create or initialize the File set the name field to null. Examples include tmpfile, wrapFile, and fdopen. See the documentation of those functions for details.

@returnsThe name last used to initialize this this file, or null otherwise.
name
));
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
("native draft survived SIGKILL; Restore and editing produced ab; dirty close deferred; Escape retained the document; explicit Discard flushed and exited");
return 0; }