-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcli.js
executable file
·101 lines (88 loc) · 2.61 KB
/
cli.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env node
const lunr = require("lunr");
const glob = require("glob");
const fs = require("fs");
const cheerio = require("cheerio");
const path = require("path");
const program = require("commander");
function pathToURL(p) {
if (path.basename(p, ".html") !== "index") {
return "/" + p;
}
return "/" + p.split(path.sep).slice(0, -1).join("/") + "/";
}
program.version(require("./package.json").version);
program
.command("index")
.description("create an index for a static site directory")
.arguments("<dir>")
.requiredOption(
"-c, --content-selector <selector>",
"DOM selector for your main content area"
)
.option(
"-i, --index-filename <path>",
"Filename to save the index JSON",
"search-index.json"
)
.option(
"--content-title-selector <selector>",
"DOM selector for the title of your content area",
"h1"
)
.option(
"--glob <pattern>",
"Files to index in the given directory",
"**/*.html"
)
.action(function (dir, cmd) {
const indexFilename = cmd.indexFilename;
const contentSelector = cmd.contentSelector;
const contentTitleSelector = cmd.contentTitleSelector;
const globPattern = cmd.glob;
let outputData = {
pages: {},
lunr: null,
};
glob(globPattern, { cwd: dir }, function (er, paths) {
console.log(`Found ${paths.length} files`);
paths.forEach((p) => {
console.log("- " + p);
const filePath = path.join(dir, p);
const data = fs.readFileSync(filePath, "utf8");
const $ = cheerio.load(data);
const content = $(contentSelector);
const title = content.find(contentTitleSelector).remove();
const url = pathToURL(p);
outputData.pages[url] = {
title: $(title.get(0))
.text()
.trim()
.replace(/</g, "<")
.replace(/>/g, ">"),
text: content
.text()
.trim()
.replace(/</g, "<")
.replace(/>/g, ">"),
};
});
outputData.lunr = lunr(function () {
this.ref("url");
this.field("title");
this.field("text");
this.metadataWhitelist = ["position"];
Object.entries(outputData.pages).forEach(function ([url, data]) {
this.add({
url: url,
...data,
});
}, this);
});
const indexOutput = JSON.stringify(outputData, null, 2);
const indexPath = path.join(dir, indexFilename);
fs.writeFileSync(indexPath, indexOutput);
console.log("\nIndex written to " + indexPath);
});
});
program.parse(process.argv);