Skip to content

Commit 940d4b6

Browse files
authored
feat: add --gen-patch-path to choose where the patch is written (#538)
<!-- claude-projects-attribution: {"github_login":"shenxianpeng"} --> As suggested in #535 (comment): a new `--gen-patch-path <PATH>` option (also read from the `GEN_PATCH_PATH` env var) sets where the combined fix patch is written, so users can run `git apply "$GEN_PATCH_PATH"` without copying the path from the logs. - Setting it implies `--gen-patch`. - A relative path is relative to the current working directory (same as `--database` in #537, and what `git apply` expects). Note that `--summary-output-file` and `--sarif-file` still resolve against `--repo-root`; happy to switch this one to match those if you prefer. - Without it, the patch stays at `<repo-root>/.cpp-linter-cache/auto-fix.patch`, and `fix-patch-path` reports whichever path was used. - A stale patch at the chosen path is removed at the start of a run, like the default one. Implementation: - `FeedbackInput::patch_path` holds the resolved path; `ClangParams::default_patch_path()` builds the default. - `FileObj::maybe_append_patch()` and `make_suggestions_from_patch()` take the patch path instead of building it from `repo_root` (both are `pub`, so this changes their signatures). - Workspace `clap` enables the `env` feature (no new crates in `Cargo.lock`). - Tests: `cli::structs::test::{default_patch_path, gen_patch_path_implies_gen_patch, gen_patch_path_from_env}` and `run::test::custom_patch_path` (stale file replaced, nothing written to the default path). Checked locally with clang 21: all `cpp-linter` lib tests (120), `--test comments` (17) and `--test reviews` (16) pass single-threaded (plain `cargo test` races on env vars, nextest doesn't); `cargo clippy --all-features --all-targets` clean; the generated CLI doc renders the option and its example block. --------- Co-authored-by: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com>
1 parent 80b06f8 commit 940d4b6

6 files changed

Lines changed: 193 additions & 54 deletions

File tree

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ strip = "symbols"
2121

2222
[workspace.dependencies]
2323
anyhow = "1.0.104"
24-
clap = { version = "4.6.7", features = ["derive"] }
24+
clap = { version = "4.6.7", features = ["derive", "env"] }
2525
colored = "3.1.1"
2626
log = { version = "0.4.34", features = ["std"] }
2727
mockito = "1.7.2"

‎cpp-linter/src/cli/mod.rs‎

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@ use std::str::FromStr;
88
#[cfg(feature = "bin")]
99
use clang_tools_manager::{RequestedVersion, logger::CLI_HELP_STYLE};
1010
#[cfg(feature = "bin")]
11-
use clap::{
12-
ArgAction, Args, Parser, Subcommand, ValueEnum, builder::FalseyValueParser, value_parser,
13-
};
11+
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum, builder::FalseyValueParser};
1412

1513
mod structs;
1614
pub use structs::{ClangParams, FeedbackInput, LinesChangedOnly, ThreadComments};
@@ -410,13 +408,15 @@ pub struct TidyOptions {
410408
/// attempted through all parent paths of the first input file. See [LLVM docs about
411409
/// setup tooling](https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html)
412410
/// for an example of setting up Clang Tooling on a source tree.
413-
#[cfg_attr(feature = "bin", arg(
414-
short = 'p',
415-
long,
416-
value_name = "PATH",
417-
value_parser = value_parser!(PathBuf),
418-
help_heading = "Clang-tidy options",
419-
))]
411+
#[cfg_attr(
412+
feature = "bin",
413+
arg(
414+
short = 'p',
415+
long,
416+
value_name = "PATH",
417+
help_heading = "Clang-tidy options",
418+
)
419+
)]
420420
pub database: Option<PathBuf>,
421421

422422
/// A string of extra arguments passed to clang-tidy for use as compiler arguments.
@@ -502,13 +502,15 @@ pub struct FeedbackOptions {
502502
///
503503
/// If the given path is relative, then it shall be relative to the given
504504
/// [`--repo-root`](#-r-repo-root) path.
505-
#[cfg_attr(feature = "bin", arg(
506-
short = 'o',
507-
long,
508-
value_name = "PATH",
509-
value_parser = value_parser!(PathBuf),
510-
help_heading = "Feedback options",
511-
))]
505+
#[cfg_attr(
506+
feature = "bin",
507+
arg(
508+
short = 'o',
509+
long,
510+
value_name = "PATH",
511+
help_heading = "Feedback options",
512+
)
513+
)]
512514
pub summary_output_file: Option<PathBuf>,
513515

