witforge-build 0.11.0

Build-script helper for compiling witforge-generated protobuf schemas with protox, prost-build, and optional pbjson-build.
Documentation
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
#![deny(missing_docs)]

//! Build-script (`build.rs`) helper for compiling `witforge`-generated `.proto` schemas with
//! `protox`, `prost-build`, and optional `pbjson-build`.
//!
//! `witforge-build` removes repetitive `build.rs` boilerplate:
//!
//! - Discovers every `.proto` file under `proto_dir` in deterministic sorted order while refusing
//!   symlinks.
//! - Emits `cargo:rerun-if-changed` directives for `proto_dir`, every subdirectory, and every
//!   discovered `.proto` file.
//! - Compiles descriptors with pure-Rust `protox` (no external `protoc` binary required) and
//!   generates Rust types via `prost-build` (plus optional `pbjson-build` behind the `pbjson`
//!   feature).
//! - Writes a consistent `prost_include.rs` include file whose module layout matches
//!   `witforge glue` for both standalone contracts (`v<major>::*`) and contracts with `deps/`
//!   (`<namespace>::<package>::v<major>::*`), without rewriting unchanged files.
//!
//! # Example
//!
//! ```no_run
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     witforge_build::compile_protos("src/generated/proto")?;
//!     Ok(())
//! }
//! ```

use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fmt::{self, Write as _};
use std::fs;
use std::path::{Component, Path, PathBuf};

use protox::prost::Message as _;

/// Default filename written inside `OUT_DIR` that includes all generated protobuf modules.
pub const DEFAULT_INCLUDE_FILE: &str = "prost_include.rs";

/// Error returned when discovering or compiling `witforge`-generated `.proto` files fails.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Failed to read a directory or file or write generated output.
    Io {
        /// The path associated with the I/O failure, if any.
        path: Option<PathBuf>,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// `OUT_DIR` was neither configured via [`Config::out_dir`] nor present in the environment.
    MissingOutDir,
    /// No `.proto` files were found under the given directory.
    NoProtoFiles(PathBuf),
    /// Refused a symlink encountered as `proto_dir` or while walking `proto_dir`.
    SymlinkRefused(PathBuf),
    /// Configured `include_file` is not a single plain filename inside `out_dir`.
    InvalidIncludeFile(PathBuf),
    /// `protox` failed to compile the `.proto` files into a `FileDescriptorSet`.
    Protox(protox::Error),
    /// `prost-build` failed to emit Rust source files from the compiled descriptors.
    Prost(std::io::Error),
    /// `pbjson-build` failed to emit proto3-JSON `serde` implementations.
    #[cfg(feature = "pbjson")]
    Pbjson(std::io::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io {
                path: Some(path),
                source,
            } => write!(f, "I/O error at {}: {source}", path.display()),
            Self::Io { path: None, source } => write!(f, "I/O error: {source}"),
            Self::MissingOutDir => write!(
                f,
                "OUT_DIR is not set; invoke from a Cargo build script or call Config::out_dir"
            ),
            Self::NoProtoFiles(dir) => {
                write!(f, "no `.proto` files found under {}", dir.display())
            }
            Self::SymlinkRefused(path) => {
                write!(f, "refusing to follow symlink {}", path.display())
            }
            Self::InvalidIncludeFile(path) => write!(
                f,
                "include_file `{}` must be a single plain filename inside out_dir",
                path.display()
            ),
            Self::Protox(err) => write!(f, "protox failed to compile protobuf schema: {err}"),
            Self::Prost(err) => write!(f, "prost-build failed: {err}"),
            #[cfg(feature = "pbjson")]
            Self::Pbjson(err) => write!(f, "pbjson-build failed: {err}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } | Self::Prost(source) => Some(source),
            Self::Protox(err) => Some(err),
            #[cfg(feature = "pbjson")]
            Self::Pbjson(err) => Some(err),
            Self::MissingOutDir
            | Self::NoProtoFiles(_)
            | Self::SymlinkRefused(_)
            | Self::InvalidIncludeFile(_) => None,
        }
    }
}

