Skip to main content

jj_cli/
git_util.rs

1// Copyright 2024 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Git utilities shared by various commands.
16
17use std::error;
18use std::io;
19use std::io::Write as _;
20use std::iter;
21use std::mem;
22use std::path::Path;
23use std::time::Duration;
24use std::time::Instant;
25
26use bstr::ByteSlice as _;
27use crossterm::terminal::Clear;
28use crossterm::terminal::ClearType;
29use indoc::writedoc;
30use itertools::Itertools as _;
31use jj_lib::commit::Commit;
32use jj_lib::git;
33use jj_lib::git::FailedRefExportReason;
34use jj_lib::git::GitExportStats;
35use jj_lib::git::GitImportOptions;
36use jj_lib::git::GitImportStats;
37use jj_lib::git::GitProgress;
38use jj_lib::git::GitPushStats;
39use jj_lib::git::GitRefKind;
40use jj_lib::git::GitSettings;
41use jj_lib::git::GitSidebandLineTerminator;
42use jj_lib::git::GitSubprocessCallback;
43use jj_lib::op_store::RefTarget;
44use jj_lib::op_store::RemoteRef;
45use jj_lib::ref_name::RemoteRefSymbol;
46use jj_lib::repo::ReadonlyRepo;
47use jj_lib::repo::Repo;
48use jj_lib::settings::RemoteSettingsMap;
49use jj_lib::workspace::Workspace;
50use unicode_width::UnicodeWidthStr as _;
51
52use crate::cleanup_guard::CleanupGuard;
53use crate::cli_util::WorkspaceCommandTransaction;
54use crate::cli_util::print_updated_commits;
55use crate::command_error::CommandError;
56use crate::command_error::cli_error;
57use crate::command_error::user_error;
58use crate::formatter::Formatter;
59use crate::formatter::FormatterExt as _;
60use crate::revset_util::parse_remote_auto_track_bookmarks_map;
61use crate::ui::ProgressOutput;
62use crate::ui::Ui;
63
64pub fn is_colocated_git_workspace(workspace: &Workspace, repo: &ReadonlyRepo) -> bool {
65    let Ok(git_backend) = git::get_git_backend(repo.store()) else {
66        return false;
67    };
68    let Some(git_workdir) = git_backend.git_workdir() else {
69        return false; // Bare repository
70    };
71    if git_workdir == workspace.workspace_root() {
72        return true;
73    }
74    // Colocated workspace should have ".git" directory, file, or symlink. Compare
75    // its parent as the git_workdir might be resolved from the real ".git" path.
76    let Ok(dot_git_path) = dunce::canonicalize(workspace.workspace_root().join(".git")) else {
77        return false;
78    };
79    dunce::canonicalize(git_workdir).ok().as_deref() == dot_git_path.parent()
80}
81
82/// Parses user-specified remote URL or path to absolute form.
83pub fn absolute_git_url(cwd: &Path, source: &str) -> Result<String, CommandError> {
84    // Git appears to turn URL-like source to absolute path if local git directory
85    // exits, and fails because '$PWD/https' is unsupported protocol. Since it would
86    // be tedious to copy the exact git (or libgit2) behavior, we simply let gix
87    // parse the input as URL, rcp-like, or local path.
88    let mut url = gix::url::parse(source.as_ref()).map_err(cli_error)?;
89    url.canonicalize(cwd).map_err(user_error)?;
90    // As of gix 0.68.0, the canonicalized path uses platform-native directory
91    // separator, which isn't compatible with libgit2 on Windows.
92    if url.scheme == gix::url::Scheme::File {
93        url.path = gix::path::to_unix_separators_on_windows(mem::take(&mut url.path)).into_owned();
94    }
95    // It's less likely that cwd isn't utf-8, so just fall back to original source.
96    Ok(String::from_utf8(url.to_bstring().into()).unwrap_or_else(|_| source.to_owned()))
97}
98
99/// Converts a git remote URL to a normalized HTTPS URL for web browsing.
100///
101/// Returns `None` if the URL cannot be converted.
102fn git_remote_url_to_web(url: &gix::Url) -> Option<String> {
103    if url.scheme == gix::url::Scheme::File || url.host().is_none() {
104        return None;
105    }
106
107    let host = url.host()?;
108    let path = url.path.to_str().ok()?;
109    let path = path.trim_matches('/');
110    let path = path.strip_suffix(".git").unwrap_or(path);
111
112    Some(format!("https://{host}/{path}"))
113}
114
115/// Returns the web URL for a git remote.
116///
117/// Attempts to convert the remote's URL to an HTTPS web URL.
118/// Returns `None` if the remote doesn't exist or its URL cannot be converted.
119pub fn get_remote_web_url(repo: &ReadonlyRepo, remote_name: &str) -> Option<String> {
120    let git_repo = git::get_git_repo(repo.store()).ok()?;
121    let remote = git_repo.try_find_remote(remote_name)?.ok()?;
122    let url = remote
123        .url(gix::remote::Direction::Fetch)
124        .or_else(|| remote.url(gix::remote::Direction::Push))?;
125    git_remote_url_to_web(url)
126}
127
128/// [`Ui`] adapter to forward Git command outputs.
129pub struct GitSubprocessUi<'a> {
130    // Don't hold locked ui.status() which could block tracing output in
131    // different threads.
132    ui: &'a Ui,
133    progress_output: Option<ProgressOutput<io::Stderr>>,
134    progress: Progress,
135    // Sequence to erase line towards end.
136    erase_end: &'static [u8],
137}
138
139impl<'a> GitSubprocessUi<'a> {
140    pub fn new(ui: &'a Ui) -> Self {
141        let progress_output = ui.progress_output();
142        let is_terminal = progress_output.is_some();
143        Self {
144            ui,
145            progress_output,
146            progress: Progress::new(Instant::now()),
147            erase_end: if is_terminal { b"\x1B[K" } else { b"        " },
148        }
149    }
150
151    fn write_sideband(
152        &self,
153        prefix: &[u8],
154        message: &[u8],
155        term: Option<GitSidebandLineTerminator>,
156    ) -> io::Result<()> {
157        // TODO: maybe progress should be temporarily cleared if there are
158        // sideband lines to write.
159        let mut scratch =
160            Vec::with_capacity(prefix.len() + message.len() + self.erase_end.len() + 1);
161        scratch.extend_from_slice(prefix);
162        scratch.extend_from_slice(message);
163        // Do not erase the current line by new empty line: For progress
164        // reporting, we may receive a bunch of percentage updates followed by
165        // '\r' to remain on the same line, and at the end receive a single '\n'
166        // to move to the next line. We should preserve the final status report
167        // line by not appending erase_end sequence to this single line break.
168        if !message.is_empty() {
169            scratch.extend_from_slice(self.erase_end);
170        }
171        // It's unlikely, but don't leave message without newline.
172        scratch.push(term.map_or(b'\n', |t| t.as_byte()));
173        self.ui.status().write_all(&scratch)
174    }
175}
176
177impl GitSubprocessCallback for GitSubprocessUi<'_> {
178    fn needs_progress(&self) -> bool {
179        self.progress_output.is_some()
180    }
181
182    fn progress(&mut self, progress: &GitProgress) -> io::Result<()> {
183        if let Some(output) = &mut self.progress_output {
184            self.progress.update(Instant::now(), progress, output)
185        } else {
186            Ok(())
187        }
188    }
189
190    fn local_sideband(
191        &mut self,
192        message: &[u8],
193        term: Option<GitSidebandLineTerminator>,
194    ) -> io::Result<()> {
195        self.write_sideband(b"git: ", message, term)
196    }
197
198    fn remote_sideband(
199        &mut self,
200        message: &[u8],
201        term: Option<GitSidebandLineTerminator>,
202    ) -> io::Result<()> {
203        self.write_sideband(b"remote: ", message, term)
204    }
205}
206
207pub fn load_git_import_options(
208    ui: &Ui,
209    git_settings: &GitSettings,
210    remote_settings: &RemoteSettingsMap,
211) -> Result<GitImportOptions, CommandError> {
212    Ok(GitImportOptions {
213        auto_local_bookmark: git_settings.auto_local_bookmark,
214        abandon_unreachable_commits: git_settings.abandon_unreachable_commits,
215        remote_auto_track_bookmarks: parse_remote_auto_track_bookmarks_map(ui, remote_settings)?,
216    })
217}
218
219pub fn print_git_import_stats(
220    ui: &Ui,
221    tx: &WorkspaceCommandTransaction<'_>,
222    stats: &GitImportStats,
223) -> Result<(), CommandError> {
224    if let Some(mut formatter) = ui.status_formatter() {
225        print_imported_changes(formatter.as_mut(), tx, stats)?;
226    }
227    print_failed_git_import(ui, stats)?;
228    Ok(())
229}
230
231fn print_imported_changes(
232    formatter: &mut dyn Formatter,
233    tx: &WorkspaceCommandTransaction<'_>,
234    stats: &GitImportStats,
235) -> Result<(), CommandError> {
236    for (kind, changes) in [
237        (GitRefKind::Bookmark, &stats.changed_remote_bookmarks),
238        (GitRefKind::Tag, &stats.changed_remote_tags),
239    ] {
240        let refs_stats = changes
241            .iter()
242            .map(|(symbol, (remote_ref, ref_target))| {
243                RefStatus::new(kind, symbol.as_ref(), remote_ref, ref_target, tx.repo())
244            })
245            .collect_vec();
246        let Some(max_width) = refs_stats.iter().map(|x| x.symbol.width()).max() else {
247            continue;
248        };
249        for status in refs_stats {
250            status.output(max_width, formatter)?;
251        }
252    }
253
254    if !stats.abandoned_commits.is_empty() {
255        writeln!(
256            formatter,
257            "Abandoned {} commits that are no longer reachable:",
258            stats.abandoned_commits.len()
259        )?;
260        let abandoned_commits: Vec<Commit> = stats
261            .abandoned_commits
262            .iter()
263            .map(|id| tx.repo().store().get_commit(id))
264            .try_collect()?;
265        let template = tx.commit_summary_template();
266        print_updated_commits(formatter, &template, &abandoned_commits)?;
267    }
268
269    Ok(())
270}
271
272fn print_failed_git_import(ui: &Ui, stats: &GitImportStats) -> Result<(), CommandError> {
273    if !stats.failed_ref_names.is_empty() {
274        writeln!(ui.warning_default(), "Failed to import some Git refs:")?;
275        let mut formatter = ui.stderr_formatter();
276        for name in &stats.failed_ref_names {
277            write!(formatter, "  ")?;
278            write!(formatter.labeled("git_ref"), "{name}")?;
279            writeln!(formatter)?;
280        }
281    }
282    if stats
283        .failed_ref_names
284        .iter()
285        .any(|name| name.starts_with(git::RESERVED_REMOTE_REF_NAMESPACE.as_bytes()))
286    {
287        writedoc!(
288            ui.hint_default(),
289            "
290            Git remote named '{name}' is reserved for local Git repository.
291            Use `jj git remote rename` to give a different name.
292            ",
293            name = git::REMOTE_NAME_FOR_LOCAL_GIT_REPO.as_symbol(),
294        )?;
295    }
296    Ok(())
297}
298
299/// Prints only the summary of git import stats (abandoned count, failed refs).
300/// Use this when a WorkspaceCommandTransaction is not available.
301pub fn print_git_import_stats_summary(ui: &Ui, stats: &GitImportStats) -> Result<(), CommandError> {
302    if !stats.abandoned_commits.is_empty()
303        && let Some(mut formatter) = ui.status_formatter()
304    {
305        writeln!(
306            formatter,
307            "Abandoned {} commits that are no longer reachable.",
308            stats.abandoned_commits.len()
309        )?;
310    }
311    print_failed_git_import(ui, stats)?;
312    Ok(())
313}
314
315pub struct Progress {
316    next_print: Instant,
317    buffer: String,
318    guard: Option<CleanupGuard>,
319}
320
321impl Progress {
322    pub fn new(now: Instant) -> Self {
323        Self {
324            next_print: now + crate::progress::INITIAL_DELAY,
325            buffer: String::new(),
326            guard: None,
327        }
328    }
329
330    pub fn update<W: std::io::Write>(
331        &mut self,
332        now: Instant,
333        progress: &GitProgress,
334        output: &mut ProgressOutput<W>,
335    ) -> io::Result<()> {
336        use std::fmt::Write as _;
337
338        if progress.overall() == 1.0 {
339            write!(output, "\r{}", Clear(ClearType::CurrentLine))?;
340            output.flush()?;
341            return Ok(());
342        }
343
344        if now < self.next_print {
345            return Ok(());
346        }
347        self.next_print = now + Duration::from_secs(1) / crate::progress::UPDATE_HZ;
348        if self.guard.is_none() {
349            let guard = output.output_guard(crossterm::cursor::Show.to_string());
350            let guard = CleanupGuard::new(move || {
351                drop(guard);
352            });
353            write!(output, "{}", crossterm::cursor::Hide).ok();
354            self.guard = Some(guard);
355        }
356
357        self.buffer.clear();
358        // Overwrite the current local or sideband progress line if any.
359        self.buffer.push('\r');
360        let control_chars = self.buffer.len();
361        write!(self.buffer, "{: >3.0}% ", 100.0 * progress.overall()).unwrap();
362
363        let bar_width = output
364            .term_width()
365            .map(usize::from)
366            .unwrap_or(0)
367            .saturating_sub(self.buffer.len() - control_chars + 2);
368        self.buffer.push('[');
369        draw_progress(progress.overall(), &mut self.buffer, bar_width);
370        self.buffer.push(']');
371
372        write!(self.buffer, "{}", Clear(ClearType::UntilNewLine)).unwrap();
373        // Move cursor back to the first column so the next sideband message
374        // will overwrite the current progress.
375        self.buffer.push('\r');
376        write!(output, "{}", self.buffer)?;
377        output.flush()?;
378        Ok(())
379    }
380}
381
382fn draw_progress(progress: f32, buffer: &mut String, width: usize) {
383    const CHARS: [char; 9] = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
384    const RESOLUTION: usize = CHARS.len() - 1;
385    let ticks = (width as f32 * progress.clamp(0.0, 1.0) * RESOLUTION as f32).round() as usize;
386    let whole = ticks / RESOLUTION;
387    for _ in 0..whole {
388        buffer.push(CHARS[CHARS.len() - 1]);
389    }
390    if whole < width {
391        let fraction = ticks % RESOLUTION;
392        buffer.push(CHARS[fraction]);
393    }
394    for _ in (whole + 1)..width {
395        buffer.push(CHARS[0]);
396    }
397}
398
399struct RefStatus {
400    ref_kind: GitRefKind,
401    symbol: String,
402    tracking_status: TrackingStatus,
403    import_status: ImportStatus,
404}
405
406impl RefStatus {
407    fn new(
408        ref_kind: GitRefKind,
409        symbol: RemoteRefSymbol<'_>,
410        remote_ref: &RemoteRef,
411        ref_target: &RefTarget,
412        repo: &dyn Repo,
413    ) -> Self {
414        let tracking_status = match ref_kind {
415            GitRefKind::Bookmark => {
416                if repo.view().get_remote_bookmark(symbol).is_tracked() {
417                    TrackingStatus::Tracked
418                } else {
419                    TrackingStatus::Untracked
420                }
421            }
422            GitRefKind::Tag => TrackingStatus::NotApplicable,
423        };
424
425        let import_status = match (remote_ref.target.is_absent(), ref_target.is_absent()) {
426            (true, false) => ImportStatus::New,
427            (false, true) => ImportStatus::Deleted,
428            _ => ImportStatus::Updated,
429        };
430
431        Self {
432            symbol: symbol.to_string(),
433            tracking_status,
434            import_status,
435            ref_kind,
436        }
437    }
438
439    fn output(&self, max_symbol_width: usize, out: &mut dyn Formatter) -> std::io::Result<()> {
440        let tracking_status = match self.tracking_status {
441            TrackingStatus::Tracked => "tracked",
442            TrackingStatus::Untracked => "untracked",
443            TrackingStatus::NotApplicable => "",
444        };
445
446        let import_status = match self.import_status {
447            ImportStatus::New => "new",
448            ImportStatus::Deleted => "deleted",
449            ImportStatus::Updated => "updated",
450        };
451
452        let symbol_width = self.symbol.width();
453        let pad_width = max_symbol_width.saturating_sub(symbol_width);
454        let padded_symbol = format!("{}{:>pad_width$}", self.symbol, "", pad_width = pad_width);
455
456        let label = match self.ref_kind {
457            GitRefKind::Bookmark => "bookmark",
458            GitRefKind::Tag => "tag",
459        };
460
461        write!(out, "{label}: ")?;
462        write!(out.labeled(label), "{padded_symbol}")?;
463        writeln!(out, " [{import_status}] {tracking_status}")
464    }
465}
466
467enum TrackingStatus {
468    Tracked,
469    Untracked,
470    NotApplicable, // for tags
471}
472
473enum ImportStatus {
474    New,
475    Deleted,
476    Updated,
477}
478
479pub fn print_git_export_stats(ui: &Ui, stats: &GitExportStats) -> Result<(), std::io::Error> {
480    if !stats.failed_bookmarks.is_empty() {
481        writeln!(ui.warning_default(), "Failed to export some bookmarks:")?;
482        let mut formatter = ui.stderr_formatter();
483        for (symbol, reason) in &stats.failed_bookmarks {
484            write!(formatter, "  ")?;
485            write!(formatter.labeled("bookmark"), "{symbol}")?;
486            for err in iter::successors(Some(reason as &dyn error::Error), |err| err.source()) {
487                write!(formatter, ": {err}")?;
488            }
489            writeln!(formatter)?;
490        }
491    }
492    if !stats.failed_tags.is_empty() {
493        writeln!(ui.warning_default(), "Failed to export some tags:")?;
494        let mut formatter = ui.stderr_formatter();
495        for (symbol, reason) in &stats.failed_tags {
496            write!(formatter, "  ")?;
497            write!(formatter.labeled("tag"), "{symbol}")?;
498            for err in iter::successors(Some(reason as &dyn error::Error), |err| err.source()) {
499                write!(formatter, ": {err}")?;
500            }
501            writeln!(formatter)?;
502        }
503    }
504    if itertools::chain(&stats.failed_bookmarks, &stats.failed_tags)
505        .any(|(_, reason)| matches!(reason, FailedRefExportReason::FailedToSet(_)))
506    {
507        writedoc!(
508            ui.hint_default(),
509            r#"
510            Git doesn't allow a branch/tag name that looks like a parent directory of
511            another (e.g. `foo` and `foo/bar`). Try to rename the bookmarks/tags that failed
512            to export or their "parent" bookmarks/tags.
513            "#,
514        )?;
515    }
516    Ok(())
517}
518
519pub fn print_push_stats(ui: &Ui, stats: &GitPushStats) -> io::Result<()> {
520    if !stats.rejected.is_empty() {
521        writeln!(
522            ui.warning_default(),
523            "The following references unexpectedly moved on the remote:"
524        )?;
525        let mut formatter = ui.stderr_formatter();
526        for (reference, reason) in &stats.rejected {
527            write!(formatter, "  ")?;
528            write!(formatter.labeled("git_ref"), "{}", reference.as_symbol())?;
529            if let Some(r) = reason {
530                write!(formatter, " (reason: {r})")?;
531            }
532            writeln!(formatter)?;
533        }
534        drop(formatter);
535        writeln!(
536            ui.hint_default(),
537            "Try fetching from the remote, then make the bookmark point to where you want it to \
538             be, and push again.",
539        )?;
540    }
541    if !stats.remote_rejected.is_empty() {
542        writeln!(
543            ui.warning_default(),
544            "The remote rejected the following updates:"
545        )?;
546        let mut formatter = ui.stderr_formatter();
547        for (reference, reason) in &stats.remote_rejected {
548            write!(formatter, "  ")?;
549            write!(formatter.labeled("git_ref"), "{}", reference.as_symbol())?;
550            if let Some(r) = reason {
551                write!(formatter, " (reason: {r})")?;
552            }
553            writeln!(formatter)?;
554        }
555        drop(formatter);
556        writeln!(
557            ui.hint_default(),
558            "Try checking if you have permission to push to all the bookmarks."
559        )?;
560    }
561    if !stats.unexported_bookmarks.is_empty() {
562        writeln!(
563            ui.warning_default(),
564            "The following bookmarks couldn't be updated locally:"
565        )?;
566        let mut formatter = ui.stderr_formatter();
567        for (symbol, reason) in &stats.unexported_bookmarks {
568            write!(formatter, "  ")?;
569            write!(formatter.labeled("bookmark"), "{symbol}")?;
570            for err in iter::successors(Some(reason as &dyn error::Error), |err| err.source()) {
571                write!(formatter, ": {err}")?;
572            }
573            writeln!(formatter)?;
574        }
575    }
576    Ok(())
577}
578
579#[cfg(test)]
580mod tests {
581    use std::path::MAIN_SEPARATOR;
582
583    use insta::assert_snapshot;
584
585    use super::*;
586
587    #[test]
588    fn test_absolute_git_url() {
589        // gix::Url::canonicalize() works even if the path doesn't exist.
590        // However, we need to ensure that no symlinks exist at the test paths.
591        let temp_dir = testutils::new_temp_dir();
592        let cwd = dunce::canonicalize(temp_dir.path()).unwrap();
593        let cwd_slash = cwd.to_str().unwrap().replace(MAIN_SEPARATOR, "/");
594
595        // Local path
596        assert_eq!(
597            absolute_git_url(&cwd, "foo").unwrap(),
598            format!("{cwd_slash}/foo")
599        );
600        assert_eq!(
601            absolute_git_url(&cwd, r"foo\bar").unwrap(),
602            if cfg!(windows) {
603                format!("{cwd_slash}/foo/bar")
604            } else {
605                format!(r"{cwd_slash}/foo\bar")
606            }
607        );
608        assert_eq!(
609            absolute_git_url(&cwd.join("bar"), &format!("{cwd_slash}/foo")).unwrap(),
610            format!("{cwd_slash}/foo")
611        );
612
613        // rcp-like
614        assert_eq!(
615            absolute_git_url(&cwd, "git@example.org:foo/bar.git").unwrap(),
616            "git@example.org:foo/bar.git"
617        );
618        // URL
619        assert_eq!(
620            absolute_git_url(&cwd, "https://example.org/foo.git").unwrap(),
621            "https://example.org/foo.git"
622        );
623        // Custom scheme isn't an error
624        assert_eq!(
625            absolute_git_url(&cwd, "custom://example.org/foo.git").unwrap(),
626            "custom://example.org/foo.git"
627        );
628        // Password shouldn't be redacted (gix::Url::to_string() would do)
629        assert_eq!(
630            absolute_git_url(&cwd, "https://user:pass@example.org/").unwrap(),
631            "https://user:pass@example.org/"
632        );
633    }
634
635    #[test]
636    fn test_git_remote_url_to_web() {
637        let to_web = |s| git_remote_url_to_web(&gix::Url::try_from(s).unwrap());
638
639        // SSH URL
640        assert_eq!(
641            to_web("git@github.com:owner/repo"),
642            Some("https://github.com/owner/repo".to_owned())
643        );
644        // HTTPS URL with .git suffix
645        assert_eq!(
646            to_web("https://github.com/owner/repo.git"),
647            Some("https://github.com/owner/repo".to_owned())
648        );
649        // SSH URL with ssh:// scheme
650        assert_eq!(
651            to_web("ssh://git@github.com/owner/repo"),
652            Some("https://github.com/owner/repo".to_owned())
653        );
654        // git:// protocol
655        assert_eq!(
656            to_web("git://github.com/owner/repo.git"),
657            Some("https://github.com/owner/repo".to_owned())
658        );
659        // File URL returns None
660        assert_eq!(to_web("file:///path/to/repo"), None);
661        // Local path returns None
662        assert_eq!(to_web("/path/to/repo"), None);
663    }
664
665    #[test]
666    fn test_bar() {
667        let mut buf = String::new();
668        draw_progress(0.0, &mut buf, 10);
669        assert_eq!(buf, "          ");
670        buf.clear();
671        draw_progress(1.0, &mut buf, 10);
672        assert_eq!(buf, "██████████");
673        buf.clear();
674        draw_progress(0.5, &mut buf, 10);
675        assert_eq!(buf, "█████     ");
676        buf.clear();
677        draw_progress(0.54, &mut buf, 10);
678        assert_eq!(buf, "█████▍    ");
679        buf.clear();
680    }
681
682    #[test]
683    fn test_update() {
684        let start = Instant::now();
685        let mut progress = Progress::new(start);
686        let mut current_time = start;
687        let mut update = |duration, overall: u64| -> String {
688            current_time += duration;
689            let mut buf = vec![];
690            let mut output = ProgressOutput::for_test(&mut buf, 25);
691            progress
692                .update(
693                    current_time,
694                    &GitProgress {
695                        deltas: (overall, 100),
696                        objects: (0, 0),
697                        counted_objects: (0, 0),
698                        compressed_objects: (0, 0),
699                    },
700                    &mut output,
701                )
702                .unwrap();
703            String::from_utf8(buf).unwrap()
704        };
705        // First output is after the initial delay
706        assert_snapshot!(update(crate::progress::INITIAL_DELAY - Duration::from_millis(1), 1), @"");
707        assert_snapshot!(update(Duration::from_millis(1), 10), @"\u{1b}[?25l\r 10% [█▊                ]\u{1b}[K");
708        // No updates for the next 30 milliseconds
709        assert_snapshot!(update(Duration::from_millis(10), 11), @"");
710        assert_snapshot!(update(Duration::from_millis(10), 12), @"");
711        assert_snapshot!(update(Duration::from_millis(10), 13), @"");
712        // We get an update now that we go over the threshold
713        assert_snapshot!(update(Duration::from_millis(100), 30), @"\r 30% [█████▍            ]\u{1b}[K");
714        // Even though we went over by quite a bit, the new threshold is relative to the
715        // previous output, so we don't get an update here
716        assert_snapshot!(update(Duration::from_millis(30), 40), @"");
717    }
718}