zorto 0.20.4

The AI-native static site generator (SSG) with executable code blocks
Documentation
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
use clap::{Parser, Subcommand};
use std::path::PathBuf;

use crate::serve;
use crate::skill;
use crate::templates;
use zorto_core::site;

const DEFAULT_OUTPUT_DIR: &str = "public";
const DEFAULT_PREVIEW_PORT: &str = "1111";
const DEFAULT_BIND_ADDRESS: &str = "127.0.0.1";
const DEFAULT_BASE_URL: &str = "http://localhost:1111";
const DEFAULT_SITE_TITLE: &str = "My Site";

#[derive(Parser)]
#[command(
    name = "zorto",
    version,
    about = "The AI-native static site generator (SSG) with executable code blocks"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Site root directory
    #[arg(short, long, default_value = ".")]
    root: PathBuf,

    /// Disable execution of code blocks ({python}, {bash}, {sh})
    #[arg(short = 'N', long)]
    no_exec: bool,

    /// Sandbox boundary for file operations (include shortcode, etc.).
    /// Paths cannot escape this directory. Defaults to --root.
    #[arg(long)]
    sandbox: Option<PathBuf>,

    /// Start the webapp CMS
    #[cfg(feature = "webapp")]
    #[arg(long)]
    webapp: bool,

    /// Start the desktop app
    #[cfg(feature = "app")]
    #[arg(long)]
    app: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Build the site
    Build {
        /// Output directory
        #[arg(short, long, default_value = DEFAULT_OUTPUT_DIR)]
        output: PathBuf,

        /// Include draft pages
        #[arg(long)]
        drafts: bool,

        /// Base URL override
        #[arg(long)]
        base_url: Option<String>,
    },

    /// Start preview server with live reload
    Preview {
        /// Output directory
        #[arg(short, long, default_value = DEFAULT_OUTPUT_DIR)]
        output: PathBuf,

        /// Port number
        #[arg(short, long, default_value = DEFAULT_PREVIEW_PORT)]
        port: u16,

        /// Include draft pages
        #[arg(long)]
        drafts: bool,

        /// Open browser
        #[arg(short = 'O', long)]
        open: bool,

        /// Bind address
        #[arg(long, default_value = DEFAULT_BIND_ADDRESS)]
        interface: String,
    },

    /// Remove output directory and/or cache
    Clean {
        /// Output directory to remove
        #[arg(short, long, default_value = DEFAULT_OUTPUT_DIR)]
        output: PathBuf,

        /// Also clear the code block execution cache (.zorto/cache/)
        #[arg(long)]
        cache: bool,
    },

    /// Initialize a new site
    Init {
        /// Site directory name (defaults to current --root)
        name: Option<String>,

        /// Template to use (default, blog, docs, business)
        #[arg(short, long, default_value = "default")]
        template: String,
    },

    /// Check site for errors without building
    Check {
        /// Include draft pages
        #[arg(long)]
        drafts: bool,
        /// Treat lint warnings as errors
        #[arg(long)]
        deny_warnings: bool,
    },

    /// Install zorto skill files for AI agents
    Skill {
        #[command(subcommand)]
        command: Option<skill::SkillCommands>,
    },
}

