reflectapi-cli 0.17.6

CLI for reflectapi
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
use anyhow::Context;
use clap::{Parser, Subcommand, ValueEnum};
use std::collections::BTreeSet;
use std::io::Write;
use std::path::{Path, PathBuf};

const GENERATED_MARKER: &str = "This file was generated by reflectapi-cli";
const GENERATED_MANIFEST: &str = ".reflectapi-generated-files";

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Turn debugging information on
    #[arg(short, long, action = clap::ArgAction::Count)]
    debug: u8,

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

#[derive(Subcommand)]
enum Commands {
    /// Generates code for typescript, rust, python or openapi from a reflectapi schema
    Codegen {
        /// Path to the source reflect schema
        #[arg(short, long, value_name = "FILE")]
        schema: Option<PathBuf>,

        /// Path to the target directory for the generated code
        #[arg(short, long, value_name = "FILE")]
        output: Option<PathBuf>,

        /// Language to generate code for
        #[arg(short, long)]
        language: Language,

        /// Specific to Rust codegen only.
        /// A module which does not need types generated for a client
        /// because that module is a 3rd party or open source crate
        /// which can be used by the client code directly as a dependency.
        /// Multiple modules can be specified.
        #[arg(long, value_delimiter = ',')]
        shared_modules: Option<Vec<String>>,

        #[arg(short, long, value_delimiter = ',')]
        include_tags: Vec<String>,

        #[arg(short, long, value_delimiter = ',')]
        exclude_tags: Vec<String>,

        /// Typecheck the generated code
        #[arg(short, long, default_value = "false")]
        typecheck: bool,

        /// Format the generated code
        #[arg(
            short,
            long,
            default_value_t = true,
            default_missing_value = "true",
            num_args = 0..=1,
            require_equals = true
        )]
        format: bool,

        /// Instrument the generated code with tracing
        #[arg(short = 'I', long, default_value = "false")]
        instrument: bool,

        // Python-specific options
        /// Package name for the generated Python client
        #[arg(long, default_value = "api_client")]
        python_package_name: String,

        /// Generate async client for Python (default: true)
        #[arg(long, default_value = "true")]
        python_async: bool,

        /// Generate sync client for Python (default: false)
        #[arg(long, default_value = "false")]
        python_sync: bool,

        /// Generate testing utilities for Python (default: false)
        #[arg(long, default_value = "false")]
        python_testing: bool,
    },
    /// Documentation subcommands
    #[command(subcommand)]
    Doc(DocSubcommand),
}

#[derive(Subcommand)]
enum DocSubcommand {
    /// Serve documentation for the reflectapi schema
    Open {
        /// Port to serve the docs on
        #[arg(short, long, default_value = "8080")]
        port: u16,

        /// Path to the source reflectapi schema
        #[arg(default_value = "reflectapi.json")]
        path: PathBuf,
    },
}

