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
use crate::{App, GeneralArgs};

use anyhow::{anyhow, Context};
use clap::Args;
use codespan_reporting::files::SimpleFile;
use jsona::parser;
use jsona_util::{
    environment::Environment,
    schema::associations::{AssociationRule, SchemaAssociation},
};
use serde_json::json;
use tokio::io::AsyncReadExt;

impl<E: Environment> App<E> {
    pub async fn execute_lint(&mut self, cmd: LintCommand) -> Result<(), anyhow::Error> {
        if let Some(store) = &cmd.schemastore {
            if store.is_empty() || store == "-" {
                self.schemas
                    .associations()
                    .add_from_schemastore(&None, &self.env.root_uri())
                    .await
                    .with_context(|| "failed to load schema store")?;
            } else {
                let url = self
                    .env
                    .to_file_uri(store)
                    .ok_or_else(|| anyhow!("invalid schemastore {store}"))?;

                self.schemas
                    .associations()
                    .add_from_schemastore(&Some(url), &self.env.root_uri())
                    .await
                    .with_context(|| "failed to load schema store")?;
            }
        }
        if let Some(name) = &cmd.schema {
            let url = self
                .schemas
                .associations()
                .get_schema_url(name)
                .ok_or_else(|| anyhow!("invalid schema `{}`", name))?;
            self.schemas.associations().add(
                AssociationRule::glob("**")?,
                SchemaAssociation {
                    meta: json!({"source": "command-line"}),
                    url,
                    priority: 999,
                },
            );
        }

        if cmd.files.is_empty() {
            self.lint_stdin(cmd).await
        } else {
            self.lint_files(cmd).await
        }
    }

    #[tracing::instrument(skip_all)]
    async fn lint_stdin(&self, _cmd: LintCommand) -> Result<(), anyhow::Error> {
        self.lint_file("-", true).await
    }

    #[tracing::instrument(skip_all)]
    async fn lint_files(&mut self, cmd: LintCommand) -> Result<(), anyhow::Error> {
        let mut result = Ok(());

        for file in &cmd.files {
            if let Err(error) = self.lint_file(file, false).await {
                tracing::error!(%error, path = ?file, "invalid file");
                result = Err(anyhow!("some files were not valid"));
            }
        }

        result
    }

    #[tracing::instrument(skip_all, fields(%file_path))]
    async fn lint_file(&self, file_path: &str, stdin: bool) -> Result<(), anyhow::Error> {
        let (file_uri, source) = if stdin {
            let mut source = String::new();
            self.env
                .stdin()
                .read_to_string(&mut source)
                .await
                .map_err(|err| anyhow!("failed to read stdin, {err}"))?;
            ("file:///_".parse().unwrap(), source)
        } else {
            self.load_file(file_path)
                .await
                .map_err(|err| anyhow!("failed to read {file_path}, {err}"))?
        };
        let parse = parser::parse(&source);
        self.print_parse_errors(&SimpleFile::new(file_path, &source), &parse.errors)
            .await?;

        if !parse.errors.is_empty() {
            return Err(anyhow!("syntax errors found"));
        }

        let dom = parse.into_dom();

        if let Err(errors) = dom.validate() {
            self.print_semantic_errors(&SimpleFile::new(file_path, &source), errors)
                .await?;

            return Err(anyhow!("semantic errors found"));
        }

        self.schemas
            .associations()
            .add_from_document(&file_uri, &dom);

        if let Some(schema_association) = self.schemas.associations().query_for(&file_uri) {
            tracing::debug!(
                schema.url = %schema_association.url,
                schema.name = schema_association.meta["name"].as_str().unwrap_or(""),
                schema.source = schema_association.meta["source"].as_str().unwrap_or(""),
                "using schema"
            );

            let errors = self.schemas.validate(&schema_association.url, &dom).await?;

            if !errors.is_empty() {
                self.print_schema_errors(&SimpleFile::new(file_path, &source), &errors)
                    .await?;

                return Err(anyhow!("schema validation failed"));
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, Args)]
pub struct LintCommand {
    #[clap(flatten)]
    pub general: GeneralArgs,

    /// URL to the schema to be used for validation.
    ///
    /// If schemastore passed, schema name can be used.
    #[clap(long)]
    pub schema: Option<String>,

    /// URL to a schema store (index), pass "-" to point to default schema store.
    #[clap(long)]
    pub schemastore: Option<String>,

    /// Paths or glob patterns to JSONA documents.
    pub files: Vec<String>,
}