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 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 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 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 output.status.success() && output.stderr.is_empty() {
215 return Ok(true);
216 }
217
218 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 let dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is missing?");
263 let _lock = LockServerClient::lock(&lock_addr.parse()?, dir)?;
264
265 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(); }
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 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 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
343fn rustfix_and_fix(
348 fixes: &mut FixedCrate,
349 rustc: &Path,
350 filename: &Path,
351 args: &FixArgs,
352) -> Result<(), Error> {
353 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 !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 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 .filter_map(|line| serde_json::from_str::<Diagnostic>(line).ok())
393 .filter_map(|diag| rustfix::collect_suggestions(&diag, &only, fix_mode));
395
396 let mut file_map = HashMap::new();
398 let mut num_suggestion = 0;
399 for suggestion in suggestions {
400 trace!("suggestion");
401 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 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 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 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 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 None | Some("2015") => "2018",
644
645 _ => "2018",
649 }
650 }
651}