1#ifndef FRAY_FILE_MANAGER_HPP
2#define FRAY_FILE_MANAGER_HPP
13#include <system_error>
29#ifndef WIN32_LEAN_AND_MEAN
30#define WIN32_LEAN_AND_MEAN
39#include <sys/syscall.h>
111 HANDLE
handle = INVALID_HANDLE_VALUE;
154 std::shared_ptr<int>
_lifetime = std::make_shared<int>(0);
162 const std::string& name)
164 if (name.empty() || name.find(
'\0') != std::string::npos ||
165 name.find(
'\\') != std::string::npos || name.find(
':') != std::string::npos)
167 const std::filesystem::path path(name);
168 if (path.is_absolute() || path.has_root_name() || path.has_root_directory())
170 for (
const auto& part : path)
171 if (part ==
"." || part ==
"..")
184 const std::filesystem::path& archive,
187 auto lockPath = archive;
188 lockPath.replace_extension(
".lock");
190 lock.
handle = CreateFileW(lockPath.c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, 0,
191 nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
193 if (lock.
handle != INVALID_HANDLE_VALUE)
195 BY_HANDLE_FILE_INFORMATION info;
196 if (!GetFileInformationByHandle(lock.
handle, &info) ||
197 (info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) ||
198 info.nFileSizeHigh != 0 || info.nFileSizeLow != 0)
201 lock.
handle = INVALID_HANDLE_VALUE;
204 if (lock.
handle == INVALID_HANDLE_VALUE)
206 lock.
handle =
::open(lockPath.c_str(), O_CREAT | O_RDWR | O_NOFOLLOW, 0600);
207 if (lock.
handle >= 0 && flock(lock.
handle, LOCK_EX | LOCK_NB) != 0)
215 struct stat descriptor, pathStatus;
216 if (fstat(lock.
handle, &descriptor) != 0 || lstat(lockPath.c_str(), &pathStatus) != 0 ||
217 descriptor.st_dev != pathStatus.st_dev || descriptor.st_ino != pathStatus.st_ino ||
218 !S_ISREG(pathStatus.st_mode) || descriptor.st_size != 0)
230 lock.
path = lockPath;
243 struct stat descriptor, pathStatus;
244 return lock.
handle >= 0 && fstat(lock.
handle, &descriptor) == 0 &&
245 lstat(lock.
path.c_str(), &pathStatus) == 0 && descriptor.st_dev == pathStatus.st_dev &&
246 descriptor.st_ino == pathStatus.st_ino && S_ISREG(pathStatus.st_mode) &&
247 descriptor.st_size == 0;
277 if (lock.
handle == INVALID_HANDLE_VALUE)
279 FILE_DISPOSITION_INFO disposition = {TRUE};
280 if (!SetFileInformationByHandle(lock.
handle, FileDispositionInfo, &disposition,
sizeof(disposition)))
285 if (!CloseHandle(lock.
handle))
290 lock.
handle = INVALID_HANDLE_VALUE;
339 if (!databaseRestored)
382 const std::string& stem)
384 const auto database =
_workspace / (stem +
".sqlite");
390 const std::time_t now = std::time(
nullptr);
393 localtime_s(&local, &now);
395 localtime_r(&now, &local);
398 std::strftime(stamp,
sizeof(stamp),
"%Y%m%d%H%M%S", &local);
400 std::error_code error;
401 std::filesystem::create_directory(folder, error);
407 auto target = folder / (stem +
"-" + stamp +
".sqlite");
408 for (
unsigned number = 1; ; ++number)
414 target = folder / (stem +
"-" + stamp +
"-" + std::to_string(number) +
".sqlite");
416 std::filesystem::copy_file(database, target, std::filesystem::copy_options::none, error);
433 std::error_code error;
434 std::filesystem::remove(
_archive, error);
437 _archive.string().c_str(), error.message().c_str());
450 const std::string& newName,
454 const auto newArchive =
_archive.parent_path() / (newName +
".fry");
473 const std::string& newName,
474 const std::filesystem::path& workspace,
494 const std::filesystem::path& path,
497 std::error_code error;
498 const auto status = std::filesystem::symlink_status(path, error);
499 if (error && error != std::errc::no_such_file_or_directory)
504 exists = status.type() != std::filesystem::file_type::not_found;
516 const std::filesystem::path& parent,
517 const std::string& stem,
518 std::filesystem::path& output)
520 for (
unsigned i = 1; i < 100000; ++i)
522 const auto candidate = parent / (stem +
"-" + std::to_string(i));
523 bool folderExists, archiveExists;
525 !
pathExists(candidate.string() +
".fry", archiveExists))
527 if (!folderExists && !archiveExists)
544 const std::filesystem::path& from,
545 const std::filesystem::path& to)
548 if (MoveFileW(from.c_str(), to.c_str()) != 0)
550 const std::error_code error(
static_cast<int>(GetLastError()), std::system_category());
551#elif defined(__APPLE__)
552 if (::renamex_np(from.c_str(), to.c_str(), RENAME_EXCL) == 0)
554 const std::error_code error(errno, std::generic_category());
555#elif defined(__linux__)
556 if (::syscall(SYS_renameat2, AT_FDCWD, from.c_str(), AT_FDCWD, to.c_str(), RENAME_NOREPLACE) == 0)
558 const std::error_code error(errno, std::generic_category());
560 const std::error_code error = std::make_error_code(std::errc::operation_not_supported);
563 from.string().c_str(), to.string().c_str(), error.message().c_str());
576 const std::filesystem::path& folder,
577 const std::string& oldName,
578 const std::string& newName)
580 std::vector<std::pair<std::filesystem::path, std::filesystem::path>> renamed;
581 for (
const char* suffix : {
".sqlite",
".sqlite-wal",
".sqlite-shm",
".sqlite-journal"})
583 const auto from = folder / (oldName + suffix);
584 const auto to = folder / (newName + suffix);
585 bool exists, destinationExists;
588 if (exists && destinationExists)
591 to.string().c_str());
595 renamed.emplace_back(from, to);
597 std::size_t completed = 0;
598 for (; completed < renamed.size(); ++completed)
600 if (!
renameExclusive(renamed[completed].first, renamed[completed].second))
602 while (completed > 0)
605 if (!
renameExclusive(renamed[completed].second, renamed[completed].first))
623 const std::filesystem::path& path,
624 const std::string& oldName,
625 const std::string& newName)
628 zip_t* archive = zip_open(path.string().c_str(), ZIP_CHECKCONS, &error);
631 if (error == ZIP_ER_NOZIP || error == ZIP_ER_INCONS || error == ZIP_ER_EOF)
634 path.string().c_str());
640 bool changed =
false;
641 for (
const char* suffix : {
".sqlite",
".sqlite-wal",
".sqlite-shm",
".sqlite-journal"})
643 const std::string from = oldName + suffix;
644 const std::string to = newName + suffix;
645 const zip_int64_t index = zip_name_locate(archive, from.c_str(), 0);
648 if (zip_error_code_zip(zip_get_error(archive)) == ZIP_ER_NOENT)
651 zip_discard(archive);
654 if (zip_name_locate(archive, to.c_str(), 0) >= 0)
658 zip_discard(archive);
661 if (zip_error_code_zip(zip_get_error(archive)) != ZIP_ER_NOENT)
664 zip_discard(archive);
667 if (zip_file_rename(archive,
static_cast<zip_uint64_t
>(index),
668 to.c_str(), ZIP_FL_ENC_UTF_8) != 0)
671 zip_discard(archive);
678 zip_discard(archive);
681 if (zip_close(archive) != 0)
684 zip_discard(archive);
698 zip_t* archive = zip_open(
_archive.string().c_str(), ZIP_RDONLY | ZIP_CHECKCONS, &error);
704 std::error_code fsError;
705 if (!std::filesystem::create_directory(
_workspace, fsError))
708 zip_discard(archive);
712 std::set<std::string> paths;
713 const zip_int64_t entries = zip_get_num_entries(archive, 0);
716 for (zip_uint64_t i = 0; ok && i < static_cast<zip_uint64_t>(entries); ++i)
718 const char* raw = zip_get_name(archive, i, 0);
719 const std::string name = raw ==
nullptr ?
"" : raw;
720 zip_uint8_t system = 0;
721 zip_uint32_t attributes = 0;
722 if (!
safeRelative(name) || !paths.insert(name).second ||
723 zip_file_get_external_attributes(archive, i, 0, &system, &attributes) != 0)
729 const unsigned type = system == ZIP_OPSYS_UNIX ? (attributes >> 16) & 0170000 : 0;
730 const bool directory = name.back() ==
'/';
731 if ((type != 0 && type != 0100000 && type != 0040000) ||
732 (type == 0040000 && !directory) || (type == 0100000 && directory))
738 const auto destination =
_workspace / std::filesystem::path(name);
741 std::filesystem::create_directories(destination, fsError);
745 std::filesystem::create_directories(destination.parent_path(), fsError);
746 if (fsError || std::filesystem::exists(destination, fsError) || fsError)
752 zip_file_t* entry = zip_fopen_index(archive, i, 0);
759 std::ofstream output(destination, std::ios::binary | std::ios::trunc);
761 zip_int64_t count = -1;
762 while (output && (count = zip_fread(entry, buffer,
sizeof(buffer))) > 0)
763 output.write(buffer, count);
765 const int closed = zip_fclose(entry);
766 if (count < 0 || !output || closed != 0)
774 zip_discard(archive);
777 std::filesystem::remove_all(
_workspace, fsError);
812 if (
_extraLock.handle != INVALID_HANDLE_VALUE)
814 if (
_lock.handle != INVALID_HANDLE_VALUE)
815 CloseHandle(
_lock.handle);
819 if (
_lock.handle >= 0)
862 const std::filesystem::path& directory,
863 const std::string& name)
866 directory.empty() || directory.string().find(
'\0') != std::string::npos ||
867 !
safeRelative(name) || name.find(
'/') != std::string::npos)
870 return fray::errors::FAILED_OPEN_PROJECT;
872 std::error_code error;
873 const auto resolved = std::filesystem::canonical(directory, error);
874 if (error || !std::filesystem::is_directory(resolved, error) || error)
877 return fray::errors::FAILED_OPEN_PROJECT;
880 return fray::errors::FAILED_OPEN_PROJECT;
884 return fray::errors::NONE;
893 const std::filesystem::path& path)
896 path.empty() || path.string().find(
'\0') != std::string::npos ||
900 return fray::errors::FAILED_OPEN_PROJECT;
902 std::error_code error;
903 const auto status = std::filesystem::symlink_status(path, error);
904 if (error || !std::filesystem::is_regular_file(status))
907 return fray::errors::FAILED_OPEN_PROJECT;
909 const auto parent = std::filesystem::canonical(
910 path.parent_path().empty() ? std::filesystem::path(
".") : path.parent_path(), error);
911 if (error || !std::filesystem::is_directory(parent, error) || error)
914 return fray::errors::FAILED_OPEN_PROJECT;
916 const auto filename = path.filename().string();
918 return fray::errors::FAILED_OPEN_PROJECT;
920 _name = path.stem().string();
923 return fray::errors::NONE;
933 const std::string& name,
934 std::filesystem::path& result)
const
939 return fray::errors::FAILED_OPEN_PROJECT;
942 for (
const auto& part : std::filesystem::path(name))
945 std::error_code error;
946 const auto status = std::filesystem::symlink_status(current, error);
947 if ((error && error != std::errc::no_such_file_or_directory) ||
948 std::filesystem::is_symlink(status))
951 return fray::errors::FAILED_OPEN_PROJECT;
955 return fray::errors::NONE;
971 const std::string& path,
974 bool deferConflictCommit =
false)
977 path.empty() || path.find(
'\0') != std::string::npos)
980 return fray::errors::FAILED_OPEN_PROJECT;
982 std::error_code error;
983 auto input = std::filesystem::weakly_canonical(path, error);
987 return fray::errors::FAILED_OPEN_PROJECT;
989 if (input.filename().empty() && input != input.root_path())
990 input = input.parent_path();
991 const bool inputArchive = input.extension() ==
".fry";
992 _name = inputArchive ? input.stem().string() : input.filename().string();
997 return fray::errors::FAILED_OPEN_PROJECT;
999 const auto parent = input.parent_path();
1000 const auto originalArchive = inputArchive ? input : parent / (
_name +
".fry");
1001 const auto originalFolder = inputArchive ? parent /
_name : input;
1002 bool hasArchive = std::filesystem::exists(originalArchive, error);
1007 return fray::errors::FAILED_OPEN_PROJECT;
1009 bool hasFolder = std::filesystem::exists(originalFolder, error);
1010 if (error || (hasFolder && !std::filesystem::is_directory(originalFolder, error)))
1014 return fray::errors::FAILED_OPEN_PROJECT;
1016 if (hasFolder && std::filesystem::is_symlink(std::filesystem::symlink_status(originalFolder, error)))
1020 return fray::errors::FAILED_OPEN_PROJECT;
1026 return fray::errors::FAILED_OPEN_PROJECT;
1028 if (hasArchive && hasFolder &&
1033 return fray::errors::PROJECT_CONFLICT;
1038 return fray::errors::FAILED_OPEN_PROJECT;
1040 hasArchive = std::filesystem::exists(originalArchive, error);
1042 hasFolder = std::filesystem::exists(originalFolder, error);
1047 return fray::errors::FAILED_OPEN_PROJECT;
1051 const F_err result = hasArchive && hasFolder ? errors::PROJECT_BOTH_EXIST :
1052 hasArchive ? errors::PROJECT_ARCHIVE_EXISTS : errors::PROJECT_FOLDER_EXISTS;
1057 ((!hasFolder && !hasArchive) ||
1062 return errors::PROJECT_NOT_FOUND;
1067 return errors::PROJECT_NOT_FOUND;
1069 if (hasArchive && hasFolder &&
1074 return fray::errors::PROJECT_CONFLICT;
1080 if (hasArchive && hasFolder)
1082 std::filesystem::path extra;
1087 return fray::errors::FAILED_OPEN_PROJECT;
1089 const std::string newName = extra.filename().string();
1090 const auto source = useArchive ? originalFolder : originalArchive;
1091 const std::filesystem::path destination = useArchive
1092 ? extra : std::filesystem::path(extra.string() +
".fry");
1093 bool folderExists, archiveExists;
1095 !
pathExists(extra.string() +
".fry", archiveExists) ||
1096 folderExists || archiveExists || !
renameExclusive(source, destination))
1100 return fray::errors::FAILED_OPEN_PROJECT;
1102 const bool renamedDatabase = useArchive
1105 if (!renamedDatabase)
1110 return fray::errors::FAILED_OPEN_PROJECT;
1113 destination.string().c_str());
1122 return fray::errors::FAILED_OPEN_PROJECT;
1135 return fray::errors::FAILED_OPEN_PROJECT;
1139 else if (!hasFolder && !std::filesystem::create_directory(
_workspace, error))
1143 return fray::errors::FAILED_OPEN_PROJECT;
1145 return fray::errors::NONE;
1158 return fray::errors::FAILED_SAVE_PROJECT;
1161 zip_t* archive = zip_open(
_archive.string().c_str(),
1166 return fray::errors::FAILED_SAVE_PROJECT;
1168 std::error_code fsError;
1169 std::filesystem::recursive_directory_iterator it(
_workspace, fsError), end;
1171 for (; ok && it != end; it.increment(fsError))
1178 const auto status = it->symlink_status(fsError);
1179 if (fsError || (!std::filesystem::is_regular_file(status) && !std::filesystem::is_directory(status)))
1185 const std::string name = it->path().lexically_relative(
_workspace).generic_string();
1192 if (std::filesystem::is_directory(status))
1193 ok = zip_dir_add(archive, (name +
"/").c_str(), ZIP_FL_ENC_UTF_8) >= 0;
1196 const std::string path = it->path().string();
1197 zip_source_t* source = zip_source_file(archive, path.c_str(), 0, -1);
1200 else if (zip_file_add(archive, name.c_str(), source, ZIP_FL_ENC_UTF_8) < 0)
1202 zip_source_free(source);
1212 fsError ? fsError.message().c_str() : zip_strerror(archive));
1213 zip_discard(archive);
1214 return fray::errors::FAILED_SAVE_PROJECT;
1216 if (zip_close(archive) != 0)
1219 zip_discard(archive);
1220 return fray::errors::FAILED_SAVE_PROJECT;
1223 return fray::errors::NONE;
1236 return fray::errors::FAILED_CLOSE_PROJECT;
1238 return reset() ? fray::errors::NONE : fray::errors::FAILED_CLOSE_PROJECT;
1252 return fray::errors::FAILED_CLOSE_PROJECT;
1254 std::error_code error;
1256 const auto contains = [](
const std::filesystem::path& parent,
const std::filesystem::path& child)
1258 auto part = parent.begin();
1259 auto other = child.begin();
1260 for (; part != parent.end() && other != child.end(); ++part, ++other)
1261 if (*part != *other)
1263 return part == parent.end();
1265 const auto cwd = std::filesystem::current_path(error);
1269 return fray::errors::FAILED_CLOSE_PROJECT;
1271 const auto current = std::filesystem::weakly_canonical(cwd, error);
1275 return fray::errors::FAILED_CLOSE_PROJECT;
1278 const char* home = std::getenv(
"HOME");
1280 if (home ==
nullptr || *home ==
'\0')
1281 home = std::getenv(
"USERPROFILE");
1283 if (home !=
nullptr && *home !=
'\0')
1285 const auto homePath = std::filesystem::weakly_canonical(home, error);
1289 return fray::errors::FAILED_CLOSE_PROJECT;
1291 protectedFolder = protectedFolder || contains(
_workspace, homePath);
1293 if (protectedFolder)
1297 return fray::errors::FAILED_CLOSE_PROJECT;
1299 std::filesystem::remove_all(
_workspace, error);
1303 _workspace.string().c_str(), error.message().c_str());
1304 return fray::errors::FAILED_CLOSE_PROJECT;
1306 return fray::errors::NONE;
Owns a project’s files, state stores, watcher and registered threads. Public operations synchronize t...
std::shared_ptr< int > _lifetime
Lifetime sentinel observed weakly by attached state managers.
bool isOpen() const
Returns whether a working directory is associated with this manager.
static bool safeRelative(const std::string &name)
Checks whether a project entry name is a safe relative path.
void commitRename(const std::string &newName, const std::filesystem::path &workspace, ProjectLock &lock)
Transfers a new lock and updates the project name and paths, then releases the old lock.
void removeArchive()
Removes the existing archive while the project is open, logging any failure. A later save recreates t...
bool _archiveExists
Whether the archive is expected to exist.
void restoreLock()
Attempts to recreate the primary lock if its file was renamed or removed. On POSIX,...
ProjectLock _extraLock
Temporary lock for the renamed, unselected conflict representation.
std::filesystem::path _workspace
Working folder path; empty when no project is open.
F_err save()
Packages the workspace into its .fry archive without deleting the workspace. Requires an open project...
bool reset()
Releases both locks and clears the current project and conflict paths.
std::filesystem::path _archive
Path of the project archive associated with the workspace.
std::weak_ptr< int > lifetime() const
Returns a weak lifetime sentinel that expires when this manager is destroyed.
ProjectLock _lock
Lock for the selected project archive path.
static bool unlockProject(ProjectLock &lock)
Removes and releases an owned project lock. On POSIX, only unlinks the path if it still identifies th...
std::filesystem::path _conflictDestination
Renamed path of the unselected representation awaiting resolution.
static bool renameExclusive(const std::filesystem::path &from, const std::filesystem::path &to)
Renames a filesystem entry without replacing an existing destination.
bool lockProject(const std::filesystem::path &archive, ProjectLock &lock)
Acquires a nonblocking exclusive lock on the archive path’s .lock file. Creates the lock file if need...
const std::filesystem::path & archivePath() const
Returns a borrowed reference to the archive path.
const std::string & projectName() const
Returns a borrowed reference to the current project or database name.
void detach()
Unregisters an attached state manager; requires a prior unmatched attach().
bool acquireRename(const std::string &newName, ProjectLock &lock)
Locks the proposed archive path after checking that the archive does not exist. Attempts to restore t...
void attach()
Registers an attached state manager; callers must balance this with detach().
static bool pathExists(const std::filesystem::path &path, bool &exists)
Inspects a path without following its final symbolic link.
bool extract()
Extracts the archive into a newly created workspace, rejecting unsafe or unsupported entries....
std::string _name
Current project name and database stem.
std::string _databaseFile
Explicit database filename for a directory-backed store; empty for a project.
static bool lockIntact(const ProjectLock &lock)
Checks that a POSIX lock descriptor still names the same empty regular file as its path.
FileManager & operator=(const FileManager &)=delete
Copy assignment is disabled; project locks have a single owner.
bool _extracted
Whether the workspace was extracted from an archive.
std::string databaseFileName() const
Returns the database filename within the open directory.
F_err filePath(const std::string &name, std::filesystem::path &result) const
Resolves a safe relative project path without accepting symbolic-link components.
bool rollbackConflict()
Attempts to restore an unselected conflict representation and its database names.
unsigned _users
Number of attached state managers; nonzero prevents save and close.
std::filesystem::path _conflictSource
Original path of an unselected representation awaiting conflict commit or rollback.
F_err removeWorkingDirectory()
Deletes the workspace tree after checking it does not contain protected locations....
F_err openDatabase(const std::filesystem::path &path)
Opens an existing named database file without treating its directory as a project.
bool requiresExistingDatabase() const
Reports whether state opens must require an existing database.
~FileManager()
Invalidates the lifetime sentinel and releases project locks. Logs if state managers remain attached;...
static bool renameFolderDatabase(const std::filesystem::path &folder, const std::string &oldName, const std::string &newName)
Renames a folder’s database and SQLite sidecars without overwriting destinations. Attempts to reverse...
bool commitConflict()
Finalizes a conflict rename by releasing its extra lock and clearing rollback state.
bool snapshotDatabase(const std::string &stem)
Copies an existing workspace database into snapshots with a timestamp and collision suffix....
F_err open(const std::string &path, ConflictChoice choice=ConflictChoice::Ask, OpenMode mode=OpenMode::OpenOrCreate, bool deferConflictCommit=false)
Opens or creates a project workspace and acquires its nonblocking project lock. May extract an archiv...
bool _existingDatabase
Whether opening state must not create a missing database file.
static bool unusedPath(const std::filesystem::path &parent, const std::string &stem, std::filesystem::path &output)
Finds an unused numbered folder name with no matching .fry archive.
const std::filesystem::path & workingDirectory() const
Returns a borrowed reference to the working folder path.
F_err close()
Releases locks and forgets the open project without saving or deleting its workspace....
std::string _conflictName
New database stem of the unselected representation.
static bool renameArchiveDatabase(const std::filesystem::path &path, const std::string &oldName, const std::string &newName)
Renames database and SQLite sidecar entries within an archive. Unreadable non-ZIP,...
FileManager(const FileManager &)=delete
Copy construction is disabled; project locks have a single owner.
bool _conflictFolder
Whether the unselected representation is a folder rather than an archive.
FileManager()=default
Constructs a closed file manager.
F_err openDirectory(const std::filesystem::path &directory, const std::string &name)
Opens an existing directory for a named state database without project archive operations.
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
ConflictChoice
Selects how an archive/folder name conflict is resolved. Ask reports a conflict; Archive selects the ...
OpenMode
Selects existence and conflict requirements when opening a project. OpenOrCreate opens or creates; Cr...
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
Owns the operating-system handle and path of a project lock file.
std::filesystem::path path
Path of the locked file.
int handle
Open locked file descriptor, or -1.