Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
200 lines (181 loc) · 6.89 KB
/
Copy pathbuild.rs
File metadata and controls
200 lines (181 loc) · 6.89 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//! Build webgit's giallo dump from the grammars/themes that Cargo fetched with
//! the giallo dependency.
//!
//! The dump is a generated artifact, not a source file: keeping it out of the
//! repo means a giallo update cannot leave behind a stale registry. Cargo
//! fetches giallo's `grammars-themes` submodule into its git checkout, so the
//! build script asks Cargo where that package is, loads every grammar and the
//! one theme webgit uses, and writes the compact bitcode+zstd dump to
//! `OUT_DIR`.
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::MetadataCommand;
use giallo::Registry;
use glob::glob;
use std::collections::HashMap;
use std::env;
use std::fs;
/// The only theme webgit ships.
const THEME: &str = "github-light-high-contrast";
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=Cargo.lock");
if let Err(error) = run() {
panic!("failed to build giallo dump: {error}");
}
}
fn run() -> Result<(), String> {
let manifest_dir =
Utf8PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|e| e.to_string())?);
let out_dir = Utf8PathBuf::from(env::var("OUT_DIR").map_err(|e| e.to_string())?);
let giallo = giallo_checkout(&manifest_dir)?;
let grammars = giallo.join("grammars-themes/packages/tm-grammars/grammars");
let themes = giallo.join("grammars-themes/packages/tm-themes/themes");
let metadata = giallo.join("grammars-themes/packages/tm-grammars/index.js");
let aliases = parse_aliases(&metadata)?;
let mut registry = Registry::default();
let mut grammar_errors = 0usize;
for path in json_files(&grammars)? {
let Some(name) = path.file_stem() else {
continue;
};
if registry.add_grammar_from_path(&path).is_err() {
grammar_errors += 1;
continue;
}
for alias in aliases.get(name).into_iter().flatten() {
registry.add_alias(name, alias);
}
}
let theme = themes.join(format!("{THEME}.json"));
registry
.add_theme_from_path(&theme)
.map_err(|e| format!("{}: {e}", theme.as_str()))?;
registry
.add_plain_grammar(&["txt", "text"])
.map_err(|e| e.to_string())?;
if grammar_errors > 0 {
println!("cargo:warning=skipped {grammar_errors} unreadable grammar(s)");
}
let dump = registry.dump().map_err(|e| e.to_string())?;
let output = out_dir.join("builtin.zst");
fs::write(&output, dump).map_err(|e| format!("{}: {e}", output.as_str()))?;
let css = format!(
"/* Generated by build.rs from the giallo {THEME} theme. */\n\n{}{}",
giallo::GIALLO_CSS,
registry
.generate_css(THEME, "g-")
.map_err(|e| e.to_string())?
);
let css = keep_page_background(css);
let output = out_dir.join("giallo.css");
fs::write(&output, css).map_err(|e| format!("{}: {e}", output.as_str()))?;
Ok(())
}
/// Drop the theme's page background from the generated `.g-code` rule. The
/// code cell inherits only the theme's foreground so the app's background,
/// selected-row colours and blame shading still show through.
fn keep_page_background(css: String) -> String {
let mut out = String::with_capacity(css.len());
let mut in_code_rule = false;
for line in css.lines() {
if line.trim_start().starts_with(".g-code") {
in_code_rule = true;
} else if in_code_rule && line.trim_start().starts_with("background-color:") {
continue;
}
out.push_str(line);
out.push('\n');
if in_code_rule && line.trim() == "}" {
in_code_rule = false;
}
}
out
}
/// Ask Cargo where it put the giallo package. This handles git checkouts without
/// depending on Cargo's `$CARGO_HOME/git/checkouts` layout.
fn giallo_checkout(manifest_dir: &Utf8Path) -> Result<Utf8PathBuf, String> {
let metadata = MetadataCommand::new()
.manifest_path(manifest_dir.join("Cargo.toml"))
.exec()
.map_err(|e| format!("cargo metadata: {e}"))?;
let package = metadata
.packages
.iter()
.find(|package| package.name == "giallo")
.ok_or("cargo metadata has no giallo package")?;
package
.manifest_path
.parent()
.map(Utf8Path::to_path_buf)
.ok_or_else(|| format!("{} has no parent", package.manifest_path))
}
/// The JSON files in `dir`, sorted for a stable dump.
fn json_files(dir: &Utf8Path) -> Result<Vec<Utf8PathBuf>, String> {
let pattern = format!("{dir}/*.json");
let mut files = Vec::new();
for path in glob(&pattern).map_err(|e| format!("{pattern}: {e}"))? {
let path = path.map_err(|e| format!("{pattern}: {e}"))?;
let path = Utf8PathBuf::from_path_buf(path)
.map_err(|path| format!("non-UTF-8 path: {}", path.display()))?;
files.push(path);
}
files.sort();
Ok(files)
}
/// Parse `name -> aliases` from the grammars package's generated `index.js`.
///
/// The file is generated with a fixed shape: top-level objects are indented by
/// two spaces, grammar fields by four. A tiny line parser avoids adding a
/// JavaScript or JS-parser dependency to the build.
fn parse_aliases(path: &Utf8Path) -> Result<HashMap<String, Vec<String>>, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.as_str()))?;
let mut aliases_by_name = HashMap::new();
let mut name = None;
let mut aliases = Vec::new();
let mut in_aliases = false;
for line in text.lines() {
if line == " {" {
name = None;
aliases.clear();
in_aliases = false;
continue;
}
if line.starts_with(" }") {
if let Some(name) = name.take()
&& !aliases.is_empty()
{
aliases_by_name.insert(name, std::mem::take(&mut aliases));
}
aliases.clear();
in_aliases = false;
continue;
}
let trimmed = line.trim_start();
if in_aliases {
aliases.extend(quoted(trimmed));
if trimmed.starts_with("],") || trimmed == "]" {
in_aliases = false;
}
} else if let Some(rest) = trimmed.strip_prefix("aliases: [") {
aliases.extend(quoted(rest));
in_aliases = !rest.contains(']');
} else if let Some(rest) = line.strip_prefix(" name: '") {
name = rest.find('\'').map(|end| rest[..end].to_string());
}
}
Ok(aliases_by_name)
}
/// Every single-quoted string in `text`.
fn quoted(text: &str) -> Vec<String> {
let mut strings = Vec::new();
let mut chars = text.char_indices();
while let Some((start, quote)) = chars.next() {
if quote != '\'' {
continue;
}
if let Some((end, _)) = chars.find(|&(_, c)| c == '\'') {
strings.push(text[start + 1..end].to_string());
}
}
strings
}