All files / src workspace-detector.ts

100% Statements 25/25
100% Branches 5/5
100% Functions 3/3
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 603x 3x 3x             3x 3x           3x 26x 26x   26x 88x 7x     81x 81x 63x 63x     19x             3x           3x 7x 1x   7x             3x 18x 18x    
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
 
export interface WorkspaceResult {
  isActive: boolean;
  root: string | null;
}
 
const HOME = os.homedir();
const MAX_LEVELS = 15;
 
/**
 * Walks up from startCwd looking for a .pisces marker file.
 * Bounded at 15 levels and stops at the user's home directory.
 */
export function findWorkspace(startCwd: string): WorkspaceResult {
  let dir = startCwd;
  let levels = 0;
 
  while (levels < MAX_LEVELS) {
    if (fs.existsSync(path.join(dir, ".pisces"))) {
      return { isActive: true, root: dir };
    }
 
    const parent = path.dirname(dir);
    if (parent === dir || dir === HOME) break;
    dir = parent;
    levels++;
  }
 
  return { isActive: false, root: null };
}
 
// ─── Singleton cache ────────────────────────────────────────────────────────
// Lazily initialised on first read so tests can mock findWorkspace() before
// the module evaluates any filesystem calls.
 
let _cached: WorkspaceResult | null = null;
 
/**
 * Returns the last resolved workspace state, initialising from process.cwd()
 * on first call. Use syncWorkspaceState() to re-evaluate after a cwd change.
 */
export function getWorkspaceState(): WorkspaceResult {
  if (_cached === null) {
    _cached = findWorkspace(process.cwd());
  }
  return _cached;
}
 
/**
 * Re-evaluates workspace state for the given cwd, updates the cache,
 * and returns the result. Called by the gatekeeper on resources_discover.
 */
export function syncWorkspaceState(cwd: string): WorkspaceResult {
  _cached = findWorkspace(cwd);
  return _cached;
}