Repository: spotify/backstage
File: packages/cli-common/src/paths.ts (TypeScript)

Code before:
  const ownDir = findOwnDir(searchDir);
  // Drive letter can end up being lowercased here on Windows, bring back to uppercase for consistency
  const targetDir = fs
    .realpathSync(process.cwd())
    .replace(/^[a-z]:/, str => str.toLocaleUpperCase('en-US'));

  // Lazy load this as it will throw an error if we're not inside the Backstage repo.
  let ownRoot = '';
  const getOwnRoot = () => {
    if (!ownRoot) {
      ownRoot = findOwnRootDir(ownDir);
    }
    return ownRoot;
  };

  // We're not always running in a monorepo, so we lazy init this to only crash commands
  // that require a monorepo when we're not in one.
  let targetRoot = '';
  const getTargetRoot = () => {
    if (!targetRoot) {
      targetRoot =
        findRootPath(targetDir, path => {
          try {
            const content = fs.readFileSync(path, 'utf8');
            const data = JSON.parse(content);
            return getWorkspacesPatterns(data).length > 0;
          } catch (error) {
            throw new Error(
              `Failed to parse package.json file while searching for root, ${error}`,
            );
          }
        }) ?? targetDir; // We didn't find any root package.json, assume we're not in a monorepo
    }
    return targetRoot;
  };

  return {
    ownDir,
    get ownRoot() {
      return getOwnRoot();
    },
    targetDir,
    get targetRoot() {
      return getTargetRoot();
    },
    resolveOwn: (...paths) => resolvePath(ownDir, ...paths),
    resolveOwnRoot: (...paths) => resolvePath(getOwnRoot(), ...paths),
    resolveTarget: (...paths) => resolvePath(targetDir, ...paths),
    resolveTargetRoot: (...paths) => resolvePath(getTargetRoot(), ...paths),
  };
}

Review comment (refactor):
Honestly I feel that the existing check is enough and simple enough to be worth using over the common utility. I suggest we just use `Boolean(data.workspaces)` or equivalent for all the monorepo checks that are covered in this PR.

Code after:
  }

  const rootDir = findRootPath(ownDir, pkgJsonPath => {
    try {
      const content = fs.readFileSync(pkgJsonPath, 'utf8');
      const data = JSON.parse(content);
      return Boolean(data.workspaces);
    } catch (error) {
      throw new Error(
        `Failed to read package.json at '${pkgJsonPath}', ${error}`,
      );
    }
  });

  if (!rootDir) {
    throw new Error(`No monorepo root found when searching from '${ownDir}'`);
  }

  return rootDir;
}

// Hierarchical directory cache shared across all OwnPathsImpl instances.
// When we resolve a searchDir to its package root, we also cache every
// intermediate directory, so sibling directories share work.
const dirCache = new Map<string, string>();

class OwnPathsImpl implements OwnPaths {
  static #instanceCache = new Map<string, OwnPathsImpl>();

  static find(searchDir: string): OwnPathsImpl {
    const dir = OwnPathsImpl.findDir(searchDir);
    let instance = OwnPathsImpl.#instanceCache.get(dir);
    if (!instance) {
      instance = new OwnPathsImpl(dir);
      OwnPathsImpl.#instanceCache.set(dir, instance);
    }
    return instance;
  }

  static findDir(searchDir: string): string {
    const visited: string[] = [];
    let dir = searchDir;

    for (let i = 0; i < 1000; i++) {
      const cached = dirCache.get(dir);
      if (cached !== undefined) {
        for (const d of visited) {
          dirCache.set(d, cached);
        }
        return cached;
      }