Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve code #5

Merged
merged 4 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 11 additions & 17 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,11 @@ impl Config {

let (dir_path, token_path, _) = Config::get_paths();

match fs::read_dir(&dir_path) {
Ok(_) => {}
Err(_) => {
fs::create_dir(&dir_path)?;
}
};
match fs::read(&token_path) {
Ok(_) => {}
Err(_) => {
fs::File::create(&token_path)?;
}
if fs::read_dir(&dir_path).is_err() {
fs::create_dir(&dir_path)?;
}
if fs::read(&token_path).is_err() {
fs::File::create(&token_path)?;
}
fs::write(&token_path, token)?;

Expand Down Expand Up @@ -111,7 +105,7 @@ impl Config {
false => {
let mut output = PR_PREFIX
.iter()
.map(|current| ("- ".to_owned() + current + "...").to_string())
.map(|current| format!("- {}...", current))
.collect::<Vec<String>>()
.join("\n");
output =
Expand Down Expand Up @@ -139,14 +133,14 @@ impl Config {
"Rework" => "rework",
"Ignore" => "feature",
"Bump" => "core",
&_ => todo!(),
_ => return Err(InquireError::Custom("Invalid input".into())),
};
let branch = branch_prefix.to_owned() + "/" + &linear_branch;
let branch = format!("{}/{}", branch_prefix, &linear_branch);

Ok(Config { pr_name, branch })
}

pub fn confirm(config: &Config) -> Result<bool, InquireError> {
pub fn confirm(&self) -> Result<bool, InquireError> {
println!(
"\
This will:
Expand All @@ -155,8 +149,8 @@ This will:
3. Push to the remote repository.
4. Create a pull request named {}.
5. Assign you the pull request.",
config.branch.bright_cyan(),
config.pr_name.bright_cyan(),
self.branch.bright_cyan(),
self.pr_name.bright_cyan(),
);
Confirm::new("Confirm? (y/n)").prompt()
}
Expand Down
115 changes: 58 additions & 57 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,73 +4,74 @@ use std::{
process::{Command, Stdio},
};

pub struct Git {}
pub fn create_branch(branch: &str) -> Result<String, Error> {
process_command(Command::new("git").arg("switch").arg("-c").arg(branch))
}

impl Git {
pub fn create_branch(branch: &str) -> Result<String, Error> {
Git::process_command(Command::new("git").arg("switch").arg("-c").arg(branch))
}
pub fn create_commit(msg: &str) -> Result<String, Error> {
process_command(
Command::new("git")
.arg("commit")
.arg("--allow-empty")
.arg("-m")
.arg(msg),
)
}

pub fn create_commit(msg: &str) -> Result<String, Error> {
Git::process_command(
Command::new("git")
.arg("commit")
.arg("--allow-empty")
.arg("-m")
.arg(msg),
)
}
pub fn push(branch: &str) -> Result<String, Error> {
process_command(
Command::new("git")
.arg("push")
.arg("-u")
.arg("origin")
.arg(branch),
)
}

pub fn push(branch: &str) -> Result<String, Error> {
Git::process_command(Command::new("git").arg("push").arg("origin").arg(branch))
pub fn get_current_repo() -> Result<String, Error> {
let git_config = fs::read_to_string(".git/config")?;
for line in git_config.lines() {
if line.contains("url = ") {
let url = line.split("url = ").collect::<Vec<&str>>()[1];
let repo = url.replace("https://github.com/", "").replace(".git", "");
return Ok(repo);
}
}
Err(Error::new(
ErrorKind::Other,
"Could not find the repository.".to_string(),
))
}

pub fn get_current_repo() -> Result<String, Error> {
let git_config = fs::read_to_string(".git/config")?;
for line in git_config.lines() {
if line.contains("url = ") {
let url = line.split("url = ").collect::<Vec<&str>>()[1];
let repo = url.replace("https://github.com/", "").replace(".git", "");
return Ok(repo);
}
pub fn get_default_branch() -> Result<String, Error> {
let origin = process_command(Command::new("git").arg("remote").arg("show").arg("origin"))?;
for line in origin.lines() {
if line.contains("HEAD branch:") {
let branch = line.split("HEAD branch: ").collect::<Vec<&str>>()[1];
return Ok(branch.to_string());
}
Err(Error::new(
ErrorKind::Other,
"Could not find the repository.".to_string(),
))
}
Err(Error::new(
ErrorKind::Other,
"Could not find the default branch.".to_string(),
))
}

pub fn get_default_branch() -> Result<String, Error> {
let origin =
Git::process_command(Command::new("git").arg("remote").arg("show").arg("origin"))?;
for line in origin.lines() {
if line.contains("HEAD branch:") {
let branch = line.split("HEAD branch: ").collect::<Vec<&str>>()[1];
return Ok(branch.to_string());
}
}
fn process_command(command: &mut Command) -> Result<String, Error> {
let output = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()?;

if output.status.success() {
Ok(String::from_utf8(output.stdout).unwrap())
} else {
Err(Error::new(
ErrorKind::Other,
"Could not find the default branch.".to_string(),
String::from_utf8(output.stderr).unwrap(),
))
}

fn process_command(command: &mut Command) -> Result<String, Error> {
let output = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap()
.wait_with_output()?;

if output.status.success() {
Ok(String::from_utf8(output.stdout).unwrap())
} else {
Err(Error::new(
ErrorKind::Other,
String::from_utf8(output.stderr).unwrap(),
))
}
}
}
82 changes: 38 additions & 44 deletions src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,38 @@ use std::collections::HashMap;

use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, USER_AGENT};

use crate::{config::Config, git::Git};
use crate::{config::Config, git};

pub struct Github {
pub token: String,
pub struct Github<'a> {
token: &'a str,
client: reqwest::Client,
}

impl Github {
pub fn new(token: &str) -> Self {
let token = token.to_string();
Self { token }
impl<'a> Github<'a> {
pub fn new(token: &'a str) -> Self {
let client = reqwest::Client::new();
Self { token, client }
}

pub async fn create_pr(
github: &Github,
config: Config,
) -> Result<String, Box<dyn std::error::Error>> {
let repo = Git::get_current_repo()?;
pub async fn create_pr(&self, config: Config) -> Result<String, Box<dyn std::error::Error>> {
let repo = git::get_current_repo()?;
let default_desc = Config::get_default_desc()?;
let base = Git::get_default_branch()?;
// let draft = String::from("true");

let mut body = HashMap::new();
body.insert("title", &config.pr_name);
body.insert("head", &config.branch);
body.insert("base", &base);
body.insert("body", &default_desc);
// body.insert("draft", &draft);

let client = reqwest::Client::new();
let response = client
.post("https://api.github.com/repos/".to_owned() + &repo + "/pulls")
let base = git::get_default_branch()?;
let draft = String::from("true");

let body = HashMap::from([
("title", &config.pr_name),
("head", &config.branch),
("base", &base),
("body", &default_desc),
("draft", &draft),
]);

let response = self
.client
.post(format!("https://api.github.com/repos/{}/pulls", &repo))
.body(serde_json::to_string(&body)?)
.headers(Github::construct_headers(&github.token))
.headers(Github::construct_headers(self.token))
.send()
.await?;

Expand All @@ -45,37 +44,32 @@ impl Github {
}

pub async fn assign_to_pr(
github: &Github,
&self,
username: &str,
number: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let repo = Git::get_current_repo()?;
let repo = git::get_current_repo()?;

let mut body = HashMap::new();
body.insert("assignees", vec![username]);
let body = HashMap::from([("assignees", vec![username])]);

let client = reqwest::Client::new();
client
.post(
"https://api.github.com/repos/".to_owned()
+ &repo
+ "/issues/"
+ number
+ "/assignees",
)
self.client
.post(format!(
"https://api.github.com/repos/{}/issues/{}/assignees",
&repo, number
))
.body(serde_json::to_string(&body)?)
.headers(Github::construct_headers(&github.token))
.headers(Github::construct_headers(self.token))
.send()
.await?;

Ok(())
}

pub async fn get_username(github: &Github) -> Result<String, Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let response = client
pub async fn get_username(&self) -> Result<String, Box<dyn std::error::Error>> {
let response = self
.client
.get("https://api.github.com/user")
.headers(Github::construct_headers(&github.token))
.headers(Github::construct_headers(self.token))
.send()
.await?;

Expand Down
Loading