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, Debug, 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: Option<Profile>) {
85 let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
86 let profile = profile.unwrap_or_else(|| t!(interactive_path()));
90 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
93 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
95 "note: this will use the configuration in {}",
96 profile.include_path(&config.src).display()
98 crate::detail_exit(1);
101 let settings = format!(
102 "# Includes one of the default files in src/bootstrap/defaults\n\
104 changelog-seen = {}\n",
107 t!(fs::write(path, settings));
109 let include_path = profile.include_path(&config.src);
110 println!("`x.py` will now use the configuration at {}", include_path.display());
112 let build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
114 ["build", build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
118 if !rustup_installed() && profile != Profile::User {
119 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
120 } else if stage_dir_exists(&stage_path[..]) {
121 attempt_toolchain_link(&stage_path[..]);
124 let suggestions = match profile {
125 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
129 "test src/test/rustdoc*",
130 "test src/tools/clippy",
131 "test src/tools/miri",
132 "test src/tools/rustfmt",
134 Profile::Library => &["check", "build", "test library/std", "doc"],
135 Profile::User => &["dist", "build"],
140 t!(install_git_hook_maybe(&config));
144 println!("To get started, try one of the following commands:");
145 for cmd in suggestions {
146 println!("- `x.py {}`", cmd);
149 if profile != Profile::User {
151 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
156 fn rustup_installed() -> bool {
157 Command::new("rustup")
159 .stdout(std::process::Stdio::null())
161 .map_or(false, |output| output.status.success())
164 fn stage_dir_exists(stage_path: &str) -> bool {
165 match fs::create_dir(&stage_path) {
167 Err(_) => Path::new(&stage_path).exists(),
171 fn attempt_toolchain_link(stage_path: &str) {
172 if toolchain_is_linked() {
176 if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
178 "Failed to create a template for stage 1 toolchain or confirm that it already exists"
183 if try_link_toolchain(&stage_path) {
185 "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
188 eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
190 "To manually link stage 1 build to `stage1` toolchain, run:\n
191 `rustup toolchain link stage1 {}`",
197 fn toolchain_is_linked() -> bool {
198 match Command::new("rustup")
199 .args(&["toolchain", "list"])
200 .stdout(std::process::Stdio::piped())
203 Ok(toolchain_list) => {
204 if !String::from_utf8_lossy(&toolchain_list.stdout).contains("stage1") {
207 // The toolchain has already been linked.
209 "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
213 // In this case, we don't know if the `stage1` toolchain has been linked;
214 // but `rustup` failed, so let's not go any further.
216 "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
223 fn try_link_toolchain(stage_path: &str) -> bool {
224 Command::new("rustup")
225 .stdout(std::process::Stdio::null())
226 .args(&["toolchain", "link", "stage1", &stage_path])
228 .map_or(false, |output| output.status.success())
231 fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
232 let pathbuf = PathBuf::from(stage_path);
234 if fs::create_dir_all(pathbuf.join("lib")).is_err() {
238 let pathbuf = pathbuf.join("bin");
239 if fs::create_dir_all(&pathbuf).is_err() {
243 let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX));
245 if pathbuf.exists() {
249 // Take care not to overwrite the file
250 let result = File::options().append(true).create(true).open(&pathbuf);
258 // Used to get the path for `Subcommand::Setup`
259 pub fn interactive_path() -> io::Result<Profile> {
260 fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
263 .map(|(letter, number)| (letter.to_string(), number.to_string()))
267 fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
268 let input = input.trim().to_lowercase();
269 for ((letter, number), profile) in abbrev_all() {
270 if input == letter || input == number {
277 println!("Welcome to the Rust project! What do you want to do with x.py?");
278 for ((letter, _), profile) in abbrev_all() {
279 println!("{}) {}: {}", letter, profile, profile.purpose());
281 let template = loop {
283 "Please choose one ({}): ",
284 abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
286 io::stdout().flush()?;
287 let mut input = String::new();
288 io::stdin().read_line(&mut input)?;
289 if input.is_empty() {
290 eprintln!("EOF on stdin, when expecting answer to question. Giving up.");
291 crate::detail_exit(1);
293 break match parse_with_abbrev(&input) {
294 Ok(profile) => profile,
296 eprintln!("error: {}", err);
297 eprintln!("note: press Ctrl+C to exit");
305 // install a git hook to automatically run tidy --bless, if they want
306 fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
307 let mut input = String::new();
309 "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
310 If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
311 pushing your code to ensure your code is up to par. If you decide later that this behavior is
312 undesirable, simply delete the `pre-push` file from .git/hooks."
315 let should_install = loop {
316 print!("Would you like to install the git hook?: [y/N] ");
317 io::stdout().flush()?;
319 io::stdin().read_line(&mut input)?;
320 break match input.trim().to_lowercase().as_str() {
322 "n" | "no" | "" => false,
324 eprintln!("error: unrecognized option '{}'", input.trim());
325 eprintln!("note: press Ctrl+C to exit");
332 let src = config.src.join("src").join("etc").join("pre-push.sh");
334 t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
335 assert!(output.status.success(), "failed to run `git`");
336 PathBuf::from(t!(String::from_utf8(output.stdout)).trim())
338 let dst = git.join("hooks").join("pre-push");
339 match fs::hard_link(src, &dst) {
341 "error: could not create hook {}: do you already have the git hook installed?\n{}",
345 Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
348 println!("Ok, skipping installation!");