#[derive(ValueEnum, Clone, Debug, PartialEq)]
enum Language {
    Typescript,
    Rust,
    Python,
    Openapi,
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Doc(doc) => match doc {
            DocSubcommand::Open { port, path } => {
                let mut path = path.canonicalize()?;
                if path.is_dir() {
                    path.push("reflectapi.json");
                }

                let schema: reflectapi::Schema = serde_json::from_reader(std::fs::File::open(
                    &path,
                )?)
                .context("Failed to parse schema file as JSON into reflectapi::Schema object")?;

                let addr = format!("0.0.0.0:{port}");
                eprintln!("Serving {} on http://{addr}", path.display());
                let openapi = reflectapi::codegen::openapi::Spec::from(&schema);
                rouille::start_server(addr, move |request| {
                    rouille::router!(request,
                        (GET) (/) => { rouille::Response::html(include_str!("../redoc.html")) },
                        (GET) (/openapi) => { rouille::Response::json(&openapi) },
                        _ => rouille::Response::empty_404()
                    )
                })
            }
        },
        Commands::Codegen {
            schema,
            output,
            language,
            shared_modules,
            include_tags,
            exclude_tags,
            typecheck,
            format,
            instrument,
            python_package_name,
            python_async,
            python_sync,
            python_testing,
        } => {
            let include_tags = BTreeSet::from_iter(include_tags);
            let exclude_tags = BTreeSet::from_iter(exclude_tags);

            let schema_path = schema.unwrap_or(std::path::PathBuf::from("reflectapi.json"));
            let schema_as_json = std::fs::read_to_string(schema_path.clone())
                .context(format!("Failed to read schema file: {schema_path:?}"))?;
            let schema: reflectapi::Schema = serde_json::from_str(&schema_as_json)
                .context("Failed to parse schema file as JSON into reflectapi::Schema object")?;

            let files: std::collections::BTreeMap<String, String> = match language {
                Language::Typescript => reflectapi::codegen::typescript::generate(
                    schema,
                    reflectapi::codegen::typescript::Config::default()
                        .format(format)
                        .typecheck(typecheck)
                        .include_tags(include_tags)
                        .exclude_tags(exclude_tags),
                )?,
                Language::Rust => {
                    let content = reflectapi::codegen::rust::generate(
                        schema,
                        reflectapi::codegen::rust::Config::default()
                            .format(format)
                            .typecheck(typecheck)
                            .instrument(instrument)
                            .include_tags(include_tags)
                            .exclude_tags(exclude_tags)
                            .shared_modules(
                                shared_modules.unwrap_or_default().into_iter().collect(),
                            ),
                    )?;
                    let mut files = std::collections::BTreeMap::new();
                    files.insert("generated.rs".to_string(), content);
                    files
                }
                Language::Python => {
                    let config = reflectapi::codegen::python::Config {
                        package_name: python_package_name,
                        generate_async: python_async,
                        generate_sync: python_sync,
                        generate_testing: python_testing,
                        format,
                        base_url: None,
                    };
                    reflectapi::codegen::python::generate_files(schema, &config)?
                }
                Language::Openapi => {
                    let content = reflectapi::codegen::openapi::generate(
                        &schema,
                        reflectapi::codegen::openapi::Config::default()
                            .include_tags(include_tags)
                            .exclude_tags(exclude_tags),
                    )?;
                    let mut files = std::collections::BTreeMap::new();
                    files.insert("openapi.json".to_string(), content);
                    files
                }
            };

            // The "main" emitted file per language. Used both for
            // stdout selection (--output -) and for matching a
            // file-shaped --output path against the codegen output.
            let primary_filename = match language {
                Language::Typescript => "generated.ts",
                Language::Rust => "generated.rs",
                Language::Python => "generated.py",
                Language::Openapi => "openapi.json",
            };

            if output == Some(std::path::PathBuf::from("-")) {
                // Print the language's primary file, not the
                // alphabetically-first one — for TS that would be
                // generated.transport.ts (sibling), for Python it
                // would be __init__.py.
                if let Some(content) = files.get(primary_filename) {
                    println!("{content}");
                } else if let Some(content) = files.values().next() {
                    println!("{content}");
                }
                return Ok(());
            }

            let output_path = output.unwrap_or_else(|| std::path::PathBuf::from("./"));

            // Decide whether `output_path` names a single file or a
            // directory. "File" means the path's filename matches one
            // of the codegen-emitted filenames AND the path doesn't
            // already exist as a directory; everything else is a
            // directory (whether it exists yet or not).
            //
            // This matters for two cases:
            //   --output ./clients/python/  → directory, write all files inside
            //   --output ./generated.ts     → file path: write generated.ts there
            //                                 and place siblings (e.g.
            //                                 generated.transport.ts) next to it
            //   --output ./brand-new-dir    → fresh directory, create + write
            let primary_name_in_path = output_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default();
            let looks_like_file = files.contains_key(primary_name_in_path)
                && !output_path.is_dir()
                && !output_path.to_string_lossy().ends_with('/');

            if !looks_like_file {
                std::fs::create_dir_all(&output_path).context(format!(
                    "Failed to create output directory: {output_path:?}"
                ))?;
                let expected_files = generated_file_set(files.keys())?;
                cleanup_stale_generated_files(&output_path, &expected_files, &language)?;
                for (filename, content) in &files {
                    write_file(
                        &output_path.join(generated_relative_path(filename)?),
                        content,
                    )?;
                }
                write_generated_manifest(&output_path, &expected_files)?;
            } else {
                let parent = parent_or_dot(&output_path);
                std::fs::create_dir_all(&parent)
                    .context(format!("Failed to create output directory: {parent:?}"))?;
                for (filename, content) in &files {
                    let dest = if filename == primary_name_in_path {
                        output_path.clone()
                    } else {
                        parent.join(generated_relative_path(filename)?)
                    };
                    write_file(&dest, content)?;
                }
            }
            Ok(())
        }
    }
}

fn generated_file_set<'a>(
    filenames: impl Iterator<Item = &'a String>,
) -> anyhow::Result<BTreeSet<PathBuf>> {
    filenames
        .map(|filename| generated_relative_path(filename).map(Path::to_path_buf))
        .collect()
}

