Skip to main content

protocheck_build/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3use std::{
4  env,
5  error::Error,
6  fs,
7  io::{self, Read},
8  path::{Path, PathBuf},
9};
10
11use prost_build::Config;
12use prost_reflect::{prost::Message, prost_types::FileDescriptorSet};
13
14/// This function compiles the proto_files in the list, it creates an intermediary file descriptor and it uses it to extract information about the messages, enums and oneofs which can later be used to generate the validation logic with protocheck.
15pub fn compile_protos_with_validators(
16  config: &mut Config,
17  proto_files: &[impl AsRef<Path>],
18  proto_include_paths: &[impl AsRef<Path>],
19  packages: &[&str],
20) -> Result<(), Box<dyn Error>> {
21  let out_dir = env::var("OUT_DIR")
22    .map(PathBuf::from)
23    .unwrap_or_else(|_| env::temp_dir());
24
25  let temp_descriptor_path = out_dir.join("temp_file_descriptor_set_for_protocheck.bin");
26  {
27    let mut temp_config = prost_build::Config::new();
28    temp_config.file_descriptor_set_path(&temp_descriptor_path);
29    temp_config.out_dir(&out_dir);
30    temp_config.compile_protos(proto_files, proto_include_paths)?;
31  }
32
33  let mut fds_file = std::fs::File::open(&temp_descriptor_path)?;
34  let mut fds_bytes = Vec::new();
35  fds_file.read_to_end(&mut fds_bytes)?;
36  let fds = FileDescriptorSet::decode(fds_bytes.as_slice())?;
37  let pool = prost_reflect::DescriptorPool::from_file_descriptor_set(fds)?;
38
39  for message_desc in pool.all_messages() {
40    let message_name = message_desc.full_name();
41    if packages.contains(&message_desc.package_name()) {
42      let attribute_str = format!(
43        r#"#[::protocheck::macros::protobuf_validate("{}")]"#,
44        message_name
45      );
46      config.message_attribute(message_name, &attribute_str);
47
48      if cfg!(feature = "cel") {
49        config.message_attribute(
50          message_name,
51          "#[derive(::protocheck::macros::TryIntoCelValue)]",
52        );
53      }
54
55      for oneof in message_desc.oneofs() {
56        let oneof_name = oneof.full_name();
57        config.type_attribute(
58          oneof_name,
59          format!(
60            r#"#[::protocheck::macros::protobuf_validate_oneof("{}")]"#,
61            oneof_name
62          ),
63        );
64
65        config.type_attribute(oneof_name, r#"#[derive(::protocheck::macros::Oneof)]"#);
66
67        if cfg!(feature = "cel") {
68          config.type_attribute(
69            oneof_name,
70            r#"#[derive(::protocheck::macros::OneofTryIntoCelValue)]"#,
71          );
72        }
73
74        for field in oneof.fields() {
75          config.field_attribute(
76            format!("{}.{}", oneof_name, field.name()),
77            format!(r#"#[protocheck(proto_name = "{}")]"#, field.name()),
78          );
79        }
80      }
81    }
82  }
83
84  config.extern_path(".buf.validate", "::protocheck::types::protovalidate");
85  config
86    .extern_path(".google.protobuf", "::protocheck::types")
87    .compile_well_known_types();
88
89  std::fs::remove_file(&temp_descriptor_path)?;
90
91  Ok(())
92}
93
94/// A helper to use when gathering the names of proto files to pass to [`prost_build::Config::compile_protos`].
95/// Recursively collects all .proto files in a given directory and its subdirectories.
96pub fn get_proto_files_recursive(base_dir: impl Into<PathBuf>) -> io::Result<Vec<String>> {
97  let base_dir: PathBuf = base_dir.into();
98  let mut proto_files = Vec::new();
99
100  if !base_dir.is_dir() {
101    return Err(io::Error::new(
102      io::ErrorKind::InvalidInput,
103      format!("Path {:?} is not a directory.", base_dir),
104    ));
105  }
106
107  // We'll use a helper function to do the actual recursive work
108  // This helps keep the public function's signature clean.
109  collect_proto_files_recursive_helper(base_dir.as_path(), &mut proto_files)?;
110
111  Ok(proto_files)
112}
113
114fn collect_proto_files_recursive_helper(
115  current_dir: &Path,
116  proto_files: &mut Vec<String>,
117) -> io::Result<()> {
118  for entry in fs::read_dir(current_dir)? {
119    let entry = entry?;
120    let path = entry.path();
121
122    if path.is_file() {
123      if path.extension().is_some_and(|ext| ext == "proto") {
124        proto_files.push(
125          path
126            .to_str()
127            .ok_or_else(|| {
128              io::Error::new(
129                io::ErrorKind::InvalidData,
130                format!("Path {:?} contains invalid Unicode.", path),
131              )
132            })?
133            .to_owned(),
134        );
135      }
136    } else if path.is_dir() {
137      collect_proto_files_recursive_helper(&path, proto_files)?;
138    }
139  }
140  Ok(())
141}