Skip to main content

origin_kit/
scaffold.rs

1//! `origin new` — a new application from the embedded template.
2//!
3//! What the template gives a product on day one is not a blank window: it is the
4//! architecture contract, logging, error handling, settings, secrets, storage, the
5//! security profile, CI, and a module that is already testable without a desktop
6//! session.
7
8use std::path::{Path, PathBuf};
9
10use origin_xtask::CURRENT_VERSION;
11
12/// Files copied verbatim; everything else is treated as text and substituted.
13const BINARY_EXTENSIONS: &[&str] = &["png", "ico", "icns", "jpg", "jpeg", "webp"];
14
15/// Suffix carried by a template file whose real name would make `cargo package` skip
16/// the directory it lives in — a nested `Cargo.toml` does exactly that, and the
17/// template has three. Stripped when the file is written (ADR-0032).
18const RENAMED_SUFFIX: &str = ".in";
19
20#[derive(Debug)]
21pub struct Options {
22    /// Directory and crate name, e.g. `my-app`.
23    pub slug: String,
24    /// Human-readable product name.
25    pub name: String,
26    /// Reverse-DNS identifier.
27    pub id: String,
28    /// Where to create the project.
29    pub into: PathBuf,
30    /// Point the dependencies at this Origin checkout instead of at crates.io.
31    ///
32    /// Used by Origin's own CI to prove the template still builds against `main`, and
33    /// useful while developing the platform and a product side by side.
34    pub local: Option<PathBuf>,
35}
36
37pub fn run(options: &Options) -> Result<(), String> {
38    validate_options(options)?;
39
40    let target = options.into.join(&options.slug);
41    if target.exists() {
42        return Err(format!("{} already exists", target.display()));
43    }
44
45    let substitutions = substitutions(options);
46    write_template(&target, &substitutions)?;
47
48    if let Some(origin) = &options.local {
49        patch_to_local(&target, origin)?;
50    }
51
52    // Leave a project that already passes its own checks, rather than one whose first
53    // CI run is red.
54    origin_xtask::generate(&target)?;
55
56    println!("created {}", target.display());
57    println!("\nnext:");
58    println!("  cd {}", target.display());
59    println!("  pnpm install");
60    println!("  cargo tauri dev");
61    println!("\nReplace the placeholder icons in src-tauri/icons before shipping.");
62    Ok(())
63}
64
65fn validate_options(options: &Options) -> Result<(), String> {
66    let valid_slug = !options.slug.is_empty()
67        && !options.slug.starts_with('-')
68        && !options.slug.ends_with('-')
69        && !options.slug.contains("--")
70        && options
71            .slug
72            .bytes()
73            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
74    if !valid_slug {
75        return Err(format!(
76            "invalid slug `{}` — use lowercase ASCII letters, digits and single path-safe hyphens",
77            options.slug
78        ));
79    }
80
81    if options.name.trim().is_empty()
82        || options
83            .name
84            .chars()
85            .any(|character| character.is_control() || matches!(character, '"' | '\\'))
86    {
87        return Err(
88            "product name must be non-empty and contain no control characters, quotes or backslashes"
89                .to_owned(),
90        );
91    }
92
93    let labels: Vec<&str> = options.id.split('.').collect();
94    let valid_id = labels.len() >= 2
95        && labels.iter().all(|label| {
96            !label.is_empty()
97                && label
98                    .bytes()
99                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
100                && label
101                    .bytes()
102                    .next()
103                    .is_some_and(|byte| byte.is_ascii_alphanumeric())
104                && label
105                    .bytes()
106                    .next_back()
107                    .is_some_and(|byte| byte.is_ascii_alphanumeric())
108        });
109    if !valid_id {
110        return Err(format!(
111            "invalid product id `{}` — expected a reverse-DNS identifier",
112            options.id
113        ));
114    }
115
116    Ok(())
117}
118
119fn substitutions(options: &Options) -> Vec<(&'static str, String)> {
120    vec![
121        ("__PRODUCT_ID__", options.id.clone()),
122        ("__PRODUCT_NAME__", options.name.clone()),
123        ("__CRATE_NAME_SNAKE__", options.slug.replace('-', "_")),
124        ("__CRATE_NAME__", options.slug.clone()),
125        ("__PACKAGE_NAME__", options.slug.clone()),
126        ("__ORIGIN_VERSION__", CURRENT_VERSION.to_string()),
127        (
128            "__ORIGIN_SEMVER__",
129            format!("{}.{}", CURRENT_VERSION.major, CURRENT_VERSION.minor),
130        ),
131        ("__ORIGIN_NPM__", format!("^{CURRENT_VERSION}")),
132    ]
133}
134
135/// Write every embedded template file into `target`.
136fn write_template(target: &Path, substitutions: &[(&str, String)]) -> Result<(), String> {
137    for (path, contents) in crate::template_files() {
138        let destination = target.join(destination(path));
139
140        if let Some(parent) = destination.parent() {
141            std::fs::create_dir_all(parent)
142                .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
143        }
144
145        let rendered = if is_binary(path) {
146            (*contents).to_vec()
147        } else {
148            let text = std::str::from_utf8(contents)
149                .map_err(|error| format!("template file {path} is not valid UTF-8: {error}"))?;
150            render(text, substitutions).into_bytes()
151        };
152
153        std::fs::write(&destination, rendered)
154            .map_err(|error| format!("cannot write {}: {error}", destination.display()))?;
155    }
156
157    Ok(())
158}
159
160/// The path a template file is written to: its own, without the `.in` suffix.
161fn destination(path: &str) -> &str {
162    path.strip_suffix(RENAMED_SUFFIX).unwrap_or(path)
163}
164
165fn is_binary(path: &str) -> bool {
166    path.rsplit('.')
167        .next()
168        .is_some_and(|extension| BINARY_EXTENSIONS.contains(&extension))
169}
170
171/// Replace every placeholder in a template file.
172///
173/// The substitutions are applied in order, longest placeholder first, so
174/// `__CRATE_NAME_SNAKE__` is not eaten by `__CRATE_NAME__`.
175fn render(contents: &str, substitutions: &[(&str, String)]) -> String {
176    let mut rendered = contents.to_owned();
177    for (placeholder, value) in substitutions {
178        rendered = rendered.replace(placeholder, value);
179    }
180    rendered
181}
182
183/// Point the generated project at a local Origin checkout.
184///
185/// Rewrites the dependencies rather than adding `[patch.crates-io]`: patching only
186/// works only for crates that exist in the registry. Used by Origin's own CI to prove
187/// the template still builds against `main`.
188fn patch_to_local(target: &Path, origin: &Path) -> Result<(), String> {
189    let origin = origin
190        .canonicalize()
191        .map_err(|error| format!("cannot resolve {}: {error}", origin.display()))?;
192
193    rewrite_cargo_dependencies(target, &origin)?;
194    rewrite_npm_dependencies(target, &origin)
195}
196
197/// Where each Origin crate lives inside the repository.
198fn crate_location(name: &str) -> &'static str {
199    match name {
200        "origin-tauri" => "host",
201        "origin-http-reqwest"
202        | "origin-notifications-tauri"
203        | "origin-secrets-system"
204        | "origin-storage-sqlite"
205        | "origin-auth-loopback" => "adapters",
206        _ => "crates",
207    }
208}
209
210fn rewrite_cargo_dependencies(target: &Path, origin: &Path) -> Result<(), String> {
211    let manifest = target.join("Cargo.toml");
212    let contents = std::fs::read_to_string(&manifest)
213        .map_err(|error| format!("cannot read {}: {error}", manifest.display()))?;
214
215    let mut document: toml_edit::DocumentMut = contents
216        .parse()
217        .map_err(|error| format!("{} is not valid TOML: {error}", manifest.display()))?;
218
219    let Some(dependencies) = document
220        .get_mut("workspace")
221        .and_then(|workspace| workspace.get_mut("dependencies"))
222        .and_then(toml_edit::Item::as_table_mut)
223    else {
224        return Err("template Cargo.toml has no [workspace.dependencies]".to_owned());
225    };
226
227    let names: Vec<String> = dependencies
228        .iter()
229        .map(|(name, _)| name.to_owned())
230        .filter(|name| name.starts_with("origin-"))
231        .collect();
232
233    for name in names {
234        let path = origin.join(crate_location(&name)).join(&name);
235        let mut value = toml_edit::InlineTable::new();
236        value.insert("path", path.display().to_string().into());
237        dependencies[&name] = toml_edit::value(value);
238    }
239
240    std::fs::write(&manifest, document.to_string())
241        .map_err(|error| format!("cannot write {}: {error}", manifest.display()))
242}
243
244fn rewrite_npm_dependencies(target: &Path, origin: &Path) -> Result<(), String> {
245    let manifest = target.join("ui").join("package.json");
246    let contents = std::fs::read_to_string(&manifest)
247        .map_err(|error| format!("cannot read {}: {error}", manifest.display()))?;
248
249    let client_release = format!("\"@casoon/origin-client\": \"^{CURRENT_VERSION}\"");
250    let ui_release = format!("\"@casoon/origin-ui\": \"^{CURRENT_VERSION}\"");
251    let rewritten = contents
252        .replace(
253            &client_release,
254            &format!(
255                "\"@casoon/origin-client\": \"link:{}\"",
256                origin.join("frontend").join("client").display()
257            ),
258        )
259        .replace(
260            &ui_release,
261            &format!(
262                "\"@casoon/origin-ui\": \"link:{}\"",
263                origin.join("frontend").join("ui").display()
264            ),
265        );
266
267    std::fs::write(&manifest, rewritten)
268        .map_err(|error| format!("cannot write {}: {error}", manifest.display()))
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn a_renamed_template_file_is_written_under_its_real_name() {
277        assert_eq!(destination("Cargo.toml.in"), "Cargo.toml");
278        assert_eq!(destination("xtask/Cargo.toml.in"), "xtask/Cargo.toml");
279        assert_eq!(destination("app.toml"), "app.toml");
280    }
281
282    #[test]
283    fn the_longer_placeholder_wins() {
284        let options = Options {
285            slug: "my-app".to_owned(),
286            name: "My App".to_owned(),
287            id: "dev.example.myapp".to_owned(),
288            into: PathBuf::from("."),
289            local: None,
290        };
291
292        let rendered = render(
293            "name = \"__CRATE_NAME__\"\nlib = \"__CRATE_NAME_SNAKE___lib\"",
294            &substitutions(&options),
295        );
296
297        assert_eq!(rendered, "name = \"my-app\"\nlib = \"my_app_lib\"");
298    }
299
300    #[test]
301    fn icons_are_not_treated_as_text() {
302        assert!(is_binary("src-tauri/icons/icon.icns"));
303        assert!(is_binary("src-tauri/icons/128x128@2x.png"));
304        assert!(!is_binary("src-tauri/tauri.conf.json"));
305        assert!(!is_binary("Cargo.toml.in"));
306    }
307
308    fn options(slug: &str, id: &str) -> Options {
309        Options {
310            slug: slug.to_owned(),
311            name: "My App".to_owned(),
312            id: id.to_owned(),
313            into: PathBuf::from("."),
314            local: None,
315        }
316    }
317
318    #[test]
319    fn a_slug_that_would_not_survive_a_path_or_a_crate_name_is_refused() {
320        assert!(validate_options(&options("my-app", "dev.example.app")).is_ok());
321        assert!(validate_options(&options("My-App", "dev.example.app")).is_err());
322        assert!(validate_options(&options("../escape", "dev.example.app")).is_err());
323        assert!(validate_options(&options("my--app", "dev.example.app")).is_err());
324        assert!(validate_options(&options("-app", "dev.example.app")).is_err());
325    }
326
327    #[test]
328    fn a_product_id_that_is_not_reverse_dns_is_refused() {
329        assert!(validate_options(&options("my-app", "app")).is_err());
330        assert!(validate_options(&options("my-app", "dev..app")).is_err());
331        assert!(validate_options(&options("my-app", "dev.example.")).is_err());
332    }
333}