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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use appstruct_migrate::inspect_database_schema;
use clap::Subcommand;
use serde::Serialize;
use similar::TextDiff;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

mod access;
mod output;
mod preflight;
mod preview;
mod render;
mod review;

use access::{resolve_access, valid_access_name};
#[cfg(test)]
use output::resolve as resolve_output;

#[derive(Clone, Debug, Subcommand)]
pub(crate) enum DbCommand {
    /// Create an App Spec draft from a live PostgreSQL schema.
    Pull {
        /// PostgreSQL schema to inspect.
        #[arg(long, default_value = "public")]
        schema: String,
        /// Project-relative destination for the generated domain draft.
        #[arg(long, default_value = "spec/imported.yaml")]
        output: PathBuf,
        /// Verify that an existing draft matches the live schema without writing.
        #[arg(long, conflicts_with = "diff")]
        check: bool,
        /// Print a unified diff against an existing draft without writing.
        #[arg(long, conflicts_with = "check")]
        diff: bool,
        /// Review and select tables in a terminal before writing the draft.
        #[arg(long, conflicts_with_all = ["check", "diff"])]
        review: bool,
        /// Access policy to add to imported entities.
        #[arg(long, value_enum, default_value = "none")]
        access: PullAccess,
        /// RBAC role used when --access role is selected.
        #[arg(long, conflicts_with = "owner")]
        role: Option<String>,
        /// Ownership relation field used when --access owner is selected.
        #[arg(long, conflicts_with = "role")]
        owner: Option<String>,
    },
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
pub(crate) enum PullAccess {
    None,
    Public,
    Authenticated,
    Role,
    Owner,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PullMode {
    Create,
    Check,
    Diff,
}

#[derive(Serialize)]
struct PullResult<'path> {
    command: &'static str,
    action: &'static str,
    schema: String,
    output: &'path Path,
    entity_count: usize,
    warnings: Vec<String>,
    preview: preview::PullPreview,
    next_steps: Vec<String>,
    preflight: preflight::Preflight,
}

#[derive(Serialize)]
struct PullComparisonResult<'path> {
    command: &'static str,
    action: &'static str,
    schema: String,
    output: &'path Path,
    entity_count: usize,
    warnings: Vec<String>,
    preview: preview::PullPreview,
    current: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<String>,
}

#[derive(Clone, Copy)]
struct PullOptions<'argument> {
    schema: &'argument str,
    output: &'argument Path,
    mode: PullMode,
    review: bool,
    access: PullAccess,
    role: Option<&'argument str>,
    owner: Option<&'argument str>,
}

struct PreparedPull {
    output_path: PathBuf,
    schema: String,
    draft: render::Draft,
    preflight: preflight::Preflight,
}

pub(crate) fn run(project: &Path, command: &DbCommand) -> ExitCode {
    match command {
        DbCommand::Pull {
            schema,
            output,
            check,
            diff,
            review,
            access,
            role,
            owner,
        } => pull(
            project,
            PullOptions {
                schema,
                output,
                mode: if *check {
                    PullMode::Check
                } else if *diff {
                    PullMode::Diff
                } else {
                    PullMode::Create
                },
                review: *review,
                access: *access,
                role: role.as_deref(),
                owner: owner.as_deref(),
            },
        ),
    }
}

