Skip to content

Commit bbe2002

Browse files
authored
Merge pull request #1241 from DanielEScherzer/return-results
Return `Result` values rather than converting errors to `None`
2 parents 19948b7 + ba8cb90 commit bbe2002

32 files changed

Lines changed: 280 additions & 262 deletions

examples/cat-file.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ fn show_commit(commit: &Commit) {
8989
}
9090
show_sig("author", Some(commit.author()));
9191
show_sig("committer", Some(commit.committer()));
92-
if let Some(msg) = commit.message() {
92+
if let Ok(msg) = commit.message() {
9393
println!("\n{}", msg);
9494
}
9595
}
@@ -100,7 +100,7 @@ fn show_tag(tag: &Tag) {
100100
println!("tag {}", tag.name().unwrap());
101101
show_sig("tagger", tag.tagger());
102102

103-
if let Some(msg) = tag.message() {
103+
if let Ok(Some(msg)) = tag.message() {
104104
println!("\n{}", msg);
105105
}
106106
}

examples/log.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ fn run(args: &Args) -> Result<(), Error> {
176176
if !sig_matches(&commit.committer(), &args.flag_committer) {
177177
return None;
178178
}
179-
if !log_message_matches(commit.message(), &args.flag_grep) {
179+
if !log_message_matches(commit.message().ok(), &args.flag_grep) {
180180
return None;
181181
}
182182
Some(Ok(commit))

examples/pull.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ fn do_fetch<'a>(
5656
// Always fetch all tags.
5757
// Perform a download and also update tips
5858
fo.download_tags(git2::AutotagOption::All);
59-
println!("Fetching {} for repo", remote.name().unwrap());
59+
println!("Fetching {} for repo", remote.name().unwrap().unwrap());
6060
remote.fetch(refs, Some(&mut fo), None)?;
6161

6262
// If there are local objects (we got a thin pack), then tell the user
@@ -90,8 +90,8 @@ fn fast_forward(
9090
rc: &git2::AnnotatedCommit,
9191
) -> Result<(), git2::Error> {
9292
let name = match lb.name() {
93-
Some(s) => s.to_string(),
94-
None => String::from_utf8_lossy(lb.name_bytes()).to_string(),
93+
Ok(s) => s.to_string(),
94+
Err(_) => String::from_utf8_lossy(lb.name_bytes()).to_string(),
9595
};
9696
let msg = format!("Fast-Forward: Setting {} to id: {}", name, rc.id());
9797
println!("{}", msg);

examples/status.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ fn show_branch(repo: &Repository, format: &Format) -> Result<(), Error> {
134134
}
135135
Err(e) => return Err(e),
136136
};
137-
let head = head.as_ref().and_then(|h| h.shorthand());
137+
let head = head.as_ref().and_then(|h| h.shorthand().ok());
138138

139139
if format == &Format::Long {
140140
println!(

examples/tag.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ fn run(args: &Args) -> Result<(), Error> {
6565
} else if args.flag_list {
6666
let pattern = args.arg_pattern.as_ref().map(|s| &s[..]).unwrap_or("*");
6767
for name in repo.tag_names(Some(pattern))?.iter() {
68-
let name = name.unwrap();
68+
let name = name.expect("Not invalid utf8").expect("Not None");
6969
let obj = repo.revparse_single(name)?;
7070

7171
if let Some(tag) = obj.as_tag() {
@@ -83,7 +83,7 @@ fn run(args: &Args) -> Result<(), Error> {
8383
fn print_tag(tag: &Tag, args: &Args) {
8484
print!("{:<16}", tag.name().unwrap());
8585
if args.flag_n.is_some() {
86-
print_list_lines(tag.message(), args);
86+
print_list_lines(tag.message().unwrap(), args);
8787
} else {
8888
println!();
8989
}
@@ -92,7 +92,7 @@ fn print_tag(tag: &Tag, args: &Args) {
9292
fn print_commit(commit: &Commit, name: &str, args: &Args) {
9393
print!("{:<16}", name);
9494
if args.flag_n.is_some() {
95-
print_list_lines(commit.message(), args);
95+
print_list_lines(commit.message().ok(), args);
9696
} else {
9797
println!();
9898
}

src/blame.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,10 +206,12 @@ impl<'blame> BlameHunk<'blame> {
206206
/// The returned message is the summary of the commit, comprising the first
207207
/// paragraph of the message with whitespace trimmed and squashed.
208208
///
209-
/// `None` may be returned if an error occurs or if the summary is not valid
210-
/// utf-8.
211-
pub fn summary(&self) -> Option<&str> {
212-
self.summary_bytes().and_then(|s| str::from_utf8(s).ok())
209+
/// `Ok(None)` may be returned if there is no summary.
210+
pub fn summary(&self) -> Result<Option<&str>, Error> {
211+
match self.summary_bytes() {
212+
Some(sb) => str::from_utf8(sb).map(|s| Some(s)).map_err(|e| e.into()),
213+
None => Ok(None),
214+
}
213215
}
214216

215217
/// Get the short "summary" of the git commit message for the hunk.
@@ -448,7 +450,7 @@ mod tests {
448450
assert_eq!(hunk.final_start_line(), 1);
449451
assert_eq!(hunk.path(), Some(Path::new("foo/bar")));
450452
assert_eq!(hunk.lines_in_hunk(), 0);
451-
assert_eq!(hunk.summary(), Some("commit"));
453+
assert_eq!(hunk.summary(), Ok(Some("commit")));
452454
assert!(!hunk.is_boundary());
453455

454456
let blame_buffer = blame.blame_buffer("\n".as_bytes()).unwrap();

src/buf.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::str;
55

66
use crate::raw;
77
use crate::util::Binding;
8+
use crate::Error;
89

910
/// A structure to wrap an intermediate buffer used by libgit2.
1011
///
@@ -34,10 +35,8 @@ impl Buf {
3435
}
3536

3637
/// Attempt to view this buffer as a string slice.
37-
///
38-
/// Returns `None` if the buffer is not valid utf-8.
39-
pub fn as_str(&self) -> Option<&str> {
40-
str::from_utf8(&**self).ok()
38+
pub fn as_str(&self) -> Result<&str, Error> {
39+
str::from_utf8(&**self).map_err(|e| e.into())
4140
}
4241
}
4342

src/commit.rs

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,8 @@ impl<'repo> Commit<'repo> {
6363
///
6464
/// The returned message will be slightly prettified by removing any
6565
/// potential leading newlines.
66-
///
67-
/// `None` will be returned if the message is not valid utf-8
68-
pub fn message(&self) -> Option<&str> {
69-
str::from_utf8(self.message_bytes()).ok()
66+
pub fn message(&self) -> Result<&str, Error> {
67+
str::from_utf8(self.message_bytes()).map_err(|e| e.into())
7068
}
7169

7270
/// Get the full message of a commit as a byte slice.
@@ -80,17 +78,18 @@ impl<'repo> Commit<'repo> {
8078
/// Get the encoding for the message of a commit, as a string representing a
8179
/// standard encoding name.
8280
///
83-
/// `None` will be returned if the encoding is not known
84-
pub fn message_encoding(&self) -> Option<&str> {
81+
/// `Ok(None)` will be returned if the encoding is not known
82+
pub fn message_encoding(&self) -> Result<Option<&str>, Error> {
8583
let bytes = unsafe { crate::opt_bytes(self, raw::git_commit_message_encoding(&*self.raw)) };
86-
bytes.and_then(|b| str::from_utf8(b).ok())
84+
match bytes {
85+
Some(b) => str::from_utf8(b).map(|s| Some(s)).map_err(|e| e.into()),
86+
None => Ok(None),
87+
}
8788
}
8889

8990
/// Get the full raw message of a commit.
90-
///
91-
/// `None` will be returned if the message is not valid utf-8
92-
pub fn message_raw(&self) -> Option<&str> {
93-
str::from_utf8(self.message_raw_bytes()).ok()
91+
pub fn message_raw(&self) -> Result<&str, Error> {
92+
str::from_utf8(self.message_raw_bytes()).map_err(|e| e.into())
9493
}
9594

9695
/// Get the full raw message of a commit.
@@ -99,10 +98,8 @@ impl<'repo> Commit<'repo> {
9998
}
10099

101100
/// Get the full raw text of the commit header.
102-
///
103-
/// `None` will be returned if the message is not valid utf-8
104-
pub fn raw_header(&self) -> Option<&str> {
105-
str::from_utf8(self.raw_header_bytes()).ok()
101+
pub fn raw_header(&self) -> Result<&str, Error> {
102+
str::from_utf8(self.raw_header_bytes()).map_err(|e| e.into())
106103
}
107104

108105
/// Get an arbitrary header field.
@@ -129,10 +126,12 @@ impl<'repo> Commit<'repo> {
129126
/// The returned message is the summary of the commit, comprising the first
130127
/// paragraph of the message with whitespace trimmed and squashed.
131128
///
132-
/// `None` may be returned if an error occurs or if the summary is not valid
133-
/// utf-8.
134-
pub fn summary(&self) -> Option<&str> {
135-
self.summary_bytes().and_then(|s| str::from_utf8(s).ok())
129+
/// `Ok(None)` may be returned if there is no summary
130+
pub fn summary(&self) -> Result<Option<&str>, Error> {
131+
match self.summary_bytes() {
132+
Some(sb) => str::from_utf8(sb).map(|s| Some(s)).map_err(|e| e.into()),
133+
None => Ok(None),
134+
}
136135
}
137136

138137
/// Get the short "summary" of the git commit message.
@@ -151,10 +150,12 @@ impl<'repo> Commit<'repo> {
151150
/// but the first paragraph of the message. Leading and trailing whitespaces
152151
/// are trimmed.
153152
///
154-
/// `None` may be returned if an error occurs or if the summary is not valid
155-
/// utf-8.
156-
pub fn body(&self) -> Option<&str> {
157-
self.body_bytes().and_then(|s| str::from_utf8(s).ok())
153+
/// `Ok(None)` may be returned if there is no body.
154+
pub fn body(&self) -> Result<Option<&str>, Error> {
155+
match self.body_bytes() {
156+
Some(sb) => str::from_utf8(sb).map(|s| Some(s)).map_err(|e| e.into()),
157+
None => Ok(None),
158+
}
158159
}
159160

160161
/// Get the long "body" of the git commit message.
@@ -347,7 +348,7 @@ impl<'repo> std::fmt::Debug for Commit<'repo> {
347348
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
348349
let mut ds = f.debug_struct("Commit");
349350
ds.field("id", &self.id());
350-
if let Some(summary) = self.summary() {
351+
if let Ok(Some(summary)) = self.summary() {
351352
ds.field("summary", &summary);
352353
}
353354
ds.finish()
@@ -424,12 +425,12 @@ mod tests {
424425
let head = repo.head().unwrap();
425426
let target = head.target().unwrap();
426427
let commit = repo.find_commit(target).unwrap();
427-
assert_eq!(commit.message(), Some("initial\n\nbody"));
428-
assert_eq!(commit.body(), Some("body"));
428+
assert_eq!(commit.message(), Ok("initial\n\nbody"));
429+
assert_eq!(commit.body(), Ok(Some("body")));
429430
assert_eq!(commit.id(), target);
430431
commit.message_raw().unwrap();
431432
commit.raw_header().unwrap();
432-
commit.message_encoding();
433+
commit.message_encoding().expect("Should not be invalid");
433434
commit.summary().unwrap();
434435
commit.body().unwrap();
435436
commit.tree_id();
@@ -441,10 +442,10 @@ mod tests {
441442
crate::Oid::from_str(tree_header_bytes.as_str().unwrap()).unwrap(),
442443
commit.tree_id()
443444
);
444-
assert_eq!(commit.author().name(), Some("name"));
445-
assert_eq!(commit.author().email(), Some("email"));
446-
assert_eq!(commit.committer().name(), Some("name"));
447-
assert_eq!(commit.committer().email(), Some("email"));
445+
assert_eq!(commit.author().name(), Ok("name"));
446+
assert_eq!(commit.author().email(), Ok("email"));
447+
assert_eq!(commit.committer().name(), Ok("name"));
448+
assert_eq!(commit.committer().email(), Ok("email"));
448449

449450
let sig = repo.signature().unwrap();
450451
let tree = repo.find_tree(commit.tree_id()).unwrap();
@@ -457,7 +458,7 @@ mod tests {
457458
.amend(Some("HEAD"), None, None, None, Some("new message"), None)
458459
.unwrap();
459460
let new_head = repo.find_commit(new_head).unwrap();
460-
assert_eq!(new_head.message(), Some("new message"));
461+
assert_eq!(new_head.message(), Ok("new message"));
461462
new_head.into_object();
462463

463464
repo.find_object(target, None).unwrap().as_commit().unwrap();

src/config.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -522,10 +522,8 @@ impl Drop for Config {
522522

523523
impl<'cfg> ConfigEntry<'cfg> {
524524
/// Gets the name of this entry.
525-
///
526-
/// May return `None` if the name is not valid utf-8
527-
pub fn name(&self) -> Option<&str> {
528-
str::from_utf8(self.name_bytes()).ok()
525+
pub fn name(&self) -> Result<&str, Error> {
526+
str::from_utf8(self.name_bytes()).map_err(|e| e.into())
529527
}
530528

531529
/// Gets the name of this entry as a byte slice.
@@ -535,13 +533,11 @@ impl<'cfg> ConfigEntry<'cfg> {
535533

536534
/// Gets the value of this entry.
537535
///
538-
/// May return `None` if the value is not valid utf-8
539-
///
540536
/// # Panics
541537
///
542538
/// Panics when no value is defined.
543-
pub fn value(&self) -> Option<&str> {
544-
str::from_utf8(self.value_bytes()).ok()
539+
pub fn value(&self) -> Result<&str, Error> {
540+
str::from_utf8(self.value_bytes()).map_err(|e| e.into())
545541
}
546542

547543
/// Gets the value of this entry as a byte slice.
@@ -683,8 +679,8 @@ mod tests {
683679
let mut entries = cfg.entries(None).unwrap();
684680
while let Some(entry) = entries.next() {
685681
let entry = entry.unwrap();
686-
entry.name();
687-
entry.value();
682+
entry.name().unwrap();
683+
entry.value().unwrap();
688684
entry.level();
689685
}
690686
}

src/mailmap.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ mod tests {
105105
let mut mm = t!(Mailmap::new());
106106

107107
let mailmapped_sig = t!(mm.resolve_signature(&sig));
108-
assert_eq!(mailmapped_sig.name(), Some(sig_name));
109-
assert_eq!(mailmapped_sig.email(), Some(sig_email));
108+
assert_eq!(mailmapped_sig.name(), Ok(sig_name));
109+
assert_eq!(mailmapped_sig.email(), Ok(sig_email));
110110

111111
t!(mm.add_entry(None, None, None, sig_email));
112112
t!(mm.add_entry(
@@ -117,8 +117,8 @@ mod tests {
117117
));
118118

119119
let mailmapped_sig = t!(mm.resolve_signature(&sig));
120-
assert_eq!(mailmapped_sig.name(), Some("real name"));
121-
assert_eq!(mailmapped_sig.email(), Some("real@email"));
120+
assert_eq!(mailmapped_sig.name(), Ok("real name"));
121+
assert_eq!(mailmapped_sig.email(), Ok("real@email"));
122122
}
123123

124124
#[test]
@@ -128,7 +128,7 @@ mod tests {
128128

129129
let sig = t!(Signature::now("name", "email"));
130130
let mailmapped_sig = t!(mm.resolve_signature(&sig));
131-
assert_eq!(mailmapped_sig.name(), Some("name"));
132-
assert_eq!(mailmapped_sig.email(), Some("prøper@emæil"));
131+
assert_eq!(mailmapped_sig.name(), Ok("name"));
132+
assert_eq!(mailmapped_sig.email(), Ok("prøper@emæil"));
133133
}
134134
}

0 commit comments

Comments
 (0)