tryAcquireLock function

Future<void Function()?> tryAcquireLock(
  1. String versionPath,
  2. String lockFilePath
)

Try to acquire a lock on a version file. Returns a release function if successful, null if already held.

Implementation

Future<void Function()?> tryAcquireLock(
  String versionPath,
  String lockFilePath,
) async {
  final versionName = p.basename(versionPath);

  if (isLockActive(lockFilePath)) {
    final existing = readLockContent(lockFilePath);
    _logDebug(
      'Cannot acquire lock for $versionName - held by PID ${existing?.pid}',
    );
    return null;
  }

  final lockContent = VersionLockContent(
    pid: pid,
    version: versionName,
    execPath: Platform.resolvedExecutable,
    acquiredAt: DateTime.now().millisecondsSinceEpoch,
  );

  try {
    writeLockFile(lockFilePath, lockContent);

    // Verify we got the lock (race condition check)
    final verify = readLockContent(lockFilePath);
    if (verify?.pid != pid) return null;

    _logDebug('Acquired PID lock for $versionName (PID $pid)');

    return () {
      try {
        final current = readLockContent(lockFilePath);
        if (current?.pid == pid) {
          File(lockFilePath).deleteSync();
          _logDebug('Released PID lock for $versionName');
        }
      } catch (_) {}
    };
  } catch (e) {
    _logDebug('Failed to acquire lock for $versionName: $e');
    return null;
  }
}