glacier-web-cli 0.5.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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! The `glacier` command-line tool.

mod access;
mod analysis;
mod audit;
mod auth;
mod diagnostics;
mod dialect;
mod docs;
mod generate;
mod lsp;
mod mcp;
mod scaffold;
mod server;
mod symbols;

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,
        /// A plain stylesheet in public/app.css, without Tailwind CSS
        #[arg(long)]
        no_tailwind: bool,
        /// JavaScript bundled by Vite (needs Node): assets/js/app.js,
        /// vite.config.js and package.json
        #[arg(long)]
        vite: 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 app's OpenAPI document (JSON): `glacier openapi > openapi.json`
    Openapi {
        /// For this API version (`version` scopes in routes!)
        #[arg(long)]
        api_version: Option<String>,
    },
    /// Print TypeScript types for the app's JSON, from its serializers:
    /// `glacier types > assets/api.ts`
    Types {
        /// For this API version (`version` scopes in routes!)
        #[arg(long)]
        api_version: Option<String>,
    },
    /// Print the application's routes
    Routes,
    /// Run one of the app's tasks (src/tasks.glacier): `glacier run reports:send 12`
    Run {
        /// The task's name
        task: String,
        /// Its arguments, in order
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// List the app's tasks and their arguments
    Tasks,
    /// The app's cache: `glacier cache clear`
    Cache {
        #[command(subcommand)]
        action: CacheCommand,
    },
    /// Show received webhook events: counts and the latest (JSON)
    Webhooks {
        #[command(subcommand)]
        action: Option<WebhooksCommand>,
    },
    /// Show the job queue: due, scheduled, running and failed jobs (JSON)
    Jobs {
        #[command(subcommand)]
        action: Option<JobsCommand>,
    },
    /// 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,
    /// The MCP server, for AI agents: speaks JSON-RPC on stdin/stdout
    Mcp,
    /// Checks the app: .glacier errors, then cargo check's, located in the .glacier source
    Check {
        /// Print the errors as JSON, one object per line
        #[arg(long)]
        json: bool,
        /// Only the .glacier compiler (fast), without building
        #[arg(long)]
        glacier_only: bool,
    },
    /// 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,
    /// Look for security problems in the app's source: raw HTML, SQL built
    /// from strings, foreign keys a request can set, open CORS, GET routes
    /// that change things, and routes without a CSRF check
    Audit,
    /// Everything to run before a commit: formatting (.glacier and Rust),
    /// clippy with warnings as errors, the tests, then the audit
    Precommit,
}

#[derive(Subcommand)]
enum WebhooksCommand {
    /// Handle a stored event again, whatever happened last time
    Replay {
        /// The event's id, from `glacier webhooks`
        id: i64,
    },
}