fn cleanup_stale_generated_files(
    output_dir: &Path,
    expected_files: &BTreeSet<PathBuf>,
    language: &Language,
) -> anyhow::Result<()> {
    let manifest_path = output_dir.join(GENERATED_MANIFEST);
    let stale_candidates = if manifest_path.is_file() {
        read_generated_manifest(&manifest_path)?
    } else {
        let mut candidates = BTreeSet::new();
        collect_legacy_generated_files(output_dir, output_dir, language, &mut candidates)?;
        candidates
    };

    for relative_path in stale_candidates {
        if expected_files.contains(&relative_path) {
            continue;
        }
        let path = output_dir.join(&relative_path);
        if path.is_file() && is_generated_file(&path, language) {
            std::fs::remove_file(&path)
                .context(format!("Failed to remove stale generated file: {path:?}"))?;
            prune_empty_generated_dirs(output_dir, path.parent());
        }
    }

    Ok(())
}

fn read_generated_manifest(path: &Path) -> anyhow::Result<BTreeSet<PathBuf>> {
    let content = std::fs::read_to_string(path)
        .context(format!("Failed to read generated file manifest: {path:?}"))?;
    let mut files = BTreeSet::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        files.insert(generated_relative_path(line)?.to_path_buf());
    }
    Ok(files)
}

fn collect_legacy_generated_files(
    output_dir: &Path,
    dir: &Path,
    language: &Language,
    files: &mut BTreeSet<PathBuf>,
) -> anyhow::Result<()> {
    for entry in std::fs::read_dir(dir).context(format!("Failed to read directory: {dir:?}"))? {
        let entry = entry?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .context(format!("Failed to inspect directory entry: {path:?}"))?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            collect_legacy_generated_files(output_dir, &path, language, files)?;
            continue;
        }
        if path.file_name().and_then(|name| name.to_str()) == Some(GENERATED_MANIFEST) {
            continue;
        }
        if is_generated_file(&path, language) {
            let relative = path
                .strip_prefix(output_dir)
                .context(format!("Generated path escaped output directory: {path:?}"))?;
            files.insert(generated_relative_path(&relative.to_string_lossy())?.to_path_buf());
        }
    }
    Ok(())
}

fn is_generated_file(path: &Path, language: &Language) -> bool {
    if !matches_language_extension(path, language) {
        return false;
    }
    let Ok(content) = std::fs::read_to_string(path) else {
        return false;
    };
    content.contains(GENERATED_MARKER)
}

fn matches_language_extension(path: &Path, language: &Language) -> bool {
    let extension = path.extension().and_then(|extension| extension.to_str());
    match language {
        Language::Typescript => extension == Some("ts"),
        Language::Rust => extension == Some("rs"),
        Language::Python => extension == Some("py"),
        Language::Openapi => extension == Some("json"),
    }
}

fn prune_empty_generated_dirs(output_dir: &Path, mut dir: Option<&Path>) {
    while let Some(current) = dir {
        if current == output_dir || !current.starts_with(output_dir) {
            break;
        }
        match std::fs::remove_dir(current) {
            Ok(()) => dir = current.parent(),
            Err(_) => break,
        }
    }
}

fn write_generated_manifest(output_dir: &Path, files: &BTreeSet<PathBuf>) -> anyhow::Result<()> {
    let mut content = format!("# {GENERATED_MARKER}\n");
    content.push_str("# Relative files generated during the last reflectapi codegen run.\n");
    for file in files {
        content.push_str(&file.to_string_lossy());
        content.push('\n');
    }
    write_file(&output_dir.join(GENERATED_MANIFEST), &content)
}

fn parent_or_dot(path: &std::path::Path) -> std::path::PathBuf {
    path.parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| std::path::PathBuf::from("."))
}

fn generated_relative_path(filename: &str) -> anyhow::Result<&std::path::Path> {
    let relative_path = std::path::Path::new(filename);
    anyhow::ensure!(
        relative_path.is_relative()
            && !relative_path
                .components()
                .any(|component| matches!(component, std::path::Component::ParentDir)),
        "Generated file path must be relative and stay within output directory: {filename}"
    );
    Ok(relative_path)
}

fn write_file(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .context(format!("Failed to create output directory: {parent:?}"))?;
    }
    let mut file =
        std::fs::File::create(path).context(format!("Failed to create file: {path:?}"))?;
    file.write_all(content.as_bytes())
        .context(format!("Failed to write to file: {path:?}"))?;
    Ok(())
}