Skip to main content

cargo/ops/
fix.rs

1use std::collections::{BTreeSet, HashMap, HashSet};
2use std::env;
3use std::ffi::OsString;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::{self, Command, ExitStatus};
7use std::str;
8
9use failure::{Error, ResultExt};
10use log::{debug, trace, warn};
11use rustfix::diagnostics::Diagnostic;
12use rustfix::{self, CodeFix};
13
14use crate::core::Workspace;
15use crate::ops::{self, CompileOptions};
16use crate::util::diagnostic_server::{Message, RustfixDiagnosticServer};
17use crate::util::errors::CargoResult;
18use crate::util::paths;
19use crate::util::{existing_vcs_repo, LockServer, LockServerClient};
20
21const FIX_ENV: &str = "__CARGO_FIX_PLZ";
22const BROKEN_CODE_ENV: &str = "__CARGO_FIX_BROKEN_CODE";
23const PREPARE_FOR_ENV: &str = "__CARGO_FIX_PREPARE_FOR";
24const EDITION_ENV: &str = "__CARGO_FIX_EDITION";
25const IDIOMS_ENV: &str = "__CARGO_FIX_IDIOMS";
26
27pub struct FixOptions<'a> {
28    pub edition: bool,
29    pub prepare_for: Option<&'a str>,
30    pub idioms: bool,
31    pub compile_opts: CompileOptions<'a>,
32    pub allow_dirty: bool,
33    pub allow_no_vcs: bool,
34    pub allow_staged: bool,
35    pub broken_code: bool,
36}
37
38pub fn fix(ws: &Workspace<'_>, opts: &mut FixOptions<'_>) -> CargoResult<()> {
39    check_version_control(opts)?;
40
41    // Spin up our lock server which our subprocesses will use to synchronize
42    // fixes.
43    let lock_server = LockServer::new()?;
44    opts.compile_opts
45        .build_config
46        .extra_rustc_env
47        .push((FIX_ENV.to_string(), lock_server.addr().to_string()));
48    let _started = lock_server.start()?;
49
50    opts.compile_opts.build_config.force_rebuild = true;
51
52    if opts.broken_code {
53        let key = BROKEN_CODE_ENV.to_string();
54        opts.compile_opts
55            .build_config
56            .extra_rustc_env
57            .push((key, "1".to_string()));
58    }
59
60    if opts.edition {
61        let key = EDITION_ENV.to_string();
62        opts.compile_opts
63            .build_config
64            .extra_rustc_env
65            .push((key, "1".to_string()));
66    } else if let Some(edition) = opts.prepare_for {
67        opts.compile_opts
68            .build_config
69            .extra_rustc_env
70            .push((PREPARE_FOR_ENV.to_string(), edition.to_string()));
71    }
72    if opts.idioms {
73        opts.compile_opts
74            .build_config
75            .extra_rustc_env
76            .push((IDIOMS_ENV.to_string(), "1".to_string()));
77    }
78    opts.compile_opts.build_config.cargo_as_rustc_wrapper = true;
79    *opts
80        .compile_opts
81        .build_config
82        .rustfix_diagnostic_server
83        .borrow_mut() = Some(RustfixDiagnosticServer::new()?);
84
85    ops::compile(ws, &opts.compile_opts)?;
86    Ok(())
87}
88
89fn check_version_control(opts: &FixOptions<'_>) -> CargoResult<()> {
90    if opts.allow_no_vcs {
91        return Ok(());
92    }
93    let config = opts.compile_opts.config;
94    if !existing_vcs_repo(config.cwd(), config.cwd()) {
95        failure::bail!(
96            "no VCS found for this package and `cargo fix` can potentially \
97             perform destructive changes; if you'd like to suppress this \
98             error pass `--allow-no-vcs`"
99        )
100    }
101
102    if opts.allow_dirty && opts.allow_staged {
103        return Ok(());
104    }
105
106    let mut dirty_files = Vec::new();
107    let mut staged_files = Vec::new();
108    if let Ok(repo) = git2::Repository::discover(config.cwd()) {
109        let mut repo_opts = git2::StatusOptions::new();
110        repo_opts.include_ignored(false);
111        for status in repo.statuses(Some(&mut repo_opts))?.iter() {
112            if let Some(path) = status.path() {
113                match status.status() {
114                    git2::Status::CURRENT => (),
115                    git2::Status::INDEX_NEW
116                    | git2::Status::INDEX_MODIFIED
117                    | git2::Status::INDEX_DELETED
118                    | git2::Status::INDEX_RENAMED
119                    | git2::Status::INDEX_TYPECHANGE => {
120                        if !opts.allow_staged {
121                            staged_files.push(path.to_string())
122                        }
123                    }
124                    _ => {
125                        if !opts.allow_dirty {
126                            dirty_files.push(path.to_string())
127                        }
128                    }
129                };
130            }
131        }
132    }
133
134    if dirty_files.is_empty() && staged_files.is_empty() {
135        return Ok(());
136    }
137
138    let mut files_list = String::new();
139    for file in dirty_files {
140        files_list.push_str("  * ");
141        files_list.push_str(&file);
142        files_list.push_str(" (dirty)\n");
143    }
144    for file in staged_files {
145        files_list.push_str("  * ");
146        files_list.push_str(&file);
147        files_list.push_str(" (staged)\n");
148    }
149
150    failure::bail!(
151        "the working directory of this package has uncommitted changes, and \
152         `cargo fix` can potentially perform destructive changes; if you'd \
153         like to suppress this error pass `--allow-dirty`, `--allow-staged`, \
154         or commit the changes to these files:\n\
155         \n\
156         {}\n\
157         ",
158        files_list
159    );
160}
161
162pub fn fix_maybe_exec_rustc() -> CargoResult<bool> {
163    let lock_addr = match env::var(FIX_ENV) {
164        Ok(s) => s,
165        Err(_) => return Ok(false),
166    };
167
168    let args = FixArgs::get();
169    trace!("cargo-fix as rustc got file {:?}", args.file);
170    let rustc = env::var_os("RUSTC").expect("failed to find RUSTC env var");
171
172    // Our goal is to fix only the crates that the end user is interested in.
173    // That's very likely to only mean the crates in the workspace the user is
174    // working on, not random crates.io crates.
175    //
176    // To that end we only actually try to fix things if it looks like we're
177    // compiling a Rust file and it *doesn't* have an absolute filename. That's
178    // not the best heuristic but matches what Cargo does today at least.
179    let mut fixes = FixedCrate::default();
180    if let Some(path) = &args.file {
181        if args.primary_package {
182            trace!("start rustfixing {:?}", path);
183            fixes = rustfix_crate(&lock_addr, rustc.as_ref(), path, &args)?;
184        }
185    }
186
187    // Ok now we have our final goal of testing out the changes that we applied.
188    // If these changes went awry and actually started to cause the crate to
189    // *stop* compiling then we want to back them out and continue to print
190    // warnings to the user.
191    //
192    // If we didn't actually make any changes then we can immediately exec the
193    // new rustc, and otherwise we capture the output to hide it in the scenario
194    // that we have to back it all out.
195    if !fixes.files.is_empty() {
196        let mut cmd = Command::new(&rustc);
197        args.apply(&mut cmd);
198        cmd.arg("--error-format=json");
199        let output = cmd.output().context("failed to spawn rustc")?;
200
201        if output.status.success() {
202            for (path, file) in fixes.files.iter() {
203                Message::Fixing {
204                    file: path.clone(),
205                    fixes: file.fixes_applied,
206                }
207                .post()?;
208            }
209        }
210
211        // If we succeeded then we'll want to commit to the changes we made, if
212        // any. If stderr is empty then there's no need for the final exec at
213        // the end, we just bail out here.
214        if output.status.success() && output.stderr.is_empty() {
215            return Ok(true);
216        }
217
218        // Otherwise if our rustc just failed then that means that we broke the
219        // user's code with our changes. Back out everything and fall through
220        // below to recompile again.
221        if !output.status.success() {
222            if env::var_os(BROKEN_CODE_ENV).is_none() {
223                for (path, file) in fixes.files.iter() {
224                    fs::write(path, &file.original_code)
225                        .with_context(|_| format!("failed to write file `{}`", path))?;
226                }
227            }
228            log_failed_fix(&output.stderr)?;
229        }
230    }
231
232    let mut cmd = Command::new(&rustc);
233    args.apply(&mut cmd);
234    exit_with(cmd.status().context("failed to spawn rustc")?);
235}
236
237#[derive(Default)]
238struct FixedCrate {
239    files: HashMap<String, FixedFile>,
240}
241
242struct FixedFile {
243    errors_applying_fixes: Vec<String>,
244    fixes_applied: u32,
245    original_code: String,
246}
247
248fn rustfix_crate(
249    lock_addr: &str,
250    rustc: &Path,
251    filename: &Path,
252    args: &FixArgs,
253) -> Result<FixedCrate, Error> {
254    args.verify_not_preparing_for_enabled_edition()?;
255
256    // First up we want to make sure that each crate is only checked by one
257    // process at a time. If two invocations concurrently check a crate then
258    // it's likely to corrupt it.
259    //
260    // Currently we do this by assigning the name on our lock to the manifest
261    // directory.
262    let dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is missing?");
263    let _lock = LockServerClient::lock(&lock_addr.parse()?, dir)?;
264
265    // Next up this is a bit suspicious, but we *iteratively* execute rustc and
266    // collect suggestions to feed to rustfix. Once we hit our limit of times to
267    // execute rustc or we appear to be reaching a fixed point we stop running
268    // rustc.
269    //
270    // This is currently done to handle code like:
271    //
272    //      ::foo::<::Bar>();
273    //
274    // where there are two fixes to happen here: `crate::foo::<crate::Bar>()`.
275    // The spans for these two suggestions are overlapping and its difficult in
276    // the compiler to *not* have overlapping spans here. As a result, a naive
277    // implementation would feed the two compiler suggestions for the above fix
278    // into `rustfix`, but one would be rejected because it overlaps with the
279    // other.
280    //
281    // In this case though, both suggestions are valid and can be automatically
282    // applied! To handle this case we execute rustc multiple times, collecting
283    // fixes each time we do so. Along the way we discard any suggestions that
284    // failed to apply, assuming that they can be fixed the next time we run
285    // rustc.
286    //
287    // Naturally we want a few protections in place here though to avoid looping
288    // forever or otherwise losing data. To that end we have a few termination
289    // conditions:
290    //
291    // * Do this whole process a fixed number of times. In theory we probably
292    //   need an infinite number of times to apply fixes, but we're not gonna
293    //   sit around waiting for that.
294    // * If it looks like a fix genuinely can't be applied we need to bail out.
295    //   Detect this when a fix fails to get applied *and* no suggestions
296    //   successfully applied to the same file. In that case looks like we
297    //   definitely can't make progress, so bail out.
298    let mut fixes = FixedCrate::default();
299    let mut last_fix_counts = HashMap::new();
300    let iterations = env::var("CARGO_FIX_MAX_RETRIES")
301        .ok()
302        .and_then(|n| n.parse().ok())
303        .unwrap_or(4);
304    for _ in 0..iterations {
305        last_fix_counts.clear();
306        for (path, file) in fixes.files.iter_mut() {
307            last_fix_counts.insert(path.clone(), file.fixes_applied);
308            file.errors_applying_fixes.clear(); // we'll generate new errors below
309        }
310        rustfix_and_fix(&mut fixes, rustc, filename, args)?;
311        let mut progress_yet_to_be_made = false;
312        for (path, file) in fixes.files.iter_mut() {
313            if file.errors_applying_fixes.is_empty() {
314                continue;
315            }
316            // If anything was successfully fixed *and* there's at least one
317            // error, then assume the error was spurious and we'll try again on
318            // the next iteration.
319            if file.fixes_applied != *last_fix_counts.get(path).unwrap_or(&0) {
320                progress_yet_to_be_made = true;
321            }
322        }
323        if !progress_yet_to_be_made {
324            break;
325        }
326    }
327
328    // Any errors still remaining at this point need to be reported as probably
329    // bugs in Cargo and/or rustfix.
330    for (path, file) in fixes.files.iter_mut() {
331        for error in file.errors_applying_fixes.drain(..) {
332            Message::ReplaceFailed {
333                file: path.clone(),
334                message: error,
335            }
336            .post()?;
337        }
338    }
339
340    Ok(fixes)
341}
342
343/// Execute `rustc` to apply one round of suggestions to the crate in question.
344///
345/// This will fill in the `fixes` map with original code, suggestions applied,
346/// and any errors encountered while fixing files.
347fn rustfix_and_fix(
348    fixes: &mut FixedCrate,
349    rustc: &Path,
350    filename: &Path,
351    args: &FixArgs,
352) -> Result<(), Error> {
353    // If not empty, filter by these lints
354    //
355    // TODO: Implement a way to specify this
356    let only = HashSet::new();
357
358    let mut cmd = Command::new(rustc);
359    cmd.arg("--error-format=json");
360    args.apply(&mut cmd);
361    let output = cmd
362        .output()
363        .with_context(|_| format!("failed to execute `{}`", rustc.display()))?;
364
365    // If rustc didn't succeed for whatever reasons then we're very likely to be
366    // looking at otherwise broken code. Let's not make things accidentally
367    // worse by applying fixes where a bug could cause *more* broken code.
368    // Instead, punt upwards which will reexec rustc over the original code,
369    // displaying pretty versions of the diagnostics we just read out.
370    if !output.status.success() && env::var_os(BROKEN_CODE_ENV).is_none() {
371        debug!(
372            "rustfixing `{:?}` failed, rustc exited with {:?}",
373            filename,
374            output.status.code()
375        );
376        return Ok(());
377    }
378
379    let fix_mode = env::var_os("__CARGO_FIX_YOLO")
380        .map(|_| rustfix::Filter::Everything)
381        .unwrap_or(rustfix::Filter::MachineApplicableOnly);
382
383    // Sift through the output of the compiler to look for JSON messages
384    // indicating fixes that we can apply.
385    let stderr = str::from_utf8(&output.stderr).context("failed to parse rustc stderr as utf-8")?;
386
387    let suggestions = stderr
388        .lines()
389        .filter(|x| !x.is_empty())
390        .inspect(|y| trace!("line: {}", y))
391        // Parse each line of stderr ignoring errors as they may not all be json
392        .filter_map(|line| serde_json::from_str::<Diagnostic>(line).ok())
393        // From each diagnostic try to extract suggestions from rustc
394        .filter_map(|diag| rustfix::collect_suggestions(&diag, &only, fix_mode));
395
396    // Collect suggestions by file so we can apply them one at a time later.
397    let mut file_map = HashMap::new();
398    let mut num_suggestion = 0;
399    for suggestion in suggestions {
400        trace!("suggestion");
401        // Make sure we've got a file associated with this suggestion and all
402        // snippets point to the same file. Right now it's not clear what
403        // we would do with multiple files.
404        let file_names = suggestion
405            .solutions
406            .iter()
407            .flat_map(|s| s.replacements.iter())
408            .map(|r| &r.snippet.file_name);
409
410        let file_name = if let Some(file_name) = file_names.clone().next() {
411            file_name.clone()
412        } else {
413            trace!("rejecting as it has no solutions {:?}", suggestion);
414            continue;
415        };
416
417        if !file_names.clone().all(|f| f == &file_name) {
418            trace!("rejecting as it changes multiple files: {:?}", suggestion);
419            continue;
420        }
421
422        file_map
423            .entry(file_name)
424            .or_insert_with(Vec::new)
425            .push(suggestion);
426        num_suggestion += 1;
427    }
428
429    debug!(
430        "collected {} suggestions for `{}`",
431        num_suggestion,
432        filename.display(),
433    );
434
435    for (file, suggestions) in file_map {
436        // Attempt to read the source code for this file. If this fails then
437        // that'd be pretty surprising, so log a message and otherwise keep
438        // going.
439        let code = match paths::read(file.as_ref()) {
440            Ok(s) => s,
441            Err(e) => {
442                warn!("failed to read `{}`: {}", file, e);
443                continue;
444            }
445        };
446        let num_suggestions = suggestions.len();
447        debug!("applying {} fixes to {}", num_suggestions, file);
448
449        // If this file doesn't already exist then we just read the original
450        // code, so save it. If the file already exists then the original code
451        // doesn't need to be updated as we've just read an interim state with
452        // some fixes but perhaps not all.
453        let fixed_file = fixes
454            .files
455            .entry(file.clone())
456            .or_insert_with(|| FixedFile {
457                errors_applying_fixes: Vec::new(),
458                fixes_applied: 0,
459                original_code: code.clone(),
460            });
461        let mut fixed = CodeFix::new(&code);
462
463        // As mentioned above in `rustfix_crate`, we don't immediately warn
464        // about suggestions that fail to apply here, and instead we save them
465        // off for later processing.
466        for suggestion in suggestions.iter().rev() {
467            match fixed.apply(suggestion) {
468                Ok(()) => fixed_file.fixes_applied += 1,
469                Err(e) => fixed_file.errors_applying_fixes.push(e.to_string()),
470            }
471        }
472        let new_code = fixed.finish()?;
473        fs::write(&file, new_code).with_context(|_| format!("failed to write file `{}`", file))?;
474    }
475
476    Ok(())
477}
478
479fn exit_with(status: ExitStatus) -> ! {
480    #[cfg(unix)]
481    {
482        use std::os::unix::prelude::*;
483        if let Some(signal) = status.signal() {
484            eprintln!("child failed with signal `{}`", signal);
485            process::exit(2);
486        }
487    }
488    process::exit(status.code().unwrap_or(3));
489}
490
491fn log_failed_fix(stderr: &[u8]) -> Result<(), Error> {
492    let stderr = str::from_utf8(stderr).context("failed to parse rustc stderr as utf-8")?;
493
494    let diagnostics = stderr
495        .lines()
496        .filter(|x| !x.is_empty())
497        .filter_map(|line| serde_json::from_str::<Diagnostic>(line).ok());
498    let mut files = BTreeSet::new();
499    let mut errors = Vec::new();
500    for diagnostic in diagnostics {
501        errors.push(diagnostic.rendered.unwrap_or(diagnostic.message));
502        for span in diagnostic.spans.into_iter() {
503            files.insert(span.file_name);
504        }
505    }
506    let mut krate = None;
507    let mut prev_dash_dash_krate_name = false;
508    for arg in env::args() {
509        if prev_dash_dash_krate_name {
510            krate = Some(arg.clone());
511        }
512
513        if arg == "--crate-name" {
514            prev_dash_dash_krate_name = true;
515        } else {
516            prev_dash_dash_krate_name = false;
517        }
518    }
519
520    let files = files.into_iter().collect();
521    Message::FixFailed {
522        files,
523        krate,
524        errors,
525    }
526    .post()?;
527
528    Ok(())
529}
530
531#[derive(Default)]
532struct FixArgs {
533    file: Option<PathBuf>,
534    prepare_for_edition: PrepareFor,
535    idioms: bool,
536    enabled_edition: Option<String>,
537    other: Vec<OsString>,
538    primary_package: bool,
539}
540
541enum PrepareFor {
542    Next,
543    Edition(String),
544    None,
545}
546
547impl Default for PrepareFor {
548    fn default() -> PrepareFor {
549        PrepareFor::None
550    }
551}
552
553impl FixArgs {
554    fn get() -> FixArgs {
555        let mut ret = FixArgs::default();
556        for arg in env::args_os().skip(1) {
557            let path = PathBuf::from(arg);
558            if path.extension().and_then(|s| s.to_str()) == Some("rs") && path.exists() {
559                ret.file = Some(path);
560                continue;
561            }
562            if let Some(s) = path.to_str() {
563                let prefix = "--edition=";
564                if s.starts_with(prefix) {
565                    ret.enabled_edition = Some(s[prefix.len()..].to_string());
566                    continue;
567                }
568            }
569            ret.other.push(path.into());
570        }
571        if let Ok(s) = env::var(PREPARE_FOR_ENV) {
572            ret.prepare_for_edition = PrepareFor::Edition(s);
573        } else if env::var(EDITION_ENV).is_ok() {
574            ret.prepare_for_edition = PrepareFor::Next;
575        }
576        ret.idioms = env::var(IDIOMS_ENV).is_ok();
577        ret.primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
578        ret
579    }
580
581    fn apply(&self, cmd: &mut Command) {
582        if let Some(path) = &self.file {
583            cmd.arg(path);
584        }
585        cmd.args(&self.other).arg("--cap-lints=warn");
586        if let Some(edition) = &self.enabled_edition {
587            cmd.arg("--edition").arg(edition);
588            if self.idioms && self.primary_package && edition == "2018" {
589                cmd.arg("-Wrust-2018-idioms");
590            }
591        }
592        if self.primary_package {
593            if let Some(edition) = self.prepare_for_edition_resolve() {
594                cmd.arg("-W").arg(format!("rust-{}-compatibility", edition));
595            }
596        }
597    }
598
599    /// Verify that we're not both preparing for an enabled edition and enabling
600    /// the edition.
601    ///
602    /// This indicates that `cargo fix --prepare-for` is being executed out of
603    /// order with enabling the edition itself, meaning that we wouldn't
604    /// actually be able to fix anything! If it looks like this is happening
605    /// then yield an error to the user, indicating that this is happening.
606    fn verify_not_preparing_for_enabled_edition(&self) -> CargoResult<()> {
607        let edition = match self.prepare_for_edition_resolve() {
608            Some(s) => s,
609            None => return Ok(()),
610        };
611        let enabled = match &self.enabled_edition {
612            Some(s) => s,
613            None => return Ok(()),
614        };
615        if edition != enabled {
616            return Ok(());
617        }
618        let path = match &self.file {
619            Some(s) => s,
620            None => return Ok(()),
621        };
622
623        Message::EditionAlreadyEnabled {
624            file: path.display().to_string(),
625            edition: edition.to_string(),
626        }
627        .post()?;
628
629        process::exit(1);
630    }
631
632    fn prepare_for_edition_resolve(&self) -> Option<&str> {
633        match &self.prepare_for_edition {
634            PrepareFor::Edition(s) => Some(s),
635            PrepareFor::Next => Some(self.next_edition()),
636            PrepareFor::None => None,
637        }
638    }
639
640    fn next_edition(&self) -> &str {
641        match self.enabled_edition.as_ref().map(|s| &**s) {
642            // 2015 -> 2018,
643            None | Some("2015") => "2018",
644
645            // This'll probably be wrong in 2020, but that's future Cargo's
646            // problem. Eventually though we'll just add more editions here as
647            // necessary.
648            _ => "2018",
649        }
650    }
651}