#[derive(Subcommand)]
enum JobsCommand {
    /// List the recurring jobs and scheduled tasks, with when each runs next
    Schedules,
    /// Queue a failed job to run again, with its attempts reset
    Retry {
        /// The job's id, from `glacier jobs`
        id: i64,
    },
    /// Run the jobs without the web server, until Ctrl-C (the app binary's
    /// `work` command; `web` is the server without them)
    Work {
        /// Extra arguments for cargo, e.g. --release
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

#[derive(Subcommand)]
enum CacheCommand {
    /// Forget everything in the app's cache (its configured store)
    Clear,
}

#[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,
    /// Load the seeds (src/seeds.glacier) in one transaction
    Seed,
    /// Migrate, then load the seeds: for a new checkout
    Setup,
    /// Write db/schema.sql (migrating in development does this too)
    Dump,
}

#[derive(Subcommand)]
enum GenerateCommand {
    /// A migration in db/migrations; `create_<table>` names start a table
    Migration {
        /// snake_case description, e.g. create_posts or add_slug_to_posts
        name: String,
        /// For another database the app names (`[databases.analytics]`):
        /// its migrations live in db/<name>/migrations/
        #[arg(long)]
        database: Option<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>,
    },
    /// Receive a provider's webhooks (stripe, github, shopify, lemon_squeezy, paddle, or any HMAC)
    Webhook {
        /// The provider, e.g. stripe
        provider: String,
    },
    /// A client for another service's API in src/clients/, with a test
    Client {
        /// The service, e.g. ConvertKit
        name: String,
        /// Its API's base URL, e.g. https://api.convertkit.com/v3
        base_url: String,
    },
    /// Middleware in src/middleware/, to run in a pipeline
    Middleware {
        /// The middleware name, e.g. RequireBeta
        name: String,
    },
    /// A mailer in src/mailers/, with HTML and text templates per mail
    Mailer {
        /// The mailer name, e.g. ReportMailer
        name: String,
        /// Its mails, e.g. ready weekly_summary
        actions: 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,
        /// Staff can sign in as another user, with a banner while they are
        #[arg(long)]
        impersonation: bool,
        /// Users make API tokens with scopes, for scripts and other apps
        #[arg(long)]
        api_tokens: bool,
    },
    /// Orgs whose members share rows: Org and Membership models, OrgAccess,
    /// the InOrg middleware, an orgs controller and routes, with tests
    Access {
        /// What the access is for: `org`
        kind: String,
        /// How URLs name the org: `session` (the current org kept in the
        /// session; the default for pages), `nested` (`/orgs/:org_id/…`; the
        /// default for JSON APIs) or `prefix` (`/:org_id/…`, as Basecamp)
        #[arg(long)]
        urls: Option<String>,
    },
    /// 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,
        /// Whose records they are: `user` (owned by the signed-in user, read
        /// through `Model.for(access)`, behind `authenticated`) or `org`.
        /// An app with an Access owns them by default: its org's, else
        /// the signed-in user's
        #[arg(long)]
        access: Option<String>,
        /// Records everyone shares, even in an app with an Access
        #[arg(long, conflicts_with = "access")]
        no_access: bool,
    },
}

/// 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")),
    // For AI agents: the conventions, and the MCP server for clients that
    // read `.mcp.json` (Claude Code among them).
    ("AGENTS.md", include_str!("../templates/AGENTS.md.tmpl")),
    (".mcp.json", include_str!("../templates/mcp.json.tmpl")),
    ("build.rs", include_str!("../templates/build.rs.tmpl")),
    // Here from the start, so builds watch it for the first migration.
    ("db/migrations/.gitkeep", ""),
    ("src/main.rs", include_str!("../templates/main.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/views/layouts/app.html",
        include_str!("../templates/layout.html.tmpl"),
    ),
    (
        "src/views/pages/home.html",
        include_str!("../templates/home.html.tmpl"),
    ),
    // Pages for errors, in the layout: the app's to change.
    (
        "src/views/errors/404.html",
        include_str!("../templates/errors/404.html.tmpl"),
    ),
    (
        "src/views/errors/500.html",
        include_str!("../templates/errors/500.html.tmpl"),
    ),
];

/// The stylesheet `glacier new` makes; the components come from the
/// component library ([`ui_files::UI_FILES`]).
const TAILWIND_TEMPLATE: &[(&str, &str)] = &[(
    "assets/app.css",
    include_str!("../templates/tailwind/app.css.tmpl"),
)];

/// The same with a plain stylesheet: `glacier new --no-tailwind`.
const PLAIN_CSS_TEMPLATE: &[(&str, &str)] = &[(
    "public/app.css",
    include_str!("../templates/plain/app.css.tmpl"),
)];

/// The component library (`templates/ui/`): its stylesheets, fonts and
/// components, copied into every new app with pages, the app's own to
/// change, as Phoenix's `core_components.ex` and shadcn's components are.
mod ui_files {
    include!(concat!(env!("OUT_DIR"), "/ui_files.rs"));
}

