Coder Social home page Coder Social logo

schemafy's People

Contributors

adeschamps avatar alesharik avatar anatawa12 avatar bemyak avatar bgilbert avatar ccouzens avatar csssuf avatar jamacku avatar marwes avatar ryansroberts avatar software-opal avatar tinou98 avatar tony84727 avatar vadimcn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schemafy's Issues

Clippy warning on missing `Eq` derive

Clippy 1.63.0 added a warning for types that derive PartialEq but not Eq, and could have derived Eq. As a result, many types generated by schemafy produce Clippy warnings:

warning: you are deriving `PartialEq` and can implement `Eq`
  --> src/mod.rs:18:1
   |
18 | / schemafy!(
19 | |     root: Config
20 | |     "schema.json"
21 | | );
   | |_^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#derive_partial_eq_without_eq
   = note: this warning originates in the macro `schemafy` (in Nightly builds, run with -Z macro-backtrace for more info)

Type is Option<serde_json::Value> instead of Option<String>

In the Vega Lite schema, there is this property on an Axis:

        "title": {
          "description": "A title for the field. If `null`, the title will be removed.\n\n__Default value:__  derived from the field's name and transformation function (`aggregate`, `bin` and `timeUnit`).  If the field has an aggregate function, the function is displayed as a part of the title (e.g., `\"Sum of Profit\"`). If the field is binned or has a time unit applied, the applied function will be denoted in parentheses (e.g., `\"Profit (binned)\"`, `\"Transaction Date (year-month)\"`).  Otherwise, the title is simply the field name.\n\n__Note__: You can customize the default field title format by providing the [`fieldTitle` property in the [config](config.html) or [`fieldTitle` function via the `compile` function's options](compile.html#field-title).",
          "type": [
            "string",
            "null"
          ]
        },

This is coming out in the generated Rust as:

    /// A title for the field. If `null`, the title will be removed.
    ///
    /// __Default value:__  derived from the field's name and transformation function (`aggregate`,
    /// `bin` and `timeUnit`).  If the field has an aggregate function, the function is displayed
    /// as a part of the title (e.g., `"Sum of Profit"`). If the field is binned or has a time unit
    /// applied, the applied function will be denoted in parentheses (e.g., `"Profit (binned)"`,
    /// `"Transaction Date (year-month)"`).  Otherwise, the title is simply the field name.
    ///
    /// __Note__: You can customize the default field title format by providing the [`fieldTitle`
    /// property in the [config](config.html) or [`fieldTitle` function via the `compile`
    /// function's options](compile.html#field-title).
    pub title: Option<serde_json::Value>,

I really think that should be Option<String> though?

Test against the JSON Schema Test Suite

I think it would be compelling to test this crate against the JSON Schema Test Suite. It's also a pretty efficient way to get one or two hundred unit tests almost for free.

I've been experimenting with it here. I added the test suite repo as a git submodule and created a test-suite crate with a build script that generates types and tests. The test crate behaves like this:

  • If schemafy ever panics or returns an error, then the build script will fail.
  • If schemafy generates invalid code, then the test crate will fail to compile.
  • If the test data can't be deserialized to the generated types, then the tests themselves will fail.

