Skip to content

Commit 218b5f4

Browse files
committed
Make codegen search up for the codegen.json.
1 parent 1ca0c01 commit 218b5f4

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

src/main.rs

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@ use clap::{arg, command};
33
use rustfmt_wrapper::rustfmt;
44
use serde::{Deserialize, Serialize};
55
use std::collections::BTreeMap;
6-
use std::path::Path;
6+
use std::path::{Path, PathBuf};
77
use tera::{from_value, to_value};
88

99
// use outputs::build_output_pairs;
1010

11-
const GLAM_ROOT: &str = "..";
1211
const CONFIG_FILE: &str = "codegen.json";
1312

1413
#[derive(Serialize, Deserialize)]
@@ -150,10 +149,25 @@ fn generate_file(
150149
.context("tera render error")
151150
}
152151

153-
fn main() -> anyhow::Result<()> {
154-
// Change into `./codegen` dir for convenience to the user
155-
std::env::set_current_dir(env!("CARGO_MANIFEST_DIR"))?;
152+
fn find_config_file() -> anyhow::Result<PathBuf> {
153+
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
154+
let mut current = manifest_dir.to_path_buf();
155+
156+
while let Some(parent) = current.parent() {
157+
let config_path = parent.join(CONFIG_FILE);
158+
if std::path::Path::new(&config_path).exists() {
159+
return Ok(config_path);
160+
}
161+
current = parent.to_path_buf();
162+
}
156163

164+
Err(anyhow::anyhow!(
165+
"codegen.json not found. Searched from {} upwards.",
166+
manifest_dir.display()
167+
))
168+
}
169+
170+
fn main() -> anyhow::Result<()> {
157171
let matches = command!()
158172
.arg(arg!([GLOB]))
159173
.arg(arg!(-f - -force))
@@ -185,9 +199,11 @@ fn main() -> anyhow::Result<()> {
185199
None
186200
};
187201

188-
let config = Config::from_file(Path::new(GLAM_ROOT).join(CONFIG_FILE))?;
202+
let config_file = find_config_file()?;
203+
let config_root = config_file.parent().unwrap_or(Path::new("."));
204+
let config = Config::from_file(config_file.as_path())?;
189205

190-
let template_path = Path::new(GLAM_ROOT)
206+
let template_path = Path::new(config_root)
191207
.join(&config.template_root)
192208
.join("**/*.rs.tera");
193209
let mut tera =
@@ -216,7 +232,7 @@ fn main() -> anyhow::Result<()> {
216232

217233
let output_pairs = config.build_output_pairs()?;
218234

219-
let repo = git2::Repository::open(GLAM_ROOT).context("failed to open git repo")?;
235+
let repo = git2::Repository::open(config_root).context("failed to open git repo")?;
220236
let workdir = repo.workdir().unwrap();
221237

222238
let mut output_paths = vec![];

0 commit comments

Comments
 (0)