/// Run the zorto CLI with the given arguments.
///
/// This is the main entry point, equivalent to calling `zorto` on the command line.
/// Pass `std::env::args()` for normal use, or synthetic args for testing.
pub fn run<I, T>(args: I) -> anyhow::Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let cli = Cli::parse_from(args);

    // Handle skill command before resolving root/sandbox (no site context needed)
    if matches!(&cli.command, Some(Commands::Skill { .. })) {
        let Some(Commands::Skill { command }) = cli.command else {
            unreachable!();
        };
        return skill::handle_skill(command);
    }

    let root = std::fs::canonicalize(&cli.root)?;
    let sandbox = resolve_sandbox(&cli.sandbox)?;

    #[cfg(feature = "webapp")]
    if cli.webapp {
        let output = resolve_output(&root, std::path::PathBuf::from(DEFAULT_OUTPUT_DIR));
        return zorto_webapp::run_webapp(&root, &output, sandbox.as_deref());
    }

    #[cfg(feature = "app")]
    if cli.app {
        return zorto_app::run_app(&root);
    }

    let Some(command) = cli.command else {
        Cli::parse_from(["zorto", "--help"]);
        unreachable!();
    };

    match command {
        Commands::Build {
            output,
            drafts,
            base_url,
        } => {
            let output = resolve_output(&root, output);
            let mut site = site::Site::load(&root, &output, drafts)?;
            site.no_exec = cli.no_exec;
            site.sandbox = sandbox;
            if let Some(url) = base_url {
                site.set_base_url(url);
            }
            site.build()?;
            println!("Site built to {}", output.display());
        }
        Commands::Preview {
            output,
            port,
            drafts,
            open,
            interface,
        } => {
            let output = resolve_output(&root, output);
            let cfg = serve::ServeConfig {
                root: &root,
                output_dir: &output,
                drafts,
                no_exec: cli.no_exec,
                sandbox: sandbox.as_deref(),
                interface: &interface,
                port,
                open_browser: open,
            };
            let rt = tokio::runtime::Runtime::new()?;
            rt.block_on(serve::serve(&cfg))?;
        }
        Commands::Clean { output, cache } => {
            let output = resolve_output(&root, output);
            if output.exists() {
                std::fs::remove_dir_all(&output)?;
                println!("Removed {}", output.display());
            }
            if cache {
                zorto_core::cache::clear_cache(&root)?;
                println!("Cleared code block cache");
            }
        }
        Commands::Init { name, template } => {
            // Detect if we should launch the interactive flow:
            // - no explicit name was given
            // - the default template value wasn't overridden by the user
            // - stdin is a TTY
            let is_interactive = name.is_none() && template == "default" && atty_stdin();

            if is_interactive {
                interactive_init(&root)?;
            } else {
                let target = match name {
                    Some(n) => root.join(n),
                    None => root.clone(),
                };
                init_site(&target, &template)?;
            }
        }
        Commands::Check {
            drafts,
            deny_warnings,
        } => {
            let output = root.join(DEFAULT_OUTPUT_DIR);
            let mut site = site::Site::load(&root, &output, drafts)?;
            site.no_exec = cli.no_exec;
            site.sandbox = sandbox;
            site.check(deny_warnings)?;
            println!("Site check passed.");
        }
        Commands::Skill { .. } => unreachable!("handled above"),
    }

    Ok(())
}

/// Resolve an output path relative to the site root.
fn resolve_output(root: &std::path::Path, output: PathBuf) -> PathBuf {
    if output.is_relative() {
        root.join(output)
    } else {
        output
    }
}

/// Canonicalize the sandbox path, returning an error if it doesn't exist.
fn resolve_sandbox(sandbox: &Option<PathBuf>) -> anyhow::Result<Option<PathBuf>> {
    match sandbox {
        Some(p) => {
            let canonical = std::fs::canonicalize(p)
                .map_err(|e| anyhow::anyhow!("cannot resolve sandbox path {}: {e}", p.display()))?;
            Ok(Some(canonical))
        }
        None => Ok(None),
    }
}

/// Check if stdin is a TTY.
fn atty_stdin() -> bool {
    use std::io::IsTerminal;
    std::io::stdin().is_terminal()
}

fn init_site(target: &std::path::Path, template: &str) -> anyhow::Result<()> {
    if target.join("config.toml").exists() {
        anyhow::bail!(
            "A zorto site already exists in {} — run `zorto preview` to work with it",
            target.display()
        );
    }
    if target.join("website").join("config.toml").exists() {
        anyhow::bail!(
            "A zorto site already exists in {}/website/ — run `zorto --root website preview` to work with it",
            target.display()
        );
    }

    templates::write_template(target, template)?;

    println!(
        "Initialized new site at {} (template: {template})",
        target.display()
    );
    Ok(())
}