There are a few cases where schemafy panics, so I excluded a few of the test files so I could at least have a functioning test suite. This includes external refs (#3) and enums where some of the variants are numbers. I only included the tests where the data is valid, since schemafy doesn't check for properties such as minLength and so on.

Along the way I realized that JSON schema have a lot of weird edge cases, including some where I personally think the spec is too lenient.

If it's useful to have partial coverage, I can open a PR now.

Line wrapping comments breaks markdown

When the comments contain bulleted lists, the current means for line wrapping them breaks those:

- Here is a bullet point item that is very long
and it continues unindented now on the second
line and the third too.
- Another item.

travis: master is currently failing

Travis runs on master are currently red, see https://travis-ci.org/Marwes/schemafy/builds/263771322.

The failure seems to be outside of schemafy scope, somewhere in-between rustfmt and nightly toolchain. I had a similar problem with clippy and CI, and I solved it via a dedicated pinned-nightly run: https://github.com/lucab/caps-rs/blob/ec179c1a6e0907b9574a2672a1c81aac15ff533f/.travis.yml

Let me know if you'd fancy such approach and whether a PR for that is welcome.

What draft(s) of JSON Schema is supported?

JSON Schema is continuing to make revisions and publish new drafts. I am guessing this is based on Draft 4. It would be great if which draft were indicated in the README.

Feature request: Macro/fn to export generated Struct to file

Hi!

I would like to use the macro within build.rs to make it export the generated struct to a file within my src.

That way schemafy can be included as dev-dependency rather than as regular dependency while also simplifying schema generation without the need of a cli tool.

Thanks

Proc macro panics on identifier beginning with a number.

Hi. I just tried this library the first time with a schema from a datatype registry, and the macro panics. I did everything like in https://github.com/Marwes/debugserver-types . The problem is the identifier. "asdf" as identifier makes it work. I believe that the identifier is valid, though. Also, I can not change it (except for this test). Those schemes are already used in other software to validate json files (I think this is one of the libraries that is used for validation: https://github.com/everit-org/json-schema/). This issue is currently not very important/urgent to me, but in case this is really a bug I thought I better report it.

Output of cargo build:

> cargo build
   Compiling schemafy_test v0.1.0 (/Users/verpfeilt/git/schemafy_test)
thread 'rustc' panicked at '`"21T111481F586Ca9A6Acbda92809"` is not a valid identifier', src/librustc_expand/proc_macro_server.rs:329:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

error: internal compiler error: unexpected panic

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports

note: rustc 1.44.1 (c7087fe00 2020-06-17) running on x86_64-apple-darwin

note: compiler flags: -C debuginfo=2 -C incremental --crate-type lib

note: some of the compiler flags provided by cargo are hidden

error: proc macro panicked
 --> src/lib.rs:3:1
  |
3 | schemafy::schemafy!("src/schema.json");
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: message: `"21T111481F586Ca9A6Acbda92809"` is not a valid identifier

warning: unused imports: `Deserialize`, `Serialize`
 --> src/lib.rs:1:13
  |
1 | use serde::{Deserialize, Serialize};
  |             ^^^^^^^^^^^  ^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error: aborting due to previous error; 1 warning emitted

error: could not compile `schemafy_test`.

To learn more, run the command again with --verbose.

My schema.json:

{
    "definitions": {
        "21.T11148_1f586ca9a6acbda92809": {
            "pattern": "^([0-9]{4})(-)?([0][1-9]|1[0-2])(-)?([0-2][0-9]|3[0-1]) ([0-1][0-9]|2[0-3])(:)?([0-5][0-9])(:)?([0-5][0-9](\\.[0-9]*)?)( UTC)?$",
            "type": "string",
            "description": "[email protected]/1f586ca9a6acbda92809"
        }
    },
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "[email protected]/29f92bd203dd3eaa5a1f",
    "$ref": "#/definitions/21.T11148_1f586ca9a6acbda92809"
}

Support more recent drafts

Schemafy currently supports draft 4. What would be involved in updating to support the more recent drafts? Is this something I might be able to take on?

`derive helper attribute is used before it is introduced` warning in schemafy::schemafy!

When generating rust types for openapi schema with schemafy::schemafy!

warning: derive helper attribute is used before it is introduced
   --> generator/src/main.rs:7:1
    |
7   | / schemafy::schemafy!(
8   | |     "../schema/openapi-schema.json"
9   | | );
    | |  ^
    | |  |
    | |__the attribute is introduced here
    |    in this macro invocation
    | 
   ::: /Users/anatawa12/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:157:1
    |
157 |   pub fn schemafy(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    |   --------------------------------------------------------------------------- in this expansion of `schemafy::schemafy!`
    |
    = note: `#[warn(legacy_derive_helpers)]` on by default
    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
    = note: for more information, see issue #79202 <https://github.com/rust-lang/rust/issues/79202>

warning: 1 warning emitted

Generated structure naming inconsistency?

So I ran this to see how things end up:

use serde_json;
use schemafy_lib::Expander;

fn main() {

    let json = r#"{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Test Schema",
  "type": "object",
  "properties": {
    "method": {
      "type": "string"
    },
    "fetch": {
      "type": "object",
      "properties": {
        "url": {
          "type": "string"
        }
      },
      "required": [
        "url"
      ]
    },

    "process": {
      "type": "object",
      "properties": {
        "replace": {
          "type": "object",
          "properties": {
            "url": {
              "type": "string"
            }
          },
          "required": [
            "url"
          ]
        }
      },
      "required": [
        "replace"
      ]
    }
  },
  "required": [
    "method",
    "fetch",
    "process"
  ]
}"#; 
    let schema = serde_json::from_str(json).unwrap();
    let mut expander = Expander::new(Some("Test Schema"), "::schemafy_core::", &schema);
    let res = expander.expand(&schema);

    


    println!("{}", 
        res.to_string()
            .replace(" # [","\n\n# [")
            .replace("pub struct ","\npub struct ")
            .replace(", pub ",",\n\tpub ")
            .replace("] pub ","]\n\tpub ")
            .replace("{ pub ","{\n\tpub ")
            .replace(" }","\n}")
        );
        
        
}

And I got this result:

# [derive (Clone , PartialEq , Debug , Deserialize , Serialize)] 
pub struct TestSchemaFetch {
        pub url : String
}

# [derive (Clone , PartialEq , Debug , Deserialize , Serialize)] 
pub struct TestSchemaFetchProcessReplace {
        pub url : String
}

# [derive (Clone , PartialEq , Debug , Deserialize , Serialize)] 
pub struct TestSchemaFetchProcess {
        pub replace : TestSchemaFetchProcessReplace
}

# [derive (Clone , PartialEq , Debug , Deserialize , Serialize)]

# [serde (rename = "Test Schema")] 
pub struct TestSchema {
        pub fetch : TestSchemaFetch ,
        pub method : String ,
        pub process : TestSchemaFetchProcess
}

Shouldn't TestSchemaFetchProcess be TestSchemaProcess as process is not a child of fetch but a neighbor?

Tag 0.7.0 with schemafy command line tool available.

Work was done to create a command line tool but it isn't possible to install this because the most recent version on crates.io is 0.6.0. Tag and publish, please. And/or make the schemafy bin part of the default build. :)

generate: incomplete types due to nested definitions

It looks like the library is producing incomplete code due to missing types in case of nested definitions.

As a short example, let's take the following JSON schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "nestedtest",
  "type": "object",
  "properties": {
  },
  "required": [
    "top"
  ],
  "definitions": {
    "top": {
      "type": "object",
      "properties": {
        "basic": {
          "type": "string"
        },
        "nested": {
          "$ref": "#/definitions/top/definitions/defnested"
        }
      },
      "definitions": {
        "defnested": {
          "type": "object",
          "properties": {
            "append": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

which produces the following struct:

# [ serde ( rename = "top" ) ]
# [ derive ( Clone , PartialEq , Debug , Default , Deserialize , Serialize ) ]
pub struct Top {
    pub basic: Option<String>,
    pub nested: Option<Defnested>,
}

However, the library is not generating any corresponding definition for Defnested.

Enum variants with multiple serde rename

In some cases, enum variants beginning with digits have multiple #[serde(rename=...)] :

This minimal input :

{
    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "properties": {},
    "definitions": {
        "myEnum": {
            "type": "string",
            "enum": [
                "1AHello",
                "2A-Hello",
                "5Hello",
                "AAHello",
                "Hello-Hello"
            ]
        }
    }
}

Will turn into this :

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename = "myEnum")]
pub enum MyEnum {
    #[serde(rename = "1AHello")]
    #[serde(rename = "1Ahello")]
    _1Ahello,
    #[serde(rename = "2A-Hello")]
    #[serde(rename = "2AHello")]
    _2AHello,
    #[serde(rename = "5Hello")]
    _5Hello,
    #[serde(rename = "AAHello")]
    Aahello,
    #[serde(rename = "Hello-Hello")]
    HelloHello,
}
pub type Request = ::std::collections::BTreeMap<String, serde_json::Value>;

1AHello and 2A-Hello both receive an extra "serde rename", but only the first is valid.

Support external refs

It would be great if schemafy could support external refs like these:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "reactions": {
      "type": "array",
      "items": { "$ref": "reaction.json" }
    }
  },
  "id": "file_comment"
}

(As discussed in #2)

How is this crate used?

This crate seems very clever and useful, but I'm having difficulty using it in a practical way.

I've consulted the doctest examples and they elide over many particulars, mostly about how to infer the generated struct names from the schema. Is it possible to examine the generated code?

In the doctest example, the nested.json schema, the code simply uses the Defnested type which is mysterious to me in a number of ways:

  • it's automatically in scope
  • the capitalization differs from the schema
  • it's not at the schema root.

So, presumably one should infer by trial and error the name of the generated types?

How then can I infer the generated types the schema has no title or type at the root?

I'm sorry to be a bit lost here, but if I'm having some difficulties I'd imagine many people would have the same difficulties.

Schema Enums not interpreted correcly

Example schema:
"https://raw.githubusercontent.com/EDSM-NET/EDDN/master/schemas/commodity-v3.0.json"

Problem:
levelType ist defined as:

        "levelType": {
            "enum"          : [0, 1, 2, 3, ""],
            "description"   : "Note: A value of \"\" indicates that the commodity is not normally sold/purchased at this station, but is currently temporarily for sale/purchase"
        }
    }
    root: Commodity
    "src/resources/commodity-v3.0.json");

Now panics with:

  --> src/main.rs:24:1
   |
24 | / schemafy::schemafy!(
25 | |     root: Commodity
26 | |     "src/resources/commodity-v3.0.json");
   | |_________________________________________^
   |
   = help: message: Expected string for enum got `0`

I tried to fix that like that but did not succeed.

--- a/schemafy-0.5.0/src/lib.rs
+++ b/schemafy-0.5.0-bak/src/lib.rs
@@ -500,11 +500,16 @@ impl<'r> Expander<'r> {
                     Value::String(ref v) => {
                         let pascal_case_variant = v.to_pascal_case();
                         let variant_name =
+                        if v == "" {^M
+                            let v = syn::Ident::new("Empty", Span::call_site());^M
+                            quote!(#v)^M
+                        } else {^M
                             rename_keyword("", &pascal_case_variant).unwrap_or_else(|| {
                                 let v = syn::Ident::new(&pascal_case_variant, Span::call_site());
                                 quote!(#v)
-                            });
-                        Some(if pascal_case_variant == *v {
+                            })^M
+                        };^M
+                        Some(if *v != "" && pascal_case_variant == *v {^M
                             variant_name
                         } else {
                             quote! {
@@ -513,6 +518,14 @@ impl<'r> Expander<'r> {
                             }
                         })
                     }
+                    Value::Number(ref v) => {^M
+                        let variant_name = syn::Ident::new(&format!("No{}", v), Span::call_site());^M
+                        let original_name = format!("{}", v);^M
+                        Some(quote! {^M
+                            #[serde(rename = #original_name)]^M
+                            #variant_name^M
+                        })^M
+                    }^M
                     Value::Null => {
                         optional = true;
                         None

This compiles and generates a Commodity struct but not a correct one.

Release new version

Hi @Marwes,

There are several fixes in the master branch I'm interested in.
Unfortunately, the latest version is from Jul 2020.
Any chance you can publish a new release?

Inline object definitions referenced from `allOf` are replicated once per reference

If an object definition is referenced from an allOf array, and that definition includes inline object definitions, those inline definitions are expanded once per allOf reference. Instead, they should be expanded exactly once, and then referenced by name in each parent struct.

For example, consider this schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "top",
  "type": "object",
  "allOf": [
    {
      "$ref": "#/definitions/common"
    },
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }
  ],
  "definitions": {
    "common": {
      "type": "object",
      "properties": {
        "info": {
          "type": "object",
          "properties": {
            "id": {
              "type": "integer"
            }
          }
        }
      }
    }
  }
}

Assuming the root structure is named Top, I'd expect this generated code:

#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct CommonInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
}
#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
#[serde(rename = "common")]
pub struct Common {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<CommonInfo>,
}
#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct Top {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<CommonInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

Here, the Common definition is emitted uselessly (Top doesn't use it) but the object type defined inline by Common is emitted and referenced as CommonInfo.

Schemafy actually produces this code:

#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct CommonInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
}
#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
#[serde(rename = "common")]
pub struct Common {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<CommonInfo>,
}
#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct TopInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i64>,
}
#[derive(Clone, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct Top {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<TopInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

Common and CommonInfo are both emitted but unused. When Top references the ...Info struct, it produces a specialized version only used by Top. If Common were referenced in multiple allOf arrays, the ...Info struct would be replicated once for each reference, each time named after the referencer.

I dug into the code a bit, but this seems hard to fix without a substantial refactor. AFAICT, every Schema would need to carry the name of its parent definition, if any, and Schema has nowhere to put this data (without misusing an existing field).

Build fails if rustfmt is not installed

Building schemafy without rustfmt installed results in an error:

   Compiling schemafy v0.4.5-alpha.0 (/home/anthony/git/schemafy)
error: failed to run custom build command for `schemafy v0.4.5-alpha.0 (/home/anthony/git/schemafy)`
process didn't exit successfully: `/home/anthony/git/schemafy/target/debug/build/schemafy-4f7c26bda0bcdbc9/build-script-build` (exit code: 101)
--- stdout
cargo:rerun-if-changed=src/schema.json

--- stderr
error: 'rustfmt' is not installed for the toolchain '1.34.0-x86_64-unknown-linux-gnu'
To install, run `rustup component add rustfmt --toolchain 1.34.0-x86_64-unknown-linux-gnu`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: StringError("")', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

If it's okay to have the build succeed even if rustfmt fails, then I think that all that needs to be done is remove the ? from the following, and possibly replace it with let _ = format(command, &output) in order to silence the warning from an unused Result.

schemafy/src/lib.rs

Lines 623 to 626 in 1d0ae91

Ok(match self.rustfmt_cmd {
Some(command) => format(command, &output)?,
None => output,
})

Alternatively, we could try to detect whether rustfmt is installed in build.rs and then only run it if it's present. Whichever you'd prefer, I'm happy to open a PR.

use of undeclared type or module `proc_macro`

When trying to install schemafy using cargo install schemafy I see the following error:

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
  --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:83:39
   |
83 |     fn build_tokens(mut self, tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
   |                                       ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
  --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:83:67
   |
83 |     fn build_tokens(mut self, tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
   |                                                                   ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:157:25
    |
157 | pub fn schemafy(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    |                         ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:157:53
    |
157 | pub fn schemafy(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    |                                                     ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:166:27
    |
166 | pub fn regenerate(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    |                           ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error[E0433]: failed to resolve: use of undeclared type or module `proc_macro`
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/schemafy-0.5.1/src/lib.rs:166:55
    |
166 | pub fn regenerate(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    |                                                       ^^^^^^^^^^ use of undeclared type or module `proc_macro`

error: aborting due to 6 previous errors

Simply replacing proc_macro with proc_macro2 in src/lib.rs sadly did not cut it.

Best,
Michel

null generates Value

for the schema

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Hashable Value",
    "id": "https://schema.qhpea.org/hashable-value.json",
    "oneOf": [
        {
            "title": "Null",
            "type": "null"
        },
        {
            "title": "Boolean",
            "type": "boolean"
        },
        {
            "title": "Integer",
            "type": "integer"
        },
        {
            "title": "String",
            "type": "string"
        },
        {
            "title": "Array",
            "type": "array",
            "items": {
                "$ref": "#"
            }
        },
        {
            "title": "Object",
            "type": "object",
            "additionalProperties": {
                "$ref": "#"
            }
        }
    ]
}

it generates

pub type HashableValueNull = Value;

pub enum HashableValue {
    Null(HashableValueNull),
    Boolean(HashableValueBoolean),
    Integer(HashableValueInteger),
    String(HashableValueString),
    Array(HashableValueArray),
    Object(HashableValueObject),
}

this is silly

Support generation from string literals

It would be nice to have an option of passing a string literal to Generator instead of a file path. Think of a case when user's JSON Schema is a part of a bigger JSON file or is a file inside of an archive. I have already implemented this functionality in our fork (see https://github.com/near/schemafy/pull/1/files#diff-bea88ef3ad765bc1058b75944aab0ac87eb4cd96906670cf16bc2bb45a0eb537, ignore other changes in that PR), but happy to prepare this as an upstream PR if you are open to adding this.

Input file path is interpreted relative to Cargo workspace root

The documentation does not state this explicitly, but it looks like the intention was for schemafy!'s path parameter to be relative to the crate root? Unfortunately, in the current incarnation, this path is actually relative to Cargo workspace root, which is pretty confusing when macro fails with "No such file or directory" error.
I think it would be better if the path were relative to the current file, like std::include_str! does.

Output fields unsorted?

In the generated output, the fields inside a struct are sorted alphabetically.

Is it possible to avoid the sorting and instead output the fields as they show up inside the json-input?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.