1 use crate::{t, VERSION};
2 use crate::{Config, TargetSelection};
3 use std::env::consts::EXE_SUFFIX;
4 use std::fmt::Write as _;
6 use std::path::{Path, PathBuf, MAIN_SEPARATOR};
7 use std::process::Command;
14 #[derive(Clone, Copy, Eq, PartialEq)]
24 fn include_path(&self, src_path: &Path) -> PathBuf {
25 PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self))
28 pub fn all() -> impl Iterator<Item = Self> {
30 // N.B. these are ordered by how they are displayed, not alphabetically
31 [Library, Compiler, Codegen, Tools, User].iter().copied()
34 pub fn purpose(&self) -> String {
37 Library => "Contribute to the standard library",
38 Compiler => "Contribute to the compiler itself",
39 Codegen => "Contribute to the compiler, and also modify LLVM or codegen",
40 Tools => "Contribute to tools which depend on the compiler, but do not modify it directly (e.g. rustdoc, clippy, miri)",
41 User => "Install Rust from source",
46 pub fn all_for_help(indent: &str) -> String {
47 let mut out = String::new();
48 for choice in Profile::all() {
49 writeln!(&mut out, "{}{}: {}", indent, choice, choice.purpose()).unwrap();
55 impl FromStr for Profile {
58 fn from_str(s: &str) -> Result<Self, Self::Err> {
60 "lib" | "library" => Ok(Profile::Library),
61 "compiler" => Ok(Profile::Compiler),
62 "llvm" | "codegen" => Ok(Profile::Codegen),
63 "maintainer" | "user" => Ok(Profile::User),
64 "tools" | "tool" | "rustdoc" | "clippy" | "miri" | "rustfmt" | "rls" => {
67 _ => Err(format!("unknown profile: '{}'", s)),
72 impl fmt::Display for Profile {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 Profile::Compiler => write!(f, "compiler"),
76 Profile::Codegen => write!(f, "codegen"),
77 Profile::Library => write!(f, "library"),
78 Profile::User => write!(f, "user"),
79 Profile::Tools => write!(f, "tools"),
84 pub fn setup(config: &Config, profile: Profile) {
85 let path = &config.config;
89 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
92 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
94 "note: this will use the configuration in {}",
95 profile.include_path(&config.src).display()
97 crate::detail_exit(1);
100 let settings = format!(
101 "# Includes one of the default files in src/bootstrap/defaults\n\
103 changelog-seen = {}\n",
106 t!(fs::write(path, settings));
108 let include_path = profile.include_path(&config.src);
109 println!("`x.py` will now use the configuration at {}", include_path.display());
111 let build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
113 ["build", build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
117 if !rustup_installed() && profile != Profile::User {
118 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
119 } else if stage_dir_exists(&stage_path[..]) {
120 attempt_toolchain_link(&stage_path[..]);
123 let suggestions = match profile {
124 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
128 "test src/test/rustdoc*",
129 "test src/tools/clippy",
130 "test src/tools/miri",
131 "test src/tools/rustfmt",
133 Profile::Library => &["check", "build", "test library/std", "doc"],
134 Profile::User => &["dist", "build"],
139 t!(install_git_hook_maybe(&config));
143 println!("To get started, try one of the following commands:");
144 for cmd in suggestions {
145 println!("- `x.py {}`", cmd);
148 if profile != Profile::User {
150 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
155 fn rustup_installed() -> bool {
156 Command::new("rustup")
158 .stdout(std::process::Stdio::null())
160 .map_or(false, |output| output.status.success())
163 fn stage_dir_exists(stage_path: &str) -> bool {
164 match fs::create_dir(&stage_path) {
166 Err(_) => Path::new(&stage_path).exists(),
170 fn attempt_toolchain_link(stage_path: &str) {
171 if toolchain_is_linked() {
175 if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
177 "Failed to create a template for stage 1 toolchain or confirm that it already exists"
182 if try_link_toolchain(&stage_path) {
184 "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
187 eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
189 "To manually link stage 1 build to `stage1` toolchain, run:\n
190 `rustup toolchain link stage1 {}`",
196 fn toolchain_is_linked() -> bool {
197 match Command::new("rustup")
198 .args(&["toolchain", "list"])
199 .stdout(std::process::Stdio::piped())
202 Ok(toolchain_list) => {
203 if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
206 // The toolchain has already been linked.
208 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
212 // In this case, we don't know if the `stage1` toolchain has been linked;
213 // but `rustup` failed, so let's not go any further.
215 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
222 fn try_link_toolchain(stage_path: &str) -> bool {
223 Command::new("rustup")
224 .stdout(std::process::Stdio::null())
225 .args(&["toolchain", "link", "stage1", &stage_path])
227 .map_or(false, |output| output.status.success())
230 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
231 let pathbuf = PathBuf::from(stage_path);
233 if fs::create_dir_all(pathbuf.join("lib")).is_err() {
237 let pathbuf = pathbuf.join("bin");
238 if fs::create_dir_all(&pathbuf).is_err() {
242 let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
244 if pathbuf.exists() {
248 // Take care not to overwrite the file
249 let result = File::options().append(true).create(true).open(&pathbuf);
257 // Used to get the path for `Subcommand::Setup`
258 pub fn interactive_path() -> io::Result<Profile> {
259 fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
262 .map(|(letter, number)| (letter.to_string(), number.to_string()))
266 fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
267 let input = input.trim().to_lowercase();
268 for ((letter, number), profile) in abbrev_all() {
269 if input == letter || input == number {
276 println!("Welcome to the Rust project! What do you want to do with x.py?");
277 for ((letter, _), profile) in abbrev_all() {
278 println!("{}) {}: {}", letter, profile, profile.purpose());
280 let template = loop {
282 "Please choose one ({}): ",
283 abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
285 io::stdout().flush()?;
286 let mut input = String::new();
287 io::stdin().read_line(&mut input)?;
288 if input.is_empty() {
289 eprintln!("EOF on stdin, when expecting answer to question. Giving up.");
290 crate::detail_exit(1);
292 break match parse_with_abbrev(&input) {
293 Ok(profile) => profile,
295 eprintln!("error: {}", err);
296 eprintln!("note: press Ctrl+C to exit");
304 // install a git hook to automatically run tidy --bless, if they want
305 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
306 let mut input = String::new();
308 "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
309 If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
310 pushing your code to ensure your code is up to par. If you decide later that this behavior is
311 undesirable, simply delete the `pre-push` file from .git/hooks."
314 let should_install = loop {
315 print!("Would you like to install the git hook?: [y/N] ");
316 io::stdout().flush()?;
318 io::stdin().read_line(&mut input)?;
319 break match input.trim().to_lowercase().as_str() {
321 "n" | "no" | "" => false,
323 eprintln!("error: unrecognized option '{}'", input.trim());
324 eprintln!("note: press Ctrl+C to exit");
331 let src = config.src.join("src").join("etc").join("pre-push.sh");
333 t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
334 assert!(output.status.success(), "failed to run `git`");
335 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
337 let dst = git.join("hooks").join("pre-push");
338 match fs::hard_link(src, &dst) {
340 "error: could not create hook {}: do you already have the git hook installed?\n{}",
344 Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
347 println!("Ok, skipping installation!");