/// Interactive init flow using dialoguer prompts.
fn interactive_init(root: &std::path::Path) -> anyhow::Result<()> {
    use dialoguer::{Input, Select};

    println!();
    println!("  Welcome to Zorto!");
    println!("  Let's create your new site.");
    println!();

    // 1. Site name / directory
    let name: String = Input::new()
        .with_prompt("  Site directory name")
        .default(".".to_string())
        .interact_text()?;

    let target = if name == "." {
        root.to_path_buf()
    } else {
        root.join(&name)
    };

    // Check for existing site in target dir or website/ subdir
    if target.join("config.toml").exists() {
        anyhow::bail!(
            "A zorto site already exists in {} — run `zorto preview` to work with it",
            target.display()
        );
    }
    if target.join("website").join("config.toml").exists() {
        anyhow::bail!(
            "A zorto site already exists in {}/website/ — run `zorto --root website preview` to work with it",
            target.display()
        );
    }

    // 2. Template selection
    let template_labels: Vec<String> = templates::TEMPLATES
        .iter()
        .map(|t| format!("{:<12} {}", t.name, t.description))
        .collect();

    let template_idx = Select::new()
        .with_prompt("  Template")
        .items(&template_labels)
        .default(0)
        .interact()?;
    let template_name = templates::TEMPLATES[template_idx].name;

    // 3. Theme selection
    let available_themes = zorto_core::themes::Theme::available();
    let theme_choice = if available_themes.is_empty() {
        None
    } else {
        let theme_descriptions: Vec<(&str, &str)> = available_themes
            .iter()
            .map(|name| {
                let desc = match *name {
                    "zorto" => "Blue/green with animations (Zorto brand)",
                    "dkdc" => "Violet/cyan with animations (dkdc brand)",
                    "default" => "Clean blue, no animations",
                    "ember" => "Warm orange/amber",
                    "forest" => "Natural green/lime",
                    "ocean" => "Calm teal/blue",
                    "rose" => "Soft pink/purple",
                    "slate" => "Minimal monochrome",
                    "midnight" => "Navy/silver corporate",
                    "sunset" => "Bold red/orange",
                    "mint" => "Modern green/cyan",
                    "plum" => "Rich purple/magenta",
                    "sand" => "Warm neutral/earth tones",
                    "arctic" => "Cool blue/white",
                    "lime" => "Bright green/yellow",
                    "charcoal" => "Dark grey/silver",
                    _ => "",
                };
                (*name, desc)
            })
            .collect();

        let theme_labels: Vec<String> = theme_descriptions
            .iter()
            .map(|(name, desc)| format!("{:<12} {}", name, desc))
            .collect();

        let default_idx = available_themes
            .iter()
            .position(|n| *n == "default")
            .unwrap_or(0);

        let theme_idx = Select::new()
            .with_prompt("  Theme")
            .items(&theme_labels)
            .default(default_idx)
            .interact()?;

        Some(available_themes[theme_idx])
    };

    // 4. Configuration
    let site_title: String = Input::new()
        .with_prompt("  Site title")
        .default(DEFAULT_SITE_TITLE.to_string())
        .interact_text()?;

    let author: String = Input::new()
        .with_prompt("  Author name")
        .default(String::new())
        .allow_empty(true)
        .interact_text()?;

    let base_url: String = Input::new()
        .with_prompt("  Base URL")
        .default(DEFAULT_BASE_URL.to_string())
        .interact_text()?;

    // 5. Create the site
    println!();
    templates::write_template(&target, template_name)?;

    // Customize the generated config with user values
    templates::customize_config(
        &target,
        &site_title,
        &base_url,
        theme_choice,
        if author.is_empty() {
            None
        } else {
            Some(author.as_str())
        },
    )?;

    // 6. Next steps
    println!("  Site created at {}", target.display());
    println!();
    if name != "." {
        println!("  Next steps:");
        println!("    cd {name} && zorto preview --open");
    } else {
        println!("  Next steps:");
        println!("    zorto preview --open");
    }
    println!();

    Ok(())
}

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

    #[test]
    fn parse_skill_install() {
        let cli = Cli::parse_from(["zorto", "skill", "install", "--target", "/tmp/skills"]);
        assert!(matches!(cli.command, Some(Commands::Skill { .. })));
    }

    #[test]
    fn parse_skill_install_all() {
        let cli = Cli::parse_from([
            "zorto",
            "skill",
            "install",
            "--target",
            "/tmp/skills",
            "--all",
        ]);
        assert!(matches!(cli.command, Some(Commands::Skill { .. })));
    }
}