1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use git2::Repository;
use std::path::Path;
use errors::Result;

pub fn branch(path: &Path) -> Result<String> {
    let repo = discover_repo(path)?;
    let head = repo.head()?;
    head.shorthand()
        .map(|string| string.into())
        .ok_or("Failed to find name from git remote".into())
}

pub fn trekker_name(path: &Path) -> Result<String> {
    let origin_remote_url = origin_remote_url(path)?;
    origin_remote_url.split('/')
        .last()
        .map(|last_piece| last_piece.split('.'))
        .and_then(|last_piece_split| last_piece_split.rev().last())
        .map(|name| name.into())
        .ok_or("Failed to find name from git remote".into())
}

pub fn origin_remote_url(path: &Path) -> Result<String> {
    let repo = discover_repo(path)?;
    let origin = repo.find_remote("origin")?;

    origin.url()
        .map(|url| url.into())
        .ok_or("No git remote origin found".into())
}

fn discover_repo(path: &Path) -> Result<Repository> {
    Repository::discover(path).map_err(|error| error.into())
}