From 25020815745ed09d60de995e07ec3d8f2a299ce5 Mon Sep 17 00:00:00 2001 From: tastytea Date: Wed, 14 Oct 2020 02:29:09 +0200 Subject: [PATCH] Throw if lockfile can't be created for 20 seconds. Also make create_lockfile() boolean. --- src/files.cpp | 16 +++++++--------- src/files.hpp | 11 ++--------- src/git.cpp | 9 +++++++-- 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/files.cpp b/src/files.cpp index 952588c..7f48893 100644 --- a/src/files.cpp +++ b/src/files.cpp @@ -219,22 +219,20 @@ fs::path get_lockfile() return path / "fediblock.lock"; } -lock_result create_lockfile() +bool create_lockfile() { const string lockfile{get_lockfile()}; if (fs::exists(lockfile)) { - return lock_result::already_locked; + return false; } - ofstream file{lockfile}; - if (file.good()) - { - file << getpid(); - return lock_result::created; - } + ofstream file; + file.exceptions(std::ofstream::failbit | std::ofstream::badbit); + file.open(lockfile); + file << getpid(); - return lock_result::error; + return true; } void remove_lockfile() diff --git a/src/files.hpp b/src/files.hpp index 4a49f4d..3c7fc15 100644 --- a/src/files.hpp +++ b/src/files.hpp @@ -27,13 +27,6 @@ namespace FediBlock::files using std::string; -enum class lock_result -{ - created, - already_locked, - error -}; - // Create and return the temporary directory. [[nodiscard]] fs::path get_tmpdir(); @@ -73,8 +66,8 @@ void remove_tmpdir(); // Return path of lockfile. [[nodiscard]] fs::path get_lockfile(); -// Attempt to create lockfile. -[[nodiscard]] lock_result create_lockfile(); +// Attempt to create lockfile. Return true if created, false if already locked. +[[nodiscard]] bool create_lockfile(); // Remove lockfile if it exists. void remove_lockfile(); diff --git a/src/git.cpp b/src/git.cpp index d25e15d..023efed 100644 --- a/src/git.cpp +++ b/src/git.cpp @@ -220,13 +220,18 @@ string get_branch_name() void update_cached_repo() { + bool lock_created{false}; for (uint8_t counter{0}; counter < 20; ++counter) { - if (files::create_lockfile() == files::lock_result::created) + if ((lock_created = files::create_lockfile())) { break; } - sleep_for(2s); + sleep_for(1s); + } + if (!lock_created) + { + throw runtime_error{"Repository was locked for too long, giving up."}; } if (!fs::exists(_repo_dir / ".git"))