~nickbp/originz

ref: d94f181c5fbfdf0f62b40ea46d3f301f4ec681e5 originz/examples/update_fbs.rs -rw-r--r-- 24.1 KiB
d94f181cNick Parker Backport current benchmark to older code 1 year, 8 months ago
                                                                                
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
#![deny(warnings)]
// Updates flatbuffers: fbs/*.fbs and src/fbs/*.rs. Executed via update-fbs.sh.

use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::{env, fs};

use anyhow::{bail, Context, Result};
use futures::future;
use hyper::{Body, Client, Method};
use hyper_rustls::HttpsConnector;
use tracing::{self, info};

use kapiti::{http::Fetcher, logging};

#[tokio::main]
async fn main() -> Result<()> {
    logging::init_logging();

    let fbs_specs_dir = Path::new("fbs");
    let csv_dir = fbs_specs_dir.join("enum-specs");
    let sections_csv_path = csv_dir.join("sections.csv");
    let sections = csv::Reader::from_path(&sections_csv_path)
        .with_context(|| format!("Failed to open {:?}", sections_csv_path))?
        .deserialize()
        .map(|v| v.expect("Failed to deserialize sections.csv entry"))
        .collect();

    match env::args().nth(1) {
        Some(val) => {
            if val == "--fetch" {
                info!("Fetching csvs (--fetch):");
                download_csvs(&csv_dir, &sections).await?;
            } else {
                panic!("Unrecognized arg: {}", val);
            }
        }
        None => info!("Skipping csv download (no --fetch)"),
    }

    // Set up path for generated rust code (both ours and flatc output)
    let rs_dir = Path::new("src").join("fbs");
    if fs::metadata(&rs_dir).is_ok() {
        // Clean any existing content.
        fs::remove_dir_all(&rs_dir)
            .with_context(|| format!("Failed to delete output dir: {:?}", rs_dir))?;
    }
    // Not needed by flatc, but we want it for writing dns_enums_conv.rs
    fs::create_dir_all(&rs_dir)
        .with_context(|| format!("Failed to create output dir: {:?}", rs_dir))?;

    let enums_conv_rs = rs_dir.join("dns_enums_conv.rs");

    // Generate ROOT/fbs/dns_enums.fbs and ROOT/src/fbs/dns_enums_conv.rs from CSV specs in ROOT/fbs/enum-specs/*
    generate_enums_fbs(fbs_specs_dir, &enums_conv_rs, &csv_dir, &sections)?;

    // Find all .fbs files in ROOT/fbs/, to be used for codegen and then mod.rs afterwards
    let mut fbs_files = fs::read_dir(fbs_specs_dir)
        .with_context(|| format!("Failed to read input dir: {:?}", fbs_specs_dir))?
        .map(|entry| {
            entry
                .expect(
                    format!("Failed to resolve entry in input dir: {:?}", fbs_specs_dir).as_str(),
                )
                .path()
        })
        .filter(|pathbuf| pathbuf.extension().map_or(false, |ext| ext == "fbs"))
        .collect::<Vec<PathBuf>>();
    fbs_files.sort();

    // Generate ROOT/src/fbs/*.rs from ROOT/fbs/*.fbs
    let status = flatc(&fbs_files, &rs_dir)?;
    if !status.success() {
        bail!("Failed to execute flatc");
    }

    // Generate ROOT/src/fbs/mod.rs
    generate_modrs(&rs_dir, &fbs_files, enums_conv_rs)?;

    Ok(())
}

#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct SectionsRecord {
    Filename: String,
    EnumName: String,
    DataType: String,
}

/// Redownloads CSV specs from IANA. This is then consumed by this tool.
async fn download_csvs(csv_dir: &Path, sections: &Vec<SectionsRecord>) -> Result<()> {
    let fetcher = Fetcher::new(1024 * 1024, Some("text/csv".to_string()));
    let client = Client::builder().build::<HttpsConnector<_>, Body>(HttpsConnector::new());

    let mut responses = future::try_join_all(sections.into_iter().map(|section| {
        let url = format!(
            "https://www.iana.org/assignments/dns-parameters/{}",
            section.Filename.as_str()
        );
        let path = csv_dir.join(&section.Filename);
        info!("- Downloading {:?} to {:?}", url, path);

        let req = fetcher
            .build_request(&Method::GET, &url)
            .expect("Failed to build HTTP request");
        client.request(req)
    }))
    .await
    .with_context(|| "Failed to download spec sections")?;

    let request_count = sections.len();
    for i in 0..request_count {
        let mut resp = responses
            .get_mut(i)
            .with_context(|| format!("Missing response index {}", i))?;
        let section = sections
            .get(i)
            .with_context(|| format!("Missing section index {}", i))?;
        let path = csv_dir.join(&section.Filename);

        info!(
            "[{}/{}] {:?} status: {}",
            i + 1,
            request_count,
            section.Filename,
            resp.status()
        );
        let mut outfile = File::create(&path.as_path())?;
        fetcher
            .write_response(&section.Filename, &mut outfile, &mut resp)
            .await?;
    }

    Ok(())
}

