History

Merge branch 'describe-rev'

Sebastian Thiel committed 4 years ago

Commit 77b7cd92 parents a87844a d24074027 files · +432 −65Browse files

Unified · Split

27 files
  1. Cargo.lock +9 −0
  2. Makefile +1 −0
  3. cargo-smart-release/src/utils.rs +2 −2
  4. git-actor/src/lib.rs +3 −3
  5. git-actor/src/signature/decode.rs +10 −2
  6. git-actor/src/signature/mod.rs +9 −9
  7. git-actor/src/time.rs +11 −11
  8. git-actor/tests/signature/mod.rs +2 −2
  9. git-actor/tests/time/mod.rs +6 −6
  10. git-object/src/commit/ref_iter.rs +4 −6
  11. git-object/tests/immutable/commit/from_bytes.rs +2 −2
  12. git-object/tests/immutable/commit/message.rs +2 −2
  13. git-object/tests/immutable/mod.rs +4 −4
  14. git-object/tests/immutable/tag.rs +2 −2
  15. git-odb/tests/odb/store/loose.rs +2 −2
  16. git-ref/src/store/file/log/line.rs +4 −4
  17. git-ref/src/store/file/loose/reflog/create_or_update/tests.rs +2 −2
  18. git-ref/tests/file/transaction/mod.rs +2 −2
  19. git-revision/Cargo.toml +13 −1
  20. git-revision/src/describe.rs +198 −0
  21. git-revision/src/lib.rs +3 −0
  22. git-revision/tests/describe/format.rs +30 −0
  23. git-revision/tests/describe/mod.rs +74 −0
  24. git-revision/tests/fixtures/make_repo_with_branches.sh +23 −0
  25. git-revision/tests/revision.rs +1 −0
  26. git-traverse/src/commit.rs +3 −1
  27. gitoxide-core/src/hours.rs +10 −2
Cargo.lock+9−0
@@ -1397,6 +1397,15 @@ dependencies = [ · 1396 unmodified lines
1397[[package]]1397[[package]]
1398name = "git-revision"1398name = "git-revision"
1399version = "0.0.0"1399version = "0.0.0"
1400dependencies = [
1401 "git-hash",
1402 "git-object",
1403 "git-repository",
1404 "git-testtools",
1405 "hash_hasher",
1406 "quick-error",
1407 "serde",
1408]
1400 1409
1401[[package]]1410[[package]]
1402name = "git-submodule"1411name = "git-submodule"
Makefile+1−0
@@ -89,6 +89,7 @@ check: ## Build all code in suitable configurations · 88 unmodified lines
89 cd git-object && cargo check --all-features \89 cd git-object && cargo check --all-features \
90 && cargo check --features verbose-object-parsing-errors90 && cargo check --features verbose-object-parsing-errors
91 cd git-index && cargo check --features serde191 cd git-index && cargo check --features serde1
92 cd git-revision && cargo check --features serde1
92 cd git-worktree && cargo check --features serde193 cd git-worktree && cargo check --features serde1
93 cd git-actor && cargo check --features serde194 cd git-actor && cargo check --features serde1
94 cd git-pack && cargo check --features serde1 \95 cd git-pack && cargo check --features serde1 \
cargo-smart-release/src/utils.rs+2−2
@@ -300,7 +300,7 @@ mod tests { · 299 unmodified lines
300}300}
301 301
302pub fn time_to_offset_date_time(time: git::actor::Time) -> OffsetDateTime {302pub fn time_to_offset_date_time(time: git::actor::Time) -> OffsetDateTime {
303 time::OffsetDateTime::from_unix_timestamp(time.time as i64)303 time::OffsetDateTime::from_unix_timestamp(time.seconds_since_unix_epoch as i64)
304 .expect("always valid unix time")304 .expect("always valid unix time")
305 .replace_offset(time::UtcOffset::from_whole_seconds(time.offset).expect("valid offset"))305 .replace_offset(time::UtcOffset::from_whole_seconds(time.offset_in_seconds).expect("valid offset"))
306}306}
git-actor/src/lib.rs+3−3
@@ -56,10 +56,10 @@ pub enum Sign { · 55 unmodified lines
56#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]56#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
57#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]57#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
58pub struct Time {58pub struct Time {
59 /// time in seconds from epoch.59 /// time in seconds since epoch.
60 pub time: u32,60 pub seconds_since_unix_epoch: u32,
61 /// time offset in seconds, may be negative to match the `sign` field.61 /// time offset in seconds, may be negative to match the `sign` field.
62 pub offset: i32,62 pub offset_in_seconds: i32,
63 /// the sign of `offset`, used to encode `-0000` which would otherwise loose sign information.63 /// the sign of `offset`, used to encode `-0000` which would otherwise loose sign information.
64 pub sign: Sign,64 pub sign: Sign,
65}65}
git-actor/src/signature/decode.rs+10−2
@@ -56,7 +56,11 @@ pub fn decode<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>( · 55 unmodified lines
56 SignatureRef {56 SignatureRef {
57 name: name.as_bstr(),57 name: name.as_bstr(),
58 email: email.as_bstr(),58 email: email.as_bstr(),
59 time: Time { time, offset, sign },59 time: Time {
60 seconds_since_unix_epoch: time,
61 offset_in_seconds: offset,
62 sign,
63 },
60 },64 },
61 ))65 ))
62}66}
@@ -84,7 +88,11 @@ mod tests { · 21 unmodified lines
84 SignatureRef {88 SignatureRef {
85 name: name.as_bytes().as_bstr(),89 name: name.as_bytes().as_bstr(),
86 email: email.as_bytes().as_bstr(),90 email: email.as_bytes().as_bstr(),
87 time: Time { time, offset, sign },91 time: Time {
92 seconds_since_unix_epoch: time,
93 offset_in_seconds: offset,
94 sign,
95 },
88 }96 }
89 }97 }
90 98
git-actor/src/signature/mod.rs+9−9
@@ -37,8 +37,8 @@ mod convert { · 36 unmodified lines
37 name: Default::default(),37 name: Default::default(),
38 email: Default::default(),38 email: Default::default(),
39 time: Time {39 time: Time {
40 time: 0,40 seconds_since_unix_epoch: 0,
41 offset: 0,41 offset_in_seconds: 0,
42 sign: Sign::Plus,42 sign: Sign::Plus,
43 },43 },
44 }44 }
@@ -145,11 +145,11 @@ mod init { · 100 unmodified lines
145 name: name.into(),145 name: name.into(),
146 email: email.into(),146 email: email.into(),
147 time: Time {147 time: Time {
148 time: std::time::SystemTime::now()148 seconds_since_unix_epoch: std::time::SystemTime::now()
149 .duration_since(std::time::UNIX_EPOCH)149 .duration_since(std::time::UNIX_EPOCH)
150 .expect("the system time doesn't run backwards that much")150 .expect("the system time doesn't run backwards that much")
151 .as_secs() as u32,151 .as_secs() as u32,
152 offset,152 offset_in_seconds: offset,
153 sign: offset.into(),153 sign: offset.into(),
154 },154 },
155 })155 })
@@ -164,11 +164,11 @@ mod init { · 8 unmodified lines
164 name: name.into(),164 name: name.into(),
165 email: email.into(),165 email: email.into(),
166 time: Time {166 time: Time {
167 time: std::time::SystemTime::now()167 seconds_since_unix_epoch: std::time::SystemTime::now()
168 .duration_since(std::time::UNIX_EPOCH)168 .duration_since(std::time::UNIX_EPOCH)
169 .expect("the system time doesn't run backwards that much")169 .expect("the system time doesn't run backwards that much")
170 .as_secs() as u32,170 .as_secs() as u32,
171 offset,171 offset_in_seconds: offset,
172 sign: offset.into(),172 sign: offset.into(),
173 },173 },
174 }174 }
@@ -183,15 +183,15 @@ mod init { · 8 unmodified lines
183 name: name.into(),183 name: name.into(),
184 email: email.into(),184 email: email.into(),
185 time: Time {185 time: Time {
186 time: seconds_since_epoch(),186 seconds_since_unix_epoch: seconds_since_unix_epoch(),
187 offset: utc_offset,187 offset_in_seconds: utc_offset,
188 sign: utc_offset.into(),188 sign: utc_offset.into(),
189 },189 },
190 }190 }
191 }191 }
192 }192 }
193 193
194 fn seconds_since_epoch() -> u32 {194 fn seconds_since_unix_epoch() -> u32 {
195 std::time::SystemTime::now()195 std::time::SystemTime::now()
196 .duration_since(std::time::UNIX_EPOCH)196 .duration_since(std::time::UNIX_EPOCH)
197 .expect("the system time doesn't run backwards that much")197 .expect("the system time doesn't run backwards that much")
git-actor/src/time.rs+11−11
@@ -16,7 +16,7 @@ impl Time { · 15 unmodified lines
16 /// Serialize this instance to `out` in a format suitable for use in header fields of serialized git commits or tags.16 /// Serialize this instance to `out` in a format suitable for use in header fields of serialized git commits or tags.
17 pub fn write_to(&self, mut out: impl io::Write) -> io::Result<()> {17 pub fn write_to(&self, mut out: impl io::Write) -> io::Result<()> {
18 let mut itoa = itoa::Buffer::new();18 let mut itoa = itoa::Buffer::new();
19 out.write_all(itoa.format(self.time).as_bytes())?;19 out.write_all(itoa.format(self.seconds_since_unix_epoch).as_bytes())?;
20 out.write_all(SPACE)?;20 out.write_all(SPACE)?;
21 out.write_all(match self.sign {21 out.write_all(match self.sign {
22 Sign::Plus => b"+",22 Sign::Plus => b"+",
@@ -26,7 +26,7 @@ impl Time { · 3 unmodified lines
26 const ZERO: &[u8; 1] = b"0";26 const ZERO: &[u8; 1] = b"0";
27 27
28 const SECONDS_PER_HOUR: i32 = 60 * 60;28 const SECONDS_PER_HOUR: i32 = 60 * 60;
29 let offset = self.offset.abs();29 let offset = self.offset_in_seconds.abs();
30 let hours = offset / SECONDS_PER_HOUR;30 let hours = offset / SECONDS_PER_HOUR;
31 assert!(hours < 25, "offset is more than a day: {}", hours);31 assert!(hours < 25, "offset is more than a day: {}", hours);
32 let minutes = (offset - (hours * SECONDS_PER_HOUR)) / 60;32 let minutes = (offset - (hours * SECONDS_PER_HOUR)) / 60;
@@ -45,23 +45,23 @@ impl Time { · 12 unmodified lines
45 pub fn size(&self) -> usize {45 pub fn size(&self) -> usize {
46 // TODO: this is not year 2038 safe…but we also can't parse larger numbers (or represent them) anyway. It's a trap nonetheless46 // TODO: this is not year 2038 safe…but we also can't parse larger numbers (or represent them) anyway. It's a trap nonetheless
47 // that can be fixed by increasing the size to usize.47 // that can be fixed by increasing the size to usize.
48 (if self.time >= 1_000_000_000 {48 (if self.seconds_since_unix_epoch >= 1_000_000_000 {
49 1049 10
50 } else if self.time >= 100_000_000 {50 } else if self.seconds_since_unix_epoch >= 100_000_000 {
51 951 9
52 } else if self.time >= 10_000_000 {52 } else if self.seconds_since_unix_epoch >= 10_000_000 {
53 853 8
54 } else if self.time >= 1_000_000 {54 } else if self.seconds_since_unix_epoch >= 1_000_000 {
55 755 7
56 } else if self.time >= 100_000 {56 } else if self.seconds_since_unix_epoch >= 100_000 {
57 657 6
58 } else if self.time >= 10_000 {58 } else if self.seconds_since_unix_epoch >= 10_000 {
59 559 5
60 } else if self.time >= 1_000 {60 } else if self.seconds_since_unix_epoch >= 1_000 {
61 461 4
62 } else if self.time >= 100 {62 } else if self.seconds_since_unix_epoch >= 100 {
63 363 3
64 } else if self.time >= 10 {64 } else if self.seconds_since_unix_epoch >= 10 {
65 265 2
66 } else {66 } else {
67 167 1
git-actor/tests/signature/mod.rs+2−2
@@ -43,8 +43,8 @@ mod write_to { · 42 unmodified lines
43 43
44 fn default_time() -> Time {44 fn default_time() -> Time {
45 Time {45 Time {
46 time: 0,46 seconds_since_unix_epoch: 0,
47 offset: 0,47 offset_in_seconds: 0,
48 sign: Sign::Plus,48 sign: Sign::Plus,
49 }49 }
50 }50 }
git-actor/tests/time/mod.rs+6−6
@@ -6,24 +6,24 @@ fn write_to() -> Result<(), Box<dyn std::error::Error>> { · 5 unmodified lines
6 for (time, expected) in &[6 for (time, expected) in &[
7 (7 (
8 Time {8 Time {
9 time: 500,9 seconds_since_unix_epoch: 500,
10 offset: 9000,10 offset_in_seconds: 9000,
11 sign: Sign::Plus,11 sign: Sign::Plus,
12 },12 },
13 "500 +0230",13 "500 +0230",
14 ),14 ),
15 (15 (
16 Time {16 Time {
17 time: 189009009,17 seconds_since_unix_epoch: 189009009,
18 offset: 36000,18 offset_in_seconds: 36000,
19 sign: Sign::Minus,19 sign: Sign::Minus,
20 },20 },
21 "189009009 -1000",21 "189009009 -1000",
22 ),22 ),
23 (23 (
24 Time {24 Time {
25 time: 0,25 seconds_since_unix_epoch: 0,
26 offset: 0,26 offset_in_seconds: 0,
27 sign: Sign::Minus,27 sign: Sign::Minus,
28 },28 },
29 "0 -0000",29 "0 -0000",
git-object/src/commit/ref_iter.rs+4−6
@@ -58,12 +58,10 @@ impl<'a> CommitRefIter<'a> { · 57 unmodified lines
58 /// if not exactly two signatures were iterable.58 /// if not exactly two signatures were iterable.
59 /// Errors are not the common case - if an error needs to be detectable, use this instance as iterator.59 /// Errors are not the common case - if an error needs to be detectable, use this instance as iterator.
60 pub fn signatures(&'a mut self) -> impl Iterator<Item = git_actor::SignatureRef<'_>> + 'a {60 pub fn signatures(&'a mut self) -> impl Iterator<Item = git_actor::SignatureRef<'_>> + 'a {
61 self.filter_map(Result::ok)61 self.filter_map(|t| match t {
62 .skip_while(|t| !matches!(t, Token::Author { .. } | Token::Committer { .. }))62 Ok(Token::Author { signature }) | Ok(Token::Committer { signature }) => Some(signature),
63 .filter_map(|t| match t {63 _ => None,
64 Token::Author { signature } | Token::Committer { signature } => Some(signature),64 })
65 _ => None,
66 })
67 }65 }
68 66
69 /// Returns the committer signature if there is no decoding error.67 /// Returns the committer signature if there is no decoding error.
git-object/tests/immutable/commit/from_bytes.rs+2−2
@@ -139,8 +139,8 @@ fn with_trailer() -> crate::Result { · 138 unmodified lines
139 name: "Kim Altintop".into(),139 name: "Kim Altintop".into(),
140 email: "kim@eagain.st".into(),140 email: "kim@eagain.st".into(),
141 time: Time {141 time: Time {
142 time: 1631514803,142 seconds_since_unix_epoch: 1631514803,
143 offset: 7200,143 offset_in_seconds: 7200,
144 sign: Sign::Plus,144 sign: Sign::Plus,
145 },145 },
146 };146 };
git-object/tests/immutable/commit/message.rs+2−2
@@ -236,8 +236,8 @@ mod summary { · 235 unmodified lines
236 name: "name".into(),236 name: "name".into(),
237 email: "email".into(),237 email: "email".into(),
238 time: Time {238 time: Time {
239 time: 0,239 seconds_since_unix_epoch: 0,
240 offset: 0,240 offset_in_seconds: 0,
241 sign: Sign::Plus,241 sign: Sign::Plus,
242 },242 },
243 };243 };
git-object/tests/immutable/mod.rs+4−4
@@ -29,8 +29,8 @@ fn signature(time: u32) -> git_actor::SignatureRef<'static> { · 28 unmodified lines
29 name: b"Sebastian Thiel".as_bstr(),29 name: b"Sebastian Thiel".as_bstr(),
30 email: b"sebastian.thiel@icloud.com".as_bstr(),30 email: b"sebastian.thiel@icloud.com".as_bstr(),
31 time: Time {31 time: Time {
32 time,32 seconds_since_unix_epoch: time,
33 offset: 28800,33 offset_in_seconds: 28800,
34 sign: Sign::Plus,34 sign: Sign::Plus,
35 },35 },
36 }36 }
@@ -42,8 +42,8 @@ fn linus_signature(time: u32) -> git_actor::SignatureRef<'static> { · 5 unmodified lines
42 name: b"Linus Torvalds".as_bstr(),42 name: b"Linus Torvalds".as_bstr(),
43 email: b"torvalds@linux-foundation.org".as_bstr(),43 email: b"torvalds@linux-foundation.org".as_bstr(),
44 time: Time {44 time: Time {
45 time,45 seconds_since_unix_epoch: time,
46 offset: -25200,46 offset_in_seconds: -25200,
47 sign: Sign::Minus,47 sign: Sign::Minus,
48 },48 },
49 }49 }
git-object/tests/immutable/tag.rs+2−2
@@ -234,8 +234,8 @@ cjHJZXWmV4CcRfmLsXzU8s2cR9A0DBvOxhPD1TlKC2JhBFXigjuL9U4Rbq9tdegB · 233 unmodified lines
234 name: b"Sebastian Thiel".as_bstr(),234 name: b"Sebastian Thiel".as_bstr(),
235 email: b"byronimo@gmail.com".as_bstr(),235 email: b"byronimo@gmail.com".as_bstr(),
236 time: git_actor::Time {236 time: git_actor::Time {
237 time: 1528473343,237 seconds_since_unix_epoch: 1528473343,
238 offset,238 offset_in_seconds: offset,
239 sign: git_actor::Sign::Plus,239 sign: git_actor::Sign::Plus,
240 },240 },
241 }),241 }),
git-odb/tests/odb/store/loose.rs+2−2
@@ -288,8 +288,8 @@ fn signature(time: u32) -> git_actor::SignatureRef<'static> { · 287 unmodified lines
288 name: b"Sebastian Thiel".as_bstr(),288 name: b"Sebastian Thiel".as_bstr(),
289 email: b"byronimo@gmail.com".as_bstr(),289 email: b"byronimo@gmail.com".as_bstr(),
290 time: Time {290 time: Time {
291 time,291 seconds_since_unix_epoch: time,
292 offset: 7200,292 offset_in_seconds: 7200,
293 sign: Sign::Plus,293 sign: Sign::Plus,
294 },294 },
295 }295 }
git-ref/src/store/file/log/line.rs+4−4
@@ -229,8 +229,8 @@ pub mod decode { · 228 unmodified lines
229 name: b"name".as_bstr(),229 name: b"name".as_bstr(),
230 email: b"foo@example.com".as_bstr(),230 email: b"foo@example.com".as_bstr(),
231 time: Time {231 time: Time {
232 time: 1234567890,232 seconds_since_unix_epoch: 1234567890,
233 offset: 0,233 offset_in_seconds: 0,
234 sign: Sign::Minus234 sign: Sign::Minus
235 }235 }
236 },236 },
@@ -255,8 +255,8 @@ pub mod decode { · 18 unmodified lines
255 name: b"Sebastian Thiel".as_bstr(),255 name: b"Sebastian Thiel".as_bstr(),
256 email: b"foo@example.com".as_bstr(),256 email: b"foo@example.com".as_bstr(),
257 time: Time {257 time: Time {
258 time: 1618030561,258 seconds_since_unix_epoch: 1618030561,
259 offset: 28800,259 offset_in_seconds: 28800,
260 sign: Sign::Plus,260 sign: Sign::Plus,
261 },261 },
262 },262 },
git-ref/src/store/file/loose/reflog/create_or_update/tests.rs+2−2
@@ -73,8 +73,8 @@ fn missing_reflog_creates_it_even_if_similarly_named_empty_dir_exists_and_append · 72 unmodified lines
73 name: "committer".into(),73 name: "committer".into(),
74 email: "commiter@example.com".into(),74 email: "commiter@example.com".into(),
75 time: Time {75 time: Time {
76 time: 1234,76 seconds_since_unix_epoch: 1234,
77 offset: 1800,77 offset_in_seconds: 1800,
78 sign: Sign::Plus,78 sign: Sign::Plus,
79 },79 },
80 };80 };
git-ref/tests/file/transaction/mod.rs+2−2
@@ -25,8 +25,8 @@ mod prepare_and_commit { · 24 unmodified lines
25 name: "committer".into(),25 name: "committer".into(),
26 email: "committer@example.com".into(),26 email: "committer@example.com".into(),
27 time: Time {27 time: Time {
28 time: 1234,28 seconds_since_unix_epoch: 1234,
29 offset: 1800,29 offset_in_seconds: 1800,
30 sign: Sign::Plus,30 sign: Sign::Plus,
31 },31 },
32 }32 }
git-revision/Cargo.toml+13−1
@@ -10,6 +10,18 @@ edition = "2018" · 9 unmodified lines
10[lib]10[lib]
11doctest = false11doctest = false
12 12
13# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html13[features]
14## Data structures implement `serde::Serialize` and `serde::Deserialize`.
15serde1 = [ "serde", "git-hash/serde1", "git-object/serde1" ]
14 16
17# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
15[dependencies]18[dependencies]
19git-hash = { version = "^0.9.1", path = "../git-hash" }
20git-object = { version = "^0.17.0", path = "../git-object" }
21hash_hasher = "2.0.3"
22quick-error = "2.0.0"
23serde = { version = "1.0.114", optional = true, default-features = false, features = ["derive"] }
24
25[dev-dependencies]
26git-testtools = { path = "../tests/tools" }
27git-repository = { version = "^0.15.0", path = "../git-repository", default-features = false, features = ["unstable"] }
git-revision/src/describe.rs+198−0
@@ -0,0 +1,198 @@
1use git_object::bstr::BStr;
2use std::borrow::Cow;
3use std::fmt::{Display, Formatter};
4
5#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)]
6#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
7pub struct Outcome<'a> {
8 pub name: Cow<'a, BStr>,
9 pub id: git_hash::ObjectId,
10 pub depth: u32,
11}
12
13impl<'a> Outcome<'a> {
14 pub fn into_format(self, hex_len: usize) -> Format<'a> {
15 Format {
16 name: self.name,
17 id: self.id,
18 hex_len,
19 depth: self.depth,
20 long: false,
21 dirty_suffix: None,
22 }
23 }
24}
25
26#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)]
27#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
28pub struct Format<'a> {
29 pub name: Cow<'a, BStr>,
30 pub id: git_hash::ObjectId,
31 pub hex_len: usize,
32 pub depth: u32,
33 pub long: bool,
34 pub dirty_suffix: Option<String>,
35}
36
37impl<'a> Format<'a> {
38 pub fn is_exact_match(&self) -> bool {
39 self.depth == 0
40 }
41 pub fn long(&mut self) -> &mut Self {
42 self.long = true;
43 self
44 }
45 pub fn short(&mut self) -> &mut Self {
46 self.long = false;
47 self
48 }
49}
50
51impl<'a> Display for Format<'a> {
52 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53 if !self.long && self.is_exact_match() {
54 self.name.fmt(f)?;
55 } else {
56 write!(
57 f,
58 "{}-{}-g{}",
59 self.name,
60 self.depth,
61 self.id.to_hex_with_len(self.hex_len)
62 )?;
63 }
64 if let Some(suffix) = &self.dirty_suffix {
65 write!(f, "-{}", suffix)?;
66 }
67 Ok(())
68 }
69}
70
71pub(crate) mod function {
72 use super::Outcome;
73 use git_hash::{oid, ObjectId};
74 use git_object::bstr::BStr;
75 use git_object::CommitRefIter;
76 use std::borrow::Cow;
77 use std::collections::{hash_map, HashMap, VecDeque};
78 use std::iter::FromIterator;
79
80 #[allow(clippy::result_unit_err)]
81 pub fn describe<'a, Find, E>(
82 commit: &oid,
83 mut find: Find,
84 name_set: &HashMap<ObjectId, Cow<'a, BStr>>,
85 ) -> Result<Option<Outcome<'a>>, E>
86 where
87 Find: for<'b> FnMut(&oid, &'b mut Vec<u8>) -> Result<CommitRefIter<'b>, E>,
88 E: std::error::Error + Send + Sync + 'static,
89 {
90 if let Some(name) = name_set.get(commit) {
91 return Ok(Some(Outcome {
92 name: name.clone(),
93 id: commit.to_owned(),
94 depth: 0,
95 }));
96 }
97
98 let mut buf = Vec::new();
99 let mut parent_buf = Vec::new();
100 let mut parents = Vec::new();
101
102 let mut queue = VecDeque::from_iter(Some(commit.to_owned()));
103 let mut candidates = Vec::new();
104 let mut seen_commits = 0;
105 let mut _gave_up_on_commit = None;
106 let mut seen = hash_hasher::HashedMap::default();
107 seen.insert(commit.to_owned(), 0u32);
108
109 const MAX_CANDIDATES: usize = std::mem::size_of::<Flags>() * 8;
110 while let Some(commit) = queue.pop_front() {
111 seen_commits += 1;
112 if let Some(name) = name_set.get(&commit) {
113 if candidates.len() < MAX_CANDIDATES {
114 let identity_bit = 1 << candidates.len();
115 candidates.push(Candidate {
116 name: name.clone(),
117 commits_in_its_future: seen_commits - 1,
118 identity_bit,
119 order: candidates.len(),
120 });
121 *seen.get_mut(&commit).expect("inserted") |= identity_bit;
122 } else {
123 _gave_up_on_commit = Some(commit);
124 break;
125 }
126 }
127
128 let flags = seen[&commit];
129 for candidate in candidates
130 .iter_mut()
131 .filter(|c| (flags & c.identity_bit) != c.identity_bit)
132 {
133 candidate.commits_in_its_future += 1;
134 }
135
136 let commit_iter = find(&commit, &mut buf)?;
137 parents.clear();
138 for token in commit_iter {
139 match token {
140 Ok(git_object::commit::ref_iter::Token::Tree { .. }) => continue,
141 Ok(git_object::commit::ref_iter::Token::Parent { id: parent_id }) => {
142 match seen.entry(parent_id) {
143 hash_map::Entry::Vacant(entry) => {
144 let mut parent = find(&parent_id, &mut parent_buf)?;
145 // TODO: figure out if not having a date is a hard error.
146 let parent_commit_date = parent
147 .committer()
148 .map(|committer| committer.time.seconds_since_unix_epoch)
149 .unwrap_or_default();
150
151 entry.insert(flags);
152 parents.push((parent_id, parent_commit_date));
153 }
154 hash_map::Entry::Occupied(mut entry) => {
155 *entry.get_mut() |= flags;
156 }
157 }
158 }
159 Ok(_unused_token) => break,
160 Err(_err) => todo!("return a decode error"),
161 }
162 }
163
164 if !parents.is_empty() {
165 parents.sort_by(|a, b| a.1.cmp(&b.1).reverse());
166 seen.extend(parents.iter().map(|e| (e.0, flags)));
167 queue.extend(parents.iter().map(|e| e.0));
168 }
169 }
170
171 if candidates.is_empty() {
172 return Ok(None);
173 }
174
175 candidates.sort_by(|a, b| {
176 a.commits_in_its_future
177 .cmp(&b.commits_in_its_future)
178 .then_with(|| a.order.cmp(&b.order))
179 });
180 Ok(candidates.into_iter().next().map(|c| Outcome {
181 name: c.name,
182 id: commit.to_owned(),
183 depth: c.commits_in_its_future,
184 }))
185 }
186
187 type Flags = u32;
188
189 #[derive(Debug)]
190 struct Candidate<'a> {
191 name: Cow<'a, BStr>,
192 commits_in_its_future: Flags,
193 /// A single bit identifying this candidate uniquely in a bitset
194 identity_bit: Flags,
195 /// The order at which we found the candidate, first one has order = 0
196 order: usize,
197 }
198}
git-revision/src/lib.rs+3−0
@@ -1 +1,4 @@
1#![forbid(unsafe_code, rust_2018_idioms)]1#![forbid(unsafe_code, rust_2018_idioms)]
2
3pub mod describe;
4pub use describe::function::describe;
git-revision/tests/describe/format.rs+30−0
@@ -0,0 +1,30 @@
1use git_object::bstr::ByteSlice;
2use git_revision::describe;
3use git_testtools::hex_to_id;
4use std::borrow::Cow;
5
6#[test]
7fn exact_match_with_dirty_and_long() {
8 let mut format = describe::Outcome {
9 name: Cow::Borrowed(b"main".as_bstr()),
10 id: hex_to_id("b920bbb055e1efb9080592a409d3975738b6efb3"),
11 depth: 0,
12 }
13 .into_format(7);
14 assert!(format.is_exact_match());
15 assert_eq!(format.to_string(), "main");
16 assert_eq!(format.long().to_string(), "main-0-gb920bbb");
17
18 format.dirty_suffix = Some("dirty".into());
19 assert_eq!(format.short().to_string(), "main-dirty");
20 assert_eq!(format.long().to_string(), "main-0-gb920bbb-dirty");
21
22 format.dirty_suffix = None;
23 format.depth = 42;
24 assert!(!format.is_exact_match());
25 assert_eq!(format.short().to_string(), "main-42-gb920bbb");
26
27 format.dirty_suffix = Some("dirty".into());
28 assert_eq!(format.to_string(), "main-42-gb920bbb-dirty");
29 assert_eq!(format.long().to_string(), "main-42-gb920bbb-dirty");
30}
git-revision/tests/describe/mod.rs+74−0
@@ -0,0 +1,74 @@
1use git_object::bstr::ByteSlice;
2use git_repository::odb::FindExt;
3use git_repository::Repository;
4use git_revision::describe;
5use git_testtools::hex_to_id;
6use std::borrow::Cow;
7
8mod format;
9
10#[test]
11fn option_none_if_no_tag_found() {
12 let repo = repo();
13 let commit = repo.head().unwrap().peel_to_commit_in_place().unwrap();
14 let res = git_revision::describe(
15 &commit.id,
16 |id, buf| repo.objects.find_commit_iter(id, buf),
17 &Default::default(),
18 )
19 .unwrap();
20 assert_eq!(res, None, "cannot find anything if there's no candidate");
21}
22#[test]
23fn typical_usecases() {
24 let repo = repo();
25 let commit = repo.head().unwrap().peel_to_commit_in_place().unwrap();
26 let name = Cow::Borrowed(b"main".as_bstr());
27 let res = git_revision::describe(
28 &commit.id,
29 |_, _| Err(std::io::Error::new(std::io::ErrorKind::Other, "shouldn't be called")),
30 &vec![(commit.id, name.clone())].into_iter().collect(),
31 )
32 .unwrap();
33
34 assert_eq!(
35 res,
36 Some(describe::Outcome {
37 name,
38 id: commit.id,
39 depth: 0,
40 }),
41 "this is an exact match"
42 );
43
44 let name = Cow::Borrowed(b"at-c5".as_bstr());
45 let res = git_revision::describe(
46 &commit.id,
47 |id, buf| repo.objects.find_commit_iter(id, buf),
48 &vec![
49 (hex_to_id("efd9a841189668f1bab5b8ebade9cd0a1b139a37"), name.clone()),
50 (
51 hex_to_id("9152eeee2328073cf23dcf8e90c949170b711659"),
52 b"at-b1c1".as_bstr().into(),
53 ),
54 ]
55 .into_iter()
56 .collect(),
57 )
58 .unwrap();
59
60 assert_eq!(
61 res,
62 Some(describe::Outcome {
63 name,
64 id: commit.id,
65 depth: 3,
66 }),
67 "a match to a tag 1 commit away with 2 commits on the other side of the merge/head"
68 );
69}
70
71fn repo() -> Repository {
72 let dir = git_testtools::scripted_fixture_repo_read_only("make_repo_with_branches.sh").unwrap();
73 git_repository::open(dir).unwrap()
74}
git-revision/tests/fixtures/make_repo_with_branches.sh+23−0
@@ -0,0 +1,23 @@
1#!/bin/bash
2set -eu -o pipefail
3
4git init -q
5git config commit.gpgsign false
6git config merge.ff false
7
8git checkout -q -b main
9git commit -q --allow-empty -m c1
10git tag at-c1
11git commit -q --allow-empty -m c2
12git commit -q --allow-empty -m c3
13git commit -q --allow-empty -m c4
14
15git checkout -q -b branch1
16git commit -q --allow-empty -m b1c1
17git tag at-b1c1
18git commit -q --allow-empty -m b1c2
19
20git checkout -q main
21git commit -q --allow-empty -m c5
22git tag at-c5
23git merge branch1 -m m1b1
git-revision/tests/revision.rs+1−0
@@ -0,0 +1 @@
1mod describe;
git-traverse/src/commit.rs+3−1
@@ -217,7 +217,9 @@ pub mod ancestors { · 216 unmodified lines
217 .and_then(|mut parent| parent.committer().map(|committer| committer.time));217 .and_then(|mut parent| parent.committer().map(|committer| committer.time));
218 218
219 if let Some(parent_committer_date) = parent_committer_date {219 if let Some(parent_committer_date) = parent_committer_date {
220 state.parents_with_date.push((id, parent_committer_date.time));220 state
221 .parents_with_date
222 .push((id, parent_committer_date.seconds_since_unix_epoch));
221 }223 }
222 224
223 if matches!(self.parents, Parents::First) {225 if matches!(self.parents, Parents::First) {
gitoxide-core/src/hours.rs+10−2
@@ -104,7 +104,14 @@ where · 103 unmodified lines
104 },104 },
105 )105 )
106 .ok_or_else(|| anyhow!("An error occurred when decoding commits - one commit could not be parsed"))?;106 .ok_or_else(|| anyhow!("An error occurred when decoding commits - one commit could not be parsed"))?;
107 all_commits.sort_by(|a, b| a.email.cmp(&b.email).then(a.time.time.cmp(&b.time.time).reverse()));107 all_commits.sort_by(|a, b| {
108 a.email.cmp(&b.email).then(
109 a.time
110 .seconds_since_unix_epoch
111 .cmp(&b.time.seconds_since_unix_epoch)
112 .reverse(),
113 )
114 });
108 if all_commits.is_empty() {115 if all_commits.is_empty() {
109 bail!("No commits to process");116 bail!("No commits to process");
110 }117 }
@@ -185,7 +192,8 @@ fn estimate_hours(commits: &[actor::Signature]) -> WorkByEmail { · 74 unmodified lines
185 + commits.iter().rev().tuple_windows().fold(192 + commits.iter().rev().tuple_windows().fold(
186 0_f32,193 0_f32,
187 |hours, (cur, next): (&actor::Signature, &actor::Signature)| {194 |hours, (cur, next): (&actor::Signature, &actor::Signature)| {
188 let change_in_minutes = (next.time.time - cur.time.time) as f32 / MINUTES_PER_HOUR;195 let change_in_minutes =
196 (next.time.seconds_since_unix_epoch - cur.time.seconds_since_unix_epoch) as f32 / MINUTES_PER_HOUR;
189 if change_in_minutes < MAX_COMMIT_DIFFERENCE_IN_MINUTES {197 if change_in_minutes < MAX_COMMIT_DIFFERENCE_IN_MINUTES {
190 hours + change_in_minutes as f32 / MINUTES_PER_HOUR198 hours + change_in_minutes as f32 / MINUTES_PER_HOUR
191 } else {199 } else {

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