diff options
author | Alex Vallée <avallee@chromium.org> | 2015-05-06 16:26:00 -0400 |
---|---|---|
committer | Elliott Hughes <enh@google.com> | 2015-07-30 15:08:53 -0700 |
commit | 47d67c96ec991ef1690b4c07188335cbc4bfa2aa (patch) | |
tree | 172e26db49ad9f4d57b47fc17f31622e47b56558 /base/test_utils.cpp | |
parent | eb0b151369371993a70c2079b8253f6dd24814b7 (diff) |
Write mkdirs in more idiomatic C++ style.
~ Rewrote mkdirs to be in C++ style.
~ Replaced adb_dir{start,stop} with std::string params and (r)find.
+ Added test for mkdirs.
Also make base/test_utils.h public and support temporary directories
as well as files.
Change-Id: I6fcbdc5e0099f3359d3aac6b00c436f250ca1329
Diffstat (limited to 'base/test_utils.cpp')
-rw-r--r-- | base/test_utils.cpp | 43 |
1 files changed, 32 insertions, 11 deletions
diff --git a/base/test_utils.cpp b/base/test_utils.cpp index 0517bc7138..dceb8b7888 100644 --- a/base/test_utils.cpp +++ b/base/test_utils.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "test_utils.h" +#include "base/test_utils.h" #include <fcntl.h> #include <stdio.h> @@ -26,34 +26,55 @@ #include <windows.h> #endif -TemporaryFile::TemporaryFile() { +#include <string> + +static std::string GetSystemTempDir() { #if defined(__ANDROID__) - init("/data/local/tmp"); + return "/data/local/tmp"; #elif defined(_WIN32) char wd[MAX_PATH] = {}; _getcwd(wd, sizeof(wd)); - init(wd); + return wd; #else - init("/tmp"); + return "/tmp"; #endif } +TemporaryFile::TemporaryFile() { + init(GetSystemTempDir()); +} + TemporaryFile::~TemporaryFile() { close(fd); - unlink(filename); + unlink(path); } -void TemporaryFile::init(const char* tmp_dir) { - snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir); +void TemporaryFile::init(const std::string& tmp_dir) { + snprintf(path, sizeof(path), "%s/TemporaryFile-XXXXXX", tmp_dir.c_str()); #if !defined(_WIN32) - fd = mkstemp(filename); + fd = mkstemp(path); #else // Windows doesn't have mkstemp, and tmpfile creates the file in the root // directory, requiring root (?!) permissions. We have to settle for mktemp. - if (mktemp(filename) == nullptr) { + if (mktemp(path) == nullptr) { abort(); } - fd = open(filename, O_RDWR | O_NOINHERIT | O_CREAT, _S_IREAD | _S_IWRITE); + fd = open(path, O_RDWR | O_NOINHERIT | O_CREAT, _S_IREAD | _S_IWRITE); #endif } + +#if !defined(_WIN32) +TemporaryDir::TemporaryDir() { + init(GetSystemTempDir()); +} + +TemporaryDir::~TemporaryDir() { + rmdir(path); +} + +bool TemporaryDir::init(const std::string& tmp_dir) { + snprintf(path, sizeof(path), "%s/TemporaryDir-XXXXXX", tmp_dir.c_str()); + return (mkdtemp(path) != nullptr); +} +#endif |