1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use anyhow::anyhow;
16 use clap::Parser as _;
17 use file_header::{
18 add_headers_recursively, check_headers_recursively,
19 license::spdx::{YearCopyrightOwnerValue, APACHE_2_0},
20 };
21 use globset::{Glob, GlobSet, GlobSetBuilder};
22 use std::{env, path::PathBuf};
23
main() -> anyhow::Result<()>24 fn main() -> anyhow::Result<()> {
25 let rust_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
26 let ignore_globset = ignore_globset()?;
27 // Note: when adding headers, there is a bug where the line spacing is off for Apache 2.0 (see https://github.com/spdx/license-list-XML/issues/2127)
28 let header = APACHE_2_0.build_header(YearCopyrightOwnerValue::new(2023, "Google LLC".into()));
29
30 let cli = Cli::parse();
31
32 match cli.subcommand {
33 Subcommand::CheckAll => {
34 let result =
35 check_headers_recursively(&rust_dir, |p| !ignore_globset.is_match(p), header, 4)?;
36 if result.has_failure() {
37 return Err(anyhow!(
38 "The following files do not have headers: {result:?}"
39 ));
40 }
41 }
42 Subcommand::AddAll => {
43 let files_with_new_header =
44 add_headers_recursively(&rust_dir, |p| !ignore_globset.is_match(p), header)?;
45 files_with_new_header
46 .iter()
47 .for_each(|path| println!("Added header to: {path:?}"));
48 }
49 }
50 Ok(())
51 }
52
ignore_globset() -> anyhow::Result<GlobSet>53 fn ignore_globset() -> anyhow::Result<GlobSet> {
54 Ok(GlobSetBuilder::new()
55 .add(Glob::new("**/.idea/**")?)
56 .add(Glob::new("**/target/**")?)
57 .add(Glob::new("**/.gitignore")?)
58 .add(Glob::new("**/CHANGELOG.md")?)
59 .add(Glob::new("**/Cargo.lock")?)
60 .add(Glob::new("**/Cargo.toml")?)
61 .add(Glob::new("**/README.md")?)
62 .add(Glob::new("*.bin")?)
63 .build()?)
64 }
65
66 #[derive(clap::Parser)]
67 struct Cli {
68 #[clap(subcommand)]
69 subcommand: Subcommand,
70 }
71
72 #[derive(clap::Subcommand, Debug, Clone)]
73 enum Subcommand {
74 /// Checks if a license is present in files that are not in the ignore list.
75 CheckAll,
76 /// Adds a license as needed to files that are not in the ignore list.
77 AddAll,
78 }
79