Skip to content

Instantly share code, notes, and snippets.

@sean-clayton
Created June 5, 2021 14:55
Show Gist options
  • Save sean-clayton/f03799cbd0744bedac35d37014bcf5ac to your computer and use it in GitHub Desktop.
Save sean-clayton/f03799cbd0744bedac35d37014bcf5ac to your computer and use it in GitHub Desktop.
#![allow(unused)]
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use std::io::{stdout, Error, ErrorKind, Write};
const LICENSE_DIRECTORY: &str = "licenses";
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let id = args.get(1);
return match id {
Some(id) => {
let license_text = license_text(id);
match license_text {
Ok(license_text) => return print_license_contents(&mut stdout(), license_text),
Err(_) => Err(Error::new(
ErrorKind::InvalidInput,
"Must provide a valid SPDX identifier.",
)),
}
}
None => {
return Err(Error::new(
ErrorKind::InvalidInput,
"Must provide a valid SPDX identifier.",
))
}
};
}
fn print_license_contents(stdout: &mut dyn Write, contents: String) -> std::io::Result<()> {
return write!(stdout, "{}", contents);
}
fn license_text(id: &str) -> std::result::Result<String, ()> {
return create_custom_license_text(LICENSE_DIRECTORY, id).or(create_license_text(id));
}
fn create_license_text(id: &str) -> std::result::Result<String, ()> {
let license = license::from_id(id);
match license {
Some(license) => {
return Ok(String::from(license.text()));
}
None => return Err(()),
}
}
fn create_custom_license_text(directory: &str, file_name: &str) -> std::result::Result<String, ()> {
let file_path = format!("{}/{}", directory, file_name);
match File::open(file_path) {
Ok(mut file) => {
let mut contents = String::new();
file.read_to_string(&mut contents);
return Ok(contents);
}
Err(_) => Err(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_create_valid_contents() {
let contents = create_license_text(&"MIT");
assert!(contents.is_ok());
}
#[test]
fn should_error_invalid_contents() {
let contents = create_license_text(&"mit");
assert!(contents.is_err());
}
#[test]
fn should_add_to_stdout() {
let mut stdout = Vec::new();
print_license_contents(&mut stdout, String::from("sup")).unwrap();
assert_eq!(stdout, b"sup");
}
#[test]
fn should_support_custom_licenses() {
let contents = create_custom_license_text(&"test-data/licenses", &"LicenseRef-Test");
assert!(contents.is_ok());
assert!(contents.unwrap() == "Test license")
}
#[test]
fn should_fail_on_non_existant_custom_licenses() {
let contents =
create_custom_license_text(&"directory does not exist", &"license does not exist");
assert!(contents.is_err());
}
#[test]
fn should_create_custom_licenses() {
let contents = license_text(&"LicenseRef-OGL");
assert!(contents.is_ok());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment