UNPKG

1.86 kBPlain TextView Raw
1import debugFactory from 'debug';
2import findRoot from 'find-root';
3import {existsSync} from 'fs';
4import {readFile, writeFile} from 'mz/fs';
5import {resolve} from 'path';
6
7const debug = debugFactory('clark:lib:project');
8
9/**
10 * Locates the monorepo's root based on various heuristics including existence
11 * of .clarkrc, package.json, and .git paths.
12 */
13export async function findProjectRoot(): Promise<string> {
14 return findRoot(process.cwd(), (dir: string) => {
15 if (!existsSync(resolve(dir, 'package.json'))) {
16 return false;
17 }
18
19 if (existsSync(resolve(dir, '.clarkrc'))) {
20 return true;
21 }
22
23 if (existsSync(resolve(dir, '.git'))) {
24 return true;
25 }
26
27 return false;
28 });
29}
30
31/**
32 * Indicates if this project has a .clarkrc file
33 * @param rootDir
34 */
35export async function hasRc(rootDir: string): Promise<boolean> {
36 debug(`checking if "${rootDir}" contains '.clarkrc'`);
37 const contains = existsSync(resolve(rootDir, '.clarkrc'));
38 debug(
39 `"${rootDir}" ${contains ? 'contains' : 'does not contain'} '.clarkrc'`,
40 );
41 return contains;
42}
43
44/**
45 * Determines whether the given paths describe an alle monorepo by checking for
46 * a packages/node_modules path in all of them.
47 * @param paths
48 */
49export function isAlleRepo(paths: string[]): boolean {
50 return paths.every(packagePath =>
51 packagePath.includes('packages/node_modules'),
52 );
53}
54
55/**
56 * Reads the monorepo's package.json
57 */
58export async function read() {
59 debug('Reading root package.json');
60 const root = JSON.parse(await readFile('package.json', 'utf-8'));
61 debug('Read root');
62 return root;
63}
64
65/**
66 * Writes the monorepo's package.json
67 */
68export async function write(pkg: object) {
69 debug('Writing root package.json');
70 await writeFile('package.json', `${JSON.stringify(pkg, null, 2)}\n`);
71 debug('Wrote root package.json');
72 return;
73}