create-axonyx 0.1.2

Scaffold a new Axonyx app
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
mod template;

use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use axonyx_core::ax_backend_codegen_prelude::compile_backend_sources_to_module;
use clap::{Parser, ValueEnum};

const DEFAULT_RUNTIME_GIT_URL: &str = "https://github.com/vladanPro/axonyx-runtime";
const DEFAULT_RUNTIME_PACKAGE: &str = "axonyx-runtime";
const DEFAULT_RUNTIME_VERSION: &str = "0.1.0";
const DEFAULT_UI_PACKAGE: &str = "axonyx-ui";
const DEFAULT_UI_VERSION: &str = "0.0.32";

#[derive(Debug, Parser)]
#[command(name = "create-axonyx")]
#[command(about = "Create a new Axonyx app", version)]
struct Cli {
    /// Name of the app directory to create
    project_name: String,

    /// Skip prompts and accept defaults
    #[arg(long)]
    yes: bool,

    /// Overwrite target directory if it exists
    #[arg(long)]
    force: bool,

    /// Initialize a git repository in the generated app
    #[arg(long)]
    git: bool,

    /// Starter template to use for the generated app
    #[arg(long, value_enum, default_value_t = AppTemplate::Minimal)]
    template: AppTemplate,

    /// Where the generated app should load axonyx-runtime from
    #[arg(long, value_enum, default_value_t = RuntimeSource::Registry)]
    runtime_source: RuntimeSource,

    /// Git URL used when --runtime-source git is selected
    #[arg(long, default_value = DEFAULT_RUNTIME_GIT_URL)]
    runtime_git_url: String,

    /// Package name used when --runtime-source registry is selected
    #[arg(long, default_value = DEFAULT_RUNTIME_PACKAGE)]
    runtime_package: String,

