on 6c11708 help sign in
helix/xtask/src/main.rs
277 lines 7.8 kB history raw
1use std::{env, error::Error};
3type DynError = Box<dyn Error>;
5pub mod helpers {
6 use std::{
7 fmt::Display,
8 path::{Path, PathBuf},
9 };
11 use crate::path;
12 use helix_core::syntax::Configuration as LangConfig;
14 #[derive(Copy, Clone)]
15 pub enum TsFeature {
16 Highlight,
17 TextObjects,
18 AutoIndent,
19 }
21 impl TsFeature {
22 pub fn all() -> &'static [Self] {
23 &[Self::Highlight, Self::TextObjects, Self::AutoIndent]
24 }
26 pub fn runtime_filename(&self) -> &'static str {
27 match *self {
28 Self::Highlight => "highlights.scm",
29 Self::TextObjects => "textobjects.scm",
30 Self::AutoIndent => "indents.toml",
31 }
32 }
33 }
35 impl Display for TsFeature {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 write!(
38 f,
39 "{}",
40 match *self {
41 Self::Highlight => "Syntax Highlighting",
42 Self::TextObjects => "Treesitter Textobjects",
43 Self::AutoIndent => "Auto Indent",
44 }
45 )
46 }
47 }
49 /// Get the list of languages that support a particular tree-sitter
50 /// based feature.
51 pub fn ts_lang_support(feat: TsFeature) -> Vec<String> {
52 let queries_dir = path::ts_queries();
54 find_files(&queries_dir, feat.runtime_filename())
55 .iter()
56 .map(|f| {
57 // .../helix/runtime/queries/python/highlights.scm
58 let tail = f.strip_prefix(&queries_dir).unwrap(); // python/highlights.scm
59 let lang = tail.components().next().unwrap(); // python
60 lang.as_os_str().to_string_lossy().to_string()
61 })
62 .collect()
63 }
65 /// Get the list of languages that have any form of tree-sitter
66 /// queries defined in the runtime directory.
67 pub fn langs_with_ts_queries() -> Vec<String> {
68 std::fs::read_dir(path::ts_queries())
69 .unwrap()
70 .filter_map(|entry| {
71 let entry = entry.ok()?;
72 entry
73 .file_type()
74 .ok()?
75 .is_dir()
76 .then(|| entry.file_name().to_string_lossy().to_string())
77 })
78 .collect()
79 }
81 // naive implementation, but suffices for our needs
82 pub fn find_files(dir: &Path, filename: &str) -> Vec<PathBuf> {
83 std::fs::read_dir(dir)
84 .unwrap()
85 .filter_map(|entry| {
86 let path = entry.ok()?.path();
87 if path.is_dir() {
88 Some(find_files(&path, filename))
89 } else {
90 (path.file_name()?.to_string_lossy() == filename).then(|| vec![path])
91 }
92 })
93 .flatten()
94 .collect()
95 }
97 pub fn lang_config() -> LangConfig {
98 let bytes = std::fs::read(path::lang_config()).unwrap();
99 toml::from_slice(&bytes).unwrap()
100 }
103pub mod md_gen {
104 use crate::DynError;
106 use crate::helpers;
107 use crate::path;
108 use std::fs;
110 use helix_term::commands::cmd::TYPABLE_COMMAND_LIST;
112 pub const TYPABLE_COMMANDS_MD_OUTPUT: &str = "typable-cmd.md";
113 pub const LANG_SUPPORT_MD_OUTPUT: &str = "lang-support.md";
115 fn md_table_heading(cols: &[String]) -> String {
116 let mut header = String::new();
117 header += &md_table_row(cols);
118 header += &md_table_row(&vec!["---".to_string(); cols.len()]);
119 header
120 }
122 fn md_table_row(cols: &[String]) -> String {
123 "| ".to_owned() + &cols.join(" | ") + " |\n"
124 }
126 fn md_mono(s: &str) -> String {
127 format!("`{}`", s)
128 }
130 pub fn typable_commands() -> Result<String, DynError> {
131 let mut md = String::new();
132 md.push_str(&md_table_heading(&[
133 "Name".to_owned(),
134 "Description".to_owned(),
135 ]));
137 let cmdify = |s: &str| format!("`:{}`", s);
139 for cmd in TYPABLE_COMMAND_LIST {
140 let names = std::iter::once(&cmd.name)
141 .chain(cmd.aliases.iter())
142 .map(|a| cmdify(a))
143 .collect::<Vec<_>>()
144 .join(", ");
146 md.push_str(&md_table_row(&[names.to_owned(), cmd.doc.to_owned()]));
147 }
149 Ok(md)
150 }
152 pub fn lang_features() -> Result<String, DynError> {
153 let mut md = String::new();
154 let ts_features = helpers::TsFeature::all();
156 let mut cols = vec!["Language".to_owned()];
157 cols.append(
158 &mut ts_features
159 .iter()
160 .map(|t| t.to_string())
161 .collect::<Vec<_>>(),
162 );
163 cols.push("Default LSP".to_owned());
165 md.push_str(&md_table_heading(&cols));
166 let config = helpers::lang_config();
168 let mut langs = config
169 .language
170 .iter()
171 .map(|l| l.language_id.clone())
172 .collect::<Vec<_>>();
173 langs.sort_unstable();
175 let mut ts_features_to_langs = Vec::new();
176 for &feat in ts_features {
177 ts_features_to_langs.push((feat, helpers::ts_lang_support(feat)));
178 }
180 let mut row = Vec::new();
181 for lang in langs {
182 let lc = config
183 .language
184 .iter()
185 .find(|l| l.language_id == lang)
186 .unwrap(); // lang comes from config
187 row.push(lc.language_id.clone());
189 for (_feat, support_list) in &ts_features_to_langs {
190 row.push(
191 if support_list.contains(&lang) {
192 "✓"
193 } else {
194 ""
195 }
196 .to_owned(),
197 );
198 }
199 row.push(
200 lc.language_server
201 .as_ref()
202 .map(|s| s.command.clone())
203 .map(|c| md_mono(&c))
204 .unwrap_or_default(),
205 );
207 md.push_str(&md_table_row(&row));
208 row.clear();
209 }
211 Ok(md)
212 }
214 pub fn write(filename: &str, data: &str) {
215 let error = format!("Could not write to {}", filename);
216 let path = path::book_gen().join(filename);
217 fs::write(path, data).expect(&error);
218 }
221pub mod path {
222 use std::path::{Path, PathBuf};
224 pub fn project_root() -> PathBuf {
225 Path::new(env!("CARGO_MANIFEST_DIR"))
226 .parent()
227 .unwrap()
228 .to_path_buf()
229 }
231 pub fn book_gen() -> PathBuf {
232 project_root().join("book/src/generated/")
233 }
235 pub fn ts_queries() -> PathBuf {
236 project_root().join("runtime/queries")
237 }
239 pub fn lang_config() -> PathBuf {
240 project_root().join("languages.toml")
241 }
244pub mod tasks {
245 use crate::md_gen;
246 use crate::DynError;
248 pub fn docgen() -> Result<(), DynError> {
249 use md_gen::*;
250 write(TYPABLE_COMMANDS_MD_OUTPUT, &typable_commands()?);
251 write(LANG_SUPPORT_MD_OUTPUT, &lang_features()?);
252 Ok(())
253 }
255 pub fn print_help() {
256 println!(
257 "
258Usage: Run with `cargo xtask <task>`, eg. `cargo xtask docgen`.
260 Tasks:
261 docgen: Generate files to be included in the mdbook output.
263 );
264 }
267fn main() -> Result<(), DynError> {
268 let task = env::args().nth(1);
269 match task {
270 None => tasks::print_help(),
271 Some(t) => match t.as_str() {
272 "docgen" => tasks::docgen()?,
273 invalid => return Err(format!("Invalid task name: {}", invalid).into()),
274 },
275 };
276 Ok(())