28#include <system_error>
37#include <sys/locking.h>
47namespace fs = std::filesystem;
54std::chrono::milliseconds LockRetryDelay(
int aAttempt )
56 return std::chrono::milliseconds( 25 << std::min( std::max( aAttempt, 0 ), 5 ) );
64 explicit FILE_LOCK(
const fs::path& aTarget ) :
66 m_lock( aTarget.native() + fs::
path(
".lock" ).native() )
69 m_fd = _wopen( m_lock.c_str(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE );
71 m_fd = open( m_lock.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666 );
76 m_result = errno == EEXIST ? GIT_ELOCKED : GIT_ERROR;
77 git_error_set_str( m_result == GIT_ELOCKED ? GIT_ERROR_OS : GIT_ERROR_FILESYSTEM,
78 "cannot create the lock file" );
86 if( m_result == 0 && !m_committed )
89 fs::remove( m_lock, ec );
93 FILE_LOCK(
const FILE_LOCK& ) =
delete;
94 FILE_LOCK& operator=(
const FILE_LOCK& ) =
delete;
97 int Result()
const {
return m_result; }
100 int Commit(
const fs::path& aContents )
102 if( m_result != 0 || m_committed )
104 git_error_set_str( GIT_ERROR_INVALID,
"the lock is not held" );
113 fs::rename( aContents, m_lock, ec );
116 fs::rename( m_lock, m_target, ec );
121 git_error_set_str( GIT_ERROR_OS, ec.message().c_str() );
148 bool m_committed =
false;
153std::optional<std::int64_t> mtimeSeconds(
const fs::path& aPath )
158 if( _wstat64( aPath.c_str(), &st ) != 0 )
163 if( stat( aPath.c_str(), &st ) != 0 )
167 return static_cast<std::int64_t
>( st.st_mtime );
173int smudgeRacyEntries( git_index* aIndex, std::int64_t aStamp )
175 std::vector<std::pair<std::string, git_index_entry>> racy;
177 for(
size_t i = 0; i < git_index_entrycount( aIndex ); ++i )
179 const git_index_entry* entry = git_index_get_byindex( aIndex, i );
181 if( entry && GIT_INDEX_ENTRY_STAGE( entry ) == 0 && entry->mode != GIT_FILEMODE_COMMIT
182 && entry->mtime.seconds >=
static_cast<std::int32_t
>( aStamp ) )
184 racy.emplace_back( entry->path, *entry );
188 for(
auto& [
path, entry] : racy )
190 entry.path =
path.c_str();
194 entry.mtime.seconds = 0;
195 entry.mtime.nanoseconds = 0;
197 if(
int rc = git_index_add( aIndex, &entry ) )
212 std::error_code ignored;
213 fs::remove( path, ignored );
225 git_index* repoIndex =
nullptr;
228 return GIT_EINVALIDSPEC;
230 if(
int rc = git_repository_index( &repoIndex, aRepo ) )
233 std::unique_ptr<git_index,
decltype( &git_index_free )> repoIndexPtr( repoIndex, &git_index_free );
234 const char* indexPathUtf8 = git_index_path( repoIndex );
237 return GIT_ENOTFOUND;
239 const fs::path indexPath(
reinterpret_cast<const char8_t*
>( indexPathUtf8 ) );
243 FILE_LOCK lock( indexPath );
246 return lock.Result();
248 SCRATCH_FILE scratch{ indexPath.native() + fs::path(
".kicad-new" ).native() };
250 const std::optional<std::int64_t> stamp = mtimeSeconds( indexPath );
253 if( fs::exists( indexPath, ec ) )
254 fs::copy_file( indexPath, scratch.path, fs::copy_options::overwrite_existing, ec );
258 git_error_set_str( GIT_ERROR_OS, ec.message().c_str() );
262 git_index*
copy =
nullptr;
263 const std::u8string scratchUtf8 = scratch.path.u8string();
265 if(
int rc = git_index_open( &
copy,
reinterpret_cast<const char*
>( scratchUtf8.c_str() ) ) )
268 std::unique_ptr<git_index,
decltype( &git_index_free )> copyPtr(
copy, &git_index_free );
273 if(
result == 0 && stamp )
280 result = lock.Commit( scratch.path );
283 git_index_read( repoIndex, 1 );
290 if( aGitError == GIT_ELOCKED || aGitError == GIT_EMODIFIED )
295 const git_error* error = git_error_last();
297 if( aGitError == GIT_ERROR && error && error->klass == GIT_ERROR_OS )
305int WithLockRetry( std::chrono::milliseconds aBudget,
const std::function<
int()>& aOp )
307 using CLOCK = std::chrono::steady_clock;
309 thread_local std::minstd_rand jitter( std::random_device{}() );
311 CLOCK::time_point deadline = CLOCK::now() + aBudget;
313 for(
int attempt = 0;; ++attempt )
320 std::chrono::milliseconds base = LockRetryDelay( attempt );
321 std::chrono::milliseconds delay = base / 2 + std::chrono::milliseconds( jitter() % ( base.count() + 1 ) );
323 if( CLOCK::now() + delay > deadline )
326 std::this_thread::sleep_for( delay );
332 m_path( aCommonDir / aName )
339 const char* commonDir = aRepo ? git_repository_commondir( aRepo ) :
nullptr;
344 return std::make_unique<REPO_ACTION_LOCK>( fs::path(
reinterpret_cast<const char8_t*
>( commonDir ) ), aName );
364 m_fd = _wopen(
m_path.c_str(), _O_CREAT | _O_RDWR | _O_BINARY | _O_NOINHERIT, _S_IREAD | _S_IWRITE );
368 m_fd = _wopen(
m_path.c_str(), _O_RDONLY | _O_BINARY | _O_NOINHERIT );
370 m_fd = open(
m_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666 );
374 m_fd = open(
m_path.c_str(), O_RDONLY | O_CLOEXEC );
379 m_error = std::generic_category().message( errno );
380 git_error_set_str( GIT_ERROR_FILESYSTEM, (
"cannot create the repository lock file: " +
m_error ).c_str() );
386 _lseek(
m_fd, 0, SEEK_SET );
388 int contended = EACCES;
390 int locked = flock(
m_fd, LOCK_EX | LOCK_NB );
391 int contended = EWOULDBLOCK;
398 if( error == contended )
400 git_error_set_str( GIT_ERROR_OS,
"another git operation holds the repository" );
404 m_error = std::generic_category().message( error );
405 git_error_set_str( GIT_ERROR_FILESYSTEM, (
"cannot lock the repository lock file: " +
m_error ).c_str() );
432 _lseek(
m_fd, 0, SEEK_SET );
433 _locking(
m_fd, _LK_UNLCK, 1 );
REPO_ACTION_LOCK(const std::filesystem::path &aCommonDir, const char *aName="kicad-action")
aCommonDir is as git_repository_commondir gives it. aName picks an independent lock in that directory...
std::filesystem::path m_path
int TryAcquire()
Try once without waiting. 0 once held, GIT_ELOCKED while another holder has it, GIT_ERROR otherwise.
int Acquire(std::chrono::milliseconds aBudget=BACKEND_LOCK_BUDGET)
TryAcquire again after each contention until it is held, fails otherwise, or aBudget is spent.
std::chrono::steady_clock CLOCK
Retrying short git writes that lost a race with another process.
bool IsLockContention(int aGitError)
True when aGitError says another writer held a lock or moved a ref first.
int EditIndexLocked(git_repository *aRepo, const std::function< int(git_index *aIndex)> &aEdit)
Rewrite aRepo's index the way git does, holding index.lock from a fresh read of the file to the renam...
int WithLockRetry(std::chrono::milliseconds aBudget, const std::function< int()> &aOp)
Run aOp, which returns 0 or a libgit2 error code, again after each lock contention until it succeeds,...
std::unique_ptr< REPO_ACTION_LOCK > RepoActionLock(git_repository *aRepo, const char *aName)
The lock aName in aRepo's common git directory, which every worktree of the repository shares.
wxString result
Test unit parsing edge cases and error handling.