-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: support typst query * style: use Literal to improve type hint * Apply suggestions from code review * Merge branch 'main' into query --------- Co-authored-by: messense <[email protected]>
- Loading branch information
Showing
6 changed files
with
254 additions
and
7 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
use comemo::Track; | ||
use ecow::{eco_format, EcoString}; | ||
use serde::Serialize; | ||
use typst::diag::{bail, StrResult}; | ||
use typst::eval::{eval_string, EvalMode, Tracer}; | ||
use typst::foundations::{Content, IntoValue, LocatableSelector, Scope}; | ||
use typst::model::Document; | ||
use typst::syntax::Span; | ||
use typst::World; | ||
|
||
use crate::world::SystemWorld; | ||
|
||
/// Processes an input file to extract provided metadata | ||
#[derive(Debug, Clone)] | ||
pub struct QueryCommand { | ||
/// Defines which elements to retrieve | ||
pub selector: String, | ||
|
||
/// Extracts just one field from all retrieved elements | ||
pub field: Option<String>, | ||
|
||
/// Expects and retrieves exactly one element | ||
pub one: bool, | ||
|
||
/// The format to serialize in | ||
pub format: SerializationFormat, | ||
} | ||
|
||
// Output file format for query command | ||
#[derive(Debug, Copy, Clone, Eq, PartialEq)] | ||
pub enum SerializationFormat { | ||
Json, | ||
Yaml, | ||
} | ||
|
||
/// Execute a query command. | ||
pub fn query(world: &mut SystemWorld, command: &QueryCommand) -> StrResult<String> { | ||
// Reset everything and ensure that the main file is present. | ||
world.reset(); | ||
world.source(world.main()).map_err(|err| err.to_string())?; | ||
|
||
let mut tracer = Tracer::new(); | ||
let result = typst::compile(world, &mut tracer); | ||
let warnings = tracer.warnings(); | ||
|
||
match result { | ||
// Retrieve and print query results. | ||
Ok(document) => { | ||
let data = retrieve(world, command, &document)?; | ||
let serialized = format(data, command)?; | ||
Ok(serialized) | ||
} | ||
// Print errors and warnings. | ||
Err(errors) => { | ||
let mut message = EcoString::from("failed to compile document"); | ||
for (i, error) in errors.into_iter().enumerate() { | ||
message.push_str(if i == 0 { ": " } else { ", " }); | ||
message.push_str(&error.message); | ||
} | ||
for warning in warnings { | ||
message.push_str(": "); | ||
message.push_str(&warning.message); | ||
} | ||
Err(message) | ||
} | ||
} | ||
} | ||
|
||
/// Retrieve the matches for the selector. | ||
fn retrieve( | ||
world: &dyn World, | ||
command: &QueryCommand, | ||
document: &Document, | ||
) -> StrResult<Vec<Content>> { | ||
let selector = eval_string( | ||
world.track(), | ||
&command.selector, | ||
Span::detached(), | ||
EvalMode::Code, | ||
Scope::default(), | ||
) | ||
.map_err(|errors| { | ||
let mut message = EcoString::from("failed to evaluate selector"); | ||
for (i, error) in errors.into_iter().enumerate() { | ||
message.push_str(if i == 0 { ": " } else { ", " }); | ||
message.push_str(&error.message); | ||
} | ||
message | ||
})? | ||
.cast::<LocatableSelector>()?; | ||
|
||
Ok(document | ||
.introspector | ||
.query(&selector.0) | ||
.into_iter() | ||
.collect::<Vec<_>>()) | ||
} | ||
|
||
/// Format the query result in the output format. | ||
fn format(elements: Vec<Content>, command: &QueryCommand) -> StrResult<String> { | ||
if command.one && elements.len() != 1 { | ||
bail!("expected exactly one element, found {}", elements.len()); | ||
} | ||
|
||
let mapped: Vec<_> = elements | ||
.into_iter() | ||
.filter_map(|c| match &command.field { | ||
Some(field) => c.get_by_name(field), | ||
_ => Some(c.into_value()), | ||
}) | ||
.collect(); | ||
|
||
if command.one { | ||
let Some(value) = mapped.first() else { | ||
bail!("no such field found for element"); | ||
}; | ||
serialize(value, command.format) | ||
} else { | ||
serialize(&mapped, command.format) | ||
} | ||
} | ||
|
||
/// Serialize data to the output format. | ||
fn serialize(data: &impl Serialize, format: SerializationFormat) -> StrResult<String> { | ||
match format { | ||
SerializationFormat::Json => { | ||
serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}")) | ||
} | ||
SerializationFormat::Yaml => serde_yaml::to_string(&data).map_err(|e| eco_format!("{e}")), | ||
} | ||
} |