1
use json_ld::{NoLoader, RemoteDocument, RemoteDocumentReference};
2
use json_ld_syntax::context::Value;
3
use locspan::{Location, Meta, Span};
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
        vocabulary::ArcIri,
16
        ContextRef, JsonLdOptions, JsonLdParser,
17
    },
18
    turtle::serializer::turtle::{TurtleConfig, TurtleSerializer},
19
};
20
use std::sync::Arc;
21

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

            
47
// ArcIri, Location<ArcIri, Span>, Value<Location<ArcIri, Span>>
48
fn create_context(context_str: &str) -> ContextRef {
49
    use json_ld::syntax::Parse;
50
    let vdoc = json_ld::syntax::Value::parse_str(context_str, |span| span).unwrap();
51
    let mdoc: Meta<_, _> = todo!();
52
    let rdoc: RemoteDocument<ArcIri, Location<ArcIri, Span>, Value<Location<ArcIri, Span>>> =
53
        RemoteDocument::new(None, None, mdoc);
54
    RemoteDocumentReference::Loaded(rdoc)
55
}
56

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

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

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