/// Summary of the files discovered and generated by [`Config::compile_protos`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct BuildOutput {
    /// Sorted `.proto` files discovered and compiled.
    pub proto_files: Vec<PathBuf>,
    /// Output directory into which generated Rust files were written.
    pub out_dir: PathBuf,
    /// Path to the generated include file (`prost_include.rs` by default), if enabled.
    pub include_file: Option<PathBuf>,
    /// Whether dependency `.proto` files were present alongside root `v<major>.proto` files.
    pub has_dependencies: bool,
    /// `cargo:rerun-if-changed=...` directives produced for `proto_dir`, subdirectories, and each
    /// `.proto` file.
    pub rerun_directives: Vec<String>,
}

/// Builder configuring how `witforge`-generated `.proto` files are compiled.
pub struct Config {
    prost: prost_build::Config,
    out_dir: Option<PathBuf>,
    include_file: Option<PathBuf>,
    file_descriptor_set_path: Option<PathBuf>,
    emit_rerun_if_changed: bool,
    #[cfg(feature = "pbjson")]
    pbjson: bool,
    #[cfg(feature = "pbjson")]
    pbjson_builder: pbjson_build::Builder,
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("Config");
        s.field("prost", &self.prost)
            .field("out_dir", &self.out_dir)
            .field("include_file", &self.include_file)
            .field("file_descriptor_set_path", &self.file_descriptor_set_path)
            .field("emit_rerun_if_changed", &self.emit_rerun_if_changed);
        #[cfg(feature = "pbjson")]
        s.field("pbjson", &self.pbjson);
        s.finish_non_exhaustive()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::new()
    }
}

impl Config {
    /// Create a default configuration that writes [`DEFAULT_INCLUDE_FILE`] to `OUT_DIR` and emits
    /// per-directory and per-file `cargo:rerun-if-changed` directives.
    #[must_use]
    pub fn new() -> Self {
        Self {
            prost: prost_build::Config::new(),
            out_dir: None,
            include_file: Some(PathBuf::from(DEFAULT_INCLUDE_FILE)),
            file_descriptor_set_path: None,
            emit_rerun_if_changed: true,
            #[cfg(feature = "pbjson")]
            pbjson: false,
            #[cfg(feature = "pbjson")]
            pbjson_builder: pbjson_build::Builder::new(),
        }
    }

