Skip to content

Commit

Permalink
Allow using git reference for branch/tag/commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Coi-l committed Mar 26, 2024
1 parent 2e32b69 commit ba3fe43
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/cmd/shelf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub fn execute(_args: &ArgMatches) -> Result<()> {
let shelf: Shelf = toml::from_str(&contents)?;

let _ = std::fs::remove_dir_all("shelf");
let _ = std::fs::remove_dir_all("repositories");
let _ = MDBook::init("shelf").create_gitignore(false).build();

let index_file_name = "shelf/src/index.md";
Expand Down Expand Up @@ -86,14 +87,39 @@ pub fn execute(_args: &ArgMatches) -> Result<()> {
checkout_path.clone()
};

let _repo = match git2::Repository::open(&checkout_path) {
let repo = match git2::Repository::open(&checkout_path) {
Ok(repo) => repo,
Err(_) => match git2::Repository::clone(&url, &checkout_path) {
Ok(repo) => repo,
Err(e) => panic!("failed to clone: {}", e),
},
};

if let Some(refname) = &sb.git_ref {
// let refname = "master"; // or a tag (v0.1.1) or a commit (8e8128)
let (object, reference) =
if let Ok((object, reference)) = repo.revparse_ext(refname) {
(object, reference)
} else if let Ok((object, reference)) =
repo.revparse_ext(&format!("origin/{refname}"))
{
(object, reference)
} else {
panic!("Could not checkout {refname}");
};

repo.checkout_tree(&object, None)
.expect("Failed to checkout");

match reference {
// gref is an actual reference like branches or tags
Some(gref) => repo.set_head(gref.name().unwrap()),
// this is a commit, not a reference
None => repo.set_head_detached(object.id()),
}
.expect("Failed to set HEAD");
}

process_book(&book_path.to_str().unwrap(), &mut index_file, &mut summary)?
} else if let Some(path) = &sb.path {
process_book(path, &mut index_file, &mut summary)?
Expand Down
3 changes: 3 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,9 @@ pub struct ShelfBook {
pub path: Option<String>,
/// git url
pub git_url: Option<String>,
/// reference to checkout in git
/// This can be a branch, commit or tag
pub git_ref: Option<String>,
}

#[derive(Deserialize, Debug)]
Expand Down

0 comments on commit ba3fe43

Please sign in to comment.