1 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
3 use crate::{t, VERSION};
4 use std::env::consts::EXE_SUFFIX;
5 use std::fmt::Write as _;
8 use std::path::{Path, PathBuf, MAIN_SEPARATOR};
9 use std::process::Command;
10 use std::str::FromStr;
11 use std::{fmt, fs, io};
13 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
23 fn include_path(&self, src_path: &Path) -> PathBuf {
24 PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
27 pub fn all() -> impl Iterator<Item = Self> {
29 // N.B. these are ordered by how they are displayed, not alphabetically
30 [Library, Compiler, Codegen, Tools, User].iter().copied()
33 pub fn purpose(&self) -> String {
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",
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();
53 pub fn as_str(&self) -> &'static str {
55 Profile::Compiler => "compiler",
56 Profile::Codegen => "codegen",
57 Profile::Library => "library",
58 Profile::Tools => "tools",
59 Profile::User => "user",
64 impl FromStr for Profile {
67 fn from_str(s: &str) -> Result<Self, Self::Err> {
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" => {
76 _ => Err(format!("unknown profile: '{}'", s)),
81 impl fmt::Display for Profile {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_str(self.as_str())
87 impl Step for Profile {
89 const DEFAULT: bool = true;
91 fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
92 for choice in Profile::all() {
93 run = run.alias(choice.as_str());
98 fn make_run(run: RunConfig<'_>) {
99 if run.builder.config.dry_run() {
103 // for Profile, `run.paths` will have 1 and only 1 element
104 // this is because we only accept at most 1 path from user input.
105 // If user calls `x.py setup` without arguments, the interactive TUI
106 // will guide user to provide one.
107 let profile = if run.paths.len() > 1 {
108 // HACK: `builder` runs this step with all paths if no path was passed.
109 t!(interactive_path())
114 .assert_single_path()
124 run.builder.ensure(profile);
127 fn run(self, builder: &Builder<'_>) {
128 setup(&builder.build.config, self)
132 pub fn setup(config: &Config, profile: Profile) {
134 ["build", config.build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
136 if !rustup_installed() && profile != Profile::User {
137 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
138 } else if stage_dir_exists(&stage_path[..]) && !config.dry_run() {
139 attempt_toolchain_link(&stage_path[..]);
142 let suggestions = match profile {
143 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
147 "test tests/rustdoc*",
148 "test src/tools/clippy",
149 "test src/tools/miri",
150 "test src/tools/rustfmt",
152 Profile::Library => &["check", "build", "test library/std", "doc"],
153 Profile::User => &["dist", "build"],
156 if !config.dry_run() {
157 t!(install_git_hook_maybe(&config));
162 println!("To get started, try one of the following commands:");
163 for cmd in suggestions {
164 println!("- `x.py {}`", cmd);
167 if profile != Profile::User {
169 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
173 let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
174 setup_config_toml(path, profile, config);
177 fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) {
181 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
184 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
186 "note: this will use the configuration in {}",
187 profile.include_path(&config.src).display()
189 crate::detail_exit(1);
192 let settings = format!(
193 "# Includes one of the default files in src/bootstrap/defaults\n\
195 changelog-seen = {}\n",
199 t!(fs::write(path, settings));
201 let include_path = profile.include_path(&config.src);
202 println!("`x.py` will now use the configuration at {}", include_path.display());
205 fn rustup_installed() -> bool {
206 Command::new("rustup")
208 .stdout(std::process::Stdio::null())
210 .map_or(false, |output| output.status.success())
213 fn stage_dir_exists(stage_path: &str) -> bool {
214 match fs::create_dir(&stage_path) {
216 Err(_) => Path::new(&stage_path).exists(),
220 fn attempt_toolchain_link(stage_path: &str) {
221 if toolchain_is_linked() {
225 if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
227 "Failed to create a template for stage 1 toolchain or confirm that it already exists"
232 if try_link_toolchain(&stage_path) {
234 "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
237 eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
239 "To manually link stage 1 build to `stage1` toolchain, run:\n
240 `rustup toolchain link stage1 {}`",
246 fn toolchain_is_linked() -> bool {
247 match Command::new("rustup")
248 .args(&["toolchain", "list"])
249 .stdout(std::process::Stdio::piped())
252 Ok(toolchain_list) => {
253 if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
256 // The toolchain has already been linked.
258 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
262 // In this case, we don't know if the `stage1` toolchain has been linked;
263 // but `rustup` failed, so let's not go any further.
265 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
272 fn try_link_toolchain(stage_path: &str) -> bool {
273 Command::new("rustup")
274 .stdout(std::process::Stdio::null())
275 .args(&["toolchain", "link", "stage1", &stage_path])
277 .map_or(false, |output| output.status.success())
280 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
281 let pathbuf = PathBuf::from(stage_path);
283 if fs::create_dir_all(pathbuf.join("lib")).is_err() {
287 let pathbuf = pathbuf.join("bin");
288 if fs::create_dir_all(&pathbuf).is_err() {
292 let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
294 if pathbuf.exists() {
298 // Take care not to overwrite the file
299 let result = File::options().append(true).create(true).open(&pathbuf);
307 // Used to get the path for `Subcommand::Setup`
308 pub fn interactive_path() -> io::Result<Profile> {
309 fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
312 .map(|(letter, number)| (letter.to_string(), number.to_string()))
316 fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
317 let input = input.trim().to_lowercase();
318 for ((letter, number), profile) in abbrev_all() {
319 if input == letter || input == number {
326 println!("Welcome to the Rust project! What do you want to do with x.py?");
327 for ((letter, _), profile) in abbrev_all() {
328 println!("{}) {}: {}", letter, profile, profile.purpose());
330 let template = loop {
332 "Please choose one ({}): ",
333 abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
335 io::stdout().flush()?;
336 let mut input = String::new();
337 io::stdin().read_line(&mut input)?;
338 if input.is_empty() {
339 eprintln!("EOF on stdin, when expecting answer to question. Giving up.");
340 crate::detail_exit(1);
342 break match parse_with_abbrev(&input) {
343 Ok(profile) => profile,
345 eprintln!("error: {}", err);
346 eprintln!("note: press Ctrl+C to exit");
354 // install a git hook to automatically run tidy, if they want
355 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
356 let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
357 assert!(output.status.success(), "failed to run `git`");
358 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
360 let dst = git.join("hooks").join("pre-push");
362 // The git hook has already been set up, or the user already has a custom hook.
366 let mut input = String::new();
369 "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
370 If you'd like, x.py can install a git hook for you that will automatically run `test tidy` before
371 pushing your code to ensure your code is up to par. If you decide later that this behavior is
372 undesirable, simply delete the `pre-push` file from .git/hooks."
375 let should_install = loop {
376 print!("Would you like to install the git hook?: [y/N] ");
377 io::stdout().flush()?;
379 io::stdin().read_line(&mut input)?;
380 break match input.trim().to_lowercase().as_str() {
382 "n" | "no" | "" => false,
384 eprintln!("error: unrecognized option '{}'", input.trim());
385 eprintln!("note: press Ctrl+C to exit");
392 let src = config.src.join("src").join("etc").join("pre-push.sh");
393 match fs::hard_link(src, &dst) {
395 "error: could not create hook {}: do you already have the git hook installed?\n{}",
399 Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
402 println!("Ok, skipping installation!");