UNPKG

1.31 kBJavaScriptView Raw
1// @flow strict-local
2
3import type {FilePath} from '@parcel/types';
4import {isGlob} from './glob';
5
6const path = require('path');
7
8export default function getRootDir(files: Array<FilePath>): FilePath {
9 let cur = null;
10
11 for (let file of files) {
12 let parsed = path.parse(file);
13 parsed.dir = findGlobRoot(parsed.dir);
14 if (!cur) {
15 cur = parsed;
16 } else if (parsed.root !== cur.root) {
17 // bail out. there is no common root.
18 // this can happen on windows, e.g. C:\foo\bar vs. D:\foo\bar
19 return process.cwd();
20 } else {
21 // find the common path parts.
22 let curParts = cur.dir.split(path.sep);
23 let newParts = parsed.dir.split(path.sep);
24 let len = Math.min(curParts.length, newParts.length);
25 let i = 0;
26 while (i < len && curParts[i] === newParts[i]) {
27 i++;
28 }
29
30 cur.dir = i > 1 ? curParts.slice(0, i).join(path.sep) : cur.root;
31 }
32 }
33
34 return cur ? cur.dir : process.cwd();
35}
36
37// Transforms a path like `packages/*/src/index.js` to the root of the glob, `packages/`
38function findGlobRoot(dir: FilePath) {
39 let parts = dir.split(path.sep);
40 let last = parts.length;
41 for (let i = parts.length - 1; i >= 0; i--) {
42 if (isGlob(parts[i])) {
43 last = i;
44 }
45 }
46
47 return parts.slice(0, last).join(path.sep);
48}