    /// Override the output directory (defaults to Cargo's `OUT_DIR` environment variable).
    #[must_use]
    pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.out_dir = Some(dir.into());
        self
    }

    /// Override the include filename written inside `out_dir` (defaults to
    /// [`DEFAULT_INCLUDE_FILE`]).
    ///
    /// Must be a single plain filename (no directory separators or `..` components).
    #[must_use]
    pub fn include_file(mut self, name: impl Into<PathBuf>) -> Self {
        self.include_file = Some(name.into());
        self
    }

    /// Disable generating the combined include file (only per-package `.rs` files are written).
    #[must_use]
    pub fn no_include_file(mut self) -> Self {
        self.include_file = None;
        self
    }

    /// Also write the compiled protobuf `FileDescriptorSet` bytes to `path`.
    #[must_use]
    pub fn file_descriptor_set_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.file_descriptor_set_path = Some(path.into());
        self
    }

    /// Control whether `cargo:rerun-if-changed=...` lines are printed to stdout (default `true`).
    #[must_use]
    pub const fn emit_rerun_if_changed(mut self, enabled: bool) -> Self {
        self.emit_rerun_if_changed = enabled;
        self
    }

    /// Access the underlying [`prost_build::Config`] for custom codegen tweaks.
    ///
    /// Note that `out_dir` and `include_file` are managed by [`Config::out_dir`] and
    /// [`Config::include_file`] and take precedence during [`Config::compile_protos`].
    pub fn prost_config(&mut self) -> &mut prost_build::Config {
        &mut self.prost
    }

    /// Configure the underlying [`prost_build::Config`] in builder style.
    ///
    /// Note that `out_dir` and `include_file` are managed by [`Config::out_dir`] and
    /// [`Config::include_file`] and take precedence during [`Config::compile_protos`].
    #[must_use]
    pub fn with_prost_config(mut self, configure: impl FnOnce(&mut prost_build::Config)) -> Self {
        configure(&mut self.prost);
        self
    }

    /// Enable or disable `pbjson-build` proto3-JSON `serde` code generation (default `false`).
    ///
    /// When enabled alongside an include file, the generated `*.serde.rs` files are included
    /// automatically beside their matching prost modules.
    #[cfg(feature = "pbjson")]
    #[must_use]
    pub const fn pbjson(mut self, enabled: bool) -> Self {
        self.pbjson = enabled;
        self
    }

    /// Access the underlying [`pbjson_build::Builder`] for custom proto3-JSON codegen options
    /// (such as [`pbjson_build::Builder::ignore_unknown_fields`]).
    ///
    /// Calling this method does not automatically enable `pbjson`; pair it with
    /// [`.pbjson(true)`](Self::pbjson) or use [`Self::with_pbjson_builder`].
    #[cfg(feature = "pbjson")]
    pub fn pbjson_builder(&mut self) -> &mut pbjson_build::Builder {
        &mut self.pbjson_builder
    }

    /// Enable `pbjson` code generation and configure the underlying [`pbjson_build::Builder`] in
    /// builder style (for example `.with_pbjson_builder(|b| { b.ignore_unknown_fields(); })`).
    #[cfg(feature = "pbjson")]
    #[must_use]
    pub fn with_pbjson_builder(
        mut self,
        configure: impl FnOnce(&mut pbjson_build::Builder),
    ) -> Self {
        self.pbjson = true;
        configure(&mut self.pbjson_builder);
        self
    }

    /// Discover and compile every `.proto` file under `proto_dir`.
    ///
    /// # Errors
    ///
    /// Returns [`Error`] if `proto_dir` cannot be read, contains symlinks or no `.proto` files,
    /// `include_file` is invalid, `OUT_DIR` is unset, or `protox` / `prost-build` /
    /// `pbjson-build` fails.
    #[allow(clippy::too_many_lines)]
    pub fn compile_protos(mut self, proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
        let proto_dir = proto_dir.as_ref();
        if let Some(include_name) = &self.include_file {
            validate_include_file_name(include_name)?;
        }

        let (proto_files, visited_dirs) = discover_protos_and_dirs(proto_dir)?;
        let out_dir = match self.out_dir {
            Some(dir) => dir,
            None => PathBuf::from(env::var_os("OUT_DIR").ok_or(Error::MissingOutDir)?),
        };
        fs::create_dir_all(&out_dir).map_err(|source| Error::Io {
            path: Some(out_dir.clone()),
            source,
        })?;

        let mut rerun_directives = Vec::with_capacity(visited_dirs.len() + proto_files.len());
        for dir in &visited_dirs {
            rerun_directives.push(format!("cargo:rerun-if-changed={}", dir.display()));
        }
        for file in &proto_files {
            rerun_directives.push(format!("cargo:rerun-if-changed={}", file.display()));
        }
        if self.emit_rerun_if_changed {
            for directive in &rerun_directives {
                println!("{directive}");
            }
        }

        let descriptors = protox::compile(&proto_files, [proto_dir]).map_err(Error::Protox)?;
        let encoded_descriptors = descriptors.encode_to_vec();
        if let Some(fds_path) = &self.file_descriptor_set_path {
            if let Some(parent) = fds_path.parent()
                && !parent.as_os_str().is_empty()
            {
                fs::create_dir_all(parent).map_err(|source| Error::Io {
                    path: Some(parent.to_path_buf()),
                    source,
                })?;
            }
            write_if_changed(fds_path, &encoded_descriptors)?;
        }

        let discovered_rel_files: BTreeSet<String> = proto_files
            .iter()
            .map(|path| rel_proto_path(proto_dir, path))
            .collect();
        let has_dependencies = proto_files
            .iter()
            .any(|path| !is_root_major_proto(proto_dir, path));
        let package_by_file: BTreeMap<String, String> = descriptors
            .file
            .iter()
            .filter_map(|file| {
                let name = file.name.as_deref()?;
                if !discovered_rel_files.contains(name) {
                    return None;
                }
                let pkg = file.package.as_deref().unwrap_or_default();
                Some((name.to_string(), pkg.to_string()))
            })
            .collect();

        #[cfg(feature = "pbjson")]
        let pbjson_enabled = self.pbjson;
        #[cfg(not(feature = "pbjson"))]
        let pbjson_enabled = false;

        #[cfg(feature = "pbjson")]
        if pbjson_enabled {
            for file in &descriptors.file {
                if file.package.as_deref().is_none_or(str::is_empty) {
                    let name = file.name.as_deref().unwrap_or("<unnamed>");
                    return Err(Error::Pbjson(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        format!(
                            "protobuf file `{name}` has no `package` declaration, which is \
                             required when `pbjson` is enabled"
                        ),
                    )));
                }
            }
        }

        #[cfg(feature = "pbjson")]
        let pbjson_prefixes = collect_pbjson_prefixes(&package_by_file);

        self.prost.out_dir(&out_dir);
        let include_path = self.include_file.as_ref().map(|name| out_dir.join(name));
        let raw_prost_include = if let Some(include_name) = &self.include_file {
            if !has_dependencies || pbjson_enabled {
                let scratch_name =
                    PathBuf::from(format!(".{}.prost", include_name.to_string_lossy()));
                self.prost.include_file(&scratch_name);
                Some(out_dir.join(scratch_name))
            } else {
                self.prost.include_file(include_name);
                None
            }
        } else {
            None
        };
        let _raw_include_cleanup = TempFileGuard(raw_prost_include.clone());

        self.prost.compile_fds(descriptors).map_err(Error::Prost)?;

        #[cfg(feature = "pbjson")]
        let serde_by_pkg: BTreeMap<String, String> = if pbjson_enabled {
            let prefix_refs: Vec<&str> = pbjson_prefixes.iter().map(String::as_str).collect();
            let generated = self
                .pbjson_builder
                .register_descriptors(&encoded_descriptors)
                .map_err(Error::Pbjson)?
                .generate(&prefix_refs, |_| Ok(Vec::<u8>::new()))
                .map_err(Error::Pbjson)?;
            let mut emitted_by_pkg = BTreeMap::new();
            let mut written_files = BTreeSet::new();
            for (package, bytes) in generated {
                let raw_pkg = package
                    .path()
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
                    .join(".");
                let serde_name = format!("{package}.serde.rs");
                write_if_changed(&out_dir.join(&serde_name), &bytes)?;
                written_files.insert(serde_name.clone());
                emitted_by_pkg.insert(raw_pkg, serde_name);
            }
            for pkg in package_by_file.values() {
                if !emitted_by_pkg.contains_key(pkg) {
                    for candidate in pbjson_candidate_file_names(pkg) {
                        if !written_files.contains(&candidate) {
                            let stale = out_dir.join(&candidate);
                            if stale.is_file() {
                                let _ = fs::remove_file(stale);
                            }
                        }
                    }
                }
            }
            emitted_by_pkg
        } else {
            BTreeMap::new()
        };

        if let Some(include_path) = &include_path {
            if has_dependencies {
                #[cfg(feature = "pbjson")]
                if pbjson_enabled && let Some(raw_path) = &raw_prost_include {
                    let spliced =
                        splice_pbjson_includes(raw_path, &package_by_file, &serde_by_pkg)?;
                    write_if_changed(include_path, spliced.as_bytes())?;
                }
                #[cfg(not(feature = "pbjson"))]
                let _ = raw_prost_include;
            } else {
                let (emitted_prost_files, root_level_file) = raw_prost_include
                    .as_deref()
                    .map(extract_prost_include_files)
                    .transpose()?
                    .unwrap_or_default();
                write_standalone_include(
                    &proto_files,
                    proto_dir,
                    &package_by_file,
                    &out_dir,
                    &emitted_prost_files,
                    root_level_file.as_deref(),
                    include_path,
                    #[cfg(feature = "pbjson")]
                    &serde_by_pkg,
                    pbjson_enabled,
                )?;
            }
        }

        Ok(BuildOutput {
            proto_files,
            out_dir,
            include_file: include_path,
            has_dependencies,
            rerun_directives,
        })
    }
}

