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
pub mod enum_derive;
pub mod fragment_arguments_derive;
pub mod fragment_derive;
pub mod inline_fragments_derive;
pub mod query_dsl;
pub mod query_module;
pub mod scalar_derive;

mod error;
mod field_type;
mod graphql_extensions;
mod ident;
mod module;
mod struct_field;
mod type_index;
mod type_path;

use error::Error;
use field_type::FieldType;
use ident::Ident;
use struct_field::StructField;
use type_index::TypeIndex;
use type_path::TypePath;

pub fn output_query_dsl<P: AsRef<std::path::Path>>(schema: P, output_path: P) -> Result<(), Error> {
    use query_dsl::QueryDslParams;
    use std::io::Write;

    let tokens = query_dsl::query_dsl_from_schema(QueryDslParams {
        schema_filename: schema.as_ref().to_str().unwrap().to_string(),
    })?;

    {
        let mut out = std::fs::File::create(output_path.as_ref()).unwrap();
        write!(&mut out, "{}", tokens).unwrap();
    }

    format_code(output_path.as_ref());

    Ok(())
}

#[allow(unused_variables)]
fn format_code(filename: &std::path::Path) {
    #[cfg(feature = "rustfmt")]
    {
        std::process::Command::new("cargo")
            .args(&["fmt", "--", filename.to_str().unwrap()])
            .spawn()
            .expect("failed to execute process");
    }
    #[cfg(not(feature = "rustfmt"))]
    {
        return code;
    }
}

fn load_schema(
    filename: impl AsRef<std::path::Path>,
) -> Result<graphql_parser::schema::Document, Error> {
    use std::path::PathBuf;
    let mut pathbuf = PathBuf::new();

    let filename = if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
        pathbuf.push(manifest_dir);
        pathbuf.push(filename);
        pathbuf.as_path()
    } else {
        filename.as_ref()
    };

    let schema = std::fs::read_to_string(filename)?;
    Ok(graphql_parser::schema::parse_schema(&schema)?.into())
}