    /// Package version used when --runtime-source registry is selected
    #[arg(long, default_value = DEFAULT_RUNTIME_VERSION)]
    runtime_version: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum RuntimeSource {
    Path,
    Git,
    Registry,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum AppTemplate {
    Minimal,
    Site,
    Docs,
}

fn main() {
    if let Err(err) = run() {
        print_create_error(&err);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();
    validate_project_name(&cli.project_name)?;

    let target_dir = std::env::current_dir()
        .context("unable to resolve current directory")?
        .join(&cli.project_name);

    if target_dir.exists() && !cli.force {
        bail!(
            "target directory '{}' already exists (use --force to overwrite)",
            target_dir.display()
        );
    }

    if target_dir.exists() && cli.force {
        fs::remove_dir_all(&target_dir).with_context(|| {
            format!(
                "failed to remove existing directory '{}'",
                target_dir.display()
            )
        })?;
    }

    if !cli.yes {
        println!(
            "This will create a new Axonyx app in '{}'.",
            target_dir.display()
        );
        if !confirm("Continue? [y/N]: ")? {
            println!("Canceled.");
            return Ok(());
        }
    }

    create_app(&target_dir, &cli)?;

    if cli.git {
        init_git(&target_dir)?;
    }

    println!();
    println!("Success! Axonyx app created at {}", target_dir.display());
    println!("Next steps:");
    println!("  cd {}", cli.project_name);
    println!("  cargo ax check");
    println!("  cargo ax doctor");
    println!("  cargo ax build --clean");
    println!("  cargo ax run dev");
    println!("Template: {:?}", cli.template);
    Ok(())
}

fn validate_project_name(name: &str) -> Result<()> {
    if name.trim().is_empty() {
        bail!("project name cannot be empty");
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        bail!("project name can contain only letters, digits, '-' and '_'");
    }
    Ok(())
}

fn print_create_error(error: &anyhow::Error) {
    eprintln!("Axonyx could not create this app.");
    eprintln!();
    eprintln!("Problem:");
    eprintln!("  {}", error);

    if let Some(hint) = hint_for_create_error(error) {
        eprintln!();
        eprintln!("Hint:");
        eprintln!("  {hint}");
    }

    let mut chain = error.chain();
    let _ = chain.next();
    let details = chain.map(ToString::to_string).collect::<Vec<_>>();
    if !details.is_empty() {
        eprintln!();
        eprintln!("Details:");
        for detail in details {
            eprintln!("  - {detail}");
        }
    }
}

fn hint_for_create_error(error: &anyhow::Error) -> Option<&'static str> {
    let combined = error
        .chain()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join("\n");

    if combined.contains("project name") {
        return Some("Use a simple folder name such as `my-site`, `docs`, or `hello-axonyx`.");
    }

    if combined.contains("target directory") && combined.contains("already exists") {
        return Some("Choose a new project name or pass `--force` if you intentionally want to replace the folder.");
    }

    if combined.contains("could not find axonyx-runtime workspace") {
        return Some("Use `--runtime-source git`, or initialize the framework submodule with `git submodule update --init --recursive`.");
    }

    if combined.contains("failed to clone axonyx-ui")
        || combined.contains("failed to launch git while vendoring axonyx-ui")
    {
        return Some("Set AXONYX_UI_SOURCE to a local axonyx-ui checkout, or check that Git can access the axonyx-ui repository.");
    }

    if combined.contains("failed to compile initial backend .ax sources") {
        return Some("The template backend sources did not compile; this is likely a framework bug. Run the core smoke script to reproduce it.");
    }

    None
}

fn create_app(target_dir: &PathBuf, cli: &Cli) -> Result<()> {
    let runtime_dependency = runtime_dependency_spec(cli)?;
    let runtime_source_note = runtime_source_note(cli);
    let template = match cli.template {
        AppTemplate::Minimal => template::AppTemplate::Minimal,
        AppTemplate::Site => template::AppTemplate::Site,
        AppTemplate::Docs => template::AppTemplate::Docs,
    };

    fs::create_dir_all(target_dir).with_context(|| {
        format!(
            "failed to create project directory '{}'",
            target_dir.display()
        )
    })?;

    for file in template::template_files(
        template,
        &cli.project_name,
        &runtime_dependency,
        &runtime_source_note,
    ) {
        let full_path = target_dir.join(file.relative_path);
        if let Some(parent) = full_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory '{}'", parent.display()))?;
        }
        fs::write(&full_path, file.contents)
            .with_context(|| format!("failed to write '{}'", full_path.display()))?;
    }

    if matches!(
        template,
        template::AppTemplate::Site | template::AppTemplate::Docs
    ) {
        install_template_ui(target_dir)?;
    }

    compile_initial_backend(target_dir)?;

    Ok(())
}

fn install_template_ui(target_dir: &Path) -> Result<()> {
    ensure_ui_cargo_dependency(target_dir)?;
    Ok(())
}

fn ensure_ui_cargo_dependency(target_dir: &Path) -> Result<()> {
    let cargo_toml = target_dir.join("Cargo.toml");
    if !cargo_toml.exists() {
        return Ok(());
    }

    let source = fs::read_to_string(&cargo_toml)
        .with_context(|| format!("failed to read '{}'", cargo_toml.display()))?;
    if source.contains("[dependencies.axonyx-ui]") || source.contains("\naxonyx-ui =") {
        return Ok(());
    }

    let mut updated = source;
    if !updated.ends_with('\n') {
        updated.push('\n');
    }
    updated.push_str(&format!(
        "\n{} = \"{}\"\n",
        DEFAULT_UI_PACKAGE, DEFAULT_UI_VERSION
    ));

    fs::write(&cargo_toml, updated)
        .with_context(|| format!("failed to write '{}'", cargo_toml.display()))?;
    Ok(())
}

fn compile_initial_backend(target_dir: &PathBuf) -> Result<()> {
    let mut sources = Vec::new();

    collect_backend_sources(target_dir, &mut sources)?;
    if sources.is_empty() {
        return Ok(());
    }

    let source_refs = sources
        .iter()
        .map(|(name, source)| (name.as_str(), source.as_str()))
        .collect::<Vec<_>>();

    let module = compile_backend_sources_to_module(&source_refs)
        .with_context(|| "failed to compile initial backend .ax sources")?;

    let generated_backend = target_dir.join("src").join("generated").join("backend.rs");
    fs::write(&generated_backend, module).with_context(|| {
        format!(
            "failed to write generated backend module '{}'",
            generated_backend.display()
        )
    })?;

    Ok(())
}

fn collect_backend_sources(target_dir: &PathBuf, out: &mut Vec<(String, String)>) -> Result<()> {
    let routes_root = target_dir.join("routes");
    let jobs_root = target_dir.join("jobs");
    let app_root = target_dir.join("app");

    collect_backend_sources_in_dir(&routes_root, &routes_root, out, true)?;
    collect_backend_sources_in_dir(&jobs_root, &jobs_root, out, true)?;
    collect_named_backend_files(&app_root, &app_root, out, &["loader.ax", "actions.ax"])?;
    Ok(())
}

fn collect_backend_sources_in_dir(
    root: &PathBuf,
    dir: &PathBuf,
    out: &mut Vec<(String, String)>,
    recurse: bool,
) -> Result<()> {
    if !dir.exists() {
        return Ok(());
    }

    for entry in fs::read_dir(dir)
        .with_context(|| format!("failed to read directory '{}'", dir.display()))?
    {
        let entry =
            entry.with_context(|| format!("failed to read entry in '{}'", dir.display()))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .with_context(|| format!("failed to inspect '{}'", path.display()))?;

        if file_type.is_dir() && recurse {
            collect_backend_sources_in_dir(root, &path, out, true)?;
            continue;
        }

        if file_type.is_file() && path.extension().and_then(|ext| ext.to_str()) == Some("ax") {
            let source = fs::read_to_string(&path)
                .with_context(|| format!("failed to read backend source '{}'", path.display()))?;
            let name = path
                .strip_prefix(root)
                .unwrap_or(&path)
                .to_string_lossy()
                .replace('\\', "/");
            out.push((name, source));
        }
    }

    Ok(())
}

fn collect_named_backend_files(
    root: &PathBuf,
    dir: &PathBuf,
    out: &mut Vec<(String, String)>,
    names: &[&str],
) -> Result<()> {
    if !dir.exists() {
        return Ok(());
    }

    for entry in fs::read_dir(dir)
        .with_context(|| format!("failed to read directory '{}'", dir.display()))?
    {
        let entry =
            entry.with_context(|| format!("failed to read entry in '{}'", dir.display()))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .with_context(|| format!("failed to inspect '{}'", path.display()))?;

        if file_type.is_dir() {
            collect_named_backend_files(root, &path, out, names)?;
            continue;
        }

        let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };

        if !names.contains(&file_name) {
            continue;
        }

        let source = fs::read_to_string(&path)
            .with_context(|| format!("failed to read backend source '{}'", path.display()))?;
        let name = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        out.push((name, source));
    }

