From 8aaa403e3f1325fed7d8018aa66a2f2dfa555f77 Mon Sep 17 00:00:00 2001 From: Evan Martin Date: Wed, 20 Dec 2023 10:11:54 -0800 Subject: [PATCH] obey builddir for placing .n2_db --- src/db.rs | 5 +++-- src/load.rs | 13 +++++++++++-- tests/e2e/basic.rs | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/db.rs b/src/db.rs index a112a0d..0c9c8cb 100644 --- a/src/db.rs +++ b/src/db.rs @@ -12,6 +12,7 @@ use std::io::BufReader; use std::io::Read; use std::io::Write; use std::mem::MaybeUninit; +use std::path::Path; const VERSION: u32 = 1; @@ -111,7 +112,7 @@ pub struct Writer { } impl Writer { - fn create(path: &str) -> std::io::Result { + fn create(path: &Path) -> std::io::Result { let f = std::fs::File::create(path)?; let mut w = Writer { ids: IdMap::default(), @@ -333,7 +334,7 @@ impl<'a> Reader<'a> { } /// Opens or creates an on-disk database, loading its state into the provided Graph. -pub fn open(path: &str, graph: &mut Graph, hashes: &mut Hashes) -> anyhow::Result { +pub fn open(path: &Path, graph: &mut Graph, hashes: &mut Hashes) -> anyhow::Result { match std::fs::OpenOptions::new() .read(true) .append(true) diff --git a/src/load.rs b/src/load.rs index d786c03..f583309 100644 --- a/src/load.rs +++ b/src/load.rs @@ -8,9 +8,9 @@ use crate::{ {db, eval, graph, parse, trace}, }; use anyhow::{anyhow, bail}; -use std::borrow::Cow; use std::collections::HashMap; use std::path::PathBuf; +use std::{borrow::Cow, path::Path}; /// A variable lookup environment for magic $in/$out variables. struct BuildImplicitVars<'a> { @@ -49,6 +49,7 @@ struct Loader { /// rule name -> list of (key, val) rules: HashMap>>, pools: SmallMap, + builddir: Option, } impl parse::Loader for Loader { @@ -196,6 +197,7 @@ impl Loader { } }; } + self.builddir = parser.vars.get("builddir").cloned(); Ok(()) } } @@ -221,7 +223,14 @@ pub fn read(build_filename: &str) -> anyhow::Result { })?; let mut hashes = graph::Hashes::default(); let db = trace::scope("db::open", || { - db::open(".n2_db", &mut loader.graph, &mut hashes) + let mut db_path = PathBuf::from(".n2_db"); + if let Some(builddir) = &loader.builddir { + db_path = Path::new(&builddir).join(db_path); + if let Some(parent) = db_path.parent() { + std::fs::create_dir_all(parent)?; + } + }; + db::open(&db_path, &mut loader.graph, &mut hashes) }) .map_err(|err| anyhow!("load .n2_db: {}", err))?; Ok(State { diff --git a/tests/e2e/basic.rs b/tests/e2e/basic.rs index 077d448..80ea3ce 100644 --- a/tests/e2e/basic.rs +++ b/tests/e2e/basic.rs @@ -312,3 +312,22 @@ build out3: phony out2 space.read("outfile")?; Ok(()) } + +// builddir controls where .n2_db is written. +#[test] +fn builddir() -> anyhow::Result<()> { + let space = TestSpace::new()?; + space.write( + "build.ninja", + &[ + "builddir = foo", + TOUCH_RULE, + "build $builddir/bar: touch", + "", + ] + .join("\n"), + )?; + space.run_expect(&mut n2_command(vec!["foo/bar"]))?; + space.read("foo/.n2_db")?; + Ok(()) +}