-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathmain.rs
494 lines (459 loc) · 17.5 KB
/
main.rs
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use std::borrow::Cow;
use std::fs::{self, read_to_string};
use std::io::ErrorKind as IoErrorKind;
use std::path::Path;
use std::process::exit;
use citationberg::taxonomy::Locator;
use citationberg::{
IndependentStyle, Locale, LocaleCode, LocaleFile, LongShortForm, Style,
};
use clap::builder::PossibleValue;
use clap::{crate_version, Arg, ArgAction, Command, ValueEnum};
use strum::VariantNames;
use hayagriva::archive::{locales, ArchivedStyle};
use hayagriva::{
io, BibliographyDriver, CitationItem, CitationRequest, LocatorPayload,
SpecificLocator,
};
use hayagriva::{BibliographyRequest, Selector};
#[derive(Debug, Copy, Clone, PartialEq, VariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum Format {
#[cfg(feature = "biblatex")]
Bibtex,
#[cfg(feature = "biblatex")]
Biblatex,
Yaml,
}
impl ValueEnum for Format {
fn value_variants<'a>() -> &'a [Self] {
if cfg!(feature = "biblatex") {
&[Self::Bibtex, Self::Biblatex, Self::Yaml]
} else {
&[Self::Yaml]
}
}
fn to_possible_value(&self) -> Option<PossibleValue> {
let value = match self {
#[cfg(feature = "biblatex")]
Format::Bibtex => "bibtex",
#[cfg(feature = "biblatex")]
Format::Biblatex => "biblatex",
Format::Yaml => "yaml",
};
Some(PossibleValue::new(value))
}
}
/// Main function of the Hayagriva CLI.
fn main() {
let matches = Command::new("Hayagriva CLI")
.version(crate_version!())
.author("The Typst Project Developers <hi@typst.app>")
.about("Format references and citations for your YAML-encoded or BibLaTeX bibliography files and query bibliographies using selectors.")
.arg(
Arg::new("INPUT")
.help("Sets the bibliography file to use")
.required(true)
.index(1)
).arg(
Arg::new("format")
.long("format")
.help("What input file format to expect")
.value_parser(clap::value_parser!(Format))
.ignore_case(true)
.num_args(1)
.global(true),
).arg(
Arg::new("selector")
.long("select")
.help("Filter the bibliography using selectors")
.num_args(1)
.global(true)
)
.arg(
Arg::new("key")
.long("key")
.short('k')
.help("Filter the bibliography using a comma-separated list of keys")
.num_args(1)
.global(true)
)
.arg(
Arg::new("show-keys")
.long("show-keys")
.help("Show the keys of all filtered entries")
.action(ArgAction::SetTrue)
.global(true)
)
.arg(
Arg::new("show-bound")
.long("show-bound")
.help("Show the bound entries of your selector for each key")
.action(ArgAction::SetTrue)
.global(true)
)
.arg(
Arg::new("no-fmt")
.long("no-fmt")
.short('n')
.help("Suppress the formatting of output with ANSI / VT100 character sequences")
.action(ArgAction::SetTrue)
.global(true)
)
.subcommand(
Command::new("cite")
.about("Format citations for all filtered entries")
.arg(
Arg::new("style")
.long("style")
.short('s')
.help("Set the citation style")
.ignore_case(true)
.num_args(1)
.required_unless_present("csl")
)
.arg(
Arg::new("csl")
.long("csl")
.help("Set a CSL file to use the style therein")
.num_args(1)
)
.arg(
Arg::new("locale")
.long("locale")
.help("Which locale to force for the citation (e.g. `en-US`)")
.num_args(1)
)
.arg(
Arg::new("locales")
.long("locales")
.help("Set a comma-separated list of CSL locales")
.num_args(1)
)
.arg(
Arg::new("locators")
.long("locators")
.help("Specify additional information for the citations, e.g. \"p. 6,p. 4\", in a comma-separated list.")
.num_args(1)
)
.arg(
Arg::new("combined")
.long("combined")
.short('c')
.action(ArgAction::SetTrue)
.help("Combine all keys into one citation (ignored for Chicago Notes)")
)
)
.subcommand(
Command::new("reference")
.about("Format a bibliography of all filtered entries")
.arg(
Arg::new("style")
.long("style")
.short('s')
.help("Set the referencing style")
.ignore_case(true)
.num_args(1)
.required_unless_present("csl")
)
.arg(
Arg::new("csl")
.long("csl")
.help("Set a CSL file to use the style therein")
.num_args(1)
)
.arg(
Arg::new("locale")
.long("locale")
.help("Which locale to force for the citation (e.g. `en-US`)")
.num_args(1)
)
.arg(
Arg::new("locales")
.long("locales")
.help("Set a space-separated list of CSL locales")
.num_args(1)
)
)
.subcommand(
Command::new("styles")
.about("List all available citation styles")
)
.get_matches();
let input = Path::new(matches.get_one::<String>("INPUT").unwrap());
let format = matches.get_one("format").cloned().unwrap_or_else(|| {
#[allow(unused_mut)]
let mut format = Format::Yaml;
#[cfg(feature = "biblatex")]
if input
.extension()
.and_then(|ext| ext.to_str())
.map_or(false, |ext| ext.to_lowercase() == "bib")
{
format = Format::Bibtex;
}
format
});
let bibliography = {
let input = match read_to_string(input) {
Ok(s) => s,
Err(e) => {
if e.kind() == IoErrorKind::NotFound {
eprintln!("Bibliography file \"{}\" not found.", input.display());
exit(5);
} else if let Some(os) = e.raw_os_error() {
eprintln!(
"Error while reading the bibliography file \"{}\": {}",
input.display(),
os
);
exit(6);
} else {
eprintln!(
"Error while reading the bibliography file \"{}\".",
input.display()
);
exit(6);
}
}
};
match format {
Format::Yaml => io::from_yaml_str(&input).unwrap(),
#[cfg(feature = "biblatex")]
Format::Biblatex | Format::Bibtex => io::from_biblatex_str(&input).unwrap(),
}
};
let bib_len = bibliography.len();
let selector =
matches
.get_one("selector")
.cloned()
.map(|src| match Selector::parse(src) {
Ok(selector) => selector,
Err(err) => {
eprintln!("Error while parsing selector: {}", err);
exit(7);
}
});
let bibliography = if let Some(keys) = matches.get_one::<String>("key") {
let mut res = vec![];
for key in keys.split(',') {
if let Some(entry) = bibliography.iter().find(|e| e.key() == key) {
res.push(entry.clone());
}
}
res.into_iter().collect()
} else if let Some(selector) = &selector {
bibliography.into_iter().filter(|e| selector.matches(e)).collect()
} else {
bibliography
};
if matches.get_flag("show-keys") || matches.get_flag("show-bound") {
println!(
"Selected {} of {} entries in the bibliography\n",
bibliography.len(),
bib_len
);
for entry in &bibliography {
println!("{}", entry.key());
if matches.get_flag("show-bound") {
if let Some(selector) = &selector {
for (k, v) in selector.apply(entry).unwrap() {
println!(
"\t{} => [{:?}] {}, {}",
k,
v.entry_type(),
if let Some(authors) =
entry.authors().or_else(|| entry.editors())
{
authors.iter().map(|a| a.name.as_str()).fold(
String::new(),
|mut prev, curr| {
if !prev.is_empty() {
prev.push_str(", ");
}
prev.push_str(curr);
prev
},
)
} else {
"no authors".to_string()
},
entry
.title()
.map(|s| s.select(LongShortForm::default()).to_str())
.unwrap_or_else(|| Cow::Borrowed("no title"))
);
}
}
}
}
exit(0);
}
match matches.subcommand() {
Some(("reference", sub_matches)) => {
let style: Option<&String> = sub_matches.get_one("style");
let csl: Option<&String> = sub_matches.get_one("csl");
let locale_path =
sub_matches.get_one::<String>("locales").map(|s| s.split(','));
let locale_str: Option<&String> = sub_matches.get_one("locale");
let (style, locales, locale) =
retrieve_assets(style, csl, locale_path, locale_str);
if style.bibliography.is_none() {
eprintln!("style has no bibliography");
exit(4);
}
let mut driver = BibliographyDriver::new();
for entry in &bibliography {
driver.citation(CitationRequest::new(
vec![CitationItem::with_entry(entry)],
&style,
locale.clone(),
&locales,
None,
))
}
for row in driver
.finish(BibliographyRequest::new(&style, locale, &locales))
.bibliography
.map(|b| b.items)
.unwrap_or_default()
{
let alternate = matches.get_flag("no-fmt");
if let Some(prefix) = row.first_field {
if alternate {
println!("{:#}", prefix)
} else {
println!("{}", prefix)
}
}
if alternate {
println!("{:#}", row.content)
} else {
println!("{}", row.content)
}
}
}
Some(("cite", sub_matches)) => {
let style: Option<&String> = sub_matches.get_one("style");
let csl: Option<&String> = sub_matches.get_one("csl");
let locale_path =
sub_matches.get_one::<String>("locales").map(|s| s.split(','));
let locale_str: Option<&String> = sub_matches.get_one("locale");
let collapse = sub_matches.get_flag("combined");
let locators: Vec<_> = sub_matches
.get_one::<String>("locators")
.into_iter()
.flat_map(|s| s.split(','))
.collect();
let (style, locales, locale) =
retrieve_assets(style, csl, locale_path, locale_str);
let assign_locator = |(i, e)| {
let mut item = CitationItem::with_entry(e);
if let Some(&locator) = locators.get(i) {
item.locator = Some(SpecificLocator(
Locator::Custom,
LocatorPayload::Str(locator),
));
}
item
};
let mut driver = BibliographyDriver::new();
if collapse {
driver.citation(CitationRequest::new(
bibliography.iter().enumerate().map(assign_locator).collect(),
&style,
locale.clone(),
&locales,
None,
));
} else {
for (i, entry) in bibliography.iter().enumerate() {
driver.citation(CitationRequest::new(
vec![assign_locator((i, entry))],
&style,
locale.clone(),
&locales,
None,
))
}
}
for row in driver
.finish(BibliographyRequest::new(&style, locale, &locales))
.citations
{
let alternate = matches.get_flag("no-fmt");
if let Some(note_number) = row.note_number {
if alternate {
println!("{:#}", note_number)
} else {
println!("{}.", note_number)
}
}
if alternate {
println!("{:#}", row.citation)
} else {
println!("{}", row.citation)
}
}
}
Some(("styles", _)) => {
for key in ArchivedStyle::all() {
let style = key.get();
println!("- {}", &key.names()[0]);
println!(" Full name: {}", &style.info().title.value);
println!(" Authors:");
for author in style.info().authors.iter() {
print!(" - {}", author.name);
if let Some(email) = &author.email {
println!(" <{}>", email);
} else {
println!();
}
}
if let Some(desc) = &style.info().summary {
println!(" Summary: {}", &desc.value);
}
}
}
_ => {
let bib = io::to_yaml_str(&bibliography).unwrap();
println!("{}", bib);
}
}
}
fn retrieve_assets<'a>(
style: Option<&String>,
csl: Option<&String>,
locale_paths: Option<impl Iterator<Item = &'a str>>,
locale_str: Option<&String>,
) -> (IndependentStyle, Vec<Locale>, Option<LocaleCode>) {
let locale: Option<_> = locale_str.map(|l: &String| LocaleCode(l.into()));
let style = match (style, csl) {
(_, Some(csl)) => {
let file_str = fs::read_to_string(csl).expect("could not read CSL file");
IndependentStyle::from_xml(&file_str).expect("CSL file malformed")
}
(Some(style), _) => {
let Style::Independent(indep) =
ArchivedStyle::by_name(style.as_str()).expect("no style found").get()
else {
panic!("dependent style in archive")
};
indep
}
(None, None) => panic!("must specify style or CSL file"),
};
let locales: Vec<Locale> = match locale_paths {
Some(locale_paths) => locale_paths
.into_iter()
.map(|locale_path| {
let file_str =
fs::read_to_string(locale_path).expect("could not read locale file");
LocaleFile::from_xml(&file_str).expect("locale file malformed").into()
})
.collect(),
None => locales(),
};
(style, locales, locale)
}