Skip to content

Commit 280268a

Browse files
committed
refactor: rename Commit -> CommitId and remove 1 layer of indentation
1 parent af78db6 commit 280268a

File tree

6 files changed

+60
-77
lines changed

6 files changed

+60
-77
lines changed

src/cli.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use clap::{
77

88
use crate::{
99
commands,
10-
config::{BranchName, Commit, PatchName, PrNumber, Remote},
10+
config::{BranchName, CommitId, PatchName, PrNumber, Remote},
1111
};
1212

1313
/// A tool which makes it easy to declaratively manage personal forks by automatically merging pull requests
@@ -35,7 +35,7 @@ pub enum Command {
3535
/// Generate a .patch file from a commit hash
3636
GenPatch {
3737
/// Transform this commit into a `.patch` file
38-
commit: Commit,
38+
commit: CommitId,
3939
/// Choose a custom file name for the `.patch` file
4040
#[arg(short, long)]
4141
filename: Option<PatchName>,
@@ -55,7 +55,7 @@ pub enum Command {
5555
branch: Option<BranchName>,
5656
/// When fetching this PR, reset to this commit
5757
#[arg(short = 'C', long)]
58-
commit: Option<Commit>,
58+
commit: Option<CommitId>,
5959
/// Check out the first fetched pull request
6060
#[arg(short, long)]
6161
checkout: bool,
@@ -68,7 +68,7 @@ pub enum Command {
6868
remote: Remote,
6969
/// When fetching this branch, reset to this commit
7070
#[arg(short = 'C', long)]
71-
commit: Option<Commit>,
71+
commit: Option<CommitId>,
7272
/// Check out the fetched branch
7373
#[arg(short, long)]
7474
checkout: bool,
@@ -131,7 +131,7 @@ pub struct Branch {
131131
/// Name of this branch in the remote
132132
pub name: String,
133133
/// When fetching this PR, reset to this commit
134-
pub commit: Option<Commit>,
134+
pub commit: Option<CommitId>,
135135
}
136136

137137
#[cfg(test)]
@@ -159,7 +159,7 @@ mod test {
159159
owner: RepoOwner::try_new("helix-editor").unwrap(),
160160
repo: RepoName::try_new("helix").unwrap(),
161161
branch: BranchName::try_new("master").unwrap(),
162-
commit: Some(Commit::try_new("1a2b3c").unwrap())
162+
commit: Some(CommitId::try_new("1a2b3c").unwrap())
163163
}
164164
);
165165
"helix-editor".parse::<Remote>().unwrap_err();

src/commands/branch_fetch.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
33
use colored::Colorize as _;
44

5-
use crate::config::{Commit, Remote};
5+
use crate::config::{CommitId, Remote};
66
use crate::git::{fetch_branch, git};
77
use anyhow::anyhow;
88

99
/// Fetch the given branch
1010
pub async fn branch_fetch(
1111
remote: Remote,
12-
commit: Option<Commit>,
12+
commit: Option<CommitId>,
1313
checkout: bool,
1414
) -> anyhow::Result<()> {
1515
let (_, info) = fetch_branch(&remote).await?;

src/commands/gen_patch.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ use std::path::PathBuf;
66
use anyhow::bail;
77

88
use crate::CONFIG_PATH;
9-
use crate::config::{Commit, PatchName};
9+
use crate::config::{CommitId, PatchName};
1010
use crate::git::git;
1111
use crate::utils::normalize_commit_msg;
1212

1313
/// Generate patch `filename` at the given `Commit`
14-
pub fn gen_patch(commit: Commit, filename: Option<PatchName>) -> anyhow::Result<()> {
14+
pub fn gen_patch(commit: CommitId, filename: Option<PatchName>) -> anyhow::Result<()> {
1515
if !CONFIG_PATH.exists() {
1616
log::info!(
1717
"Config directory {} does not exist, creating it...",

src/commands/pr_fetch.rs

Lines changed: 40 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use anyhow::{Context as _, anyhow};
44
use colored::Colorize as _;
55

6-
use crate::config::{BranchName, Commit, PrNumber, Remote, RepoName, RepoOwner};
6+
use crate::config::{BranchName, CommitId, PrNumber, Remote, RepoName, RepoOwner};
77
use crate::git::{fetch_pull_request, git};
88

99
/// Fetch the given `pr` of `remote` at `commit` and store it in local `branch`
@@ -13,7 +13,7 @@ pub async fn pr_fetch(
1313
pr: PrNumber,
1414
remote: Option<Remote>,
1515
branch: Option<BranchName>,
16-
commit: Option<Commit>,
16+
commit: Option<CommitId>,
1717
checkout: bool,
1818
) -> anyhow::Result<()> {
1919
pub const GITHUB_REMOTE_PREFIX: &str = "[email protected]:";
@@ -45,58 +45,53 @@ pub async fn pr_fetch(
4545
Ok,
4646
)?;
4747

48-
match fetch_pull_request(
48+
let Ok((response, info)) = fetch_pull_request(
4949
&format!("{}/{}", remote.owner, remote.repo),
5050
// TODO: make fetch_pull_request accept a u32 instead
5151
pr,
5252
branch,
5353
commit.as_ref(),
5454
)
5555
.await
56-
{
57-
Ok((response, info)) => {
58-
log::info!(
59-
"Fetched pull request {} available at branch {}{}",
60-
crate::utils::display_link(
61-
&format!(
62-
"{}{}{}{}",
63-
"#".bright_blue(),
64-
pr.to_string().bright_blue(),
65-
" ".bright_blue(),
66-
response.title.bright_blue().italic()
67-
),
68-
&response.html_url
69-
),
70-
info.branch.local_branch_name.as_ref().bright_cyan(),
71-
commit
72-
.clone()
73-
.map(|commit_hash| {
74-
format!(", at commit {}", commit_hash.as_ref().bright_yellow())
75-
})
76-
.unwrap_or_default()
77-
);
56+
.inspect_err(|err| {
57+
log::error!("{err}");
58+
}) else {
59+
return Ok(());
60+
};
7861

79-
// Attempt to cleanup after ourselves
80-
let _ = git(["remote", "remove", &info.remote.local_remote_alias]);
62+
log::info!(
63+
"Fetched pull request {} available at branch {}{}",
64+
crate::utils::display_link(
65+
&format!(
66+
"{}{}{}{}",
67+
"#".bright_blue(),
68+
pr.to_string().bright_blue(),
69+
" ".bright_blue(),
70+
response.title.bright_blue().italic()
71+
),
72+
&response.html_url
73+
),
74+
info.branch.local_branch_name.as_ref().bright_cyan(),
75+
commit
76+
.clone()
77+
.map(|commit_hash| { format!(", at commit {}", commit_hash.as_ref().bright_yellow()) })
78+
.unwrap_or_default()
79+
);
8180

82-
if checkout {
83-
if let Err(cant_checkout) =
84-
git(["checkout", info.branch.local_branch_name.as_ref()])
85-
{
86-
log::error!(
87-
"Could not check out branch {}:\n{cant_checkout}",
88-
info.branch.local_branch_name
89-
);
90-
} else {
91-
log::info!(
92-
"Automatically checked out the first branch: {}",
93-
info.branch.local_branch_name
94-
);
95-
}
96-
}
97-
}
98-
Err(err) => {
99-
log::error!("{err}");
81+
// Attempt to cleanup after ourselves
82+
let _ = git(["remote", "remove", &info.remote.local_remote_alias]);
83+
84+
if checkout {
85+
if let Err(checkout_err) = git(["checkout", info.branch.local_branch_name.as_ref()]) {
86+
log::error!(
87+
"Could not check out branch {}:\n{checkout_err}",
88+
info.branch.local_branch_name
89+
);
90+
} else {
91+
log::info!(
92+
"Automatically checked out the first branch: {}",
93+
info.branch.local_branch_name
94+
);
10095
}
10196
}
10297

src/config.rs

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ pub struct Remote {
4040
/// e.g. `master`
4141
pub branch: BranchName,
4242
/// e.g. `1a2b3c`
43-
pub commit: Option<Commit>,
43+
pub commit: Option<CommitId>,
4444
}
4545

4646
impl Remote {
@@ -104,7 +104,7 @@ pub struct PullRequest {
104104
/// Number of the pull request
105105
pub number: PrNumber,
106106
/// Commit to checkout of the pull request. If none, uses the latest commit
107-
pub commit: Option<Commit>,
107+
pub commit: Option<CommitId>,
108108
}
109109

110110
impl FromStr for PullRequest {
@@ -132,7 +132,7 @@ pub struct Branch {
132132
/// Name of the branch
133133
pub name: BranchName,
134134
/// Commit to checkout when fetching this branch
135-
pub commit: Option<Commit>,
135+
pub commit: Option<CommitId>,
136136
}
137137

138138
impl FromStr for Branch {
@@ -158,7 +158,7 @@ pub struct Ref {
158158
/// Git item. E.g. branch, or remote which may associate with the `commit`
159159
pub item: String,
160160
/// Commit to checkout of the `item`. If none, uses the latest commit
161-
pub commit: Option<Commit>,
161+
pub commit: Option<CommitId>,
162162
}
163163

164164
impl FromStr for Ref {
@@ -180,7 +180,7 @@ impl FromStr for Ref {
180180
} else {
181181
// They want to use a specific commit
182182
let head: String = parts[0..len - 1].iter().map(|s| String::from(*s)).collect();
183-
let commit = (parts[len - 1].to_owned()).parse::<Commit>().ok();
183+
let commit = (parts[len - 1].to_owned()).parse::<CommitId>().ok();
184184
Self { item: head, commit }
185185
}
186186
.pipe(Ok)
@@ -259,12 +259,11 @@ impl Display for PatchName {
259259
}
260260

261261
/// Represents a git commit hash
262-
// #[cfg_attr(test, nutype_test_util::derive(From))]
263262
#[nutype(
264263
validate(not_empty, predicate = is_valid_commit_hash),
265-
derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, AsRef, TryFrom)
264+
derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, AsRef, TryFrom, FromStr)
266265
)]
267-
pub struct Commit(String);
266+
pub struct CommitId(String);
268267

269268
/// Does not check if the commit exists, just checks if it is potentially valid
270269
///
@@ -273,17 +272,6 @@ pub fn is_valid_commit_hash(hash: &str) -> bool {
273272
hash.chars().all(|ch| ch.is_ascii_hexdigit())
274273
}
275274

276-
impl FromStr for Commit {
277-
type Err = String;
278-
279-
fn from_str(s: &str) -> Result<Self, Self::Err> {
280-
Self::try_new(s).map_err(|err| match err {
281-
CommitError::NotEmptyViolated => "commit cannot be empty".to_string(),
282-
CommitError::PredicateViolated => format!("invalid commit hash: {s}"),
283-
})
284-
}
285-
}
286-
287275
/// Implement `Deserialize` for these types, given that they have a `FromStr` impl
288276
// This is not a blanket impl as that would violate the orphan rule
289277
macro_rules! impl_deserialize_for {

src/git.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//! - Extract into a separate module, put it behind some more nice API
55
//! - Use `gix`? Or anyways, we could go without spawning an entire process each
66
//! time we want to interact with Git
7-
use crate::config::{BranchName, Commit, PrNumber};
7+
use crate::config::{BranchName, CommitId, PrNumber};
88
use std::path::{Path, PathBuf};
99
use std::process::{self, Output};
1010
use std::sync::LazyLock;
@@ -72,7 +72,7 @@ pub static CLIENT: LazyLock<Client> = LazyLock::new(|| *Box::new(Client::new()))
7272

7373
/// Fetches a branch of a remote into local. Optionally accepts a commit hash
7474
/// for versioning.
75-
pub fn add_remote_branch(remote_branch: &RemoteBranch, commit: Option<&Commit>) -> Result<()> {
75+
pub fn add_remote_branch(remote_branch: &RemoteBranch, commit: Option<&CommitId>) -> Result<()> {
7676
if let Err(err) = git([
7777
"remote",
7878
"add",
@@ -347,7 +347,7 @@ pub async fn fetch_pull_request(
347347
repo: &str,
348348
pull_request: PrNumber,
349349
custom_branch_name: Option<BranchName>,
350-
commit_hash: Option<&Commit>,
350+
commit_hash: Option<&CommitId>,
351351
) -> Result<(GitHubResponse, RemoteBranch)> {
352352
let url = format!("https://api.github.com/repos/{repo}/pulls/{pull_request}");
353353

0 commit comments

Comments
 (0)