bootstrap/core/build_steps/
setup.rs

1//! First time setup of a dev environment
2//!
3//! These are build-and-run steps for `./x.py setup`, which allows quickly setting up the directory
4//! for modifying, building, and running the compiler and library. Running arbitrary configuration
5//! allows setting up things that cannot be simply captured inside the config.toml, in addition to
6//! leading people away from manually editing most of the config.toml values.
7
8use std::env::consts::EXE_SUFFIX;
9use std::fmt::Write as _;
10use std::fs::File;
11use std::io::Write;
12use std::path::{MAIN_SEPARATOR_STR, Path, PathBuf};
13use std::str::FromStr;
14use std::{fmt, fs, io};
15
16use sha2::Digest;
17
18use crate::core::builder::{Builder, RunConfig, ShouldRun, Step};
19use crate::utils::change_tracker::CONFIG_CHANGE_HISTORY;
20use crate::utils::exec::command;
21use crate::utils::helpers::{self, hex_encode};
22use crate::{Config, t};
23
24#[cfg(test)]
25mod tests;
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
28pub enum Profile {
29    Compiler,
30    Library,
31    Tools,
32    Dist,
33    None,
34}
35
36static PROFILE_DIR: &str = "src/bootstrap/defaults";
37
38impl Profile {
39    fn include_path(&self, src_path: &Path) -> PathBuf {
40        PathBuf::from(format!("{}/{PROFILE_DIR}/config.{}.toml", src_path.display(), self))
41    }
42
43    pub fn all() -> impl Iterator<Item = Self> {
44        use Profile::*;
45        // N.B. these are ordered by how they are displayed, not alphabetically
46        [Library, Compiler, Tools, Dist, None].iter().copied()
47    }
48
49    pub fn purpose(&self) -> String {
50        use Profile::*;
51        match self {
52            Library => "Contribute to the standard library",
53            Compiler => "Contribute to the compiler itself",
54            Tools => "Contribute to tools which depend on the compiler, but do not modify it directly (e.g. rustdoc, clippy, miri)",
55            Dist => "Install Rust from source",
56            None => "Do not modify `config.toml`"
57        }
58        .to_string()
59    }
60
61    pub fn all_for_help(indent: &str) -> String {
62        let mut out = String::new();
63        for choice in Profile::all() {
64            writeln!(&mut out, "{}{}: {}", indent, choice, choice.purpose()).unwrap();
65        }
66        out
67    }
68
69    pub fn as_str(&self) -> &'static str {
70        match self {
71            Profile::Compiler => "compiler",
72            Profile::Library => "library",
73            Profile::Tools => "tools",
74            Profile::Dist => "dist",
75            Profile::None => "none",
76        }
77    }
78}
79
80impl FromStr for Profile {
81    type Err = String;
82
83    fn from_str(s: &str) -> Result<Self, Self::Err> {
84        match s {
85            "lib" | "library" => Ok(Profile::Library),
86            "compiler" => Ok(Profile::Compiler),
87            "maintainer" | "dist" | "user" => Ok(Profile::Dist),
88            "tools" | "tool" | "rustdoc" | "clippy" | "miri" | "rustfmt" => Ok(Profile::Tools),
89            "none" => Ok(Profile::None),
90            "llvm" | "codegen" => Err("the \"llvm\" and \"codegen\" profiles have been removed,\
91                use \"compiler\" instead which has the same functionality"
92                .to_string()),
93            _ => Err(format!("unknown profile: '{s}'")),
94        }
95    }
96}
97
98impl fmt::Display for Profile {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(self.as_str())
101    }
102}
103
104impl Step for Profile {
105    type Output = ();
106    const DEFAULT: bool = true;
107
108    fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
109        for choice in Profile::all() {
110            run = run.alias(choice.as_str());
111        }
112        run
113    }
114
115    fn make_run(run: RunConfig<'_>) {
116        if run.builder.config.dry_run() {
117            return;
118        }
119
120        let path = &run.builder.config.config.clone().unwrap_or(PathBuf::from("config.toml"));
121        if path.exists() {
122            eprintln!();
123            eprintln!(
124                "ERROR: you asked for a new config file, but one already exists at `{}`",
125                t!(path.canonicalize()).display()
126            );
127
128            match prompt_user(
129                "Do you wish to override the existing configuration (which will allow the setup process to continue)?: [y/N]",
130            ) {
131                Ok(Some(PromptResult::Yes)) => {
132                    t!(fs::remove_file(path));
133                }
134                _ => {
135                    println!("Exiting.");
136                    crate::exit!(1);
137                }
138            }
139        }
140
141        // for Profile, `run.paths` will have 1 and only 1 element
142        // this is because we only accept at most 1 path from user input.
143        // If user calls `x.py setup` without arguments, the interactive TUI
144        // will guide user to provide one.
145        let profile = if run.paths.len() > 1 {
146            // HACK: `builder` runs this step with all paths if no path was passed.
147            t!(interactive_path())
148        } else {
149            run.paths
150                .first()
151                .unwrap()
152                .assert_single_path()
153                .path
154                .as_path()
155                .as_os_str()
156                .to_str()
157                .unwrap()
158                .parse()
159                .unwrap()
160        };
161
162        run.builder.ensure(profile);
163    }
164
165    fn run(self, builder: &Builder<'_>) {
166        setup(&builder.build.config, self);
167    }
168}
169
170pub fn setup(config: &Config, profile: Profile) {
171    let suggestions: &[&str] = match profile {
172        Profile::Compiler | Profile::None => &["check", "build", "test"],
173        Profile::Tools => &[
174            "check",
175            "build",
176            "test tests/rustdoc*",
177            "test src/tools/clippy",
178            "test src/tools/miri",
179            "test src/tools/rustfmt",
180        ],
181        Profile::Library => &["check", "build", "test library/std", "doc"],
182        Profile::Dist => &["dist", "build"],
183    };
184
185    println!();
186
187    println!("To get started, try one of the following commands:");
188    for cmd in suggestions {
189        println!("- `x.py {cmd}`");
190    }
191
192    if profile != Profile::Dist {
193        println!(
194            "For more suggestions, see https://rustc-dev-guide.rust-lang.org/building/suggested.html"
195        );
196    }
197
198    if profile == Profile::Tools {
199        eprintln!();
200        eprintln!(
201            "NOTE: the `tools` profile sets up the `stage2` toolchain (use \
202            `rustup toolchain link 'name' build/host/stage2` to use rustc)"
203        )
204    }
205
206    let path = &config.config.clone().unwrap_or(PathBuf::from("config.toml"));
207    setup_config_toml(path, profile, config);
208}
209
210fn setup_config_toml(path: &Path, profile: Profile, config: &Config) {
211    if profile == Profile::None {
212        return;
213    }
214
215    let latest_change_id = CONFIG_CHANGE_HISTORY.last().unwrap().change_id;
216    let settings = format!(
217        "# Includes one of the default files in {PROFILE_DIR}\n\
218    profile = \"{profile}\"\n\
219    change-id = {latest_change_id}\n"
220    );
221
222    t!(fs::write(path, settings));
223
224    let include_path = profile.include_path(&config.src);
225    println!("`x.py` will now use the configuration at {}", include_path.display());
226}
227
228/// Creates a toolchain link for stage1 using `rustup`
229#[derive(Clone, Debug, Eq, PartialEq, Hash)]
230pub struct Link;
231impl Step for Link {
232    type Output = ();
233    const DEFAULT: bool = true;
234
235    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
236        run.alias("link")
237    }
238
239    fn make_run(run: RunConfig<'_>) {
240        if run.builder.config.dry_run() {
241            return;
242        }
243        if let [cmd] = &run.paths[..] {
244            if cmd.assert_single_path().path.as_path().as_os_str() == "link" {
245                run.builder.ensure(Link);
246            }
247        }
248    }
249    fn run(self, builder: &Builder<'_>) -> Self::Output {
250        let config = &builder.config;
251
252        if config.dry_run() {
253            return;
254        }
255
256        if !rustup_installed(builder) {
257            println!("WARNING: `rustup` is not installed; Skipping `stage1` toolchain linking.");
258            return;
259        }
260
261        let stage_path =
262            ["build", config.build.rustc_target_arg(), "stage1"].join(MAIN_SEPARATOR_STR);
263
264        if stage_dir_exists(&stage_path[..]) && !config.dry_run() {
265            attempt_toolchain_link(builder, &stage_path[..]);
266        }
267    }
268}
269
270fn rustup_installed(builder: &Builder<'_>) -> bool {
271    let mut rustup = command("rustup");
272    rustup.arg("--version");
273
274    rustup.allow_failure().run_always().run_capture_stdout(builder).is_success()
275}
276
277fn stage_dir_exists(stage_path: &str) -> bool {
278    match fs::create_dir(stage_path) {
279        Ok(_) => true,
280        Err(_) => Path::new(&stage_path).exists(),
281    }
282}
283
284fn attempt_toolchain_link(builder: &Builder<'_>, stage_path: &str) {
285    if toolchain_is_linked(builder) {
286        return;
287    }
288
289    if !ensure_stage1_toolchain_placeholder_exists(stage_path) {
290        eprintln!(
291            "Failed to create a template for stage 1 toolchain or confirm that it already exists"
292        );
293        return;
294    }
295
296    if try_link_toolchain(builder, stage_path) {
297        println!(
298            "Added `stage1` rustup toolchain; try `cargo +stage1 build` on a separate rust project to run a newly-built toolchain"
299        );
300    } else {
301        eprintln!("`rustup` failed to link stage 1 build to `stage1` toolchain");
302        eprintln!(
303            "To manually link stage 1 build to `stage1` toolchain, run:\n
304            `rustup toolchain link stage1 {}`",
305            &stage_path
306        );
307    }
308}
309
310fn toolchain_is_linked(builder: &Builder<'_>) -> bool {
311    match command("rustup")
312        .allow_failure()
313        .args(["toolchain", "list"])
314        .run_capture_stdout(builder)
315        .stdout_if_ok()
316    {
317        Some(toolchain_list) => {
318            if !toolchain_list.contains("stage1") {
319                return false;
320            }
321            // The toolchain has already been linked.
322            println!(
323                "`stage1` toolchain already linked; not attempting to link `stage1` toolchain"
324            );
325        }
326        None => {
327            // In this case, we don't know if the `stage1` toolchain has been linked;
328            // but `rustup` failed, so let's not go any further.
329            println!(
330                "`rustup` failed to list current toolchains; not attempting to link `stage1` toolchain"
331            );
332        }
333    }
334    true
335}
336
337fn try_link_toolchain(builder: &Builder<'_>, stage_path: &str) -> bool {
338    command("rustup")
339        .args(["toolchain", "link", "stage1", stage_path])
340        .run_capture_stdout(builder)
341        .is_success()
342}
343
344fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool {
345    let pathbuf = PathBuf::from(stage_path);
346
347    if fs::create_dir_all(pathbuf.join("lib")).is_err() {
348        return false;
349    };
350
351    let pathbuf = pathbuf.join("bin");
352    if fs::create_dir_all(&pathbuf).is_err() {
353        return false;
354    };
355
356    let pathbuf = pathbuf.join(format!("rustc{EXE_SUFFIX}"));
357
358    if pathbuf.exists() {
359        return true;
360    }
361
362    // Take care not to overwrite the file
363    let result = File::options().append(true).create(true).open(&pathbuf);
364    if result.is_err() {
365        return false;
366    }
367
368    true
369}
370
371// Used to get the path for `Subcommand::Setup`
372pub fn interactive_path() -> io::Result<Profile> {
373    fn abbrev_all() -> impl Iterator<Item = ((String, String), Profile)> {
374        ('a'..)
375            .zip(1..)
376            .map(|(letter, number)| (letter.to_string(), number.to_string()))
377            .zip(Profile::all())
378    }
379
380    fn parse_with_abbrev(input: &str) -> Result<Profile, String> {
381        let input = input.trim().to_lowercase();
382        for ((letter, number), profile) in abbrev_all() {
383            if input == letter || input == number {
384                return Ok(profile);
385            }
386        }
387        input.parse()
388    }
389
390    println!("Welcome to the Rust project! What do you want to do with x.py?");
391    for ((letter, _), profile) in abbrev_all() {
392        println!("{}) {}: {}", letter, profile, profile.purpose());
393    }
394    let template = loop {
395        print!(
396            "Please choose one ({}): ",
397            abbrev_all().map(|((l, _), _)| l).collect::<Vec<_>>().join("/")
398        );
399        io::stdout().flush()?;
400        let mut input = String::new();
401        io::stdin().read_line(&mut input)?;
402        if input.is_empty() {
403            eprintln!("EOF on stdin, when expecting answer to question.  Giving up.");
404            crate::exit!(1);
405        }
406        break match parse_with_abbrev(&input) {
407            Ok(profile) => profile,
408            Err(err) => {
409                eprintln!("ERROR: {err}");
410                eprintln!("NOTE: press Ctrl+C to exit");
411                continue;
412            }
413        };
414    };
415    Ok(template)
416}
417
418#[derive(PartialEq)]
419enum PromptResult {
420    Yes,   // y/Y/yes
421    No,    // n/N/no
422    Print, // p/P/print
423}
424
425/// Prompt a user for a answer, looping until they enter an accepted input or nothing
426fn prompt_user(prompt: &str) -> io::Result<Option<PromptResult>> {
427    let mut input = String::new();
428    loop {
429        print!("{prompt} ");
430        io::stdout().flush()?;
431        input.clear();
432        io::stdin().read_line(&mut input)?;
433        match input.trim().to_lowercase().as_str() {
434            "y" | "yes" => return Ok(Some(PromptResult::Yes)),
435            "n" | "no" => return Ok(Some(PromptResult::No)),
436            "p" | "print" => return Ok(Some(PromptResult::Print)),
437            "" => return Ok(None),
438            _ => {
439                eprintln!("ERROR: unrecognized option '{}'", input.trim());
440                eprintln!("NOTE: press Ctrl+C to exit");
441            }
442        };
443    }
444}
445
446/// Installs `src/etc/pre-push.sh` as a Git hook
447#[derive(Clone, Debug, Eq, PartialEq, Hash)]
448pub struct Hook;
449
450impl Step for Hook {
451    type Output = ();
452    const DEFAULT: bool = true;
453
454    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
455        run.alias("hook")
456    }
457
458    fn make_run(run: RunConfig<'_>) {
459        if let [cmd] = &run.paths[..] {
460            if cmd.assert_single_path().path.as_path().as_os_str() == "hook" {
461                run.builder.ensure(Hook);
462            }
463        }
464    }
465
466    fn run(self, builder: &Builder<'_>) -> Self::Output {
467        let config = &builder.config;
468
469        if config.dry_run() || !config.rust_info.is_managed_git_subrepository() {
470            return;
471        }
472
473        t!(install_git_hook_maybe(builder, config));
474    }
475}
476
477// install a git hook to automatically run tidy, if they want
478fn install_git_hook_maybe(builder: &Builder<'_>, config: &Config) -> io::Result<()> {
479    let git = helpers::git(Some(&config.src))
480        .args(["rev-parse", "--git-common-dir"])
481        .run_capture(builder)
482        .stdout();
483    let git = PathBuf::from(git.trim());
484    let hooks_dir = git.join("hooks");
485    let dst = hooks_dir.join("pre-push");
486    if dst.exists() {
487        // The git hook has already been set up, or the user already has a custom hook.
488        return Ok(());
489    }
490
491    println!(
492        "\nRust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
493If you'd like, x.py can install a git hook for you that will automatically run `test tidy` before
494pushing your code to ensure your code is up to par. If you decide later that this behavior is
495undesirable, simply delete the `pre-push` file from .git/hooks."
496    );
497
498    if prompt_user("Would you like to install the git hook?: [y/N]")? != Some(PromptResult::Yes) {
499        println!("Ok, skipping installation!");
500        return Ok(());
501    }
502    if !hooks_dir.exists() {
503        // We need to (try to) create the hooks directory first.
504        let _ = fs::create_dir(hooks_dir);
505    }
506    let src = config.src.join("src").join("etc").join("pre-push.sh");
507    match fs::hard_link(src, &dst) {
508        Err(e) => {
509            eprintln!(
510                "ERROR: could not create hook {}: do you already have the git hook installed?\n{}",
511                dst.display(),
512                e
513            );
514            return Err(e);
515        }
516        Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"),
517    };
518    Ok(())
519}
520
521/// Handles editor-specific setup differences
522#[derive(Clone, Debug, Eq, PartialEq)]
523enum EditorKind {
524    Emacs,
525    Helix,
526    Vim,
527    VsCode,
528    Zed,
529}
530
531impl EditorKind {
532    // Used in `./tests.rs`.
533    #[allow(dead_code)]
534    pub const ALL: &[EditorKind] = &[
535        EditorKind::Emacs,
536        EditorKind::Helix,
537        EditorKind::Vim,
538        EditorKind::VsCode,
539        EditorKind::Zed,
540    ];
541
542    fn prompt_user() -> io::Result<Option<EditorKind>> {
543        let prompt_str = "Available editors:
5441. Emacs
5452. Helix
5463. Vim
5474. VS Code
5485. Zed
549
550Select which editor you would like to set up [default: None]: ";
551
552        let mut input = String::new();
553        loop {
554            print!("{}", prompt_str);
555            io::stdout().flush()?;
556            io::stdin().read_line(&mut input)?;
557
558            let mut modified_input = input.to_lowercase();
559            modified_input.retain(|ch| !ch.is_whitespace());
560            match modified_input.as_str() {
561                "1" | "emacs" => return Ok(Some(EditorKind::Emacs)),
562                "2" | "helix" => return Ok(Some(EditorKind::Helix)),
563                "3" | "vim" => return Ok(Some(EditorKind::Vim)),
564                "4" | "vscode" => return Ok(Some(EditorKind::VsCode)),
565                "5" | "zed" => return Ok(Some(EditorKind::Zed)),
566                "" | "none" => return Ok(None),
567                _ => {
568                    eprintln!("ERROR: unrecognized option '{}'", input.trim());
569                    eprintln!("NOTE: press Ctrl+C to exit");
570                }
571            }
572
573            input.clear();
574        }
575    }
576
577    /// A list of historical hashes of each LSP settings file
578    /// New entries should be appended whenever this is updated so we can detect
579    /// outdated vs. user-modified settings files.
580    fn hashes(&self) -> &'static [&'static str] {
581        match self {
582            EditorKind::Emacs => &[
583                "51068d4747a13732440d1a8b8f432603badb1864fa431d83d0fd4f8fa57039e0",
584                "d29af4d949bbe2371eac928a3c31cf9496b1701aa1c45f11cd6c759865ad5c45",
585                "b5dd299b93dca3ceeb9b335f929293cb3d4bf4977866fbe7ceeac2a8a9f99088",
586            ],
587            EditorKind::Helix => &[
588                "2d3069b8cf1b977e5d4023965eb6199597755e6c96c185ed5f2854f98b83d233",
589                "6736d61409fbebba0933afd2e4c44ff2f97c1cb36cf0299a7f4a7819b8775040",
590                "f252dcc30ca85a193a699581e5e929d5bd6c19d40d7a7ade5e257a9517a124a5",
591            ],
592            EditorKind::Vim | EditorKind::VsCode => &[
593                "ea67e259dedf60d4429b6c349a564ffcd1563cf41c920a856d1f5b16b4701ac8",
594                "56e7bf011c71c5d81e0bf42e84938111847a810eee69d906bba494ea90b51922",
595                "af1b5efe196aed007577899db9dae15d6dbc923d6fa42fa0934e68617ba9bbe0",
596                "3468fea433c25fff60be6b71e8a215a732a7b1268b6a83bf10d024344e140541",
597                "47d227f424bf889b0d899b9cc992d5695e1b78c406e183cd78eafefbe5488923",
598                "b526bd58d0262dd4dda2bff5bc5515b705fb668a46235ace3e057f807963a11a",
599                "828666b021d837a33e78d870b56d34c88a5e2c85de58b693607ec574f0c27000",
600                "811fb3b063c739d261fd8590dd30242e117908f5a095d594fa04585daa18ec4d",
601                "4eecb58a2168b252077369da446c30ed0e658301efe69691979d1ef0443928f4",
602                "c394386e6133bbf29ffd32c8af0bb3d4aac354cba9ee051f29612aa9350f8f8d",
603                "e53e9129ca5ee5dcbd6ec8b68c2d87376474eb154992deba3c6d9ab1703e0717",
604            ],
605            EditorKind::Zed => &[
606                "bbce727c269d1bd0c98afef4d612eb4ce27aea3c3a8968c5f10b31affbc40b6c",
607                "a5380cf5dd9328731aecc5dfb240d16dac46ed272126b9728006151ef42f5909",
608            ],
609        }
610    }
611
612    fn settings_path(&self, config: &Config) -> PathBuf {
613        config.src.join(self.settings_short_path())
614    }
615
616    fn settings_short_path(&self) -> PathBuf {
617        self.settings_folder().join(match self {
618            EditorKind::Emacs => ".dir-locals.el",
619            EditorKind::Helix => "languages.toml",
620            EditorKind::Vim => "coc-settings.json",
621            EditorKind::VsCode | EditorKind::Zed => "settings.json",
622        })
623    }
624
625    fn settings_folder(&self) -> PathBuf {
626        match self {
627            EditorKind::Emacs => PathBuf::new(),
628            EditorKind::Helix => PathBuf::from(".helix"),
629            EditorKind::Vim => PathBuf::from(".vim"),
630            EditorKind::VsCode => PathBuf::from(".vscode"),
631            EditorKind::Zed => PathBuf::from(".zed"),
632        }
633    }
634
635    fn settings_template(&self) -> &'static str {
636        match self {
637            EditorKind::Emacs => include_str!("../../../../etc/rust_analyzer_eglot.el"),
638            EditorKind::Helix => include_str!("../../../../etc/rust_analyzer_helix.toml"),
639            EditorKind::Vim | EditorKind::VsCode => {
640                include_str!("../../../../etc/rust_analyzer_settings.json")
641            }
642            EditorKind::Zed => include_str!("../../../../etc/rust_analyzer_zed.json"),
643        }
644    }
645
646    fn backup_extension(&self) -> String {
647        format!("{}.bak", self.settings_short_path().extension().unwrap().to_str().unwrap())
648    }
649}
650
651/// Sets up or displays the LSP config for one of the supported editors
652#[derive(Clone, Debug, Eq, PartialEq, Hash)]
653pub struct Editor;
654
655impl Step for Editor {
656    type Output = ();
657    const DEFAULT: bool = true;
658
659    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
660        run.alias("editor")
661    }
662
663    fn make_run(run: RunConfig<'_>) {
664        if run.builder.config.dry_run() {
665            return;
666        }
667        if let [cmd] = &run.paths[..] {
668            if cmd.assert_single_path().path.as_path().as_os_str() == "editor" {
669                run.builder.ensure(Editor);
670            }
671        }
672    }
673
674    fn run(self, builder: &Builder<'_>) -> Self::Output {
675        let config = &builder.config;
676        if config.dry_run() {
677            return;
678        }
679        match EditorKind::prompt_user() {
680            Ok(editor_kind) => {
681                if let Some(editor_kind) = editor_kind {
682                    while !t!(create_editor_settings_maybe(config, editor_kind.clone())) {}
683                } else {
684                    println!("Ok, skipping editor setup!");
685                }
686            }
687            Err(e) => eprintln!("Could not determine the editor: {e}"),
688        }
689    }
690}
691
692/// Create the recommended editor LSP config file for rustc development, or just print it
693/// If this method should be re-called, it returns `false`.
694fn create_editor_settings_maybe(config: &Config, editor: EditorKind) -> io::Result<bool> {
695    let hashes = editor.hashes();
696    let (current_hash, historical_hashes) = hashes.split_last().unwrap();
697    let settings_path = editor.settings_path(config);
698    let settings_short_path = editor.settings_short_path();
699    let settings_filename = settings_short_path.to_str().unwrap();
700    // If None, no settings file exists
701    // If Some(true), is a previous version of settings.json
702    // If Some(false), is not a previous version (i.e. user modified)
703    // If it's up to date we can just skip this
704    let mut mismatched_settings = None;
705    if let Ok(current) = fs::read_to_string(&settings_path) {
706        let mut hasher = sha2::Sha256::new();
707        hasher.update(&current);
708        let hash = hex_encode(hasher.finalize().as_slice());
709        if hash == *current_hash {
710            return Ok(true);
711        } else if historical_hashes.contains(&hash.as_str()) {
712            mismatched_settings = Some(true);
713        } else {
714            mismatched_settings = Some(false);
715        }
716    }
717    println!(
718        "\nx.py can automatically install the recommended `{settings_filename}` file for rustc development"
719    );
720
721    match mismatched_settings {
722        Some(true) => {
723            eprintln!("WARNING: existing `{settings_filename}` is out of date, x.py will update it")
724        }
725        Some(false) => eprintln!(
726            "WARNING: existing `{settings_filename}` has been modified by user, x.py will back it up and replace it"
727        ),
728        _ => (),
729    }
730    let should_create = match prompt_user(&format!(
731        "Would you like to create/update `{settings_filename}`? (Press 'p' to preview values): [y/N]"
732    ))? {
733        Some(PromptResult::Yes) => true,
734        Some(PromptResult::Print) => false,
735        _ => {
736            println!("Ok, skipping settings!");
737            return Ok(true);
738        }
739    };
740    if should_create {
741        let settings_folder_path = config.src.join(editor.settings_folder());
742        if !settings_folder_path.exists() {
743            fs::create_dir(settings_folder_path)?;
744        }
745        let verb = match mismatched_settings {
746            // exists but outdated, we can replace this
747            Some(true) => "Updated",
748            // exists but user modified, back it up
749            Some(false) => {
750                // exists and is not current version or outdated, so back it up
751                let backup = settings_path.clone().with_extension(editor.backup_extension());
752                eprintln!(
753                    "WARNING: copying `{}` to `{}`",
754                    settings_path.file_name().unwrap().to_str().unwrap(),
755                    backup.file_name().unwrap().to_str().unwrap(),
756                );
757                fs::copy(&settings_path, &backup)?;
758                "Updated"
759            }
760            _ => "Created",
761        };
762        fs::write(&settings_path, editor.settings_template())?;
763        println!("{verb} `{}`", settings_filename);
764    } else {
765        println!("\n{}", editor.settings_template());
766    }
767    Ok(should_create)
768}