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 path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
84 let profile = profile.unwrap_or_else(|| t!(interactive_path()));
85 setup_config_toml(path, profile, config);
88 ["build", config.build.rustc_target_arg(), "stage1"].join(&MAIN_SEPARATOR.to_string());
92 if !rustup_installed() && profile != Profile::User {
93 eprintln!("`rustup` is not installed; cannot link `stage1` toolchain");
94 } else if stage_dir_exists(&stage_path[..]) {
95 attempt_toolchain_link(&stage_path[..]);
98 let suggestions = match profile {
99 Profile::Codegen | Profile::Compiler => &["check", "build", "test"][..],
103 "test src/test/rustdoc*",
104 "test src/tools/clippy",
105 "test src/tools/miri",
106 "test src/tools/rustfmt",
108 Profile::Library => &["check", "build", "test library/std", "doc"],
109 Profile::User => &["dist", "build"],
114 t!(install_git_hook_maybe(&config));
118 println!("To get started, try one of the following commands:");
119 for cmd in suggestions {
120 println!("- `x.py {}`", cmd);
123 if profile != Profile::User {
125 "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
130 fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) {
133 "error: you asked `x.py` to setup a new config file, but one already exists at `{}`",
136 eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display());
138 "note: this will use the configuration in {}",
139 profile.include_path(&config.src).display()
141 crate::detail_exit(1);
144 let settings = format!(
145 "# Includes one of the default files in src/bootstrap/defaults\n\
147 changelog-seen = {}\n",
150 t!(fs::write(path, settings));
152 let include_path = profile.include_path(&config.src);
153 println!("`x.py` will now use the configuration at {}", include_path.display());
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!");