summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/GlobRemap.js
blob: 5e2bea37a771f42fda650f4e4063cf258a228acd (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import path from "node:path";
import ProjectDirectories from "./ProjectDirectories.js";
import PathNormalizer from "./PathNormalizer.js";

// even on Windows (in cmd.exe) these paths are normalized to forward slashes
// tinyglobby expects forward slashes on Windows
const SEP = "/";

class GlobRemap {
	constructor(paths = []) {
		this.paths = paths;
		this.cwd = GlobRemap.getCwd(paths);
	}

	getCwd() {
		return this.cwd;
	}

	getRemapped(paths) {
		return paths.map((entry) => GlobRemap.remapInput(entry, this.cwd));
	}

	getInput() {
		return this.getRemapped(this.paths);
	}

	getOutput(paths = []) {
		return paths.map((entry) => GlobRemap.remapOutput(entry, this.cwd));
	}

	static getParentDirPrefix(filePath = "") {
		let count = [];
		for (let p of filePath.split(SEP)) {
			if (p === "..") {
				count.push("..");
			} else {
				break;
			}
		}

		if (count.length > 0) {
			// trailing slash
			return count.join(SEP) + SEP;
		}
		return "";
	}

	static getLongestParentDirPrefix(filePaths) {
		let longest = "";
		filePaths
			.map((entry) => {
				return this.getParentDirPrefix(entry);
			})
			.filter((entry) => Boolean(entry))
			.forEach((prefix) => {
				if (!longest || prefix.length > longest.length) {
					longest = prefix;
				}
			});
		return longest;
	}

	// alias
	static getCwd(filePaths) {
		return this.getLongestParentDirPrefix(filePaths);
	}

	static remapInput(entry, cwd) {
		if (cwd) {
			if (!entry.startsWith("**" + SEP) && !entry.startsWith(`.git${SEP}**`)) {
				return PathNormalizer.normalizeSeperator(ProjectDirectories.getRelativeTo(entry, cwd));
			}
		}
		return entry;
	}

	static remapOutput(entry, cwd) {
		if (cwd) {
			return PathNormalizer.normalizeSeperator(path.join(cwd, entry));
		}
		return entry;
	}
}

export default GlobRemap;