Skip to content

Commit 9afa917

Browse files
authored
handle all invalid identifier characters (#37)
1 parent a45d305 commit 9afa917

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

typify-impl/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ readme = "../README.md"
1010

1111
[dependencies]
1212
convert_case = "0.4"
13+
log = "0.4"
1314
proc-macro2 = "1.0"
1415
quote = "1.0"
1516
rustfmt-wrapper = "0.1"
1617
schemars = "0.8"
1718
serde_json = "1.0"
1819
syn = { version = "1.0", features = ["full"] }
1920
thiserror = "1.0"
20-
log = "0.4"
21+
unicode-xid = "0.2"
2122

2223
[dev-dependencies]
2324
expectorate = "1.0"

typify-impl/src/util.rs

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2021 Oxide Computer Company
1+
// Copyright 2022 Oxide Computer Company
22

33
use std::collections::HashSet;
44

@@ -7,6 +7,7 @@ use schemars::schema::{
77
ArrayValidation, InstanceType, Metadata, ObjectValidation, Schema, SchemaObject, SingleOrVec,
88
SubschemaValidation,
99
};
10+
use unicode_xid::UnicodeXID;
1011

1112
use crate::Name;
1213

@@ -463,16 +464,19 @@ pub(crate) fn schema_is_named(schema: &Schema) -> Option<String> {
463464
}
464465

465466
fn sanitize(input: &str, case: Case) -> String {
466-
let out = input
467-
.replace("$", "-")
468-
.replace("@", "-")
469-
.replace("/", "-")
470-
.replace("+", "-plus-")
471-
.replace("'", "")
472-
.to_case(case);
467+
// If every case was special then none of them would be.
468+
let out = match input {
469+
"+1" => "plus1".to_string(),
470+
"-1" => "minus1".to_string(),
471+
_ => input
472+
.replace("'", "")
473+
.replace(|c: char| !c.is_xid_continue(), "-")
474+
.to_case(case),
475+
};
476+
473477
let out = match out.chars().next() {
474478
None => "x".to_case(case),
475-
Some('a'..='z' | 'A'..='Z' | '_') => out,
479+
Some(c) if c.is_xid_start() => out,
476480
Some(_) => format!("_{}", out),
477481
};
478482

@@ -618,8 +622,16 @@ mod tests {
618622
fn test_sanitize() {
619623
assert_eq!(sanitize("type", Case::Snake), "type_");
620624
assert_eq!(sanitize("ref", Case::Snake), "ref_");
621-
assert_eq!(sanitize("+1", Case::Snake), "plus_1");
622-
assert_eq!(sanitize("-1", Case::Snake), "_1");
625+
assert_eq!(sanitize("+1", Case::Snake), "plus1");
626+
assert_eq!(sanitize("-1", Case::Snake), "minus1");
623627
assert_eq!(sanitize("@timestamp", Case::Pascal), "Timestamp");
628+
assert_eq!(sanitize("won't and can't", Case::Pascal), "WontAndCant");
629+
assert_eq!(
630+
sanitize(
631+
"urn:ietf:params:scim:schemas:extension:gluu:2.0:user_",
632+
Case::Camel
633+
),
634+
"urnIetfParamsScimSchemasExtensionGluu20User"
635+
);
624636
}
625637
}

0 commit comments

Comments
 (0)