appstruct-cli 0.2.0

Command-line compiler and development workflow for AppStruct 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
use appstruct_ir::Diagnostic;
use clap::{Parser, Subcommand};
use serde::Serialize;
use std::env;
use std::path::PathBuf;
use std::process::ExitCode;

mod access_preview;
mod auth_admin;
mod build;
mod cache;
mod capabilities;
mod db;
mod deploy;
mod development;
mod doctor;
mod environment;
mod fingerprint;
mod generation;
mod migration;
mod module_registry;
mod preset;
mod project_diagnostics;
mod project_new;
mod project_status;
mod report;
mod schema;
mod template;
mod transaction;
mod update;

#[derive(Debug, Parser)]
#[command(
    name = "appstruct",
    version,
    about = "Compile AppStruct application specifications"
)]
struct Cli {
    /// Project directory or a path within the project.
    #[arg(long, global = true)]
    project: Option<PathBuf>,

    /// Select human-readable or machine-readable command output.
    #[arg(long, global = true, value_enum, default_value_t = report::OutputFormat::Text)]
    format: report::OutputFormat,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Explain declared resource and field access for a sample actor.
    Access {
        #[command(subcommand)]
        command: access_preview::AccessCommand,
    },
    /// Show the Auth and Billing provider support matrix.
    Capabilities,
    /// Create a new `AppStruct` project from an official template.
    New {
        name: String,
        #[arg(long, value_enum, default_value_t = project_new::ProjectTemplate::Dashboard)]
        template: project_new::ProjectTemplate,
    },
    /// Interactively create a new `AppStruct` project.
    Init(project_new::InitArgs),
    /// Build validated backend and web production artifacts.
    Build,
    /// Manage authentication accounts.
    Auth {
        #[command(subcommand)]
        command: auth_admin::AuthCommand,
    },
    /// Check the local toolchain, database mode, and project configuration.
    Doctor {},
    /// Start PostgreSQL coordination, the API, and the Rsbuild development server.
    Dev {
        #[arg(long)]
        api_port: Option<u16>,
        #[arg(long)]
        web_port: Option<u16>,
        /// Do not open the generated Web application in the default browser.
        #[arg(long)]
        no_open: bool,
    },
    /// Inspect an existing PostgreSQL database.
    Db {
        #[command(subcommand)]
        command: db::DbCommand,
    },
    /// Verify immutable artifacts before promotion to another environment.
    Deploy {
        #[command(subcommand)]
        command: deploy::DeployCommand,
    },
    /// Validate the App Spec and build normalized IR in memory.
    Check {
        /// Treat non-fatal App Spec diagnostics as errors.
        #[arg(long)]
        deny_warnings: bool,
    },
    /// Generate canonical IR and the minimal Rust backend artifact.
    Generate {
        /// Verify generated files are current without writing them.
        #[arg(long)]
        check: bool,
        /// Report compiler, planner, formatter, and output timings.
        #[arg(long)]
        timings: bool,
    },
    /// Plan or accept database schema migrations.
    Migrate {
        #[command(subcommand)]
        command: migration::MigrateCommand,
    },
    /// Install, update, verify, remove, and inspect signed remote modules.
    Module {
        #[command(subcommand)]
        command: module_registry::ModuleCommand,
    },
    /// Inspect the locked official preset and its expanded module defaults.
    Preset {
        #[command(subcommand)]
        command: preset::PresetCommand,
    },
    /// Print the App Spec JSON Schema for editor integration.
    Schema,
    /// Compare user-owned delivery files with the current official template.
    Template {
        #[command(subcommand)]
        command: template::TemplateCommand,
    },
    /// Stage, verify, and transactionally commit locked framework updates.
    Update,
    /// Inspect the local project control-plane status.
    Project {
        #[command(subcommand)]
        command: project_status::ProjectCommand,
    },
    /// Show the local project control-plane status.
    Status,
}

#[derive(Serialize)]
struct CheckReport<'diagnostic> {
    valid: bool,
    entity_count: usize,
    diagnostics: &'diagnostic [Diagnostic],
}

fn main() -> ExitCode {
    run(Cli::parse())
}

fn run(cli: Cli) -> ExitCode {
    report::set_output_format(cli.format);
    if let Command::New { name, template } = &cli.command {
        let parent = match project_start(cli.project.as_ref()) {
            Ok(path) => path,
            Err(exit) => return exit,
        };
        return project_new::run(&parent, name, *template);
    }
    if let Command::Init(args) = &cli.command {
        let parent = match project_start(cli.project.as_ref()) {
            Ok(path) => path,
            Err(exit) => return exit,
        };
        return project_new::init(&parent, args);
    }
    if matches!(&cli.command, Command::Schema | Command::Capabilities) {
        if matches!(&cli.command, Command::Capabilities) {
            return capabilities::run();
        }
        return schema::run();
    }
    let start = match project_start(cli.project.as_ref()) {
        Ok(path) => path,
        Err(exit) => return exit,
    };
    let project = match appstruct_compiler::discover_project(&start) {
        Ok(project) => project,
        Err(diagnostic) => {
            if matches!(&cli.command, Command::Check { .. })
                && cli.format == report::OutputFormat::Json
            {
                render_json_report(false, 0, std::slice::from_ref(&diagnostic));
                return ExitCode::from(1);
            }
            return report::fail_diagnostics(report::ErrorCategory::Project, vec![diagnostic]);
        }
    };

    match cli.command {
        Command::New { .. } | Command::Init(_) | Command::Schema | Command::Capabilities => {
            unreachable!()
        }
        Command::Auth { command } => auth_admin::run(&project, &command),
        Command::Access { command } => access_preview::run(&project, &command),
        Command::Build => build::run(&project),
        Command::Doctor {} => doctor::run(&project, cli.format == report::OutputFormat::Json),
        Command::Dev {
            api_port,
            web_port,
            no_open,
        } => development::run(&project, api_port, web_port, !no_open),
        Command::Db { command } => db::run(&project, &command),
        Command::Deploy { command } => deploy::run(&project, &command),
        Command::Check { deny_warnings } => run_check(&project, cli.format, deny_warnings),
        Command::Generate { check, timings } => {
            generation::run_with_timings(&project, check, timings)
        }
        Command::Migrate { command } => migration::run(&project, command),
        Command::Module { command } => module_registry::run(&project, &command),
        Command::Preset { command } => preset::run(&project, &command),
        Command::Template { command } => template::run(&project, &command),
        Command::Update => update::run(&project),
        Command::Project { command } => {
            project_diagnostics::run(&project, &command, cli.format == report::OutputFormat::Json)
        }
        Command::Status => project_status::run(&project, cli.format == report::OutputFormat::Json),
    }
}