/// Discover every `.proto` file under `proto_dir` in deterministic sorted order.
///
/// # Errors
///
/// Returns [`Error::Io`] if `proto_dir` cannot be read, [`Error::SymlinkRefused`] if `proto_dir`
/// itself or any entry inside it is a symlink, or [`Error::NoProtoFiles`] if no `.proto` files
/// exist.
pub fn discover_protos(proto_dir: impl AsRef<Path>) -> Result<Vec<PathBuf>, Error> {
    let (files, _) = discover_protos_and_dirs(proto_dir.as_ref())?;
    Ok(files)
}

/// Discover and compile every `.proto` file under `proto_dir` with default [`Config`].
///
/// # Errors
///
/// Returns the same errors as [`Config::compile_protos`].
pub fn compile_protos(proto_dir: impl AsRef<Path>) -> Result<BuildOutput, Error> {
    Config::new().compile_protos(proto_dir)
}

struct TempFileGuard(Option<PathBuf>);

impl Drop for TempFileGuard {
    fn drop(&mut self) {
        if let Some(path) = &self.0 {
            let _ = fs::remove_file(path);
        }
    }
}

fn validate_include_file_name(name: &Path) -> Result<(), Error> {
    if name.as_os_str().as_encoded_bytes().contains(&b'\\') {
        return Err(Error::InvalidIncludeFile(name.to_path_buf()));
    }
    let mut components = name.components();
    match (components.next(), components.next()) {
        (Some(Component::Normal(part)), None) if !part.is_empty() && name.as_os_str() == part => {
            Ok(())
        }
        _ => Err(Error::InvalidIncludeFile(name.to_path_buf())),
    }
}