/// Vite's setup: `glacier new --vite`.
const VITE_TEMPLATE: &[(&str, &str)] = &[
    (
        "package.json",
        include_str!("../templates/vite/package.json.tmpl"),
    ),
    (
        "vite.config.js",
        include_str!("../templates/vite/vite.config.js.tmpl"),
    ),
    (
        "assets/js/app.js",
        include_str!("../templates/vite/app.js.tmpl"),
    ),
];

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

fn main() -> ExitCode {
    let result = match Cli::parse().command {
        Command::New {
            name,
            glacier_path,
            dialect,
            api,
            no_tailwind,
            vite,
        } => new_app(&name, glacier_path, dialect, api, !no_tailwind, vite),
        Command::Server { no_watch, args } => server::run(&args, !no_watch),
        Command::Types { api_version } => task(
            "typescript",
            &[("GLACIER_API_VERSION", api_version.as_deref().unwrap_or(""))],
        ),
        Command::Routes => task("routes", &[]),
        Command::Run { task, args } => {
            let mut cargo = vec!["-q".to_owned(), "--".to_owned(), task];
            cargo.extend(args);
            cargo_run(&cargo, &[])
        }
        Command::Tasks => task("tasks", &[]),
        Command::Cache {
            action: CacheCommand::Clear,
        } => task("cache:clear", &[]),
        Command::Webhooks { action: None } => task("webhooks", &[]),
        Command::Webhooks {
            action: Some(WebhooksCommand::Replay { id }),
        } => task("webhooks:replay", &[("GLACIER_EVENT_ID", &id.to_string())]),
        Command::Jobs { action: None } => task("jobs", &[]),
        Command::Jobs {
            action: Some(JobsCommand::Schedules),
        } => task("jobs:schedules", &[]),
        Command::Jobs {
            action: Some(JobsCommand::Retry { id }),
        } => task("jobs:retry", &[("GLACIER_JOB_ID", &id.to_string())]),
        Command::Jobs {
            action: Some(JobsCommand::Work { args }),
        } => {
            let mut args = args;
            args.extend(["--".to_owned(), "work".to_owned()]);
            cargo_run(&args, &[])
        }
        Command::Openapi { api_version } => task(
            "openapi",
            &[("GLACIER_API_VERSION", api_version.as_deref().unwrap_or(""))],
        ),
        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::Mcp => mcp::run(),
        Command::Check { json, glacier_only } => check(json, glacier_only),
        Command::Fmt { check, paths } => dialect::format(&paths, check),
        Command::Audit => audit::run(Path::new(".")),
        Command::Precommit => precommit(),
        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::Db(DbCommand::Seed) => task("db:seed", &[]),
        Command::Db(DbCommand::Dump) => task("db:dump", &[]),
        Command::Db(DbCommand::Setup) => {
            task("db:migrate", &[]).and_then(|()| task("db:seed", &[]))
        }
        Command::Generate(GenerateCommand::Migration { name, database }) => match database {
            Some(database) => generate::named_migration(&name, &database),
            // The jobs tables, as `glacier generate job` adds them.
            None if name == "create_glacier_jobs" => {
                generate::migration_with("create_glacier_jobs", scaffold::JOBS_MIGRATION)
            }
            None => generate::migration(&name),
        },
        Command::Generate(GenerateCommand::Job { name, fields }) => scaffold::job(&name, &fields),
        Command::Generate(GenerateCommand::Webhook { provider }) => scaffold::webhook(&provider),
        Command::Generate(GenerateCommand::Client { name, base_url }) => {
            scaffold::client(&name, &base_url)
        }
        Command::Generate(GenerateCommand::Mailer { name, actions }) => {
            scaffold::mailer(&name, &actions)
        }
        Command::Generate(GenerateCommand::Middleware { name }) => scaffold::middleware(&name),
        Command::Generate(GenerateCommand::Policy { name }) => scaffold::policy(&name),
        Command::Generate(GenerateCommand::Authentication {
            api,
            impersonation,
            api_tokens,
        }) => auth::authentication(
            api,
            auth::Extras {
                impersonation,
                api_tokens,
            },
        ),
        Command::Generate(GenerateCommand::Access { kind, urls }) => {
            access::access(&kind, urls.as_deref())
        }
        Command::Generate(GenerateCommand::Scaffold {
            name,
            fields,
            dialect,
            access,
            no_access,
        }) => scaffold::scaffold(&name, &fields, dialect, access.as_deref(), no_access),
        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)> {
    let routes = match (dialect, api) {
        (Dialect::Glacier, false) => (
            "src/routes.glacier",
            include_str!("../templates/routes.glacier.tmpl"),
        ),
        (Dialect::Glacier, true) => (
            "src/routes.glacier",
            include_str!("../templates/api/routes.glacier.tmpl"),
        ),
        (Dialect::Rust, false) => ("src/routes.rs", include_str!("../templates/routes.rs.tmpl")),
        (Dialect::Rust, true) => (
            "src/routes.rs",
            include_str!("../templates/api/routes.rs.tmpl"),
        ),
    };
    let mut files = controller_and_model_files(dialect, api);
    files.push(routes);
    files
}

fn controller_and_model_files(dialect: Dialect, api: bool) -> Vec<(&'static str, &'static str)> {
    match (dialect, api) {
        (Dialect::Glacier, true) => vec![
            (
                "src/app.glacier",
                include_str!("../templates/api/app.glacier.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"),
            ),
            (
                "src/seeds.glacier",
                include_str!("../templates/seeds.glacier.tmpl"),
            ),
        ],
        (Dialect::Rust, true) => vec![
            ("src/app.rs", include_str!("../templates/api/app.rs.tmpl")),
            (
                "src/controllers/home_controller.rs",
                include_str!("../templates/api/home_controller.rs.tmpl"),
            ),
            ("src/seeds.rs", include_str!("../templates/seeds.rs.tmpl")),
        ],
        (Dialect::Glacier, false) => vec![
            (
                "src/app.glacier",
                include_str!("../templates/app.glacier.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"),
            ),
            (
                "src/seeds.glacier",
                include_str!("../templates/seeds.glacier.tmpl"),
            ),
        ],
        (Dialect::Rust, false) => vec![
            ("src/app.rs", include_str!("../templates/app.rs.tmpl")),
            (
                "src/controllers/pages_controller.rs",
                include_str!("../templates/pages_controller.rs.tmpl"),
            ),
            ("src/seeds.rs", include_str!("../templates/seeds.rs.tmpl")),
        ],
    }
}

fn new_app(
    name: &str,
    glacier_path: Option<PathBuf>,
    dialect: Dialect,
    api: bool,
    tailwind: bool,
    vite: bool,
) -> Result<(), String> {
    validate_name(name)?;
    if vite && api {
        return Err("`--vite` is for apps with pages; an `--api` app has no assets".into());
    }
    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 styles: &[(&str, &str)] = match (api, tailwind) {
        (true, _) => &[],
        (false, true) => TAILWIND_TEMPLATE,
        (false, false) => PLAIN_CSS_TEMPLATE,
    };
    let controllers = controller_files(dialect, api);
    let scripts: &[(&str, &str)] = if vite { VITE_TEMPLATE } else { &[] };
    for (path, template) in APP_TEMPLATE
        .iter()
        .chain(flavour)
        .chain(styles)
        .chain(scripts)
        .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(
                "{{display_name}}",
                &auth::display_name(&name.replace('-', "_")),
            )
            .replace("{{glacier_dependency}}", &glacier_dependency)
            .replace("{{dialect_dependency}}", &dialect_dependency)
            .replace("{{secret}}", &secret());
        // Tailwind builds into public/assets/ (git-ignores it); a plain
        // stylesheet is public/app.css itself.
        let contents = match *path {
            "src/views/layouts/app.html" if !tailwind => {
                contents.replace("/assets/app.css", "/app.css")
            }
            ".gitignore" if tailwind && !api => {
                contents + "# Built from assets/app.css by every build\n/public/assets/\n"
            }
            _ => contents,
        };
        let contents = match *path {
            "src/views/layouts/app.html" if vite => contents.replace(
                "  </head>",
                "    {{ vite(\"assets/js/app.js\") }}\n  </head>",
            ),
            ".gitignore" if vite => {
                contents
                    + "# Vite: packages, and what a release build writes\n/node_modules/\n/public/build/\n"
            }
            _ => contents,
        };
        fs::write(&target, contents).map_err(|e| format!("writing {}: {e}", target.display()))?;
        println!("      create  {name}/{path}");
    }
    if !api {
        for (path, bytes) in ui_files::UI_FILES {
            let target = root.join(path);
            if let Some(dir) = target.parent() {
                fs::create_dir_all(dir).map_err(|e| format!("creating {}: {e}", dir.display()))?;
            }
            fs::write(&target, bytes).map_err(|e| format!("writing {}: {e}", target.display()))?;
        }
        println!(
            "      create  {name}/src/components/ ({} components), public/ui/, public/fonts/",
            ui_files::UI_FILES
                .iter()
                .filter(|(path, _)| path.ends_with(".html") && !path.ends_with(".preview.html"))
                .count()
        );
    }

    if vite {
        println!("\nDone! Next:\n\n    cd {name}\n    npm install\n    glacier server\n");
    } else {
        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()
}

/// `glacier check`: the app's errors, as JSON lines or as text.
fn check(as_json: bool, glacier_only: bool) -> Result<(), String> {
    let app = Path::new(".");
    let diagnostics = if glacier_only {
        analysis::glacier_errors(app)
    } else {
        analysis::build_errors(app)?
    };
    let errors = diagnostics
        .iter()
        .filter(|d| d["severity"] == "error")
        .count();
    for d in &diagnostics {
        if as_json {
            println!("{d}");
        } else {
            let place = format!(
                "{}:{}:{}",
                d["file"].as_str().unwrap_or("?"),
                d["line"],
                d["column"]
            );
            println!(
                "{}: {}: {}",
                place,
                d["severity"].as_str().unwrap_or("error"),
                d["message"].as_str().unwrap_or_default()
            );
            if let Some(expected) = d["expected"].as_str() {
                println!("    expected: {expected}");
            }
            if let Some(fix) = d["fix"]["replacement"].as_str() {
                println!("    fix: {fix}");
            }
        }
    }
    if errors == 0 {
        if !as_json {
            println!("No errors.");
        }
        Ok(())
    } else {
        Err(format!("{errors} error(s)"))
    }
}

/// 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}"))
    }
}

/// `glacier precommit`: each check in turn, stopping at the first that
/// fails; the audit last, whose findings are printed but don't fail it.
fn precommit() -> Result<(), String> {
    println!("== glacier fmt --check");
    dialect::format(&[], true)?;
    println!("== cargo fmt --check");
    let rustfmt = std::process::Command::new("cargo")
        .args(["fmt", "--check"])
        .status()
        .map_err(|e| format!("running cargo fmt: {e}"))?;
    if !rustfmt.success() {
        return Err("Rust files need formatting: run `cargo fmt`".into());
    }
    println!("== clippy");
    let clippy_args: Vec<String> = ["--all-targets", "--", "-D", "warnings"]
        .iter()
        .map(|a| (*a).to_owned())
        .collect();
    if !dialect::cargo("clippy", &clippy_args) {
        return Err("clippy found problems".into());
    }
    println!("== tests");
    if !dialect::cargo("test", &[]) {
        return Err("tests failed".into());
    }
    println!("== audit");
    if let Err(summary) = audit::run(Path::new(".")) {
        println!("{summary} (not a failure: each is a place to look)");
    }
    Ok(())
}

#[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());
    }
}