Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to prepend header indicating tool version #19

Merged
merged 2 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 32 additions & 11 deletions proto-gen/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,20 @@ pub fn run_generation(
proto_ws: &ProtoWorkspace,
opts: Builder,
config: prost_build::Config,
commit: bool,
format: bool,
gen_opts: &GenOptions,
) -> Result<(), String> {
let top_mod_content = generate_to_tmp(proto_ws, opts, config).map_err(|e| {
let top_mod_content = generate_to_tmp(proto_ws, opts, config, gen_opts).map_err(|e| {
format!("Failed to generate protos into temp dir for proto workspace {proto_ws:#?} \n{e}")
})?;
let old = &proto_ws.output_dir;
let new = &proto_ws.tmp_dir;
if format {
if gen_opts.format {
recurse_fmt(new)?;
}
let diff = run_diff(old, new, &top_mod_content)?;
if diff > 0 {
println!("Found diff in {diff} protos at {:?}", proto_ws.output_dir);
if commit {
if gen_opts.commit {
println!("Writing {diff} protos to {:?}", proto_ws.output_dir);
recurse_copy_clean(new, old)?;
let out_top_name = as_file_name_string(old)?;
Expand All @@ -61,10 +60,19 @@ pub struct ProtoWorkspace {
pub output_dir: PathBuf,
}

#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct GenOptions {
pub commit: bool,
pub format: bool,
pub prepend_header: bool,
}

fn generate_to_tmp(
ws: &ProtoWorkspace,
opts: Builder,
config: prost_build::Config,
gen_opts: &GenOptions,
) -> Result<String, String> {
let old_out = std::env::var("OUT_DIR");
std::env::set_var("OUT_DIR", &ws.tmp_dir);
Expand All @@ -78,10 +86,10 @@ fn generate_to_tmp(
std::env::remove_var("OUT_DIR");
}

clean_up_file_structure(&ws.tmp_dir)
clean_up_file_structure(&ws.tmp_dir, gen_opts)
}

fn clean_up_file_structure(out_dir: &Path) -> Result<String, String> {
fn clean_up_file_structure(out_dir: &Path, gen_opts: &GenOptions) -> Result<String, String> {
let rd = fs::read_dir(out_dir)
.map_err(|e| format!("Failed read output dir {out_dir:?} when cleaning up files \n{e}"))?;
let mut out_modules = Module {
Expand Down Expand Up @@ -121,7 +129,7 @@ fn clean_up_file_structure(out_dir: &Path) -> Result<String, String> {
let mut top_level_mod = "#![allow(clippy::doc_markdown, clippy::use_self)]\n".to_string();
sortable_children.sort_by(|a, b| a.borrow().get_name().cmp(b.borrow().get_name()));
for module in sortable_children {
module.borrow_mut().dump_to_disk()?;
module.borrow_mut().dump_to_disk(gen_opts)?;
let _ = top_level_mod.write_fmt(format_args!("pub mod {};\n", module.borrow().get_name()));
}
Ok(top_level_mod)
Expand Down Expand Up @@ -189,7 +197,7 @@ impl Module {
Ok(())
}

fn dump_to_disk(&self) -> Result<(), String> {
fn dump_to_disk(&self, gen_opts: &GenOptions) -> Result<(), String> {
let module_expose_output = if self.children.is_empty() {
None
} else {
Expand All @@ -211,7 +219,7 @@ impl Module {
"pub mod {};\n",
sorted_child.borrow().get_name()
));
sorted_child.borrow().dump_to_disk()?;
sorted_child.borrow().dump_to_disk(gen_opts)?;
}
Some(output)
};
Expand Down Expand Up @@ -241,7 +249,12 @@ impl Module {
} else if !is_same_file {
let file_content = fs::read_to_string(file)
.map_err(|e| format!("Failed to read created file {file:?} \n{e}"))?;
let clean_content = hide_doctests(&file_content);
let mut clean_content = hide_doctests(&file_content);

if gen_opts.prepend_header {
prepend_header(&mut clean_content);
}

fs::write(&file_location, clean_content.as_bytes()).map_err(|e| {
format!("Failed to write file contents to {file_location:?} \n{e}")
})?;
Expand Down Expand Up @@ -274,6 +287,14 @@ impl Module {
}
}

fn prepend_header(clean_content: &mut String) {
let version = env!("CARGO_PKG_VERSION");
clean_content.insert_str(
0,
&format!("// Generated with https://github.com/EmbarkStudios/proto-gen v.{version}\n\n"),
);
}

fn as_file_name_string(path: impl AsRef<Path>) -> Result<String, String> {
let path = path.as_ref();
let file_name = path
Expand Down
25 changes: 18 additions & 7 deletions proto-gen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
mod gen;
mod kv;

use gen::GenOptions;
use kv::KvValueParser;

use std::fmt::Debug;
Expand All @@ -25,6 +26,9 @@ struct Opts {
/// Use `rustfmt` on the code after generation, `rustfmt` needs to be on the path
#[clap(short, long)]
format: bool,
/// Prepend header indicating tool version in generated source files
#[clap(short, long, default_value_t = false)]
prepend_header: bool,
#[command(subcommand)]
routine: Routine,
}
Expand Down Expand Up @@ -130,7 +134,12 @@ fn run_with_opts(opts: Opts) -> Result<(), i32> {
Routine::Validate { workspace } => (workspace, false),
Routine::Generate { workspace } => (workspace, true),
};
if let Err(err) = run_ws(ws, bldr, config, commit, opts.format) {
let gen_opts = GenOptions {
commit,
format: opts.format,
prepend_header: opts.prepend_header,
};
if let Err(err) = run_ws(ws, bldr, config, &gen_opts) {
eprintln!("Failed to run command \n{err}");
return Err(1);
}
Expand All @@ -141,8 +150,7 @@ fn run_ws(
opts: WorkspaceOpts,
bldr: Builder,
config: prost_build::Config,
commit: bool,
format: bool,
gen_opts: &GenOptions,
) -> Result<(), String> {
if opts.proto_files.is_empty() {
return Err("--proto-files needs at least one file to generate".to_string());
Expand All @@ -157,8 +165,7 @@ fn run_ws(
},
bldr,
config,
commit,
format,
gen_opts,
)
} else {
// Deleted on drop
Expand All @@ -172,8 +179,7 @@ fn run_ws(
},
bldr,
config,
commit,
format,
gen_opts,
)
}
}
Expand Down Expand Up @@ -244,6 +250,7 @@ message TestMessage {
routine: Routine::Generate {
workspace: test_cfg.workspace.clone(),
},
prepend_header: true,
};
// Generate
run_with_opts(opts).unwrap();
Expand All @@ -253,6 +260,7 @@ message TestMessage {
routine: Routine::Validate {
workspace: test_cfg.workspace.clone(),
},
prepend_header: true,
};
// Validate it's the same after generation
run_with_opts(opts).unwrap();
Expand All @@ -262,6 +270,7 @@ message TestMessage {
routine: Routine::Validate {
workspace: test_cfg.workspace,
},
prepend_header: true,
};
// Validate it's not the same if specifying no fmt
match run_with_opts(opts) {
Expand All @@ -282,6 +291,7 @@ message TestMessage {
routine: Routine::Generate {
workspace: test_cfg.workspace,
},
prepend_header: true,
};
// Generate
run_with_opts(opts).unwrap();
Expand Down Expand Up @@ -371,6 +381,7 @@ message NestedTransitiveMsg {
tonic,
format: false,
routine: Routine::Generate { workspace },
prepend_header: true,
};
run_with_opts(opts).unwrap();
assert_exists_not_empty(&proto_types_dir.join("my_proto.rs"));
Expand Down
Loading