fn discover_protos_and_dirs(proto_dir: &Path) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Error> {
    let normalized_root: PathBuf = proto_dir.components().collect();
    let root_meta = fs::symlink_metadata(&normalized_root).map_err(|source| Error::Io {
        path: Some(proto_dir.to_path_buf()),
        source,
    })?;
    if root_meta.file_type().is_symlink() {
        return Err(Error::SymlinkRefused(proto_dir.to_path_buf()));
    }

    let mut files = Vec::new();
    let mut dirs = vec![proto_dir.to_path_buf()];
    collect_protos_recursive(proto_dir, &mut files, &mut dirs)?;
    files.sort();
    dirs.sort();
    if files.is_empty() {
        return Err(Error::NoProtoFiles(proto_dir.to_path_buf()));
    }
    Ok((files, dirs))
}

fn collect_protos_recursive(
    dir: &Path,
    out_files: &mut Vec<PathBuf>,
    out_dirs: &mut Vec<PathBuf>,
) -> Result<(), Error> {
    let mut entries: Vec<PathBuf> = fs::read_dir(dir)
        .map_err(|source| Error::Io {
            path: Some(dir.to_path_buf()),
            source,
        })?
        .map(|entry| {
            entry.map(|item| item.path()).map_err(|source| Error::Io {
                path: Some(dir.to_path_buf()),
                source,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort();

    for path in entries {
        let meta = fs::symlink_metadata(&path).map_err(|source| Error::Io {
            path: Some(path.clone()),
            source,
        })?;
        if meta.file_type().is_symlink() {
            return Err(Error::SymlinkRefused(path));
        }
        if meta.is_dir() {
            out_dirs.push(path.clone());
            collect_protos_recursive(&path, out_files, out_dirs)?;
        } else if meta.is_file()
            && path
                .extension()
                .and_then(std::ffi::OsStr::to_str)
                .is_some_and(|ext| ext.eq_ignore_ascii_case("proto"))
        {
            out_files.push(path);
        }
    }
    Ok(())
}

/// Whether `path` is a top-level `witforge proto` root file (`v<major>.proto`).
fn is_root_major_proto(proto_dir: &Path, path: &Path) -> bool {
    let Ok(rel) = path.strip_prefix(proto_dir) else {
        return false;
    };
    if rel.components().count() != 1 {
        return false;
    }
    let Some(name) = rel.file_name().and_then(std::ffi::OsStr::to_str) else {
        return false;
    };
    parse_root_major(name).is_some()
}

fn parse_root_major(file_name: &str) -> Option<u64> {
    let dot = file_name.rfind('.')?;
    if !file_name[dot + 1..].eq_ignore_ascii_case("proto") {
        return None;
    }
    let stem = &file_name[..dot];
    let digits = stem.strip_prefix('v')?;
    if digits.is_empty()
        || !digits.bytes().all(|b| b.is_ascii_digit())
        || (digits.len() > 1 && digits.starts_with('0'))
    {
        return None;
    }
    digits.parse().ok()
}

fn prost_file_name(pkg: &str) -> String {
    prost_build::Module::from_protobuf_package_name(pkg).to_file_name_or("_")
}

#[cfg(feature = "pbjson")]
fn pbjson_candidate_file_names(pkg: &str) -> Vec<String> {
    let module = prost_build::Module::from_protobuf_package_name(pkg);
    let prost_stem = if module.is_empty() {
        "_".to_string()
    } else {
        module.parts().collect::<Vec<_>>().join(".")
    };
    let primary = format!("{prost_stem}.serde.rs");
    let compat_stem = module
        .parts()
        .map(|part| match part {
            "r#gen" => "gen",
            "__" => "_",
            other => other,
        })
        .collect::<Vec<_>>()
        .join(".");
    let fallback = format!("{compat_stem}.serde.rs");
    if fallback == primary {
        vec![primary]
    } else {
        vec![primary, fallback]
    }
}

#[cfg(feature = "pbjson")]
fn collect_pbjson_prefixes(package_by_file: &BTreeMap<String, String>) -> BTreeSet<String> {
    let mut prefixes = BTreeSet::new();
    for pkg in package_by_file.values() {
        if !pkg.is_empty() {
            prefixes.insert(format!(".{pkg}"));
        }
    }
    prefixes
}

fn rel_proto_path(proto_dir: &Path, path: &Path) -> String {
    path.strip_prefix(proto_dir)
        .unwrap_or(path)
        .components()
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/")
}

fn extract_prost_include_files(
    raw_include_path: &Path,
) -> Result<(BTreeSet<String>, Option<String>), Error> {
    let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
        path: Some(raw_include_path.to_path_buf()),
        source,
    })?;
    let mut files = BTreeSet::new();
    let mut root_level_file = None;
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("include!(\"")
            && let Some(file_name) = rest.strip_suffix("\");")
        {
            if line.starts_with("include!(\"") && root_level_file.is_none() {
                root_level_file = Some(file_name.to_string());
            }
            files.insert(file_name.to_string());
        }
    }
    Ok((files, root_level_file))
}

fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<(), Error> {
    if let Ok(existing) = fs::read(path)
        && existing == bytes
    {
        return Ok(());
    }
    fs::write(path, bytes).map_err(|source| Error::Io {
        path: Some(path.to_path_buf()),
        source,
    })
}

#[allow(clippy::too_many_arguments)]
fn write_standalone_include(
    proto_files: &[PathBuf],
    proto_dir: &Path,
    package_by_file: &BTreeMap<String, String>,
    out_dir: &Path,
    emitted_prost_files: &BTreeSet<String>,
    root_level_file: Option<&str>,
    include_path: &Path,
    #[cfg(feature = "pbjson")] serde_by_pkg: &BTreeMap<String, String>,
    pbjson_enabled: bool,
) -> Result<(), Error> {
    #[cfg(not(feature = "pbjson"))]
    let _ = pbjson_enabled;

    let mut majors: BTreeMap<u64, (String, PathBuf)> = BTreeMap::new();
    for path in proto_files {
        let rel = rel_proto_path(proto_dir, path);
        if let Some(file_name) = path.file_name().and_then(std::ffi::OsStr::to_str)
            && let Some(major) = parse_root_major(file_name)
        {
            let pkg = package_by_file.get(&rel).cloned().unwrap_or_default();
            if let Some((_, existing)) = majors.insert(major, (pkg, path.clone())) {
                return Err(Error::Io {
                    path: Some(path.clone()),
                    source: std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        format!(
                            "duplicate root major proto for `v{major}`: `{}` conflicts with `{}`",
                            path.display(),
                            existing.display()
                        ),
                    ),
                });
            }
        }
    }

    let mut out = String::from("// @generated by witforge-build; do not edit.\n");
    for (major, (pkg, _)) in majors {
        let rs_name = if pkg.is_empty() {
            root_level_file.map_or_else(|| prost_file_name(""), ToString::to_string)
        } else {
            prost_file_name(&pkg)
        };
        let _ = writeln!(out);
        if emitted_prost_files.contains(&rs_name) {
            let _ = writeln!(out, "pub mod v{major} {{");
            let _ = writeln!(out, "    include!({rs_name:?});");
            #[cfg(feature = "pbjson")]
            if pbjson_enabled && let Some(serde_name) = serde_by_pkg.get(&pkg) {
                let _ = writeln!(out, "    include!({serde_name:?});");
            }
            let _ = writeln!(out, "}}");
        } else {
            let stale = out_dir.join(&rs_name);
            if stale.is_file() {
                let _ = fs::remove_file(stale);
            }
            let _ = writeln!(out, "pub mod v{major} {{}}");
        }
    }

    write_if_changed(include_path, out.as_bytes())
}