/// Generates dns_enums.fbs from IANA csv spec files. This is then consumed by flatc.
fn generate_enums_fbs(
    fbs_specs_dir: &Path,
    enums_conv_rs: &Path,
    csv_dir: &Path,
    sections: &Vec<SectionsRecord>,
) -> Result<()> {
    let fbspath = fbs_specs_dir.join("dns_enums.fbs");
    let mut fbsfile =
        fs::File::create(&fbspath).with_context(|| "Failed to create dns_enums.fbs file")?;
    let mut convfile = fs::File::create(&enums_conv_rs)
        .with_context(|| "Failed to create dns_enums_conv.rs file")?;
    info!("Generating {:?} and {:?}", &fbspath, enums_conv_rs);
    fbsfile.write(b"// This file is autogenerated by update_fbs.rs. Don't touch.\n")?;

    convfile.write(b"// This file is autogenerated by update_fbs.rs. Don't touch.\n\n")?;
    convfile.write(b"use super::dns_enums_generated;\n")?;

    // Iterate over entries in input, open their respective files
    for section in sections {
        let enum_csv_path = csv_dir.join(&section.Filename);
        info!("- Parsing {:?} from {:?}", section.EnumName, enum_csv_path);
        let entries = match section.EnumName.as_str() {
            // Rather than trying to make everything perfectly generic,
            // just have per-file/entry tweaks/cleanup via separate functions.
            "ResourceClass" => generate_resourceclass_enum(enum_csv_path)?,
            "ResourceType" => generate_resourcetype_enum(enum_csv_path)?,
            "OpCode" => generate_opcode_enum(enum_csv_path)?,
            "ResponseCode" => generate_responsecode_enum(enum_csv_path)?,
            "OPTOptionCode" => generate_optoptioncode_enum(enum_csv_path)?,
            &_ => panic!("Unsupported enum: {}", section.EnumName),
        };

        // Write enum entries to enums.fbs
        fbsfile
            .write(format!("\nenum {} : {} {{\n", section.EnumName, section.DataType).as_bytes())?;
        for entry in &entries {
            if entry.doc {
                fbsfile.write(format!("\n  /// {}\n", entry.comment1).as_bytes())?;
                if let Some(c2) = &entry.comment2 {
                    fbsfile.write(format!("  /// {}\n", c2).as_bytes())?;
                }
            } else {
                fbsfile.write(format!("\n  // {}\n", entry.comment1).as_bytes())?;
                if let Some(c2) = &entry.comment2 {
                    fbsfile.write(format!("  // {}\n", c2).as_bytes())?;
                }
            }
            if let Some(n) = &entry.name {
                if let Some(i) = &entry.intval {
                    fbsfile.write(format!("  {} = {},\n", n, i).as_bytes())?;
                } else {
                    panic!("Missing entry.intval for entry.name={}", n)
                }
            }
        }
        fbsfile.write(b"\n}\n")?;

        // Write enum entries to enum_conv.rs

        // string -> enum
        convfile.write(
            format!(
                "\npub fn {}_str(s: String) -> Option<dns_enums_generated::{}> {{\n",
                section.EnumName.to_lowercase(),
                section.EnumName
            )
            .as_bytes(),
        )?;
        convfile.write(b"    match s.as_str() {\n")?;
        for entry in &entries {
            if let Some(n) = &entry.name {
                convfile.write(
                    format!(
                        "        \"{}\" => Some(dns_enums_generated::{}::{}),\n",
                        n, section.EnumName, n
                    )
                    .as_bytes(),
                )?;
            }
        }
        convfile.write(b"        _ => None\n")?;
        convfile.write(b"    }\n")?;
        convfile.write(b"}\n")?;

        // usize -> enum
        convfile.write(
            format!(
                "\npub fn {}_int(i: usize) -> Option<dns_enums_generated::{}> {{\n",
                section.EnumName.to_lowercase(),
                section.EnumName
            )
            .as_bytes(),
        )?;
        convfile.write(b"    match i {\n")?;
        for entry in &entries {
            if let Some(n) = &entry.name {
                if let Some(i) = &entry.intval {
                    convfile.write(
                        format!(
                            "        {} => Some(dns_enums_generated::{}::{}),\n",
                            i, section.EnumName, n
                        )
                        .as_bytes(),
                    )?;
                } else {
                    panic!("Missing entry.intval for entry.name={}", n)
                }
            }
        }
        convfile.write(b"        _ => None\n")?;
        convfile.write(b"    }\n")?;
        convfile.write(b"}\n")?;
    }
    Ok(())
}

