Skip to main content

luxid_cli/
naming.rs

1//! Turning one name the user typed into every name the generator needs.
2//!
3//! `luxid make:model User` has to produce `user.rs`, `users`, `UsersController`,
4//! `users_controller.rs`, `StoreUser`, and a handful more. Getting these
5//! consistent is most of what makes generated code feel like it belongs.
6
7/// Every spelling of a model name.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Names {
10    /// `User`
11    pub model: String,
12    /// `user`
13    pub snake: String,
14    /// `users`
15    pub plural: String,
16    /// `UsersController`
17    pub controller: String,
18    /// `users_controller`
19    pub controller_file: String,
20    /// `StoreUser`
21    pub store_request: String,
22    /// `UpdateUser`
23    pub update_request: String,
24    /// `UserPolicy`
25    pub policy: String,
26    /// `UserFactory`
27    pub factory: String,
28    /// `UserSeeder`
29    pub seeder: String,
30}
31
32impl Names {
33    /// Accepts whatever the user typed — `User`, `user`, `user_profile`,
34    /// `UserProfile` — and normalises from there.
35    pub fn new(input: &str) -> Self {
36        let snake = to_snake(input);
37        let model = to_pascal(&snake);
38        let plural = pluralize(&snake);
39
40        Self {
41            controller: format!("{}Controller", to_pascal(&plural)),
42            controller_file: format!("{plural}_controller"),
43            store_request: format!("Store{model}"),
44            update_request: format!("Update{model}"),
45            policy: format!("{model}Policy"),
46            factory: format!("{model}Factory"),
47            seeder: format!("{model}Seeder"),
48            model,
49            snake,
50            plural,
51        }
52    }
53}
54
55/// `UserProfile` / `userProfile` / `user_profile` → `user_profile`.
56pub fn to_snake(input: &str) -> String {
57    let mut out = String::with_capacity(input.len() + 4);
58    let mut previous_lower = false;
59
60    for ch in input.chars() {
61        if ch == '_' || ch == '-' || ch == ' ' {
62            if !out.ends_with('_') && !out.is_empty() {
63                out.push('_');
64            }
65            previous_lower = false;
66            continue;
67        }
68
69        if ch.is_uppercase() {
70            if previous_lower && !out.is_empty() {
71                out.push('_');
72            }
73            out.extend(ch.to_lowercase());
74            previous_lower = false;
75        } else {
76            out.push(ch);
77            previous_lower = true;
78        }
79    }
80
81    out
82}
83
84/// `user_profile` → `UserProfile`.
85pub fn to_pascal(input: &str) -> String {
86    input
87        .split('_')
88        .filter(|part| !part.is_empty())
89        .map(|part| {
90            let mut chars = part.chars();
91            match chars.next() {
92                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
93                None => String::new(),
94            }
95        })
96        .collect()
97}
98
99/// The inverse of the singularisation `#[derive(Model)]` performs, and just as
100/// deliberately simple. Irregular nouns are the user's to override.
101pub fn pluralize(input: &str) -> String {
102    let (head, last) = match input.rsplit_once('_') {
103        Some((head, last)) => (Some(head), last),
104        None => (None, input),
105    };
106
107    let plural = if last.is_empty() {
108        String::new()
109    } else if let Some(stem) = last.strip_suffix('y') {
110        // `category` → `categories`, but `day` → `days`.
111        if stem.chars().last().is_some_and(is_vowel) {
112            format!("{last}s")
113        } else {
114            format!("{stem}ies")
115        }
116    } else if last.ends_with('s')
117        || last.ends_with("sh")
118        || last.ends_with("ch")
119        || last.ends_with('x')
120        || last.ends_with('z')
121    {
122        format!("{last}es")
123    } else {
124        format!("{last}s")
125    };
126
127    match head {
128        Some(head) => format!("{head}_{plural}"),
129        None => plural,
130    }
131}
132
133fn is_vowel(ch: char) -> bool {
134    matches!(ch, 'a' | 'e' | 'i' | 'o' | 'u')
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn snake_cases_every_spelling() {
143        assert_eq!(to_snake("User"), "user");
144        assert_eq!(to_snake("UserProfile"), "user_profile");
145        assert_eq!(to_snake("user_profile"), "user_profile");
146        assert_eq!(to_snake("userProfile"), "user_profile");
147        assert_eq!(to_snake("user-profile"), "user_profile");
148    }
149
150    #[test]
151    fn pascal_cases_from_snake() {
152        assert_eq!(to_pascal("user"), "User");
153        assert_eq!(to_pascal("user_profile"), "UserProfile");
154    }
155
156    #[test]
157    fn pluralizes_the_common_shapes() {
158        assert_eq!(pluralize("user"), "users");
159        assert_eq!(pluralize("post"), "posts");
160        assert_eq!(pluralize("category"), "categories");
161        assert_eq!(
162            pluralize("day"),
163            "days",
164            "a vowel before `y` just takes `s`"
165        );
166        assert_eq!(pluralize("address"), "addresses");
167        assert_eq!(pluralize("branch"), "branches");
168        assert_eq!(pluralize("box"), "boxes");
169        assert_eq!(pluralize("user_profile"), "user_profiles");
170    }
171
172    #[test]
173    fn round_trips_against_the_derive_singularizer() {
174        // `#[derive(Model)]` singularises table names; these must agree or a
175        // generated model reports the wrong name in its 404s.
176        for word in [
177            "users",
178            "posts",
179            "categories",
180            "addresses",
181            "branches",
182            "user_profiles",
183        ] {
184            let singular = crate::naming::tests::singularize_like_derive(word);
185            assert_eq!(pluralize(&singular), word, "round trip failed for {word}");
186        }
187    }
188
189    /// Mirrors the rule in `luxid-macros`, so the two stay in step.
190    fn singularize_like_derive(table: &str) -> String {
191        let (head, last) = match table.rsplit_once('_') {
192            Some((head, last)) => (Some(head), last),
193            None => (None, table),
194        };
195
196        let singular = if let Some(stem) = last.strip_suffix("ies") {
197            format!("{stem}y")
198        } else if last.ends_with("sses") || last.ends_with("shes") || last.ends_with("ches") {
199            last.trim_end_matches("es").to_owned()
200        } else if last.ends_with("ss") {
201            last.to_owned()
202        } else if let Some(stem) = last.strip_suffix('s') {
203            stem.to_owned()
204        } else {
205            last.to_owned()
206        };
207
208        match head {
209            Some(head) => format!("{head}_{singular}"),
210            None => singular,
211        }
212    }
213
214    #[test]
215    fn derives_every_name_from_one_input() {
216        let names = Names::new("UserProfile");
217
218        assert_eq!(names.model, "UserProfile");
219        assert_eq!(names.snake, "user_profile");
220        assert_eq!(names.plural, "user_profiles");
221        assert_eq!(names.controller, "UserProfilesController");
222        assert_eq!(names.controller_file, "user_profiles_controller");
223        assert_eq!(names.store_request, "StoreUserProfile");
224        assert_eq!(names.update_request, "UpdateUserProfile");
225        assert_eq!(names.policy, "UserProfilePolicy");
226    }
227
228    #[test]
229    fn normalises_however_the_user_typed_it() {
230        assert_eq!(Names::new("user"), Names::new("User"));
231        assert_eq!(Names::new("user_profile"), Names::new("UserProfile"));
232    }
233}