temp-dir.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include <string>
  19. #include <vector>
  20. #include <ftw.h>
  21. #include <gtest/gtest.h>
  22. #include <sys/stat.h>
  23. #include "utils/temp-dir.h"
  24. #include "x-platform/syscall.h"
  25. namespace TestUtils {
  26. /*
  27. * Callback to remove a directory in the nftw visitor.
  28. */
  29. int nftw_remove(const char *fpath, const struct stat *sb, int typeflag,
  30. struct FTW *ftwbuf);
  31. TempDir::TempDir() {
  32. std::vector path_pattern(path_.begin(), path_.end());
  33. is_path_init_ = XPlatform::Syscall::CreateTempDir(path_pattern);
  34. EXPECT_TRUE(is_path_init_);
  35. path_.assign(path_pattern.data());
  36. }
  37. TempDir::TempDir(TempDir &&other) noexcept : path_{std::move(other.path_)} {}
  38. TempDir &TempDir::operator=(const TempDir &other) {
  39. if (&other != this) {
  40. path_ = other.path_;
  41. }
  42. return *this;
  43. }
  44. TempDir &TempDir::operator=(TempDir &&other) noexcept {
  45. if (&other != this) {
  46. path_ = std::move(other.path_);
  47. }
  48. return *this;
  49. }
  50. TempDir::~TempDir() {
  51. if (is_path_init_) {
  52. nftw(path_.c_str(), nftw_remove, 64, FTW_DEPTH | FTW_PHYS);
  53. }
  54. }
  55. int nftw_remove(const char *fpath, const struct stat *sb, int typeflag,
  56. FTW *ftwbuf) {
  57. (void)sb;
  58. (void)typeflag;
  59. (void)ftwbuf;
  60. int rv = remove(fpath);
  61. EXPECT_EQ(0, rv);
  62. return rv;
  63. }
  64. } // namespace TestUtils