fn pull(project: &Path, options: PullOptions<'_>) -> ExitCode {
    let prepared = match prepare_pull(project, options) {
        Ok(Some(prepared)) => prepared,
        Ok(None) => return ExitCode::SUCCESS,
        Err(exit) => return exit,
    };
    if options.mode != PullMode::Create {
        return compare_draft(
            project,
            &prepared.output_path,
            prepared.schema,
            prepared.draft,
            options.mode,
        );
    }
    if let Some(parent) = prepared.output_path.parent()
        && let Err(error) = fs::create_dir_all(parent)
    {
        return write_error(&prepared.output_path, &error);
    }
    if let Err(error) =
        crate::transaction::write_new(&prepared.output_path, prepared.draft.source.as_bytes())
    {
        return write_error(&prepared.output_path, &error);
    }
    let relative = prepared
        .output_path
        .strip_prefix(project)
        .unwrap_or(&prepared.output_path);
    if crate::report::is_json() {
        let preview = preview::build(&prepared.draft);
        crate::report::success(&PullResult {
            command: "db",
            action: "pull",
            schema: prepared.schema,
            output: relative,
            entity_count: prepared.draft.entity_count,
            warnings: prepared.draft.warnings,
            preview,
            next_steps: pull_next_steps(relative),
            preflight: prepared.preflight,
        });
    } else {
        println!(
            "Created App Spec draft {} ({} entities)",
            relative.display(),
            prepared.draft.entity_count
        );
        preview::print(&prepared.draft);
        preflight::print(&prepared.preflight);
        for warning in &prepared.draft.warnings {
            crate::report::warning("AS6306", crate::report::ErrorCategory::Database, warning);
        }
        println!("Next:");
        for step in pull_next_steps(relative) {
            println!("  {step}");
        }
    }
    ExitCode::SUCCESS
}

fn pull_next_steps(output: &Path) -> Vec<String> {
    vec![
        format!("Review access rules and warnings in {}, then add the draft to appstruct.yaml includes.", output.display()),
        "Run appstruct check, appstruct generate, then appstruct migrate plan to review required columns and module tables.".to_owned(),
        "For a fresh development database, apply reviewed migrations and run appstruct doctor, then appstruct dev.".to_owned(),
        "For an existing database, align required structure, then preview appstruct migrate baseline; use --accept only after it matches. Read the Existing PostgreSQL guide.".to_owned(),
    ]
}

fn prepare_pull(
    project: &Path,
    options: PullOptions<'_>,
) -> Result<Option<PreparedPull>, ExitCode> {
    if options.review && (crate::report::is_json() || !review::interactive()) {
        return Err(crate::report::fail(
            "AS6310",
            crate::report::ErrorCategory::Project,
            "db pull --review requires a terminal and text output",
            crate::report::ExitClass::Usage,
        ));
    }
    if let Err(message) = validate_schema_name(options.schema) {
        return Err(crate::report::fail(
            "AS6301",
            crate::report::ErrorCategory::Configuration,
            message,
            crate::report::ExitClass::Usage,
        ));
    }
    let configured_access = match resolve_access(options.access, options.role, options.owner) {
        Ok(access) => access,
        Err(message) => {
            return Err(crate::report::fail(
                "AS6312",
                crate::report::ErrorCategory::Configuration,
                message,
                crate::report::ExitClass::Usage,
            ));
        }
    };
    let output_path = match output::resolve(project, options.output, options.mode) {
        Ok(path) => path,
        Err(error) => {
            return Err(crate::report::fail(
                "AS6302",
                crate::report::ErrorCategory::Project,
                error.to_string(),
                crate::report::ExitClass::Usage,
            ));
        }
    };
    let environment = match crate::environment::ProjectEnvironment::load(project) {
        Ok(environment) => environment,
        Err(error) => {
            return Err(crate::report::fail(
                "AS6303",
                crate::report::ErrorCategory::Configuration,
                format!("cannot load project environment: {error}"),
                crate::report::ExitClass::Environment,
            ));
        }
    };
    let Some(database_url) = environment.get("DATABASE_URL") else {
        return Err(crate::report::fail(
            "AS6304",
            crate::report::ErrorCategory::Configuration,
            "DATABASE_URL is required for db pull",
            crate::report::ExitClass::Environment,
        ));
    };
    let inspection = match inspect_database_schema(&database_url, options.schema) {
        Ok(inspection) => inspection,
        Err(error) => {
            return Err(crate::report::fail(
                "AS6305",
                crate::report::ErrorCategory::Database,
                error.to_string(),
                crate::report::ExitClass::Database,
            ));
        }
    };
    let (selected, access) = if options.review {
        match review_schema(inspection.clone()) {
            Ok(Some((selected, selected_access))) => (selected, selected_access),
            Ok(None) => return Ok(None),
            Err(exit) => return Err(exit),
        }
    } else {
        (inspection.clone(), configured_access)
    };
    let draft = render::render_with_access(&selected, &access);
    let preflight = preflight::build(project, options.output, &draft, &inspection, &database_url);
    if options.review {
        preflight::print(&preflight);
        match review::confirm_write() {
            Ok(true) => {}
            Ok(false) => {
                println!("Import cancelled; no draft was written");
                return Ok(None);
            }
            Err(error) => return Err(write_error(&output_path, &error)),
        }
    }
    Ok(Some(PreparedPull {
        output_path,
        schema: inspection.name,
        draft,
        preflight,
    }))
}

