Skip to content

Update edition and rustfmt #428

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

Merged
merged 3 commits into from
Jun 5, 2019
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ both threadsafe and memory safe and allows both reading and writing git
repositories.
"""
categories = ["api-bindings"]
edition = "2018"

[badges]
travis-ci = { repository = "rust-lang/git2-rs" }
Expand Down
36 changes: 19 additions & 17 deletions examples/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,10 @@
#![deny(warnings)]
#![allow(trivial_casts)]

extern crate git2;
extern crate docopt;
#[macro_use]
extern crate serde_derive;

use std::path::Path;
use docopt::Docopt;
use git2::Repository;
use serde_derive::Deserialize;
use std::path::Path;

#[derive(Deserialize)]
struct Args {
Expand All @@ -33,21 +29,26 @@ struct Args {
}

fn run(args: &Args) -> Result<(), git2::Error> {
let repo = try!(Repository::open(&Path::new(".")));
let mut index = try!(repo.index());
let repo = Repository::open(&Path::new("."))?;
let mut index = repo.index()?;

let cb = &mut |path: &Path, _matched_spec: &[u8]| -> i32 {
let status = repo.status_file(path).unwrap();

let ret = if status.contains(git2::Status::WT_MODIFIED) ||
status.contains(git2::Status::WT_NEW) {
let ret = if status.contains(git2::Status::WT_MODIFIED)
|| status.contains(git2::Status::WT_NEW)
{
println!("add '{}'", path.display());
0
} else {
1
};

if args.flag_dry_run {1} else {ret}
if args.flag_dry_run {
1
} else {
ret
}
};
let cb = if args.flag_verbose || args.flag_update {
Some(cb as &mut git2::IndexMatchedPath)
Expand All @@ -56,17 +57,17 @@ fn run(args: &Args) -> Result<(), git2::Error> {
};

if args.flag_update {
try!(index.update_all(args.arg_spec.iter(), cb));
index.update_all(args.arg_spec.iter(), cb)?;
} else {
try!(index.add_all(args.arg_spec.iter(), git2::IndexAddOption::DEFAULT, cb));
index.add_all(args.arg_spec.iter(), git2::IndexAddOption::DEFAULT, cb)?;
}

try!(index.write());
index.write()?;
Ok(())
}

fn main() {
const USAGE: &'static str = "
const USAGE: &str = "
usage: add [options] [--] [<spec>..]

Options:
Expand All @@ -76,8 +77,9 @@ Options:
-h, --help show this message
";

let args = Docopt::new(USAGE).and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
match run(&args) {
Ok(()) => {}
Err(e) => println!("error: {}", e),
Expand Down
44 changes: 22 additions & 22 deletions examples/blame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,14 @@
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/

extern crate git2;
extern crate docopt;
#[macro_use]
extern crate serde_derive;

use docopt::Docopt;
use git2::{Repository, BlameOptions};
use git2::{BlameOptions, Repository};
use serde_derive::Deserialize;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::io::{BufReader, BufRead};

#[derive(Deserialize)] #[allow(non_snake_case)]
#[derive(Deserialize)]
#[allow(non_snake_case)]
struct Args {
arg_path: String,
arg_spec: Option<String>,
Expand All @@ -32,7 +29,7 @@ struct Args {
}

fn run(args: &Args) -> Result<(), git2::Error> {
let repo = try!(Repository::open("."));
let repo = Repository::open(".")?;
let path = Path::new(&args.arg_path[..]);

// Prepare our blame options
Expand All @@ -45,8 +42,7 @@ fn run(args: &Args) -> Result<(), git2::Error> {

// Parse spec
if let Some(spec) = args.arg_spec.as_ref() {

let revspec = try!(repo.revparse(spec));
let revspec = repo.revparse(spec)?;

let (oldest, newest) = if revspec.mode().contains(git2::RevparseMode::SINGLE) {
(None, revspec.from())
Expand All @@ -66,29 +62,32 @@ fn run(args: &Args) -> Result<(), git2::Error> {
commit_id = format!("{}", commit.id())
}
}

}

let spec = format!("{}:{}", commit_id, path.display());
let blame = try!(repo.blame_file(path, Some(&mut opts)));
let object = try!(repo.revparse_single(&spec[..]));
let blob = try!(repo.find_blob(object.id()));
let blame = repo.blame_file(path, Some(&mut opts))?;
let object = repo.revparse_single(&spec[..])?;
let blob = repo.find_blob(object.id())?;
let reader = BufReader::new(blob.content());

for (i, line) in reader.lines().enumerate() {
if let (Ok(line), Some(hunk)) = (line, blame.get_line(i+1)) {
if let (Ok(line), Some(hunk)) = (line, blame.get_line(i + 1)) {
let sig = hunk.final_signature();
println!("{} {} <{}> {}", hunk.final_commit_id(),
String::from_utf8_lossy(sig.name_bytes()),
String::from_utf8_lossy(sig.email_bytes()), line);
println!(
"{} {} <{}> {}",
hunk.final_commit_id(),
String::from_utf8_lossy(sig.name_bytes()),
String::from_utf8_lossy(sig.email_bytes()),
line
);
}
}

Ok(())
}

fn main() {
const USAGE: &'static str = "
const USAGE: &str = "
usage: blame [options] [<spec>] <path>

Options:
Expand All @@ -97,8 +96,9 @@ Options:
-F follow only the first parent commits
";

let args = Docopt::new(USAGE).and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
match run(&args) {
Ok(()) => {}
Err(e) => println!("error: {}", e),
Expand Down
58 changes: 34 additions & 24 deletions examples/cat-file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,11 @@

#![deny(warnings)]

extern crate git2;
extern crate docopt;
#[macro_use]
extern crate serde_derive;

use std::io::{self, Write};

use docopt::Docopt;
use git2::{Repository, ObjectType, Blob, Commit, Signature, Tag, Tree};
use git2::{Blob, Commit, ObjectType, Repository, Signature, Tag, Tree};
use serde_derive::Deserialize;

#[derive(Deserialize)]
struct Args {
Expand All @@ -38,9 +34,9 @@ struct Args {

fn run(args: &Args) -> Result<(), git2::Error> {
let path = args.flag_git_dir.as_ref().map(|s| &s[..]).unwrap_or(".");
let repo = try!(Repository::open(path));
let repo = Repository::open(path)?;

let obj = try!(repo.revparse_single(&args.arg_object));
let obj = repo.revparse_single(&args.arg_object)?;
if args.flag_v && !args.flag_q {
println!("{} {}\n--", obj.kind().unwrap().str(), obj.id());
}
Expand All @@ -63,9 +59,7 @@ fn run(args: &Args) -> Result<(), git2::Error> {
Some(ObjectType::Tree) => {
show_tree(obj.as_tree().unwrap());
}
Some(ObjectType::Any) | None => {
println!("unknown {}", obj.id())
}
Some(ObjectType::Any) | None => println!("unknown {}", obj.id()),
}
}
Ok(())
Expand Down Expand Up @@ -100,26 +94,41 @@ fn show_tag(tag: &Tag) {

fn show_tree(tree: &Tree) {
for entry in tree.iter() {
println!("{:06o} {} {}\t{}",
entry.filemode(),
entry.kind().unwrap().str(),
entry.id(),
entry.name().unwrap());
println!(
"{:06o} {} {}\t{}",
entry.filemode(),
entry.kind().unwrap().str(),
entry.id(),
entry.name().unwrap()
);
}
}

fn show_sig(header: &str, sig: Option<Signature>) {
let sig = match sig { Some(s) => s, None => return };
let sig = match sig {
Some(s) => s,
None => return,
};
let offset = sig.when().offset_minutes();
let (sign, offset) = if offset < 0 {('-', -offset)} else {('+', offset)};
let (sign, offset) = if offset < 0 {
('-', -offset)
} else {
('+', offset)
};
let (hours, minutes) = (offset / 60, offset % 60);
println!("{} {} {} {}{:02}{:02}",
header, sig, sig.when().seconds(), sign, hours, minutes);

println!(
"{} {} {} {}{:02}{:02}",
header,
sig,
sig.when().seconds(),
sign,
hours,
minutes
);
}

fn main() {
const USAGE: &'static str = "
const USAGE: &str = "
usage: cat-file (-t | -s | -e | -p) [options] <object>

Options:
Expand All @@ -133,8 +142,9 @@ Options:
-h, --help show this message
";

let args = Docopt::new(USAGE).and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
match run(&args) {
Ok(()) => {}
Err(e) => println!("error: {}", e),
Expand Down
64 changes: 37 additions & 27 deletions examples/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,10 @@

#![deny(warnings)]

extern crate git2;
extern crate docopt;
#[macro_use]
extern crate serde_derive;

use docopt::Docopt;
use git2::build::{RepoBuilder, CheckoutBuilder};
use git2::{RemoteCallbacks, Progress, FetchOptions};
use git2::build::{CheckoutBuilder, RepoBuilder};
use git2::{FetchOptions, Progress, RemoteCallbacks};
use serde_derive::Deserialize;
use std::cell::RefCell;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -52,22 +48,34 @@ fn print(state: &mut State) {
let kbytes = stats.received_bytes() / 1024;
if stats.received_objects() == stats.total_objects() {
if !state.newline {
println!("");
println!();
state.newline = true;
}
print!("Resolving deltas {}/{}\r", stats.indexed_deltas(),
stats.total_deltas());
print!(
"Resolving deltas {}/{}\r",
stats.indexed_deltas(),
stats.total_deltas()
);
} else {
print!("net {:3}% ({:4} kb, {:5}/{:5}) / idx {:3}% ({:5}/{:5}) \
/ chk {:3}% ({:4}/{:4}) {}\r",
network_pct, kbytes, stats.received_objects(),
stats.total_objects(),
index_pct, stats.indexed_objects(), stats.total_objects(),
co_pct, state.current, state.total,
state.path
.as_ref()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default())
print!(
"net {:3}% ({:4} kb, {:5}/{:5}) / idx {:3}% ({:5}/{:5}) \
/ chk {:3}% ({:4}/{:4}) {}\r",
network_pct,
kbytes,
stats.received_objects(),
stats.total_objects(),
index_pct,
stats.indexed_objects(),
stats.total_objects(),
co_pct,
state.current,
state.total,
state
.path
.as_ref()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default()
)
}
io::stdout().flush().unwrap();
}
Expand Down Expand Up @@ -99,26 +107,28 @@ fn run(args: &Args) -> Result<(), git2::Error> {

let mut fo = FetchOptions::new();
fo.remote_callbacks(cb);
try!(RepoBuilder::new().fetch_options(fo).with_checkout(co)
.clone(&args.arg_url, Path::new(&args.arg_path)));
println!("");
RepoBuilder::new()
.fetch_options(fo)
.with_checkout(co)
.clone(&args.arg_url, Path::new(&args.arg_path))?;
println!();

Ok(())
}

fn main() {
const USAGE: &'static str = "
const USAGE: &str = "
usage: add [options] <url> <path>

Options:
-h, --help show this message
";

let args = Docopt::new(USAGE).and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
match run(&args) {
Ok(()) => {}
Err(e) => println!("error: {}", e),
}
}

Loading