2 use crate::{t, VERSION};
3 use std::env::consts::EXE_SUFFIX;
4 use std::fmt::Write as _;
7 use std::path::{Path, PathBuf, MAIN_SEPARATOR};
8 use std::process::Command;
10 use std::{fmt, fs, io};
12 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
22 fn include_path(&self, src_path: &Path) -> PathBuf {
23 PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
26 pub fn all() -> impl Iterator<Item = Self> {
28 // N.B. these are ordered by how they are displayed, not alphabetically
29 [Library, Compiler, Codegen, Tools, User].iter().copied()
32 pub fn purpose(&self) -> String {
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",
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();
53 impl FromStr for Profile {
56 fn from_str(s: &str) -> Result<Self, Self::Err> {
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" => {
65 _ => Err(format!("unknown profile: '{}'", s)),
70 impl fmt::Display for Profile {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
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"),
82 pub fn setup(config: &Config, profile: Option<Profile>) {
83 let profile = profile.unwrap_or_else(|| t!(interactive_path()));
85 ["build", config.build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
87 if !rustup_installed() && profile != Profile::User {
88 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
89 } else if stage_dir_exists(&stage_path[..]) {
90 attempt_toolchain_link(&stage_path[..]);
93 let suggestions = match profile {
94 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
98 "test src/test/rustdoc*",
99 "test src/tools/clippy",
100 "test src/tools/miri",
101 "test src/tools/rustfmt",
103 Profile::Library => &["check", "build", "test library/std", "doc"],
104 Profile::User => &["dist", "build"],
107 t!(install_git_hook_maybe(&config));
111 println!("To get started, try one of the following commands:");
112 for cmd in suggestions {
113 println!("- `x.py {}`", cmd);
116 if profile != Profile::User {
118 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
122 let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
123 setup_config_toml(path, profile, config);
126 fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) {
130 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
133 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
135 "note: this will use the configuration in {}",
136 profile.include_path(&config.src).display()
138 crate::detail_exit(1);
141 let settings = format!(
142 "# Includes one of the default files in src/bootstrap/defaults\n\
144 changelog-seen = {}\n",
147 t!(fs::write(path, settings));
149 let include_path = profile.include_path(&config.src);
150 println!("`x.py` will now use the configuration at {}", include_path.display());
153 fn rustup_installed() -> bool {
154 Command::new("rustup")
156 .stdout(std::process::Stdio::null())
158 .map_or(false, |output| output.status.success())
161 fn stage_dir_exists(stage_path: &str) -> bool {
162 match fs::create_dir(&stage_path) {
164 Err(_) => Path::new(&stage_path).exists(),
168 fn attempt_toolchain_link(stage_path: &str) {
169 if toolchain_is_linked() {
173 if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
175 "Failed to create a template for stage 1 toolchain or confirm that it already exists"
180 if try_link_toolchain(&stage_path) {
182 "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
185 eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
187 "To manually link stage 1 build to `stage1` toolchain, run:\n
188 `rustup toolchain link stage1 {}`",
194 fn toolchain_is_linked() -> bool {
195 match Command::new("rustup")
196 .args(&["toolchain", "list"])
197 .stdout(std::process::Stdio::piped())
200 Ok(toolchain_list) => {
201 if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
204 // The toolchain has already been linked.
206 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
210 // In this case, we don't know if the `stage1` toolchain has been linked;
211 // but `rustup` failed, so let's not go any further.
213 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
220 fn try_link_toolchain(stage_path: &str) -> bool {
221 Command::new("rustup")
222 .stdout(std::process::Stdio::null())
223 .args(&["toolchain", "link", "stage1", &stage_path])
225 .map_or(false, |output| output.status.success())
228 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
229 let pathbuf = PathBuf::from(stage_path);
231 if fs::create_dir_all(pathbuf.join("lib")).is_err() {
235 let pathbuf = pathbuf.join("bin");
236 if fs::create_dir_all(&pathbuf).is_err() {
240 let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
242 if pathbuf.exists() {
246 // Take care not to overwrite the file
247 let result = File::options().append(true).create(true).open(&pathbuf);
255 // Used to get the path for `Subcommand::Setup`
256 pub fn interactive_path() -> io::Result<Profile> {
257 fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
260 .map(|(letter, number)| (letter.to_string(), number.to_string()))
264 fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
265 let input = input.trim().to_lowercase();
266 for ((letter, number), profile) in abbrev_all() {
267 if input == letter || input == number {
274 println!("Welcome to the Rust project! What do you want to do with x.py?");
275 for ((letter, _), profile) in abbrev_all() {
276 println!("{}) {}: {}", letter, profile, profile.purpose());
278 let template = loop {
280 "Please choose one ({}): ",
281 abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
283 io::stdout().flush()?;
284 let mut input = String::new();
285 io::stdin().read_line(&mut input)?;
286 if input.is_empty() {
287 eprintln!("EOF on stdin, when expecting answer to question. Giving up.");
288 crate::detail_exit(1);
290 break match parse_with_abbrev(&input) {
291 Ok(profile) => profile,
293 eprintln!("error: {}", err);
294 eprintln!("note: press Ctrl+C to exit");
302 // install a git hook to automatically run tidy --bless, if they want
303 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
304 let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
305 assert!(output.status.success(), "failed to run `git`");
306 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
308 let dst = git.join("hooks").join("pre-push");
310 // The git hook has already been set up, or the user already has a custom hook.
314 let mut input = String::new();
317 "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
318 If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
319 pushing your code to ensure your code is up to par. If you decide later that this behavior is
320 undesirable, simply delete the `pre-push` file from .git/hooks."
323 let should_install = loop {
324 print!("Would you like to install the git hook?: [y/N] ");
325 io::stdout().flush()?;
327 io::stdin().read_line(&mut input)?;
328 break match input.trim().to_lowercase().as_str() {
330 "n" | "no" | "" => false,
332 eprintln!("error: unrecognized option '{}'", input.trim());
333 eprintln!("note: press Ctrl+C to exit");
340 let src = config.src.join("src").join("etc").join("pre-push.sh");
341 match fs::hard_link(src, &dst) {
343 "error: could not create hook {}: do you already have the git hook installed?\n{}",
347 Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
350 println!("Ok, skipping installation!");