514516
/// Provide this option with a path to which clang-tidy diagnostics are
@@ -528,12 +530,10 @@ pub struct FeedbackOptions {
528530
/// > In GitHub Actions, the SARIF file can be uploaded to
529531
/// > [GitHub code scanning](https://docs.github.com/en/code-security/code-scanning/integrating-with-code-scanning/uploading-a-sarif-file-to-github)
530532
/// > with the `github/codeql-action/upload-sarif` action.
531-
#[cfg_attr(feature = "bin", arg(
532-
long,
533-
value_name = "PATH",
534-
value_parser = value_parser!(PathBuf),
535-
help_heading = "Feedback options",
536-
))]
533+
#[cfg_attr(
534+
feature = "bin",
535+
arg(long, value_name = "PATH", help_heading = "Feedback options",)
536+
)]
537537
pub sarif_file: Option<PathBuf>,
538538

539539
/// Set this option to false to disable the use of
@@ -593,6 +593,33 @@ pub struct FeedbackOptions {
593593
help_heading = "Feedback options",
594594
))]
595595
pub gen_patch: bool,
596+
597+
/// Write the patch file of applied clang fixes to this path.
598+
///
599+
/// Setting this implies [`--gen-patch`](#-f-gen-patch).
600+
/// A relative path is relative to the current working directory.
601+
/// If not set, the patch is written to `.cpp-linter-cache/auto-fix.patch`
602+
/// in the [`--repo-root`](#-r-repo-root) folder.
603+
///
604+
/// This can also be set with the `GEN_PATCH_PATH` environment variable,
605+
/// so the same variable can be used to apply the patch afterward:
606+
///
607+
/// ```shell
608+
/// export GEN_PATCH_PATH=fixes.patch
609+
/// cpp-linter
610+
/// git apply "$GEN_PATCH_PATH"
611+
/// ```
612+
#[cfg_attr(
613+
feature = "bin",
614+
arg(
615+
long,
616+
value_name = "PATH",
617+
env = "GEN_PATCH_PATH",
618+
help_heading = "Feedback options",
619+
verbatim_doc_comment,
620+
)
621+
)]
622+
pub gen_patch_path: Option<PathBuf>,
596623
}
597624

598625
/// Parses a single value of the `--extensions` option.

‎cpp-linter/src/cli/structs.rs‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use std::{fmt::Display, path::PathBuf};
1+
use std::{
2+
fmt::Display,
3+
path::{Path, PathBuf},
4+
};
25

36
#[cfg(feature = "bin")]
47
use clap::{ValueEnum, builder::PossibleValue};
@@ -237,6 +240,11 @@ impl ClangParams {
237240
/// The file name for aggregating auto-fixes into a unified patch.
238241
pub(crate) const AUTO_FIX_PATCH: &str = "auto-fix.patch";
239242

243+
/// The default path of the generated patch file, in the cache directory of `repo_root`.
244+
pub(crate) fn default_patch_path(repo_root: &Path) -> PathBuf {
245+
repo_root.join(Self::CACHE_DIR).join(Self::AUTO_FIX_PATCH)
246+
}
247+
240248
pub(crate) fn get_cache_path(&self) -> PathBuf {
241249
self.repo_root.join(Self::CACHE_DIR).join("patched")
242250
}
@@ -289,7 +297,9 @@ impl From<&Cli> for ClangParams {
289297
tidy_filter,
290298
format_filter,
291299
repo_root,
292-
gen_patch: args.feedback_options.pr_review || args.feedback_options.gen_patch,
300+
gen_patch: args.feedback_options.pr_review
301+
|| args.feedback_options.gen_patch
302+
|| args.feedback_options.gen_patch_path.is_some(),
293303
}
294304
}
295305
}
@@ -333,6 +343,9 @@ pub struct FeedbackInput {
333343
///
334344
/// Only used when `pr_review` is false.
335345
pub gen_patch: bool,
346+
347+
/// The path of the generated patch file.
348+
pub patch_path: PathBuf,
336349
}
337350

