91 lines
2.8 KiB
C++
91 lines
2.8 KiB
C++
// SPDX-License-Identifier: LGPL-3.0-only
|
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
module;
|
|
|
|
#include <errno.h>
|
|
#include <sys/stat.h>
|
|
#include <termios.h>
|
|
#include <unistd.h>
|
|
|
|
module Nostro:File_impl;
|
|
import :File;
|
|
import std;
|
|
|
|
using namespace Nostro;
|
|
namespace fs = std::filesystem;
|
|
|
|
namespace {
|
|
// An environment variable as a path, or nothing when it is not set.
|
|
std::optional<fs::path> Environment(const std::string& name) {
|
|
// getenv answers with a char*, null when the variable is not set.
|
|
// lint-disable-next-line no-char-pointer
|
|
const char* const value = std::getenv(name.c_str());
|
|
return value ? std::optional<fs::path>(value) : std::nullopt;
|
|
}
|
|
}
|
|
|
|
fs::path Nostro::GetConfigPath() {
|
|
if(const std::optional<fs::path> xdg = Environment("XDG_CONFIG_HOME")) {
|
|
return *xdg / ".config/nostro";
|
|
}
|
|
if(const std::optional<fs::path> home = Environment("HOME")) {
|
|
return *home / ".config/nostro";
|
|
}
|
|
throw std::runtime_error("XDG_CONFIG_HOME and HOME not set");
|
|
}
|
|
|
|
fs::path Nostro::GetCachePath() {
|
|
if(const std::optional<fs::path> xdg = Environment("XDG_CACHE_HOME")) {
|
|
return *xdg / "nostro";
|
|
}
|
|
if(const std::optional<fs::path> home = Environment("HOME")) {
|
|
return *home / ".cache/nostro";
|
|
}
|
|
throw std::runtime_error("XDG_CACHE_HOME and HOME not set");
|
|
}
|
|
|
|
void Nostro::CreatePrivateFile(const fs::path& path) {
|
|
const fs::path dir(path.parent_path());
|
|
|
|
fs::create_directories(dir.parent_path());
|
|
|
|
if(mkdir(dir.c_str(), S_IRWXU) == -1) {
|
|
if(errno != EEXIST) {
|
|
throw std::system_error(errno, std::generic_category(), std::format("cannot create {}", dir.string()));
|
|
}
|
|
|
|
}
|
|
|
|
if(mknod(path.c_str(), S_IFREG | S_IRUSR | S_IWUSR, 0) == -1) {
|
|
if(errno != EEXIST) {
|
|
throw std::system_error(errno, std::generic_category(), std::format("cannot create {}", path.string()));
|
|
}
|
|
}
|
|
}
|
|
|
|
std::string Nostro::ReadSecret(std::string_view prompt) {
|
|
const bool terminal = isatty(STDIN_FILENO) == 1;
|
|
termios shown{};
|
|
if(terminal) {
|
|
std::print(std::cerr, "{}", prompt);
|
|
tcgetattr(STDIN_FILENO, &shown);
|
|
termios hidden = shown;
|
|
hidden.c_lflag &= ~static_cast<tcflag_t>(ECHO);
|
|
tcsetattr(STDIN_FILENO, TCSANOW, &hidden);
|
|
}
|
|
|
|
std::string line;
|
|
const bool read = static_cast<bool>(std::getline(std::cin, line));
|
|
if(terminal) {
|
|
tcsetattr(STDIN_FILENO, TCSANOW, &shown);
|
|
std::println(std::cerr);
|
|
}
|
|
if(!read) {
|
|
throw std::runtime_error(std::format("nothing given for '{}'", prompt));
|
|
}
|
|
|
|
const std::size_t first = line.find_first_not_of(" \t\r");
|
|
const std::size_t last = line.find_last_not_of(" \t\r");
|
|
return first == std::string::npos ? std::string() : line.substr(first, last - first + 1);
|
|
}
|