struct EnumEntry {
    /// Whether to use 2 slashes (false) or 3 slashes (true) on comment1 and comment2
    doc: bool,
    /// First comment line
    comment1: String,
    /// Second comment line
    comment2: Option<String>,
    /// The name of the enum, or None (comment-only)
    name: Option<String>,
    /// The int value of the enum, ignored if name=None
    intval: Option<String>,
}

#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct ResourceClassRecord {
    Decimal: String,
    Name: String,
    Reference: String,
}

fn generate_resourceclass_enum(enum_csv_path: PathBuf) -> Result<Vec<EnumEntry>> {
    let mut entries = Vec::new();
    for record in csv::Reader::from_path(&enum_csv_path)
        .with_context(|| format!("Failed to open enum CSV file: {:?}", enum_csv_path))?
        .deserialize()
    {
        let record: ResourceClassRecord = record
            .with_context(|| format!("Failed to read/deserialize CSV file: {:?}", enum_csv_path))?;
        let ignored = record.Decimal.contains('-') || record.Name == "Unassigned";

        // Enum comment: Name and/or reference
        let mut comment1 = record.Name.clone();
        if !record.Reference.is_empty() {
            comment1.push_str(format!(" {}", record.Reference.replace('\n', " ")).as_str());
        }

        if ignored {
            // The entry is for an unassigned value or range, list as a comment
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: Some(record.Decimal),
                name: None,
                intval: None,
            });
        } else {
            // The entry is for a single value (which may be "reserved"...)
            let name = match record.Name.as_str() {
                // When the value is reserved, include the number in the enum name
                "Reserved" => format!("RESERVED_{}", record.Decimal),
                // Manually make these names usable
                "QCLASS NONE" => "NONE".to_string(),
                "QCLASS * (ANY)" => "ANY".to_string(),
                // All others: Use the first word, capitalized
                _ => match record.Name.split_ascii_whitespace().next() {
                    Some(first_word) => first_word.to_uppercase(),
                    None => panic!("Missing name '{}' in {:?}", record.Name, enum_csv_path),
                },
            };
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: None,
                name: Some(format!("CLASS_{}", name)),
                intval: Some(record.Decimal),
            });
        }
    }
    Ok(entries)
}

#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct ResourceTypeRecord {
    Value: String,
    TYPE: String,
    Meaning: String,
    Reference: String,
}

fn generate_resourcetype_enum(enum_csv_path: PathBuf) -> Result<Vec<EnumEntry>> {
    let mut entries = Vec::new();
    for record in csv::Reader::from_path(&enum_csv_path)
        .with_context(|| format!("Failed to open enum CSV file: {:?}", enum_csv_path))?
        .deserialize()
    {
        let record: ResourceTypeRecord = record
            .with_context(|| format!("Failed to read/deserialize CSV file: {:?}", enum_csv_path))?;
        let ignored = record.Value.contains('-') || record.TYPE == "Unassigned";

        // Enum comment: Type or Reference+Meaning
        let mut comment1: String;
        if record.Reference.is_empty() && record.Meaning.is_empty() {
            // No additional info, just write the "TYPE" (usually something like 'Unassigned')
            comment1 = record.TYPE.clone();
        } else {
            // Instead of the TYPE, write the Meaning and/or Reference
            comment1 = String::new();
            if !record.Meaning.is_empty() {
                comment1.push_str(record.Meaning.replace('\n', " ").as_str());
            }
            if !record.Reference.is_empty() {
                if !record.Meaning.is_empty() {
                    comment1.push(' ');
                }
                comment1.push_str(record.Reference.replace('\n', " ").as_str())
            }
        }

        if ignored {
            // The entry is for an unassigned value or range, list as a comment
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: Some(record.Value),
                name: None,
                intval: None,
            });
        } else {
            // The entry is for a single value (which may be "reserved"...)
            let name = match record.TYPE.as_str() {
                // When the value is reserved, include the number in the enum name
                "Reserved" => format!("RESERVED_{}", record.Value),
                // Manually make these names usable
                "*" => "ANY".to_string(),
                // All others: Use the type as-is
                _ => match record.Meaning.contains("OBSOLETE") {
                    true => record.TYPE.replace('-', "_") + "_OBSOLETE",
                    false => record.TYPE.replace('-', "_"),
                },
            };
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: None,
                name: Some(format!("TYPE_{}", name)),
                intval: Some(record.Value),
            });
        }
    }
    Ok(entries)
}

