19 #define foreach(it_type, it, collection) \
20 for (it_type it = (collection).begin(); it != (collection).end(); ++it)
22 #define foreach_reverse(it_type, it, collection) \
23 for (it_type it = (collection).rbegin(); it != (collection).rend(); ++it)
26 /* Return an environment variable. */
27 string
getEnv(const string
& key
, const string
& def
= "");
29 /* Return an absolutized path, resolving paths relative to the
30 specified directory, or the current directory otherwise. The path
31 is also canonicalised. */
32 Path
absPath(Path path
, Path dir
= "");
34 /* Canonicalise a path by removing all `.' or `..' components and
35 double or trailing slashes. Optionally resolves all symlink
36 components such that each component of the resulting path is *not*
38 Path
canonPath(const Path
& path
, bool resolveSymlinks
= false);
40 /* Return the directory part of the given canonical path, i.e.,
41 everything before the final `/'. If the path is the root or an
42 immediate child thereof (e.g., `/foo'), this means an empty string
44 Path
dirOf(const Path
& path
);
46 /* Return the base name of the given canonical path, i.e., everything
47 following the final `/'. */
48 string
baseNameOf(const Path
& path
);
50 /* Check whether a given path is a descendant of the given
52 bool isInDir(const Path
& path
, const Path
& dir
);
54 /* Get status of `path'. */
55 struct stat
lstat(const Path
& path
);
57 /* Return true iff the given path exists. */
58 bool pathExists(const Path
& path
);
60 /* Read the contents (target) of a symbolic link. The result is not
61 in any way canonicalised. */
62 Path
readLink(const Path
& path
);
64 bool isLink(const Path
& path
);
66 /* Read the contents of a directory. The entries `.' and `..' are
72 unsigned char type
; // one of DT_*
73 DirEntry(const string
& name
, ino_t ino
, unsigned char type
)
74 : name(name
), ino(ino
), type(type
) { }
77 typedef vector
<DirEntry
> DirEntries
;
79 DirEntries
readDirectory(const Path
& path
);
81 unsigned char getFileType(const Path
& path
);
83 /* Read the contents of a file into a string. */
84 string
readFile(int fd
);
85 string
readFile(const Path
& path
, bool drain
= false);
87 /* Write a string to a file. */
88 void writeFile(const Path
& path
, const string
& s
);
90 /* Read a line from a file descriptor. */
91 string
readLine(int fd
);
93 /* Write a line to a file descriptor. */
94 void writeLine(int fd
, string s
);
96 /* Delete a path; i.e., in the case of a directory, it is deleted
97 recursively. Don't use this at home, kids. The second variant
98 returns the number of bytes and blocks freed, and 'linkThreshold' denotes
99 the number of links under which a file is accounted for in 'bytesFreed'. */
100 void deletePath(const Path
& path
);
102 void deletePath(const Path
& path
, unsigned long long & bytesFreed
,
103 size_t linkThreshold
= 1);
105 /* Create a temporary directory. */
106 Path
createTempDir(const Path
& tmpRoot
= "", const Path
& prefix
= "nix",
107 bool includePid
= true, bool useGlobalCounter
= true, mode_t mode
= 0755);
109 /* Create a directory and all its parents, if necessary. Returns the
110 list of created directories, in order of creation. */
111 Paths
createDirs(const Path
& path
);
113 /* Create a symlink. */
114 void createSymlink(const Path
& target
, const Path
& link
);
117 template<class T
, class A
>
118 T
singleton(const A
& a
)
130 ltPretty
, /* nice, nested output */
131 ltEscapes
, /* nesting indicated using escape codes (for log2xml) */
132 ltFlat
/* no nesting */
135 extern LogType logType
;
136 extern Verbosity verbosity
; /* suppress msgs > this */
145 void open(Verbosity level
, const FormatOrString
& fs
);
149 void printMsg_(Verbosity level
, const FormatOrString
& fs
);
151 #define startNest(varName, level, f) \
153 if (level <= verbosity) { \
154 varName.open(level, (f)); \
157 #define printMsg(level, f) \
159 if (level <= nix::verbosity) { \
160 nix::printMsg_(level, (f)); \
164 #define debug(f) printMsg(lvlDebug, f)
166 void warnOnce(bool & haveWarned
, const FormatOrString
& fs
);
168 void writeToStderr(const string
& s
);
170 extern void (*_writeToStderr
) (const unsigned char * buf
, size_t count
);
173 /* Wrappers arount read()/write() that read/write exactly the
174 requested number of bytes. */
175 void readFull(int fd
, unsigned char * buf
, size_t count
);
176 void writeFull(int fd
, const unsigned char * buf
, size_t count
);
177 void writeFull(int fd
, const string
& s
);
179 MakeError(EndOfFile
, Error
)
182 /* Read a file descriptor until EOF occurs. */
183 string
drainFD(int fd
);
187 /* Automatic cleanup of resources. */
191 struct AutoDeleteArray
194 AutoDeleteArray(T
* p
) : p(p
) { }
208 AutoDelete(const Path
& p
, bool recursive
= true);
220 AutoCloseFD(const AutoCloseFD
& fd
);
222 void operator =(int fd
);
223 operator int() const;
233 AutoCloseFD readSide
, writeSide
;
243 AutoCloseDir(DIR * dir
);
245 void operator =(DIR * dir
);
260 void operator =(pid_t pid
);
262 void kill(bool quiet
= false);
263 int wait(bool block
);
264 void setSeparatePG(bool separatePG
);
265 void setKillSignal(int signal
);
268 /* An "agent" is a helper program that runs in the background and that we talk
269 to over pipes, such as the "guix offload" program. */
272 /* Pipes for talking to the agent. */
275 /* Pipe for the agent's standard output/error. */
278 /* Pipe for build standard output/error--e.g., for build processes started
279 by "guix offload". */
282 /* The process ID of the agent. */
285 /* The command and arguments passed to the agent along with a list of
286 environment variable name/value pairs. */
287 Agent(const string
&command
, const Strings
&args
,
288 const std::map
<string
, string
> &env
= std::map
<string
, string
>());
294 /* Kill all processes running under the specified uid by sending them
296 void killUser(uid_t uid
);
299 /* Fork a process that runs the given function, and return the child
300 pid to the caller. */
301 pid_t
startProcess(std::function
<void()> fun
, bool dieWithParent
= true,
302 const string
& errorPrefix
= "error: ", bool runExitHandlers
= false);
305 /* Run a program and return its stdout in a string (i.e., like the
306 shell backtick operator). */
307 string
runProgram(Path program
, bool searchPath
= false,
308 const Strings
& args
= Strings());
310 MakeError(ExecError
, Error
)
312 /* Convert a list of strings to a null-terminated vector of char
313 *'s. The result must not be accessed beyond the lifetime of the
315 std::vector
<char *> stringsToCharPtrs(const Strings
& ss
);
317 /* Close all file descriptors except stdin, stdout, stderr, and those
318 listed in the given set. Good practice in child processes. */
319 void closeMostFDs(const set
<int> & exceptions
);
321 /* Set the close-on-exec flag for the given file descriptor. */
322 void closeOnExec(int fd
);
324 /* Common initialisation performed in child processes. */
325 void commonChildInit(Pipe
& logPipe
);
327 /* User interruption. */
329 extern volatile sig_atomic_t _isInterrupted
;
333 void inline checkInterrupt()
335 if (_isInterrupted
) _interrupted();
338 MakeError(Interrupted
, BaseError
)
341 /* String tokenizer. */
342 template<class C
> C
tokenizeString(const string
& s
, const string
& separators
= " \t\n\r");
345 /* Concatenate the given strings with a separator between the
347 string
concatStringsSep(const string
& sep
, const Strings
& ss
);
348 string
concatStringsSep(const string
& sep
, const StringSet
& ss
);
351 /* Remove trailing whitespace from a string. */
352 string
chomp(const string
& s
);
355 /* Convert the exit status of a child as returned by wait() into an
357 string
statusToString(int status
);
359 bool statusOk(int status
);
362 /* Parse a string into an integer. */
363 template<class N
> bool string2Int(const string
& s
, N
& n
)
365 std::istringstream
str(s
);
367 return str
&& str
.get() == EOF
;
371 /* Return true iff `s' ends in `suffix'. */
372 bool hasSuffix(const string
& s
, const string
& suffix
);
375 /* Read string `s' from stream `str'. */
376 void expect(std::istream
& str
, const string
& s
);
378 MakeError(FormatError
, Error
)
381 /* Read a C-style string from stream `str'. */
382 string
parseString(std::istream
& str
);
385 /* Utility function used to parse legacy ATerms. */
386 bool endOfList(std::istream
& str
);
389 /* Exception handling in destructors: print an error message, then
390 ignore the exception. */
391 void ignoreException();