338351
#[cfg(feature = "bin")]
@@ -350,7 +363,12 @@ impl From<&Cli> for FeedbackInput {
350363
repo_root: args.source_options.repo_root.clone(),
351364
summary_output_file: args.feedback_options.summary_output_file.clone(),
352365
sarif_file: args.feedback_options.sarif_file.clone(),
353-
gen_patch: args.feedback_options.gen_patch,
366+
gen_patch: args.feedback_options.gen_patch
367+
|| args.feedback_options.gen_patch_path.is_some(),
368+
patch_path: match &args.feedback_options.gen_patch_path {
369+
Some(path) => std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()),
370+
None => ClangParams::default_patch_path(&args.source_options.repo_root),
371+
},
354372
}
355373
}
356374
}
@@ -370,6 +388,7 @@ impl Default for FeedbackInput {
370388
summary_output_file: None,
371389
sarif_file: None,
372390
gen_patch: false,
391+
patch_path: ClangParams::default_patch_path(Path::new(".")),
373392
}
374393
}
375394
}
@@ -380,7 +399,9 @@ mod test {
380399

381400
use clap::{Parser, ValueEnum};
382401

383-
use super::{ClangParams, Cli, LinesChangedOnly, ThreadComments};
402+
use std::path::PathBuf;
403+
404+
use super::{ClangParams, Cli, FeedbackInput, LinesChangedOnly, ThreadComments};
384405

385406
#[test]
386407
fn parse_positional() {
@@ -443,6 +464,45 @@ mod test {
443464
}
444465
}
445466

467+
#[test]
468+
fn default_patch_path() {
469+
let cli = Cli::parse_from(["cpp-linter", "--repo-root", "sub"]);
470+
let feedback_input = FeedbackInput::from(&cli);
471+
assert!(!feedback_input.gen_patch);
472+
assert_eq!(
473+
feedback_input.patch_path,
474+
PathBuf::from("sub/.cpp-linter-cache/auto-fix.patch")
475+
);
476+
}
477+
478+
#[test]
479+
fn gen_patch_path_implies_gen_patch() {
480+
let cli = Cli::parse_from(["cpp-linter", "--gen-patch-path", "fixes.patch"]);
481+
let feedback_input = FeedbackInput::from(&cli);
482+
assert!(feedback_input.gen_patch);
483+
// a relative path is relative to the working directory
484+
assert_eq!(
485+
feedback_input.patch_path,
486+
std::env::current_dir().unwrap().join("fixes.patch")
487+
);
488+
assert!(ClangParams::from(&cli).gen_patch);
489+
}
490+
491+
#[test]
492+
fn gen_patch_path_from_env() {
493+
unsafe {
494+
std::env::set_var("GEN_PATCH_PATH", "from-env.patch");
495+
}
496+
let cli = Cli::parse_from(["cpp-linter"]);
497+
unsafe {
498+
std::env::remove_var("GEN_PATCH_PATH");
499+
}
500+
assert_eq!(
501+
cli.feedback_options.gen_patch_path,
502+
Some(PathBuf::from("from-env.patch"))
503+
);
504+
}
505+
446506
#[test]
447507
fn absolute_db_path() {
448508
let tmp_dir = tempfile::tempdir().unwrap();

‎cpp-linter/src/common_fs.rs‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::{
1717
clang_tools::{
1818
ReviewComments, Suggestion, clang_format::FormatAdvice, clang_tidy::TidyAdvice, make_patch,
1919
},
20-
cli::{ClangParams, LinesChangedOnly},
20+
cli::LinesChangedOnly,
2121
error::FileObjError,
2222
};
2323

@@ -169,7 +169,11 @@ impl FileObj {
169169
/// a PR review is not being posted. Both function have to create a patch by
170170
/// reading the original file and patched file (in cache), but
171171
/// [`FileObj::make_suggestions_from_patch()`] does more with the diff than this function.
172-
pub fn maybe_append_patch(&self, repo_root: &Path) -> Result<(), FileObjError> {
172+
pub fn maybe_append_patch(
173+
&self,
174+
repo_root: &Path,
175+
patch_path: &Path,
176+
) -> Result<(), FileObjError> {
173177
let patched = match &self.patched_path {
174178
Some(patched_path) if patched_path.exists() => {
175179
fs::read_to_string(patched_path).map_err(FileObjError::ReadFile)?
@@ -180,29 +184,28 @@ impl FileObj {
180184
fs::read_to_string(repo_root.join(&self.name)).map_err(FileObjError::ReadFile)?;
181185
let (diff, input) = make_patch(patched.as_str(), &original_content);
182186
let file_name = self.name.to_string_lossy().replace("\\", "/");
183-
Self::append_patch(&file_name, &input, &diff, repo_root)?;
187+
Self::append_patch(&file_name, &input, &diff, patch_path)?;
184188
Ok(())
185189
}
186190

187-
/// write fixes to a unified patch file in the cache directory.
191+
/// write fixes to the unified patch file at `patch_path`.
188192
fn append_patch(
189193
file_name: &str,
190194
input: &InternedInput<&str>,
191195
diff: &Diff,
192-
repo_root: &Path,
196+
patch_path: &Path,
193197
) -> Result<(), FileObjError> {
194198
let printer = BasicLineDiffPrinter(&input.interner);
195199
let diff_config = UnifiedDiffConfig::default();
196200
let unified_diff = diff.unified_diff(&printer, diff_config, input).to_string();
197201
if !unified_diff.is_empty() {
198-
let patch_path_parent = repo_root.join(ClangParams::CACHE_DIR);
199-
fs::create_dir_all(&patch_path_parent).map_err(FileObjError::MkDirFailed)?;
200-
let patch_file_path = patch_path_parent.join(ClangParams::AUTO_FIX_PATCH);
202+
let patch_path_parent = patch_path.parent().unwrap_or(Path::new(""));
203+
fs::create_dir_all(patch_path_parent).map_err(FileObjError::MkDirFailed)?;
201204
let mut patch_file = fs::OpenOptions::new()
202205
.append(true)
203206
.create(true)
204207
.truncate(false)
205-
.open(&patch_file_path)
208+
.open(patch_path)
206209
.map_err(FileObjError::OpenPatchFileFailed)?;
207210
patch_file
208211
.write_all(
@@ -224,6 +227,7 @@ impl FileObj {
224227
review_comments: &mut ReviewComments,
225228
summary_only: bool,
226229
repo_root: &Path,
230+
patch_path: &Path,
227231
) -> Result<(), FileObjError> {
228232
let patched = match &self.patched_path {
229233
Some(patched_path) if patched_path.exists() => {
@@ -235,7 +239,7 @@ impl FileObj {
235239
fs::read_to_string(repo_root.join(&self.name)).map_err(FileObjError::ReadFile)?;
236240
let (diff, input) = make_patch(patched.as_str(), &original_content);
237241
let file_name = self.name.to_string_lossy().replace("\\", "/");
238-
Self::append_patch(&file_name, &input, &diff, repo_root)?;
242+
Self::append_patch(&file_name, &input, &diff, patch_path)?;
239243

240244
self.get_suggestions(review_comments, &diff, &input, summary_only)
241245
.map_err(FileObjError::DisplayStringFailed)?;
@@ -425,7 +429,10 @@ mod test {
425429
use tempfile::{NamedTempFile, TempDir};
426430

427431
use super::FileObj;
428-
use crate::{clang_tools::ReviewComments, cli::LinesChangedOnly};
432+
use crate::{
433+
clang_tools::ReviewComments,
434+
cli::{ClangParams, LinesChangedOnly},
435+
};
429436

430437
// *********************** tests for FileObj::get_ranges()
431438

@@ -508,7 +515,12 @@ mod test {
508515

509516
let mut review_comments = ReviewComments::default();
510517
file_obj
511-
.make_suggestions_from_patch(&mut review_comments, false, repo_root.path())
518+
.make_suggestions_from_patch(
519+
&mut review_comments,
520+
false,
521+
repo_root.path(),
522+
&ClangParams::default_patch_path(repo_root.path()),
523+
)
512524
.unwrap();
513525

514526
assert_eq!(review_comments.comments.len(), 1);
@@ -568,7 +580,12 @@ mod test {
568580

569581
let mut review_comments = ReviewComments::default();
570582
file_obj
571-
.make_suggestions_from_patch(&mut review_comments, false, repo_root.path())
583+
.make_suggestions_from_patch(
584+
&mut review_comments,
585+
false,
586+
repo_root.path(),
587+
&ClangParams::default_patch_path(repo_root.path()),
588+
)
572589
.unwrap();
573590
assert_eq!(review_comments.comments.len(), 2);
574591
// 1 fix and 2 unfixed diagnostics, all within the diff (in 2 comments)
@@ -599,7 +616,12 @@ mod test {
599616

600617
// Processing the same file again merges duplicate suggestions
601618
file_obj
602-
.make_suggestions_from_patch(&mut review_comments, false, repo_root.path())
619+
.make_suggestions_from_patch(
620+
&mut review_comments,
621+
false,
622+
repo_root.path(),
623+
&ClangParams::default_patch_path(repo_root.path()),
624+
)
603625
.unwrap();
604626
assert_eq!(review_comments.comments.len(), 2);
605627
assert_eq!(
@@ -613,7 +635,12 @@ mod test {
613635
// Only counts the unfixed diagnostics in summary-only mode
614636
let mut summary_comments = ReviewComments::default();
615637
file_obj
616-
.make_suggestions_from_patch(&mut summary_comments, true, repo_root.path())
638+
.make_suggestions_from_patch(
639+
&mut summary_comments,
640+
true,
641+
repo_root.path(),
642+
&ClangParams::default_patch_path(repo_root.path()),
643+
)
617644
.unwrap();
618645
assert!(summary_comments.comments.is_empty());
619646
assert_eq!(summary_comments.tool_total, 3);

0 commit comments

Comments
 (0)