/ build.rs
build.rs
 1  // Copyright (C) 2019-2021 Alpha-Delta Network Inc.
 2  // This file is part of the alphastd library.
 3  
 4  // The alphastd library is free software: you can redistribute it and/or modify
 5  // it under the terms of the GNU General Public License as published by
 6  // the Free Software Foundation, either version 3 of the License, or
 7  // (at your option) any later version.
 8  
 9  // The alphastd library is distributed in the hope that it will be useful,
10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  // GNU General Public License for more details.
13  
14  // You should have received a copy of the GNU General Public License
15  // along with the alphastd library. If not, see <https://www.gnu.org/licenses/>.
16  
17  use std::{fs::File, io::Read, path::Path};
18  
19  use walkdir::WalkDir;
20  
21  // The following license text that should be present at the beginning of every source file.
22  const EXPECTED_LICENSE_TEXT: &[u8] = include_bytes!(".resources/license_header");
23  
24  // The following directories will be excluded from the license scan.
25  const DIRS_TO_SKIP: [&str; 5] = [".cargo", ".circleci", ".git", ".github", "target"];
26  
27  fn check_file_licenses<P: AsRef<Path>>(path: P) {
28      let path = path.as_ref();
29  
30      let mut iter = WalkDir::new(path).into_iter();
31      while let Some(entry) = iter.next() {
32          let entry = entry.unwrap();
33          let entry_type = entry.file_type();
34  
35          // Skip the specified directories.
36          if entry_type.is_dir() && DIRS_TO_SKIP.contains(&entry.file_name().to_str().unwrap_or("")) {
37              iter.skip_current_dir();
38  
39              continue;
40          }
41  
42          // Check all files with the ".rs" extension.
43          if entry_type.is_file() && entry.file_name().to_str().unwrap_or("").ends_with(".rs") {
44              let file = File::open(entry.path()).unwrap();
45              let mut contents = Vec::with_capacity(EXPECTED_LICENSE_TEXT.len());
46              file.take(EXPECTED_LICENSE_TEXT.len() as u64)
47                  .read_to_end(&mut contents)
48                  .unwrap();
49  
50              assert!(
51                  contents == EXPECTED_LICENSE_TEXT,
52                  "The license in \"{}\" is either missing or it doesn't match the expected string!",
53                  entry.path().display()
54              );
55          }
56      }
57  
58      // Re-run upon any changes to the workspace.
59      println!("cargo:rerun-if-changed=.");
60  }
61  
62  // The build script; it currently only checks the licenses.
63  fn main() {
64      // Check licenses in the current folder.
65      check_file_licenses(".");
66  }