Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2008 litl, LLC
4 : :
5 : : #ifndef UTIL_MISC_H_
6 : : #define UTIL_MISC_H_
7 : :
8 : : #include <config.h>
9 : :
10 : : #include <errno.h>
11 : : #include <stdio.h> // for FILE, stdout
12 : : #include <string.h> // for memcpy
13 : :
14 : : #ifdef G_DISABLE_ASSERT
15 : : # define GJS_USED_ASSERT [[maybe_unused]]
16 : : #else
17 : : # define GJS_USED_ASSERT
18 : : #endif
19 : :
20 : : bool gjs_environment_variable_is_set (const char *env_variable_name);
21 : :
22 : : char** gjs_g_strv_concat(char*** strv_array, int len);
23 : :
24 : : /*
25 : : * LogFile:
26 : : * RAII class encapsulating access to a FILE* pointer that must be closed,
27 : : * unless it is an already-open fallback file such as stdout or stderr.
28 : : */
29 : : class LogFile {
30 : : FILE* m_fp;
31 : : const char* m_errmsg;
32 : : bool m_should_close : 1;
33 : :
34 : : LogFile(const LogFile&) = delete;
35 : : LogFile& operator=(const LogFile&) = delete;
36 : :
37 : : public:
38 : 114 : explicit LogFile(const char* filename, FILE* fallback_fp = stdout)
39 : 114 : : m_errmsg(nullptr), m_should_close(false) {
40 [ + + ]: 114 : if (filename) {
41 : 3 : m_fp = fopen(filename, "a");
42 [ + + ]: 3 : if (!m_fp)
43 : 2 : m_errmsg = strerror(errno);
44 : : else
45 : 1 : m_should_close = true;
46 : : } else {
47 : 111 : m_fp = fallback_fp;
48 : : }
49 : 114 : }
50 : :
51 : 114 : ~LogFile() {
52 [ + + ]: 114 : if (m_should_close)
53 : 1 : fclose(m_fp);
54 : 114 : }
55 : :
56 : 3 : FILE* fp() { return m_fp; }
57 : 3 : bool has_error() { return !!m_errmsg; }
58 : 2 : const char* errmsg() { return m_errmsg; }
59 : : };
60 : :
61 : : #endif // UTIL_MISC_H_
|