1
use json_ld::{NoLoader, RemoteDocument, RemoteDocumentReference};
2
use json_ld_syntax::context::Value;
3
use locspan::Meta;
4
use sophia::{
5
    api::{
6
        graph::CollectibleGraph,
7
        parser::QuadParser,
8
        serializer::{Stringifier, TripleSerializer},
9
        source::QuadSource,
10
    },
11
    inmem::graph::LightGraph,
12
    iri::Iri,
13
    jsonld::{
14
        loader_factory::{DefaultLoaderFactory, LoaderFactory},
15
        JsonLdOptions, JsonLdParser,
16
    },
17
    turtle::serializer::turtle::{TurtleConfig, TurtleSerializer},
18
};
19
use std::sync::Arc;
20

            
21
fn main() {
22
    let mut args = std::env::args();
23
    let json_ld_path = args.nth(1).expect("Missing jsonld file.");
24
    let context_path = args.next();
25
    if let Some(context_path) = &context_path {
26
        println!(
27
            "Loading {} with @context from {}",
28
            json_ld_path, context_path
29
        );
30
    } else {
31
        println!("Loading {}", json_ld_path);
32
    }
33
    let json_str = std::fs::read_to_string(&json_ld_path)
34
        .expect(&format!("Could not read file {}.", json_ld_path));
35
    let mut options = create_options();
36
    if let Some(context_path) = context_path {
37
        let context_str = std::fs::read_to_string(&context_path)
38
            .expect(&format!("Could not read file {}.", context_path));
39
        let context = create_context(&context_str);
40
        options = options.with_expand_context::<()>(context);
41
    }
42
    let parser = create_parser(options);
43
    parse(&json_str, parser);
44
}
45

            
46
fn create_context<L: std::clone::Clone>(
47
    context_str: &str,
48
) -> RemoteDocumentReference<Iri<Arc<str>>, L, Value<L>> {
49
    use json_ld::syntax::Parse;
50
    let vdoc: Meta<_, _> = json_ld::syntax::Value::parse_str(context_str, |span| span).unwrap();
51
    let mdoc: Meta<Value<L>, L> = todo!();
52
    let rdoc: RemoteDocument<_, _, _> = RemoteDocument::new(None, None, mdoc);
53
    RemoteDocumentReference::Loaded(rdoc)
54
}
55

            
56
fn create_options<I, M, T>() -> JsonLdOptions<DefaultLoaderFactory<NoLoader<I, M, T>>> {
57
    JsonLdOptions::<DefaultLoaderFactory<NoLoader<I, M, T>>>::default()
58
}
59

            
60
fn create_parser<LF>(options: JsonLdOptions<LF>) -> JsonLdParser<LF> {
61
    JsonLdParser::<LF>::new_with_options(options)
62
}
63

            
64
fn parse<LF>(json_str: &str, parser: JsonLdParser<LF>)
65
where
66
    LF: LoaderFactory,
67
{
68
    let graph = LightGraph::from_triple_source(parser.parse_str(json_str).to_triples()).unwrap();
69
    let mut stringifier =
70
        TurtleSerializer::new_stringifier_with_config(TurtleConfig::new().with_pretty(true));
71
    let rdf = stringifier.serialize_graph(&graph).unwrap().as_str();
72
    println!("{}", rdf);
73
}