Skip to main content

git_internal/internal/object/
tag.rs

1//! In Git objects there are two types of tags: Lightweight tags and annotated tags.
2//!
3//! A lightweight tag is simply a pointer to a specific commit in Git's version history,
4//! without any additional metadata or information associated with it. It is created by
5//! running the `git tag` command with a name for the tag and the commit hash that it points to.
6//!
7//! An annotated tag, on the other hand, is a Git object in its own right, and includes
8//! metadata such as the tagger's name and email address, the date and time the tag was created,
9//! and a message describing the tag. It is created by running the `git tag -a` command with
10//! a name for the tag, the commit hash that it points to, and the additional metadata that
11//! should be associated with the tag.
12//!
13//! When you create a tag in Git, whether it's a lightweight or annotated tag, Git creates a
14//! new object in its object database to represent the tag. This object includes the name of the
15//! tag, the hash of the commit it points to, and any additional metadata associated with the
16//! tag (in the case of an annotated tag).
17//!
18//! There is no difference in binary format between lightweight tags and annotated tags in Git,
19//! as both are represented using the same lightweight object format in Git's object database.
20//!
21//! The lightweight tag is a reference to a specific commit in Git's version history, not be stored
22//! as a separate object in Git's object database. This means that if you create a lightweight tag
23//! and then move the tag to a different commit, the tag will still point to the original commit.
24//!
25//! The lightweight just a text file with the commit hash in it, and the file name is the tag name.
26//! If one of -a, -s, or -u \<key-id\> is passed, the command creates a tag object, and requires a tag
27//! message. Unless -m \<msg\> or -F \<file\> is given, an editor is started for the user to type in the
28//! tag message.
29//!
30//! ```bash
31//! 4b00093bee9b3ef5afc5f8e3645dc39cfa2f49aa
32//! ```
33//!
34//! The annotated tag is a Git object in its own right, and includes metadata such as the tagger's
35//! name and email address, the date and time the tag was created, and a message describing the tag.
36//!
37//! So, we can use the `git cat-file -p <tag>` command to get the tag object, and the command not
38//! for the lightweight tag.
39use std::fmt::Display;
40
41use bstr::ByteSlice;
42
43use crate::{
44    errors::GitError,
45    hash::{HashKind, ObjectHash},
46    internal::object::{ObjectTrait, ObjectType, signature::Signature},
47};
48
49/// The tag object is used to Annotated tag
50#[derive(Eq, Debug, Clone)]
51pub struct Tag {
52    pub id: ObjectHash,
53    pub object_hash: ObjectHash,
54    pub object_type: ObjectType,
55    pub tag_name: String,
56    pub tagger: Signature,
57    pub message: String,
58}
59
60impl PartialEq for Tag {
61    fn eq(&self, other: &Self) -> bool {
62        self.id == other.id
63    }
64}
65
66impl Display for Tag {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(
69            f,
70            "object {}\ntype {}\ntag {}\ntagger {}\n\n{}",
71            self.object_hash, self.object_type, self.tag_name, self.tagger, self.message
72        )
73    }
74}
75
76impl Tag {
77    // pub fn new_from_meta(meta: Meta) -> Result<Tag, GitError> {
78    //     Ok(Tag::new_from_data(meta.data))
79    // }
80
81    // pub fn new_from_file(path: &str) -> Result<Tag, GitError> {
82    //     let meta = Meta::new_from_file(path)?;
83    //     Tag::new_from_meta(meta)
84    // }
85
86    /// Create an annotated tag and derive its ID with an explicit repository `kind`.
87    ///
88    /// Does not consult the thread-local [`HashKind`]. `object_hash` must
89    /// belong to `kind`; a cross-kind reference fails closed with
90    /// [`GitError::InvalidHashValue`]. Never panics.
91    pub fn new_with_kind(
92        kind: HashKind,
93        object_hash: ObjectHash,
94        object_type: ObjectType,
95        tag_name: String,
96        tagger: Signature,
97        message: String,
98    ) -> Result<Self, GitError> {
99        object_hash.ensure_kind(kind)?;
100        let mut tag = Self {
101            id: ObjectHash::zero_for_kind(kind),
102            object_hash,
103            object_type,
104            tag_name,
105            tagger,
106            message,
107        };
108        let data = tag.to_data()?;
109        tag.id = ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Tag, &data)?;
110        Ok(tag)
111    }
112
113    /// Create an annotated tag using the thread-local [`HashKind`]; see [`Tag::new_with_kind`].
114    pub fn new(
115        object_hash: ObjectHash,
116        object_type: ObjectType,
117        tag_name: String,
118        tagger: Signature,
119        message: String,
120    ) -> Self {
121        let mut tag = Self {
122            id: ObjectHash::default(),
123            object_hash,
124            object_type,
125            tag_name,
126            tagger,
127            message,
128        };
129        // The id is the canonical git object hash of the *serialized* tag
130        // (`to_data()`), computed exactly like `Commit::new`. Previously this
131        // hashed a hand-written `format!` string that interpolated the tagger via
132        // `Signature`'s `Display` (a human-readable `"<name> <<email>>\nDate: …"`
133        // form) rather than `Signature::to_data()` (`"tagger <name> <<email>>
134        // <timestamp> <tz>"`). That made `id != hash(to_data())`, so the bytes
135        // libra stores/packs hash to a *different* OID than the ref points at —
136        // breaking every packfile round-trip (fetch/push/repack) of annotated
137        // tags. Hashing `to_data()` keeps the id canonical.
138        tag.id = ObjectHash::from_type_and_data(ObjectType::Tag, &tag.to_data().unwrap());
139        tag
140    }
141}
142
143impl ObjectTrait for Tag {
144    /// The tag object is used to Annotated tag, it's binary format is:
145    ///
146    /// ```bash
147    /// object <object_hash> 0x0a # The SHA-1 hash of the object that the annotated tag is attached to (usually a commit)
148    /// type <object_type> 0x0a #The type of Git object that the annotated tag is attached to (usually 'commit')
149    /// tag <tag_name> 0x0a # The name of the annotated tag(in UTF-8 encoding)
150    /// tagger <tagger> 0x0a # The name, email address, and date of the person who created the annotated tag
151    /// <message>
152    /// ```
153    fn from_bytes(row_data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
154    where
155        Self: Sized,
156    {
157        let mut headers = row_data;
158        let mut message_start = 0;
159
160        if let Some(pos) = headers.find(b"\n\n") {
161            message_start = pos + 2;
162            headers = &headers[..pos];
163        }
164
165        let mut object_hash: Option<ObjectHash> = None;
166        let mut object_type: Option<ObjectType> = None;
167        let mut tag_name: Option<String> = None;
168        let mut tagger: Option<Signature> = None;
169
170        for line in headers.lines() {
171            if let Some(s) = line.strip_prefix(b"object ") {
172                let hash_str = s.to_str().map_err(|_| {
173                    GitError::InvalidTagObject(format!(
174                        "Invalid UTF-8 in object hash (from_bytes: expected {} {} hex chars, got {} bytes)",
175                        hash.kind().hex_len(),
176                        hash.kind(),
177                        s.len()
178                    ))
179                })?;
180                // The referenced object belongs to the tag's own repository kind; never
181                // infer the algorithm from the hex length.
182                object_hash = Some(
183                    ObjectHash::from_hex_for_kind(hash.kind(), hash_str).map_err(|e| {
184                        GitError::InvalidTagObject(format!("Invalid object hash format: {e}"))
185                    })?,
186                );
187            } else if let Some(s) = line.strip_prefix(b"type ") {
188                let type_str = s.to_str().map_err(|_| {
189                    GitError::InvalidTagObject("Invalid UTF-8 in object type".to_string())
190                })?;
191                object_type = Some(ObjectType::from_string(type_str)?);
192            } else if let Some(s) = line.strip_prefix(b"tag ") {
193                let tag_str = s.to_str().map_err(|_| {
194                    GitError::InvalidTagObject("Invalid UTF-8 in tag name".to_string())
195                })?;
196                tag_name = Some(tag_str.to_string());
197            } else if line.starts_with(b"tagger ") {
198                tagger = Some(Signature::from_data(line.to_vec())?);
199            }
200        }
201
202        let message = if message_start > 0 {
203            String::from_utf8_lossy(&row_data[message_start..]).to_string()
204        } else {
205            String::new()
206        };
207
208        Ok(Tag {
209            id: hash,
210            object_hash: object_hash
211                .ok_or_else(|| GitError::InvalidTagObject("Missing object hash".to_string()))?,
212            object_type: object_type
213                .ok_or_else(|| GitError::InvalidTagObject("Missing object type".to_string()))?,
214            tag_name: tag_name
215                .ok_or_else(|| GitError::InvalidTagObject("Missing tag name".to_string()))?,
216            tagger: tagger
217                .ok_or_else(|| GitError::InvalidTagObject("Missing tagger".to_string()))?,
218            message,
219        })
220    }
221
222    fn get_type(&self) -> ObjectType {
223        ObjectType::Tag
224    }
225
226    fn get_size(&self) -> usize {
227        self.to_data().map(|data| data.len()).unwrap_or(0)
228    }
229
230    ///
231    /// ```bash
232    /// object <object_hash> 0x0a # The SHA-1/ SHA-256 hash of the object that the annotated tag is attached to (usually a commit)
233    /// type <object_type> 0x0a #The type of Git object that the annotated tag is attached to (usually 'commit')
234    /// tag <tag_name> 0x0a # The name of the annotated tag(in UTF-8 encoding)
235    /// tagger <tagger> 0x0a # The name, email address, and date of the person who created the annotated tag
236    /// <message>
237    /// ```
238    /// When using SHA-1, `<object_hash>` is 40 hex chars; when using SHA-256, it is 64 hex chars.
239    fn to_data(&self) -> Result<Vec<u8>, GitError> {
240        let mut data = Vec::new();
241
242        data.extend_from_slice(b"object ");
243        data.extend_from_slice(self.object_hash.to_string().as_bytes());
244        data.extend_from_slice(b"\n");
245
246        data.extend_from_slice(b"type ");
247        data.extend_from_slice(self.object_type.to_string().as_bytes());
248        data.extend_from_slice(b"\n");
249
250        data.extend_from_slice(b"tag ");
251        data.extend_from_slice(self.tag_name.as_bytes());
252        data.extend_from_slice(b"\n");
253
254        data.extend_from_slice(&self.tagger.to_data()?);
255        data.extend_from_slice(b"\n\n");
256
257        data.extend_from_slice(self.message.as_bytes());
258
259        Ok(data)
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use std::str::FromStr;
266
267    use super::*;
268    use crate::{
269        hash::{HashKind, ObjectHash, set_hash_kind_for_test},
270        internal::object::signature::{Signature, SignatureType},
271    };
272
273    /// Helper to build a deterministic signature for tests.
274    fn make_sig() -> Signature {
275        Signature::new(
276            SignatureType::Tagger,
277            "tagger".to_string(),
278            "tagger@example.com".to_string(),
279        )
280    }
281
282    /// `1234567890abcdef…` repeated to the width of `kind` (no exhaustive `HashKind` match,
283    /// so adding a variant does not break this helper).
284    fn pattern_id(kind: HashKind) -> ObjectHash {
285        let bytes: Vec<u8> = [0x12u8, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]
286            .iter()
287            .cycle()
288            .take(kind.size())
289            .copied()
290            .collect();
291        ObjectHash::from_bytes_for_kind(kind, &bytes).unwrap()
292    }
293
294    /// Tag creation should serialize/deserialize correctly under the given hash kind.
295    fn round_trip(kind: HashKind) {
296        let _guard = set_hash_kind_for_test(kind);
297        let target = pattern_id(kind);
298        let sig = make_sig();
299        let tag = Tag::new(
300            target,
301            ObjectType::Commit,
302            "v1.0.0".to_string(),
303            sig.clone(),
304            "release".to_string(),
305        );
306
307        let data = tag.to_data().unwrap();
308        let parsed = Tag::from_bytes(&data, tag.id).unwrap();
309
310        assert_eq!(parsed.id, tag.id);
311        assert_eq!(parsed.object_hash, target);
312        assert_eq!(parsed.object_type, ObjectType::Commit);
313        assert_eq!(parsed.tag_name, "v1.0.0");
314        assert_eq!(parsed.message, "release");
315        assert_eq!(parsed.tagger.to_string(), sig.to_string());
316    }
317
318    /// Tag round trip tests for both SHA-1 and SHA-256 hash kinds.
319    #[tokio::test]
320    async fn tag_round_trip() {
321        round_trip(HashKind::Sha1);
322        round_trip(HashKind::Sha256);
323    }
324
325    /// Regression: a tag's `id` MUST equal the canonical git object hash of its
326    /// serialized (`to_data()`) form. Before the fix, `Tag::new` hashed a
327    /// `Display`-based string (which renders the tagger as a human-readable
328    /// `"<name> <<email>>\nDate: <chrono-date> <tz>"`) instead of `to_data()`
329    /// (`"tagger <name> <<email>> <timestamp> <tz>"`), so `id != hash(to_data())`.
330    /// The object was then stored/packed under different bytes than its id —
331    /// breaking every packfile round-trip (fetch/push/repack) of annotated tags.
332    #[test]
333    fn tag_id_is_canonical_hash_of_to_data() {
334        for kind in [HashKind::Sha1, HashKind::Sha256] {
335            let _guard = set_hash_kind_for_test(kind);
336            let target = pattern_id(kind);
337            let tag = Tag::new(
338                target,
339                ObjectType::Commit,
340                "v1.0.0".to_string(),
341                make_sig(),
342                "release".to_string(),
343            );
344            let canonical =
345                ObjectHash::from_type_and_data(ObjectType::Tag, &tag.to_data().unwrap());
346            assert_eq!(
347                tag.id, canonical,
348                "tag id must be the canonical hash of its to_data() bytes ({kind:?})"
349            );
350        }
351    }
352
353    /// Invalid tag missing required fields should error.
354    #[test]
355    fn tag_invalid_missing_fields_errors() {
356        let _guard = set_hash_kind_for_test(HashKind::Sha1);
357        let bad = b"type commit\ntag v1.0.0\n\nno object line".to_vec();
358        let hash = ObjectHash::from_str("ffffffffffffffffffffffffffffffffffffffff").unwrap();
359        assert!(Tag::from_bytes(&bad, hash).is_err());
360    }
361}