]> git.lizzy.rs Git - rust.git/blob - src/tools/x/src/main.rs
Auto merge of #89285 - jackh726:issue-88862, r=nikomatsakis
[rust.git] / src / tools / x / src / main.rs
1 //! Run `x.py` from any subdirectory of a rust compiler checkout.
2 //!
3 //! We prefer `exec`, to avoid adding an extra process in the process tree.
4 //! However, since `exec` isn't available on Windows, we indirect through
5 //! `exec_or_status`, which will call `exec` on unix and `status` on Windows.
6 //!
7 //! We use `python`, `python3`, or `python2` as the python interpreter to run
8 //! `x.py`, in that order of preference.
9
10 use std::{
11     env, io,
12     process::{self, Command, ExitStatus},
13 };
14
15 const PYTHON: &str = "python";
16 const PYTHON2: &str = "python2";
17 const PYTHON3: &str = "python3";
18
19 fn python() -> &'static str {
20     let val = match env::var_os("PATH") {
21         Some(val) => val,
22         None => return PYTHON,
23     };
24
25     let mut python2 = false;
26     let mut python3 = false;
27
28     for dir in env::split_paths(&val) {
29         if dir.join(PYTHON).exists() {
30             return PYTHON;
31         }
32
33         python2 |= dir.join(PYTHON2).exists();
34         python3 |= dir.join(PYTHON3).exists();
35     }
36
37     if python3 {
38         PYTHON3
39     } else if python2 {
40         PYTHON2
41     } else {
42         PYTHON
43     }
44 }
45
46 #[cfg(unix)]
47 fn exec_or_status(command: &mut Command) -> io::Result<ExitStatus> {
48     use std::os::unix::process::CommandExt;
49     Err(command.exec())
50 }
51
52 #[cfg(not(unix))]
53 fn exec_or_status(command: &mut Command) -> io::Result<ExitStatus> {
54     command.status()
55 }
56
57 fn main() {
58     let current = match env::current_dir() {
59         Ok(dir) => dir,
60         Err(err) => {
61             eprintln!("Failed to get current directory: {}", err);
62             process::exit(1);
63         }
64     };
65
66     for dir in current.ancestors() {
67         let candidate = dir.join("x.py");
68
69         if candidate.exists() {
70             let mut python = Command::new(python());
71
72             python.arg(&candidate).args(env::args().skip(1)).current_dir(dir);
73
74             let result = exec_or_status(&mut python);
75
76             match result {
77                 Err(error) => {
78                     eprintln!("Failed to invoke `{}`: {}", candidate.display(), error);
79                 }
80                 Ok(status) => {
81                     process::exit(status.code().unwrap_or(1));
82                 }
83             }
84         }
85     }
86
87     eprintln!(
88         "x.py not found. Please run inside of a checkout of `https://github.com/rust-lang/rust`."
89     );
90
91     process::exit(1);
92 }