Commit 25b6f61d authored by Brad King's avatar Brad King Committed by Kitware Robot

Merge topic 'rustfmt-20180904'

885c7387 MergeCommand: use debug_struct
a50cdc6b rust: avoid unnecessary Vec collecting
62f8658f rustfmt: add a space after a comment marker
b4898058 rustfmt: markup a TODO item with an issue number
458474b6 rustfmt: reformat function call arguments
b68441b1 rustfmt: reformat `where` clauses
e5d3e65b rustfmt: move operators to the front
9ae0df0a rustfmt: sort imports
...
Acked-by: Kitware Robot's avatarKitware Robot <kwrobot@kitware.com>
Merge-request: !62
parents 11acb0ac 885c7387
// Copyright {\d+} Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum_trailing_comma = true
fn_args_density = "Compressed"
fn_args_layout = "Visual"
match_block_trailing_comma = true
match_wildcard_trailing_comma = true
reorder_imported_names = true
struct_lit_multiline_style = "ForceMulti"
struct_lit_trailing_comma = "Always"
struct_trailing_comma = "Always"
where_trailing_comma = true
force_multiline_blocks = true
report_todo = "Unnumbered"
report_fixme = "Unnumbered"
struct_lit_single_line = false
trailing_comma = "Always"
license_template_path = ".license.template"
......@@ -14,8 +14,8 @@ use std::fmt::{self, Display};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// The Git object id of a commit.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommitId(String);
impl CommitId {
......@@ -36,8 +36,8 @@ impl Display for CommitId {
}
}
#[derive(Debug, Clone)]
/// A context for performing git commands.
#[derive(Debug, Clone)]
pub struct GitContext {
/// The path to the `.git` directory.
gitdir: PathBuf,
......@@ -45,8 +45,8 @@ pub struct GitContext {
config: Option<PathBuf>,
}
#[derive(Debug, PartialEq, Eq)]
/// An identity for creating git commits.
#[derive(Debug, PartialEq, Eq)]
pub struct Identity {
/// The name.
pub name: String,
......@@ -57,8 +57,9 @@ pub struct Identity {
impl Identity {
/// Create a new identity.
pub fn new<N, E>(name: N, email: E) -> Self
where N: ToString,
E: ToString,
where
N: ToString,
E: ToString,
{
Self {
name: name.to_string(),
......@@ -79,8 +80,8 @@ impl Display for Identity {
}
}
#[derive(Debug)]
/// Status of a merge check.
#[derive(Debug)]
pub enum MergeStatus {
/// The branches do not contain common history.
NoCommonHistory,
......@@ -92,20 +93,23 @@ pub enum MergeStatus {
impl Display for MergeStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"{}",
match *self {
MergeStatus::NoCommonHistory => "no common history",
MergeStatus::AlreadyMerged => "already merged",
MergeStatus::Mergeable(_) => "mergeable",
})
write!(
f,
"{}",
match *self {
MergeStatus::NoCommonHistory => "no common history",
MergeStatus::AlreadyMerged => "already merged",
MergeStatus::Mergeable(_) => "mergeable",
},
)
}
}
impl GitContext {
/// Create a new context for the given directory.
pub fn new<P>(gitdir: P) -> Self
where P: AsRef<Path>,
where
P: AsRef<Path>,
{
Self {
gitdir: gitdir.as_ref().to_path_buf(),
......@@ -115,8 +119,9 @@ impl GitContext {
/// Create a new context for the given directory with git configuration.
pub fn new_with_config<P, C>(gitdir: P, config: C) -> Self
where P: AsRef<Path>,
C: AsRef<Path>,
where
P: AsRef<Path>,
C: AsRef<Path>,
{
Self {
gitdir: gitdir.as_ref().to_path_buf(),
......@@ -143,21 +148,24 @@ impl GitContext {
///
/// The remote is interpreted by Git, so it can be a remote or a specific URL.
pub fn fetch<R, I, N>(&self, remote: R, refnames: I) -> Result<()>
where R: AsRef<str>,
I: IntoIterator<Item = N>,
N: AsRef<OsStr>,
where
R: AsRef<str>,
I: IntoIterator<Item = N>,
N: AsRef<OsStr>,
{
let fetch = self.git()
let fetch = self
.git()
.arg("fetch")
.arg(remote.as_ref())
.args(&refnames.into_iter()
.collect::<Vec<_>>())
.args(refnames.into_iter())
.output()
.chain_err(|| "failed to construct fetch command")?;
if !fetch.status.success() {
bail!(ErrorKind::Git(format!("fetch from {} failed: {}",
remote.as_ref(),
String::from_utf8_lossy(&fetch.stderr))));
bail!(ErrorKind::Git(format!(
"fetch from {} failed: {}",
remote.as_ref(),
String::from_utf8_lossy(&fetch.stderr)
)));
}
Ok(())
......@@ -165,23 +173,29 @@ impl GitContext {
/// Fetch a commit from the given remote into a specific local refname.
pub fn fetch_into<R, N, T>(&self, remote: R, refname: N, target: T) -> Result<()>
where R: AsRef<str>,
N: AsRef<str>,
T: AsRef<str>,
where
R: AsRef<str>,
N: AsRef<str>,
T: AsRef<str>,
{
self.fetch(remote,
&[&format!("{}:{}", refname.as_ref(), target.as_ref())])
self.fetch(
remote,
&[&format!("{}:{}", refname.as_ref(), target.as_ref())],
)
}
/// Fetch a commit from the given remote into a specific local refname, allowing rewinds.
pub fn force_fetch_into<R, N, T>(&self, remote: R, refname: N, target: T) -> Result<()>
where R: AsRef<str>,
N: AsRef<str>,
T: AsRef<str>,
where
R: AsRef<str>,
N: AsRef<str>,
T: AsRef<str>,
{
self.fetch_into(remote.as_ref(),
format!("+{}", refname.as_ref()),
target.as_ref())
self.fetch_into(
remote.as_ref(),
format!("+{}", refname.as_ref()),
target.as_ref(),
)
}
/// Create a tree where further work on the given revision can occur.
......@@ -196,14 +210,16 @@ impl GitContext {
/// The reserved reference is created as `refs/{name}/heads/{id}` where `id` is a unique
/// integer (which is also returned).
pub fn reserve_ref<N>(&self, name: N, commit: &CommitId) -> Result<(String, usize)>
where N: AsRef<str>,
where
N: AsRef<str>,
{
let ref_prefix = format!("refs/{}/heads", name.as_ref());
debug!(target: "git", "reserving ref under {}", ref_prefix);
loop {
let for_each_ref = self.git()
let for_each_ref = self
.git()
.arg("for-each-ref")
.arg("--format=%(refname)")
.arg("--")
......@@ -211,9 +227,11 @@ impl GitContext {
.output()
.chain_err(|| "failed to construct for-each-ref command")?;
if !for_each_ref.status.success() {
bail!(ErrorKind::Git(format!("listing all {} refs: {}",
ref_prefix,
String::from_utf8_lossy(&for_each_ref.stderr))));
bail!(ErrorKind::Git(format!(
"listing all {} refs: {}",
ref_prefix,
String::from_utf8_lossy(&for_each_ref.stderr)
)));
}
let refs = String::from_utf8_lossy(&for_each_ref.stdout);
......@@ -222,7 +240,8 @@ impl GitContext {
debug!(target: "git", "trying to reserve ref {}", new_ref);
let lock_ref = self.git()
let lock_ref = self
.git()
.arg("update-ref")
.arg(&new_ref)
.arg(commit.as_str())
......@@ -258,7 +277,8 @@ impl GitContext {
/// It is assumed that the `bases` refs are aligned with the `heads` references and not used
/// for other purposes.
pub fn reserve_refs<N>(&self, name: N, commit: &CommitId) -> Result<(String, String)>
where N: AsRef<str>,
where
N: AsRef<str>,
{
let (new_ref, id) = self.reserve_ref(name.as_ref(), commit)?;
let new_base = format!("refs/{}/bases/{}", name.as_ref(), id);
......@@ -281,7 +301,8 @@ impl GitContext {
return Ok(MergeStatus::NoCommonHistory);
}
let bases = String::from_utf8_lossy(&merge_base.stdout);
let bases = bases.split_whitespace()
let bases = bases
.split_whitespace()
.map(CommitId::new)
.collect::<Vec<_>>();
......
......@@ -43,8 +43,8 @@ mod prepare;
pub use error::Error;
pub use error::ErrorKind;
pub use error::ResultExt;
pub use error::Result;
pub use error::ResultExt;
pub use git::CommitId;
pub use git::GitContext;
......@@ -52,9 +52,9 @@ pub use git::Identity;
pub use git::MergeStatus;
pub use prepare::Conflict;
pub use prepare::GitWorkArea;
pub use prepare::MergeCommand;
pub use prepare::MergeResult;
pub use prepare::GitWorkArea;
pub use prepare::SubmoduleConfig;
#[cfg(test)]
......
This diff is collapsed.
......@@ -62,8 +62,10 @@ fn git_context(workspace_path: &Path) -> GitContext {
.output()
.unwrap();
if !clone.status.success() {
panic!("origin clone failed: {}",
String::from_utf8_lossy(&clone.stderr));
panic!(
"origin clone failed: {}",
String::from_utf8_lossy(&clone.stderr),
);
}
GitContext::new(gitdir)
......@@ -78,24 +80,30 @@ fn git_context_submodule(workspace_path: &Path, commit: &CommitId) -> GitContext
.output()
.unwrap();
if !clone.status.success() {
panic!("origin clone failed: {}",
String::from_utf8_lossy(&clone.stderr));
panic!(
"origin clone failed: {}",
String::from_utf8_lossy(&clone.stderr),
);
}
let ctx = GitContext::new(gitdir.join(".git"));
let checkout = ctx.git()
let checkout = ctx
.git()
.arg("checkout")
.arg(commit.as_str())
.current_dir(&gitdir)
.output()
.unwrap();
if !checkout.status.success() {
panic!("checkout failed: {}",
String::from_utf8_lossy(&checkout.stderr));
panic!(
"checkout failed: {}",
String::from_utf8_lossy(&checkout.stderr),
);
}
let submodule_update = ctx.git()
let submodule_update = ctx
.git()
.arg("submodule")
.arg("update")
.arg("--init")
......@@ -103,8 +111,10 @@ fn git_context_submodule(workspace_path: &Path, commit: &CommitId) -> GitContext
.output()
.unwrap();
if !submodule_update.status.success() {
panic!("submodule update failed: {}",
String::from_utf8_lossy(&submodule_update.stderr));
panic!(
"submodule update failed: {}",
String::from_utf8_lossy(&submodule_update.stderr),
);
}
ctx
......@@ -125,10 +135,11 @@ fn git_context_new(workspace_path: &Path) -> GitContext {
let ctx = GitContext::new(gitdir.join(".git"));
let commit = ctx.git()
let commit = ctx
.git()
.arg("commit")
.arg("--allow-empty")
.arg("-m").arg("root commit")
.args(&["-m", "root commit"])
.output()
.unwrap();
if !commit.status.success() {
......@@ -175,7 +186,8 @@ fn test_reserve_ref() {
assert_eq!(count, expected);
assert_eq!(refname, format!("refs/{}/heads/{}", name, expected));
let rev_parse = ctx.git()
let rev_parse = ctx
.git()
.arg("rev-parse")
.arg("--verify")
.arg(refname)
......@@ -224,7 +236,8 @@ fn test_reserve_refs() {
assert_eq!(head, format!("refs/{}/heads/{}", name, expected));
assert_eq!(base, format!("refs/{}/bases/{}", name, expected));
let rev_parse_head = ctx.git()
let rev_parse_head = ctx
.git()
.arg("rev-parse")
.arg("--verify")
.arg(head)
......@@ -235,7 +248,8 @@ fn test_reserve_refs() {
assert_eq!(actual_ref.trim(), commit.as_str());
let rev_parse_base = ctx.git()
let rev_parse_base = ctx
.git()
.arg("rev-parse")
.arg("--verify")
.arg(base)
......@@ -270,10 +284,10 @@ fn test_mergeable() {
if let MergeStatus::Mergeable(bases) = status {
assert_eq!(bases, &[base]);
} else {
panic!("topic {} should be mergeable into {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should be mergeable into {}: {:?}",
topic, base, status,
);
}
}
......@@ -290,10 +304,10 @@ fn test_mergeable_already_merged() {
if let MergeStatus::AlreadyMerged = status {
// OK
} else {
panic!("topic {} should already be merged into {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should already be merged into {}: {:?}",
topic, base, status,
);
}
}
......@@ -310,10 +324,10 @@ fn test_mergeable_conflict() {
if let MergeStatus::Mergeable(bases) = status {
assert_eq!(bases, &[CommitId::new(BASE_COMMIT)]);
} else {
panic!("topic {} should be mergeable into {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should be mergeable into {}: {:?}",
topic, base, status,
);
}
}
......@@ -335,25 +349,23 @@ fn test_mergeable_no_common_history() {
if let MergeStatus::NoCommonHistory = status {
// OK
} else {
panic!("topic {} should not have a common history with {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should not have a common history with {}: {:?}",
topic, base, status,
);
}
}
fn check_workarea(workarea: &GitWorkArea, commit: &CommitId) {
let rev_parse = workarea.git()
let rev_parse = workarea
.git()
.arg("rev-parse")
.arg(format!("{}^{{tree}}", commit))
.output()
.unwrap();
assert!(rev_parse.status.success());
let write_tree = workarea.git()
.arg("write-tree")
.output()
.unwrap();
let write_tree = workarea.git().arg("write-tree").output().unwrap();
assert!(write_tree.status.success());
let actual = String::from_utf8_lossy(&write_tree.stdout);
......@@ -407,24 +419,30 @@ fn test_work_area_setup_submodule() {
check_workarea(&workarea, &commit);
assert!(!workarea.submodule_config().is_empty());
let submodule_config = workarea.submodule_config()
let submodule_config = workarea
.submodule_config()
.iter()
.map(|(name, config)| {
(name.as_str(),
config.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0)))
(
name.as_str(),
config
.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0)),
)
})
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0));
assert_eq!(submodule_config,
&[
("submodule",
vec![
("path", "submodule"),
("url", "https://gitlab.kitware.com/utils/test-repo.git"),
]),
]);
assert_eq!(
submodule_config,
&[(
"submodule",
vec![
("path", "submodule"),
("url", "https://gitlab.kitware.com/utils/test-repo.git"),
]
),],
);
}
#[test]
......@@ -437,24 +455,30 @@ fn test_work_area_setup_submodule_custom_name() {
check_workarea(&workarea, &commit);
assert!(!workarea.submodule_config().is_empty());
let submodule_config = workarea.submodule_config()
let submodule_config = workarea
.submodule_config()
.iter()
.map(|(name, config)| {
(name.as_str(),
config.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0)))
(
name.as_str(),
config
.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0)),
)
})
.sorted_by(|ref a, ref b| Ord::cmp(&a.0, &b.0));
assert_eq!(submodule_config,
&[
("custom-name",
vec![
("path", "submodule"),
("url", "https://gitlab.kitware.com/utils/test-repo.git"),
]),
]);
assert_eq!(
submodule_config,
&[(
"custom-name",
vec![
("path", "submodule"),
("url", "https://gitlab.kitware.com/utils/test-repo.git"),
]
),],
);
}
#[test]
......@@ -476,7 +500,8 @@ fn test_setup_merge() {
if let MergeResult::Ready(command) = merge {
let commit = command.commit("commit message").unwrap();
let rev_parse = ctx.git()
let rev_parse = ctx
.git()
.arg("rev-parse")
.arg("--verify")
.arg(format!("{}^{{tree}}", commit))
......@@ -484,18 +509,21 @@ fn test_setup_merge() {
.unwrap();
assert!(rev_parse.status.success());
let merged_tree = String::from_utf8_lossy(&rev_parse.stdout);
assert_eq!(merged_tree.trim(), "254e4e42cb914f935679319389e2af07eebb2157");
assert_eq!(
merged_tree.trim(),
"254e4e42cb914f935679319389e2af07eebb2157",
);
} else {
panic!("expected the merge from {} into {} to be fine: {:?}",
topic,
base,
merge);
panic!(
"expected the merge from {} into {} to be fine: {:?}",
topic, base, merge,
);
}
} else {
panic!("topic {} should be mergeable into {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should be mergeable into {}: {:?}",
topic, base, status,
);
}
}
......@@ -515,7 +543,8 @@ fn test_setup_merge_ours() {
if let MergeResult::Ready(command) = merge {
let commit = command.commit("commit message").unwrap();
let rev_parse = ctx.git()
let rev_parse = ctx
.git()
.arg("rev-parse")
.arg("--verify")
.arg(format!("{}^{{tree}}", commit))
......@@ -523,12 +552,15 @@ fn test_setup_merge_ours() {
.unwrap();
assert!(rev_parse.status.success());
let merged_tree = String::from_utf8_lossy(&rev_parse.stdout);
assert_eq!(merged_tree.trim(), "d6e9a7ef309d55ab0bc68e978e34bea528d7bb94");
assert_eq!(
merged_tree.trim(),
"d6e9a7ef309d55ab0bc68e978e34bea528d7bb94",
);
} else {
panic!("expected the merge from {} into {} to be fine: {:?}",
topic,
base,
merge);
panic!(
"expected the merge from {} into {} to be fine: {:?}",
topic, base, merge,
);
}
}
......@@ -551,16 +583,16 @@ fn test_setup_merge_rewind() {
if let MergeResult::Ready(_) = merge {
// OK
} else {
panic!("expected the merge from {} into {} to be fine: {:?}",
topic,
base,
merge);
panic!(
"expected the merge from {} into {} to be fine: {:?}",
topic, base, merge,
);
}
} else {
panic!("topic {} should be mergeable into {}: {:?}",
topic,
base,
status);
panic!(
"topic {} should be mergeable into {}: {:?}",
topic, base, status,
);