Skip to content

Commit

Permalink
add verbosity option logging
Browse files Browse the repository at this point in the history
Signed-off-by: Brend Smits <[email protected]>
  • Loading branch information
Brend-Smits committed Apr 19, 2023
1 parent ffdf7ba commit 0b76b9f
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 13 deletions.
41 changes: 41 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ edition = "2021"
assert_cmd = "2.0.11"
assert_fs = "1.0.13"
clap = { version = "4.2.2", features = ["derive"] }
clap-verbosity-flag = "2.0.1"
env_logger = "0.10.0"
log = "0.4.17"
predicates = "3.0.3"
reqwest = { version = "0.11", features = ["json"] }
serde = "1.0.160"
Expand Down
21 changes: 16 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::fs::{self, File};
use std::io::{BufRead, BufReader, BufWriter, Write};

use clap::Parser;
use clap_verbosity_flag::Verbosity;
use log::{info, warn};
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, USER_AGENT};
use serde_json::from_str;
use serde_json::Value;
Expand All @@ -18,13 +20,22 @@ struct Cli {
#[clap(short, long)]
/// The GitHub API token for authentication.
token: Option<String>,
#[clap(flatten)]
verbose: Verbosity,
}

#[derive(Debug)]
pub struct CustomError(String);

fn main() -> Result<(), CustomError> {
let args = Cli::parse();

env_logger::Builder::new()
.filter_level(args.verbose.log_level_filter())
.format_module_path(false)
.format_target(false)
.init();

let client = reqwest::Client::new();
read_file_and_process_line_by_line(&args, &client, &fetch_sbom)?;
Ok(())
Expand Down Expand Up @@ -90,7 +101,7 @@ async fn fetch_sbom(
HeaderValue::from_str(&format!("Bearer {}", token)).expect("Expects bearer token"),
);
} else {
println!("Token is not set! I can only access some public repositories. Consider using a token with --token option");
info!("Token is not set! I can only access some public repositories. Consider using a token with --token option");
}
headers.insert(
USER_AGENT,
Expand All @@ -108,15 +119,15 @@ async fn fetch_sbom(
.await
.map_err(|err| CustomError(format!("Failed to get response body: {}", err)))?;
if response_text.contains("API rate limit exceeded") {
println!("Error: API rate limit exceeded");
warn!("Error: API rate limit exceeded");
std::process::exit(1);
}
if response_text.contains("Not Found") {
println!("Error: Repository '{}' not found", repo_name);
warn!("Error: Repository '{}' not found", repo_name);
return Ok(());
}
if response_text.contains("Bad credentials") {
println!("Error: Invalid Token, check token permissions and expiry date!");
warn!("Error: Invalid Token, check token permissions and expiry date!");
std::process::exit(1);
}

Expand All @@ -135,7 +146,7 @@ async fn fetch_sbom(
.expect("Could not create directory");
let sbom_save_directory_path = format!("{}/{}.json", sbom_save_directory_path, repo_name);
save_sbom_to_file(repo_name, &response_text, &sbom_save_directory_path)?;
println!("{:#?}", spdx.to_string());
info!("{:#?}", spdx.to_string());
Ok(())
}

Expand Down
20 changes: 12 additions & 8 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ fn retrieves_sbom_from_github() -> Result<(), Box<dyn std::error::Error>> {
cmd.arg("--repo-list-path")
.arg(file.path())
.arg("--save-directory-path")
.arg("target/tmp/");
.arg("target/tmp/")
.arg("-vvv");

// Assert
cmd.assert().success().stdout(predicate::str::contains(
cmd.assert().success().stderr(predicate::str::contains(
"com.github.Brend-Smits/retrieve-github-sbom-action",
));
cmd.assert().success().stdout(predicate::str::contains(
cmd.assert().success().stderr(predicate::str::contains(
"Token is not set! I can only access some public repositories. Consider using a token with --token option",
));
Ok(())
Expand All @@ -35,7 +36,8 @@ fn file_doesnt_exist() -> Result<(), Box<dyn std::error::Error>> {
.arg("--save-directory-path")
.arg("test/file/doesnt/exist")
.arg("--token")
.arg("foo");
.arg("foo")
.arg("-vvv");
cmd.assert().failure().stderr(predicate::str::contains(
"Error reading `test/file/doesnt/exist`: No such file or directory (os error 2)",
));
Expand All @@ -54,8 +56,9 @@ fn invalid_token_should_error() -> Result<(), Box<dyn std::error::Error>> {
.arg("--save-directory-path")
.arg("test/path/doesnt-exist")
.arg("--token")
.arg("foo");
cmd.assert().failure().stdout(predicate::str::contains(
.arg("foo")
.arg("-vvv");
cmd.assert().failure().stderr(predicate::str::contains(
"Error: Invalid Token, check token permissions and expiry date!\n",
));

Expand All @@ -73,8 +76,9 @@ fn non_existent_repo_should_log_and_continue() -> Result<(), Box<dyn std::error:
cmd.arg("--repo-list-path")
.arg(file.path())
.arg("--save-directory-path")
.arg("target/tmp");
cmd.assert().success().stdout(predicate::str::contains(
.arg("target/tmp")
.arg("-vvv");
cmd.assert().success().stderr(predicate::str::contains(
"Repository 'brend-smits/repo-doesnt-exist' not found",
));

Expand Down

0 comments on commit 0b76b9f

Please sign in to comment.