Files
pruefwerk/compliance-agent/src/classify/language.rs
T
Sharang ParnerkarandClaude Opus 5.5 90bcb6e4f8
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 11m10s
fix(plc): a committed CODESYS project types a repository PLC only on its own
A code repository that also keeps a CODESYS project (a package.json,
pom.xml or Cargo.toml beside it) stays a code target and keeps its code
scans; its CODESYS components and runtime CVEs are collected by the code
pipeline either way. The committed-files verdict drops below the backend
manifests; a repository with nothing but the archive is still PLC.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
2026-10-08 23:26:00 +02:00

958 lines
35 KiB
Rust

//! Heuristic target-type classification from artifact kinds and source markers.
//!
//! Complements the Firmwerk firmware detector: this handles web / backend /
//! mobile / desktop / PLC by sniffing manifest files and file extensions in the
//! ingested code trees, plus strong priors from the artifact kinds themselves
//! (a PLC-project artifact is a PLC target; an `.ipa` is an iOS app).
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::{ArtifactKind, DetectedFact, TargetType};
use compliance_core::traits::{ClassificationInput, ClassifierVerdict, TargetClassifier};
/// Max directory depth scanned for marker files: deep enough for an Android
/// module's `app/src/main/AndroidManifest.xml` inside a monorepo folder.
const SCAN_DEPTH: usize = 6;
/// Directories not searched: build output, installed dependencies and tool
/// caches (Unity's `Library`, `Temp`, `Obj`), which hold other projects'
/// markers.
const SKIPPED_DIRS: &[&str] = &[
".git",
".gradle",
"build",
"node_modules",
"pods",
"deriveddata",
"library",
"temp",
"obj",
"logs",
];
/// Files whose location (relative path) is kept, for checks that need more
/// than the name: an Android module's manifest, Gradle build files, a Unity
/// project's settings.
const LOCATED_FILES: &[&str] = &[
"androidmanifest.xml",
"build.gradle",
"build.gradle.kts",
"projectversion.txt",
"pubspec.yaml",
"web.config",
];
/// Extensions of files whose location is kept: .NET project files.
const LOCATED_EXTENSIONS: &[&str] = &["csproj", "vbproj"];
/// Markers collected from a code tree.
#[derive(Default)]
struct Markers {
files: HashSet<String>,
dirs: HashSet<String>,
exts: HashSet<String>,
/// Relative paths (`/`-separated, as on disk) of the [`LOCATED_FILES`]
/// and [`LOCATED_EXTENSIONS`].
located: Vec<String>,
}
impl Markers {
fn has_file(&self, name: &str) -> bool {
self.files.contains(name)
}
fn has_ext(&self, ext: &str) -> bool {
self.exts.contains(ext)
}
fn any_dir_ends_with(&self, suffix: &str) -> bool {
self.dirs.iter().any(|d| d.ends_with(suffix))
}
/// The located files whose path ends with `suffix`.
fn located_ending<'a>(&'a self, suffix: &'a str) -> impl Iterator<Item = &'a String> + 'a {
self.located
.iter()
.filter(move |p| p.to_lowercase().ends_with(suffix))
}
}
/// Collect marker file/dir/extension names up to [`SCAN_DEPTH`], skipping
/// [`SKIPPED_DIRS`].
fn collect_markers(root: &Path) -> Markers {
let mut m = Markers::default();
let entries = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(SCAN_DEPTH)
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().to_lowercase().as_str()))
})
.filter_map(Result::ok);
for entry in entries {
let name = entry.file_name().to_string_lossy().to_lowercase();
if entry.file_type().is_dir() {
m.dirs.insert(name);
continue;
}
if let Some(ext) = entry.path().extension() {
m.exts.insert(ext.to_string_lossy().to_lowercase());
}
let ext = entry
.path()
.extension()
.map(|e| e.to_string_lossy().to_lowercase())
.unwrap_or_default();
if LOCATED_FILES.contains(&name.as_str()) || LOCATED_EXTENSIONS.contains(&ext.as_str()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
m.located.push(rel.to_string_lossy().replace('\\', "/"));
}
}
m.files.insert(name);
}
m.located.sort();
m
}
/// The text of `rel` under `root`, if it is small enough to be a manifest.
fn read_small(root: &Path, rel: &str) -> Option<String> {
const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
let path = root.join(rel);
let size = fs::metadata(&path).ok()?.len();
(size <= MAX_MANIFEST_BYTES)
.then(|| fs::read_to_string(&path).ok())
.flatten()
}
/// The mobile frameworks and app modules in a tree, beyond plain markers.
#[derive(Default)]
struct MobileShape {
/// Android application or library modules: their manifests, or Gradle
/// files applying the Android plugin.
android_modules: Vec<String>,
react_native: bool,
flutter: bool,
/// A Unity project (`ProjectSettings/ProjectVersion.txt`).
unity: bool,
/// A Unity project building for Android: Android plug-ins or a chosen
/// Android bundle identifier (see [`crate::pipeline::unity_settings`]).
unity_android: bool,
/// A Unity project building for iOS, likewise.
unity_ios: bool,
/// The bundle identifiers chosen for those platforms (`ios:com.x.y`).
unity_bundle_ids: Vec<String>,
}
/// How many .NET projects of each kind a tree holds.
#[derive(Default, Debug, PartialEq)]
struct DotnetShape {
/// WPF or Windows Forms applications.
desktop: usize,
/// ASP.NET (classic or Core) and WCF services.
service: usize,
/// Every project file, including libraries and tools.
projects: usize,
}
/// Markers of a WPF or Windows Forms project, in its project file.
const DESKTOP_PROJECT_MARKERS: &[&str] = &[
"<usewpf>true",
"<usewindowsforms>true",
"presentationframework",
"system.windows.forms",
// The WPF project type GUID of old-style project files.
"60dc8134-eba5-43b8-bcc9-bb4bc16c2548",
];
/// Markers of an ASP.NET or WCF project, in its project file.
const SERVICE_PROJECT_MARKERS: &[&str] = &[
"microsoft.net.sdk.web",
"microsoft.aspnetcore",
"system.web.mvc",
"system.web.http",
"system.servicemodel",
// The ASP.NET web application project type GUID.
"349c5851-65df-11da-9384-00065b846f21",
];
/// The kinds of the .NET projects under `root`. A project is a service when
/// its file names ASP.NET or WCF or a `Web.config` sits beside it, a desktop
/// app when it names WPF or Windows Forms.
fn dotnet_shape(root: &Path, m: &Markers) -> DotnetShape {
let mut shape = DotnetShape::default();
let web_configs: Vec<&str> = m
.located_ending("web.config")
.map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir))
.collect();
for project in m
.located_ending(".csproj")
.chain(m.located_ending(".vbproj"))
{
shape.projects += 1;
let text = read_small(root, project).unwrap_or_default().to_lowercase();
let dir = project.rsplit_once('/').map_or("", |(dir, _)| dir);
if SERVICE_PROJECT_MARKERS.iter().any(|k| text.contains(k)) || web_configs.contains(&dir) {
shape.service += 1;
} else if DESKTOP_PROJECT_MARKERS.iter().any(|k| text.contains(k)) {
shape.desktop += 1;
}
}
shape
}
/// The confidence for a .NET kind found in `count` of `projects` project
/// files: the dominant kind ranks highest, and none outranks a clear mobile
/// or PLC signal (0.8).
fn dotnet_confidence(count: usize, projects: usize) -> f32 {
// Counts of project files are small; the share needs no more precision.
#[allow(clippy::cast_precision_loss)]
let share = count as f32 / projects.max(1) as f32;
0.55 + 0.2 * share
}
/// What kind of mobile project the tree at `root` is.
fn mobile_shape(root: &Path, m: &Markers) -> MobileShape {
let mut shape = MobileShape::default();
for manifest in m.located_ending("androidmanifest.xml") {
// Every Android manifest names Android code: a Gradle module's
// `src/main/`, an Eclipse (ADT) project's root, a Unity project's
// `Assets/Plugins/Android/`. Only test manifests say nothing about
// the product.
let lower = format!("/{}", manifest.to_lowercase());
if !lower.contains("/androidtest/") && !lower.contains("/test/") {
shape.android_modules.push(manifest.clone());
}
}
for build in m
.located_ending("build.gradle")
.chain(m.located_ending("build.gradle.kts"))
{
let applies_android = read_small(root, build).is_some_and(|text| {
text.contains("com.android.application") || text.contains("com.android.library")
});
let module = build.rsplit_once('/').map_or("", |(dir, _)| dir);
let known = shape.android_modules.iter().any(|m| m.starts_with(module));
if applies_android && !known {
shape.android_modules.push(build.clone());
}
}
shape.react_native =
read_small(root, "package.json").is_some_and(|text| text.contains("\"react-native\""));
shape.flutter = m
.located_ending("pubspec.yaml")
.any(|p| read_small(root, p).is_some_and(|text| text.contains("sdk: flutter")));
// A Unity project's root holds `ProjectSettings/ProjectVersion.txt`.
let unity_roots: Vec<&str> = m
.located_ending("projectsettings/projectversion.txt")
.map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir))
.map(|settings| settings.rsplit_once('/').map_or("", |(dir, _)| dir))
.collect();
shape.unity = !unity_roots.is_empty();
for unity in unity_roots {
let platforms = crate::pipeline::unity_settings::unity_platforms(&root.join(unity));
for (name, platform, targeted) in [
("ios", platforms.ios, &mut shape.unity_ios),
("android", platforms.android, &mut shape.unity_android),
] {
let Some(platform) = platform else {
continue;
};
*targeted = true;
if let Some(id) = platform.bundle_id {
shape.unity_bundle_ids.push(format!("{name}:{id}"));
}
}
}
shape
}
/// Whether a `package.json` at `root` looks like a front-end app. A React
/// Native app also names `react`, but it is a mobile app.
fn package_json_is_frontend(root: &Path) -> bool {
let Ok(content) = fs::read_to_string(root.join("package.json")) else {
return false;
};
let c = content.to_lowercase();
!c.contains("\"react-native\"")
&& ["react", "next", "vue", "@angular", "svelte", "vite"]
.iter()
.any(|f| c.contains(f))
}
/// The heuristic classifier: artifact-kind priors + source-tree markers.
pub struct HeuristicClassifier;
impl HeuristicClassifier {
/// Verdicts from the artifact kinds alone (no filesystem needed).
fn kind_priors(&self, input: &ClassificationInput<'_>) -> Vec<ClassifierVerdict> {
let mut out = Vec::new();
for a in input.artifacts {
let lower = a.source_ref.to_lowercase();
match a.kind {
ArtifactKind::PlcProject => out.push(verdict(
TargetType::PlcSps,
0.85,
"PLC project artifact",
vec![],
)),
ArtifactKind::MobilePackage => {
let (tt, why) = if lower.ends_with(".ipa") {
(TargetType::IosApp, "iOS package (.ipa)")
} else {
(TargetType::AndroidApp, "Android package (.apk/.aab)")
};
out.push(verdict(tt, 0.85, why, vec![]));
}
ArtifactKind::ContainerImage => out.push(verdict(
TargetType::BackendService,
0.4,
"container image",
vec![],
)),
ArtifactKind::FirmwareImage => out.push(verdict(
TargetType::FirmwareBareMetal,
0.35,
"firmware image (pending firmwerk detection)",
vec![],
)),
// A CODESYS project archive uploaded as a plain archive: it is
// unpacked for the scan, so its extension is the evidence.
ArtifactKind::SourceArchive if lower.ends_with(".projectarchive") => out.push(
verdict(TargetType::PlcSps, 0.85, "CODESYS project archive", vec![]),
),
ArtifactKind::LiveUrl if input.artifacts.len() == 1 => {
out.push(verdict(TargetType::WebApp, 0.3, "live URL only", vec![]))
}
_ => {}
}
}
out
}
/// Verdicts from scanning the ingested code trees for manifest markers.
fn source_verdicts(&self, input: &ClassificationInput<'_>) -> Vec<ClassifierVerdict> {
let mut out = Vec::new();
for a in input.artifacts {
if !matches!(a.kind, ArtifactKind::GitRepo | ArtifactKind::SourceArchive) {
continue;
}
let Some(path) = input.working_paths.get(&a.id) else {
continue;
};
let m = collect_markers(path);
let shape = mobile_shape(path, &m);
// Mobile (checked first — strongest signal).
if !shape.android_modules.is_empty() || m.has_ext("apk") || m.has_ext("aab") {
let mut facts = facts_lang("kotlin/java");
// A repository with several apps (phone and tablet) names each.
facts.extend(
shape
.android_modules
.iter()
.take(10)
.map(|module| DetectedFact::new("android_module", module, "heuristic")),
);
out.push(verdict(
TargetType::AndroidApp,
0.8,
"Android manifest / gradle",
facts,
));
}
for (present, framework) in [
(shape.react_native, "react-native"),
(shape.flutter, "flutter"),
] {
if present {
let mut facts = facts_lang(if shape.flutter { "dart" } else { "javascript" });
facts.push(DetectedFact::new("framework", framework, "heuristic"));
out.push(verdict(
TargetType::AndroidApp,
0.75,
"cross-platform mobile app",
facts,
));
}
}
if shape.unity {
let mut facts = facts_lang("csharp");
facts.push(DetectedFact::new("framework", "unity", "heuristic"));
for id in &shape.unity_bundle_ids {
facts.push(DetectedFact::new("bundle_id", id.clone(), "heuristic"));
}
// Unity keeps the build target out of the repository; a chosen
// bundle identifier or native plug-ins for a platform, or
// Android app modules beside it, are the sign it ships there.
let android = shape.unity_android || !shape.android_modules.is_empty();
if android {
out.push(verdict(
TargetType::AndroidApp,
0.8,
"Unity project building for Android",
facts.clone(),
));
}
if shape.unity_ios {
out.push(verdict(
TargetType::IosApp,
0.8,
"Unity project building for iOS",
facts.clone(),
));
}
if !android && !shape.unity_ios {
out.push(verdict(
TargetType::DesktopApp,
0.6,
"Unity project (build target unknown)",
facts,
));
}
}
if m.any_dir_ends_with(".xcodeproj")
|| m.any_dir_ends_with(".xcworkspace")
|| m.has_file("info.plist")
|| m.has_file("cartfile")
|| m.has_file("podfile")
|| m.has_ext("ipa")
{
out.push(verdict(
TargetType::IosApp,
0.8,
"Xcode project / Info.plist / CocoaPods / Carthage",
facts_lang("swift/objc"),
));
}
// .NET, split by what each project builds. A Unity project's
// solution and C# projects are generated by the editor and say
// nothing about the product.
let dotnet = if shape.unity {
DotnetShape::default()
} else {
dotnet_shape(path, &m)
};
if dotnet.desktop > 0 {
out.push(verdict(
TargetType::DesktopApp,
dotnet_confidence(dotnet.desktop, dotnet.projects),
"WPF / Windows Forms projects",
facts_lang("csharp"),
));
}
if dotnet.service > 0 || m.has_ext("svc") {
out.push(verdict(
TargetType::BackendService,
dotnet_confidence(dotnet.service.max(1), dotnet.projects),
"ASP.NET / WCF projects",
facts_lang("csharp"),
));
}
// Native desktop projects, and .NET projects of no clear kind
// (libraries, console tools).
let unclear_dotnet = dotnet.desktop == 0
&& dotnet.service == 0
&& (dotnet.projects > 0 || (!shape.unity && m.has_ext("sln")));
if unclear_dotnet || m.has_ext("vcxproj") || m.has_ext("desktop") {
out.push(verdict(
TargetType::DesktopApp,
0.55,
"desktop project files",
facts_lang("dotnet/native"),
));
}
// PLC.
if m.has_ext("st") {
out.push(verdict(
TargetType::PlcSps,
0.8,
"Structured Text sources",
facts_lang("iec-61131-3"),
));
}
// A CODESYS project (or its archive) committed to the repository:
// PLC when nothing else is there. Below a backend manifest, so a
// code repository that also keeps a PLC project stays a code
// target (its CODESYS components are collected either way) and
// keeps its code scans.
if m.has_ext("projectarchive") || m.has_ext("project") {
out.push(verdict(
TargetType::PlcSps,
0.5,
"CODESYS project files",
facts_lang("iec-61131-3"),
));
}
// Web vs backend from package.json.
if m.has_file("package.json") {
if package_json_is_frontend(path) {
out.push(verdict(
TargetType::WebApp,
0.65,
"package.json with a front-end framework",
facts_lang("javascript"),
));
} else {
out.push(verdict(
TargetType::BackendService,
0.55,
"package.json (no front-end framework)",
facts_lang("javascript"),
));
}
}
// Backend languages.
for (file, lang) in [
("cargo.toml", "rust"),
("go.mod", "go"),
("pom.xml", "java"),
("requirements.txt", "python"),
("pyproject.toml", "python"),
] {
if m.has_file(file) {
out.push(verdict(
TargetType::BackendService,
0.6,
"backend build manifest",
facts_lang(lang),
));
}
}
// Container-only.
if m.has_file("dockerfile") && out.is_empty() {
out.push(verdict(
TargetType::BackendService,
0.4,
"Dockerfile",
facts_lang("container"),
));
}
}
out
}
}
impl TargetClassifier for HeuristicClassifier {
fn name(&self) -> &str {
"heuristic"
}
async fn classify(
&self,
input: &ClassificationInput<'_>,
) -> Result<Vec<ClassifierVerdict>, CoreError> {
let mut out = self.kind_priors(input);
out.extend(self.source_verdicts(input));
Ok(out)
}
}
fn verdict(
target_type: TargetType,
confidence: f32,
rationale: &str,
facts: Vec<DetectedFact>,
) -> ClassifierVerdict {
ClassifierVerdict {
target_type,
confidence,
facts,
rationale: rationale.to_string(),
}
}
fn facts_lang(lang: &str) -> Vec<DetectedFact> {
vec![DetectedFact::new("language", lang, "heuristic")]
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use compliance_core::models::Artifact;
use std::collections::HashMap;
use std::path::PathBuf;
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let p = std::env::temp_dir().join(format!("cs-classify-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&p).expect("mkdir");
Self(p)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
async fn classify_tree(setup: impl FnOnce(&Path)) -> Vec<ClassifierVerdict> {
let scratch = Scratch::new();
setup(&scratch.0);
let artifact = Artifact::git_repo("https://git/x", "main");
let mut wp = HashMap::new();
wp.insert(artifact.id.clone(), scratch.0.clone());
let artifacts = vec![artifact];
let input = ClassificationInput {
artifacts: &artifacts,
working_paths: &wp,
description: None,
};
HeuristicClassifier
.classify(&input)
.await
.expect("classify")
}
#[tokio::test]
async fn frontend_package_json_is_webapp() {
let v = classify_tree(|root| {
fs::write(
root.join("package.json"),
r#"{"dependencies":{"react":"18"}}"#,
)
.unwrap();
})
.await;
assert!(v.iter().any(|x| x.target_type == TargetType::WebApp));
}
#[tokio::test]
async fn cargo_toml_is_backend() {
let v = classify_tree(|root| {
fs::write(root.join("Cargo.toml"), "[package]\nname='x'").unwrap();
})
.await;
assert!(v
.iter()
.any(|x| x.target_type == TargetType::BackendService));
}
#[tokio::test]
async fn android_manifest_is_android() {
let v = classify_tree(|root| {
fs::write(root.join("AndroidManifest.xml"), "<manifest/>").unwrap();
})
.await;
assert!(v.iter().any(|x| x.target_type == TargetType::AndroidApp));
}
/// Write `files` (relative path, content) under `root`.
fn write_all(root: &Path, files: &[(&str, &str)]) {
for (rel, content) in files {
let path = root.join(rel);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(path, content).expect("write");
}
}
/// The verdict with the highest confidence.
fn top(verdicts: &[ClassifierVerdict]) -> TargetType {
verdicts
.iter()
.max_by(|a, b| a.confidence.total_cmp(&b.confidence))
.map(|v| v.target_type)
.expect("a verdict")
}
#[tokio::test]
async fn an_android_app_with_two_modules_and_a_unity_part_is_an_android_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
("settings.gradle", "include ':phone', ':tablet'"),
(
"phone/build.gradle",
"apply plugin: 'com.android.application'",
),
("phone/src/main/AndroidManifest.xml", "<manifest/>"),
(
"tablet/build.gradle",
"apply plugin: 'com.android.application'",
),
("tablet/src/main/AndroidManifest.xml", "<manifest/>"),
(
"unity/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2021.3.1f1",
),
("unity/Assets/Scripts/Pump.cs", "class Pump {}"),
("unity/Assembly-CSharp.csproj", "<Project/>"),
(
"unity/Library/PackageCache/x/AndroidManifest.xml",
"<manifest/>",
),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
let android = v
.iter()
.find(|x| x.target_type == TargetType::AndroidApp && x.rationale.contains("manifest"))
.expect("android verdict");
let modules: Vec<&str> = android
.facts
.iter()
.filter(|f| f.key == "android_module")
.map(|f| f.value.as_str())
.collect();
assert_eq!(
modules,
[
"phone/src/main/AndroidManifest.xml",
"tablet/src/main/AndroidManifest.xml"
]
);
// The generated Unity C# project is not read as a desktop app.
assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp));
}
#[tokio::test]
async fn an_eclipse_adt_project_and_a_unity_plugin_manifest_are_android() {
// The shape of a real pilot repository: an old ADT app (manifest at
// the project root, no Gradle) beside a Unity project whose only
// Android trace is its plugin manifest; Unity's generated C#
// projects alongside.
let v = classify_tree(|root| {
write_all(
root,
&[
("Phone/AndroidManifest.xml", "<manifest/>"),
("Phone/project.properties", "target=android-11"),
("Phone/src/com/example/Main.java", "class Main {}"),
(
"Game/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2019.4.1f1",
),
(
"Game/Assets/Plugins/Android/AndroidManifest.xml",
"<manifest/>",
),
("Game/Assembly-CSharp.csproj", "<Project/>"),
("Phone/src/test/AndroidManifest.xml", "<manifest/>"),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
let modules: Vec<&str> = v
.iter()
.flat_map(|x| &x.facts)
.filter(|f| f.key == "android_module")
.map(|f| f.value.as_str())
.collect();
assert_eq!(
modules,
[
"Game/Assets/Plugins/Android/AndroidManifest.xml",
"Phone/AndroidManifest.xml"
]
);
assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp));
}
#[tokio::test]
async fn a_unity_project_with_android_plugins_is_an_android_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2021.3.1f1",
),
("Assets/Plugins/Android/libpump.aar", ""),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
assert!(v.iter().any(|x| x
.facts
.iter()
.any(|f| f.key == "framework" && f.value == "unity")));
}
#[tokio::test]
async fn a_unity_project_for_ios_and_android_offers_both_with_its_bundle_ids() {
let settings = "%YAML 1.1\nPlayerSettings:\n applicationIdentifier:\n \
Android: com.DefaultCompany.Pump\n iPhone: com.example.pump\n \
iOSTargetOSVersionString: 12.0\n";
let v = classify_tree(|root| {
write_all(
root,
&[
(
"game/ProjectSettings/ProjectVersion.txt",
"m_EditorVersion: 2022.3.1f1",
),
("game/ProjectSettings/ProjectSettings.asset", settings),
("game/Assets/Plugins/Android/libpump.aar", ""),
],
);
})
.await;
let types: Vec<TargetType> = v.iter().map(|x| x.target_type).collect();
assert!(types.contains(&TargetType::IosApp), "{types:?}");
assert!(types.contains(&TargetType::AndroidApp), "{types:?}");
assert!(!types.contains(&TargetType::DesktopApp), "{types:?}");
assert!(v.iter().any(|x| x
.facts
.iter()
.any(|f| f.key == "bundle_id" && f.value == "ios:com.example.pump")));
}
#[tokio::test]
async fn a_react_native_app_is_mobile_not_a_web_app() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"package.json",
r#"{"dependencies":{"react":"18.2.0","react-native":"0.72.0"}}"#,
),
("android/app/src/main/AndroidManifest.xml", "<manifest/>"),
],
);
})
.await;
assert_eq!(top(&v), TargetType::AndroidApp);
assert!(!v.iter().any(|x| x.target_type == TargetType::WebApp));
}
#[tokio::test]
async fn a_flutter_app_is_mobile() {
let v = classify_tree(|root| {
write_all(
root,
&[(
"pubspec.yaml",
"dependencies:\n flutter:\n sdk: flutter\n",
)],
);
})
.await;
assert!(v.iter().any(|x| x
.facts
.iter()
.any(|f| f.key == "framework" && f.value == "flutter")));
}
#[tokio::test]
async fn dotnet_projects_split_into_desktop_and_services_by_majority() {
let wpf = r#"<Project><PropertyGroup><ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids></PropertyGroup><Reference Include="PresentationFramework" /></Project>"#;
let web = r#"<Project><Reference Include="System.Web.Mvc" /></Project>"#;
let wcf = r#"<Project><Reference Include="System.ServiceModel" /></Project>"#;
let services = classify_tree(|root| {
write_all(
root,
&[
("Plant.sln", ""),
("Plant.Client/Plant.Client.csproj", wpf),
("Plant.Web/Plant.Web.csproj", web),
("Plant.Web/Web.config", "<configuration/>"),
("Plant.Service/Plant.Service.csproj", wcf),
("Plant.Service/Pump.svc", ""),
("Plant.Core/Plant.Core.csproj", "<Project/>"),
],
);
})
.await;
assert_eq!(top(&services), TargetType::BackendService);
assert!(services
.iter()
.any(|x| x.target_type == TargetType::DesktopApp));
let desktop = classify_tree(|root| {
write_all(
root,
&[
("Plant.Client/Plant.Client.csproj", wpf),
(
"Plant.Tool/Plant.Tool.csproj",
"<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><UseWindowsForms>true</UseWindowsForms></PropertyGroup></Project>",
),
],
);
})
.await;
assert_eq!(top(&desktop), TargetType::DesktopApp);
}
#[tokio::test]
async fn markers_inside_build_output_and_dependencies_are_ignored() {
let v = classify_tree(|root| {
write_all(
root,
&[
(
"node_modules/x/android/src/main/AndroidManifest.xml",
"<manifest/>",
),
("app/build/intermediates/AndroidManifest.xml", "<manifest/>"),
("Cargo.toml", "[package]\nname='x'"),
],
);
})
.await;
assert!(!v.iter().any(|x| x.target_type == TargetType::AndroidApp));
}
#[tokio::test]
async fn structured_text_is_plc() {
let v = classify_tree(|root| {
fs::write(root.join("main.st"), "PROGRAM main END_PROGRAM").unwrap();
})
.await;
assert!(v.iter().any(|x| x.target_type == TargetType::PlcSps));
}
#[tokio::test]
async fn a_committed_codesys_archive_is_plc_unless_code_is_beside_it() {
let only_archive = classify_tree(|root| {
fs::write(root.join("Line.projectarchive"), b"PK").unwrap();
})
.await;
assert_eq!(top(&only_archive), TargetType::PlcSps);
let mixed = classify_tree(|root| {
fs::write(root.join("Pump.project"), b"").unwrap();
fs::write(root.join("package.json"), "{}").unwrap();
})
.await;
assert_eq!(top(&mixed), TargetType::BackendService);
}
#[tokio::test]
async fn an_uploaded_codesys_archive_prior_is_plc() {
let artifacts = vec![Artifact::source_archive("Line.projectarchive")];
let input = ClassificationInput {
artifacts: &artifacts,
working_paths: &HashMap::new(),
description: None,
};
let v = HeuristicClassifier.classify(&input).await.unwrap();
assert_eq!(top(&v), TargetType::PlcSps);
}
#[tokio::test]
async fn ipa_artifact_prior_is_ios() {
let artifacts = vec![Artifact::mobile_package("app.ipa")];
let wp = HashMap::new();
let input = ClassificationInput {
artifacts: &artifacts,
working_paths: &wp,
description: None,
};
let v = HeuristicClassifier
.classify(&input)
.await
.expect("classify");
assert!(v.iter().any(|x| x.target_type == TargetType::IosApp));
}
}