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