From 10d09fa137f02db7dc976584bf5520dd42d18ddd Mon Sep 17 00:00:00 2001 From: Gustavo Miranda Date: Tue, 20 Oct 2026 21:39:07 -0300 Subject: [PATCH] feat(collect): collect local Git activity devlog collect runs the configured sources over a day or a range of days and upserts what they find. The git source reads the repositories under collect.git.roots: commits authored by collect.git.authorEmails on every branch, with the branch taken from the reflog when the commit was made here; branch activity windows from the reflog; and the uncommitted and unpushed work of the checked-out branch, timed by file modification. Entries get the device name and the ticket keys collect.ticketPattern finds in their branch and first line. collect.timezone files them under the right day, with the zone database embedded for Windows. Uncommitted work is part of the branch activity snapshot instead of a kind of its own, so committing it refreshes the same entry. --- cmd/collect.go | 356 ++++++++++++ cmd/config.go | 44 +- cmd/summary/create.go | 4 +- docs/commands.md | 30 + docs/configuration.md | 22 + internal/collector/collector.go | 168 ++++++ internal/collector/gitlocal/gitlocal.go | 582 +++++++++++++++++++ internal/collector/gitlocal/gitlocal_test.go | 199 +++++++ internal/store/activity.go | 6 +- 9 files changed, 1392 insertions(+), 19 deletions(-) create mode 100644 cmd/collect.go create mode 100644 internal/collector/collector.go create mode 100644 internal/collector/gitlocal/gitlocal.go create mode 100644 internal/collector/gitlocal/gitlocal_test.go diff --git a/cmd/collect.go b/cmd/collect.go new file mode 100644 index 0000000..240679a --- /dev/null +++ b/cmd/collect.go @@ -0,0 +1,356 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "regexp" + "slices" + "sort" + "strings" + "time" + + "devlog/internal/collector" + "devlog/internal/collector/gitlocal" + "devlog/internal/store" + + "github.com/fatih/color" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// defaultCollectSources run when collect.sources is not configured. +var defaultCollectSources = []string{"git"} + +// collectorFactories build each collector from the configuration. +var collectorFactories = map[string]func() collector.Collector{ + "git": func() collector.Collector { + return &gitlocal.Collector{ + Roots: configList("collect.git.roots"), + AuthorEmails: configList("collect.git.authoremails"), + } + }, +} + +var collectCmd = &cobra.Command{ + Use: "collect", + Short: "Collect development activity from this device", + Long: `Collects development activity and stores it as entries on the day it +happened, without rewriting it: + + git commits you authored on every branch, branch activity from the + reflog, and uncommitted or unpushed work on the checked-out branch, + in the repositories under collect.git.roots + +Each entry keeps its repository, branch, ticket keys (collect.ticketPattern), +and time, so an agent can later turn the day into timesheet descriptions. +Running collect again is safe: stored entries are completed, not duplicated, +and snapshots such as branch activity are refreshed. + +The sources default to collect.sources. Times use collect.timezone, or the +system time zone when it is empty.`, + Example: ` devlog collect + devlog collect --date 2026-08-17 --dry-run + devlog collect --from 2026-08-17 --to 2026-08-21 --sources git + devlog collect --remote`, + Args: cobra.NoArgs, + RunE: runCollect, +} + +type collectReport struct { + From time.Time `json:"from"` + To time.Time `json:"to"` + DryRun bool `json:"dryRun,omitempty"` + Collectors []collectorRunSummary `json:"collectors"` +} + +type collectorRunSummary struct { + Name string `json:"name"` + Added int `json:"added"` + Updated int `json:"updated"` + Unchanged int `json:"unchanged"` + Skipped string `json:"skipped,omitempty"` + Error string `json:"error,omitempty"` + Entries []store.Entry `json:"entries,omitempty"` +} + +func runCollect(cmd *cobra.Command, args []string) error { + dryRun, _ := cmd.Flags().GetBool("dry-run") + remoteSync, _ := cmd.Flags().GetBool("remote") + asJSON, _ := cmd.Flags().GetBool("json") + envFile, _ := cmd.Flags().GetString("env-file") + if envFile != "" { + path, err := absolutePath(envFile) + if err != nil { + return fmt.Errorf("could not resolve environment file %q: %w", envFile, err) + } + if err := loadEnvFile(path); err != nil { + return fmt.Errorf("could not load environment file: %w", err) + } + } + + loc, err := collectLocation() + if err != nil { + return err + } + window, err := collectWindow(cmd, loc) + if err != nil { + return err + } + sources, err := cmd.Flags().GetStringSlice("sources") + if err != nil { + return err + } + collectors, err := configuredCollectors(sources) + if err != nil { + return err + } + tickets, err := ticketPattern() + if err != nil { + return err + } + + repo, err := store.OpenRepository() + if err != nil { + return fmt.Errorf("could not open DevLog data: %w", err) + } + if remoteSync && !dryRun { + if err := syncConfiguredRemote(cmd.Context(), repo); err != nil { + return fmt.Errorf("remote pull failed: %w", err) + } + } + deviceID, err := store.DeviceID(repo.ConfigRoot) + if err != nil { + return fmt.Errorf("could not read the device ID: %w", err) + } + deviceName := deviceName() + + results := collector.Run(cmd.Context(), collectors, window, collector.Options{ + DeviceID: deviceID, DeviceName: deviceName, Tickets: tickets, + }) + + report := collectReport{From: window.From, To: window.To, DryRun: dryRun} + runs := map[string]store.CollectorStatus{} + var failed []string + now := time.Now() + for _, result := range results { + summary := collectorRunSummary{Name: result.Collector, Skipped: result.Skipped} + status := store.CollectorStatus{LastRunAt: now, Skipped: result.Skipped} + if dryRun { + summary.Entries = slices.Clone(result.Entries) + sort.SliceStable(summary.Entries, func(i, j int) bool { + return summary.Entries[i].Activity.OccurredAt.Before(summary.Entries[j].Activity.OccurredAt) + }) + } else if len(result.Entries) > 0 { + upserted, err := repo.UpsertEntries(result.Entries, loc) + if err != nil { + return fmt.Errorf("could not save %s activity: %w", result.Collector, err) + } + summary.Added, summary.Updated, summary.Unchanged = len(upserted.Added), len(upserted.Updated), upserted.Unchanged + } + status.Entries = len(result.Entries) + if result.Err != nil { + summary.Error = result.Err.Error() + status.Error = summary.Error + failed = append(failed, result.Collector) + } else if result.Skipped == "" { + coveredTo := window.To + if now.Before(coveredTo) { + coveredTo = now + } + status.LastSuccessAt, status.CoveredFrom, status.CoveredTo = now, window.From, coveredTo + } + runs[result.Collector] = status + report.Collectors = append(report.Collectors, summary) + } + + if !dryRun { + if err := repo.RecordCollectorRuns(deviceName, runs); err != nil { + return err + } + if remoteSync { + if err := syncConfiguredRemote(cmd.Context(), repo); err != nil { + return fmt.Errorf("activity was saved locally, but remote push failed: %w", err) + } + } + } + + if asJSON { + data, err := json.MarshalIndent(report, "", " ") + if err != nil { + return fmt.Errorf("could not encode the collection report: %w", err) + } + fmt.Fprintln(cmd.OutOrStdout(), string(data)) + } else { + printCollectReport(report) + } + if len(failed) > 0 { + return fmt.Errorf("collection failed for %s", strings.Join(failed, ", ")) + } + return nil +} + +func printCollectReport(report collectReport) { + last := report.To.Add(-time.Nanosecond) + if report.From.Format("2006-01-02") == last.Format("2006-01-02") { + fmt.Printf("Activity for %s\n", report.From.Format("2006-01-02")) + } else { + fmt.Printf("Activity from %s to %s\n", report.From.Format("2006-01-02"), last.Format("2006-01-02")) + } + for _, summary := range report.Collectors { + switch { + case summary.Skipped != "": + fmt.Printf("%s %s skipped: %s\n", color.YellowString("·"), summary.Name, summary.Skipped) + continue + case report.DryRun: + for _, entry := range summary.Entries { + fmt.Printf("%s [%s] %s %s\n", color.CyanString("•"), entry.Project, entry.Activity.OccurredAt.Format("15:04"), firstDescriptionLine(entry.Description)) + } + fmt.Printf("%s %s: %d entries (dry-run, nothing written)\n", color.GreenString("✔"), summary.Name, len(summary.Entries)) + default: + fmt.Printf("%s %s: %d new, %d updated, %d unchanged\n", color.GreenString("✔"), summary.Name, summary.Added, summary.Updated, summary.Unchanged) + } + if summary.Error != "" { + fmt.Fprintf(os.Stderr, "%s %s failed: %s\n", color.RedString("✗"), summary.Name, summary.Error) + } + } +} + +func firstDescriptionLine(description string) string { + line, _, _ := strings.Cut(description, "\n") + return line +} + +// collectLocation is the time zone collected activity is filed under. +func collectLocation() (*time.Location, error) { + name := strings.TrimSpace(viper.GetString("collect.timezone")) + if name == "" { + return time.Local, nil + } + loc, err := time.LoadLocation(name) + if err != nil { + return nil, fmt.Errorf("invalid collect.timezone %q: use an IANA name such as America/Los_Angeles", name) + } + return loc, nil +} + +func collectWindow(cmd *cobra.Command, loc *time.Location) (collector.Window, error) { + date, _ := cmd.Flags().GetString("date") + from, _ := cmd.Flags().GetString("from") + to, _ := cmd.Flags().GetString("to") + parse := func(flag, value string) (time.Time, error) { + parsed, err := time.ParseInLocation("2006-01-02", value, loc) + if err != nil { + return time.Time{}, fmt.Errorf("invalid --%s value %q: expected YYYY-MM-DD", flag, value) + } + return parsed, nil + } + switch { + case date != "" && (from != "" || to != ""): + return collector.Window{}, fmt.Errorf("use either --date or --from and --to") + case date != "": + day, err := parse("date", date) + if err != nil { + return collector.Window{}, err + } + return collector.DayWindow(day, loc), nil + case from != "" || to != "": + if from == "" || to == "" { + return collector.Window{}, fmt.Errorf("--from and --to must be used together") + } + first, err := parse("from", from) + if err != nil { + return collector.Window{}, err + } + last, err := parse("to", to) + if err != nil { + return collector.Window{}, err + } + if last.Before(first) { + return collector.Window{}, fmt.Errorf("--to must not be earlier than --from") + } + return collector.DaysWindow(first, last, loc), nil + default: + return collector.DayWindow(time.Now().In(loc), loc), nil + } +} + +func configuredCollectors(sources []string) ([]collector.Collector, error) { + if len(sources) == 0 { + sources = configList("collect.sources") + } + if len(sources) == 0 { + sources = defaultCollectSources + } + var collectors []collector.Collector + for _, source := range sources { + name := strings.ToLower(strings.TrimSpace(source)) + factory, ok := collectorFactories[name] + if !ok { + known := make([]string, 0, len(collectorFactories)) + for candidate := range collectorFactories { + known = append(known, candidate) + } + sort.Strings(known) + return nil, fmt.Errorf("unknown activity source %q; choose from %s", source, strings.Join(known, ", ")) + } + if !slices.ContainsFunc(collectors, func(c collector.Collector) bool { return c.Name() == name }) { + collectors = append(collectors, factory()) + } + } + return collectors, nil +} + +func ticketPattern() (*regexp.Regexp, error) { + pattern := viper.GetString("collect.ticketpattern") + if pattern == "" { + pattern = collector.DefaultTicketPattern + } + compiled, err := regexp.Compile(pattern) + if err != nil { + return nil, fmt.Errorf("invalid collect.ticketPattern %q: %w", pattern, err) + } + return compiled, nil +} + +// deviceName labels this device in collected activity. +func deviceName() string { + if name := strings.TrimSpace(viper.GetString("device.name")); name != "" { + return name + } + if host, err := os.Hostname(); err == nil { + return host + } + return "unknown" +} + +// configList reads a list setting saved as a JSON array or written by hand as +// a comma-separated string. +func configList(key string) []string { + var values []string + if value, ok := viper.Get(key).(string); ok { + values = strings.Split(value, ",") + } else { + values = viper.GetStringSlice(key) + } + var cleaned []string + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + cleaned = append(cleaned, trimmed) + } + } + return cleaned +} + +func init() { + RootCmd.AddCommand(collectCmd) + collectCmd.Flags().String("date", "", "Day to collect (YYYY-MM-DD, defaults to today)") + collectCmd.Flags().String("from", "", "First day to collect (YYYY-MM-DD), with --to") + collectCmd.Flags().String("to", "", "Last day to collect (YYYY-MM-DD), with --from") + collectCmd.Flags().StringSlice("sources", nil, "Comma-separated sources to collect (defaults to collect.sources)") + collectCmd.Flags().Bool("dry-run", false, "Print what would be collected without writing entries") + collectCmd.Flags().Bool("remote", false, "Pull and push the configured DevLog Git remote") + collectCmd.Flags().Bool("json", false, "Print the collection report as JSON") + collectCmd.Flags().String("env-file", "", "Load API credentials from a protected KEY=VALUE file") + _ = collectCmd.Flags().MarkHidden("env-file") +} diff --git a/cmd/config.go b/cmd/config.go index bcd0c9f..fce5493 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -16,23 +16,30 @@ type configValueKind int const ( configString configValueKind = iota configBool + configStringList ) var configurableKeys = map[string]configValueKind{ - "defaults.language": configString, - "defaults.project": configString, - "defaults.style": configString, - "github.tokenenvvar": configString, - "github.username": configString, - "llm.apikeyenvvar": configString, - "llm.baseurl": configString, - "llm.enabled": configBool, - "llm.model": configString, - "llm.provider": configString, - "remote.branch": configString, - "remote.enabled": configBool, - "remote.url": configString, - "storage.path": configString, + "collect.git.authoremails": configStringList, + "collect.git.roots": configStringList, + "collect.sources": configStringList, + "collect.ticketpattern": configString, + "collect.timezone": configString, + "defaults.language": configString, + "defaults.project": configString, + "defaults.style": configString, + "device.name": configString, + "github.tokenenvvar": configString, + "github.username": configString, + "llm.apikeyenvvar": configString, + "llm.baseurl": configString, + "llm.enabled": configBool, + "llm.model": configString, + "llm.provider": configString, + "remote.branch": configString, + "remote.enabled": configBool, + "remote.url": configString, + "storage.path": configString, } var configCmd = &cobra.Command{ @@ -103,6 +110,15 @@ func canonicalConfigKey(value string) (string, error) { } func parseConfigValue(key, value string) (any, error) { + if configurableKeys[key] == configStringList { + items := []string{} + for item := range strings.SplitSeq(value, ",") { + if trimmed := strings.TrimSpace(item); trimmed != "" { + items = append(items, trimmed) + } + } + return items, nil + } if configurableKeys[key] == configBool { parsed, err := strconv.ParseBool(value) if err != nil { diff --git a/cmd/summary/create.go b/cmd/summary/create.go index 6ecfd57..a3933e3 100644 --- a/cmd/summary/create.go +++ b/cmd/summary/create.go @@ -52,8 +52,8 @@ Examples: if err != nil { return fmt.Errorf("could not read entries for %s: %w", summaryDate.Format("2006-01-02"), err) } - // Sessions, uncommitted work, and branch activity describe state, not - // finished work, so they stay out of summaries. + // Sessions and branch activity describe state, not finished work, so + // they stay out of summaries. entries = slices.DeleteFunc(entries, func(e store.Entry) bool { return e.Activity != nil && e.Activity.Snapshot() }) diff --git a/docs/commands.md b/docs/commands.md index 10980b1..f8783d0 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -59,6 +59,36 @@ List saved summaries. With no options, it shows the current week. | `--from ` | Set the start of a custom range. | | `--to ` | Set the end of a custom range. | +## Activity collection + +### `devlog collect` + +Collect development activity from this device and store it on the day it +happened. Entries keep their repository, branch, ticket keys, and time, and +their text is never rewritten. Running it again completes stored entries +instead of duplicating them. + +| Source | What it records | +| --- | --- | +| `git` | Commits you authored on every branch, branch activity from the reflog, and uncommitted or unpushed work on the checked-out branch, for the repositories under `collect.git.roots`. | + +| Option | Description | +| --- | --- | +| `--date ` | Collect a specific day (defaults to today). | +| `--from `, `--to ` | Collect a range of days. | +| `--sources ` | Comma-separated sources (defaults to `collect.sources`). | +| `--dry-run` | Print what would be collected without writing it. | +| `--remote` | Pull and push the configured data repository around the collection. | +| `--json` | Print the collection report as JSON. | + +Each run also records, per device and source, when it last ran and which +window it covered, under `devices/` in the data directory. + +```bash +devlog collect --dry-run +devlog collect --from 2026-08-17 --to 2026-08-21 +``` + ## GitHub activity ### `devlog sync` diff --git a/docs/configuration.md b/docs/configuration.md index a92fcd6..be2e091 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,6 +24,12 @@ devlog config set defaults.project my-project | `llm.baseURL` | Optional OpenAI-compatible API base URL. | empty | | `llm.model` | Model sent to the provider. | `openai/gpt-oss-120b:free` | | `llm.apiKeyEnvVar` | Environment variable containing the LLM API key. | `OPENROUTER_API_KEY` | +| `device.name` | Name that labels this device in collected activity. | Host name | +| `collect.sources` | Sources `devlog collect` uses when `--sources` is omitted. | `git` | +| `collect.timezone` | IANA time zone collected activity is filed under. | System time zone | +| `collect.ticketPattern` | Regular expression for ticket keys in branches and descriptions. | `\b[A-Z][A-Z0-9]+-[0-9]+\b` | +| `collect.git.roots` | Directories searched for Git repositories, up to four levels deep. | empty | +| `collect.git.authorEmails` | Author emails whose commits are yours. | Each repository's `user.email` | | `remote.enabled` | Whether Git synchronization is configured. | `false` | | `remote.url` | Data repository URL. | empty | | `remote.branch` | Data repository branch. | `main` | @@ -31,6 +37,22 @@ devlog config set defaults.project my-project A custom `storage.path` must be a dedicated data directory. It cannot contain DevLog's configuration or credential files. +## Activity collection + +List settings take comma-separated values: + +```bash +devlog config set device.name laptop +devlog config set collect.timezone America/Los_Angeles +devlog config set collect.git.roots ~/dev/work-projects +devlog config set collect.git.authorEmails you@company.com,you@example.com +devlog config set collect.ticketPattern 'PROJ-[0-9]+' +devlog collect --dry-run +``` + +Narrow `collect.ticketPattern` to your tracker's project keys when the default +also matches words such as `UTF-8`. + ## GitHub Set a username explicitly or leave it empty to use the account authenticated by diff --git a/internal/collector/collector.go b/internal/collector/collector.go new file mode 100644 index 0000000..4fb75d5 --- /dev/null +++ b/internal/collector/collector.go @@ -0,0 +1,168 @@ +// Package collector gathers development activity from local tools and remote +// services into DevLog entries, without rewriting it. +package collector + +import ( + "context" + "errors" + "fmt" + "regexp" + "slices" + "strings" + "time" + + "devlog/internal/store" + + // Collection runs on machines without Go's zone database, such as + // Windows, where time.LoadLocation would otherwise fail. + _ "time/tzdata" +) + +// DefaultTicketPattern matches issue keys such as PROJ-236. +const DefaultTicketPattern = `\b[A-Z][A-Z0-9]+-[0-9]+\b` + +// Window is the half-open time range [From, To) a collection covers. +type Window struct { + From time.Time + To time.Time + Location *time.Location +} + +// DayWindow covers the calendar day of day in loc. +func DayWindow(day time.Time, loc *time.Location) Window { + from := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, loc) + return Window{From: from, To: from.AddDate(0, 0, 1), Location: loc} +} + +// DaysWindow covers the calendar days from first to last, both included. +func DaysWindow(first, last time.Time, loc *time.Location) Window { + window := DayWindow(first, loc) + window.To = DayWindow(last, loc).To + return window +} + +// Contains reports whether t falls inside the window. +func (w Window) Contains(t time.Time) bool { + return !t.Before(w.From) && t.Before(w.To) +} + +// Day returns t's calendar day in the window's location as YYYY-MM-DD. +func (w Window) Day(t time.Time) string { + return t.In(w.Location).Format("2006-01-02") +} + +// Request is what a collector needs to run. +type Request struct { + Window Window + // DeviceID identifies this device in the sources of entries that only + // it can see, such as branch activity. + DeviceID string +} + +// Collector gathers the entries of one source. +type Collector interface { + Name() string + Collect(ctx context.Context, request Request) ([]store.Entry, error) +} + +// SkippedError reports that a collector's source is not available or not +// configured on this device. It is not a failure. +type SkippedError struct { + Reason string +} + +func (e *SkippedError) Error() string { return e.Reason } + +// Skip returns a SkippedError with a formatted reason. +func Skip(format string, args ...any) error { + return &SkippedError{Reason: fmt.Sprintf(format, args...)} +} + +// Result is the outcome of one collector. +type Result struct { + Collector string + Entries []store.Entry + Skipped string + Err error +} + +// Options adjust the entries every collector returns. +type Options struct { + DeviceID string + // DeviceName labels the entries with the device that collected them. + DeviceName string + Tickets *regexp.Regexp +} + +// Run runs each collector over the window. Entries are labeled with the +// device, given the ticket keys found in their branch and first description +// line, and dropped when their activity falls outside the window. A collector +// that fails partway keeps the entries it returned with its error. +func Run(ctx context.Context, collectors []Collector, window Window, options Options) []Result { + request := Request{Window: window, DeviceID: options.DeviceID} + results := make([]Result, 0, len(collectors)) + for _, collector := range collectors { + result := Result{Collector: collector.Name()} + entries, err := collector.Collect(ctx, request) + var skipped *SkippedError + if errors.As(err, &skipped) { + result.Skipped = skipped.Reason + results = append(results, result) + continue + } + result.Err = err + for _, entry := range entries { + if entry.Activity == nil || !window.Contains(entry.Activity.OccurredAt) { + continue + } + activity := *entry.Activity + if activity.Device == "" { + activity.Device = options.DeviceName + } + activity.Tickets = append(slices.Clone(activity.Tickets), Tickets(options.Tickets, activity.Branch, firstLine(entry.Description))...) + entry.Activity = &activity + result.Entries = append(result.Entries, entry) + } + results = append(results, result) + } + return results +} + +// Tickets returns the distinct ticket keys pattern finds in texts. +func Tickets(pattern *regexp.Regexp, texts ...string) []string { + if pattern == nil { + return nil + } + var found []string + for _, text := range texts { + for _, match := range pattern.FindAllString(text, -1) { + if !slices.Contains(found, match) { + found = append(found, match) + } + } + } + return found +} + +// ShortRepoName turns "owner/repo" into "repo", the project name entries of +// that repository share. +func ShortRepoName(fullName string) string { + if i := strings.LastIndex(fullName, "/"); i >= 0 { + return fullName[i+1:] + } + return fullName +} + +// Truncate shortens text to at most limit runes, marking the cut. +func Truncate(text string, limit int) string { + runes := []rune(text) + if len(runes) <= limit { + return text + } + return strings.TrimSpace(string(runes[:limit])) + "…" +} + +func firstLine(text string) string { + line, _, _ := strings.Cut(text, "\n") + return line +} diff --git a/internal/collector/gitlocal/gitlocal.go b/internal/collector/gitlocal/gitlocal.go new file mode 100644 index 0000000..eaececa --- /dev/null +++ b/internal/collector/gitlocal/gitlocal.go @@ -0,0 +1,582 @@ +// Package gitlocal collects activity from the Git repositories on this +// device: authored commits on every branch, branch activity recorded in the +// reflog, and the uncommitted and unpushed work of the checked-out branch. +package gitlocal + +import ( + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "devlog/internal/collector" + "devlog/internal/store" +) + +const ( + defaultMaxDepth = 4 + commandTimeout = 30 * time.Second + maxBodyLength = 1500 + maxStatFiles = 500 +) + +// skippedDirectories are never searched for repositories. +var skippedDirectories = map[string]bool{ + "node_modules": true, "vendor": true, "dist": true, "build": true, "target": true, "bin": true, "obj": true, +} + +// Collector reads the repositories found under Roots. +type Collector struct { + Roots []string + // AuthorEmails select the commits that are yours. When empty, each + // repository's user.email is used. + AuthorEmails []string + MaxDepth int + Git string + now func() time.Time +} + +func (c *Collector) Name() string { return "git" } + +func (c *Collector) Collect(ctx context.Context, request collector.Request) ([]store.Entry, error) { + if len(c.Roots) == 0 { + return nil, collector.Skip("no repository roots are configured; run devlog config set collect.git.roots [,...]") + } + git := c.git() + if _, err := exec.LookPath(git); err != nil { + return nil, collector.Skip("git is not installed") + } + repositories, err := Discover(c.Roots, c.MaxDepth) + if err != nil { + return nil, err + } + var entries []store.Entry + var errs []error + for _, dir := range repositories { + repoEntries, err := c.collectRepository(ctx, dir, request) + if err != nil { + errs = append(errs, fmt.Errorf("%s: %w", dir, err)) + } + entries = append(entries, repoEntries...) + } + return entries, errors.Join(errs...) +} + +func (c *Collector) git() string { + if c.Git != "" { + return c.Git + } + return "git" +} + +func (c *Collector) clock() time.Time { + if c.now != nil { + return c.now() + } + return time.Now() +} + +// Discover returns the Git repositories under roots, searching at most +// maxDepth directories deep and not inside repositories, hidden directories, +// or dependency and build folders. +func Discover(roots []string, maxDepth int) ([]string, error) { + if maxDepth <= 0 { + maxDepth = defaultMaxDepth + } + var found []string + for _, root := range roots { + root, err := expandHome(root) + if err != nil { + return nil, err + } + info, err := os.Stat(root) + if err != nil { + return nil, fmt.Errorf("could not read repository root %s: %w", root, err) + } + if !info.IsDir() { + return nil, fmt.Errorf("repository root %s is not a directory", root) + } + err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + if path == root { + return err + } + return fs.SkipDir + } + if !entry.IsDir() { + return nil + } + if path != root && (strings.HasPrefix(entry.Name(), ".") || skippedDirectories[entry.Name()]) { + return fs.SkipDir + } + if _, err := os.Stat(filepath.Join(path, ".git")); err == nil { + if !slices.Contains(found, path) { + found = append(found, path) + } + return fs.SkipDir + } + if rel, err := filepath.Rel(root, path); err == nil && rel != "." && len(strings.Split(rel, string(filepath.Separator))) >= maxDepth { + return fs.SkipDir + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("could not search repository root %s: %w", root, err) + } + } + return found, nil +} + +// Repository identifies a working tree. +type Repository struct { + Dir string + // Name is "owner/repo" from the remote URL, or the directory name. + Name string + remotes []string +} + +// Identify finds the repository that contains dir. +func Identify(ctx context.Context, git, dir string) (Repository, error) { + if git == "" { + git = "git" + } + top, err := run(ctx, git, dir, "rev-parse", "--show-toplevel") + if err != nil { + return Repository{}, err + } + repo := Repository{Dir: filepath.Clean(strings.TrimSpace(string(top)))} + repo.Name = filepath.Base(repo.Dir) + if output, err := run(ctx, git, repo.Dir, "remote"); err == nil { + repo.remotes = strings.Fields(string(output)) + } + remote := "origin" + if !slices.Contains(repo.remotes, remote) && len(repo.remotes) > 0 { + remote = repo.remotes[0] + } + if len(repo.remotes) > 0 { + if output, err := run(ctx, git, repo.Dir, "remote", "get-url", remote); err == nil { + if name := RepoNameFromURL(strings.TrimSpace(string(output))); name != "" { + repo.Name = name + } + } + } + return repo, nil +} + +var scpLikeURL = regexp.MustCompile(`^[^@/]+@[^:/]+:(.+)$`) + +// RepoNameFromURL returns "owner/repo" for a remote URL, or "" when it has +// no such path. +func RepoNameFromURL(url string) string { + path := url + if match := scpLikeURL.FindStringSubmatch(url); match != nil { + path = match[1] + } else if _, rest, ok := strings.Cut(url, "://"); ok { + if _, after, ok := strings.Cut(rest, "/"); ok { + path = after + } else { + return "" + } + } + path = strings.TrimSuffix(strings.Trim(path, "/"), ".git") + parts := strings.Split(path, "/") + if len(parts) >= 3 && parts[len(parts)-2] == "_git" { + // Azure DevOps: https://dev.azure.com///_git/ + parts = append(parts[:len(parts)-2], parts[len(parts)-1]) + } + if len(parts) < 2 || parts[len(parts)-2] == "" || parts[len(parts)-1] == "" { + return "" + } + return parts[len(parts)-2] + "/" + parts[len(parts)-1] +} + +type branchDay struct { + day string + branch string +} + +type branchActivity struct { + first, last time.Time + count int + changes *store.Changes +} + +func (a *branchActivity) add(t time.Time) { + if a.count == 0 || t.Before(a.first) { + a.first = t + } + if a.count == 0 || t.After(a.last) { + a.last = t + } + a.count++ +} + +func (c *Collector) collectRepository(ctx context.Context, dir string, request collector.Request) ([]store.Entry, error) { + git := c.git() + window := request.Window + repo, err := Identify(ctx, git, dir) + if err != nil { + return nil, err + } + emails := c.AuthorEmails + if len(emails) == 0 { + if output, err := run(ctx, git, repo.Dir, "config", "user.email"); err == nil && strings.TrimSpace(string(output)) != "" { + emails = []string{strings.TrimSpace(string(output))} + } + } + + reflog, err := readReflog(ctx, git, repo.Dir) + if err != nil { + return nil, err + } + activity := map[branchDay]*branchActivity{} + touch := func(branch string, t time.Time) { + if branch == "" || !window.Contains(t) { + return + } + key := branchDay{day: window.Day(t), branch: branch} + if activity[key] == nil { + activity[key] = &branchActivity{} + } + activity[key].add(t.In(window.Location)) + } + commitBranches := walkReflog(reflog, touch) + + var entries []store.Entry + if len(emails) > 0 { + commits, err := c.commits(ctx, repo, emails, window, commitBranches) + if err != nil { + return nil, err + } + entries = append(entries, commits...) + } + + now := c.clock() + if window.Contains(now) { + branch, changes, mtimes, err := workingTree(ctx, git, repo.Dir) + if err != nil { + return nil, err + } + if branch != "" { + today := branchDay{day: window.Day(now), branch: branch} + for _, mtime := range mtimes { + if window.Day(mtime) == today.day { + touch(branch, mtime) + } + } + if current := activity[today]; current != nil && changes != nil { + current.changes = changes + } + } + } + + for key, branch := range activity { + entries = append(entries, branchEntry(repo, key, branch, request.DeviceID)) + } + return entries, nil +} + +func branchEntry(repo Repository, key branchDay, activity *branchActivity, deviceID string) store.Entry { + description := "Activity on branch " + key.branch + if summary := describeChanges(activity.changes); summary != "" { + description += "; " + summary + } + entry := store.Entry{ + Project: collector.ShortRepoName(repo.Name), + Description: description, + Tags: []string{"git", "branch"}, + Source: fmt.Sprintf("git:branch:%s:%s:%s:%s", deviceID, repo.Name, key.branch, key.day), + Activity: &store.Activity{ + Kind: store.KindBranchActivity, + Collector: "git", + OccurredAt: activity.first, + Repo: repo.Name, + Branch: key.branch, + Directory: repo.Dir, + Count: activity.count, + Changes: activity.changes, + }, + } + if activity.last.After(activity.first) { + last := activity.last + entry.Activity.EndedAt = &last + } + return entry +} + +func describeChanges(changes *store.Changes) string { + if changes == nil { + return "" + } + var parts []string + if changes.Files > 0 { + parts = append(parts, fmt.Sprintf("%d uncommitted files (+%d −%d)", changes.Files, changes.Insertions, changes.Deletions)) + } + if changes.Untracked > 0 { + parts = append(parts, fmt.Sprintf("%d untracked", changes.Untracked)) + } + if changes.Unpushed > 0 { + parts = append(parts, fmt.Sprintf("%d unpushed commits", changes.Unpushed)) + } + return strings.Join(parts, ", ") +} + +type reflogEntry struct { + at time.Time + subject string + sha string +} + +// readReflog returns HEAD's reflog, oldest first. A repository without one +// returns nothing. +func readReflog(ctx context.Context, git, dir string) ([]reflogEntry, error) { + output, err := run(ctx, git, dir, "log", "--walk-reflogs", "--date=unix", "--format=%gd%x1f%gs%x1f%H", "-n", "20000", "HEAD") + if err != nil { + if _, headErr := run(ctx, git, dir, "rev-parse", "--verify", "HEAD"); headErr != nil { + return nil, nil + } + return nil, err + } + var entries []reflogEntry + for line := range strings.SplitSeq(strings.TrimSpace(string(output)), "\n") { + fields := strings.Split(line, "\x1f") + if len(fields) != 3 { + continue + } + selector := fields[0] + open, close := strings.LastIndex(selector, "{"), strings.LastIndex(selector, "}") + if open < 0 || close < open { + continue + } + seconds, err := strconv.ParseInt(selector[open+1:close], 10, 64) + if err != nil { + continue + } + entries = append(entries, reflogEntry{at: time.Unix(seconds, 0), subject: fields[1], sha: fields[2]}) + } + slices.Reverse(entries) + return entries, nil +} + +var ( + checkoutSubject = regexp.MustCompile(`^checkout: moving from .+ to (.+)$`) + finishSubject = regexp.MustCompile(`\(finish\): returning to refs/heads/(.+)$`) + fullSHA = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) +) + +// walkReflog follows the checked-out branch through the reflog, reporting +// each operation on a branch to touch, and returns the branch every commit +// was made on. +func walkReflog(entries []reflogEntry, touch func(branch string, at time.Time)) map[string]string { + commitBranches := map[string]string{} + current := "" + for _, entry := range entries { + if match := checkoutSubject.FindStringSubmatch(entry.subject); match != nil { + current = match[1] + if fullSHA.MatchString(current) { + current = "" + } + } else if match := finishSubject.FindStringSubmatch(entry.subject); match != nil { + current = match[1] + } else if strings.HasPrefix(entry.subject, "commit") && current != "" { + commitBranches[entry.sha] = current + } + touch(current, entry.at) + } + return commitBranches +} + +func (c *Collector) commits(ctx context.Context, repo Repository, emails []string, window collector.Window, commitBranches map[string]string) ([]store.Entry, error) { + // --since filters by committer date, which is never earlier than the + // author date, so it cannot drop a commit authored in the window. + args := []string{"log", "--branches", "--remotes", "--no-merges", "--source", "--fixed-strings", + "--since=" + window.From.Format(time.RFC3339), "--format=%H%x1f%aI%x1f%S%x1f%s%x1f%b%x1e"} + for _, email := range emails { + args = append(args, "--author="+email) + } + output, err := run(ctx, c.git(), repo.Dir, args...) + if err != nil { + if _, headErr := run(ctx, c.git(), repo.Dir, "rev-parse", "--verify", "HEAD"); headErr != nil { + return nil, nil + } + return nil, err + } + var entries []store.Entry + for record := range strings.SplitSeq(string(output), "\x1e") { + fields := strings.SplitN(strings.TrimLeft(record, "\r\n"), "\x1f", 5) + if len(fields) != 5 { + continue + } + sha, subject, body := fields[0], fields[3], strings.TrimSpace(fields[4]) + authored, err := time.Parse(time.RFC3339, fields[1]) + if err != nil || !window.Contains(authored) { + continue + } + branch := commitBranches[sha] + if branch == "" { + branch = repo.branchFromRef(fields[2]) + } + description := subject + if body != "" { + description += "\n\n" + collector.Truncate(body, maxBodyLength) + } + entries = append(entries, store.Entry{ + Project: collector.ShortRepoName(repo.Name), + Description: description, + Tags: []string{"git", "commit"}, + Source: "commit:" + sha, + Activity: &store.Activity{ + Kind: store.KindCommit, + Collector: "git", + OccurredAt: authored, + Repo: repo.Name, + Branch: branch, + SHA: sha, + Directory: repo.Dir, + }, + }) + } + return entries, nil +} + +// branchFromRef turns the ref git log --source reports into a branch name. +func (r Repository) branchFromRef(ref string) string { + ref = strings.TrimPrefix(ref, "refs/heads/") + ref = strings.TrimPrefix(ref, "refs/remotes/") + for _, remote := range r.remotes { + if branch, ok := strings.CutPrefix(ref, remote+"/"); ok { + return branch + } + } + if ref == "HEAD" { + return "" + } + return ref +} + +// workingTree returns the checked-out branch, its uncommitted and unpushed +// work, and when the changed files were last modified. +func workingTree(ctx context.Context, git, dir string) (string, *store.Changes, []time.Time, error) { + output, err := run(ctx, git, dir, "status", "--porcelain=v2", "--branch", "-z") + if err != nil { + return "", nil, nil, err + } + var branch, oid string + upstream := false + changes := &store.Changes{} + var paths []string + records := strings.Split(string(output), "\x00") + for i := 0; i < len(records); i++ { + record := records[i] + switch { + case strings.HasPrefix(record, "# branch.head "): + branch = strings.TrimPrefix(record, "# branch.head ") + case strings.HasPrefix(record, "# branch.oid "): + oid = strings.TrimPrefix(record, "# branch.oid ") + case strings.HasPrefix(record, "# branch.upstream "): + upstream = true + case strings.HasPrefix(record, "# branch.ab "): + var ahead, behind int + if _, err := fmt.Sscanf(strings.TrimPrefix(record, "# branch.ab "), "+%d -%d", &ahead, &behind); err == nil { + changes.Unpushed = ahead + } + case strings.HasPrefix(record, "1 "): + changes.Files++ + paths = append(paths, field(record, 8)) + case strings.HasPrefix(record, "2 "): + changes.Files++ + paths = append(paths, field(record, 9)) + i++ // the original path follows a rename or copy + case strings.HasPrefix(record, "u "): + changes.Files++ + paths = append(paths, field(record, 10)) + case strings.HasPrefix(record, "? "): + changes.Untracked++ + paths = append(paths, strings.TrimPrefix(record, "? ")) + } + } + if branch == "(detached)" { + return "", nil, nil, nil + } + if !upstream && oid != "" && oid != "(initial)" { + if count, err := run(ctx, git, dir, "rev-list", "--count", "HEAD", "--not", "--remotes"); err == nil { + changes.Unpushed, _ = strconv.Atoi(strings.TrimSpace(string(count))) + } + } + if changes.Files > 0 && oid != "(initial)" { + if stat, err := run(ctx, git, dir, "diff", "--shortstat", "HEAD"); err == nil { + changes.Insertions, changes.Deletions = parseShortstat(string(stat)) + } + } + var mtimes []time.Time + for _, path := range paths[:min(len(paths), maxStatFiles)] { + if info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(path))); err == nil { + mtimes = append(mtimes, info.ModTime()) + } + } + if *changes == (store.Changes{}) { + changes = nil + } + return branch, changes, mtimes, nil +} + +// field returns the porcelain v2 path that follows n space-separated fields. +func field(record string, n int) string { + parts := strings.SplitN(record, " ", n+1) + if len(parts) <= n { + return "" + } + return parts[n] +} + +var shortstatNumber = regexp.MustCompile(`(\d+) (insertion|deletion)`) + +func parseShortstat(stat string) (insertions, deletions int) { + for _, match := range shortstatNumber.FindAllStringSubmatch(stat, -1) { + value, _ := strconv.Atoi(match[1]) + if match[2] == "insertion" { + insertions = value + } else { + deletions = value + } + } + return insertions, deletions +} + +func run(ctx context.Context, git, dir string, args ...string) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, commandTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, git, append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0") + var stderr bytes.Buffer + cmd.Stderr = &stderr + output, err := cmd.Output() + if err != nil { + message := strings.TrimSpace(stderr.String()) + if message == "" { + message = err.Error() + } + return output, fmt.Errorf("git %s failed: %s", args[0], message) + } + return output, nil +} + +func expandHome(path string) (string, error) { + if path == "~" || strings.HasPrefix(path, "~/") || strings.HasPrefix(path, `~\`) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + path = filepath.Join(home, path[1:]) + } + return filepath.Abs(path) +} diff --git a/internal/collector/gitlocal/gitlocal_test.go b/internal/collector/gitlocal/gitlocal_test.go new file mode 100644 index 0000000..ae3bf3d --- /dev/null +++ b/internal/collector/gitlocal/gitlocal_test.go @@ -0,0 +1,199 @@ +package gitlocal + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "regexp" + "testing" + "time" + + "devlog/internal/collector" + "devlog/internal/store" +) + +const me = "me@example.com" + +func gitAt(t *testing.T, dir string, at time.Time, email string, args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + stamp := at.Format(time.RFC3339) + cmd.Env = append(os.Environ(), + "GIT_AUTHOR_NAME=Dev", "GIT_AUTHOR_EMAIL="+email, "GIT_AUTHOR_DATE="+stamp, + "GIT_COMMITTER_NAME=Dev", "GIT_COMMITTER_EMAIL="+email, "GIT_COMMITTER_DATE="+stamp, + ) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v failed: %s", args, output) + } +} + +func isolateGit(t *testing.T) { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") +} + +func writeFile(t *testing.T, path, content string, mtime time.Time) { + t.Helper() + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, mtime, mtime); err != nil { + t.Fatal(err) + } +} + +func TestCollectReadsCommitsBranchesAndUncommittedWork(t *testing.T) { + isolateGit(t) + loc, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + t.Fatal(err) + } + at := func(hour, minute int) time.Time { return time.Date(2026, 8, 17, hour, minute, 0, 0, loc) } + + root := t.TempDir() + dir := filepath.Join(root, "work", "widgets") + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + gitAt(t, dir, at(8, 0), me, "init", "-b", "main") + gitAt(t, dir, at(8, 0), me, "remote", "add", "origin", "git@github.com:acme/widgets.git") + writeFile(t, filepath.Join(dir, "a.txt"), "a\n", at(9, 0)) + gitAt(t, dir, at(9, 0), me, "add", ".") + gitAt(t, dir, at(9, 0), me, "commit", "-m", "chore: start") + gitAt(t, dir, at(10, 0), me, "checkout", "-b", "feature/PROJ-7-widgets") + writeFile(t, filepath.Join(dir, "b.txt"), "b\n", at(10, 30)) + gitAt(t, dir, at(10, 30), me, "add", ".") + gitAt(t, dir, at(10, 30), me, "commit", "-m", "feat: add widgets", "-m", "Explains the widgets.") + writeFile(t, filepath.Join(dir, "c.txt"), "c\n", at(11, 0)) + gitAt(t, dir, at(11, 0), "someone@example.com", "add", ".") + gitAt(t, dir, at(11, 0), "someone@example.com", "commit", "-m", "feat: someone else's work") + writeFile(t, filepath.Join(dir, "a.txt"), "a\nmore\n", at(14, 0)) + writeFile(t, filepath.Join(dir, "new.txt"), "new\n", at(14, 5)) + + c := &Collector{Roots: []string{root}, AuthorEmails: []string{me}, now: func() time.Time { return at(15, 0) }} + window := collector.DayWindow(at(0, 0), loc) + entries, err := c.Collect(context.Background(), collector.Request{Window: window, DeviceID: "device-1"}) + if err != nil { + t.Fatal(err) + } + + commits := map[string]store.Entry{} + var branches []store.Entry + for _, entry := range entries { + switch entry.Activity.Kind { + case store.KindCommit: + commits[entry.Description] = entry + case store.KindBranchActivity: + branches = append(branches, entry) + } + } + if len(commits) != 2 { + t.Fatalf("commits = %v, want only the two authored by me", commits) + } + feature, ok := commits["feat: add widgets\n\nExplains the widgets."] + if !ok { + t.Fatalf("commits = %v, want the feature commit with its body", commits) + } + if feature.Activity.Branch != "feature/PROJ-7-widgets" || feature.Activity.Repo != "acme/widgets" || feature.Project != "widgets" { + t.Errorf("feature commit activity = %+v", feature.Activity) + } + if !feature.Activity.OccurredAt.Equal(at(10, 30)) || feature.Source != "commit:"+feature.Activity.SHA { + t.Errorf("feature commit = %+v", feature) + } + + if len(branches) != 1 { + t.Fatalf("branch activity = %+v, want only the feature branch", branches) + } + branch := branches[0] + if branch.Activity.Branch != "feature/PROJ-7-widgets" || !branch.Activity.OccurredAt.Equal(at(10, 0)) || !branch.Activity.EndedAt.Equal(at(14, 5)) { + t.Errorf("branch activity = %+v from %v to %v", branch.Activity, branch.Activity.OccurredAt, branch.Activity.EndedAt) + } + if branch.Source != "git:branch:device-1:acme/widgets:feature/PROJ-7-widgets:2026-08-17" { + t.Errorf("branch source = %q", branch.Source) + } + want := store.Changes{Files: 1, Insertions: 1, Untracked: 1, Unpushed: 3} + if branch.Activity.Changes == nil || *branch.Activity.Changes != want { + t.Errorf("changes = %+v, want %+v", branch.Activity.Changes, want) + } + + results := collector.Run(context.Background(), []collector.Collector{c}, window, collector.Options{ + DeviceName: "laptop", Tickets: regexp.MustCompile(collector.DefaultTicketPattern), + }) + for _, entry := range results[0].Entries { + if entry.Activity.Branch == "feature/PROJ-7-widgets" && (len(entry.Activity.Tickets) != 1 || entry.Activity.Tickets[0] != "PROJ-7") { + t.Errorf("tickets of %q = %v, want [PROJ-7]", entry.Description, entry.Activity.Tickets) + } + if entry.Activity.Device != "laptop" { + t.Errorf("device of %q = %q", entry.Description, entry.Activity.Device) + } + } +} + +func TestCollectSkipsWithoutRoots(t *testing.T) { + _, err := (&Collector{}).Collect(context.Background(), collector.Request{}) + if _, ok := err.(*collector.SkippedError); !ok { + t.Fatalf("error = %v, want a skip", err) + } +} + +func TestDiscoverSkipsHiddenAndDependencyFolders(t *testing.T) { + root := t.TempDir() + for _, path := range []string{"a/.git", "b/node_modules/c/.git", ".hidden/d/.git", "e/f/.git", "a/nested/.git"} { + if err := os.MkdirAll(filepath.Join(root, path), 0755); err != nil { + t.Fatal(err) + } + } + found, err := Discover([]string{root}, 4) + if err != nil { + t.Fatal(err) + } + want := []string{filepath.Join(root, "a"), filepath.Join(root, "e", "f")} + if len(found) != len(want) || found[0] != want[0] || found[1] != want[1] { + t.Fatalf("Discover() = %v, want %v", found, want) + } +} + +func TestRepoNameFromURL(t *testing.T) { + for url, want := range map[string]string{ + "git@github.com:acme/widgets-api.git": "acme/widgets-api", + "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/Example/Widgets.Api.git": "Example/Widgets.Api", + "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/acme/widgets-docs": "acme/widgets-docs", + "ssh://git@github.com/acme/widgets.git": "acme/widgets", + "https://dev.azure.com/org/project/_git/repo": "project/repo", + "/srv/git/widgets.git": "git/widgets", + "https://example.com": "", + } { + if got := RepoNameFromURL(url); got != want { + t.Errorf("RepoNameFromURL(%q) = %q, want %q", url, got, want) + } + } +} + +func TestWalkReflogFollowsCheckoutsAndRebases(t *testing.T) { + base := time.Date(2026, 8, 17, 9, 0, 0, 0, time.UTC) + entries := []reflogEntry{ + {at: base, subject: "commit (initial): start", sha: "1"}, + {at: base.Add(time.Minute), subject: "checkout: moving from main to feature/x", sha: "1"}, + {at: base.Add(2 * time.Minute), subject: "commit: work", sha: "2"}, + {at: base.Add(3 * time.Minute), subject: "checkout: moving from feature/x to 0123456789abcdef0123456789abcdef01234567", sha: "3"}, + {at: base.Add(4 * time.Minute), subject: "rebase (pick): work", sha: "4"}, + {at: base.Add(5 * time.Minute), subject: "rebase (finish): returning to refs/heads/feature/x", sha: "4"}, + } + touched := map[string]int{} + commits := walkReflog(entries, func(branch string, _ time.Time) { + if branch != "" { + touched[branch]++ + } + }) + if touched["feature/x"] != 3 || len(touched) != 1 { + t.Errorf("touched = %v, want feature/x three times", touched) + } + if commits["2"] != "feature/x" || commits["1"] != "" { + t.Errorf("commit branches = %v", commits) + } +} diff --git a/internal/store/activity.go b/internal/store/activity.go index 41ea8fd..abbe667 100644 --- a/internal/store/activity.go +++ b/internal/store/activity.go @@ -19,7 +19,6 @@ const ( KindComment = "comment" KindBranchCreated = "branch-created" KindBranchActivity = "branch-activity" - KindWIP = "wip" KindSession = "session" KindNote = "note" ) @@ -48,7 +47,8 @@ type Activity struct { Count int `json:"count,omitempty"` } -// Changes summarizes uncommitted or unpushed work in a repository. +// Changes summarizes the uncommitted and unpushed work on a branch when it +// was collected. type Changes struct { Files int `json:"files,omitempty"` Insertions int `json:"insertions,omitempty"` @@ -61,7 +61,7 @@ type Changes struct { // the work goes on, so a later collection replaces it instead of filling it. func (a *Activity) Snapshot() bool { switch a.Kind { - case KindWIP, KindSession, KindBranchActivity: + case KindSession, KindBranchActivity: return true } return false