| 1 |
// SPDX-FileCopyrightText: 2021 - 2023 UnionTech Software Technology Co., Ltd. |
| 2 |
// |
| 3 |
// SPDX-License-Identifier: LGPL-3.0-or-later |
| 4 |
|
| 5 |
#pragma once |
| 6 |
|
| 7 |
#include <QDir> |
| 8 |
|
| 9 |
class EnvGuard { |
| 10 |
public: |
| 11 |
void set(const char *name, const QByteArray &value, bool mkpath = true) |
| 12 |
{ |
| 13 |
m_name = name; |
| 14 |
if (m_originValue.isEmpty()) |
| 15 |
m_originValue = qgetenv(m_name); |
| 16 |
qputenv(m_name, value); |
| 17 |
|
| 18 |
if (mkpath && !QDir(value).exists()) { |
| 19 |
QDir().mkpath(value); |
| 20 |
} |
| 21 |
} |
| 22 |
void unset(const char *name) |
| 23 |
{ |
| 24 |
m_name = name; |
| 25 |
m_originValue = qgetenv(m_name); |
| 26 |
qunsetenv(m_name); |
| 27 |
} |
| 28 |
void restore() |
| 29 |
{ |
| 30 |
qputenv(m_name, m_originValue); |
| 31 |
} |
| 32 |
QString value() |
| 33 |
{ |
| 34 |
return qgetenv(m_name); |
| 35 |
} |
| 36 |
~EnvGuard() { |
| 37 |
if (m_name) |
| 38 |
restore(); |
| 39 |
} |
| 40 |
private: |
| 41 |
QByteArray m_originValue; |
| 42 |
const char* m_name = nullptr; |
| 43 |
}; |
| 44 |
|
| 45 |
class FileGuard { |
| 46 |
public: |
| 47 |
explicit FileGuard(const QString &fileName) |
| 48 |
: m_fileName(fileName){ } |
| 49 |
virtual ~FileGuard() { |
| 50 |
QFile::remove(m_fileName); |
| 51 |
} |
| 52 |
const QString fileName() const { return m_fileName; } |
| 53 |
private: |
| 54 |
QString m_fileName; |
| 55 |
}; |
| 56 |
|
| 57 |
class FileCopyGuard : public FileGuard { |
| 58 |
public: |
| 59 |
FileCopyGuard(const QString &source, const QString &target) |
| 60 |
: FileGuard(target) |
| 61 |
{ |
| 62 |
if (!QFile::exists(QFileInfo(target).path())) |
| 63 |
QDir().mkpath(QFileInfo(target).path()); |
| 64 |
QFile::copy(source, target); |
| 65 |
} |
| 66 |
}; |