ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
scoped_tempdir.h
Go to the documentation of this file.
1#ifndef PROVSQL_SCOPED_TEMPDIR_H
2#define PROVSQL_SCOPED_TEMPDIR_H
3
4extern "C" {
5#include <unistd.h>
6}
7
8#include <string>
9#include <vector>
10
11#include "provsql_error.h"
12
13namespace provsql {
14
15/**
16 * @brief RAII guard around a freshly mkdtemp'd /tmp directory.
17 *
18 * Wraps the boilerplate every external-tool launch shares: create a
19 * private 0700 directory, write the Tseytin CNF and any sibling files
20 * into it, and on scope exit unlink each tracked file and rmdir the
21 * directory. If the body throws (missing tool, runtime failure,
22 * malformed output), the destructor still runs and the /tmp leak is
23 * avoided. Pass @c keep() in the verbose-debug arm to leave the
24 * artifacts on disk for inspection.
25 *
26 * Best-effort: the destructor swallows unlink/rmdir errors because it
27 * must not throw during stack unwinding.
28 */
30 public:
32 char buf[] = "/tmp/provsqlXXXXXX";
33 if (mkdtemp(buf) == nullptr)
34 throw CircuitException("Cannot create temporary directory");
35 path_ = buf;
36 }
38 if (keep_) return;
39 for (const auto &f : files_) (void)::unlink(f.c_str());
40 (void)::rmdir(path_.c_str());
41 }
42 ScopedTempDir(const ScopedTempDir &) = delete;
44
45 /// Build a path under the temp dir and register it for cleanup.
46 std::string file(const std::string &basename) {
47 std::string p = path_ + "/" + basename;
48 files_.push_back(p);
49 return p;
50 }
51 /// Also track a file we did not create through @c file() (e.g. a
52 /// helper tool's scratch output sitting in @c path_).
53 void track(const std::string &p) { files_.push_back(p); }
54 /// Leave the directory on disk; cleanup is skipped at scope exit.
55 void keep() { keep_ = true; }
56 const std::string &path() const { return path_; }
57
58 private:
59 std::string path_;
60 std::vector<std::string> files_;
61 bool keep_ = false;
62};
63
64} // namespace provsql
65
66#endif // PROVSQL_SCOPED_TEMPDIR_H
Exception type thrown by circuit operations on invalid input.
Definition Circuit.h:206
std::string file(const std::string &basename)
Build a path under the temp dir and register it for cleanup.
void track(const std::string &p)
Also track a file we did not create through file() (e.g.
ScopedTempDir(const ScopedTempDir &)=delete
const std::string & path() const
void keep()
Leave the directory on disk; cleanup is skipped at scope exit.
ScopedTempDir & operator=(const ScopedTempDir &)=delete
std::vector< std::string > files_
Uniform error-reporting macros for ProvSQL.