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
use anyhow::{self, Context};
use thiserror::Error;
use ninja_builder::{
build, build_externals, caching_mtime_rebuilder,
task::{description_to_tasks, description_to_tasks_with_start, Key},
ParallelTopoScheduler,
};
use ninja_metrics::scoped_metric;
use ninja_parse::{build_representation, Loader};
use std::{ffi::OsStr, os::unix::ffi::OsStrExt, path::Path};
#[derive(Debug, PartialEq, Eq)]
pub enum DebugMode {
List,
Stats,
}
#[derive(Error, Debug)]
#[error("Unknown debug setting '{0}'")]
pub struct DebugModeError(String);
impl std::str::FromStr for DebugMode {
type Err = DebugModeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"stats" => Ok(DebugMode::Stats),
"list" => Ok(DebugMode::List),
e @ _ => Err(DebugModeError(e.to_owned())),
}
}
}
#[derive(Debug)]
pub struct Config {
pub execution_dir: Option<String>,
pub parallelism: usize,
pub build_file: String,
pub debug_modes: Vec<DebugMode>,
pub targets: Vec<String>,
}
struct FileLoader {}
impl Loader for FileLoader {
fn load(&mut self, from: Option<&[u8]>, request: &[u8]) -> std::io::Result<Vec<u8>> {
let path = if let Some(from) = from {
let src_path = Path::new(OsStr::from_bytes(from));
let req_path = Path::new(OsStr::from_bytes(request));
if req_path.components().count() > 1 {
todo!("handle relative paths");
} else {
src_path.with_file_name(req_path)
}
} else {
Path::new(OsStr::from_bytes(request)).to_owned()
};
std::fs::read(path)
}
}
pub fn run(config: Config) -> anyhow::Result<()> {
if let Some(dir) = &config.execution_dir {
std::env::set_current_dir(&dir).with_context(|| format!("changing to {} for -C", &dir))?;
}
let metrics_enabled = config.debug_modes.iter().any(|v| v == &DebugMode::Stats);
if metrics_enabled {
ninja_metrics::enable();
}
let mut loader = FileLoader {};
let repr = build_representation(&mut loader, config.build_file.into_bytes())?;
let (tasks, requested) = {
scoped_metric!("to_tasks");
if config.targets.is_empty() {
description_to_tasks(repr)
} else {
description_to_tasks_with_start(
repr,
Some(config.targets.into_iter().map(|v| v.into_bytes()).collect()),
)
}
};
let rebuilder = caching_mtime_rebuilder();
let scheduler = ParallelTopoScheduler::new(config.parallelism);
{
scoped_metric!("build");
if let Some(requested) = requested {
build(
scheduler,
&rebuilder,
&tasks,
requested.into_iter().map(Key::Path).collect(),
)?;
} else {
build_externals(scheduler, &rebuilder, &tasks)?;
}
}
if metrics_enabled {
ninja_metrics::dump();
}
Ok(())
}