feat: add Authentication

This commit is contained in:
Patrick 2024-11-14 21:41:37 +01:00
parent 82bf793ff8
commit 622cb26a3e
Signed by: patrick
GPG key ID: 451F95EFB8BECD0F

View file

@ -1,4 +1,5 @@
use std::{
env,
fmt::Write,
fs::{self, File},
io::{self, BufRead, BufReader},
@ -7,7 +8,7 @@ use std::{
use clap::{Args, Parser, Subcommand};
use color_eyre::eyre::{bail, ContextCompat, Result};
use regex::Regex;
use reqwest::Client;
use reqwest::{header, Client};
use serde::Deserialize;
#[derive(Parser)]
@ -84,7 +85,7 @@ fn parse_pr(pr: &str) -> Result<u32> {
let re = Regex::new(r"^[0-9]*$")?;
let re2 = Regex::new(r"^https://github.com/NixOS/nixpkgs/pull/([0-9]*)$")?;
if let Some(caps) = re.captures(pr) {
Ok(caps[1].parse::<u32>()?)
Ok(caps[0].parse::<u32>()?)
} else if let Some(caps) = re2.captures(pr) {
Ok(caps[1].parse::<u32>()?)
} else {
@ -93,6 +94,7 @@ fn parse_pr(pr: &str) -> Result<u32> {
}
async fn get_pr(pr: u32, client: &Client) -> Result<PR> {
eprintln!("https://api.github.com/repos/nixos/nixpkgs/pulls/{}", pr);
let request = client
.get(format!(
"https://api.github.com/repos/nixos/nixpkgs/pulls/{}",
@ -103,8 +105,13 @@ async fn get_pr(pr: u32, client: &Client) -> Result<PR> {
let v: PR = serde_json::from_str(&text)?;
Ok(v)
}
async fn contains(branch: &str, pr: &PR, client: &Client) -> Result<bool> {
if let Some(sha) = &pr.merge_commit_sha {
eprintln!(
"https://api.github.com/repos/nixos/nixpkgs/compare/{}...{}",
branch, sha
);
let req = client
.get(format!(
"https://api.github.com/repos/nixos/nixpkgs/compare/{}...{}",
@ -148,7 +155,19 @@ fn get_local_nixp_rev() -> Result<String> {
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let client = Client::builder().user_agent("nixp-meta tool").build()?;
let token = env::var("GH_TOKEN");
let client = Client::builder().user_agent("nixp-meta tool");
let mut headers = header::HeaderMap::new();
match token {
Ok(token) => {
// Consider marking security-sensitive headers with `set_sensitive`.
let mut auth_value = header::HeaderValue::from_str(&format!("token {}", token))?;
auth_value.set_sensitive(true);
headers.insert(header::AUTHORIZATION, auth_value);
}
Err(_) => eprintln!("Could not get GH_TOKEN, requests will be unauthorized"),
};
let client = client.default_headers(headers).build()?;
match &cli.command {
CliCommands::Track(opts) => {
let pr = parse_pr(&opts.pr)?;