]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/setup.rs
Refactor `setup_config_toml` into a function
[rust.git] / src / bootstrap / setup.rs
1 use crate::Config;
2 use crate::{t, VERSION};
3 use std::env::consts::EXE_SUFFIX;
4 use std::fmt::Write as _;
5 use std::fs::File;
6 use std::io::Write;
7 use std::path::{Path, PathBuf, MAIN_SEPARATOR};
8 use std::process::Command;
9 use std::str::FromStr;
10 use std::{fmt, fs, io};
11
12 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
13 pub enum Profile {
14     Compiler,
15     Codegen,
16     Library,
17     Tools,
18     User,
19 }
20
21 impl Profile {
22     fn include_path(&self, src_path: &Path) -> PathBuf {
23         PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
24     }
25
26     pub fn all() -> impl Iterator<Item = Self> {
27         use Profile::*;
28         // N.B. these are ordered by how they are displayed, not alphabetically
29         [Library, Compiler, Codegen, Tools, User].iter().copied()
30     }
31
32     pub fn purpose(&self) -> String {
33         use Profile::*;
34         match self {
35             Library => "Contribute to the standard library",
36             Compiler => "Contribute to the compiler itself",
37             Codegen => "Contribute to the compiler, and also modify LLVM or codegen",
38             Tools => "Contribute to tools which depend on the compiler, but do not modify it directly (e.g. rustdoc, clippy, miri)",
39             User => "Install Rust from source",
40         }
41         .to_string()
42     }
43
44     pub fn all_for_help(indent: &str) -> String {
45         let mut out = String::new();
46         for choice in Profile::all() {
47             writeln!(&mut out, "{}{}: {}", indent, choice, choice.purpose()).unwrap();
48         }
49         out
50     }
51 }
52
53 impl FromStr for Profile {
54     type Err = String;
55
56     fn from_str(s: &str) -> Result<Self, Self::Err> {
57         match s {
58             "lib" | "library" => Ok(Profile::Library),
59             "compiler" => Ok(Profile::Compiler),
60             "llvm" | "codegen" => Ok(Profile::Codegen),
61             "maintainer" | "user" => Ok(Profile::User),
62             "tools" | "tool" | "rustdoc" | "clippy" | "miri" | "rustfmt" | "rls" => {
63                 Ok(Profile::Tools)
64             }
65             _ => Err(format!("unknown profile: '{}'", s)),
66         }
67     }
68 }
69
70 impl fmt::Display for Profile {
71     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72         match self {
73             Profile::Compiler => write!(f, "compiler"),
74             Profile::Codegen => write!(f, "codegen"),
75             Profile::Library => write!(f, "library"),
76             Profile::User => write!(f, "user"),
77             Profile::Tools => write!(f, "tools"),
78         }
79     }
80 }
81
82 pub fn setup(config: &Config, profile: Option<Profile>) {
83     let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
84     let profile = profile.unwrap_or_else(|| t!(interactive_path()));
85     setup_config_toml(path, profile, config);
86
87     let stage_path =
88         ["build", config.build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
89
90     println!();
91
92     if !rustup_installed() && profile != Profile::User {
93         eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
94     } else if stage_dir_exists(&stage_path[..]) {
95         attempt_toolchain_link(&stage_path[..]);
96     }
97
98     let suggestions = match profile {
99         Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
100         Profile::Tools => &[
101             "check",
102             "build",
103             "test src/test/rustdoc*",
104             "test src/tools/clippy",
105             "test src/tools/miri",
106             "test src/tools/rustfmt",
107         ],
108         Profile::Library => &["check", "build", "test library/std", "doc"],
109         Profile::User => &["dist", "build"],
110     };
111
112     println!();
113
114     t!(install_git_hook_maybe(&config));
115
116     println!();
117
118     println!("To get started, try one of the following commands:");
119     for cmd in suggestions {
120         println!("- `x.py {}`", cmd);
121     }
122
123     if profile != Profile::User {
124         println!(
125             "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
126         );
127     }
128 }
129
130 fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) {
131     if path.exists() {
132         eprintln!(
133             "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
134             path.display()
135         );
136         eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
137         eprintln!(
138             "note: this will use the configuration in {}",
139             profile.include_path(&config.src).display()
140         );
141         crate::detail_exit(1);
142     }
143
144     let settings = format!(
145         "# Includes one of the default files in src/bootstrap/defaults\n\
146     profile = \"{}\"\n\
147     changelog-seen = {}\n",
148         profile, VERSION
149     );
150     t!(fs::write(path, settings));
151
152     let include_path = profile.include_path(&config.src);
153     println!("`x.py` will now use the configuration at {}", include_path.display());
154 }
155
156 fn rustup_installed() -> bool {
157     Command::new("rustup")
158         .arg("--version")
159         .stdout(std::process::Stdio::null())
160         .output()
161         .map_or(false, |output| output.status.success())
162 }
163
164 fn stage_dir_exists(stage_path: &str) -> bool {
165     match fs::create_dir(&stage_path) {
166         Ok(_) => true,
167         Err(_) => Path::new(&stage_path).exists(),
168     }
169 }
170
171 fn attempt_toolchain_link(stage_path: &str) {
172     if toolchain_is_linked() {
173         return;
174     }
175
176     if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
177         eprintln!(
178             "Failed to create a template for stage 1 toolchain or confirm that it already exists"
179         );
180         return;
181     }
182
183     if try_link_toolchain(&stage_path) {
184         println!(
185             "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
186         );
187     } else {
188         eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
189         eprintln!(
190             "To manually link stage 1 build to `stage1` toolchain, run:\n
191             `rustup toolchain link stage1 {}`",
192             &stage_path
193         );
194     }
195 }
196
197 fn toolchain_is_linked() -> bool {
198     match Command::new("rustup")
199         .args(&["toolchain", "list"])
200         .stdout(std::process::Stdio::piped())
201         .output()
202     {
203         Ok(toolchain_list) => {
204             if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
205                 return false;
206             }
207             // The toolchain has already been linked.
208             println!(
209                 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
210             );
211         }
212         Err(_) => {
213             // In this case, we don't know if the `stage1` toolchain has been linked;
214             // but `rustup` failed, so let's not go any further.
215             println!(
216                 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
217             );
218         }
219     }
220     true
221 }
222
223 fn try_link_toolchain(stage_path: &str) -> bool {
224     Command::new("rustup")
225         .stdout(std::process::Stdio::null())
226         .args(&["toolchain", "link", "stage1", &stage_path])
227         .output()
228         .map_or(false, |output| output.status.success())
229 }
230
231 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
232     let pathbuf = PathBuf::from(stage_path);
233
234     if fs::create_dir_all(pathbuf.join("lib")).is_err() {
235         return false;
236     };
237
238     let pathbuf = pathbuf.join("bin");
239     if fs::create_dir_all(&pathbuf).is_err() {
240         return false;
241     };
242
243     let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
244
245     if pathbuf.exists() {
246         return true;
247     }
248
249     // Take care not to overwrite the file
250     let result = File::options().append(true).create(true).open(&pathbuf);
251     if result.is_err() {
252         return false;
253     }
254
255     return true;
256 }
257
258 // Used to get the path for `Subcommand::Setup`
259 pub fn interactive_path() -> io::Result<Profile> {
260     fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
261         ('a'..)
262             .zip(1..)
263             .map(|(letter, number)| (letter.to_string(), number.to_string()))
264             .zip(Profile::all())
265     }
266
267     fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
268         let input = input.trim().to_lowercase();
269         for ((letter, number), profile) in abbrev_all() {
270             if input == letter || input == number {
271                 return Ok(profile);
272             }
273         }
274         input.parse()
275     }
276
277     println!("Welcome to the Rust project! What do you want to do with x.py?");
278     for ((letter, _), profile) in abbrev_all() {
279         println!("{}) {}: {}", letter, profile, profile.purpose());
280     }
281     let template = loop {
282         print!(
283             "Please choose one ({}): ",
284             abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
285         );
286         io::stdout().flush()?;
287         let mut input = String::new();
288         io::stdin().read_line(&mut input)?;
289         if input.is_empty() {
290             eprintln!("EOF on stdin, when expecting answer to question.  Giving up.");
291             crate::detail_exit(1);
292         }
293         break match parse_with_abbrev(&input) {
294             Ok(profile) => profile,
295             Err(err) => {
296                 eprintln!("error: {}", err);
297                 eprintln!("note: press Ctrl+C to exit");
298                 continue;
299             }
300         };
301     };
302     Ok(template)
303 }
304
305 // install a git hook to automatically run tidy --bless, if they want
306 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
307     let mut input = String::new();
308     println!(
309         "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
310 If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
311 pushing your code to ensure your code is up to par. If you decide later that this behavior is
312 undesirable, simply delete the `pre-push` file from .git/hooks."
313     );
314
315     let should_install = loop {
316         print!("Would you like to install the git hook?: [y/N] ");
317         io::stdout().flush()?;
318         input.clear();
319         io::stdin().read_line(&mut input)?;
320         break match input.trim().to_lowercase().as_str() {
321             "y" | "yes" => true,
322             "n" | "no" | "" => false,
323             _ => {
324                 eprintln!("error: unrecognized option '{}'", input.trim());
325                 eprintln!("note: press Ctrl+C to exit");
326                 continue;
327             }
328         };
329     };
330
331     if should_install {
332         let src = config.src.join("src").join("etc").join("pre-push.sh");
333         let git =
334             t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
335                 assert!(output.status.success(), "failed to run `git`");
336                 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
337             }));
338         let dst = git.join("hooks").join("pre-push");
339         match fs::hard_link(src, &dst) {
340             Err(e) => eprintln!(
341                 "error: could not create hook {}: do you already have the git hook installed?\n{}",
342                 dst.display(),
343                 e
344             ),
345             Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
346         };
347     } else {
348         println!("Ok, skipping installation!");
349     }
350     Ok(())
351 }