    Ok(())
}

fn init_git(target_dir: &PathBuf) -> Result<()> {
    let status = std::process::Command::new("git")
        .arg("init")
        .current_dir(target_dir)
        .status()
        .context("failed to execute git init")?;

    if !status.success() {
        bail!("git init failed with status {status}");
    }

    Ok(())
}

fn runtime_dependency_spec(cli: &Cli) -> Result<String> {
    match cli.runtime_source {
        RuntimeSource::Path => {
            let runtime_crate = runtime_workspace_root()?
                .join("crates")
                .join("axonyx-runtime")
                .canonicalize()
                .context("failed to resolve axonyx-runtime crate path")?;

            let runtime_path = cargo_toml_path(&runtime_crate);
            Ok(format!("axonyx-runtime = {{ path = \"{runtime_path}\" }}"))
        }
        RuntimeSource::Git => Ok(format!(
            "axonyx-runtime = {{ git = \"{}\" }}",
            cli.runtime_git_url.trim()
        )),
        RuntimeSource::Registry => Ok(format!(
            "{} = \"{}\"",
            cli.runtime_package.trim(),
            cli.runtime_version.trim()
        )),
    }
}

fn runtime_source_note(cli: &Cli) -> String {
    match cli.runtime_source {
        RuntimeSource::Path => "This scaffold links against the local `axonyx-runtime` workspace path. Use this mode when contributing to Axonyx itself, typically through the `vendor/axonyx-runtime` git submodule in the framework repo.".to_string(),
        RuntimeSource::Git => format!(
            "This scaffold links against the shared `axonyx-runtime` Git repository at `{}`. Use this mode when testing an unreleased runtime branch.",
            cli.runtime_git_url.trim()
        ),
        RuntimeSource::Registry => format!(
            "This scaffold uses the published crates.io runtime package `{}` at version `{}`.",
            cli.runtime_package.trim(),
            cli.runtime_version.trim()
        ),
    }
}

fn workspace_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("create-axonyx should live under <workspace>/crates/create-axonyx")
        .to_path_buf()
}

fn runtime_workspace_root() -> Result<PathBuf> {
    let workspace = workspace_root();
    let submodule = workspace.join("vendor").join("axonyx-runtime");
    if submodule.exists() {
        return Ok(submodule);
    }

    let sibling = workspace.parent().map_or_else(
        || PathBuf::from("axonyx-runtime"),
        |parent| parent.join("axonyx-runtime"),
    );
    if sibling.exists() {
        return Ok(sibling);
    }

    bail!(
        "could not find axonyx-runtime workspace; expected '{}' or '{}'",
        submodule.display(),
        sibling.display()
    );
}

