Clone Github Repo to Directory named after Repo using Rust

Viewed 102

I have a simple Rust app that tries to clone a git repo. How can the cloned repo be named after the repo?

For example, if we are trying to clone the repo at https://github.com/ytdl-org/youtube-dl.git, it should be cloned to the directory ./cloned_repos/youtube-dl.

extern crate git2;
use git2::Repository;

fn clone_repo(url: &str) {
    println!("Cloning repo: {}", url);
    match Repository::clone(url, format!("./cloned_repos/{}", "repo_name")) {
        Ok(repo) => repo,
        Err(e) => panic!("failed to clone: {}", e),
    };
}

fn main() {
    let url = "https://github.com/ytdl-org/youtube-dl";
    clone_repo(&url);
}
1 Answers

You could do:

extern crate git2;
use git2::Repository;

fn clone_repo(url: &str) {
    println!("Cloning repo: {}", url);
    let git_name = url.split("/").collect::<Vec<&str>>().pop().unwrap();
    let repo_name = git_name.replace(".git", "");
    match Repository::clone(url, format!("./cloned_repos/{}", repo_name)) {
        Ok(repo) => repo,
        Err(e) => panic!("failed to clone: {}", e),
    };
}

fn main() {
    let url = "https://github.com/ytdl-org/youtube-dl";
    clone_repo(&url);
}
Related