GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/util/file_guard.h
Date: 2025-08-31 02:39:21
Exec Total Coverage
Lines: 25 25 100.0%
Branches: 4 6 66.7%

Line Branch Exec Source
1 /**
2 * This file is part of the CernVM File System.
3 */
4
5 #ifndef CVMFS_UTIL_FILE_GUARD_H_
6 #define CVMFS_UTIL_FILE_GUARD_H_
7
8 #include <unistd.h>
9
10 #include <cstdio>
11 #include <string>
12
13 #include "util/single_copy.h"
14
15 #ifdef CVMFS_NAMESPACE_GUARD
16 namespace CVMFS_NAMESPACE_GUARD {
17 #endif
18
19
20 /**
21 * RAII object to call `unlink()` on a containing file when it gets out of scope
22 */
23 class UnlinkGuard : SingleCopy {
24 public:
25 enum InitialState {
26 kEnabled,
27 kDisabled
28 };
29
30 703 inline UnlinkGuard() : enabled_(false) { }
31 12796 inline explicit UnlinkGuard(const std::string &path,
32 const InitialState state = kEnabled)
33 12796 : path_(path), enabled_(state == kEnabled) { }
34 13488 inline ~UnlinkGuard() {
35
2/2
✓ Branch 1 taken 4540 times.
✓ Branch 2 taken 8948 times.
13488 if (IsEnabled())
36 4540 unlink(path_.c_str());
37 13488 }
38
39 703 inline void Set(const std::string &path) {
40 703 path_ = path;
41 703 Enable();
42 703 }
43
44 27100 inline bool IsEnabled() const { return enabled_; }
45 4014 inline void Enable() { enabled_ = true; }
46 276 inline void Disable() { enabled_ = false; }
47
48 58950 const std::string &path() const { return path_; }
49
50 private:
51 std::string path_;
52 bool enabled_;
53 };
54
55
56 /**
57 * RAII object to close a file descriptor when it gets out of scope
58 */
59 class FdGuard : SingleCopy {
60 public:
61 inline FdGuard() : fd_(-1) { }
62 296 explicit inline FdGuard(const int fd) : fd_(fd) { }
63 296 inline ~FdGuard() {
64
1/2
✓ Branch 0 taken 296 times.
✗ Branch 1 not taken.
296 if (fd_ >= 0)
65 296 close(fd_);
66 296 }
67 int fd() const { return fd_; }
68
69 private:
70 int fd_;
71 };
72
73
74 /**
75 * RAII object to close a FILE stream when it gets out of scope
76 */
77 class FileGuard : SingleCopy {
78 public:
79 inline FileGuard() : file_(NULL) { }
80 2432 explicit inline FileGuard(FILE *file) : file_(file) { }
81 2432 inline ~FileGuard() {
82
1/2
✓ Branch 0 taken 2432 times.
✗ Branch 1 not taken.
2432 if (file_ != NULL)
83 2432 fclose(file_);
84 2432 }
85 const FILE *file() const { return file_; }
86
87 private:
88 FILE *file_;
89 };
90
91
92 #ifdef CVMFS_NAMESPACE_GUARD
93 } // namespace CVMFS_NAMESPACE_GUARD
94 #endif
95
96 #endif // CVMFS_UTIL_FILE_GUARD_H_
97