fn cargo_toml_path(path: &Path) -> String {
    let normalized = path.to_string_lossy().replace('\\', "/");
    normalized
        .strip_prefix("//?/")
        .unwrap_or(&normalized)
        .to_string()
}

fn confirm(prompt: &str) -> Result<bool> {
    print!("{prompt}");
    io::stdout().flush().context("failed to flush stdout")?;

    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .context("failed to read confirmation input")?;

    let normalized = line.trim().to_ascii_lowercase();
    Ok(normalized == "y" || normalized == "yes")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_temp_dir(label: &str) -> PathBuf {
        let unique = format!(
            "axonyx-create-{}-{}",
            label,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should move forward")
                .as_nanos()
        );
        let dir = std::env::temp_dir().join(unique);
        fs::create_dir_all(&dir).expect("temp dir should create");
        dir
    }

    #[test]
    fn site_template_enables_ui_module() {
        let files = template::template_files(
            template::AppTemplate::Site,
            "demo-site",
            "axonyx-runtime = { git = \"https://example.com/runtime\" }",
            "runtime note",
        );

        let axonyx_toml = files
            .iter()
            .find(|file| file.relative_path == "Axonyx.toml")
            .expect("Axonyx.toml should exist");

        assert!(axonyx_toml.contents.contains("enabled = [\"ui\"]"));
    }

    #[test]
    fn create_error_hint_detects_existing_target_directory() {
        let error = anyhow::anyhow!(
            "target directory 'demo-site' already exists (use --force to overwrite)"
        );

        assert_eq!(
            hint_for_create_error(&error),
            Some("Choose a new project name or pass `--force` if you intentionally want to replace the folder.")
        );
    }

    #[test]
    fn create_error_hint_detects_missing_local_runtime() {
        let error = anyhow::anyhow!("could not find axonyx-runtime workspace");

        assert_eq!(
            hint_for_create_error(&error),
            Some("Use `--runtime-source git`, or initialize the framework submodule with `git submodule update --init --recursive`.")
        );
    }

    #[test]
    fn create_site_template_adds_registry_ui_and_scaffolds_foundry_layout() {
        let workspace = make_temp_dir("site-template");
        let target_dir = workspace.join("demo-site");

        let cli = Cli {
            project_name: "demo-site".to_string(),
            yes: true,
            force: false,
            git: false,
            template: AppTemplate::Site,
            runtime_source: RuntimeSource::Registry,
            runtime_git_url: DEFAULT_RUNTIME_GIT_URL.to_string(),
            runtime_package: DEFAULT_RUNTIME_PACKAGE.to_string(),
            runtime_version: DEFAULT_RUNTIME_VERSION.to_string(),
        };

        create_app(&target_dir, &cli).expect("site template should scaffold");

        assert!(!target_dir.join("vendor/axonyx-ui").exists());
        assert!(!target_dir.join("public/css/axonyx-ui").exists());

        let layout =
            fs::read_to_string(target_dir.join("app/layout.ax")).expect("layout should read");
        assert!(layout.contains("@axonyx/ui/foundry/SiteShell.ax"));
        assert!(layout.contains("<Theme>silver</Theme>"));
        assert!(layout.contains("/_ax/pkg/axonyx-ui/index.css"));

        let cargo_toml =
            fs::read_to_string(target_dir.join("Cargo.toml")).expect("cargo manifest should read");
        assert!(cargo_toml.contains("axonyx-runtime = \"0.1.0\""));
        assert!(cargo_toml.contains("axonyx-ui = \"0.0.32\""));

        let page = fs::read_to_string(target_dir.join("app/page.ax")).expect("page should read");
        assert!(page.contains("@axonyx/ui/foundry/SectionCard.ax"));

        let axonyx_toml =
            fs::read_to_string(target_dir.join("Axonyx.toml")).expect("config should read");
        assert!(axonyx_toml.contains("enabled = [\"ui\"]"));
        assert!(!axonyx_toml.contains("[package_overrides]"));

        let posts_page = fs::read_to_string(target_dir.join("app/posts/page.ax"))
            .expect("posts page should read");
        assert!(posts_page.contains("<If when={load PostsList}>"));
        assert!(posts_page.contains("<Each items={load PostsList} as=\"post\">"));
        assert!(posts_page.contains("<Else>"));

        fs::remove_dir_all(workspace).expect("temp dir should clean up");
    }
}