File indexing completed on 2024-05-19 05:42:29

0001 // ct_lvttst_tmpdir.cpp                                                -*-C++-*-
0002 
0003 /*
0004 // Copyright 2023 Codethink Ltd <codethink@codethink.co.uk>
0005 // SPDX-License-Identifier: Apache-2.0
0006 //
0007 // Licensed under the Apache License, Version 2.0 (the "License");
0008 // you may not use this file except in compliance with the License.
0009 // You may obtain a copy of the License at
0010 //
0011 //     http://www.apache.org/licenses/LICENSE-2.0
0012 //
0013 // Unless required by applicable law or agreed to in writing, software
0014 // distributed under the License is distributed on an "AS IS" BASIS,
0015 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0016 // See the License for the specific language governing permissions and
0017 // limitations under the License.
0018 */
0019 
0020 #include <cassert>
0021 #include <ct_lvttst_tmpdir.h>
0022 
0023 TmpDir::TmpDir(const std::string& dirname): tmp_dir(std::filesystem::temp_directory_path() / dirname)
0024 {
0025     std::filesystem::remove_all(tmp_dir);
0026     std::filesystem::create_directories(tmp_dir);
0027 }
0028 
0029 TmpDir::~TmpDir()
0030 {
0031     std::filesystem::remove_all(tmp_dir);
0032 }
0033 
0034 std::filesystem::path TmpDir::path() const
0035 {
0036     return tmp_dir;
0037 }
0038 
0039 std::filesystem::path TmpDir::createDir(const std::string& dirname) const
0040 {
0041     auto p = path() / dirname;
0042     auto r = std::filesystem::create_directories(p);
0043     (void) r;
0044     assert(r);
0045     return p;
0046 }
0047 
0048 std::filesystem::path TmpDir::createTextFile(const std::string& name, const std::string& contents) const
0049 {
0050     auto filePath = path() / std::filesystem::path(name);
0051     if (!std::filesystem::exists(filePath.parent_path())) {
0052         (void) createDir(filePath.parent_path().string());
0053     }
0054     if (std::filesystem::exists(filePath)) {
0055         std::filesystem::remove(filePath);
0056     }
0057     auto scriptStream = std::ofstream(filePath.string());
0058     scriptStream << contents;
0059     scriptStream.close();
0060     assert(std::ifstream{filePath.string()}.good());
0061     return filePath;
0062 }