glacier-web-cli 0.1.0

Command-line tool for creating and running Glacier applications.
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
//! The `glacier` command-line tool.

mod auth;
mod diagnostics;
mod dialect;
mod generate;
mod lsp;
mod scaffold;
mod server;

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command as Process, ExitCode};

use clap::{Parser, Subcommand, ValueEnum};

#[derive(Parser)]
#[command(name = "glacier", version, about = "The Glacier web framework")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create a new Glacier application
    New {
        /// Name of the application (also its directory)
        name: String,
        /// Path to a local `glacier` crate (crates/glacier in a checkout),
        /// instead of the published `glacier-web`
        #[arg(long)]
        glacier_path: Option<PathBuf>,
        /// The language for generated controllers
        #[arg(long, value_enum, default_value_t = Dialect::Glacier)]
        dialect: Dialect,
        /// A JSON API: no views, assets or CSRF, errors as JSON; the
        /// generators then make JSON controllers
        #[arg(long)]
        api: bool,
    },
    /// Run the app, rebuilding and restarting it when files change
    #[command(alias = "s")]
    Server {
        /// Run once without watching for changes
        #[arg(long)]
        no_watch: bool,
        /// Extra arguments for cargo, e.g. --release
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Print the application's routes
    Routes,
    /// Compile .glacier files, then build (errors point at .glacier lines)
    #[command(alias = "b")]
    Build {
        /// Extra arguments for cargo, e.g. --release
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Run the app's tests (failures point at .glacier lines)
    #[command(alias = "t")]
    Test {
        /// Extra arguments for cargo test, e.g. a name filter
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Compile .glacier files into the hidden .glacier/ folder (build.rs does this too)
    Compile,
    /// Language server for .glacier files (proxies rust-analyzer)
    Lsp,
    /// Format .glacier files (all of them under src/, or the paths given)
    Fmt {
        /// Report unformatted files and fail instead of rewriting them
        #[arg(long)]
        check: bool,
        /// Files to format; defaults to every .glacier file under src/
        paths: Vec<PathBuf>,
    },
    /// Manage the database
    #[command(subcommand)]
    Db(DbCommand),
    /// Generate code
    #[command(subcommand, alias = "g")]
    Generate(GenerateCommand),
    /// Print a new random value for `secret_key_base`
    Secret,
}

#[derive(Subcommand)]
enum DbCommand {
    /// Apply pending migrations
    Migrate,
    /// Revert the most recent migrations
    Rollback {
        /// How many migrations to revert
        #[arg(long, default_value_t = 1)]
        steps: usize,
    },
    /// List migrations and whether each is applied
    Status,
}

#[derive(Subcommand)]
enum GenerateCommand {
    /// A migration in src/migrations; `create_<table>` names start a table
    Migration {
        /// snake_case description, e.g. create_posts or add_slug_to_posts
        name: String,
    },
    /// A model and its migration, with tests (and a factory)
    Model {
        /// The model name, e.g. Post or BlogPost
        name: String,
        /// Fields as name:type, as for `scaffold`
        #[arg(required = true)]
        fields: Vec<String>,
        /// The language for the tests
        #[arg(long, value_enum, default_value_t = Dialect::Glacier)]
        dialect: Dialect,
    },
    /// A controller with actions, their views and routes, and tests
    Controller {
        /// The controller name, e.g. Pages or Reports
        name: String,
        /// Action names, e.g. about contact
        #[arg(required = true)]
        actions: Vec<String>,
        /// The language for the controller and its tests
        #[arg(long, value_enum, default_value_t = Dialect::Glacier)]
        dialect: Dialect,
    },
    /// A policy: who may do what with a model, for `authorize`
    Policy {
        /// The model name, e.g. Post
        name: String,
    },
    /// A background job, run by the app's workers
    Job {
        /// The job name, e.g. SendReport
        name: String,
        /// Its arguments as name:type, as for `scaffold`
        fields: Vec<String>,
    },
    /// Sign up, sign in and sign out: User and Session models, controllers,
    /// views and tests, as code in the app
    Authentication {
        /// JSON endpoints and bearer tokens instead of pages and cookies
        #[arg(long)]
        api: bool,
    },
    /// A model, migration, CRUD controller, views and routes, with tests
    Scaffold {
        /// The model name, e.g. Post or BlogPost
        name: String,
        /// Fields as name:type, e.g. title:string body:text:optional published:boolean
        /// (types: string, text, integer, bigint, float, boolean, references;
        /// `:optional` makes string/text nullable)
        #[arg(required = true)]
        fields: Vec<String>,
        /// The language for the controller
        #[arg(long, value_enum, default_value_t = Dialect::Glacier)]
        dialect: Dialect,
    },
}

/// The language generated controllers are written in.
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Dialect {
    /// `.glacier`, compiled to Rust at build time
    Glacier,
    /// Plain Rust
    Rust,
}

/// Files of every new application: (path, template).
const APP_TEMPLATE: &[(&str, &str)] = &[
    ("Cargo.toml", include_str!("../templates/Cargo.toml.tmpl")),
    (".gitignore", include_str!("../templates/gitignore.tmpl")),
    ("build.rs", include_str!("../templates/build.rs.tmpl")),
    ("src/main.rs", include_str!("../templates/main.rs.tmpl")),
    (
        "src/migrations/mod.rs",
        include_str!("../templates/migrations_mod.rs.tmpl"),
    ),
    (
        "config/default.toml",
        include_str!("../templates/config_default.toml.tmpl"),
    ),
    (
        "config/development.toml",
        include_str!("../templates/config_development.toml.tmpl"),
    ),
    (
        "config/test.toml",
        include_str!("../templates/config_test.toml.tmpl"),
    ),
    (
        "config/production.toml",
        include_str!("../templates/config_production.toml.tmpl"),
    ),
];

/// Files of an app with pages: views, a stylesheet, CSRF protection.
const BROWSER_TEMPLATE: &[(&str, &str)] = &[
    ("src/lib.rs", include_str!("../templates/lib.rs.tmpl")),
    ("src/routes.rs", include_str!("../templates/routes.rs.tmpl")),
    ("src/views.rs", include_str!("../templates/views.rs.tmpl")),
    (
        "src/views/layouts/app.html",
        include_str!("../templates/layout.html.tmpl"),
    ),
    (
        "src/views/pages/home.html",
        include_str!("../templates/home.html.tmpl"),
    ),
    ("public/app.css", include_str!("../templates/app.css.tmpl")),
];

/// Files of a JSON API (`glacier new --api`).
const API_TEMPLATE: &[(&str, &str)] = &[
    ("src/lib.rs", include_str!("../templates/api/lib.rs.tmpl")),
    (
        "src/routes.rs",
        include_str!("../templates/api/routes.rs.tmpl"),
    ),
];

fn main() -> ExitCode {
    let result = match Cli::parse().command {
        Command::New {
            name,
            glacier_path,
            dialect,
            api,
        } => new_app(&name, glacier_path, dialect, api),
        Command::Server { no_watch, args } => server::run(&args, !no_watch),
        Command::Routes => task("routes", &[]),
        Command::Build { args } => {
            if dialect::cargo("build", &args) {
                Ok(())
            } else {
                Err("build failed".into())
            }
        }
        Command::Test { args } => {
            if dialect::cargo("test", &args) {
                Ok(())
            } else {
                Err("tests failed".into())
            }
        }
        Command::Lsp => lsp::run(),
        Command::Fmt { check, paths } => dialect::format(&paths, check),
        Command::Compile => dialect::compile_all().map(|written| {
            let total = dialect::sources().len();
            println!("compiled {total} .glacier file(s), {written} changed");
        }),
        Command::Db(DbCommand::Migrate) => task("db:migrate", &[]),
        Command::Db(DbCommand::Rollback { steps }) => {
            task("db:rollback", &[("GLACIER_STEPS", &steps.to_string())])
        }
        Command::Db(DbCommand::Status) => task("db:status", &[]),
        Command::Generate(GenerateCommand::Migration { name }) => generate::migration(&name),
        Command::Generate(GenerateCommand::Job { name, fields }) => scaffold::job(&name, &fields),
        Command::Generate(GenerateCommand::Policy { name }) => scaffold::policy(&name),
        Command::Generate(GenerateCommand::Authentication { api }) => auth::authentication(api),
        Command::Generate(GenerateCommand::Scaffold {
            name,
            fields,
            dialect,
        }) => scaffold::scaffold(&name, &fields, dialect),
        Command::Generate(GenerateCommand::Model {
            name,
            fields,
            dialect,
        }) => scaffold::model_only(&name, &fields, dialect),
        Command::Generate(GenerateCommand::Controller {
            name,
            actions,
            dialect,
        }) => scaffold::controller_only(&name, &actions, dialect),
        Command::Secret => {
            println!("{}", secret());
            Ok(())
        }
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(message) => {
            eprintln!("error: {message}");
            ExitCode::FAILURE
        }
    }
}

/// The app's starter controller and models module (and, in `.glacier`, its
/// test), in the chosen language.
fn controller_files(dialect: Dialect, api: bool) -> Vec<(&'static str, &'static str)> {
    match (dialect, api) {
        (Dialect::Glacier, true) => vec![
            (
                "src/models/mod.rs",
                include_str!("../templates/models_mod_glacier.rs.tmpl"),
            ),
            (
                "src/controllers/mod.rs",
                include_str!("../templates/api/controllers_mod_glacier.rs.tmpl"),
            ),
            (
                "src/controllers/home_controller.glacier",
                include_str!("../templates/api/home_controller.glacier.tmpl"),
            ),
            (
                "tests/glacier.rs",
                include_str!("../templates/api/tests_glacier.rs.tmpl"),
            ),
            (
                "tests/controllers/home_controller.test.glacier",
                include_str!("../templates/api/home_controller.test.glacier.tmpl"),
            ),
        ],
        (Dialect::Rust, true) => vec![
            (
                "src/models/mod.rs",
                include_str!("../templates/models_mod.rs.tmpl"),
            ),
            (
                "src/controllers/mod.rs",
                include_str!("../templates/api/controllers_mod.rs.tmpl"),
            ),
            (
                "src/controllers/home_controller.rs",
                include_str!("../templates/api/home_controller.rs.tmpl"),
            ),
        ],
        (Dialect::Glacier, false) => vec![
            (
                "src/models/mod.rs",
                include_str!("../templates/models_mod_glacier.rs.tmpl"),
            ),
            (
                "src/controllers/mod.rs",
                include_str!("../templates/controllers_mod_glacier.rs.tmpl"),
            ),
            (
                "src/controllers/pages_controller.glacier",
                include_str!("../templates/pages_controller.glacier.tmpl"),
            ),
            ("tests/glacier.rs", scaffold::TESTS_RS),
            (
                "tests/controllers/pages_controller.test.glacier",
                include_str!("../templates/pages_controller.test.glacier.tmpl"),
            ),
        ],
        (Dialect::Rust, false) => vec![
            (
                "src/models/mod.rs",
                include_str!("../templates/models_mod.rs.tmpl"),
            ),
            (
                "src/controllers/mod.rs",
                include_str!("../templates/controllers_mod.rs.tmpl"),
            ),
            (
                "src/controllers/pages_controller.rs",
                include_str!("../templates/pages_controller.rs.tmpl"),
            ),
        ],
    }
}

fn new_app(
    name: &str,
    glacier_path: Option<PathBuf>,
    dialect: Dialect,
    api: bool,
) -> Result<(), String> {
    validate_name(name)?;
    let root = Path::new(name);
    if root.exists() {
        return Err(format!("`{name}` already exists"));
    }

    let (glacier_dependency, dialect_dependency) = dependencies(glacier_path)?;
    let flavour = if api { API_TEMPLATE } else { BROWSER_TEMPLATE };
    let controllers = controller_files(dialect, api);
    for (path, template) in APP_TEMPLATE.iter().chain(flavour).chain(&controllers) {
        let target = root.join(path);
        if let Some(dir) = target.parent() {
            fs::create_dir_all(dir).map_err(|e| format!("creating {}: {e}", dir.display()))?;
        }
        let contents = template
            .replace("{{name}}", name)
            .replace("{{crate_name}}", &name.replace('-', "_"))
            .replace("{{glacier_dependency}}", &glacier_dependency)
            .replace("{{dialect_dependency}}", &dialect_dependency)
            .replace("{{secret}}", &secret());
        fs::write(&target, contents).map_err(|e| format!("writing {}: {e}", target.display()))?;
        println!("      create  {name}/{path}");
    }

    println!("\nDone! Next:\n\n    cd {name}\n    glacier server\n");
    Ok(())
}

/// The new app's `glacier-web` and `glacier-dialect` dependency lines: the
/// crates at `--glacier-path`, else those in the Glacier checkout this CLI
/// was built from, else (installed from crates.io) this CLI's version.
fn dependencies(glacier_path: Option<PathBuf>) -> Result<(String, String), String> {
    let checkout = Path::new(env!("CARGO_MANIFEST_DIR")).join("../glacier");
    let path = match glacier_path {
        Some(path) => Some(
            path.canonicalize()
                .map_err(|_| format!("can't find the glacier crate at {}", path.display()))?,
        ),
        None => is_glacier_crate(&checkout)
            .then(|| checkout.canonicalize().ok())
            .flatten(),
    };
    Ok(match path {
        Some(path) => {
            let glacier = path.display().to_string().replace('\\', "\\\\");
            let dialect = path
                .join("../glacier-dialect")
                .display()
                .to_string()
                .replace('\\', "\\\\");
            (
                format!("glacier-web = {{ path = \"{glacier}\" }}"),
                format!("glacier-dialect = {{ path = \"{dialect}\" }}"),
            )
        }
        None => {
            let version = env!("CARGO_PKG_VERSION");
            (
                format!("glacier-web = \"{version}\""),
                format!("glacier-dialect = \"{version}\""),
            )
        }
    })
}

/// Whether `dir` holds the `glacier-web` crate.
fn is_glacier_crate(dir: &Path) -> bool {
    fs::read_to_string(dir.join("Cargo.toml"))
        .is_ok_and(|manifest| manifest.contains("name = \"glacier-web\""))
}

fn validate_name(name: &str) -> Result<(), String> {
    let starts_with_letter = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic());
    let valid_chars = name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    if starts_with_letter && valid_chars {
        Ok(())
    } else {
        Err(format!(
            "invalid app name `{name}`: use letters, digits, `_` or `-`, starting with a letter"
        ))
    }
}

/// 64 random bytes, hex-encoded: comfortably above the 32-byte minimum.
fn secret() -> String {
    let mut bytes = [0u8; 64];
    getrandom::fill(&mut bytes).expect("the OS random number generator failed");
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Runs the app with `GLACIER_TASK` set, so it performs `name` and exits.
fn task(name: &str, envs: &[(&str, &str)]) -> Result<(), String> {
    let mut envs = envs.to_vec();
    envs.push(("GLACIER_TASK", name));
    cargo_run(&["-q".into()], &envs)
}

pub(crate) fn cargo_run(args: &[String], envs: &[(&str, &str)]) -> Result<(), String> {
    if !Path::new("Cargo.toml").exists() {
        return Err("no Cargo.toml here; run this from your app's directory".into());
    }
    let status = Process::new("cargo")
        .arg("run")
        .args(args)
        .envs(envs.iter().copied())
        .status()
        .map_err(|e| format!("failed to run cargo: {e}"))?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("cargo run exited with {status}"))
    }
}

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

    #[test]
    fn validates_names() {
        assert!(validate_name("blog").is_ok());
        assert!(validate_name("my-app_2").is_ok());
        assert!(validate_name("2fast").is_err());
        assert!(validate_name("").is_err());
        assert!(validate_name("../etc").is_err());
    }
}