fn project_start(project: Option<&PathBuf>) -> Result<PathBuf, ExitCode> {
    if let Some(path) = project {
        return Ok(path.clone());
    }
    env::current_dir().map_err(|error| {
        report::fail(
            "AS6001",
            report::ErrorCategory::Project,
            format!("cannot read current directory: {error}"),
            report::ExitClass::Environment,
        )
    })
}

fn run_check(
    project: &std::path::Path,
    format: report::OutputFormat,
    deny_warnings: bool,
) -> ExitCode {
    match appstruct_compiler::compile_project_report(project) {
        Ok(report) => {
            let mut diagnostics = report.diagnostics;
            match appstruct_codegen::check_user_symbols(project, &report.ir) {
                Ok(missing) => diagnostics.extend(missing),
                Err(error) => {
                    return report::fail(
                        "AS5008",
                        report::ErrorCategory::Generation,
                        format!("cannot inspect app/web sources: {error}"),
                        report::ExitClass::Environment,
                    );
                }
            }
            // Errors always fail the check; `--deny-warnings` additionally promotes warnings.
            let has_error = diagnostics
                .iter()
                .any(|diagnostic| diagnostic.severity == appstruct_ir::Severity::Error);
            let denied = has_error || (deny_warnings && !diagnostics.is_empty());
            match format {
                report::OutputFormat::Text => {
                    for diagnostic in &diagnostics {
                        report::render_text_diagnostic(diagnostic);
                    }
                    if !denied {
                        println!(
                            "App Spec is valid: {} ({} entities)",
                            report.ir.app.name,
                            report.ir.entities.len()
                        );
                    }
                }
                report::OutputFormat::Json => {
                    render_json_report(!denied, report.ir.entities.len(), &diagnostics);
                }
            }
            if denied {
                ExitCode::from(1)
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(diagnostics) => {
            match format {
                report::OutputFormat::Text => {
                    for diagnostic in &diagnostics {
                        report::render_text_diagnostic(diagnostic);
                    }
                }
                report::OutputFormat::Json => render_json_report(false, 0, &diagnostics),
            }
            ExitCode::from(1)
        }
    }
}

fn render_json_report(valid: bool, entity_count: usize, diagnostics: &[Diagnostic]) {
    let report = CheckReport {
        valid,
        entity_count,
        diagnostics,
    };
    match serde_json::to_string_pretty(&report) {
        Ok(output) => println!("{output}"),
        Err(error) => {
            let _ = report::fail(
                "AS5003",
                report::ErrorCategory::Validation,
                format!("failed to serialize diagnostics: {error}"),
                report::ExitClass::Environment,
            );
        }
    }
}

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

    fn fixture() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/m0-project")
    }

    #[test]
    fn check_commands_succeed_for_the_m0_fixture() {
        assert_eq!(
            run(Cli {
                project: Some(fixture()),
                format: report::OutputFormat::Json,
                command: Command::Check {
                    deny_warnings: false,
                },
            }),
            ExitCode::SUCCESS
        );
        assert_eq!(
            run(Cli {
                project: Some(fixture()),
                format: report::OutputFormat::Text,
                command: Command::Check {
                    deny_warnings: false,
                },
            }),
            ExitCode::SUCCESS
        );
    }

    #[test]
    fn missing_projects_fail_for_json_and_text_check() {
        let missing = PathBuf::from("/missing-appstruct-project");
        assert_ne!(
            run(Cli {
                project: Some(missing.clone()),
                format: report::OutputFormat::Json,
                command: Command::Check {
                    deny_warnings: false,
                },
            }),
            ExitCode::SUCCESS
        );
        assert_ne!(
            run(Cli {
                project: Some(missing),
                format: report::OutputFormat::Text,
                command: Command::Doctor {},
            }),
            ExitCode::SUCCESS
        );
    }

    #[test]
    fn migrate_plan_and_preset_show_cover_command_dispatch() {
        assert_eq!(
            run(Cli {
                project: Some(fixture()),
                format: report::OutputFormat::Text,
                command: Command::Migrate {
                    command: migration::MigrateCommand::Plan,
                },
            }),
            ExitCode::SUCCESS
        );
        assert_ne!(
            run(Cli {
                project: Some(fixture()),
                format: report::OutputFormat::Json,
                command: Command::Preset {
                    command: preset::PresetCommand::Show { expanded: false },
                },
            }),
            ExitCode::SUCCESS
        );
        assert_eq!(
            run(Cli {
                project: Some(fixture()),
                format: report::OutputFormat::Text,
                command: Command::Module {
                    command: module_registry::ModuleCommand::List,
                },
            }),
            ExitCode::SUCCESS
        );
    }
}