resolveSessionDir function
Auto-locate the session directory by walking up from start (defaults to
CWD) looking for an existing .fdb/ directory whose PID file points at a
live process.
Walk stops at $HOME or the filesystem root, whichever comes first.
- If a live
.fdb/is found in a parent ofstart, logs oneINFO:line to stderr so the user knows which directory was picked. - If no live
.fdb/is found anywhere, returnsnulland leaves_sessionDirat the CWD default so commands likestatuscan handle the missing-session case themselves.
Returns the resolved session-dir path, or null if no live session was found.
Implementation
String? resolveSessionDir({Directory? start}) {
final cwd = (start ?? Directory.current).absolute.path;
final home = Platform.environment['HOME'] ?? '/';
var current = Directory(cwd);
while (true) {
final candidate = Directory('${current.path}/$sessionDirName');
if (candidate.existsSync()) {
final pidPath = '${candidate.path}/fdb.pid';
final pidFile = File(pidPath);
bool alive;
if (pidFile.existsSync()) {
final raw = pidFile.readAsStringSync().trim();
final pid = int.tryParse(raw);
if (pid != null) {
try {
alive = Process.runSync('kill', ['-0', pid.toString()]).exitCode == 0;
} catch (_) {
alive = false;
}
} else {
alive = false;
}
} else {
// No PID file — only treat as a valid candidate if a vm_uri.txt
// exists, indicating an interrupted launch that left a recoverable
// VM service session. A bare .fdb/ with neither file is a leftover
// directory that should not attract walk-up resolution.
alive = File('${candidate.path}/vm_uri.txt').existsSync();
}
if (alive) {
final resolved = candidate.absolute.path;
if (resolved != Directory('$cwd/$sessionDirName').absolute.path) {
stderr.writeln('INFO: Using session dir from ${current.path}');
}
_sessionDir = resolved;
return resolved;
}
}
// Stop at $HOME or filesystem root — never walk past either.
final parent = current.parent;
final atHome = current.absolute.path == Directory(home).absolute.path;
final atRoot = parent.path == current.path;
if (atHome || atRoot) break;
current = parent;
}
// No live session found — keep _sessionDir at <CWD>/.fdb/ so commands like
// `status` can handle the missing-session case themselves.
_sessionDir = '$cwd/$sessionDirName';
return null;
}