Lines
93.62 %
Functions
28.57 %
use json_ld::{
expansion::Policy, syntax::Value, NoLoader, RemoteDocument, RemoteDocumentReference,
};
use sophia::{
api::{
graph::CollectibleGraph,
parser::QuadParser,
serializer::{Stringifier, TripleSerializer},
source::QuadSource,
},
inmem::graph::LightGraph,
jsonld::{
loader_factory::{DefaultLoaderFactory, LoaderFactory},
vocabulary::ArcIri,
ContextRef, JsonLdOptions, JsonLdParser,
turtle::serializer::turtle::{TurtleConfig, TurtleSerializer},
use std::sync::Arc;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args();
let json_ld_path = args.nth(1).expect("Missing jsonld file.");
let context_path = args.next();
if let Some(context_path) = &context_path {
println!(
"Loading {} with @context from {}",
json_ld_path, context_path
);
} else {
println!("Loading {}", json_ld_path);
}
let json_str = std::fs::read_to_string(&json_ld_path)
.unwrap_or_else(|e| panic!("Could not read file {}: {}", json_ld_path, e));
let mut options = JsonLdOptions::<DefaultLoaderFactory<NoLoader<_, _, _>>>::default()
.with_expansion_policy(Policy::Standard);
if let Some(context_path) = context_path {
let context_str = std::fs::read_to_string(&context_path)
.map_err(|e| format!("Could not read file {}: {}", context_path, e))?;
let iri = ArcIri::new(Arc::from(format!("file:{}", &context_path)))?;
let context = parse_context(iri, &context_str)?;
options = options.with_expand_context::<()>(context);
let parser = JsonLdParser::new_with_options(options);
let turtle = to_turtle(&json_str, parser)?;
println!("{}", turtle.as_str());
Ok(())
fn parse_context(iri: ArcIri, context_str: &str) -> Result<ContextRef, Box<dyn std::error::Error>> {
use json_ld::syntax::Parse;
let doc = Value::parse_str(context_str, |span| {
locspan::Location::new(iri.clone(), span)
})?;
use json_ld::ExtractContext;
let context =
Value::extract_context(doc).map_err(|e| format!("Could not extract @context: {}", e))?;
let rdoc = RemoteDocument::new(Some(iri), None, context);
Ok(RemoteDocumentReference::Loaded(rdoc))
fn to_turtle<LF: LoaderFactory>(
json_str: &str,
parser: JsonLdParser<LF>,
) -> Result<impl Stringifier, Box<dyn std::error::Error>> {
let graph = LightGraph::from_triple_source(parser.parse_str(json_str).to_triples())?;
let mut stringifier =
TurtleSerializer::new_stringifier_with_config(TurtleConfig::new().with_pretty(true));
stringifier.serialize_graph(&graph)?;
Ok(stringifier)