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
use std::path::Path;

use anyhow::{Context, Error};

/// Update the `schema.graphql` file.
#[derive(Debug, clap::Parser)]
pub struct SyncSchema {
    /// The GraphQL endpoint to send requests to.
    #[clap(long, env, default_value = "https://registry.wapm.io/graphql")]
    registry: String,
}

impl SyncSchema {
    pub fn execute(self) -> Result<(), Error> {
        let SyncSchema { registry } = self;
        let endpoint = format!("{registry}/schema.graphql");

        fetch_schema(&endpoint).and_then(|s| sync(&s))
    }
}

fn fetch_schema(endpoint: &str) -> Result<String, Error> {
    let response = ureq::get(endpoint)
        .send_bytes(&[])
        .context("Unable to fetch the GraphQL schema")?;
    anyhow::ensure!(
        response.status() == 200,
        "{} {}",
        response.status(),
        response.status_text()
    );

    response
        .into_string()
        .context("Unable to read the response as a string")
}

fn sync(schema: &str) -> Result<(), Error> {
    let graphql_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("graphql");
    let schema_path = graphql_dir.join("schema.graphql");

    match std::fs::read_to_string(&schema_path) {
        Ok(s) if s == schema => {
            log::debug!("Schema is already up to date");
            return Ok(());
        }
        Ok(_) => {
            log::debug!("Schema needs updating");
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            log::debug!("The schema file hasn't been created yet");
        }
        Err(e) => {
            return Err(
                Error::new(e).context(format!("Unable to read \"{}\"", schema_path.display()))
            );
        }
    }

    std::fs::create_dir_all(&graphql_dir).with_context(|| {
        format!(
            "Unable to create the \"{}\" directory",
            graphql_dir.display()
        )
    })?;

    std::fs::write(&schema_path, schema)
        .with_context(|| format!("Unable to write to \"{}\"", schema_path.display()))?;

    log::info!("The schema was updated. Please commit the changes.");

    Ok(())
}