18 #define foreach(it_type, it, collection) \
19 for (it_type it = (collection).begin(); it != (collection).end(); ++it)
21 #define foreach_reverse(it_type, it, collection) \
22 for (it_type it = (collection).rbegin(); it != (collection).rend(); ++it)
25 /* Return an environment variable. */
26 string
getEnv(const string
& key
, const string
& def
= "");
28 /* Return an absolutized path, resolving paths relative to the
29 specified directory, or the current directory otherwise. The path
30 is also canonicalised. */
31 Path
absPath(Path path
, Path dir
= "");
33 /* Canonicalise a path by removing all `.' or `..' components and
34 double or trailing slashes. Optionally resolves all symlink
35 components such that each component of the resulting path is *not*
37 Path
canonPath(const Path
& path
, bool resolveSymlinks
= false);
39 /* Return the directory part of the given canonical path, i.e.,
40 everything before the final `/'. If the path is the root or an
41 immediate child thereof (e.g., `/foo'), this means an empty string
43 Path
dirOf(const Path
& path
);
45 /* Return the base name of the given canonical path, i.e., everything
46 following the final `/'. */
47 string
baseNameOf(const Path
& path
);
49 /* Check whether a given path is a descendant of the given
51 bool isInDir(const Path
& path
, const Path
& dir
);
53 /* Get status of `path'. */
54 struct stat
lstat(const Path
& path
);
56 /* Return true iff the given path exists. */
57 bool pathExists(const Path
& path
);
59 /* Read the contents (target) of a symbolic link. The result is not
60 in any way canonicalised. */
61 Path
readLink(const Path
& path
);
63 bool isLink(const Path
& path
);
65 /* Read the contents of a directory. The entries `.' and `..' are
71 unsigned char type
; // one of DT_*
72 DirEntry(const string
& name
, ino_t ino
, unsigned char type
)
73 : name(name
), ino(ino
), type(type
) { }
76 typedef vector
<DirEntry
> DirEntries
;
78 DirEntries
readDirectory(const Path
& path
);
80 unsigned char getFileType(const Path
& path
);
82 /* Read the contents of a file into a string. */
83 string
readFile(int fd
);
84 string
readFile(const Path
& path
, bool drain
= false);
86 /* Write a string to a file. */
87 void writeFile(const Path
& path
, const string
& s
);
89 /* Read a line from a file descriptor. */
90 string
readLine(int fd
);
92 /* Write a line to a file descriptor. */
93 void writeLine(int fd
, string s
);
95 /* Delete a path; i.e., in the case of a directory, it is deleted
96 recursively. Don't use this at home, kids. The second variant
97 returns the number of bytes and blocks freed, and 'linkThreshold' denotes
98 the number of links under which a file is accounted for in 'bytesFreed'. */
99 void deletePath(const Path
& path
);
101 void deletePath(const Path
& path
, unsigned long long & bytesFreed
,
102 size_t linkThreshold
= 1);
104 /* Create a temporary directory. */
105 Path
createTempDir(const Path
& tmpRoot
= "", const Path
& prefix
= "nix",
106 bool includePid
= true, bool useGlobalCounter
= true, mode_t mode
= 0755);
108 /* Create a directory and all its parents, if necessary. Returns the
109 list of created directories, in order of creation. */
110 Paths
createDirs(const Path
& path
);
112 /* Create a symlink. */
113 void createSymlink(const Path
& target
, const Path
& link
);
116 template<class T
, class A
>
117 T
singleton(const A
& a
)
129 ltPretty
, /* nice, nested output */
130 ltEscapes
, /* nesting indicated using escape codes (for log2xml) */
131 ltFlat
/* no nesting */
134 extern LogType logType
;
135 extern Verbosity verbosity
; /* suppress msgs > this */
144 void open(Verbosity level
, const FormatOrString
& fs
);
148 void printMsg_(Verbosity level
, const FormatOrString
& fs
);
150 #define startNest(varName, level, f) \
152 if (level <= verbosity) { \
153 varName.open(level, (f)); \
156 #define printMsg(level, f) \
158 if (level <= nix::verbosity) { \
159 nix::printMsg_(level, (f)); \
163 #define debug(f) printMsg(lvlDebug, f)
165 void warnOnce(bool & haveWarned
, const FormatOrString
& fs
);
167 void writeToStderr(const string
& s
);
169 extern void (*_writeToStderr
) (const unsigned char * buf
, size_t count
);
172 /* Wrappers arount read()/write() that read/write exactly the
173 requested number of bytes. */
174 void readFull(int fd
, unsigned char * buf
, size_t count
);
175 void writeFull(int fd
, const unsigned char * buf
, size_t count
);
176 void writeFull(int fd
, const string
& s
);
178 MakeError(EndOfFile
, Error
)
181 /* Read a file descriptor until EOF occurs. */
182 string
drainFD(int fd
);
186 /* Automatic cleanup of resources. */
190 struct AutoDeleteArray
193 AutoDeleteArray(T
* p
) : p(p
) { }
207 AutoDelete(const Path
& p
, bool recursive
= true);
219 AutoCloseFD(const AutoCloseFD
& fd
);
221 void operator =(int fd
);
222 operator int() const;
232 AutoCloseFD readSide
, writeSide
;
242 AutoCloseDir(DIR * dir
);
244 void operator =(DIR * dir
);
259 void operator =(pid_t pid
);
261 void kill(bool quiet
= false);
262 int wait(bool block
);
263 void setSeparatePG(bool separatePG
);
264 void setKillSignal(int signal
);
267 /* An "agent" is a helper program that runs in the background and that we talk
268 to over pipes, such as the "guix offload" program. */
271 /* Pipes for talking to the agent. */
274 /* Pipe for the agent's standard output/error. */
277 /* Pipe for build standard output/error--e.g., for build processes started
278 by "guix offload". */
281 /* The process ID of the agent. */
284 /* The command and arguments passed to the agent. */
285 Agent(const string
&command
, const Strings
&args
);
291 /* Kill all processes running under the specified uid by sending them
293 void killUser(uid_t uid
);
296 /* Fork a process that runs the given function, and return the child
297 pid to the caller. */
298 pid_t
startProcess(std::function
<void()> fun
, bool dieWithParent
= true,
299 const string
& errorPrefix
= "error: ", bool runExitHandlers
= false);
302 /* Run a program and return its stdout in a string (i.e., like the
303 shell backtick operator). */
304 string
runProgram(Path program
, bool searchPath
= false,
305 const Strings
& args
= Strings());
307 MakeError(ExecError
, Error
)
309 /* Convert a list of strings to a null-terminated vector of char
310 *'s. The result must not be accessed beyond the lifetime of the
312 std::vector
<char *> stringsToCharPtrs(const Strings
& ss
);
314 /* Close all file descriptors except stdin, stdout, stderr, and those
315 listed in the given set. Good practice in child processes. */
316 void closeMostFDs(const set
<int> & exceptions
);
318 /* Set the close-on-exec flag for the given file descriptor. */
319 void closeOnExec(int fd
);
321 /* Common initialisation performed in child processes. */
322 void commonChildInit(Pipe
& logPipe
);
324 /* User interruption. */
326 extern volatile sig_atomic_t _isInterrupted
;
330 void inline checkInterrupt()
332 if (_isInterrupted
) _interrupted();
335 MakeError(Interrupted
, BaseError
)
338 /* String tokenizer. */
339 template<class C
> C
tokenizeString(const string
& s
, const string
& separators
= " \t\n\r");
342 /* Concatenate the given strings with a separator between the
344 string
concatStringsSep(const string
& sep
, const Strings
& ss
);
345 string
concatStringsSep(const string
& sep
, const StringSet
& ss
);
348 /* Remove trailing whitespace from a string. */
349 string
chomp(const string
& s
);
352 /* Convert the exit status of a child as returned by wait() into an
354 string
statusToString(int status
);
356 bool statusOk(int status
);
359 /* Parse a string into an integer. */
360 template<class N
> bool string2Int(const string
& s
, N
& n
)
362 std::istringstream
str(s
);
364 return str
&& str
.get() == EOF
;
368 /* Return true iff `s' ends in `suffix'. */
369 bool hasSuffix(const string
& s
, const string
& suffix
);
372 /* Read string `s' from stream `str'. */
373 void expect(std::istream
& str
, const string
& s
);
375 MakeError(FormatError
, Error
)
378 /* Read a C-style string from stream `str'. */
379 string
parseString(std::istream
& str
);
382 /* Utility function used to parse legacy ATerms. */
383 bool endOfList(std::istream
& str
);
386 /* Exception handling in destructors: print an error message, then
387 ignore the exception. */
388 void ignoreException();