#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct OpCodeRecord {
    OpCode: String,
    Name: String,
    Reference: String,
}

fn generate_opcode_enum(enum_csv_path: PathBuf) -> Result<Vec<EnumEntry>> {
    let mut entries = Vec::new();
    for record in csv::Reader::from_path(&enum_csv_path)
        .with_context(|| format!("Failed to open enum CSV file: {:?}", enum_csv_path))?
        .deserialize()
    {
        let record: OpCodeRecord = record
            .with_context(|| format!("Failed to read/deserialize CSV file: {:?}", enum_csv_path))?;
        let ignored = record.OpCode.contains('-') || record.Name == "Unassigned";

        // Enum comment: Name and/or reference
        let mut comment1 = record.Name.clone();
        if !record.Reference.is_empty() {
            comment1.push_str(format!(" {}", record.Reference.replace('\n', " ")).as_str());
        }

        if ignored {
            // The entry is for an unassigned value or range, list as a comment
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: Some(record.OpCode),
                name: None,
                intval: None,
            });
        } else {
            // The entry is for a single value (which may be "reserved"...)
            let name = match record.Name.as_str() {
                // Manually make these names usable
                "DNS Stateful Operations (DSO)" => "DSO".to_string(),
                "IQuery  (Inverse Query, OBSOLETE)" => "IQUERY_OBSOLETE".to_string(),
                // All others: Use the name as-is
                _ => record.Name.to_uppercase(),
            };
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: None,
                name: Some(format!("OP_{}", name)),
                intval: Some(record.OpCode),
            });
        }
    }
    Ok(entries)
}

// RCODE,Name,Description,Reference
#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct ResponseCodeRecord {
    RCODE: String,
    Name: String,
    Description: String,
    Reference: String,
}

fn generate_responsecode_enum(enum_csv_path: PathBuf) -> Result<Vec<EnumEntry>> {
    let mut entries = Vec::new();
    for record in csv::Reader::from_path(&enum_csv_path)
        .with_context(|| format!("Failed to open enum CSV file: {:?}", enum_csv_path))?
        .deserialize()
    {
        let record: ResponseCodeRecord = record
            .with_context(|| format!("Failed to read/deserialize CSV file: {:?}", enum_csv_path))?;
        let ignored = record.RCODE.contains('-') || record.Name == "Unassigned";

        // Enum comment: Name and/or description/reference
        let mut comment1 = record.Name.clone();
        if !record.Description.is_empty() {
            comment1.push_str(format!(": {}", record.Description.replace('\n', " ")).as_str());
        }
        if !record.Reference.is_empty() {
            comment1.push_str(format!(" {}", record.Reference.replace('\n', " ")).as_str());
        }

        if ignored {
            // The entry is for an unassigned value or range, list as a comment
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: Some(record.RCODE),
                name: None,
                intval: None,
            });
        } else if record.Description == "Not Authorized" {
            // Don't print out a duplicate RCODE=9 for both versions of "NotAuth". Let the first one handle it.
            continue;
        } else if record.Name == "BADSIG" {
            // Don't print out a duplicate RCODE=16 value for both BADVERS+BADSIG. Let BADVERS handle it.
            continue;
        } else {
            // The entry is for a single value (which may be "reserved"...)
            let name = match record.Name.as_str() {
                // Manually make these names usable
                "Reserved, can be allocated by Standards Action" => "RESERVED_65535".to_string(),
                // BADVERS and BADSIG share RCODE=16, so include both in the name. We skip BADSIG above.
                "BADVERS" => "BADVERS_BADSIG".to_string(),
                // All others: Use the name as-is
                _ => record.Name.to_uppercase(),
            };
            let comment2 = match record.Name.as_str() {
                "NotAuth" => Some(String::from("NotAuth: Not Authorized [RFC2845]")),
                "BADVERS" => Some(String::from("BADSIG: TSIG Signature Failure [RFC2845]")),
                _ => None,
            };
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2,
                name: Some(format!("RESPONSE_{}", name)),
                intval: Some(record.RCODE),
            });
        }
    }
    Ok(entries)
}

