cleanupStaleLocks function

int cleanupStaleLocks(
  1. String locksDir
)

Clean up stale locks (locks where the process is no longer running). Returns the number of locks cleaned up. Handles both PID-based locks and legacy directory locks.

Implementation

int cleanupStaleLocks(String locksDir) {
  int cleanedCount = 0;
  try {
    final dir = Directory(locksDir);
    if (!dir.existsSync()) return 0;

    final lockEntries = dir.listSync().where((e) => e.path.endsWith('.lock'));

    for (final entry in lockEntries) {
      try {
        final stat = entry.statSync();
        if (stat.type == FileSystemEntityType.directory) {
          // Legacy proper-lockfile directory lock
          Directory(entry.path).deleteSync(recursive: true);
          cleanedCount++;
          _logDebug(
            'Cleaned up legacy directory lock: ${p.basename(entry.path)}',
          );
        } else if (!isLockActive(entry.path)) {
          File(entry.path).deleteSync();
          cleanedCount++;
          _logDebug('Cleaned up stale lock: ${p.basename(entry.path)}');
        }
      } catch (_) {}
    }
  } catch (_) {}
  return cleanedCount;
}