GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/util/file_guard.h
Date: 2026-10-11 02:40:02
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 619 inline UnlinkGuard() : enabled_(false) { }
31 12686 inline explicit UnlinkGuard(const std::string &path,
32 const InitialState state = kEnabled)
33 12686 : path_(path), enabled_(state == kEnabled) { }
34 13257 inline ~UnlinkGuard() {
35
2/2
✓ Branch 1 taken 4253 times.
✓ Branch 2 taken 9004 times.
13257 if (IsEnabled())
36 4253 unlink(path_.c_str());
37 13257 }
38
39 619 inline void Set(const std::string &path) {
40 619 path_ = path;
41 619 Enable();
42 619 }
43
44 26487 inline bool IsEnabled() const { return enabled_; }
45 3825 inline void Enable() { enabled_ = true; }
46 209 inline void Disable() { enabled_ = false; }
47
48 60738 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 274 explicit inline FdGuard(const int fd) : fd_(fd) { }
63 274 inline ~FdGuard() {
64
1/2
✓ Branch 0 taken 274 times.
✗ Branch 1 not taken.
274 if (fd_ >= 0)
65 274 close(fd_);
66 274 }
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 26752 explicit inline FileGuard(FILE *file) : file_(file) { }
81 26752 inline ~FileGuard() {
82
1/2
✓ Branch 0 taken 26752 times.
✗ Branch 1 not taken.
26752 if (file_ != NULL)
83 26752 fclose(file_);
84 26752 }
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