1 |
|
2 |
|
3 | import type {FilePath} from '@parcel/types';
|
4 | import {isGlob} from './glob';
|
5 |
|
6 | const path = require('path');
|
7 |
|
8 | export 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 |
|
18 |
|
19 | return process.cwd();
|
20 | } else {
|
21 |
|
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 |
|
38 | function 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 | }
|