1use std::collections::{HashMap, HashSet};
18
19use crate::change_id::{resolved_change_id, ChangeId};
20use crate::config::{parse_bool, ConfigSet};
21use crate::error::Result;
22use crate::ident::Signature;
23use crate::objects::{CommitData, ObjectId, ObjectKind, OidHashMap, OidHashSet};
24use crate::odb::Odb;
25use crate::refs::{PackedPeel, PackedRefPeels};
26use crate::repo::Repository;
27use crate::state::{resolve_head_for_repository, HeadState};
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
31#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
32#[cfg_attr(feature = "serde-models", serde(rename_all = "snake_case"))]
33pub enum DecorationKind {
34 Branch,
36 RemoteBranch,
38 Tag,
40 Stash,
42 Head,
44 Grafted,
46 Other,
51}
52
53#[derive(Clone, Debug)]
55pub struct DecorationItem {
56 pub refname: Option<String>,
58 pub display: String,
60 pub kind: DecorationKind,
62}
63
64pub type DecorationMap = HashMap<String, Vec<DecorationItem>>;
66
67#[derive(Clone, Debug, PartialEq, Eq)]
69#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
70pub struct CommitRefDecoration {
71 pub name: String,
73 pub kind: DecorationKind,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
79#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
80pub struct LoadedCommit {
81 pub oid: ObjectId,
83 pub parents: Vec<ObjectId>,
85 pub author: Signature,
88 pub committer: Signature,
90 pub message: String,
92 pub refs: Vec<CommitRefDecoration>,
94 pub change_id: ChangeId,
96 pub change_id_stored: bool,
98}
99
100#[derive(Default, Clone)]
104pub struct DecorationFilter {
105 pub include: Vec<String>,
107 pub exclude: Vec<String>,
109 pub exclude_config: Vec<String>,
112}
113
114impl DecorationFilter {
115 pub fn is_empty(&self) -> bool {
117 self.include.is_empty() && self.exclude.is_empty() && self.exclude_config.is_empty()
118 }
119
120 pub fn matches(&self, refname: &str) -> bool {
122 for pat in &self.exclude {
124 if decoration_pattern_matches(pat, refname) {
125 return false;
126 }
127 }
128 if !self.include.is_empty() {
130 for pat in &self.include {
131 if decoration_pattern_matches(pat, refname) {
132 return true;
133 }
134 }
135 return false;
136 }
137 for pat in &self.exclude_config {
139 if decoration_pattern_matches(pat, refname) {
140 return false;
141 }
142 }
143 true
144 }
145}
146
147pub fn normalize_glob_ref(pattern: &str) -> String {
151 let mut out = String::new();
152 if !pattern.starts_with("refs/") && pattern != "HEAD" {
153 out.push_str("refs/");
154 }
155 out.push_str(pattern);
156 if out.ends_with('/') {
157 out.pop();
158 }
159 out
160}
161
162fn decoration_pattern_matches(pattern: &str, refname: &str) -> bool {
166 let has_glob = pattern.bytes().any(|b| matches!(b, b'*' | b'?' | b'['));
167 if has_glob {
168 crate::wildmatch::wildmatch(pattern.as_bytes(), refname.as_bytes(), 0)
169 } else {
170 if let Some(rest) = refname.strip_prefix(pattern) {
172 rest.is_empty() || rest.starts_with('/')
173 } else {
174 false
175 }
176 }
177}
178
179fn replace_ref_base() -> String {
180 let mut base = crate::environment::Environment::empty()
181 .var("GIT_REPLACE_REF_BASE")
182 .unwrap_or_else(|| "refs/replace/".to_owned());
183 if !base.ends_with('/') {
184 base.push('/');
185 }
186 base
187}
188
189fn prepend_decoration(items: &mut Vec<DecorationItem>, item: DecorationItem) {
190 items.insert(0, item);
191}
192
193#[derive(Clone, Default)]
198#[non_exhaustive]
199pub struct DecorationOptions {
200 pub full_ref_names: bool,
202 pub clear_decorations: bool,
205 pub filter: DecorationFilter,
207 pub commits: Option<Vec<ObjectId>>,
211}
212
213impl DecorationOptions {
214 #[must_use]
216 pub fn with_full_ref_names(mut self, full_ref_names: bool) -> Self {
217 self.full_ref_names = full_ref_names;
218 self
219 }
220
221 #[must_use]
223 pub fn with_clear_decorations(mut self, clear_decorations: bool) -> Self {
224 self.clear_decorations = clear_decorations;
225 self
226 }
227
228 #[must_use]
230 pub fn with_filter(mut self, filter: DecorationFilter) -> Self {
231 self.filter = filter;
232 self
233 }
234
235 #[must_use]
237 pub fn with_commits(mut self, commits: Option<Vec<ObjectId>>) -> Self {
238 self.commits = commits;
239 self
240 }
241}
242
243pub trait CommitReuse {
249 fn take_commit(&mut self, oid: &ObjectId) -> Option<Result<CommitData>>;
256
257 fn cached_subject_line(&self, oid: &ObjectId) -> Option<Result<String>> {
259 let _ = oid;
260 None
261 }
262}
263
264impl CommitReuse for OidHashMap<CommitData> {
265 fn take_commit(&mut self, oid: &ObjectId) -> Option<Result<CommitData>> {
266 self.remove(oid).map(Ok)
267 }
268
269 fn cached_subject_line(&self, oid: &ObjectId) -> Option<Result<String>> {
270 self.get(oid).map(|data| {
271 Ok(data
272 .message
273 .lines()
274 .find(|line| !line.trim().is_empty())
275 .map(str::trim)
276 .unwrap_or("(no subject)")
277 .to_owned())
278 })
279 }
280}
281
282impl CommitReuse for () {
284 fn take_commit(&mut self, _oid: &ObjectId) -> Option<Result<CommitData>> {
285 None
286 }
287}
288
289impl<T: CommitReuse + ?Sized> CommitReuse for &mut T {
290 fn take_commit(&mut self, oid: &ObjectId) -> Option<Result<CommitData>> {
291 (**self).take_commit(oid)
292 }
293}
294
295pub(crate) fn load_commits(
297 repo: &Repository,
298 oids: &[ObjectId],
299 decorations: &DecorationMap,
300 parsed: &mut impl CommitReuse,
301) -> Result<Vec<LoadedCommit>> {
302 let mut out = Vec::with_capacity(oids.len());
303 for oid in oids {
304 let data = match parsed.take_commit(oid) {
305 Some(data) => data?,
306 None => repo.read_commit_with_replace(oid)?,
307 };
308 let resolved = resolved_change_id(oid, &data);
309 let hex = oid.to_hex();
310 let refs = decorations
311 .get(&hex)
312 .map(|items| {
313 items
314 .iter()
315 .map(|item| CommitRefDecoration {
316 name: item.display.clone(),
317 kind: item.kind,
318 })
319 .collect()
320 })
321 .unwrap_or_default();
322 out.push(LoadedCommit {
323 oid: *oid,
324 parents: data.parents,
325 author: Signature::from_header_lossy(&data.author),
326 committer: Signature::from_header_lossy(&data.committer),
327 message: data.message,
328 refs,
329 change_id: resolved.id,
330 change_id_stored: resolved.stored,
331 });
332 }
333 Ok(out)
334}
335
336pub(crate) fn collect_decorations(
338 repo: &Repository,
339 options: &DecorationOptions,
340) -> Result<DecorationMap> {
341 let targets: Option<OidHashSet> = options
342 .commits
343 .as_ref()
344 .map(|commits| commits.iter().copied().collect());
345 collect_decorations_impl(
346 repo,
347 options.full_ref_names,
348 options.clear_decorations,
349 &options.filter,
350 targets.as_ref(),
351 )
352}
353
354fn collect_decorations_impl(
356 repo: &Repository,
357 full: bool,
358 clear_decorations: bool,
359 filter: &DecorationFilter,
360 targets: Option<&OidHashSet>,
361) -> Result<DecorationMap> {
362 let mut map: DecorationMap = HashMap::new();
363 let git_dir = &repo.git_dir();
364
365 let head = resolve_head_for_repository(repo)?;
366 let hide_remote_update_noise = repo
367 .config()
368 .snapshot()
369 .unwrap_or_else(|_| std::sync::Arc::new(ConfigSet::new()))
370 .value("grit.submoduleUpdateRemoteDecorations")
371 .as_deref()
372 .and_then(|value| parse_bool(value).ok())
373 .unwrap_or(false);
374 let rep_base = replace_ref_base();
375
376 let mut all_refs = match targets {
377 _ if !repo.refs_on_disk() => crate::refs::list_refs_for_repository(repo, "refs/")?,
378 Some(targets) => {
381 crate::refs::list_refs_filtering_packed(git_dir, "refs/", &|name, oid, peel| {
382 name.starts_with(&rep_base)
383 || match peel {
384 PackedPeel::Peeled(peeled) => targets.contains(&peeled),
385 PackedPeel::NotTag => targets.contains(oid),
386 PackedPeel::Unknown => true,
387 }
388 })?
389 }
390 None => crate::refs::list_refs(git_dir, "refs/")?,
391 };
392 all_refs.sort_by(|a, b| a.0.cmp(&b.0));
393 let peeler = RefTipPeeler::new(repo, targets);
394
395 for (refname, oid) in all_refs {
396 if !filter.is_empty() && !refname.starts_with(&rep_base) && !filter.matches(&refname) {
398 continue;
399 }
400 if refname.starts_with(&rep_base) {
401 let Some(rest) = refname.strip_prefix(&rep_base) else {
402 continue;
403 };
404 let rest = rest.trim();
405 if rest.len() != 40 {
406 continue;
407 }
408 let Ok(replaced) = rest.parse::<ObjectId>() else {
409 continue;
410 };
411 if targets.is_some_and(|t| !t.contains(&replaced)) {
412 continue;
413 }
414 prepend_decoration(
415 map.entry(rest.to_owned()).or_default(),
416 DecorationItem {
417 refname: None,
418 display: "replaced".to_owned(),
419 kind: DecorationKind::Grafted,
420 },
421 );
422 continue;
423 }
424
425 if refname == "refs/stash" || refname.starts_with("refs/stash/") {
426 let Some(hex) = peeler.commit_hex(&refname, &oid) else {
427 continue;
428 };
429 prepend_decoration(
430 map.entry(hex).or_default(),
431 DecorationItem {
432 refname: Some("refs/stash".to_string()),
433 display: "refs/stash".to_owned(),
434 kind: DecorationKind::Stash,
435 },
436 );
437 continue;
438 }
439
440 if let Some(rest) = refname.strip_prefix("refs/heads/") {
441 let Some(hex) = peeler.commit_hex(&refname, &oid) else {
442 continue;
443 };
444 let display = if full {
445 refname.clone()
446 } else {
447 rest.to_owned()
448 };
449 prepend_decoration(
450 map.entry(hex).or_default(),
451 DecorationItem {
452 refname: Some(refname.clone()),
453 display,
454 kind: DecorationKind::Branch,
455 },
456 );
457 continue;
458 }
459
460 if let Some(rest) = refname.strip_prefix("refs/tags/") {
461 let Some(peeled) = peeler.commit_hex(&refname, &oid) else {
462 continue;
463 };
464 let display = if full {
465 refname.clone()
466 } else {
467 rest.to_owned()
468 };
469 prepend_decoration(
470 map.entry(peeled).or_default(),
471 DecorationItem {
472 refname: Some(refname.clone()),
473 display,
474 kind: DecorationKind::Tag,
475 },
476 );
477 continue;
478 }
479
480 if let Some(rest) = refname.strip_prefix("refs/remotes/") {
481 let Some(peeled) = peeler.commit_hex(&refname, &oid) else {
482 continue;
483 };
484 let display = if full {
485 refname.clone()
486 } else {
487 rest.to_owned()
488 };
489 prepend_decoration(
490 map.entry(peeled).or_default(),
491 DecorationItem {
492 refname: Some(refname.clone()),
493 display,
494 kind: DecorationKind::RemoteBranch,
495 },
496 );
497 continue;
498 }
499
500 if clear_decorations || !filter.is_empty() {
508 let Some(peeled) = peeler.commit_hex(&refname, &oid) else {
509 continue;
510 };
511 prepend_decoration(
512 map.entry(peeled).or_default(),
513 DecorationItem {
514 refname: Some(refname.clone()),
515 display: refname.clone(),
516 kind: DecorationKind::Other,
517 },
518 );
519 }
520 }
521
522 if let Some(oid) = head
523 .oid()
524 .filter(|oid| targets.is_none_or(|t| t.contains(*oid)))
525 {
526 if filter.is_empty() || filter.matches("HEAD") {
527 let hex = oid.to_hex();
528 prepend_decoration(
529 map.entry(hex).or_default(),
530 DecorationItem {
531 refname: Some("HEAD".to_string()),
532 display: "HEAD".to_owned(),
533 kind: DecorationKind::Head,
534 },
535 );
536 }
537 }
538
539 for items in map.values_mut() {
540 let mut seen = HashSet::new();
544 items.retain(|it| seen.insert((it.kind, it.display.clone(), it.refname.clone())));
545 if hide_remote_update_noise {
546 let branch_names: HashSet<String> = items
547 .iter()
548 .filter(|it| it.kind == DecorationKind::Branch)
549 .map(|it| it.display.clone())
550 .collect();
551 if !branch_names.is_empty() {
552 let hide_detached_head = !matches!(head, HeadState::Branch { .. });
553 items.retain(|it| {
554 if hide_detached_head && it.kind == DecorationKind::Head {
555 return false;
556 }
557 if it.kind == DecorationKind::RemoteBranch {
558 let short_remote = it
559 .display
560 .split_once('/')
561 .map(|(_, branch)| branch)
562 .unwrap_or(it.display.as_str());
563 return !branch_names.contains(short_remote) && short_remote != "HEAD";
564 }
565 true
566 });
567 }
568 }
569 }
570
571 Ok(map)
572}
573
574pub fn peel_to_commit_hex(odb: &Odb, hex: &str) -> Option<String> {
580 let oid: ObjectId = hex.parse().ok()?;
581 odb.peel_to_commit(oid)
582 .ok()
583 .flatten()
584 .map(|commit| commit.to_hex())
585}
586
587struct RefTipPeeler<'a> {
598 repo: &'a Repository,
599 packed: Option<PackedRefPeels>,
600 graph: std::cell::OnceCell<Option<std::sync::Arc<crate::commit_graph_file::CommitGraphChain>>>,
601 targets: Option<&'a OidHashSet>,
602 pack_context: std::cell::OnceCell<crate::pack_store::PackReadContextGuard>,
603}
604
605impl<'a> RefTipPeeler<'a> {
606 fn new(repo: &'a Repository, targets: Option<&'a OidHashSet>) -> Self {
607 let packed = PackedRefPeels::for_store(repo.ref_store(), repo.git_dir()).ok();
609 Self {
610 repo,
611 packed,
612 graph: std::cell::OnceCell::new(),
613 targets,
614 pack_context: std::cell::OnceCell::new(),
615 }
616 }
617
618 fn is_commit(&self, oid: &ObjectId) -> bool {
619 let graph = self
620 .graph
621 .get_or_init(|| self.repo.odb().commit_graph_chain());
622 if graph.as_ref().is_some_and(|g| g.find_commit(oid).is_some()) {
623 return true;
624 }
625 self.repo
626 .odb()
627 .read_info(oid)
628 .is_ok_and(|info| info.kind == ObjectKind::Commit)
629 }
630
631 fn commit_hex(&self, refname: &str, oid: &ObjectId) -> Option<String> {
633 let key = self.key(refname, oid)?;
634 if self.targets.is_some_and(|t| !t.contains(&key)) {
635 return None;
636 }
637 Some(key.to_hex())
638 }
639
640 fn key(&self, refname: &str, oid: &ObjectId) -> Option<ObjectId> {
641 match self.packed.as_ref().and_then(|p| p.peeled(refname, oid)) {
642 Some(Some(peeled)) => {
643 if let Some(targets) = self.targets {
644 return targets.contains(&peeled).then_some(peeled);
646 }
647 return Some(if self.is_commit(&peeled) {
648 peeled
649 } else {
650 *oid
651 });
652 }
653 Some(None) => return Some(*oid),
654 None => {}
655 }
656 if self.targets.is_some_and(|t| t.contains(oid)) {
657 return Some(*oid);
658 }
659 self.pack_context
661 .get_or_init(|| self.repo.odb().pack_read_context_guard());
662 Some(
663 self.repo
664 .odb()
665 .peel_to_commit(*oid)
666 .ok()
667 .flatten()
668 .unwrap_or(*oid),
669 )
670 }
671}
672
673pub fn current_branch_decoration_index(
679 items: &[DecorationItem],
680 head: &HeadState,
681) -> Option<usize> {
682 let refname = match head {
683 HeadState::Branch { refname, .. } => refname.as_str(),
684 _ => return None,
685 };
686 if !items.iter().any(|it| it.kind == DecorationKind::Head) {
690 return None;
691 }
692 items
693 .iter()
694 .position(|it| it.kind == DecorationKind::Branch && it.refname.as_deref() == Some(refname))
695}