1 /** Operations for Creating Temporary Files and Directories.
2     Copyright: Per Nordlöw 2018-.
3     License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4     Authors: $(WEB Per Nordlöw)
5  */
6 module nxt.tempfs;
7 
8 /** Create a New Temporary File starting with ($D namePrefix) and ending with 6 randomly defined characters.
9  *
10  * Returns: File Descriptor to opened file.
11 */
12 int tempfile(string namePrefix = null) @trusted
13 {
14     version(linux)
15     {
16         import core.sys.posix.stdlib: mkstemp;
17 
18         char[4096] buf;
19         buf[0 .. namePrefix.length] = namePrefix[]; // copy the name into the mutable buffer
20         buf[namePrefix.length .. namePrefix.length + 6] = "XXXXXX"[];
21         buf[namePrefix.length + 6] = 0; // make sure it is zero terminated yourself
22 
23         auto tmp = mkstemp(buf.ptr);
24 
25         // dbg(buf[0 .. namePrefix.length + 6]);
26         return tmp;
27     }
28 }
29 
30 /** TODO Scoped variant of tempfile.
31  *
32  * Search http://forum.dlang.org/thread/mailman.262.1386205638.3242.digitalmars-d-learn@puremagic.com
33  */
34 
35 /** Create a New Temporary Directory Tree.
36  *
37  * Returns: Path to root of tree.
38  */
39 char* temptree(char* name_x,
40                char* template_ = null) @trusted
41 {
42     return null;
43 }
44 
45 /** Returns the path to a new (unique) temporary file.
46  *
47  * See_Also: https://forum.dlang.org/post/ytmwfzmeqjumzfzxithe@forum.dlang.org
48  * See_Also: https://dlang.org/library/std/stdio/file.tmpfile.html
49  */
50 string tempFilePath(const scope string prefix,
51                     const scope string extension = null)
52 {
53     import std.uuid : randomUUID;
54     import std.file : tempDir;
55     import std.path : buildPath;
56     return buildPath(tempDir(), prefix ~ "_" ~ randomUUID.toString() ~ extension); // TODO use nxt.appending.append()
57 }