History

feat!: improve `head()` peeling API

Previously it was partially untested and it was hard to obtain an object of choice. Further breaking changes: * rename `Head::peeled()` to `into_peeled_id()` * rename `Head::into_fully_peeled_id()` to `try_peel_into_id()` * rename `Head::peel_to_id_in_place()` to `Head::try_peel_to_id_in_place()`

Sebastian Thiel committed 3 years ago

Commit 4e6a4e61 parent 266c9fc10 files · +140 −81Browse files

Unified · Split

10 files
  1. gix/examples/stats.rs +2 −2
  2. gix/src/clone/checkout.rs +1 −1
  3. gix/src/head/peel.rs +71 −60
  4. gix/src/reference/errors.rs +1 −3
  5. gix/src/repository/reference.rs +7 −9
  6. gix/tests/fixtures/generated-archives/make_head_repos.tar.xz +3 −0
  7. gix/tests/fixtures/make_head_repos.sh +30 −0
  8. gix/tests/head/mod.rs +20 −1
  9. gix/tests/id/mod.rs +3 −3
  10. gix/tests/repository/object.rs +2 −2
gix/examples/stats.rs+2−2
@@ -11,8 +11,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { · 10 unmodified lines
11 let mut most_recent_commit_id = None;11 let mut most_recent_commit_id = None;
12 let num_commits = repo12 let num_commits = repo
13 .head()?13 .head()?
14 .into_fully_peeled_id()14 .try_into_peeled_id()?
15 .ok_or("Cannot provide meaningful stats on empty repos")??15 .ok_or("Cannot provide meaningful stats on empty repos")?
16 .ancestors()16 .ancestors()
17 .all()?17 .all()?
18 .map_while(Result::ok)18 .map_while(Result::ok)
gix/src/clone/checkout.rs+1−1
@@ -87,7 +87,7 @@ pub mod main_worktree { · 86 unmodified lines
87 let workdir = repo.work_dir().ok_or_else(|| Error::BareRepository {87 let workdir = repo.work_dir().ok_or_else(|| Error::BareRepository {
88 git_dir: repo.git_dir().to_owned(),88 git_dir: repo.git_dir().to_owned(),
89 })?;89 })?;
90 let root_tree = match repo.head()?.peel_to_id_in_place().transpose()? {90 let root_tree = match repo.head()?.try_peel_to_id_in_place()? {
91 Some(id) => id.object().expect("downloaded from remote").peel_to_tree()?.id,91 Some(id) => id.object().expect("downloaded from remote").peel_to_tree()?.id,
92 None => {92 None => {
93 return Ok((93 return Ok((
gix/src/head/peel.rs+71−60
@@ -1,12 +1,14 @@
1use crate::{1use crate::{
2 ext::{ObjectIdExt, ReferenceExt},2 ext::{ObjectIdExt, ReferenceExt},
3 head::Kind,
3 Head,4 Head,
4};5};
5 6
6mod error {7mod error {
7 use crate::{object, reference};8 use crate::{object, reference};
8 9
9 /// The error returned by [`Head::peel_to_id_in_place()`][super::Head::peel_to_id_in_place()] and [`Head::into_fully_peeled_id()`][super::Head::into_fully_peeled_id()].10 /// The error returned by [`Head::peel_to_id_in_place()`](super::Head::try_peel_to_id_in_place())
11 /// and [`Head::into_fully_peeled_id()`](super::Head::try_into_peeled_id()).
10 #[derive(Debug, thiserror::Error)]12 #[derive(Debug, thiserror::Error)]
11 #[allow(missing_docs)]13 #[allow(missing_docs)]
12 pub enum Error {14 pub enum Error {
@@ -19,7 +21,22 @@ mod error { · 6 unmodified lines
19 21
20pub use error::Error;22pub use error::Error;
21 23
22use crate::head::Kind;24///
25pub mod into_id {
26 use crate::object;
27
28 /// The error returned by [`Head::into_peeled_id()`](super::Head::into_peeled_id()).
29 #[derive(Debug, thiserror::Error)]
30 #[allow(missing_docs)]
31 pub enum Error {
32 #[error(transparent)]
33 Peel(#[from] super::Error),
34 #[error("Branch '{name}' does not have any commits")]
35 Unborn { name: gix_ref::FullName },
36 #[error(transparent)]
37 ObjectKind(#[from] object::try_into::Error),
38 }
39}
23 40
24///41///
25pub mod to_commit {42pub mod to_commit {
@@ -39,85 +56,79 @@ pub mod to_commit { · 13 unmodified lines
39}56}
40 57
41impl<'repo> Head<'repo> {58impl<'repo> Head<'repo> {
42 // TODO: tests59 /// Peel this instance and consume to make obtaining its final target id possible, while returning an error on unborn heads.
43 /// Peel this instance to make obtaining its final target id possible, while returning an error on unborn heads.60 ///
44 pub fn peeled(mut self) -> Result<Self, Error> {61 /// The final target is obtained by following symbolic references and peeling tags to their final destination, which
45 self.peel_to_id_in_place().transpose()?;62 /// typically is a commit, but can be any object.
46 Ok(self)63 pub fn into_peeled_id(mut self) -> Result<crate::Id<'repo>, into_id::Error> {
64 self.try_peel_to_id_in_place()?;
65 self.id().ok_or_else(|| match self.kind {
66 Kind::Symbolic(gix_ref::Reference { name, .. }) | Kind::Unborn(name) => into_id::Error::Unborn { name },
67 Kind::Detached { .. } => unreachable!("id can be returned after peeling"),
68 })
69 }
70
71 /// Consume this instance and transform it into the final object that it points to, or `Ok(None)` if the `HEAD`
72 /// reference is yet to be born.
73 ///
74 /// The final target is obtained by following symbolic references and peeling tags to their final destination, which
75 /// typically is a commit, but can be any object.
76 pub fn try_into_peeled_id(mut self) -> Result<Option<crate::Id<'repo>>, Error> {
77 self.try_peel_to_id_in_place()
47 }78 }
48 79
49 // TODO: tests
50 // TODO: Fix this! It's not consistently peeling tags. The whole peeling business should be reconsidered to do what people usually
51 // want which is to peel references, if present, and then peel objects with control over which object type to end at.
52 // Finding a good interface for that isn't easy as ideally, it's an iterator that shows the intermediate objects so the user
53 // can select which tag of a chain to choose.
54 /// Follow the symbolic reference of this head until its target object and peel it by following tag objects until there is no80 /// Follow the symbolic reference of this head until its target object and peel it by following tag objects until there is no
55 /// more object to follow, and return that object id.81 /// more object to follow, and return that object id.
56 ///82 ///
57 /// Returns `None` if the head is unborn.83 /// Returns `Ok(None)` if the head is unborn.
58 pub fn peel_to_id_in_place(&mut self) -> Option<Result<crate::Id<'repo>, Error>> {84 ///
59 Some(match &mut self.kind {85 /// The final target is obtained by following symbolic references and peeling tags to their final destination, which
60 Kind::Unborn(_name) => return None,86 /// typically is a commit, but can be any object.
87 pub fn try_peel_to_id_in_place(&mut self) -> Result<Option<crate::Id<'repo>>, Error> {
88 Ok(Some(match &mut self.kind {
89 Kind::Unborn(_name) => return Ok(None),
61 Kind::Detached {90 Kind::Detached {
62 peeled: Some(peeled), ..91 peeled: Some(peeled), ..
63 } => Ok((*peeled).attach(self.repo)),92 } => (*peeled).attach(self.repo),
64 Kind::Detached { peeled: None, target } => {93 Kind::Detached { peeled: None, target } => {
65 match target94 let id = target.attach(self.repo);
66 .attach(self.repo)95 if id.header()?.kind() == gix_object::Kind::Commit {
67 .object()96 id
68 .map_err(Into::into)97 } else {
69 .and_then(|obj| obj.peel_tags_to_end().map_err(Into::into))98 match id.object()?.peel_tags_to_end() {
70 .map(|peeled| peeled.id)99 Ok(obj) => {
71 {100 self.kind = Kind::Detached {
72 Ok(peeled) => {101 peeled: Some(obj.id),
73 self.kind = Kind::Detached {102 target: *target,
74 peeled: Some(peeled),103 };
75 target: *target,104 obj.id()
76 };105 }
77 Ok(peeled.attach(self.repo))106 Err(err) => return Err(err.into()),
78 }107 }
79 Err(err) => Err(err),
80 }108 }
81 }109 }
82 Kind::Symbolic(r) => {110 Kind::Symbolic(r) => {
83 let mut nr = r.clone().attach(self.repo);111 let mut nr = r.clone().attach(self.repo);
84 let peeled = nr.peel_to_id_in_place().map_err(Into::into);112 let peeled = nr.peel_to_id_in_place();
85 *r = nr.detach();113 *r = nr.detach();
86 peeled114 peeled?
87 }115 }
88 })116 }))
89 }117 }
90 118
91 // TODO: tests
92 // TODO: something similar in `crate::Reference`
93 /// Follow the symbolic reference of this head until its target object and peel it by following tag objects until there is no119 /// Follow the symbolic reference of this head until its target object and peel it by following tag objects until there is no
94 /// more object to follow, transform the id into a commit if possible and return that.120 /// more object to follow, transform the id into a commit if possible and return that.
95 ///121 ///
96 /// Returns an error if the head is unborn or if it doesn't point to a commit.122 /// Returns an error if the head is unborn or if it doesn't point to a commit.
97 pub fn peel_to_commit_in_place(&mut self) -> Result<crate::Commit<'repo>, to_commit::Error> {123 pub fn peel_to_commit_in_place(&mut self) -> Result<crate::Commit<'repo>, to_commit::Error> {
98 let id = self.peel_to_id_in_place().ok_or_else(|| to_commit::Error::Unborn {124 let id = self
99 name: self.referent_name().expect("unborn").to_owned(),125 .try_peel_to_id_in_place()?
100 })??;126 .ok_or_else(|| to_commit::Error::Unborn {
101 id.object()127 name: self.referent_name().expect("unborn").to_owned(),
102 .map_err(|err| to_commit::Error::Peel(Error::FindExistingObject(err)))128 })?;
103 .and_then(|object| object.try_into_commit().map_err(Into::into))129 Ok(id
104 }130 .object()
105 131 .map_err(|err| to_commit::Error::Peel(Error::FindExistingObject(err)))?
106 /// Consume this instance and transform it into the final object that it points to, or `None` if the `HEAD`132 .try_into_commit()?)
107 /// reference is yet to be born.
108 pub fn into_fully_peeled_id(self) -> Option<Result<crate::Id<'repo>, Error>> {
109 Some(match self.kind {
110 Kind::Unborn(_name) => return None,
111 Kind::Detached {
112 peeled: Some(peeled), ..
113 } => Ok(peeled.attach(self.repo)),
114 Kind::Detached { peeled: None, target } => target
115 .attach(self.repo)
116 .object()
117 .map_err(Into::into)
118 .and_then(|obj| obj.peel_tags_to_end().map_err(Into::into))
119 .map(|obj| obj.id.attach(self.repo)),
120 Kind::Symbolic(r) => r.attach(self.repo).peel_to_id_in_place().map_err(Into::into),
121 })
122 }133 }
123}134}
gix/src/reference/errors.rs+1−3
@@ -43,9 +43,7 @@ pub mod head_id { · 42 unmodified lines
43 #[error(transparent)]43 #[error(transparent)]
44 Head(#[from] crate::reference::find::existing::Error),44 Head(#[from] crate::reference::find::existing::Error),
45 #[error(transparent)]45 #[error(transparent)]
46 PeelToId(#[from] crate::head::peel::Error),46 PeelToId(#[from] crate::head::peel::into_id::Error),
47 #[error("Branch '{name}' does not have any commits")]
48 Unborn { name: gix_ref::FullName },
49 }47 }
50}48}
51 49
gix/src/repository/reference.rs+7−9
@@ -174,7 +174,8 @@ impl crate::Repository { · 173 unmodified lines
174 .attach(self))174 .attach(self))
175 }175 }
176 176
177 /// Resolve the `HEAD` reference, follow and peel its target and obtain its object id.177 /// Resolve the `HEAD` reference, follow and peel its target and obtain its object id,
178 /// following symbolic references and tags until a commit is found.
178 ///179 ///
179 /// Note that this may fail for various reasons, most notably because the repository180 /// Note that this may fail for various reasons, most notably because the repository
180 /// is freshly initialized and doesn't have any commits yet.181 /// is freshly initialized and doesn't have any commits yet.
@@ -182,12 +183,7 @@ impl crate::Repository { · 1 unmodified line
182 /// Also note that the returned id is likely to point to a commit, but could also183 /// Also note that the returned id is likely to point to a commit, but could also
183 /// point to a tree or blob. It won't, however, point to a tag as these are always peeled.184 /// point to a tree or blob. It won't, however, point to a tag as these are always peeled.
184 pub fn head_id(&self) -> Result<crate::Id<'_>, reference::head_id::Error> {185 pub fn head_id(&self) -> Result<crate::Id<'_>, reference::head_id::Error> {
185 let mut head = self.head()?;186 Ok(self.head()?.into_peeled_id()?)
186 head.peel_to_id_in_place()
187 .ok_or_else(|| reference::head_id::Error::Unborn {
188 name: head.referent_name().expect("unborn").to_owned(),
189 })?
190 .map_err(Into::into)
191 }187 }
192 188
193 /// Return the name to the symbolic reference `HEAD` points to, or `None` if the head is detached.189 /// Return the name to the symbolic reference `HEAD` points to, or `None` if the head is detached.
@@ -203,7 +199,8 @@ impl crate::Repository { · 9 unmodified lines
203 Ok(self.head()?.try_into_referent())199 Ok(self.head()?.try_into_referent())
204 }200 }
205 201
206 /// Return the commit object the `HEAD` reference currently points to after peeling it fully.202 /// Return the commit object the `HEAD` reference currently points to after peeling it fully,
203 /// following symbolic references and tags until a commit is found.
207 ///204 ///
208 /// Note that this may fail for various reasons, most notably because the repository205 /// Note that this may fail for various reasons, most notably because the repository
209 /// is freshly initialized and doesn't have any commits yet. It could also fail if the206 /// is freshly initialized and doesn't have any commits yet. It could also fail if the
@@ -212,7 +209,8 @@ impl crate::Repository { · 2 unmodified lines
212 Ok(self.head()?.peel_to_commit_in_place()?)209 Ok(self.head()?.peel_to_commit_in_place()?)
213 }210 }
214 211
215 /// Return the tree id the `HEAD` reference currently points to after peeling it fully.212 /// Return the tree id the `HEAD` reference currently points to after peeling it fully,
213 /// following symbolic references and tags until a commit is found.
216 ///214 ///
217 /// Note that this may fail for various reasons, most notably because the repository215 /// Note that this may fail for various reasons, most notably because the repository
218 /// is freshly initialized and doesn't have any commits yet. It could also fail if the216 /// is freshly initialized and doesn't have any commits yet. It could also fail if the
gix/tests/fixtures/generated-archives/make_head_repos.tar.xz+3−0
@@ -0,0 +1,3 @@
1version https://git-lfs.github.com/spec/v1
2oid sha256:1de90b3e0c6547fda6759fb5df5e4bdf410dbe062ef9ef4f972308452c3224d7
3size 11508
gix/tests/fixtures/make_head_repos.sh+30−0
@@ -0,0 +1,30 @@
1#!/bin/bash
2set -eu -o pipefail
3
4(git init symbolic && cd symbolic
5 git commit -m "init" --allow-empty
6)
7
8git clone symbolic detached
9(cd detached
10 git remote rm origin
11 git checkout @
12)
13
14git clone symbolic tag-symbolic
15(cd tag-symbolic
16 git tag -a -m make-tag-object point-at-commit HEAD
17 git tag point-at-tag point-at-commit
18 git tag -a -m make-tag-object point-at-tag-start point-at-tag
19 git remote rm origin
20 echo "ref: refs/tags/point-at-tag-start" > .git/HEAD
21)
22
23git clone tag-symbolic tag-detached
24(cd tag-detached
25 git remote rm origin
26 git fetch --tags
27 git rev-parse point-at-tag-start > .git/HEAD.tmp
28 mv .git/HEAD.tmp .git/HEAD
29)
30
gix/tests/head/mod.rs+20−1
@@ -1,5 +1,24 @@
1mod into_remote {1mod peel {
2 use crate::util::{hex_to_id, named_subrepo_opts};
2 3
4 #[test]
5 fn all_cases() -> crate::Result {
6 let expected_commit = hex_to_id("fafd9d08a839d99db60b222cd58e2e0bfaf1f7b2");
7 for name in ["detached", "symbolic", "tag-detached", "tag-symbolic"] {
8 let repo = named_subrepo_opts("make_head_repos.sh", name, gix::open::Options::isolated())?;
9 assert_eq!(repo.head()?.into_peeled_id()?, expected_commit);
10 assert_eq!(repo.head_id()?, expected_commit);
11 let commit = repo.head_commit()?;
12 assert_eq!(commit.id, expected_commit);
13 assert_eq!(repo.head_tree_id()?, commit.tree_id()?);
14 assert_eq!(repo.head()?.try_into_peeled_id()?.expect("born"), expected_commit);
15 assert_eq!(repo.head()?.try_peel_to_id_in_place()?.expect("born"), expected_commit);
16 }
17 Ok(())
18 }
19}
20
21mod into_remote {
3 use crate::remote;22 use crate::remote;
4 23
5 #[test]24 #[test]
gix/tests/id/mod.rs+3−3
@@ -75,7 +75,7 @@ mod ancestors { · 74 unmodified lines
75 fn all() -> crate::Result {75 fn all() -> crate::Result {
76 let repo = crate::repo("make_repo_with_fork_and_dates.sh")?.to_thread_local();76 let repo = crate::repo("make_repo_with_fork_and_dates.sh")?.to_thread_local();
77 for use_commit_graph in [false, true] {77 for use_commit_graph in [false, true] {
78 let head = repo.head()?.into_fully_peeled_id().expect("born")?;78 let head = repo.head()?.into_peeled_id()?;
79 let commits_graph_order = head79 let commits_graph_order = head
80 .ancestors()80 .ancestors()
81 .use_commit_graph(use_commit_graph)81 .use_commit_graph(use_commit_graph)
@@ -118,7 +118,7 @@ mod ancestors { · 36 unmodified lines
118 fn pre_epoch() -> crate::Result {118 fn pre_epoch() -> crate::Result {
119 let repo = crate::repo("make_pre_epoch_repo.sh")?.to_thread_local();119 let repo = crate::repo("make_pre_epoch_repo.sh")?.to_thread_local();
120 for use_commit_graph in [false, true] {120 for use_commit_graph in [false, true] {
121 let head = repo.head()?.into_fully_peeled_id().expect("born")?;121 let head = repo.head()?.into_peeled_id()?;
122 let commits = head122 let commits = head
123 .ancestors()123 .ancestors()
124 .sorting(commit::Sorting::ByCommitTimeNewestFirst) // assure we have time set124 .sorting(commit::Sorting::ByCommitTimeNewestFirst) // assure we have time set
@@ -137,7 +137,7 @@ mod ancestors { · 12 unmodified lines
137 #[test]137 #[test]
138 fn filtered() -> crate::Result {138 fn filtered() -> crate::Result {
139 let repo = crate::repo("make_repo_with_fork_and_dates.sh")?.to_thread_local();139 let repo = crate::repo("make_repo_with_fork_and_dates.sh")?.to_thread_local();
140 let head = repo.head()?.into_fully_peeled_id().expect("born")?;140 let head = repo.head()?.into_peeled_id()?;
141 141
142 for use_commit_graph in [false, true] {142 for use_commit_graph in [false, true] {
143 for sorting in [143 for sorting in [
gix/tests/repository/object.rs+2−2
@@ -128,7 +128,7 @@ mod find { · 127 unmodified lines
128 2 => repo.object_cache_size(128 * 1024),128 2 => repo.object_cache_size(128 * 1024),
129 _ => unreachable!("BUG"),129 _ => unreachable!("BUG"),
130 }130 }
131 for commit_id in repo.head()?.peeled()?.id().expect("born").ancestors().all()? {131 for commit_id in repo.head()?.into_peeled_id()?.ancestors().all()? {
132 let commit = commit_id?;132 let commit = commit_id?;
133 assert_eq!(commit.id().object()?.kind, gix_object::Kind::Commit);133 assert_eq!(commit.id().object()?.kind, gix_object::Kind::Commit);
134 assert_eq!(commit.id().header()?.kind(), gix_object::Kind::Commit);134 assert_eq!(commit.id().header()?.kind(), gix_object::Kind::Commit);
@@ -363,7 +363,7 @@ mod commit { · 228 unmodified lines
363 vec!["commit: hello there", "commit: c2", "commit (initial): c1"],363 vec!["commit: hello there", "commit: c2", "commit (initial): c1"],
364 "we get the actual HEAD log, not the log of some reference"364 "we get the actual HEAD log, not the log of some reference"
365 );365 );
366 let current_commit = repo.head()?.into_fully_peeled_id().expect("born")?;366 let current_commit = repo.head()?.into_peeled_id()?;
367 assert_eq!(current_commit, first_commit_id, "the commit was set");367 assert_eq!(current_commit, first_commit_id, "the commit was set");
368 368
369 let second_commit_id = repo.commit(369 let second_commit_id = repo.commit(

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t