Skip to content

Commit fc628c5

Browse files
committed
adjust integration tests to rely on --repo-root using an absolute path
1 parent 9fcf74d commit fc628c5

10 files changed

Lines changed: 67 additions & 51 deletions

File tree

cpp-linter/src/clang_tools/clang_tidy.rs

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
//! output.
33
44
use std::{
5-
env::{consts::OS, current_dir},
5+
env::consts::OS,
66
fs,
7-
path::PathBuf,
7+
path::{Path, PathBuf},
88
process::Command,
99
sync::{Arc, Mutex, MutexGuard},
1010
};
@@ -144,13 +144,13 @@ const NOTE_HEADER: &str = r"^(.+):(\d+):(\d+):\s(\w+):(.*)\[([a-zA-Z\d\-\.]+),?[
144144
fn parse_tidy_output(
145145
tidy_stdout: &[u8],
146146
database_json: &Option<Vec<CompilationUnit>>,
147+
repo_root: &Path,
147148
) -> Result<TidyAdvice, ClangCaptureError> {
148149
let note_header = Regex::new(NOTE_HEADER)?;
149150
let fixed_note = Regex::new(r"^.+:(\d+):\d+:\snote: FIX-IT applied suggested code changes$")?;
150151
let mut found_fix = false;
151152
let mut notification = None;
152153
let mut result = Vec::new();
153-
let cur_dir = current_dir().map_err(ClangCaptureError::UnknownWorkingDirectory)?;
154154
for line in String::from_utf8(tidy_stdout.to_vec())
155155
.map_err(|e| ClangCaptureError::NonUtf8Output {
156156
task: "convert clang-tidy stdout".to_string(),
@@ -191,16 +191,16 @@ fn parse_tidy_output(
191191
// file was not a named unit in the database;
192192
// try to normalize path as if relative to working directory.
193193
// NOTE: This shouldn't happen with a properly formed JSON database
194-
filename = normalize_path(&PathBuf::from_iter([&cur_dir, &filename]));
194+
filename = normalize_path(&PathBuf::from_iter([repo_root, &filename]));
195195
}
196196
} else {
197197
// still need to normalize the relative path despite missing database info.
198198
// let's assume the file is relative to current working directory.
199-
filename = normalize_path(&PathBuf::from_iter([&cur_dir, &filename]));
199+
filename = normalize_path(&PathBuf::from_iter([repo_root, &filename]));
200200
}
201-
debug_assert!(filename.is_absolute());
201+
202202
if filename.is_absolute()
203-
&& let Ok(file_n) = filename.strip_prefix(&cur_dir)
203+
&& let Ok(file_n) = filename.strip_prefix(repo_root)
204204
{
205205
// if this filename can't be made into a relative path, then it is
206206
// likely not a member of the project's sources (ie /usr/include/stdio.h)
@@ -297,16 +297,17 @@ pub fn run_clang_tidy(
297297
);
298298
cmd.args(["--line-filter", filter.as_str()]);
299299
}
300+
let repo_file_path = PathBuf::from_iter([&clang_params.repo_root, &file.name]);
300301
let original_content = if !clang_params.tidy_review {
301302
None
302303
} else {
303304
cmd.arg("--fix-errors");
304-
Some(
305-
fs::read_to_string(&file.name).map_err(|e| ClangCaptureError::ReadFileFailed {
305+
Some(fs::read_to_string(&repo_file_path).map_err(|e| {
306+
ClangCaptureError::ReadFileFailed {
306307
file_name: file_name.clone(),
307308
source: e,
308-
})?,
309-
)
309+
}
310+
})?)
310311
};
311312
if !clang_params.style.is_empty() {
312313
cmd.args(["--format-style", clang_params.style.as_str()]);
@@ -348,6 +349,7 @@ pub fn run_clang_tidy(
348349
file.tidy_advice = Some(parse_tidy_output(
349350
&output.stdout,
350351
&clang_params.database_json,
352+
&clang_params.repo_root,
351353
)?);
352354
if clang_params.tidy_review
353355
&& let Some(original_content) = &original_content
@@ -356,14 +358,14 @@ pub fn run_clang_tidy(
356358
// cache file changes in a buffer and restore the original contents for further analysis
357359
tidy_advice.patched =
358360
Some(
359-
fs::read(&file_name).map_err(|e| ClangCaptureError::ReadFileFailed {
361+
fs::read(&repo_file_path).map_err(|e| ClangCaptureError::ReadFileFailed {
360362
file_name: file_name.clone(),
361363
source: e,
362364
})?,
363365
);
364366
}
365367
// original_content is guaranteed to be Some() value at this point
366-
fs::write(&file_name, original_content).map_err(|e| {
368+
fs::write(&repo_file_path, original_content).map_err(|e| {
367369
ClangCaptureError::WriteFileFailed {
368370
file_name,
369371
source: e,
@@ -565,7 +567,7 @@ TrenchBroom/TrenchBroom/common/test/src/mdl/tst_ReadFreeImageTexture.cpp:44:48:
565567
44 | return diskFS.openFile(name) | kdl::and_then([](const auto& file) {
566568
| ^
567569
"#;
568-
let advice = parse_tidy_output(tidy_out.as_bytes(), &None).unwrap();
570+
let advice = parse_tidy_output(tidy_out.as_bytes(), &None, &PathBuf::from(".")).unwrap();
569571
assert_eq!(advice.notes.len(), 4);
570572
for note in advice.notes {
571573
assert!(note.diagnostic.contains('-'));

cpp-linter/src/cli/structs.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ pub struct FeedbackInput {
232232
pub tidy_review: bool,
233233
pub format_review: bool,
234234
pub passive_reviews: bool,
235+
pub repo_root: PathBuf,
235236
}
236237

237238
#[cfg(feature = "bin")]
@@ -247,6 +248,7 @@ impl From<&Cli> for FeedbackInput {
247248
tidy_review: args.feedback_options.tidy_review,
248249
format_review: args.feedback_options.format_review,
249250
passive_reviews: args.feedback_options.passive_reviews,
251+
repo_root: PathBuf::from(&args.source_options.repo_root),
250252
}
251253
}
252254
}
@@ -263,6 +265,7 @@ impl Default for FeedbackInput {
263265
tidy_review: false,
264266
format_review: false,
265267
passive_reviews: false,
268+
repo_root: PathBuf::from("."),
266269
}
267270
}
268271
}

cpp-linter/src/common_fs/mod.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
//! A module to hold all common file system functionality.
22
3-
use std::{fmt::Debug, fs, ops::RangeInclusive, path::PathBuf};
3+
use std::{
4+
fmt::Debug,
5+
fs,
6+
ops::RangeInclusive,
7+
path::{Path, PathBuf},
8+
};
49

510
use gix_imara_diff::Hunk;
611

@@ -140,8 +145,10 @@ impl FileObj {
140145
&self,
141146
review_comments: &mut ReviewComments,
142147
summary_only: bool,
148+
repo_root: &Path,
143149
) -> Result<(), FileObjError> {
144-
let original_content = fs::read_to_string(&self.name).map_err(FileObjError::ReadFile)?;
150+
let original_content =
151+
fs::read_to_string(repo_root.join(&self.name)).map_err(FileObjError::ReadFile)?;
145152
let file_name = self.name.to_str().unwrap_or_default().replace("\\", "/");
146153
if let Some(advice) = &self.format_advice {
147154
let patched = fs::read_to_string(&advice.patched).map_err(FileObjError::ReadFile)?;

cpp-linter/src/git.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ mod test {
99
use std::{
1010
env::{self, current_dir, set_current_dir},
1111
fs,
12+
path::PathBuf,
1213
process::Command,
1314
};
1415

@@ -101,7 +102,7 @@ mod test {
101102
&LinesChangedOnly::Off.into(),
102103
&base_diff,
103104
ignore_staged,
104-
".",
105+
&PathBuf::from("."),
105106
)
106107
.await
107108
.unwrap()

cpp-linter/src/rest_client/mod.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::{
22
env,
3-
path::PathBuf,
3+
path::{Path, PathBuf},
44
sync::{Arc, Mutex},
55
};
66

@@ -54,7 +54,7 @@ impl RestClient {
5454
lines_changed_only: &LinesChangedOnly,
5555
base_diff: &Option<String>,
5656
ignore_index: bool,
57-
repo_root: &str,
57+
repo_root: &Path,
5858
) -> Result<Vec<FileObj>, ClientError> {
5959
let files = self
6060
.client
@@ -181,7 +181,11 @@ impl RestClient {
181181
let file = file
182182
.lock()
183183
.map_err(|e| ClientError::MutexPoisoned(e.to_string()))?;
184-
file.make_suggestions_from_patch(&mut review_comments, summary_only)?;
184+
file.make_suggestions_from_patch(
185+
&mut review_comments,
186+
summary_only,
187+
&feedback_inputs.repo_root,
188+
)?;
185189
}
186190

187191
let mut options = ReviewOptions {

cpp-linter/src/run.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ pub async fn run_main(args: Vec<String>) -> Result<()> {
101101
}
102102

103103
rest_api_client.start_log_group("Get list of specified source files");
104+
let repo_root_path = PathBuf::from(&cli.source_options.repo_root);
104105
let files = if !matches!(cli.source_options.lines_changed_only, LinesChangedOnly::Off)
105106
|| cli.source_options.files_changed_only
106107
{
@@ -111,7 +112,7 @@ pub async fn run_main(args: Vec<String>) -> Result<()> {
111112
&cli.source_options.lines_changed_only.clone().into(),
112113
&cli.source_options.diff_base,
113114
cli.source_options.ignore_index,
114-
&cli.source_options.repo_root,
115+
&repo_root_path,
115116
)
116117
.await?
117118
} else {
@@ -123,7 +124,7 @@ pub async fn run_main(args: Vec<String>) -> Result<()> {
123124
let file_path = PathBuf::from(&file_name);
124125
FileObj::new(
125126
file_path
126-
.strip_prefix(&cli.source_options.repo_root)
127+
.strip_prefix(&repo_root_path)
127128
.map(PathBuf::from)
128129
.unwrap_or(file_path),
129130
)
@@ -136,7 +137,7 @@ pub async fn run_main(args: Vec<String>) -> Result<()> {
136137
&LinesChangedOnly::Off.into(),
137138
&cli.source_options.diff_base,
138139
cli.source_options.ignore_index,
139-
&cli.source_options.repo_root,
140+
&repo_root_path,
140141
)
141142
.await?;
142143
for changed_file in changed_files {

cpp-linter/tests/comments.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use cpp_linter::run::run_main;
55
use git_bot_feedback::LinesChangedOnly;
66
use mockito::Matcher;
77
use std::{env, fmt::Display, io::Write, path::Path};
8-
use tempfile::NamedTempFile;
8+
use tempfile::{NamedTempFile, TempDir};
99

1010
mod common;
1111
use common::{create_test_space, mock_server};
@@ -62,7 +62,7 @@ impl Default for TestParams {
6262
}
6363
}
6464

65-
async fn setup(lib_root: &Path, test_params: &TestParams) {
65+
async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) {
6666
let mut event_payload_path = NamedTempFile::new_in("./").unwrap();
6767
let tmp_out_file = NamedTempFile::new().unwrap();
6868
unsafe {
@@ -253,6 +253,7 @@ async fn setup(lib_root: &Path, test_params: &TestParams) {
253253
format!("--no-lgtm={}", test_params.no_lgtm),
254254
"-p=build".to_string(),
255255
"-i=build".to_string(),
256+
format!("--repo-root={}", tmp_dir.path().to_str().unwrap()),
256257
];
257258
if test_params.force_lgtm {
258259
args.push("-e=c".to_string());
@@ -278,9 +279,7 @@ async fn setup(lib_root: &Path, test_params: &TestParams) {
278279
async fn test_comment(test_params: &TestParams) {
279280
let tmp_dir = create_test_space(true);
280281
let lib_root = env::current_dir().unwrap();
281-
env::set_current_dir(tmp_dir.path()).unwrap();
282-
setup(&lib_root, test_params).await;
283-
env::set_current_dir(lib_root.as_path()).unwrap();
282+
setup(&lib_root, &tmp_dir, test_params).await;
284283
drop(tmp_dir);
285284
}
286285

cpp-linter/tests/common/mod.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use tempfile::TempDir;
2121
/// The returned directory object will automatically delete the
2222
/// temporary folder when it is dropped out of scope.
2323
pub fn create_test_space(setup_meson: bool) -> TempDir {
24-
let tmp = TempDir::new().unwrap();
24+
let tmp = TempDir::with_prefix("cpp-linter-test").unwrap();
2525
fs::create_dir(tmp.path().join("src")).unwrap();
2626
let src = fs::read_dir("tests/demo").unwrap();
2727
for file in src {
@@ -48,11 +48,10 @@ pub fn create_test_space(setup_meson: bool) -> TempDir {
4848
"demo.cpp",
4949
"demo.hpp",
5050
]);
51-
let output = cmd.output().expect("Failed to run 'meson init'");
52-
println!(
53-
"meson init stdout:\n{}",
54-
String::from_utf8(output.stdout.to_vec()).unwrap()
55-
);
51+
let status = cmd.status().expect("Failed to run 'meson init'");
52+
if !status.success() {
53+
panic!("Failed to initialize meson project with 'meson init'");
54+
}
5655
let meson_build_dir = tmp.path().join("build");
5756
let mut cmd = Command::new("meson");
5857
cmd.args([
@@ -61,13 +60,12 @@ pub fn create_test_space(setup_meson: bool) -> TempDir {
6160
meson_build_dir.as_path().to_str().unwrap(),
6261
test_dir.to_str().unwrap(),
6362
]);
64-
let output = cmd
65-
.output()
63+
let status = cmd
64+
.status()
6665
.expect("Failed to generate build assets with 'meson setup'");
67-
println!(
68-
"meson setup stdout:\n{}",
69-
String::from_utf8(output.stdout.to_vec()).unwrap()
70-
);
66+
if !status.success() {
67+
panic!("Failed to generate build assets with 'meson setup'");
68+
}
7169
let db = fs::File::open(meson_build_dir.join("compile_commands.json"))
7270
.expect("Failed to open compilation database");
7371
for line in io::BufReader::new(db).lines().map_while(Result::ok) {

cpp-linter/tests/paginated_changed_files.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@ use mockito::Matcher;
77
use tempfile::{NamedTempFile, TempDir};
88

99
use cpp_linter::{logger, rest_client::RestClient};
10-
use std::{env, io::Write, path::Path};
10+
use std::{
11+
env,
12+
io::Write,
13+
path::{Path, PathBuf},
14+
};
1115

1216
#[derive(PartialEq, Default)]
1317
enum EventType {
@@ -32,7 +36,7 @@ const RESET_RATE_LIMIT_HEADER: &str = "x-ratelimit-reset";
3236
const REMAINING_RATE_LIMIT_HEADER: &str = "x-ratelimit-remaining";
3337
const MALFORMED_RESPONSE_PAYLOAD: &str = "{\"message\":\"Resource not accessible by integration\"}";
3438

35-
async fn get_paginated_changes(lib_root: &Path, test_params: &TestParams) {
39+
async fn get_paginated_changes(lib_root: &Path, _tmp_dir: &TempDir, test_params: &TestParams) {
3640
let tmp = TempDir::new().expect("Failed to create a temp dir for test");
3741
let mut event_payload = NamedTempFile::new_in(tmp.path())
3842
.expect("Failed to spawn a tmp file for test event payload");
@@ -145,7 +149,7 @@ async fn get_paginated_changes(lib_root: &Path, test_params: &TestParams) {
145149
&LinesChangedOnly::Off,
146150
&None::<String>,
147151
false,
148-
".",
152+
&PathBuf::from("."),
149153
)
150154
.await;
151155
match files {
@@ -177,9 +181,7 @@ async fn get_paginated_changes(lib_root: &Path, test_params: &TestParams) {
177181
async fn test_get_changes(test_params: &TestParams) {
178182
let tmp_dir = create_test_space(false);
179183
let lib_root = env::current_dir().unwrap();
180-
env::set_current_dir(tmp_dir.path()).unwrap();
181-
get_paginated_changes(&lib_root, test_params).await;
182-
env::set_current_dir(lib_root.as_path()).unwrap();
184+
get_paginated_changes(&lib_root, &tmp_dir, test_params).await;
183185
drop(tmp_dir);
184186
}
185187

cpp-linter/tests/reviews.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use cpp_linter::{
77
use git_bot_feedback::LinesChangedOnly;
88
use mockito::Matcher;
99
use std::{env, io::Write, path::Path};
10-
use tempfile::NamedTempFile;
10+
use tempfile::{NamedTempFile, TempDir};
1111

1212
mod common;
1313
use common::{create_test_space, mock_server};
@@ -70,7 +70,7 @@ fn generate_tool_summary(review_enabled: bool, force_lgtm: bool, tool_name: &str
7070
}
7171
}
7272

73-
async fn setup(lib_root: &Path, test_params: &TestParams) {
73+
async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) {
7474
let mut event_payload_path = NamedTempFile::new_in("./").unwrap();
7575
let event_payload = if test_params.bad_pr_info {
7676
"".to_string()
@@ -239,6 +239,7 @@ async fn setup(lib_root: &Path, test_params: &TestParams) {
239239
format!("--no-lgtm={}", test_params.no_lgtm),
240240
"-p=build".to_string(),
241241
"-i=build".to_string(),
242+
format!("--repo-root={}", tmp_dir.path().to_str().unwrap()),
242243
];
243244
if test_params.force_lgtm {
244245
if test_params.tidy_review {
@@ -272,9 +273,7 @@ async fn setup(lib_root: &Path, test_params: &TestParams) {
272273
async fn test_review(test_params: &TestParams) {
273274
let tmp_dir = create_test_space(true);
274275
let lib_root = env::current_dir().unwrap();
275-
env::set_current_dir(tmp_dir.path()).unwrap();
276-
setup(&lib_root, test_params).await;
277-
env::set_current_dir(lib_root.as_path()).unwrap();
276+
setup(&lib_root, &tmp_dir, test_params).await;
278277
drop(tmp_dir);
279278
}
280279

0 commit comments

Comments
 (0)