Skip to content

Commit 758f855

Browse files
qticascramm
authored andcommitted
Locate license file in packge root if not specified in cargo metadata (bazelbuild#2521)
bazelbuild#2476 added rules_license license metadata to crate BUILD files but many crates to do not have a license file specified in their cargo metadata. This PR adds a fallback that attempts to locate a license file in the crate package root directory.
1 parent 3833a79 commit 758f855

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

crate_universe/src/context/crate_context.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ impl CrateContext {
450450
}
451451
}
452452

453-
let license_file = package.license_file.as_ref().map(|path| path.to_string());
453+
let license_file = Self::locate_license_file(package);
454454

455455
let package_url: Option<String> = match package.repository {
456456
Some(..) => package.repository.clone(),
@@ -650,6 +650,33 @@ impl CrateContext {
650650
self
651651
}
652652

653+
fn locate_license_file(package: &Package) -> Option<String> {
654+
if let Some(license_file_path) = &package.license_file {
655+
return Some(license_file_path.to_string());
656+
}
657+
let package_root = package
658+
.manifest_path
659+
.as_std_path()
660+
.parent()
661+
.expect("Every manifest should have a parent directory");
662+
if package_root.exists() {
663+
let mut paths: Vec<_> = package_root
664+
.read_dir()
665+
.unwrap()
666+
.map(|r| r.unwrap())
667+
.collect();
668+
paths.sort_by_key(|dir| dir.path());
669+
for path in paths {
670+
if let Some(file_name) = path.file_name().to_str() {
671+
if file_name.to_uppercase().starts_with("LICENSE") {
672+
return Some(file_name.to_string());
673+
}
674+
}
675+
}
676+
}
677+
None
678+
}
679+
653680
/// Determine whether or not a crate __should__ include a build script
654681
/// (build.rs) if it happens to have one.
655682
fn crate_includes_build_script(

0 commit comments

Comments
 (0)