1 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
3 use crate::{t, VERSION};
5 use std::env::consts::EXE_SUFFIX;
6 use std::fmt::Write as _;
9 use std::path::{Path, PathBuf, MAIN_SEPARATOR};
10 use std::process::Command;
11 use std::str::FromStr;
12 use std::{fmt, fs, io};
17 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
26 /// A list of historical hashes of `src/etc/vscode_settings.json`.
27 /// New entries should be appended whenever this is updated so we can detected
28 /// outdated vs. user-modified settings files.
29 static SETTINGS_HASHES: &[&str] =
30 &["ea67e259dedf60d4429b6c349a564ffcd1563cf41c920a856d1f5b16b4701ac8"];
31 static VSCODE_SETTINGS: &str = include_str!("../etc/vscode_settings.json");
34 fn include_path(&self, src_path: &Path) -> PathBuf {
35 PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
38 pub fn all() -> impl Iterator<Item = Self> {
40 // N.B. these are ordered by how they are displayed, not alphabetically
41 [Library, Compiler, Codegen, Tools, User].iter().copied()
44 pub fn purpose(&self) -> String {
47 Library => "Contribute to the standard library",
48 Compiler => "Contribute to the compiler itself",
49 Codegen => "Contribute to the compiler, and also modify LLVM or codegen",
50 Tools => "Contribute to tools which depend on the compiler, but do not modify it directly (e.g. rustdoc, clippy, miri)",
51 User => "Install Rust from source",
56 pub fn all_for_help(indent: &str) -> String {
57 let mut out = String::new();
58 for choice in Profile::all() {
59 writeln!(&mut out, "{}{}: {}", indent, choice, choice.purpose()).unwrap();
64 pub fn as_str(&self) -> &'static str {
66 Profile::Compiler => "compiler",
67 Profile::Codegen => "codegen",
68 Profile::Library => "library",
69 Profile::Tools => "tools",
70 Profile::User => "user",
75 impl FromStr for Profile {
78 fn from_str(s: &str) -> Result<Self, Self::Err> {
80 "lib" | "library" => Ok(Profile::Library),
81 "compiler" => Ok(Profile::Compiler),
82 "llvm" | "codegen" => Ok(Profile::Codegen),
83 "maintainer" | "user" => Ok(Profile::User),
84 "tools" | "tool" | "rustdoc" | "clippy" | "miri" | "rustfmt" | "rls" => {
87 _ => Err(format!("unknown profile: '{}'", s)),
92 impl fmt::Display for Profile {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str(self.as_str())
98 impl Step for Profile {
100 const DEFAULT: bool = true;
102 fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
103 for choice in Profile::all() {
104 run = run.alias(choice.as_str());
109 fn make_run(run: RunConfig<'_>) {
110 if run.builder.config.dry_run() {
114 // for Profile, `run.paths` will have 1 and only 1 element
115 // this is because we only accept at most 1 path from user input.
116 // If user calls `x.py setup` without arguments, the interactive TUI
117 // will guide user to provide one.
118 let profile = if run.paths.len() > 1 {
119 // HACK: `builder` runs this step with all paths if no path was passed.
120 t!(interactive_path())
125 .assert_single_path()
135 run.builder.ensure(profile);
138 fn run(self, builder: &Builder<'_>) {
139 setup(&builder.build.config, self)
143 pub fn setup(config: &Config, profile: Profile) {
145 ["build", config.build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
147 if !rustup_installed() && profile != Profile::User {
148 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
149 } else if stage_dir_exists(&stage_path[..]) && !config.dry_run() {
150 attempt_toolchain_link(&stage_path[..]);
153 let suggestions = match profile {
154 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
158 "test tests/rustdoc*",
159 "test src/tools/clippy",
160 "test src/tools/miri",
161 "test src/tools/rustfmt",
163 Profile::Library => &["check", "build", "test library/std", "doc"],
164 Profile::User => &["dist", "build"],
167 if !config.dry_run() {
168 t!(install_git_hook_maybe(&config));
169 t!(create_vscode_settings_maybe(&config));
174 println!("To get started, try one of the following commands:");
175 for cmd in suggestions {
176 println!("- `x.py {}`", cmd);
179 if profile != Profile::User {
181 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
185 let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
186 setup_config_toml(path, profile, config);
189 fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) {
193 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
196 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
198 "note: this will use the configuration in {}",
199 profile.include_path(&config.src).display()
201 crate::detail_exit(1);
204 let settings = format!(
205 "# Includes one of the default files in src/bootstrap/defaults\n\
207 changelog-seen = {}\n",
211 t!(fs::write(path, settings));
213 let include_path = profile.include_path(&config.src);
214 println!("`x.py` will now use the configuration at {}", include_path.display());
217 fn rustup_installed() -> bool {
218 Command::new("rustup")
220 .stdout(std::process::Stdio::null())
222 .map_or(false, |output| output.status.success())
225 fn stage_dir_exists(stage_path: &str) -> bool {
226 match fs::create_dir(&stage_path) {
228 Err(_) => Path::new(&stage_path).exists(),
232 fn attempt_toolchain_link(stage_path: &str) {
233 if toolchain_is_linked() {
237 if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
239 "Failed to create a template for stage 1 toolchain or confirm that it already exists"
244 if try_link_toolchain(&stage_path) {
246 "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
249 eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
251 "To manually link stage 1 build to `stage1` toolchain, run:\n
252 `rustup toolchain link stage1 {}`",
258 fn toolchain_is_linked() -> bool {
259 match Command::new("rustup")
260 .args(&["toolchain", "list"])
261 .stdout(std::process::Stdio::piped())
264 Ok(toolchain_list) => {
265 if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
268 // The toolchain has already been linked.
270 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
274 // In this case, we don't know if the `stage1` toolchain has been linked;
275 // but `rustup` failed, so let's not go any further.
277 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
284 fn try_link_toolchain(stage_path: &str) -> bool {
285 Command::new("rustup")
286 .stdout(std::process::Stdio::null())
287 .args(&["toolchain", "link", "stage1", &stage_path])
289 .map_or(false, |output| output.status.success())
292 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
293 let pathbuf = PathBuf::from(stage_path);
295 if fs::create_dir_all(pathbuf.join("lib")).is_err() {
299 let pathbuf = pathbuf.join("bin");
300 if fs::create_dir_all(&pathbuf).is_err() {
304 let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
306 if pathbuf.exists() {
310 // Take care not to overwrite the file
311 let result = File::options().append(true).create(true).open(&pathbuf);
319 // Used to get the path for `Subcommand::Setup`
320 pub fn interactive_path() -> io::Result<Profile> {
321 fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
324 .map(|(letter, number)| (letter.to_string(), number.to_string()))
328 fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
329 let input = input.trim().to_lowercase();
330 for ((letter, number), profile) in abbrev_all() {
331 if input == letter || input == number {
338 println!("Welcome to the Rust project! What do you want to do with x.py?");
339 for ((letter, _), profile) in abbrev_all() {
340 println!("{}) {}: {}", letter, profile, profile.purpose());
342 let template = loop {
344 "Please choose one ({}): ",
345 abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
347 io::stdout().flush()?;
348 let mut input = String::new();
349 io::stdin().read_line(&mut input)?;
350 if input.is_empty() {
351 eprintln!("EOF on stdin, when expecting answer to question. Giving up.");
352 crate::detail_exit(1);
354 break match parse_with_abbrev(&input) {
355 Ok(profile) => profile,
357 eprintln!("error: {}", err);
358 eprintln!("note: press Ctrl+C to exit");
373 /// Prompt a user for a answer, looping until they enter an accepted input or nothing
374 fn prompt_user(prompt: &str) -> io::Result<Option<PromptResult>> {
375 let mut input = String::new();
378 io::stdout().flush()?;
380 io::stdin().read_line(&mut input)?;
381 match input.trim().to_lowercase().as_str() {
382 "y" | "yes" => return Ok(Some(PromptResult::Yes)),
383 "n" | "no" => return Ok(Some(PromptResult::No)),
384 "p" | "print" => return Ok(Some(PromptResult::Print)),
385 "" => return Ok(None),
387 eprintln!("error: unrecognized option '{}'", input.trim());
388 eprintln!("note: press Ctrl+C to exit");
394 // install a git hook to automatically run tidy, if they want
395 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
396 let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
397 assert!(output.status.success(), "failed to run `git`");
398 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
400 let dst = git.join("hooks").join("pre-push");
402 // The git hook has already been set up, or the user already has a custom hook.
407 "\nRust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
408 If you'd like, x.py can install a git hook for you that will automatically run `test tidy` before
409 pushing your code to ensure your code is up to par. If you decide later that this behavior is
410 undesirable, simply delete the `pre-push` file from .git/hooks."
413 if prompt_user("Would you like to install the git hook?: [y/N]")? != Some(PromptResult::Yes) {
414 println!("Ok, skipping installation!");
417 let src = config.src.join("src").join("etc").join("pre-push.sh");
418 match fs::hard_link(src, &dst) {
421 "error: could not create hook {}: do you already have the git hook installed?\n{}",
427 Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
432 /// Create a `.vscode/settings.json` file for rustc development, or just print it
433 fn create_vscode_settings_maybe(config: &Config) -> io::Result<()> {
434 let (current_hash, historical_hashes) = SETTINGS_HASHES.split_last().unwrap();
435 let vscode_settings = config.src.join(".vscode").join("settings.json");
436 // If None, no settings.json exists
437 // If Some(true), is a previous version of settings.json
438 // If Some(false), is not a previous version (i.e. user modified)
439 // If it's up to date we can just skip this
440 let mut mismatched_settings = None;
441 if let Ok(current) = fs::read_to_string(&vscode_settings) {
442 let mut hasher = sha2::Sha256::new();
443 hasher.update(¤t);
444 let hash = hex::encode(hasher.finalize().as_slice());
445 if hash == *current_hash {
447 } else if historical_hashes.contains(&hash.as_str()) {
448 mismatched_settings = Some(true);
450 mismatched_settings = Some(false);
454 "\nx.py can automatically install the recommended `.vscode/settings.json` file for rustc development"
456 match mismatched_settings {
457 Some(true) => eprintln!(
458 "warning: existing `.vscode/settings.json` is out of date, x.py will update it"
460 Some(false) => eprintln!(
461 "warning: existing `.vscode/settings.json` has been modified by user, x.py will back it up and replace it"
465 let should_create = match prompt_user(
466 "Would you like to create/update `settings.json`, or only print suggested settings?: [y/p/N]",
468 Some(PromptResult::Yes) => true,
469 Some(PromptResult::Print) => false,
471 println!("Ok, skipping settings!");
476 let path = config.src.join(".vscode");
478 fs::create_dir(&path)?;
480 let verb = match mismatched_settings {
481 // exists but outdated, we can replace this
482 Some(true) => "Updated",
483 // exists but user modified, back it up
485 // exists and is not current version or outdated, so back it up
486 let mut backup = vscode_settings.clone();
487 backup.set_extension("bak");
488 eprintln!("warning: copying `settings.json` to `settings.json.bak`");
489 fs::copy(&vscode_settings, &backup)?;
494 fs::write(&vscode_settings, &VSCODE_SETTINGS)?;
495 println!("{verb} `.vscode/settings.json`");
497 println!("\n{VSCODE_SETTINGS}");