#[cfg(feature = "pbjson")]
fn splice_pbjson_includes(
    raw_include_path: &Path,
    package_by_file: &BTreeMap<String, String>,
    serde_by_pkg: &BTreeMap<String, String>,
) -> Result<String, Error> {
    let text = fs::read_to_string(raw_include_path).map_err(|source| Error::Io {
        path: Some(raw_include_path.to_path_buf()),
        source,
    })?;

    let mut serde_by_prost_file: BTreeMap<String, String> = BTreeMap::new();
    for pkg in package_by_file.values() {
        let prost_name = prost_file_name(pkg);
        if let Some(serde_name) = serde_by_pkg.get(pkg) {
            serde_by_prost_file.insert(prost_name, serde_name.clone());
        }
    }

    let mut out = String::with_capacity(text.len() + serde_by_prost_file.len() * 48);
    for line in text.lines() {
        out.push_str(line);
        out.push('\n');
        let trimmed = line.trim_start();
        let indent = &line[..line.len() - trimmed.len()];
        if let Some(rest) = trimmed.strip_prefix("include!(\"")
            && let Some(prost_name) = rest.strip_suffix("\");")
            && let Some(serde_name) = serde_by_prost_file.get(prost_name)
        {
            let _ = writeln!(out, "{indent}include!({serde_name:?});");
        }
    }
    Ok(out)
}