3 ms·
Not a bad write-up. The Rust code snippets can be slimmed down very slightly though. Here's main(): fn main() { let args = os::args(); let
by eridius 12y ago
Not a bad write-up. The Rust code snippets can be slimmed down very slightly though. Here's main():
fn main() {
let args = os::args();
let washed_args = args.iter().map(|arg| arg.as_slice()).collect::<Vec<_>>();
match washed_args.as_slice() {
[_, "review", opts..] => review(opts),
_ => usage()
}
}
although I might actually suggest the alternative approach:
fn main() {
let mut args = os::args().into_iter();
args.next(); // skip program name
match args.next().map(|s| s.as_slice()) {
Some("review") => review(args.collect::<Vec<_>>()),
_ => usage()
}
}
(this approach requires `review()` to take a `Vec<String>` instead of a `&[&str]`, but that's not a difficult change, and we could fix it using a second line of code if we wanted but at the cost of introducing a new allocation, like the original code does)
For review() I'd suggest changing the original code:
let cwd = os::getcwd();
let have_dot_git = have_dot_git(cwd.clone());
let dot_git_dir: &Path = match have_dot_git.as_ref() {
Some(path) => path,
None => { panic!("{} does not appear to have a controlling .git directory; you are not in a git repository!", cwd.display()) },
};
to the following:
let cwd = os::getcwd();
let dot_git_dir = have_dot_git(&cwd).expect(format!("{} does not appear to have a controlling .git directory; you are not in a git repository!", cwd.display()).as_slice());
This actually leaves `dot_git_dir` as a `Path` instead of a `&Path`, but I think that's better anyway. It also requires `have_dot_git()` to take a `&Path` instead of (what I assume it takes now,) a `Path`, which is an appropriate change as there's no need for cloning the path.
- eridius 12y agoIt's also worth pointing out that if you enable the `slicing_syntax` feature gate then all the `.as_slice()` calls can turn into the suffix operator `[]`.
- dbaupp 12y agoYour expect version changes behaviour: it does the allocation and string formatting unconditionally even if `have_dot_git(&cwd)` is `Some`. It is probably not a problem for this since the other operations are significantly more expensive, but it can be a gotcha if used inside a loop.
- eridius 12y agoYou're right, that's what I get for doing this fast. In that case I'd say let dot_git_dir = have_dot_git(&cwd).unwrap_or_else(|| panic!("{} does not appear to have a controlling .git directory; you are not in a git repository!", cwd.display()));