// RCODE,Name,Description,Reference
#[allow(non_snake_case)]
#[derive(serde::Deserialize)]
struct OPTOptionCodeRecord {
    Value: String,
    Name: String,
    Status: String,
    Reference: String,
}

fn generate_optoptioncode_enum(enum_csv_path: PathBuf) -> Result<Vec<EnumEntry>> {
    let mut entries = Vec::new();
    for record in csv::Reader::from_path(&enum_csv_path)
        .with_context(|| format!("Failed to open enum CSV file: {:?}", enum_csv_path))?
        .deserialize()
    {
        let record: OPTOptionCodeRecord = record
            .with_context(|| format!("Failed to read/deserialize CSV file: {:?}", enum_csv_path))?;
        let ignored = record.Value.contains('-') || record.Name == "Unassigned";

        // Enum comment: Name and/or status/reference
        let mut comment1 = record.Name.clone();
        if !record.Status.is_empty() {
            comment1.push_str(format!(": {}", record.Status.replace('\n', " ")).as_str());
        }
        if !record.Reference.is_empty() {
            comment1.push_str(format!(" {}", record.Reference.replace('\n', " ")).as_str());
        }

        if ignored {
            // The entry is for an unassigned value or range, list as a comment
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: Some(record.Value),
                name: None,
                intval: None,
            });
        } else {
            // The entry is for a single value (which may be "reserved"...)
            let name = match record.Value.as_str() {
                // Override the csv-defined name of "Reserved" for the zero value
                // "EXTENDED-RCODE value 0 indicates that an unextended RCODE is in use"
                "0" => "NONE".to_string(),
                _ => match record.Name.as_str() {
                    // When the value is reserved, include the number in the enum name
                    "Reserved" => format!("RESERVED_{}", record.Value),
                    // All others: Use the type as-is (but with '-' and ' ' cleaned up)
                    _ => record
                        .Name
                        .to_uppercase()
                        .replace('-', "_")
                        .replace(' ', "_"),
                },
            };
            entries.push(EnumEntry {
                doc: !ignored,
                comment1,
                comment2: None,
                name: Some(format!("OPTOPTION_{}", name)),
                intval: Some(record.Value),
            });
        }
    }
    Ok(entries)
}

/// Generates rust framebuffer code from <spec_files> to <output_dir>/*.rs.
fn flatc(spec_files: &Vec<PathBuf>, output_dir: &Path) -> Result<ExitStatus> {
    info!("Running flatc: {:?} => {:?}", spec_files, output_dir);

    // Before starting, check that the user has flatc installed
    // As a side effect the flatbuffers version is written to stdout, but that may be handy for debugging someday.

    if let Err(_) = Command::new("flatc").arg("--version").status() {
        bail!("Unable to run 'flatc --version'. Ensure that flatbuffers is installed.");
    }

    Command::new("flatc")
        .arg("-o")
        .arg(
            output_dir
                .to_str()
                .with_context(|| "Unable to convert output dir to string")?,
        )
        .arg("--rust")
        .args(spec_files.iter().map(|p| {
            p.to_str()
                .expect("Failed to convert flatc input path to string")
        }))
        .status()
        .with_context(|| format!("Failed to run 'flatc -o {:?} --rust [...]'", output_dir))
}

/// Generates output/mod.rs so that the output package can be consumed by the rest of the project.
fn generate_modrs(output: &Path, fbs_files: &Vec<PathBuf>, enums_conv_rs: PathBuf) -> Result<()> {
    let modrs_path = output.join("mod.rs");
    info!("Generating {:?}", modrs_path);
    let mut modrs =
        fs::File::create(&modrs_path).with_context(|| "Failed to create mod.rs file")?;
    modrs.write(b"// This file is autogenerated by update_fbs.rs. Don't touch.\n\n")?;

    for path in fbs_files {
        if let Some(filestem) = path.file_stem() {
            let filestem = filestem
                .to_str()
                .with_context(|| format!("Failed to format path as utf-8: {:?}", path))?;
            modrs.write(
                format!(
                    "#[allow(unused_imports, dead_code)]\npub mod {}_generated;\n",
                    filestem
                )
                .as_bytes(),
            )?;
        }
    }

    modrs.write(b"\n")?;

    // Omit the #[allow] and the "_generated" suffix when writing the dns_enums_conv entry
    if let Some(filestem) = enums_conv_rs.file_stem() {
        let filestem = filestem
            .to_str()
            .with_context(|| format!("Failed to format path as utf-8: {:?}", enums_conv_rs))?;
        modrs.write(format!("pub mod {};\n", filestem).as_bytes())?;
    }

    Ok(())
}