fn review_schema(
    inspection: appstruct_migrate::IntrospectedSchema,
) -> Result<Option<(appstruct_migrate::IntrospectedSchema, render::AccessMode)>, ExitCode> {
    match review::select(inspection) {
        Ok(Some((selected, access))) => Ok(Some((selected, access))),
        Ok(None) => {
            println!("Import cancelled; no draft was written");
            Ok(None)
        }
        Err(error) => Err(crate::report::fail(
            "AS6311",
            crate::report::ErrorCategory::Project,
            format!("cannot review database tables: {error}"),
            crate::report::ExitClass::Usage,
        )),
    }
}

fn compare_draft(
    project: &Path,
    output_path: &Path,
    schema: String,
    draft: render::Draft,
    mode: PullMode,
) -> ExitCode {
    let existing = match fs::read_to_string(output_path) {
        Ok(existing) => existing,
        Err(error) => return read_error(output_path, &error),
    };
    let current = existing == draft.source;
    let relative = output_path.strip_prefix(project).unwrap_or(output_path);
    if mode == PullMode::Check && !current {
        return crate::report::fail(
            "AS6308",
            crate::report::ErrorCategory::Validation,
            format!(
                "App Spec draft `{}` differs from PostgreSQL schema `{schema}`",
                relative.display()
            ),
            crate::report::ExitClass::Validation,
        );
    }
    let diff = (mode == PullMode::Diff && !current)
        .then(|| render_diff(relative, &existing, &draft.source));
    if crate::report::is_json() {
        let preview = preview::build(&draft);
        crate::report::success(&PullComparisonResult {
            command: "db",
            action: if mode == PullMode::Check {
                "check"
            } else {
                "diff"
            },
            schema,
            output: relative,
            entity_count: draft.entity_count,
            warnings: draft.warnings,
            preview,
            current,
            diff,
        });
    } else {
        for warning in &draft.warnings {
            crate::report::warning("AS6306", crate::report::ErrorCategory::Database, warning);
        }
        if let Some(diff) = diff {
            print!("{diff}");
        } else {
            println!("App Spec draft {} is current", relative.display());
        }
    }
    ExitCode::SUCCESS
}

fn render_diff(path: &Path, existing: &str, expected: &str) -> String {
    TextDiff::from_lines(existing, expected)
        .unified_diff()
        .header(&path.display().to_string(), "live PostgreSQL schema")
        .to_string()
}

fn validate_schema_name(schema: &str) -> Result<(), String> {
    if schema.is_empty() || schema.trim() != schema {
        return Err(
            "database schema must be a non-empty name without surrounding whitespace".into(),
        );
    }
    if schema.len() > 63 || schema.chars().any(char::is_control) {
        return Err(
            "database schema must be at most 63 bytes and contain no control characters".into(),
        );
    }
    Ok(())
}

fn write_error(path: &Path, error: &std::io::Error) -> ExitCode {
    crate::report::fail(
        "AS6307",
        crate::report::ErrorCategory::Transaction,
        format!("cannot write App Spec draft `{}`: {error}", path.display()),
        crate::report::ExitClass::Environment,
    )
}

fn read_error(path: &Path, error: &std::io::Error) -> ExitCode {
    crate::report::fail(
        "AS6309",
        crate::report::ErrorCategory::Transaction,
        format!("cannot read App Spec draft `{}`: {error}", path.display()),
        crate::report::ExitClass::Environment,
    )
}

#[cfg(test)]
mod tests;