util: add perm string helper functions

PermsToSymbolicString will convert from fs::perms to string type
'rwxrwxrwx'.

InterpretPermString will convert from a user-supplied "perm string" such
as 'owner', 'group' or 'all, into appropriate fs::perms.
This commit is contained in:
willcl-ark 2024-06-27 10:00:17 +01:00
parent 8efd03ad04
commit 7df03f1a92
No known key found for this signature in database
GPG Key ID: CE6EC49945C17EA6
2 changed files with 54 additions and 0 deletions

View File

@ -16,6 +16,7 @@
#include <fstream>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <system_error>
#include <utility>
@ -269,3 +270,42 @@ bool TryCreateDirectories(const fs::path& p)
// create_directories didn't create the directory, it had to have existed already
return false;
}
std::string PermsToSymbolicString(fs::perms p)
{
std::string perm_str(9, '-');
auto set_perm = [&](size_t pos, fs::perms required_perm, char letter) {
if ((p & required_perm) != fs::perms::none) {
perm_str[pos] = letter;
}
};
set_perm(0, fs::perms::owner_read, 'r');
set_perm(1, fs::perms::owner_write, 'w');
set_perm(2, fs::perms::owner_exec, 'x');
set_perm(3, fs::perms::group_read, 'r');
set_perm(4, fs::perms::group_write, 'w');
set_perm(5, fs::perms::group_exec, 'x');
set_perm(6, fs::perms::others_read, 'r');
set_perm(7, fs::perms::others_write, 'w');
set_perm(8, fs::perms::others_exec, 'x');
return perm_str;
}
std::optional<fs::perms> InterpretPermString(const std::string& s)
{
if (s == "owner") {
return fs::perms::owner_read | fs::perms::owner_write;
} else if (s == "group") {
return fs::perms::owner_read | fs::perms::owner_write |
fs::perms::group_read;
} else if (s == "all") {
return fs::perms::owner_read | fs::perms::owner_write |
fs::perms::group_read |
fs::perms::others_read;
} else {
return std::nullopt;
}
}

View File

@ -12,6 +12,7 @@
#include <cstdio>
#include <iosfwd>
#include <limits>
#include <optional>
/**
* Ensure file contents are fully committed to disk, using a platform-specific
@ -62,6 +63,19 @@ void ReleaseDirectoryLocks();
bool TryCreateDirectories(const fs::path& p);
fs::path GetDefaultDataDir();
/** Convert fs::perms to symbolic string of the form 'rwxrwxrwx'
*
* @param[in] p the perms to be converted
* @return Symbolic permissions string
*/
std::string PermsToSymbolicString(fs::perms p);
/** Interpret a custom permissions level string as fs::perms
*
* @param[in] s Permission level string
* @return Permissions as fs::perms
*/
std::optional<fs::perms> InterpretPermString(const std::string& s);
#ifdef WIN32
fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif