diff --git a/CHANGELOG.md b/CHANGELOG.md index aac556f1..539ca871 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,46 @@ # Изменения +## 1.7.1 — 2026-10-25 + +Мелкий текст стал чётче, статус больших рабочих папок считается вдвое быстрее, а +открытие репозитория больше не задерживает интерфейс. Цифры измерены на Windows, +20 потоков. + +### Чёткий текст + +- Мелкий текст рисуется с вертикальным хинтингом и подъёмом контраста тонких + штрихов: высоты строчных и заглавных букв попадают на целые пиксели, тёмный + текст на светлом фоне стал плотнее. Ширины строк и раскладка не меняются. + Субпиксельное сглаживание не включается: в удалённом сеансе от него нет толку. + Для этого движок headless-gui обновлён до v3.43.0. + +### Скорость на больших рабочих папках + +- Статус папки на 50 тысяч файлов вместе с неизменёнными файлами (так его + запрашивает панель «Файлы») — 53 мс вместо 103 и 41 МБ вместо 122. Атрибуты + файлов берутся из кэша без построения правил заново, а для каждого файла + проверяется только то, нужен ли ему внешний фильтр. +- Каталог, где лежат отслеживаемые файлы, читается за скан один раз: поиск + неотслеживаемых файлов берёт уже прочитанный листинг. Статус 50 тысяч файлов — + 30 мс вместо 44. +- Открытие репозитория на 80 тысяч файлов задерживает интерфейс на 19 мс вместо + 250–440: первый снимок слежения за папкой делается в фоне, и проверка статуса + дожидается его, чтобы не пропустить изменения сразу после открытия. Новый список + игнорируемых каталогов передаётся работающему слежению, а не перезапускает его с + полным обходом папки. + +### Исправления + +- Подгрузка следующей страницы журнала больше не сбрасывает выделенный коммит и не + перестраивает всю таблицу. +- В Blame коммит открывается одним щелчком по его ссылке, над ней курсор-рука. +- Защищённое соединение по медленной сети ждёт минуту вместо 15 секунд, а таймер + ответа сервера запускается только после отправки запроса. Если соединение так и не + установилось, Go.Git пишет об этом прямо, а не «context deadline exceeded». +- На Windows коммит, сделанный сразу после того, как git или антивирус отпустили + `packed-refs.lock`, больше не падает с «Access is denied»: пока система + дозакрывает старый файл, Go.Git ждёт до секунды, как и при занятом замке. + ## 1.7.0 — 2026-10-16 Релиз про скорость: статус, журнал, счётчики веток и чтение объектов на больших diff --git a/README.en.md b/README.en.md index e4c8ee74..cd8bf2ff 100644 --- a/README.en.md +++ b/README.en.md @@ -17,7 +17,7 @@ interface. An alternative to the paid SmartGit. window; the layout is remembered. - Localization: Russian and English out of the box, any other language is a single JSON file. -## What 1.7.0 can already do +## What 1.7.1 can already do **Interface.** The menu and toolbar mirror SmartGit; the toolbar is configured in a separate window and stored in `config.toml`. Dock panels: @@ -83,8 +83,7 @@ what to look at when something goes wrong: [USER_GUIDE.md](USER_GUIDE.md) ## What is still missing -Horizontal scrolling in the compare and conflict-resolution windows (waiting -on the engine), the GitHub and Jira integrations, `core.sharedRepository`. +The GitHub and Jira integrations, `core.sharedRepository`. The order of work is in docs/RELEASE_PLAN.md. ## Building diff --git a/README.md b/README.md index d43c8a10..d9d65801 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ раскладка запоминается. - Локализация: русский и английский из коробки, любой другой язык — один JSON-файл. -## Что уже умеет 1.7.0 +## Что уже умеет 1.7.1 **Интерфейс.** Меню и панель инструментов повторяют SmartGit; панель настраивается в отдельном окне и хранится в `config.toml`. Док-панели: @@ -82,8 +82,7 @@ Windows, Secret Service на Linux, мастер-пароль или файл к ## Чего ещё нет -Горизонтальная прокрутка в окнах сравнения и разрешения конфликтов (ждём -движок), интеграция с GitHub и Jira, `core.sharedRepository`. +Интеграция с GitHub и Jira, `core.sharedRepository`. Порядок работ — в docs/RELEASE_PLAN.md. ## Сборка diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index fa153ae0..a394e68d 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,58 +1,44 @@ -# Go.Git 1.7.0 — Speed +# Go.Git 1.7.1 — Sharper text, faster big working trees -Status, the journal, branch counters and object reading are noticeably faster on -big repositories, and Go.Git now writes the commit graph itself. +Small text is sharper, the status of a big working tree takes half the time, and +opening a repository no longer holds up the interface. All numbers below were measured on Windows with a 20-thread processor. -## Working tree status - -- Status of a repository with 50 thousand files takes 0.12 s instead of 5.1 s. - Almost all the time went into stating each file through a path that is opened - component by component. A directory is now read once and its files are described - from that listing; only small directories and files missing from a listing are - stated one by one. -- The index is compared with HEAD through the cache tree: if a directory has the - same tree as in HEAD, it is not read at all. With nothing staged, no tree below - the root is read. -- Untracked directories are walked in parallel, each read once. With 20 thousand - untracked files the status takes 23 ms instead of 46 ms, with 20 thousand ignored - files 24 ms instead of 76 ms. The ignore and attribute matchers no longer wait for - each other behind a lock. - -## Journal and history - -- If a repository has no commit graph, Go.Git writes it in the background after the - repository is opened. With a graph the journal streams its first page instead of - walking the whole history. The settings `core.commitGraph` and - `gc.writeCommitGraph` are honoured, and shallow clones are left alone. -- Parsing a commit makes almost four times fewer allocations: a walk over 10 thousand commits goes - from 330 thousand allocations to 90 thousand and from 12.1 ms to 7.5 ms. -- The journal hands its rows to the grid once per page instead of copying them - twice: with 100 thousand rows 65 ms instead of 127 ms and 284 MB instead of 635 MB. -- A refresh no longer restarts the journal when no branch, tag or remote moved. - -## Branch counters - -- The ahead and behind counters are computed once for each pair of branch tips and - remembered, so a refresh recounts only the branches that moved. All walks of one - computation share the commits they have parsed, and the counting reuses the open - repository and its cached commit graph. - -## Objects and references - -- Pack indexes keep their name table in memory and, together with packfiles, are - read through a memory mapping on Windows and Linux (with a fallback to plain - reads). Looking an object up in a pack index takes about 70 ns. -- `packed-refs` is parsed once while the file does not change instead of on every - miss. -- A missing object no longer rescans the pack directory when it has not changed. -- The pack that answered last is searched first; the decompression buffers are - pooled; the parsed object cache sweeps dead entries lazily; the raw object cache - is split into shards so parallel readers stop sharing one lock. - -## Diagnostics - -- `GOGIT_TRACE_STARTUP=1` writes the startup steps with their time since the process - start into `gogit.log`: logger opened, application built, repository opened, - window started, first journal page and working tree status shown. +## Sharper text + +- Small text is drawn with vertical hinting and a contrast boost for thin strokes: + the heights of lowercase and capital letters land on whole pixels, and dark text + on a light background looks denser. Line widths and layout do not change. + Subpixel smoothing stays off because it is useless in a remote session. The + headless-gui engine is updated to v3.43.0 for this. + +## Big working trees + +- Status of a working tree with 50 thousand files, unchanged files included (the + way the Files pane asks for it), takes 53 ms instead of 103 ms and 41 MB instead + of 122 MB. File attributes come from the cache without rebuilding the rule stack, + and for every file only the question of whether it needs an external filter is + asked. +- A directory with tracked files is read once per scan: the search for untracked + files reuses the listing that was already read. Status of 50 thousand files takes + 30 ms instead of 44 ms. +- Opening a repository with 80 thousand files holds up the interface for 19 ms + instead of 250–440 ms. The working tree watcher takes its first snapshot in the + background, and the status scan waits for it so that no change made right after + opening is lost. A new set of ignored directories reaches the running watcher + instead of restarting it with a full walk of the tree. + +## Fixes + +- Loading the next page of the journal no longer drops the selected commit or + rebuilds the whole table. +- In Blame a commit opens with a single click on its link, and the cursor turns + into a hand over it. +- A secure connection over a slow network waits a minute instead of 15 seconds, and + the server response timer starts only after the request is sent. When the + connection never comes up, Go.Git says so instead of "context deadline exceeded". +- On Windows a commit made right after git or a virus scanner let go of + `packed-refs.lock` no longer fails with "Access is denied": while the system is + still closing the old file, Go.Git waits up to a second, as it does for a busy + lock. diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 6717a633..866c7ad3 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -259,7 +259,8 @@ git-клиентом (или из консоли), Go.Git тоже обнару **Кто менял строки** (Blame) — из контекстного меню файла или кнопки «Кто менял» на панели инструментов: список строк файла с автором, коммитом, временем и текстом; выбор строки показывает, из какого коммита она пришла, и -может передать выделение в Investigate. **Исследовать** (Investigate, +может передать выделение в Investigate; щелчок по ссылке коммита открывает +этот коммит. **Исследовать** (Investigate, `git log -L`) — история изменений именно выбранных строк, доступна из списка файлов, из панели «Изменения» и из Blame; список найденных коммитов можно остановить кнопкой «Остановить», не дожидаясь конца истории. diff --git a/cmd/gogit/winres/winres.json b/cmd/gogit/winres/winres.json index ee0cbb56..def0c670 100644 --- a/cmd/gogit/winres/winres.json +++ b/cmd/gogit/winres/winres.json @@ -11,7 +11,7 @@ "0409": { "identity": { "name": "Go.Git", - "version": "1.7.0.0" + "version": "1.7.1.0" }, "description": "Go.Git git client", "minimum-os": "win7", @@ -35,8 +35,8 @@ "#1": { "0000": { "fixed": { - "file_version": "1.7.0.0", - "product_version": "1.7.0.0" + "file_version": "1.7.1.0", + "product_version": "1.7.1.0" }, "info": { "0409": { diff --git a/go.mod b/go.mod index bace6c1a..911ff399 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/BurntSushi/toml v1.6.0 github.com/godbus/dbus/v5 v5.2.2 github.com/jcmturner/gokrb5/v8 v8.4.4 - github.com/oops1/headless-gui/v3 v3.35.1 + github.com/oops1/headless-gui/v3 v3.43.0 golang.org/x/crypto v0.56.0 golang.org/x/sys v0.47.0 golang.org/x/text v0.41.0 diff --git a/go.sum b/go.sum index ec7b8f42..ee101645 100644 --- a/go.sum +++ b/go.sum @@ -30,14 +30,12 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6 github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= -github.com/oops1/headless-gui/v3 v3.23.0 h1:4GEXBzab3jIsvXf8xJsWdDzIc3L5wkFW89uQxkjbLls= -github.com/oops1/headless-gui/v3 v3.23.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= -github.com/oops1/headless-gui/v3 v3.25.0 h1:eWyw/UHozczW62RJbr3UGVAFmKGpgMypwyw4cLbQ2X8= -github.com/oops1/headless-gui/v3 v3.25.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= -github.com/oops1/headless-gui/v3 v3.26.0 h1:G4/I3vOhmImyzctsnvG2qTrDwEbMCwiCtcndPosSNnQ= -github.com/oops1/headless-gui/v3 v3.26.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= -github.com/oops1/headless-gui/v3 v3.35.1 h1:3NmKdX2yUIatqdP+GFfNDXbBWi7F201gfivHzoq5SKc= -github.com/oops1/headless-gui/v3 v3.35.1/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= +github.com/oops1/headless-gui/v3 v3.39.0 h1:a7wJdqsR+yhjSJrSVgD9bWVchDa+oeu7LiP45eQUwrc= +github.com/oops1/headless-gui/v3 v3.39.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= +github.com/oops1/headless-gui/v3 v3.42.0 h1:meVrKaf7DSzJA/HuyjN3KdKs6XenzOXARWqi5QWPPv8= +github.com/oops1/headless-gui/v3 v3.42.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= +github.com/oops1/headless-gui/v3 v3.43.0 h1:qY/PhHjndWu4CMXCAcgqSrqVlQ0z7hV8FeC34jVhhXo= +github.com/oops1/headless-gui/v3 v3.43.0/go.mod h1:KfrQeckxm94JygZq21eM6fpaQCYhUkL1vrb71WY5to8= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/internal/app/app.go b/internal/app/app.go index 7f0de815..34d6cb11 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -417,6 +417,7 @@ func NewFromXAML(cfg *config.Config, paths config.Paths, xaml []byte, log *slog. root.Title = i18n.T("App.Title") a.eng = engine.New(cfg.Window.Width, cfg.Window.Height, targetFPS) + a.eng.SetTextQuality(engine.TextQuality{Hinting: true, Contrast: engine.DefaultTextContrast}) a.eng.SetRoot(root) a.eng.SetOnModalClosed(func(widget.ModalWidget) { a.releaseClosedDialogs() }) a.startPostQueue() diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 0052b04c..8e3a3d99 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/oops1/headless-gui/v3/engine" "github.com/oops1/headless-gui/v3/widget" "github.com/oops1/gogit/internal/config" @@ -58,6 +59,14 @@ func TestNewLoadsMainWindow(t *testing.T) { } } +func TestNewTurnsOnHintedHighContrastText(t *testing.T) { + a := newTestApp(t) + got := a.Engine().TextQuality() + if !got.Hinting || got.Contrast != engine.DefaultTextContrast || got.LCD { + t.Fatalf("text quality = %+v, want hinting with default contrast and no LCD", got) + } +} + func TestMenuStructure(t *testing.T) { a := newTestApp(t) items := a.menu.Items() diff --git a/internal/app/transporterrors.go b/internal/app/transporterrors.go index 95c9135c..6c43df73 100644 --- a/internal/app/transporterrors.go +++ b/internal/app/transporterrors.go @@ -25,6 +25,7 @@ var transportErrorKeys = []struct { {transport.ErrProtocolNotAllowed, "Operation.Error.ProtocolNotAllowed"}, {transport.ErrProxyAuthRequired, "Operation.Error.ProxyAuthRequired"}, {transport.ErrTLSConfig, "Operation.Error.TLSConfig"}, + {transport.ErrTLSHandshakeTimeout, "Operation.Error.TLSHandshakeTimeout"}, } func localizeOperationError(err error) error { diff --git a/internal/app/watch.go b/internal/app/watch.go index fd9fdd27..3b91a45e 100644 --- a/internal/app/watch.go +++ b/internal/app/watch.go @@ -14,6 +14,8 @@ type watcherIface interface { Poke() Pause() Resume() + Ready() <-chan struct{} + SetSkipDirs(dirs []string) } func newRealWatcher(layout gitrepo.Layout, opts watch.Options) watcherIface { @@ -50,14 +52,30 @@ func (a *App) ignoredDirectories() []string { } func (a *App) syncWatcherSkips() { + skip := a.ignoredDirectories() a.watchMu.Lock() - current := a.watchSkip - running := a.watcher != nil + w := a.watcher + changed := w != nil && !slices.Equal(a.watchSkip, skip) + if changed { + a.watchSkip = skip + } a.watchMu.Unlock() - if !running || slices.Equal(current, a.ignoredDirectories()) { + if changed { + w.SetSkipDirs(skip) + } +} + +func (a *App) waitForWatcherBaseline(ctx context.Context) { + a.watchMu.Lock() + w := a.watcher + a.watchMu.Unlock() + if w == nil { return } - a.restartWatcherForCurrentRepository() + select { + case <-ctx.Done(): + case <-w.Ready(): + } } func (a *App) runWatcher(ctx context.Context, w watcherIface) { diff --git a/internal/app/watch_test.go b/internal/app/watch_test.go index 921bcc82..a840b50b 100644 --- a/internal/app/watch_test.go +++ b/internal/app/watch_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "slices" + "sync" "sync/atomic" "testing" "time" @@ -25,14 +26,33 @@ import ( type fakeWatcher struct { changes chan watch.ChangeSet started chan struct{} + ready chan struct{} stopped atomic.Bool pokes atomic.Int32 pauses atomic.Int32 resumes atomic.Int32 + skipsMu sync.Mutex + skips [][]string } func newFakeWatcher() *fakeWatcher { - return &fakeWatcher{changes: make(chan watch.ChangeSet, 4), started: make(chan struct{})} + ready := make(chan struct{}) + close(ready) + return &fakeWatcher{changes: make(chan watch.ChangeSet, 4), started: make(chan struct{}), ready: ready} +} + +func (w *fakeWatcher) Ready() <-chan struct{} { return w.ready } + +func (w *fakeWatcher) SetSkipDirs(dirs []string) { + w.skipsMu.Lock() + w.skips = append(w.skips, slices.Clone(dirs)) + w.skipsMu.Unlock() +} + +func (w *fakeWatcher) skipUpdates() [][]string { + w.skipsMu.Lock() + defer w.skipsMu.Unlock() + return slices.Clone(w.skips) } func (w *fakeWatcher) Run(ctx context.Context) iter.Seq[watch.ChangeSet] { @@ -592,3 +612,83 @@ func TestWatcherSkipsTheDirectoriesGitIgnores(t *testing.T) { time.Sleep(20 * time.Millisecond) } } + +func TestAnIgnoredDirectoryReachesTheRunningWatcherWithoutRestartingIt(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "main") + buildWorkingRepoFixture(t, target) + if err := writeFile(target, ".gitignore", "out/\n"); err != nil { + t.Fatal(err) + } + if err := writeFile(filepath.Join(target, "out"), "build.log", "x\n"); err != nil { + t.Fatal(err) + } + cfg := config.Default() + cfg.Repositories = []config.Repository{{ID: "r1", Name: "Main", Path: target}} + a := newTestAppWithConfig(t, cfg) + var started atomic.Int32 + fw := newFakeWatcher() + a.newWatcher = func(gitrepo.Layout, watch.Options) watcherIface { + started.Add(1) + return fw + } + + a.ActivateRepository("r1") + waitForWorkingIdle(t, a) + + updates := fw.skipUpdates() + if len(updates) != 1 || !slices.Contains(updates[0], "out") { + t.Fatalf("skip updates = %v, want one carrying the ignored directory", updates) + } + if got := started.Load(); got != 1 { + t.Fatalf("watchers started = %d, want the first one kept running", got) + } +} + +func TestTheWorkingScanWaitsUntilTheWatcherHasItsBaseline(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "main") + buildWorkingRepoFixture(t, target) + cfg := config.Default() + cfg.Repositories = []config.Repository{{ID: "r1", Name: "Main", Path: target}} + a := newTestAppWithConfig(t, cfg) + fw := newFakeWatcher() + fw.ready = make(chan struct{}) + a.newWatcher = func(gitrepo.Layout, watch.Options) watcherIface { return fw } + + a.ActivateRepository("r1") + time.Sleep(50 * time.Millisecond) + if rows := filesRowCountOnDispatcher(t, a); rows != 0 { + t.Fatalf("the files grid shows %d rows before the watcher baseline, want none", rows) + } + + close(fw.ready) + waitForWorkingRows(t, a, 5) +} + +func TestStoppingTheWorkingScanReleasesAWaitForTheWatcherBaseline(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "main") + buildWorkingRepoFixture(t, target) + cfg := config.Default() + cfg.Repositories = []config.Repository{{ID: "r1", Name: "Main", Path: target}} + a := newTestAppWithConfig(t, cfg) + fw := newFakeWatcher() + fw.ready = make(chan struct{}) + a.newWatcher = func(gitrepo.Layout, watch.Options) watcherIface { return fw } + a.ActivateRepository("r1") + + stopped := make(chan struct{}) + go func() { + a.stopWorking() + close(stopped) + }() + + waitForChannel(t, stopped, "the working scan stop") +} + +func TestWaitingForTheWatcherBaselineWithoutAWatcherReturnsAtOnce(t *testing.T) { + a := newTestApp(t) + + a.waitForWatcherBaseline(t.Context()) +} diff --git a/internal/app/working.go b/internal/app/working.go index 7a1674ee..f03e7bda 100644 --- a/internal/app/working.go +++ b/internal/app/working.go @@ -103,6 +103,7 @@ func (a *App) stopWorkingLocked() { func (a *App) runWorking(ctx context.Context, wt *worktree.Worktree) { defer a.finishWorking() + a.waitForWatcherBaseline(ctx) status, err := wt.Status(ctx) if err != nil { if !errors.Is(err, context.Canceled) { diff --git a/internal/app/working_diff_test.go b/internal/app/working_diff_test.go index f3cf1801..f8070d07 100644 --- a/internal/app/working_diff_test.go +++ b/internal/app/working_diff_test.go @@ -177,6 +177,17 @@ func TestBlobVsWorktreeDiffFailsWhenTheContextIsAlreadyCancelled(t *testing.T) { } } +func TestBlobVsWorktreeDiffFailsWhenTheWorkingFileCannotBeRead(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "main") + initTestRepoWithBranch(t, target, "main") + o := openTestRepository(t, target) + + if _, err := blobVsWorktreeDiff(t.Context(), o, "../outside.txt", hash.Zero); !errors.Is(err, worktree.ErrReadWorkingTree) { + t.Fatalf("blobVsWorktreeDiff returned error %v, want ErrReadWorkingTree", err) + } +} + func TestRunWorkingDiffLogsAWarningForARealError(t *testing.T) { widget.ClearStrings() t.Cleanup(widget.ClearStrings) diff --git a/internal/assets/i18n/en.json b/internal/assets/i18n/en.json index 591b2ee2..24dff7b6 100644 --- a/internal/assets/i18n/en.json +++ b/internal/assets/i18n/en.json @@ -1160,6 +1160,7 @@ "Operation.Error.ProtocolNotAllowed": "The protocol of this address is forbidden by protocol.allow or GIT_ALLOW_PROTOCOL", "Operation.Error.ProxyAuthRequired": "The proxy requires authentication", "Operation.Error.TLSConfig": "The TLS settings http.sslCAInfo, http.sslCAPath, http.sslCert or http.sslKey cannot be used", + "Operation.Error.TLSHandshakeTimeout": "The secure connection to the server was not established in time: the network or proxy is too slow", "Operation.Log.AttributionRemoved": "Attribution removed from commits: %d", "Operation.Log.Canceling": "Cancel requested…", "Operation.Log.Checkout": "Checking out…", diff --git a/internal/assets/i18n/ru.json b/internal/assets/i18n/ru.json index 7fe5aa10..4f33c761 100644 --- a/internal/assets/i18n/ru.json +++ b/internal/assets/i18n/ru.json @@ -1160,6 +1160,7 @@ "Operation.Error.ProtocolNotAllowed": "Протокол этого адреса запрещён настройкой protocol.allow или GIT_ALLOW_PROTOCOL", "Operation.Error.ProxyAuthRequired": "Прокси требует аутентификации", "Operation.Error.TLSConfig": "Настройки TLS http.sslCAInfo, http.sslCAPath, http.sslCert или http.sslKey нельзя применить", + "Operation.Error.TLSHandshakeTimeout": "Защищённое соединение с сервером не установилось вовремя: сеть или прокси слишком медленные", "Operation.Log.AttributionRemoved": "Атрибуция убрана из коммитов: %d", "Operation.Log.Canceling": "Отмена запрошена…", "Operation.Log.Checkout": "Переключение…", diff --git a/internal/gitcore/attributes/attributes.go b/internal/gitcore/attributes/attributes.go index f97994bf..379ec648 100644 --- a/internal/gitcore/attributes/attributes.go +++ b/internal/gitcore/attributes/attributes.go @@ -198,12 +198,17 @@ type attrNode struct { err error } +type resolvedValues struct { + values map[string]Value + err error +} + type Attributes struct { opts AttributeOptions perDir *fileCache[attrLine] globalFiles *fileCache[attrLine] nodes map[string]*attrNode - resolved map[string]map[string]Value + resolved map[string]resolvedValues globals [][]attrLine globalErr error globalsOnce sync.Once @@ -225,7 +230,7 @@ func New(opts AttributeOptions) *Attributes { return parseAttributesFile(source, "", data, true) }), nodes: map[string]*attrNode{}, - resolved: map[string]map[string]Value{}, + resolved: map[string]resolvedValues{}, } } @@ -313,7 +318,6 @@ func fillStates(out map[string]Value, states []attrState, macros map[string][]at func (a *Attributes) Lookup(path string) (map[string]Value, error) { clean, isDir := normalizePath(path) - lists, err := a.stack(parentDir(clean)) key := clean if isDir { key += "/" @@ -322,8 +326,9 @@ func (a *Attributes) Lookup(path string) (map[string]Value, error) { cached, ok := a.resolved[key] a.resolvedMu.Unlock() if ok { - return cached, err + return cached.values, cached.err } + lists, err := a.stack(parentDir(clean)) macros := determineMacros(lists) out := map[string]Value{} for _, list := range lists { @@ -336,11 +341,16 @@ func (a *Attributes) Lookup(path string) (map[string]Value, error) { } } a.resolvedMu.Lock() - a.resolved[key] = out + a.resolved[key] = resolvedValues{values: out, err: err} a.resolvedMu.Unlock() return out, err } +func (a *Attributes) value(path, name string) Value { + all, _ := a.Lookup(path) + return all[name] +} + func (a *Attributes) Get(path string, names ...string) map[string]Value { all, _ := a.Lookup(path) if len(names) == 0 { @@ -356,7 +366,7 @@ func (a *Attributes) Get(path string, names ...string) map[string]Value { } func (a *Attributes) Binary(path string) bool { - return a.Get(path, "diff")["diff"].IsUnset() + return a.value(path, "diff").IsUnset() } func driverName(v Value) string { @@ -366,8 +376,6 @@ func driverName(v Value) string { return "" } -func (a *Attributes) Diff(path string) string { return driverName(a.Get(path, "diff")["diff"]) } -func (a *Attributes) Merge(path string) string { return driverName(a.Get(path, "merge")["merge"]) } -func (a *Attributes) Filter(path string) string { - return driverName(a.Get(path, "filter")["filter"]) -} +func (a *Attributes) Diff(path string) string { return driverName(a.value(path, "diff")) } +func (a *Attributes) Merge(path string) string { return driverName(a.value(path, "merge")) } +func (a *Attributes) Filter(path string) string { return driverName(a.value(path, "filter")) } diff --git a/internal/gitcore/attributes/attributes_test.go b/internal/gitcore/attributes/attributes_test.go index 63005939..1768f8b3 100644 --- a/internal/gitcore/attributes/attributes_test.go +++ b/internal/gitcore/attributes/attributes_test.go @@ -2,6 +2,7 @@ package attributes import ( "errors" + "maps" "slices" "strings" "testing" @@ -318,6 +319,18 @@ func TestLookupReportsAttributeLoaderErrors(t *testing.T) { } } +func TestLookupAnsweredFromTheCacheStillReportsTheLoaderError(t *testing.T) { + attrs := New(AttributeOptions{Work: failingLoader("sub/.gitattributes")}) + first, firstErr := attrs.Lookup("sub/x.txt") + again, againErr := attrs.Lookup("sub/x.txt") + if !errors.Is(firstErr, errLoader) || !errors.Is(againErr, errLoader) { + t.Fatalf("Lookup errors = %v then %v, want %v both times", firstErr, againErr, errLoader) + } + if !maps.Equal(first, again) { + t.Fatalf("a cached Lookup returned %v, want %v", again, first) + } +} + func TestBinaryAndDriverHelpersReadAttributes(t *testing.T) { attrs := testAttributes(map[string]string{ ".gitattributes": "*.bin binary\n*.c diff=cpp merge=union filter=indent\n*.txt diff\n", diff --git a/internal/gitcore/attributes/bench_test.go b/internal/gitcore/attributes/bench_test.go index 34b46785..0ec80cce 100644 --- a/internal/gitcore/attributes/bench_test.go +++ b/internal/gitcore/attributes/bench_test.go @@ -90,3 +90,24 @@ func BenchmarkAttributesGet(b *testing.B) { } } } + +func BenchmarkAttributesPolicyOnAWarmCache(b *testing.B) { + paths := benchmarkPaths() + files := map[string]string{ + ".gitattributes": "* text=auto\n*.o binary\n*.bin filter=lfs -text\n", + } + for dir := range 20 { + files[fmt.Sprintf("dir%02d/.gitattributes", dir)] = "*.bak -text\n*.tmp ident\n" + } + attrs := New(AttributeOptions{Work: MemoryLoader(files)}) + for _, path := range paths { + attrs.Policy(path.Name) + } + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + for _, path := range paths { + attrs.Policy(path.Name) + } + } +} diff --git a/internal/gitcore/attributes/convert.go b/internal/gitcore/attributes/convert.go index 45f40f72..37ffc076 100644 --- a/internal/gitcore/attributes/convert.go +++ b/internal/gitcore/attributes/convert.go @@ -110,7 +110,11 @@ func eolFromValue(v Value) Conversion { } func (a *Attributes) Text(path string) TextPolicy { - values := a.Get(path, "text", "crlf", "eol") + values, _ := a.Lookup(path) + return a.textOf(values) +} + +func (a *Attributes) textOf(values map[string]Value) TextPolicy { action := crlfFromValue(values["text"]) if action == CRLFUndefined { action = crlfFromValue(values["crlf"]) diff --git a/internal/gitcore/attributes/diffdriver.go b/internal/gitcore/attributes/diffdriver.go index 48ba88c7..706659e7 100644 --- a/internal/gitcore/attributes/diffdriver.go +++ b/internal/gitcore/attributes/diffdriver.go @@ -3,7 +3,7 @@ package attributes import "strings" func (a *Attributes) DiffBinary(path string) (binary bool, known bool) { - value := a.Get(path, "diff")["diff"] + value := a.value(path, "diff") cfg := a.opts.Config switch { case value.IsUnset(): diff --git a/internal/gitcore/attributes/lfssmudge_test.go b/internal/gitcore/attributes/lfssmudge_test.go index ae6af3b6..cde4054b 100644 --- a/internal/gitcore/attributes/lfssmudge_test.go +++ b/internal/gitcore/attributes/lfssmudge_test.go @@ -67,10 +67,14 @@ func TestPolicyClassifiesSmudgeDrivers(t *testing.T) { if tc.config != "" { opts.Config = loadConfig(t, tc.config) } - policy := testAttributes(attrs, opts).Policy(tc.path) + set := testAttributes(attrs, opts) + policy := set.Policy(tc.path) if policy.Clean != tc.clean || policy.Smudge != tc.smudge || policy.SkipSmudge != tc.skip || policy.FilterUnsupported() != tc.unsupported { t.Fatalf("Policy(%q) = clean %d smudge %d skip %v unsupported %v", tc.path, policy.Clean, policy.Smudge, policy.SkipSmudge, policy.FilterUnsupported()) } + if got := set.FilterUnsupported(tc.path); got != tc.unsupported { + t.Fatalf("FilterUnsupported(%q) = %v, want %v as the policy says", tc.path, got, tc.unsupported) + } }) } } diff --git a/internal/gitcore/attributes/pipeline.go b/internal/gitcore/attributes/pipeline.go index aabc1b38..a6ae27bb 100644 --- a/internal/gitcore/attributes/pipeline.go +++ b/internal/gitcore/attributes/pipeline.go @@ -41,13 +41,12 @@ type Policy struct { } func (a *Attributes) Policy(path string) Policy { - values := a.Get(path, "ident", "filter", "working-tree-encoding") + values, _ := a.Lookup(path) filter := driverName(values["filter"]) - clean, _ := a.filterDriver(filter, "clean", lfsCleanCommands) - smudge, skip := a.filterDriver(filter, "smudge", lfsSmudgeCommands) + clean, smudge, skip := a.filterDrivers(filter) return Policy{ Path: path, - Text: a.Text(path), + Text: a.textOf(values), Ident: values["ident"].IsSet(), Encoding: values["working-tree-encoding"], Filter: filter, @@ -58,6 +57,17 @@ func (a *Attributes) Policy(path string) Policy { } } +func (a *Attributes) FilterUnsupported(path string) bool { + clean, smudge, _ := a.filterDrivers(driverName(a.value(path, "filter"))) + return unsupportedFilter(clean, smudge) +} + +func (a *Attributes) filterDrivers(name string) (clean, smudge FilterKind, skipSmudge bool) { + clean, _ = a.filterDriver(name, "clean", lfsCleanCommands) + smudge, skipSmudge = a.filterDriver(name, "smudge", lfsSmudgeCommands) + return clean, smudge, skipSmudge +} + func (a *Attributes) filterDriver(name, capability string, single map[string]bool) (FilterKind, bool) { cfg := a.opts.Config if name == "" || cfg == nil { @@ -84,7 +94,11 @@ func isLFSExtension(subsection string) bool { } func (p Policy) FilterUnsupported() bool { - return p.Clean == FilterExternal || p.Smudge == FilterExternal + return unsupportedFilter(p.Clean, p.Smudge) +} + +func unsupportedFilter(clean, smudge FilterKind) bool { + return clean == FilterExternal || smudge == FilterExternal } func (p Policy) filterError() error { diff --git a/internal/gitcore/refs/helpers_test.go b/internal/gitcore/refs/helpers_test.go index 85132d46..e0005c09 100644 --- a/internal/gitcore/refs/helpers_test.go +++ b/internal/gitcore/refs/helpers_test.go @@ -241,3 +241,20 @@ func swapWrite(t *testing.T, after int, err error) { } t.Cleanup(func() { fsWrite = previous }) } + +func swapOpenFile(t *testing.T, fail func(name string, call int) bool, err error) *int { + t.Helper() + previous := fsOpenFile + calls := new(int) + fsOpenFile = func(root *os.Root, name string, flag int, perm fs.FileMode) (*os.File, error) { + if strings.HasSuffix(filepath.ToSlash(name), packedRefsFile+lockSuffix) { + *calls++ + if fail(filepath.ToSlash(name), *calls) { + return nil, &fs.PathError{Op: "open", Path: name, Err: err} + } + } + return previous(root, name, flag, perm) + } + t.Cleanup(func() { fsOpenFile = previous }) + return calls +} diff --git a/internal/gitcore/refs/lockrelease_linux.go b/internal/gitcore/refs/lockrelease_linux.go new file mode 100644 index 00000000..ec2bd1c5 --- /dev/null +++ b/internal/gitcore/refs/lockrelease_linux.go @@ -0,0 +1,5 @@ +package refs + +func lockMayBeReleasing(error) bool { + return false +} diff --git a/internal/gitcore/refs/lockrelease_linux_test.go b/internal/gitcore/refs/lockrelease_linux_test.go new file mode 100644 index 00000000..2615a7d3 --- /dev/null +++ b/internal/gitcore/refs/lockrelease_linux_test.go @@ -0,0 +1,21 @@ +package refs + +import ( + "errors" + "syscall" + "testing" +) + +func TestLockPackedGivesUpAtOnceWhenAccessIsDenied(t *testing.T) { + store := openStore(t, newGitDir(t)) + calls := swapOpenFile(t, func(string, int) bool { return true }, syscall.EACCES) + + _, err := store.lockPacked() + + if !errors.Is(err, ErrWriteFailed) || !errors.Is(err, syscall.EACCES) { + t.Fatalf("lockPacked returned %v, want the write failure with access denied", err) + } + if *calls != 1 { + t.Fatalf("lockPacked tried %d times, want a single attempt", *calls) + } +} diff --git a/internal/gitcore/refs/lockrelease_windows.go b/internal/gitcore/refs/lockrelease_windows.go new file mode 100644 index 00000000..03939650 --- /dev/null +++ b/internal/gitcore/refs/lockrelease_windows.go @@ -0,0 +1,11 @@ +package refs + +import ( + "errors" + + "golang.org/x/sys/windows" +) + +func lockMayBeReleasing(err error) bool { + return errors.Is(err, windows.ERROR_ACCESS_DENIED) +} diff --git a/internal/gitcore/refs/lockrelease_windows_test.go b/internal/gitcore/refs/lockrelease_windows_test.go new file mode 100644 index 00000000..d874e7c3 --- /dev/null +++ b/internal/gitcore/refs/lockrelease_windows_test.go @@ -0,0 +1,46 @@ +package refs + +import ( + "errors" + "testing" + "time" + + "golang.org/x/sys/windows" +) + +func TestLockPackedWaitsWhileTheReleasedLockIsStillBeingDeleted(t *testing.T) { + store := openStore(t, newGitDir(t)) + calls := swapOpenFile(t, func(_ string, call int) bool { return call <= 3 }, windows.ERROR_ACCESS_DENIED) + + lock, err := store.lockPacked() + + if err != nil { + t.Fatalf("lockPacked returned %v while the old lock was only being deleted", err) + } + lock.release() + if *calls != 4 { + t.Fatalf("lockPacked tried %d times, want three refusals and one success", *calls) + } +} + +func TestLockPackedReportsAnAccessDeniedThatOutlastsTheTimeout(t *testing.T) { + store := openStore(t, newGitDir(t)) + shortenPackedLockTimeout(t, 30*time.Millisecond) + calls := swapOpenFile(t, func(string, int) bool { return true }, windows.ERROR_ACCESS_DENIED) + + _, err := store.lockPacked() + + if !errors.Is(err, ErrWriteFailed) || !errors.Is(err, windows.ERROR_ACCESS_DENIED) || errors.Is(err, ErrLocked) { + t.Fatalf("lockPacked returned %v, want the write failure with access denied", err) + } + if *calls < 2 { + t.Fatalf("lockPacked tried %d times, want it to retry before giving up", *calls) + } +} + +func shortenPackedLockTimeout(t *testing.T, d time.Duration) { + t.Helper() + previous := packedLockTimeout + packedLockTimeout = d + t.Cleanup(func() { packedLockTimeout = previous }) +} diff --git a/internal/gitcore/refs/transaction.go b/internal/gitcore/refs/transaction.go index 6ba8e434..80a48fef 100644 --- a/internal/gitcore/refs/transaction.go +++ b/internal/gitcore/refs/transaction.go @@ -370,7 +370,8 @@ func (s *Store) lockPacked() (*lockFile, error) { deadline := time.Now().Add(packedLockTimeout) for { lock, err := newLock(s.common, packedRefsFile) - if !errors.Is(err, ErrLocked) || time.Now().After(deadline) { + busy := errors.Is(err, ErrLocked) || err != nil && lockMayBeReleasing(err) + if !busy || time.Now().After(deadline) { return lock, err } time.Sleep(10 * time.Millisecond) diff --git a/internal/gitcore/refs/tree.go b/internal/gitcore/refs/tree.go index 1bcfaea6..6e3d98fa 100644 --- a/internal/gitcore/refs/tree.go +++ b/internal/gitcore/refs/tree.go @@ -21,6 +21,9 @@ var ( fsRename = func(root *os.Root, from, to string) error { return root.Rename(from, to) } fsRemove = func(root *os.Root, name string) error { return root.Remove(name) } fsWrite = func(file *os.File, data []byte) (int, error) { return file.Write(data) } + fsOpenFile = func(root *os.Root, name string, flag int, perm fs.FileMode) (*os.File, error) { + return root.OpenFile(name, flag, perm) + } ) type tree struct { @@ -56,14 +59,14 @@ func (t tree) isFile(rel string) bool { func (t tree) create(rel string, flag int) (*os.File, error) { name := filepath.FromSlash(rel) - file, err := t.root.OpenFile(name, flag, filePerm) + file, err := fsOpenFile(t.root, name, flag, filePerm) if !errors.Is(err, fs.ErrNotExist) { return file, err } if err := t.root.MkdirAll(filepath.FromSlash(path.Dir(rel)), dirPerm); err != nil { return nil, fmt.Errorf("%w: %s: %w", ErrDirFailed, rel, err) } - return t.root.OpenFile(name, flag, filePerm) + return fsOpenFile(t.root, name, flag, filePerm) } func (t tree) rename(from, to string) error { diff --git a/internal/gitcore/transport/errors.go b/internal/gitcore/transport/errors.go index e4b42902..b4e562fb 100644 --- a/internal/gitcore/transport/errors.go +++ b/internal/gitcore/transport/errors.go @@ -33,5 +33,6 @@ var ( ErrClientKeyEncrypted = errors.New("transport: the tls client key is encrypted") ErrLowSpeed = errors.New("transport: transfer speed stayed below http.lowSpeedLimit") ErrHeaderTimeout = errors.New("transport: no response headers from the server in time") + ErrTLSHandshakeTimeout = errors.New("transport: the tls handshake with the server did not finish in time") ErrProtocolNotAllowed = errors.New("transport: protocol is not allowed") ) diff --git a/internal/gitcore/transport/http.go b/internal/gitcore/transport/http.go index 9436652e..0af82f60 100644 --- a/internal/gitcore/transport/http.go +++ b/internal/gitcore/transport/http.go @@ -12,6 +12,7 @@ import ( "mime" "net" "net/http" + "net/http/httptrace" "net/url" "strings" "sync" @@ -22,9 +23,8 @@ import ( const defaultUserAgent = "git/2.45.0 (Go.Git)" -const tlsHandshakeTimeout = 15 * time.Second - var ( + tlsHandshakeTimeout = 60 * time.Second discoveryHeaderTimeout = 30 * time.Second errUnsupportedMediaType = errors.New("transport: the server refused the request encoding") ) @@ -235,12 +235,12 @@ func (s *httpSession) attempt(ctx context.Context, method, rawURL, contentType, } } s.applyHeaders(req, contentType, proxyAuthorization, headers) - stopHeaderTimer := func() bool { return false } + headerWait := &headerDeadline{cancel: cancel} if method == http.MethodGet { - stopHeaderTimer = time.AfterFunc(discoveryHeaderTimeout, func() { cancel(ErrHeaderTimeout) }).Stop + req = req.WithContext(httptrace.WithClientTrace(reqCtx, &httptrace.ClientTrace{WroteRequest: headerWait.start})) } resp, err := s.client.Do(req) - stopHeaderTimer() + headerWait.stop() if err != nil { watch.stop() cause := context.Cause(reqCtx) @@ -251,6 +251,31 @@ func (s *httpSession) attempt(ctx context.Context, method, rawURL, contentType, return resp, nil } +type headerDeadline struct { + mu sync.Mutex + cancel context.CancelCauseFunc + timer *time.Timer + stopped bool +} + +func (d *headerDeadline) start(httptrace.WroteRequestInfo) { + d.mu.Lock() + defer d.mu.Unlock() + if d.stopped || d.timer != nil { + return + } + d.timer = time.AfterFunc(discoveryHeaderTimeout, func() { d.cancel(ErrHeaderTimeout) }) +} + +func (d *headerDeadline) stop() { + d.mu.Lock() + defer d.mu.Unlock() + d.stopped = true + if d.timer != nil { + d.timer.Stop() + } +} + func (s *httpSession) send(ctx context.Context, method, suffix, contentType string, body *requestBody, headers map[string]string) (*http.Response, error) { target := s.baseURL + suffix leg := func(proxyAuthorization string) (*http.Response, error) { diff --git a/internal/gitcore/transport/httptimeout_test.go b/internal/gitcore/transport/httptimeout_test.go new file mode 100644 index 00000000..6f9cde9d --- /dev/null +++ b/internal/gitcore/transport/httptimeout_test.go @@ -0,0 +1,124 @@ +package transport + +import ( + "context" + "crypto/tls" + "errors" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "net/http/httptrace" + "testing" + "time" +) + +func swapTLSHandshakeTimeout(t *testing.T, d time.Duration) { + t.Helper() + original := tlsHandshakeTimeout + tlsHandshakeTimeout = d + t.Cleanup(func() { tlsHandshakeTimeout = original }) +} + +func silentListener(t *testing.T) net.Listener { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("Listen returned error %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = conn.Close() }) + } + }() + return ln +} + +func TestHTTPDiscoveryFailsWithHandshakeTimeoutWhenTheServerNeverAnswersTLS(t *testing.T) { + clearProxyEnvironment(t) + swapTLSHandshakeTimeout(t, 50*time.Millisecond) + ln := silentListener(t) + err := advertiseThrough(t, "https://"+ln.Addr().String()+"/repo.git", Options{}) + if !errors.Is(err, ErrTLSHandshakeTimeout) { + t.Fatalf("advertise returned %v, want ErrTLSHandshakeTimeout", err) + } +} + +func TestHandshakeReportsCancellationInsteadOfTimeout(t *testing.T) { + client, server := net.Pipe() + t.Cleanup(func() { _ = server.Close() }) + ctx, cancel := context.WithCancel(t.Context()) + time.AfterFunc(20*time.Millisecond, cancel) + s := &httpSession{tlsConfig: &tls.Config{MinVersion: tls.VersionTLS12}} + _, err := s.handshakeTLS(ctx, client, "example.com") + if !errors.Is(err, context.Canceled) || errors.Is(err, ErrTLSHandshakeTimeout) { + t.Fatalf("handshakeTLS returned %v, want context.Canceled", err) + } +} + +type slowHandshakeListener struct { + net.Listener + delay time.Duration +} + +func (l slowHandshakeListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return &slowFirstReadConn{Conn: conn, delay: l.delay}, nil +} + +type slowFirstReadConn struct { + net.Conn + delay time.Duration + read bool +} + +func (c *slowFirstReadConn) Read(p []byte) (int, error) { + if !c.read { + c.read = true + time.Sleep(c.delay) + } + return c.Conn.Read(p) +} + +func TestHTTPDiscoveryHeaderTimeoutDoesNotCountTheTLSHandshake(t *testing.T) { + clearProxyEnvironment(t) + swapDiscoveryHeaderTimeout(t, 100*time.Millisecond) + server := httptest.NewUnstartedServer(http.HandlerFunc(advertiseV1Handler)) + server.Config.ErrorLog = log.New(io.Discard, "", 0) + server.Listener = slowHandshakeListener{Listener: server.Listener, delay: 300 * time.Millisecond} + server.StartTLS() + t.Cleanup(server.Close) + cfg := testGitConfig(t, "[http]\n\tsslCAInfo = "+writeServerCertificate(t, server)+"\n") + if err := advertiseThrough(t, server.URL+"/repo.git", Options{Config: cfg}); err != nil { + t.Fatalf("advertise returned %v after a slow handshake", err) + } +} + +func TestHeaderDeadlineIgnoresStartAfterStop(t *testing.T) { + d := &headerDeadline{cancel: func(error) { t.Errorf("cancel fired after stop") }} + d.stop() + d.start(httptrace.WroteRequestInfo{}) + if d.timer != nil { + t.Fatalf("start armed a timer after stop") + } +} + +func TestHeaderDeadlineKeepsTheFirstTimerOnRepeatedStart(t *testing.T) { + d := &headerDeadline{cancel: func(error) {}} + d.start(httptrace.WroteRequestInfo{}) + first := d.timer + d.start(httptrace.WroteRequestInfo{}) + d.stop() + if d.timer != first { + t.Fatalf("a repeated start replaced the running timer") + } +} diff --git a/internal/gitcore/transport/httptunnel.go b/internal/gitcore/transport/httptunnel.go index 66e57226..87a8636d 100644 --- a/internal/gitcore/transport/httptunnel.go +++ b/internal/gitcore/transport/httptunnel.go @@ -25,10 +25,13 @@ func (s *httpSession) tlsConfigFor(host string) *tls.Config { func (s *httpSession) handshakeTLS(ctx context.Context, conn net.Conn, host string) (*tls.Conn, error) { tc := tls.Client(conn, s.tlsConfigFor(host)) - hsCtx, cancel := context.WithTimeout(ctx, tlsHandshakeTimeout) + hsCtx, cancel := context.WithTimeoutCause(ctx, tlsHandshakeTimeout, ErrTLSHandshakeTimeout) defer cancel() if err := tc.HandshakeContext(hsCtx); err != nil { _ = conn.Close() + if cause := context.Cause(hsCtx); errors.Is(cause, ErrTLSHandshakeTimeout) { + return nil, cause + } return nil, err } return tc, nil diff --git a/internal/gitcore/worktree/bench_test.go b/internal/gitcore/worktree/bench_test.go index 3595cc38..476fc5ef 100644 --- a/internal/gitcore/worktree/bench_test.go +++ b/internal/gitcore/worktree/bench_test.go @@ -129,3 +129,16 @@ func BenchmarkStatusWithTwentyThousandIgnoredFiles(b *testing.B) { } } } + +func BenchmarkStatusOfFiftyThousandFilesIncludingUnmodified(b *testing.B) { + tr := newLargeBenchRepo(b, 50000) + w := tr.openWith(Options{IncludeUnmodified: true}) + ctx := b.Context() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if _, err := w.Status(ctx); err != nil { + b.Fatalf("Status returned error %v", err) + } + } +} diff --git a/internal/gitcore/worktree/coverage_test.go b/internal/gitcore/worktree/coverage_test.go index be22bd84..603ca815 100644 --- a/internal/gitcore/worktree/coverage_test.go +++ b/internal/gitcore/worktree/coverage_test.go @@ -155,6 +155,7 @@ func TestCompareToWorktreeDetectsExecutableBitEvenWhenStatCacheMatches(t *testin Stat: index.Stat{MTime: mtime, Size: 7}, }) w := tr.open() + w.hideUntracked = true w.fileMode = true original := fsLstatFile fsLstatFile = func(root *os.Root, name string) (os.FileInfo, error) { @@ -176,6 +177,7 @@ func TestCompareToWorktreeDetectsExecutableBitAfterAFullContentRead(t *testing.T tr.writeFile("run2.sh", "echo\n") tr.stageContent("run2.sh", "echo\n") w := tr.open() + w.hideUntracked = true w.fileMode = true original := fsLstatFile fsLstatFile = func(root *os.Root, name string) (os.FileInfo, error) { @@ -205,6 +207,7 @@ func TestCompareToWorktreeFailsWhenHashingASymlinkTargetWithAnUnsupportedFormat( Stat: index.Stat{MTime: time.Unix(1, 0), Size: 999}, }) w := tr.open() + w.hideUntracked = true w.format = hash.Format(99) originalLstat, originalReadlink := fsLstatFile, fsReadlinkFile fsLstatFile = func(root *os.Root, name string) (os.FileInfo, error) { diff --git a/internal/gitcore/worktree/errors_test.go b/internal/gitcore/worktree/errors_test.go index 187b1cf6..0b50dd39 100644 --- a/internal/gitcore/worktree/errors_test.go +++ b/internal/gitcore/worktree/errors_test.go @@ -202,7 +202,7 @@ func TestUntrackedEntriesStopsWhenContextIsCanceled(t *testing.T) { tr.writeFile("a.txt", "hi\n") tr.writeFile("dir/b.txt", "hi\n") w := tr.open() - if _, err := w.untrackedEntries(newStepContext(0), map[string]bool{}, map[string]bool{}); err == nil { + if _, err := w.untrackedEntries(newStepContext(0), map[string]bool{}, map[string]bool{}, nil); err == nil { t.Fatalf("untrackedEntries returned no error for a canceled context") } } @@ -371,6 +371,7 @@ func TestCompareToWorktreeFailsWhenLstatFails(t *testing.T) { tr.stage("a.txt", "hi\n") tr.commit("initial") w := tr.open() + w.hideUntracked = true original := fsLstatFile fsLstatFile = func(root *os.Root, name string) (os.FileInfo, error) { return nil, errors.New("boom") } t.Cleanup(func() { fsLstatFile = original }) @@ -406,6 +407,7 @@ func TestCompareToWorktreeDetectsSymlinkChangesUsingFaultInjection(t *testing.T) Stat: index.Stat{MTime: time.Unix(1, 0), Size: 999}, }) w := tr.open() + w.hideUntracked = true originalLstat, originalReadlink := fsLstatFile, fsReadlinkFile t.Cleanup(func() { @@ -440,6 +442,7 @@ func TestCompareToWorktreeIsUnmodifiedWhenTheSymlinkTargetIsUnchanged(t *testing Stat: index.Stat{MTime: time.Unix(1, 0), Size: 999}, }) w := tr.open() + w.hideUntracked = true originalLstat, originalReadlink := fsLstatFile, fsReadlinkFile t.Cleanup(func() { @@ -474,6 +477,7 @@ func TestCompareToWorktreeFailsWhenReadlinkFails(t *testing.T) { Stat: index.Stat{MTime: time.Unix(1, 0), Size: 999}, }) w := tr.open() + w.hideUntracked = true originalLstat, originalReadlink := fsLstatFile, fsReadlinkFile t.Cleanup(func() { diff --git a/internal/gitcore/worktree/listingreuse_test.go b/internal/gitcore/worktree/listingreuse_test.go new file mode 100644 index 00000000..28057956 --- /dev/null +++ b/internal/gitcore/worktree/listingreuse_test.go @@ -0,0 +1,85 @@ +package worktree + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/oops1/gogit/internal/gitcore/index" +) + +func countDirectoryOpens(t *testing.T) func() map[string]int { + t.Helper() + var mu sync.Mutex + opened := map[string]int{} + original := fsOpenDir + fsOpenDir = func(root *os.Root, name string) (*os.File, error) { + mu.Lock() + opened[filepath.ToSlash(name)]++ + mu.Unlock() + return original(root, name) + } + t.Cleanup(func() { fsOpenDir = original }) + return func() map[string]int { + mu.Lock() + defer mu.Unlock() + return opened + } +} + +func TestStatusReadsEveryTrackedDirectoryOnlyOnce(t *testing.T) { + tr := newTestRepo(t) + tr.stage("a.txt", "a\n") + tr.stage("dir/b.txt", "b\n") + tr.stage("dir/sub/c.txt", "c\n") + for i := range batchedStatMinimum { + tr.stage(fmt.Sprintf("dir/sub/many%02d.txt", i), "many\n") + } + tr.commit("tracked") + tr.writeFile("dir/new.txt", "new\n") + tr.writeFile("dir/sub/c.txt", "changed\n") + w := tr.open() + opens := countDirectoryOpens(t) + + status, err := w.Status(t.Context()) + + if err != nil { + t.Fatalf("Status returned error %v", err) + } + for _, dir := range []string{".", "dir", "dir/sub"} { + if got := opens()[dir]; got != 1 { + t.Errorf("directory %q was read %d times, want once: %v", dir, got, opens()) + } + } + entries := entryMap(status.Entries) + if entries["dir/new.txt"].Unstaged != StatusUntracked || entries["dir/sub/c.txt"].Unstaged != StatusModified { + t.Fatalf("status = %+v, want dir/new.txt untracked and dir/sub/c.txt modified", status.Entries) + } +} + +func TestScanningWithoutUntrackedFilesKeepsNoListingsAndStatsSmallDirectoriesOneByOne(t *testing.T) { + tr := newTestRepo(t) + tr.stage("dir/b.txt", "b\n") + tr.commit("tracked") + w := tr.open() + w.hideUntracked = true + var entries []*index.Entry + for entry := range w.currentIndex().Entries() { + entries = append(entries, entry) + } + opens := countDirectoryOpens(t) + + scan, err := w.unstagedStatuses(t.Context(), entries, gitlinkRules{}) + + if err != nil { + t.Fatalf("unstagedStatuses returned error %v", err) + } + if scan.listings != nil { + t.Fatalf("listings = %v, want none when untracked files are hidden", scan.listings) + } + if got := opens()["dir"]; got != 0 { + t.Fatalf("a directory with one tracked file was listed %d times, want lstat only", got) + } +} diff --git a/internal/gitcore/worktree/statbatch_test.go b/internal/gitcore/worktree/statbatch_test.go index 609d2a8e..917cd5bd 100644 --- a/internal/gitcore/worktree/statbatch_test.go +++ b/internal/gitcore/worktree/statbatch_test.go @@ -69,9 +69,10 @@ func TestStatusReadsABigDirectoryOnceInsteadOfStatingEachFileInIt(t *testing.T) } } -func TestStatusStatesFilesOfSmallDirectoriesOneByOne(t *testing.T) { +func TestStatusStatesFilesOfSmallDirectoriesOneByOneWhenUntrackedFilesAreHidden(t *testing.T) { tr := newBatchedRepo(t, batchedStatMinimum) w := tr.open() + w.hideUntracked = true inSmall := countLstatCalls(t, "small/") if _, err := w.Status(t.Context()); err != nil { @@ -202,7 +203,7 @@ func TestStatusStopsWhenTheCallerGivesUpInTheMiddleOfAGroup(t *testing.T) { group[at] = at } - err := w.scanGroup(newStepContext(0), entries, group, gitlinkRules{}, make([]unstagedChange, len(entries))) + err := w.scanGroup(newStepContext(0), entries, group, gitlinkRules{}, make([]unstagedChange, len(entries)), nil) if !errors.Is(err, context.Canceled) { t.Fatalf("scanGroup returned %v, want the cancellation", err) diff --git a/internal/gitcore/worktree/status.go b/internal/gitcore/worktree/status.go index 3922c80a..58d9b1cb 100644 --- a/internal/gitcore/worktree/status.go +++ b/internal/gitcore/worktree/status.go @@ -116,7 +116,7 @@ func (w *Worktree) Status(ctx context.Context) (Status, error) { unstaged := scan.changes var untracked []Entry if !w.hideUntracked { - untracked, err = w.untrackedEntries(ctx, trackedDirs, trackedFiles) + untracked, err = w.untrackedEntries(ctx, trackedDirs, trackedFiles, scan.listings) if err != nil { return Status{}, err } @@ -160,7 +160,7 @@ func (w *Worktree) Status(ctx context.Context) (Status, error) { result := Status{HeadBranch: branch, Detached: detached, Entries: make([]Entry, 0, len(combined))} for _, entry := range combined { w.fillWorkingInfo(entry, scan.stats) - entry.FilterUnsupported = !entry.IsDir && w.policy(entry.Path).FilterUnsupported() + entry.FilterUnsupported = !entry.IsDir && w.attrs.FilterUnsupported(entry.Path) result.Entries = append(result.Entries, *entry) } slices.SortFunc(result.Entries, func(a, b Entry) int { return strings.Compare(a.Path, b.Path) }) diff --git a/internal/gitcore/worktree/untracked.go b/internal/gitcore/worktree/untracked.go index 0131525f..5086a36d 100644 --- a/internal/gitcore/worktree/untracked.go +++ b/internal/gitcore/worktree/untracked.go @@ -13,6 +13,7 @@ type untrackedScan struct { ctx context.Context trackedDirs map[string]bool trackedFiles map[string]bool + listings map[string][]fs.DirEntry mu sync.Mutex out []Entry @@ -23,15 +24,16 @@ type untrackedScan struct { slots chan struct{} } -func (w *Worktree) untrackedEntries(ctx context.Context, trackedDirs, trackedFiles map[string]bool) ([]Entry, error) { +func (w *Worktree) untrackedEntries(ctx context.Context, trackedDirs, trackedFiles map[string]bool, listings map[string][]fs.DirEntry) ([]Entry, error) { scan := &untrackedScan{ w: w, ctx: ctx, trackedDirs: trackedDirs, trackedFiles: trackedFiles, + listings: listings, slots: make(chan struct{}, w.workers), } - items, err := w.readDirTyped("") + items, err := scan.readTrackedDir("") if err != nil { return nil, err } @@ -91,8 +93,15 @@ func (s *untrackedScan) descend(rel string) { } } +func (s *untrackedScan) readTrackedDir(rel string) ([]dirEntry, error) { + if items, ok := s.listings[rel]; ok { + return typedEntries(items), nil + } + return s.w.readDirTyped(rel) +} + func (s *untrackedScan) enter(rel string) { - children, err := s.w.readDirTyped(rel) + children, err := s.readTrackedDir(rel) if err != nil { s.fail(err) return @@ -228,9 +237,13 @@ func (w *Worktree) readDirTyped(rel string) ([]dirEntry, error) { if err != nil { return nil, err } + return typedEntries(entries), nil +} + +func typedEntries(entries []fs.DirEntry) []dirEntry { out := make([]dirEntry, len(entries)) for i, entry := range entries { out[i] = dirEntry{name: entry.Name(), isDir: entry.IsDir(), entry: entry} } - return out, nil + return out } diff --git a/internal/gitcore/worktree/workingtree.go b/internal/gitcore/worktree/workingtree.go index e0aefb0d..b01c8409 100644 --- a/internal/gitcore/worktree/workingtree.go +++ b/internal/gitcore/worktree/workingtree.go @@ -30,8 +30,37 @@ type workingStat struct { } type workingScan struct { - changes map[string]unstagedChange - stats map[string]workingStat + changes map[string]unstagedChange + stats map[string]workingStat + listings map[string][]fs.DirEntry +} + +type keptListings struct { + mu sync.Mutex + dirs map[string][]fs.DirEntry +} + +func (k *keptListings) keep(dir string, items []fs.DirEntry) { + if k == nil { + return + } + k.mu.Lock() + k.dirs[dir] = items + k.mu.Unlock() +} + +func (k *keptListings) all() map[string][]fs.DirEntry { + if k == nil { + return nil + } + return k.dirs +} + +func listingKey(dir string) string { + if dir == "." { + return "" + } + return dir } type directoryListing map[string]fs.DirEntry @@ -45,11 +74,12 @@ func (l directoryListing) info(name string) (fs.FileInfo, bool) { return info, err == nil } -func (w *Worktree) listDirectory(rel string) directoryListing { +func (w *Worktree) listDirectory(rel string, kept *keptListings) directoryListing { items, err := w.readDir(rel) if err != nil { return nil } + kept.keep(rel, items) listing := make(directoryListing, len(items)) for _, item := range items { listing[item.Name()] = item @@ -78,6 +108,10 @@ func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, } close(queue) scanned := make([]unstagedChange, len(entries)) + var kept *keptListings + if !w.hideUntracked { + kept = &keptListings{dirs: make(map[string][]fs.DirEntry, len(groups))} + } var ( wg sync.WaitGroup once sync.Once @@ -87,7 +121,7 @@ func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, for range min(w.workers, len(groups)) { wg.Go(func() { for group := range queue { - if err := w.scanGroup(ctx, entries, group, rules, scanned); err != nil { + if err := w.scanGroup(ctx, entries, group, rules, scanned, kept); err != nil { fail(err) return } @@ -102,8 +136,9 @@ func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, return workingScan{}, err } scan := workingScan{ - changes: make(map[string]unstagedChange), - stats: make(map[string]workingStat, len(entries)), + changes: make(map[string]unstagedChange), + stats: make(map[string]workingStat, len(entries)), + listings: kept.all(), } for at, change := range scanned { if change.code != StatusUnmodified { @@ -116,10 +151,10 @@ func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, return scan, nil } -func (w *Worktree) scanGroup(ctx context.Context, entries []*index.Entry, group []int, rules gitlinkRules, scanned []unstagedChange) error { +func (w *Worktree) scanGroup(ctx context.Context, entries []*index.Entry, group []int, rules gitlinkRules, scanned []unstagedChange, kept *keptListings) error { var listing directoryListing - if len(group) >= batchedStatMinimum { - listing = w.listDirectory(path.Dir(entries[group[0]].Path)) + if len(group) >= batchedStatMinimum || kept != nil { + listing = w.listDirectory(listingKey(path.Dir(entries[group[0]].Path)), kept) } for _, at := range group { if err := ctx.Err(); err != nil { diff --git a/internal/repo/watch/watch.go b/internal/repo/watch/watch.go index 31abca3d..ecd16bb7 100644 --- a/internal/repo/watch/watch.go +++ b/internal/repo/watch/watch.go @@ -112,38 +112,83 @@ func (o Options) normalize() Options { } type Watcher struct { - layout repo.Layout - opts Options - snapshotFn func() Snapshot + layout repo.Layout + custom func() Snapshot mu sync.Mutex + opts Options + skipGen uint64 paused bool resumeCh chan struct{} pokeCh chan struct{} baseline Snapshot + baselineGen uint64 + ready chan struct{} baselineOnce sync.Once } func New(layout repo.Layout, opts Options) *Watcher { opts = opts.normalize() - w := &Watcher{layout: layout, opts: opts, pokeCh: make(chan struct{}, 1)} - if opts.Snapshot != nil { - w.snapshotFn = opts.Snapshot - } else { - w.snapshotFn = func() Snapshot { return take(w.layout, w.opts) } - } - w.baseline = w.snapshotFn() + w := &Watcher{layout: layout, opts: opts, custom: opts.Snapshot, pokeCh: make(chan struct{}, 1), ready: make(chan struct{})} + go w.takeBaseline() return w } -func (w *Watcher) initialSnapshot() Snapshot { +func (w *Watcher) takeBaseline() { + defer close(w.ready) + w.baseline, w.baselineGen = w.snapshot() +} + +func (w *Watcher) Ready() <-chan struct{} { return w.ready } + +func (w *Watcher) SetSkipDirs(dirs []string) { + w.mu.Lock() + defer w.mu.Unlock() + w.opts.SkipDirs = slices.Clone(dirs) + w.skipGen++ +} + +func (w *Watcher) snapshot() (Snapshot, uint64) { + w.mu.Lock() + opts, gen := w.opts, w.skipGen + w.mu.Unlock() + if w.custom != nil { + return w.custom(), gen + } + return take(w.layout, opts), gen +} + +func (w *Watcher) initialSnapshot(ctx context.Context) (Snapshot, uint64, bool) { first := false w.baselineOnce.Do(func() { first = true }) - if first { - return w.baseline + if !first { + snap, gen := w.snapshot() + return snap, gen, true + } + select { + case <-ctx.Done(): + return nil, 0, false + case <-w.ready: + return w.baseline, w.baselineGen, true + } +} + +func changesBetween(prev, next Snapshot, skipsChanged bool) ChangeSet { + if skipsChanged { + return diffCommon(prev, next) } - return w.snapshotFn() + return Diff(prev, next) +} + +func diffCommon(prev, next Snapshot) ChangeSet { + var changes ChangeSet + for path, before := range prev { + if after, ok := next[path]; ok && !before.equal(after) { + changes = changes.add(before.Kind) + } + } + return changes } func (w *Watcher) Poke() { @@ -189,7 +234,10 @@ func minDuration(a, b time.Duration) time.Duration { func (w *Watcher) Run(ctx context.Context) iter.Seq[ChangeSet] { return func(yield func(ChangeSet) bool) { - prev := w.initialSnapshot() + prev, prevGen, ok := w.initialSnapshot(ctx) + if !ok { + return + } interval := w.opts.MinInterval timer := time.NewTimer(interval) defer timer.Stop() @@ -200,7 +248,7 @@ func (w *Watcher) Run(ctx context.Context) iter.Seq[ChangeSet] { return case <-resumeCh: } - prev = w.snapshotFn() + prev, prevGen = w.snapshot() interval = w.opts.MinInterval timer.Reset(interval) continue @@ -215,9 +263,9 @@ func (w *Watcher) Run(ctx context.Context) iter.Seq[ChangeSet] { timer.Reset(w.opts.MinInterval) continue } - next := w.snapshotFn() - changes := Diff(prev, next) - prev = next + next, nextGen := w.snapshot() + changes := changesBetween(prev, next, nextGen != prevGen) + prev, prevGen = next, nextGen if len(changes) == 0 { interval = minDuration(interval*2, w.opts.MaxInterval) } else { diff --git a/internal/repo/watch/watch_test.go b/internal/repo/watch/watch_test.go index 25ed9e98..756f7f19 100644 --- a/internal/repo/watch/watch_test.go +++ b/internal/repo/watch/watch_test.go @@ -492,27 +492,130 @@ func TestNewNormalizesOptions(t *testing.T) { assertOptionsEqual(t, w.opts, want) } -func TestNewSnapshotFnReflectsTheGivenLayout(t *testing.T) { +func TestNewSnapshotReflectsTheGivenLayout(t *testing.T) { layout := newTestLayout(t, false) w := New(layout, Options{}) - snap := w.snapshotFn() + snap, _ := w.snapshot() if e, ok := snap[gitPath(layout, "HEAD")]; !ok || !e.Exists { t.Fatalf("snapshot missing HEAD entry: %+v", snap) } } -func TestNewCapturesTheBaselineSnapshotSynchronouslyFromOptionsSnapshot(t *testing.T) { +func TestNewReturnsBeforeTheBaselineIsTakenAndSignalsWhenItIsReady(t *testing.T) { + release := make(chan struct{}) var calls atomic.Int32 w := New(repo.Layout{}, Options{Snapshot: func() Snapshot { + <-release calls.Add(1) return Snapshot{"marker": {Kind: Head, Exists: true}} }}) - if got := calls.Load(); got != 1 { - t.Fatalf("Options.Snapshot called %d times during New, want 1", got) + select { + case <-w.Ready(): + t.Fatal("the watcher reported a baseline that is still being taken") + default: } - if _, ok := w.baseline["marker"]; !ok { - t.Fatalf("baseline = %v, want the injected snapshot", w.baseline) + close(release) + select { + case <-w.Ready(): + case <-time.After(testTimeout): + t.Fatal("the watcher never finished its baseline") } + if _, ok := w.baseline["marker"]; !ok || calls.Load() != 1 { + t.Fatalf("baseline = %v after %d snapshots, want the injected snapshot taken once", w.baseline, calls.Load()) + } +} + +func TestRunStopsWhenCancelledWhileTheBaselineIsStillBeingTaken(t *testing.T) { + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + w := New(repo.Layout{}, Options{Snapshot: func() Snapshot { + <-release + return Snapshot{} + }}) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + for cs := range w.Run(ctx) { + t.Fatalf("Run reported %v although it was cancelled before the baseline", cs) + } +} + +func TestSetSkipDirsAppliesToTheNextSnapshot(t *testing.T) { + layout := newTestLayout(t, false) + out := filepath.Join(layout.WorkTree, "out") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + w := New(layout, Options{}) + <-w.Ready() + before, beforeGen := w.snapshot() + + w.SetSkipDirs([]string{"out"}) + after, afterGen := w.snapshot() + + if _, ok := before[out]; !ok { + t.Fatalf("the snapshot before the skip misses %s: %v", out, before) + } + if _, ok := after[out]; ok || afterGen == beforeGen { + t.Fatalf("after SetSkipDirs the snapshot still holds %s (generation %d -> %d)", out, beforeGen, afterGen) + } +} + +func TestDiffCommonReportsOnlyPathsPresentInBothSnapshots(t *testing.T) { + prev := Snapshot{"kept": {Kind: WorkTree, Size: 1}, "gone": {Kind: Refs}} + next := Snapshot{"kept": {Kind: WorkTree, Size: 1}, "new": {Kind: Index}} + if got := diffCommon(prev, next); len(got) != 0 { + t.Fatalf("diffCommon = %v, want nothing for paths that only appeared or vanished", got) + } + next["kept"] = Entry{Kind: WorkTree, Size: 2} + if got := diffCommon(prev, next); !got.Has(WorkTree) || len(got) != 1 { + t.Fatalf("diffCommon = %v, want the changed WorkTree path", got) + } +} + +func TestRunDoesNotReportDirectoriesThatOnlyVanishedBecauseTheSkipsChanged(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + snaps := []Snapshot{ + {"a": {Kind: WorkTree, Size: 1}, "b": {Kind: WorkTree, Size: 1}}, + {"a": {Kind: WorkTree, Size: 1}}, + {"a": {Kind: WorkTree, Size: 2}}, + } + var at atomic.Int32 + w := New(repo.Layout{}, Options{MinInterval: time.Hour, MaxInterval: time.Hour, Snapshot: func() Snapshot { + return snaps[min(int(at.Add(1))-1, len(snaps)-1)] + }}) + ctx, cancel := context.WithCancel(t.Context()) + results := make(chan ChangeSet, 4) + done := make(chan struct{}) + go func() { + defer close(done) + for cs := range w.Run(ctx) { + results <- cs + } + }() + synctest.Wait() + + w.SetSkipDirs([]string{"b"}) + w.Poke() + synctest.Wait() + select { + case cs := <-results: + t.Fatalf("a directory that vanished only because it is now skipped was reported: %v", cs) + default: + } + + w.Poke() + synctest.Wait() + select { + case cs := <-results: + if !cs.Has(WorkTree) { + t.Fatalf("changes = %v, want WorkTree", cs) + } + default: + t.Fatal("a real change after the skip update was not reported") + } + cancel() + <-done + }) } func TestPokeDropsExtraSignalsWhenAlreadyQueued(t *testing.T) { @@ -573,10 +676,11 @@ func TestRunReportsHeadChangeWithinMinInterval(t *testing.T) { }) } -func TestRunReportsAChangeMadeBetweenNewAndTheFirstIteration(t *testing.T) { +func TestRunReportsAChangeMadeBetweenReadyAndTheFirstIteration(t *testing.T) { synctest.Test(t, func(t *testing.T) { layout := newTestLayout(t, false) w := New(layout, Options{MinInterval: time.Second, MaxInterval: 4 * time.Second}) + <-w.Ready() headFile := gitPath(layout, "HEAD") if err := os.WriteFile(headFile, []byte("ref: refs/heads/created-before-the-first-iteration\n"), 0o644); err != nil { t.Fatalf("WriteFile returned error %v", err) @@ -596,7 +700,7 @@ func TestRunReportsAChangeMadeBetweenNewAndTheFirstIteration(t *testing.T) { t.Fatalf("changes = %v, want Head", cs) } case <-time.After(testTimeout): - t.Fatal("a change made between New and the first iteration was not reported") + t.Fatal("a change made between Ready and the first iteration was not reported") } cancel() <-done diff --git a/internal/ui/blameview/view.go b/internal/ui/blameview/view.go index 2d173495..b2d69cfe 100644 --- a/internal/ui/blameview/view.go +++ b/internal/ui/blameview/view.go @@ -72,6 +72,7 @@ type View struct { lines []Line selected int linkColor color.RGBA + commitCol *datagrid.DataGridTemplateColumn OnInvestigate func(line Line) OnCommit func(id hash.ObjectID) @@ -131,6 +132,8 @@ func (v *View) bind(named map[string]widget.Widget) error { func (v *View) buildColumns() { commit := datagrid.NewTemplateColumn(i18n.T("Dialog.Blame.Column.Commit"), v.drawCommitCell) commit.SetWidth(datagrid.PixelWidth(commitWidth)) + commit.SetCursor(datagrid.CursorHand) + v.commitCol = commit when := datagrid.NewTextColumn(i18n.T("Dialog.Blame.Column.When"), "When") when.SetWidth(datagrid.PixelWidth(whenWidth)) author := datagrid.NewTemplateColumn(i18n.T("Dialog.Blame.Column.Author"), v.drawAuthorCell) @@ -183,18 +186,18 @@ func (v *View) commitOf(index int) (hash.ObjectID, bool) { return v.lines[index].Commit, true } -func (v *View) onRowActivated(index int, _ interface{}) { - if v.OnCommit == nil { +func (v *View) onCellClicked(e datagrid.CellClickedEvent) { + if v.OnCommit == nil || e.Column != datagrid.Column(v.commitCol) || e.Button != 0 || e.DoubleClick { return } - if id, ok := v.commitOf(index); ok { + if id, ok := v.commitOf(e.RowIndex); ok { v.OnCommit(id) } } func (v *View) wire() { v.table.Grid.OnSelectionChanged = v.onSelected - v.table.Grid.OnRowActivated = v.onRowActivated + v.table.Grid.OnCellClicked = v.onCellClicked v.lookBtn.OnClick = v.investigate v.closeBtn.OnClick = v.close v.dlg.CancelAction = v.close diff --git a/internal/ui/blameview/view_test.go b/internal/ui/blameview/view_test.go index eef726f8..6dbcb28a 100644 --- a/internal/ui/blameview/view_test.go +++ b/internal/ui/blameview/view_test.go @@ -216,30 +216,55 @@ func TestTheRowsAreTightAndUnstriped(t *testing.T) { } } -func TestActivatingARowAsksForItsCommit(t *testing.T) { +func commitClick(v *View, row int) datagrid.CellClickedEvent { + return datagrid.CellClickedEvent{RowIndex: row, Column: v.commitCol} +} + +func TestClickingTheCommitLinkAsksForItsCommit(t *testing.T) { v := newTestView(t) v.SetLines("f", twoLines()) var asked hash.ObjectID v.OnCommit = func(got hash.ObjectID) { asked = got } - v.table.Grid.OnRowActivated(1, nil) + v.table.Grid.OnCellClicked(commitClick(v, 1)) if asked != id("two") { - t.Fatalf("asked for %s, want the commit of the activated row", asked) + t.Fatalf("asked for %s, want the commit of the clicked row", asked) + } +} + +func TestTheCommitColumnShowsAHandCursor(t *testing.T) { + v := newTestView(t) + + if got := v.commitCol.Cursor(); got != datagrid.CursorHand { + t.Fatalf("cursor = %d, want the hand over the commit link", got) } } -func TestActivatingARowWithoutAHandlerOrOutsideTheListIsQuiet(t *testing.T) { +func TestClicksThatAreNotASingleLeftClickOnTheLinkAreQuiet(t *testing.T) { v := newTestView(t) v.SetLines("f", twoLines()) - v.table.Grid.OnRowActivated(0, nil) + v.table.Grid.OnCellClicked(commitClick(v, 0)) asked := false v.OnCommit = func(hash.ObjectID) { asked = true } - v.table.Grid.OnRowActivated(7, nil) - if asked { - t.Fatal("a row outside the list must not name a commit") + text := commitClick(v, 0) + text.Column = v.table.Grid.Columns()[4] + right := commitClick(v, 0) + right.Button = 1 + double := commitClick(v, 0) + double.DoubleClick = true + for name, e := range map[string]datagrid.CellClickedEvent{ + "outside the list": commitClick(v, 7), + "another column": text, + "right button": right, + "double click": double, + } { + v.table.Grid.OnCellClicked(e) + if asked { + t.Fatalf("a click %s must not name a commit", name) + } } } diff --git a/internal/ui/journal/view.go b/internal/ui/journal/view.go index 31329e16..c70c99fd 100644 --- a/internal/ui/journal/view.go +++ b/internal/ui/journal/view.go @@ -2,7 +2,6 @@ package journal import ( "image/color" - "slices" "sync" "github.com/oops1/headless-gui/v3/widget" @@ -16,7 +15,6 @@ const nearEndRows = 5 type View struct { grid *widget.DataGridWidget items *datagrid.ObservableCollection - shown []any columnsMu sync.Mutex authorHeader string fullAuthorName bool @@ -85,7 +83,6 @@ func (v *View) installMessageColumn() { } func (v *View) Reset() { - v.shown = nil v.items.Clear() v.lanes.Reset() v.resizeToVisibleRows() @@ -154,12 +151,12 @@ func (v *View) ClearSelection() { } func (v *View) Append(rows []Row) { - v.shown = slices.Grow(v.shown, len(rows)) + page := make([]any, 0, len(rows)) for _, row := range rows { row.Graph = v.lanes.Add(graph.Commit{ID: row.ID, Parents: row.Parents}) - v.shown = append(v.shown, row) + page = append(page, row) } - v.items.SetItems(v.shown) + v.items.AddRange(page) v.resizeToVisibleRows() } diff --git a/internal/ui/journal/view_test.go b/internal/ui/journal/view_test.go index 6b1a276c..aec82d86 100644 --- a/internal/ui/journal/view_test.go +++ b/internal/ui/journal/view_test.go @@ -332,6 +332,24 @@ func TestAppendKeepsEveryPageInOrder(t *testing.T) { } } +func TestAppendingAPageKeepsTheSelectedRowQuietly(t *testing.T) { + v, grid := bound(t) + first := sampleRows(3) + v.Append(first) + grid.Grid.SetSelectedIndex(1) + selections := 0 + v.OnSelect = func(Row) { selections++ } + + v.Append(sampleRows(3)) + + if got, _ := grid.Grid.SelectedItem().(Row); got.ID != first[1].ID { + t.Fatalf("selected %s, want the selection kept on %s", got.ID, first[1].ID) + } + if selections != 0 { + t.Fatalf("selections = %d, want the next page to leave the selection alone", selections) + } +} + func BenchmarkAppendingTwoHundredPagesToTheJournal(b *testing.B) { page := sampleRows(500) b.ReportAllocs()