aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/packages/turbo-utils/src/getTurboRoot.ts
blob: 64a37be833f8368f9ffcdbb3296bff6a0eeef6d3 (plain) (blame)
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
import { findRootSync } from "@manypkg/find-root";
import searchUp from "./searchUp";
import JSON5 from "json5";

interface Options {
  cache?: boolean;
}

function contentCheck(content: string): boolean {
  const result = JSON5.parse(content);
  return !result.extends;
}

const configCache: Record<string, string> = {};

function getTurboRoot(cwd?: string, opts?: Options): string | null {
  const cacheEnabled = opts?.cache ?? true;
  const currentDir = cwd || process.cwd();

  if (cacheEnabled && configCache[currentDir]) {
    return configCache[currentDir];
  }

  // Turborepo root can be determined by a turbo.json without an extends key
  let root = searchUp({
    target: "turbo.json",
    cwd: currentDir,
    contentCheck,
  });

  if (!root) {
    try {
      root = findRootSync(currentDir);
      if (!root) {
        return null;
      }
    } catch (err) {
      return null;
    }
  }

  if (cacheEnabled) {
    configCache[currentDir] = root;
  }

  return root;
}

export default getTurboRoot;