-
Notifications
You must be signed in to change notification settings - Fork 14
/
lib.rs
603 lines (549 loc) · 22.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! This crate contains a number of analyses
//! that can be run on dependency graph generated by `guppy`
//! the types for holding data has `tabled` trait
//! for pretty display
use anyhow::{anyhow, Result};
use git2::{build::CheckoutBuilder, Oid};
use guppy::graph::{PackageGraph, PackageMetadata};
use guppy::MetadataCommand;
use separator::Separatable;
use std::path::Path;
use tabled::Tabled;
use url::Url;
mod advisory;
mod code;
mod cratesio;
mod diff;
pub mod ghcomment;
mod github;
pub mod super_toml;
mod update;
use ghcomment::{Emoji::*, GitHubCommentGenerator, ListStyle::Bulleted, TextStyle::*};
use update::{UpdateReviewReport, VersionConflict};
// Usage metrics pulled from crates.io API
#[derive(Tabled, Clone)]
pub struct TabledCratesioReport {
pub name: String,
pub hosted_on_cratesio: bool,
pub cratesio_downloads: u64,
pub cratesio_dependents: u64,
}
// Usage, activity metrics pulled from GitHub API
#[derive(Tabled, Clone)]
pub struct TabledGitHubReport {
pub name: String,
pub hosted_on_github: bool,
pub github_stars: u64,
pub github_subscribers: u64,
pub github_forks: u64,
pub open_issues: u64,
pub days_since_last_commit_on_default_branch: u64,
pub days_since_last_open_issue: u64,
pub open_issues_labeld_bug: u64,
pub open_issues_labeled_security: u64,
pub past_days_for_recent_stats: u64,
pub recent_commits: u64,
pub recent_committers: u64,
}
// Analaysis on difference between crates.io and git source
// for a crate version: difference is a potential red flag
#[derive(Tabled, Clone)]
pub struct TabledCrateSourceDiffReport {
pub name: String,
pub version: String,
pub cratesio_source_diff_analyzed: bool,
pub cratesio_different_from_source: bool,
pub files_added: u64,
pub files_modified: u64,
}
#[derive(Tabled, Default)]
pub struct TabledCodeReport {
pub name: String,
pub version: String,
pub is_direct: bool,
pub loc_analyzed: bool,
pub total_loc: u64,
pub rust_loc: u64,
pub unsafe_analyzed: bool,
pub forbids_unsafe: bool,
pub unsafe_expressions: u64,
pub has_build_script: bool,
pub deps_analyzed: bool,
pub total_deps: u64,
pub deps_with_build_script: u64,
pub deps_total_loc: u64,
pub deps_total_rust_loc: u64,
pub deps_analyzed_for_unsafe: u64,
pub deps_forbidding_unsafe: u64,
pub deps_using_unsafe: u64,
pub deps_total_unsafe_expressions: u64,
}
pub struct InvidualDepReport {
pub tabled_cratesio_report: TabledCratesioReport,
pub tabled_github_report: TabledGitHubReport,
pub tabled_crate_source_diff_report: TabledCrateSourceDiffReport,
}
pub struct DepDiveReport {
pub crate_stats: Vec<InvidualDepReport>,
pub code_stats: Vec<TabledCodeReport>,
}
pub struct DependencyAnalyzer;
impl DependencyAnalyzer {
pub fn analyze_dep(&self, package: &PackageMetadata) -> Result<InvidualDepReport> {
// let name = package.name().to_string();
// let has_build_script = package.has_build_script();
println!("analyzing crates.io metrics...");
let cratesio_report = cratesio::CratesioAnalyzer::new()?;
let cratesio_report = cratesio_report.analyze_cratesio(package)?;
let tabled_cratesio_report = TabledCratesioReport {
name: cratesio_report.name,
hosted_on_cratesio: cratesio_report.is_hosted,
cratesio_downloads: cratesio_report.downloads,
cratesio_dependents: cratesio_report.dependents,
};
println!("analyzing github metrics...");
let github_report = github::GitHubAnalyzer::new()?;
let github_report = github_report.analyze_github(package)?;
let tabled_github_report = TabledGitHubReport {
name: github_report.name,
hosted_on_github: github_report.is_github_repo,
github_stars: github_report.repo_stats.stargazers_count,
github_subscribers: github_report.repo_stats.subscribers_count,
github_forks: github_report.repo_stats.forks,
open_issues: github_report.repo_stats.open_issues,
days_since_last_commit_on_default_branch: github_report
.activity_metrics
.days_since_last_commit,
days_since_last_open_issue: github_report
.activity_metrics
.days_since_last_open_issue
.unwrap_or(0),
open_issues_labeld_bug: github_report.activity_metrics.open_issues_labeld_bug,
open_issues_labeled_security: github_report
.activity_metrics
.open_issues_labeled_security,
past_days_for_recent_stats: github_report.activity_metrics.recent_activity.past_days,
recent_commits: github_report.activity_metrics.recent_activity.commits,
recent_committers: github_report.activity_metrics.recent_activity.committers,
};
println!("analyzing difference in crates.io hosted source vs git source");
let crate_source_report = diff::DiffAnalyzer::new()?;
let crate_source_report = crate_source_report.analyze_crate_source_diff(
package.name(),
&package.version().to_string(),
package.repository(),
)?;
let mut cratesio_source_diff_analyzed = false;
let mut cratesio_different_from_source = false;
let mut files_added = 0;
let mut files_modified = 0;
if crate_source_report.is_different.is_some() {
cratesio_source_diff_analyzed = true;
// If is_different has value then should below ones as well
cratesio_different_from_source = crate_source_report.is_different.unwrap();
let diff_report = crate_source_report.file_diff_stats.unwrap();
files_added = diff_report.files_added.len() as u64;
files_modified = diff_report.files_modified.len() as u64;
}
let tabled_crate_source_diff_report = TabledCrateSourceDiffReport {
name: crate_source_report.name,
version: crate_source_report.version,
cratesio_source_diff_analyzed,
cratesio_different_from_source,
files_added,
files_modified,
};
Ok(InvidualDepReport {
tabled_cratesio_report,
tabled_github_report,
tabled_crate_source_diff_report,
})
}
}
pub struct DependencyGraphAnalyzer;
impl DependencyGraphAnalyzer {
pub fn analyze_dep_graph(&self, graph: &PackageGraph) -> Result<DepDiveReport> {
// Group stats
println!("analyzing code metrics");
let code_reports = code::CodeAnalyzer::new();
let code_reports = code_reports.analyze_code(graph)?;
let code_reports = code_reports
.iter()
.map(|r| Self::get_tabled_code_report(r.clone()))
.collect();
// Individual stats
let direct_dependencies: Vec<_> = graph
.query_workspace()
.resolve_with_fn(|_, link| {
// Collect direct dependencies of workspace packages.
let (from, to) = link.endpoints();
from.in_workspace() && !to.in_workspace()
})
.packages(guppy::graph::DependencyDirection::Forward)
.filter(|pkg| !pkg.in_workspace())
.collect();
// Run Analysis on each direct dependency
let reports: Vec<InvidualDepReport> = direct_dependencies
.iter()
.map(|pkg| DependencyAnalyzer.analyze_dep(pkg))
.collect::<Result<_>>()?;
Ok(DepDiveReport {
crate_stats: reports,
code_stats: code_reports,
})
}
fn get_tabled_code_report(code_report: code::CodeReport) -> TabledCodeReport {
let name = code_report.name;
let version = code_report.version;
let is_direct = code_report.is_direct;
let has_build_script = code_report.has_build_script;
let mut loc_analyzed = false;
let mut total_loc = 0;
let mut rust_loc = 0;
if code_report.loc_report.is_some() {
let loc_report = code_report.loc_report.unwrap();
loc_analyzed = true;
total_loc = loc_report.total_loc;
rust_loc = loc_report.rust_loc;
}
let mut unsafe_analyzed = false;
let mut forbids_unsafe = false;
let mut unsafe_expressions = 0;
if code_report.unsafe_report.is_some() {
unsafe_analyzed = true;
let unsafe_report = code_report.unsafe_report.unwrap();
forbids_unsafe = unsafe_report.forbids_unsafe;
unsafe_expressions = unsafe_report.used_unsafe_count.expressions;
}
let mut deps_analyzed = false;
let mut total_deps = 0;
let mut deps_with_build_script = 0;
let mut deps_total_loc = 0;
let mut deps_total_rust_loc = 0;
let mut deps_analyzed_for_unsafe = 0;
let mut deps_forbidding_unsafe = 0;
let mut deps_using_unsafe = 0;
let mut deps_total_unsafe_expressions = 0;
if code_report.dep_report.is_some() {
deps_analyzed = true;
let dep_report = code_report.dep_report.unwrap();
total_deps = dep_report.total_deps;
deps_total_loc = dep_report.deps_total_loc_report.total_loc;
deps_total_rust_loc = dep_report.deps_total_loc_report.rust_loc;
deps_analyzed_for_unsafe = dep_report.deps_analyzed_for_unsafe;
deps_forbidding_unsafe = dep_report.deps_forbidding_unsafe;
deps_with_build_script = dep_report.deps_with_build_script;
deps_using_unsafe = dep_report.deps_using_unsafe;
deps_total_unsafe_expressions = dep_report.deps_total_used_unsafe_details.expressions;
}
TabledCodeReport {
name,
version,
is_direct,
loc_analyzed,
total_loc,
rust_loc,
unsafe_analyzed,
forbids_unsafe,
unsafe_expressions,
has_build_script,
deps_analyzed,
total_deps,
deps_with_build_script,
deps_total_loc,
deps_total_rust_loc,
deps_analyzed_for_unsafe,
deps_forbidding_unsafe,
deps_using_unsafe,
deps_total_unsafe_expressions,
}
}
}
pub struct UpdateAnalyzer;
impl UpdateAnalyzer {
pub fn run_update_analyzer(
prior_graph: &PackageGraph,
post_graph: &PackageGraph,
) -> Result<UpdateReviewReport> {
let update_analyzer = update::UpdateAnalyzer::new();
update_analyzer.analyze_updates(&prior_graph, &post_graph)
}
pub fn get_summary_report(
prior_graph: &PackageGraph,
post_graph: &PackageGraph,
) -> Result<String> {
let update_review_report = Self::run_update_analyzer(&prior_graph, &post_graph)?;
let gh = GitHubCommentGenerator::new();
// Write down info on updated dependencies
gh.add_header("Dependency update review", 2)?;
for report in &update_review_report.dep_update_review_reports {
// Version update info
gh.add_header(
&format!(
"{} upgraded to {} from {}",
report.name, report.updated_version.version, report.prior_version.version
),
3,
)?;
let mut checkmark_table: Vec<Vec<&str>> = Vec::new();
// Cratesio downloads
gh.add_collapsible_section(
"Click to show download counts",
&GitHubCommentGenerator::get_html_table(&[
vec![
report.updated_version.version.to_string(),
report.updated_version.downloads.separated_string(),
],
vec![
report.prior_version.version.to_string(),
report.prior_version.downloads.separated_string(),
],
]),
);
// Advisory
checkmark_table.push(vec![
"No known advisories",
GitHubCommentGenerator::get_checkmark(
report.updated_version.known_advisories.is_empty(),
),
]);
if !report.updated_version.known_advisories.is_empty() {
let ids: Vec<(String, Option<Url>)> = report
.updated_version
.known_advisories
.iter()
.map(|a| (a.id.clone(), a.url.clone()))
.collect();
gh.add_collapsible_section(
":bomb: The updated version contains known advisories",
&GitHubCommentGenerator::get_hyperlinked_list(&ids, Bulleted)?,
);
}
let fixed_advisories: Vec<(String, Option<Url>)> = report
.prior_version
.known_advisories
.iter()
.filter(|a| !report.updated_version.known_advisories.contains(a))
.map(|a| (a.id.clone(), a.url.clone()))
.collect();
if !fixed_advisories.is_empty() {
gh.add_collapsible_section(
":tada: This update fixes known advisories",
&GitHubCommentGenerator::get_hyperlinked_list(&fixed_advisories, Bulleted)?,
);
}
// Diff summary
match &report.diff_stats {
None => checkmark_table.push(vec![
"Depdive failed to get the diff between versions from crates.io",
GitHubCommentGenerator::get_emoji(Warning),
]),
Some(stats) => {
// Diff overview
gh.add_collapsible_section(
"Click to show version diff summary",
&GitHubCommentGenerator::get_html_table(&[
vec![
"total files changed".to_string(),
stats.files_changed.len().separated_string(),
],
vec![
"total rust files changed".to_string(),
stats.rust_files_changed.separated_string(),
],
vec![
"total loc change".to_string(),
(stats.insertions + stats.deletions).separated_string(),
],
]),
);
let changed_file_paths: Vec<String> =
stats.files_changed.iter().cloned().collect();
gh.add_collapsible_section(
"Click to show changed files",
&GitHubCommentGenerator::get_list(&changed_file_paths, Bulleted, Code)?,
);
checkmark_table.push(vec![
"No change in the build script",
GitHubCommentGenerator::get_checkmark(
stats.modified_build_scripts.is_empty(),
),
]);
if !stats.modified_build_scripts.is_empty() {
let paths: Vec<String> =
stats.modified_build_scripts.iter().cloned().collect();
gh.add_collapsible_section(
"Click to show modified build scripts",
&GitHubCommentGenerator::get_list(&paths, Bulleted, Code)?,
);
}
checkmark_table.push(vec![
"No change in any file with unsafe code",
GitHubCommentGenerator::get_checkmark(stats.unsafe_file_changed.is_empty()),
]);
if !stats.unsafe_file_changed.is_empty() {
let paths: Vec<String> = stats
.unsafe_file_changed
.iter()
.map(|stats| stats.file.clone())
.collect();
gh.add_collapsible_section(
"Click to show changed files with unsafe code",
&GitHubCommentGenerator::get_list(&paths, Bulleted, Code)?,
);
}
}
}
match report.updated_version.crate_source_diff_report.is_different {
None => {
checkmark_table.push(vec![
"Depdive failed to compare the new version with its source",
GitHubCommentGenerator::get_emoji(Warning),
]);
}
Some(f) => {
checkmark_table.push(vec![
"The source and crates.io code are the same",
GitHubCommentGenerator::get_checkmark(!f),
]);
if f {
let changed_files = report
.updated_version
.crate_source_diff_report
.file_diff_stats
.as_ref()
.ok_or_else(|| {
anyhow!("Cannot locate file paths in git source diff report")
})?;
// Only added and modified files are of concern
let paths: Vec<String> = changed_files
.files_added
.union(&changed_files.files_modified)
.cloned()
.collect();
gh.add_collapsible_section(
":warning: May wanna take a look at this files in crates.io",
&GitHubCommentGenerator::get_list(&paths, Bulleted, Code)?,
)
}
}
}
gh.add_html_table(&checkmark_table);
}
if !update_review_report.version_conflicts.is_empty() {
let mut conflicts: Vec<String> = Vec::new();
for conflict in &update_review_report.version_conflicts {
match conflict {
VersionConflict::DirectTransitiveVersionConflict {
name,
direct_dep_version,
transitive_dep_version,
} => conflicts.push(format!(
"{} has version {} as a transitive dep but version {} as a direct dep",
name, transitive_dep_version, direct_dep_version
)),
}
}
gh.add_collapsible_section(
":warning: Possible dependency Conflicts",
&GitHubCommentGenerator::get_list(&conflicts, Bulleted, Plain)?,
);
}
Ok(gh.get_comment())
}
pub fn run_update_analyzer_from_repo_commits(
name: &str,
repository: &str,
commit_a: &str,
commit_b: &str,
) -> Result<String> {
let diff_analyzer = diff::DiffAnalyzer::new()?;
let repo = diff_analyzer.get_git_repo(name, repository)?;
let path = repo
.path()
.parent()
.ok_or_else(|| anyhow!("repository path not found for {}", repository))?;
let mut checkout_builder = CheckoutBuilder::new();
checkout_builder.force();
// Get prior_graph
repo.checkout_tree(
&repo.find_object(Oid::from_str(commit_a)?, None)?,
Some(&mut checkout_builder),
)?;
let prior_graph = MetadataCommand::new().current_dir(path).build_graph()?;
// Get post_graph
repo.checkout_tree(
&repo.find_object(Oid::from_str(commit_b)?, None)?,
Some(&mut checkout_builder),
)?;
let post_graph = MetadataCommand::new().current_dir(path).build_graph()?;
UpdateAnalyzer::get_summary_report(&prior_graph, &post_graph)
}
pub fn run_update_from_paths(path_a: &Path, path_b: &Path) -> Result<String> {
let prior_graph = MetadataCommand::new().current_dir(path_a).build_graph()?;
let post_graph = MetadataCommand::new().current_dir(path_b).build_graph()?;
UpdateAnalyzer::get_summary_report(&prior_graph, &post_graph)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_update_review_report_from_repo_commits() {
println!(
"{}",
UpdateAnalyzer::run_update_analyzer_from_repo_commits(
"diem",
"https://github.com/diem/diem",
"20da44ad0918e6f260e9f150a60f28ec3b8665b2",
"2b2e529d96b6fbd9b5d111ecdd21acb61e95a28f"
)
.unwrap()
);
}
#[test]
fn test_update_review_report_from_paths() {
let mut checkout_builder = CheckoutBuilder::new();
checkout_builder.force();
let da = diff::DiffAnalyzer::new().unwrap();
let repo = da
.get_git_repo(
"test_a",
"https://github.com/nasifimtiazohi/test-version-tag",
)
.unwrap();
repo.checkout_tree(
&repo
.find_object(
Oid::from_str("43ffefddc15cc21725207e51f4d41d9931d197f2").unwrap(),
None,
)
.unwrap(),
Some(&mut checkout_builder),
)
.unwrap();
let path_a = repo.path().parent().unwrap();
// Get post_graph
let repo = da
.get_git_repo(
"test_b",
"https://github.com/nasifimtiazohi/test-version-tag",
)
.unwrap();
repo.checkout_tree(
&repo
.find_object(
Oid::from_str("96a541d081863875b169fc88cd8f58bbd268d377").unwrap(),
None,
)
.unwrap(),
Some(&mut checkout_builder),
)
.unwrap();
let path_b = repo.path().parent().unwrap();
println!(
"{}",
UpdateAnalyzer::run_update_from_paths(&path_a, &path_b).unwrap()
);
}
}