mod repository;
use std::path::{Component, Path, PathBuf};
use serde::Serialize;
use crate::app::{AppSnapshot, CoverageReport, lexical};
use crate::boundary::links::{Cycle, Link};
use crate::boundary::rules::{Rules, RulesSource};
use crate::findings::{Detail, Findings};
use crate::modules::composer::Version;
use crate::modules::layout::Layout;
use crate::modules::module::Module;
pub use repository::{Repository, read_repository};
pub const SCHEMA_VERSION: u32 = 1;
const MAX_MODULES: usize = 2_000;
const MAX_LINKS: usize = 50_000;
const MAX_REFERENCES: usize = 100_000;
const MAX_FINDINGS: usize = 50_000;
pub const MAX_TEXT: usize = 1_024;
const MAX_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
const MAX_BODY_BYTES: usize = 4 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PushDocument {
pub schema_version: u32,
pub generated_at: String,
pub tool: PushTool,
pub app_path: String,
pub git: PushGit,
pub ci: PushCi,
pub environment: Option<String>,
pub snapshot: PushSnapshot,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PushTool {
pub name: String,
pub version: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PushGit {
pub repository: Option<String>,
pub commit: String,
pub head_commit: Option<String>,
pub branch: Option<String>,
pub base_branch: Option<String>,
pub base_commit: Option<String>,
pub pull_request: Option<u64>,
pub shallow: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PushCi {
pub provider: String,
pub run_id: Option<String>,
pub run_attempt: Option<u32>,
pub run_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushContext {
pub generated_at: String,
pub tool_version: String,
pub app_path: String,
pub git: PushGit,
pub ci: PushCi,
pub environment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PushSnapshot {
pub name: String,
pub laravel: Option<Version>,
pub package: Version,
pub actuator: Option<Version>,
pub layout: Layout,
pub modules: Vec<Module>,
pub coverage_report: Option<CoverageReport>,
pub links: Vec<Link>,
pub cycles: Vec<Cycle>,
pub rules: Rules,
pub rules_source: RulesSource,
pub coverage_ignored: Option<String>,
pub findings: Findings,
pub coverage_limit: u8,
}
pub fn push_document(app: AppSnapshot, context: PushContext) -> PushDocument {
let AppSnapshot {
root,
name,
laravel,
package,
actuator,
app_url: _,
app_env: _,
layout,
modules,
coverage_report,
git: _,
links,
cycles,
rules,
rules_source,
coverage_ignored,
findings,
coverage_limit,
package_data: _,
} = app;
let shallow = context.git.shallow;
let layout = Layout {
modules_dir: relative(&root, &layout.modules_dir),
statuses_file: relative(&root, &layout.statuses_file),
..layout
};
let modules = modules
.into_iter()
.map(|module| Module {
dir: relative(&root, &module.dir),
churn: if shallow { None } else { module.churn },
uncommitted: None,
..module
})
.collect();
let coverage_report = coverage_report.map(|report| CoverageReport {
path: relative(&root, &report.path),
..report
});
let mut links = links;
for reference in links.iter_mut().flat_map(|link| &mut link.refs) {
relative_text(&root, &mut reference.file);
}
let mut findings = findings;
for finding in &mut findings.list {
match &mut finding.detail {
Detail::InvalidManifest { file, .. }
| Detail::NoManifestName { file }
| Detail::StaleStatus { file, .. } => relative_text(&root, file),
Detail::NamespaceMismatch { folder, .. } => relative_text(&root, folder),
Detail::CircularUse { .. }
| Detail::ReadsInternals { .. }
| Detail::LowCoverage { .. }
| Detail::MissingTranslations { .. } => {}
}
}
PushDocument {
schema_version: SCHEMA_VERSION,
generated_at: context.generated_at,
tool: PushTool {
name: "mortise".to_owned(),
version: context.tool_version,
},
app_path: context.app_path,
git: context.git,
ci: context.ci,
environment: context.environment,
snapshot: PushSnapshot {
name,
laravel,
package,
actuator,
layout,
modules,
coverage_report,
links,
cycles,
rules,
rules_source,
coverage_ignored,
findings,
coverage_limit,
},
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PushLimit {
TooMany {
what: Counted,
count: usize,
limit: usize,
},
TooLong { text: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Counted {
Modules,
Links,
References,
Findings,
DocumentBytes,
BodyBytes,
}
impl PushDocument {
pub fn over_limit(&self) -> Option<PushLimit> {
let snapshot = &self.snapshot;
let references = snapshot.links.iter().map(|link| link.refs.len()).sum();
let counts = [
(Counted::Modules, snapshot.modules.len(), MAX_MODULES),
(Counted::Links, snapshot.links.len(), MAX_LINKS),
(Counted::References, references, MAX_REFERENCES),
(
Counted::Findings,
snapshot.findings.list.len(),
MAX_FINDINGS,
),
];
if let Some((what, count, limit)) = counts.into_iter().find(|(_, n, max)| n > max) {
return Some(PushLimit::TooMany { what, count, limit });
}
let path = |path: &PathBuf| path.to_string_lossy().into_owned();
let layout = [&snapshot.layout.modules_dir, &snapshot.layout.statuses_file];
let finding_paths =
snapshot
.findings
.list
.iter()
.filter_map(|finding| match &finding.detail {
Detail::InvalidManifest { file, .. }
| Detail::NoManifestName { file }
| Detail::StaleStatus { file, .. } => Some(file.clone()),
Detail::NamespaceMismatch { folder, .. } => Some(folder.clone()),
_ => None,
});
std::iter::once(self.app_path.clone())
.chain(layout.into_iter().map(path))
.chain(snapshot.modules.iter().map(|module| path(&module.dir)))
.chain(
snapshot
.coverage_report
.iter()
.map(|report| path(&report.path)),
)
.chain(
snapshot
.links
.iter()
.flat_map(|link| &link.refs)
.flat_map(|reference| [reference.file.clone(), reference.class.clone()]),
)
.chain(finding_paths)
.find(|text| text.chars().count() > MAX_TEXT)
.map(|text| PushLimit::TooLong { text })
}
}
pub fn byte_limit(document: usize, body: usize) -> Option<PushLimit> {
let too_many =
|what, count, limit| (count > limit).then_some(PushLimit::TooMany { what, count, limit });
too_many(Counted::DocumentBytes, document, MAX_DOCUMENT_BYTES)
.or_else(|| too_many(Counted::BodyBytes, body, MAX_BODY_BYTES))
}
fn relative(root: &Path, path: &Path) -> PathBuf {
let root = lexical(root);
let path = lexical(path);
let root: Vec<Component<'_>> = root.components().collect();
let path: Vec<Component<'_>> = path.components().collect();
let common = root.iter().zip(&path).take_while(|(a, b)| a == b).count();
let name = |part: &Component<'_>| part.as_os_str().to_string_lossy().into_owned();
if common == 0 {
return PathBuf::from(path.last().map(name).unwrap_or_else(|| ".".into()));
}
let mut relative: Vec<String> = vec!["..".into(); root.len() - common];
relative.extend(path[common..].iter().map(name));
if relative.is_empty() {
return PathBuf::from(".");
}
PathBuf::from(relative.join("/"))
}
fn relative_text(root: &Path, text: &mut String) {
let path = Path::new(text.as_str());
if path.is_absolute() || path.has_root() {
*text = relative(root, path).to_string_lossy().into_owned();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_outside_the_app_climbs_out_and_never_stays_absolute() {
let root = Path::new("/ci/repo/app");
let shown = |path: &str| relative(root, Path::new(path));
assert_eq!(
shown("/ci/repo/app/Modules/Billing"),
Path::new("Modules/Billing")
);
assert_eq!(shown("/ci/repo/app"), Path::new("."));
assert_eq!(
shown("/ci/repo/build/../coverage/clover.xml"),
Path::new("../coverage/clover.xml")
);
assert_eq!(shown("clover.xml"), Path::new("clover.xml"));
}
#[cfg(windows)]
#[test]
fn a_unc_path_as_the_core_writes_it_keeps_its_folders() {
let root = Path::new(r"\\server\share\repo");
let mut text = "//server/share/shared/Modules/Billing/app/Invoice.php".to_owned();
relative_text(root, &mut text);
assert_eq!(text, "../shared/Modules/Billing/app/Invoice.php");
}
}