GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/util/file_guard.h
Date: 2025-09-28 02:35:26
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 420 inline UnlinkGuard() : enabled_(false) { }
31 11491 inline explicit UnlinkGuard(const std::string &path,
32 const InitialState state = kEnabled)
33 11491 : path_(path), enabled_(state == kEnabled) { }
34 11903 inline ~UnlinkGuard() {
35
2/2
✓ Branch 1 taken 4194 times.
✓ Branch 2 taken 7709 times.
11903 if (IsEnabled())
36 4194 unlink(path_.c_str());
37 11903 }
38
39 420 inline void Set(const std::string &path) {
40 420 path_ = path;
41 420 Enable();
42 420 }
43
44 24361 inline bool IsEnabled() const { return enabled_; }
45 3967 inline void Enable() { enabled_ = true; }
46 222 inline void Disable() { enabled_ = false; }
47
48 57377 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 180 explicit inline FdGuard(const int fd) : fd_(fd) { }
63 180 inline ~FdGuard() {
64
1/2
✓ Branch 0 taken 180 times.
✗ Branch 1 not taken.
180 if (fd_ >= 0)
65 180 close(fd_);
66 180 }
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 608 explicit inline FileGuard(FILE *file) : file_(file) { }
81 608 inline ~FileGuard() {
82
1/2
✓ Branch 0 taken 608 times.
✗ Branch 1 not taken.
608 if (file_ != NULL)
83 608 fclose(file_);
84 608 }
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