diff --git a/README.md b/README.md index 2e7be3e..4779dee 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,8 @@ It provides: - **Contributor detail pages** — summary metrics, charts, repositories, pull requests and reviews. - **Repository list and detail pages** — contributors, commits, PRs, reviews, - last activity, archived status. + last activity, archived status. Every column header on the list sorts the + table; clicking the active column flips the direction. - **Status page** — sync health, GraphQL rate limit, stored row counts, run history. - **Global date filter** — 7 or 30 days, 3/6/12 months or a custom range, applied consistently across every page. diff --git a/internal/database/database_test.go b/internal/database/database_test.go index 25137da..2f45de7 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -387,7 +387,7 @@ func TestOrganizationIsolation(t *testing.T) { } } - repos, err := db.RepositoryRanking(ctx, f) + repos, err := db.RepositoryRanking(ctx, f, metrics.DefaultRepositorySort, metrics.SortDesc) if err != nil { t.Fatal(err) } @@ -471,7 +471,7 @@ func TestArchivedRepositoriesAreExcludedFromAnalytics(t *testing.T) { // The repository list keeps archived repositories visible and flagged. f.IncludeArchived = true - repos, err := db.RepositoryRanking(ctx, f) + repos, err := db.RepositoryRanking(ctx, f, metrics.DefaultRepositorySort, metrics.SortDesc) if err != nil { t.Fatal(err) } @@ -799,7 +799,7 @@ func TestRepositoryAndContributorDetailQueries(t *testing.T) { } // A repository with no activity in the window must still be listed. - ranking, err := db.RepositoryRanking(ctx, f) + ranking, err := db.RepositoryRanking(ctx, f, metrics.DefaultRepositorySort, metrics.SortDesc) if err != nil { t.Fatal(err) } @@ -895,3 +895,123 @@ func contains(haystack, needle string) bool { return false })() } + +func TestRepositoryRankingSortsByEveryColumn(t *testing.T) { + db := testDB(t) + ctx := context.Background() + org := mustOrg(t, db, "O_1", "acme") + + // zulu: most commits, no reviews, active, newest activity. + zulu := mustRepo(t, db, org, "R_z", "zulu", false) + // alpha: fewest commits, most reviews, oldest activity. + alpha := mustRepo(t, db, org, "R_a", "alpha", false) + // mike is archived and has no activity at all. + mike := mustRepo(t, db, org, "R_m", "mike", true) + + alice := mustContributor(t, db, "U_alice", "alice", false) + bob := mustContributor(t, db, "U_bob", "bob", false) + + for i := 0; i < 6; i++ { + mustCommit(t, db, org.ID, zulu, &alice, fmt.Sprintf("z%d", i), day(10+i), 100, 10, 5) + } + mustCommit(t, db, org.ID, alpha, &alice, "a1", day(2), 5, 1, 1) + mustCommit(t, db, org.ID, alpha, &bob, "a2", day(2), 5, 1, 1) + + prZ := mustPR(t, db, org.ID, zulu, &alice, "PR_z", 1, day(11), nil, nil) + prA := mustPR(t, db, org.ID, alpha, &alice, "PR_a1", 1, day(2), nil, nil) + merged := day(3) + mustPR(t, db, org.ID, alpha, &bob, "PR_a2", 2, day(2), &merged, &merged) + _ = prZ + + mustReview(t, db, org.ID, alpha, prA, &bob, "RV_1", models.ReviewApproved, day(3), 1) + mustReview(t, db, org.ID, alpha, prA, &alice, "RV_2", models.ReviewCommented, day(3), 1) + + rebuild(t, db, org.ID, []int64{zulu, alpha, mike}) + + f := fullRange() + f.OrganizationID = org.ID + f.IncludeArchived = true + + cases := []struct { + key, dir string + wantTop string + }{ + {"name", metrics.SortAsc, "alpha"}, + {"name", metrics.SortDesc, "zulu"}, + {"commits", metrics.SortDesc, "zulu"}, + {"contributors", metrics.SortDesc, "alpha"}, + {"additions", metrics.SortDesc, "zulu"}, + {"prs_opened", metrics.SortDesc, "alpha"}, + {"prs_merged", metrics.SortDesc, "alpha"}, + {"reviews", metrics.SortDesc, "alpha"}, + {"last_activity", metrics.SortDesc, "zulu"}, + {"last_activity", metrics.SortAsc, "alpha"}, + {"status", metrics.SortDesc, "mike"}, + } + for _, c := range cases { + t.Run(c.key+"-"+c.dir, func(t *testing.T) { + rows, err := db.RepositoryRanking(ctx, f, c.key, c.dir) + if err != nil { + t.Fatalf("sort by %s %s: %v", c.key, c.dir, err) + } + if len(rows) != 3 { + t.Fatalf("got %d rows, want 3", len(rows)) + } + if rows[0].Name != c.wantTop { + names := make([]string, len(rows)) + for i, r := range rows { + names[i] = r.Name + } + t.Errorf("sorted by %s %s the order is %v, want %q first", c.key, c.dir, names, c.wantTop) + } + }) + } +} + +func TestRepositoriesWithoutActivitySortLastInBothDirections(t *testing.T) { + db := testDB(t) + ctx := context.Background() + org := mustOrg(t, db, "O_1", "acme") + active := mustRepo(t, db, org, "R_a", "active", false) + idle := mustRepo(t, db, org, "R_i", "idle", false) + alice := mustContributor(t, db, "U_alice", "alice", false) + + mustCommit(t, db, org.ID, active, &alice, "c1", day(2), 10, 1, 1) + rebuild(t, db, org.ID, []int64{active, idle}) + + f := fullRange() + f.OrganizationID = org.ID + + // A repository with no activity in the period has a NULL last_activity. It + // must never jump to the top of an ascending sort. + for _, dir := range []string{metrics.SortAsc, metrics.SortDesc} { + rows, err := db.RepositoryRanking(ctx, f, "last_activity", dir) + if err != nil { + t.Fatal(err) + } + if rows[len(rows)-1].Name != "idle" { + t.Errorf("sorting last_activity %s put %q last, want idle", dir, rows[len(rows)-1].Name) + } + } +} + +func TestRepositoryRankingIgnoresAnInjectedSortKey(t *testing.T) { + db := testDB(t) + ctx := context.Background() + org := mustOrg(t, db, "O_1", "acme") + mustRepo(t, db, org, "R_1", "api", false) + + f := fullRange() + f.OrganizationID = org.ID + + rows, err := db.RepositoryRanking(ctx, f, "name; DROP TABLE repositories", "ASC; DROP TABLE repositories") + if err != nil { + t.Fatalf("an unknown sort must be ignored, not fail: %v", err) + } + if len(rows) != 1 { + t.Errorf("got %d rows, want 1", len(rows)) + } + if countRows(t, db, "repositories") != 1 { + t.Fatal("the repositories table disappeared: the sort key reached SQL") + } +} diff --git a/internal/database/queries.go b/internal/database/queries.go index 851a4bb..b83f6ae 100644 --- a/internal/database/queries.go +++ b/internal/database/queries.go @@ -317,10 +317,18 @@ SELECT r.id, r.organization_id, r.github_id, r.name, r.full_name, r.url, r.descr WHERE r.organization_id = $1 AND ($4 OR NOT r.is_archived)` -// RepositoryRanking returns repository rows for the repositories page. -func (db *DB) RepositoryRanking(ctx context.Context, f Filter) ([]models.RepositoryStats, error) { - q := repositoryStatsSQL + ` - ORDER BY COALESCE(stats.commits, 0) DESC, COALESCE(stats.prs_opened, 0) DESC, lower(r.name) ASC` +// RepositoryRanking returns repository rows for the repositories page, ordered +// by one column. +// +// sortKey and sortDir are resolved through the metrics allow-list, so the +// ORDER BY clause can only ever contain a known column reference and one of two +// direction keywords. +func (db *DB) RepositoryRanking(ctx context.Context, f Filter, sortKey, sortDir string) ([]models.RepositoryStats, error) { + col, dir := metrics.ResolveRepositorySort(sortKey, sortDir) + // Repositories with no activity in the period sort last either way, rather + // than jumping to the top of an ascending sort. + q := repositoryStatsSQL + fmt.Sprintf( + "\n ORDER BY %s %s NULLS LAST, lower(r.name) ASC", col.SortExpr, metrics.SQLDirection(dir)) rows, err := db.Pool.Query(ctx, q, f.args()...) if err != nil { diff --git a/internal/http/handlers.go b/internal/http/handlers.go index 2555b84..766cdaa 100644 --- a/internal/http/handlers.go +++ b/internal/http/handlers.go @@ -4,6 +4,7 @@ package http import ( "encoding/json" + "html/template" "net/http" "net/url" "strconv" @@ -190,7 +191,7 @@ func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { s.serverError(w, r, err) return } - repos, err := s.db.RepositoryRanking(ctx, pc.Filter) + repos, err := s.db.RepositoryRanking(ctx, pc.Filter, metrics.DefaultRepositorySort, metrics.SortDesc) if err != nil { s.serverError(w, r, err) return @@ -332,9 +333,28 @@ func (s *Server) handleContributor(w http.ResponseWriter, r *http.Request) { s.render(w, r, http.StatusOK, "contributor.html", view) } +// sortHeader is one clickable column header of the repositories table. +type sortHeader struct { + Label string + Title string + // Numeric headers are right-aligned, matching their cells. + Numeric bool + // Active marks the column the table is currently ordered by. + Active bool + // Ascending is meaningful only when Active is set. + Ascending bool + Href template.URL + // AriaSort is the value of the th aria-sort attribute. + AriaSort string +} + type repositoriesView struct { layoutData Rows []models.RepositoryStats + Headers []sortHeader + SortKey string + SortDir string + SortLabel string IncludeArchived bool } @@ -343,8 +363,22 @@ func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) { if !ok { return } - view := repositoriesView{layoutData: pc.Layout, IncludeArchived: s.cfg.IncludeArchived} + q := r.URL.Query() + col, dir := metrics.ResolveRepositorySort(q.Get("sort"), q.Get("dir")) + + view := repositoriesView{ + layoutData: pc.Layout, + IncludeArchived: s.cfg.IncludeArchived, + SortKey: col.Key, + SortDir: dir, + SortLabel: col.Label, + Headers: repositoryHeaders(pc.Layout.Range.Query(), col.Key, dir), + } view.Title = "Repositories" + // Keep the chosen column in the period picker and the navigation links. + view.Query = cloneValues(pc.Layout.Range.Query()) + view.Query.Set("sort", col.Key) + view.Query.Set("dir", dir) if pc.Org == nil { s.render(w, r, http.StatusOK, "repositories.html", view) @@ -355,7 +389,7 @@ func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) { // visible and clearly marked, even when excluded from analytics. filter := pc.Filter filter.IncludeArchived = true - rows, err := s.db.RepositoryRanking(r.Context(), filter) + rows, err := s.db.RepositoryRanking(r.Context(), filter, col.Key, dir) if err != nil { s.serverError(w, r, err) return @@ -364,6 +398,40 @@ func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) { s.render(w, r, http.StatusOK, "repositories.html", view) } +// repositoryHeaders builds one header link per sortable column. Clicking the +// active column flips its direction; clicking any other starts at that column's +// natural direction. +func repositoryHeaders(base url.Values, activeKey, activeDir string) []sortHeader { + cols := metrics.RepositoryColumns() + out := make([]sortHeader, 0, len(cols)) + for _, c := range cols { + active := c.Key == activeKey + next := c.ToggleDirection(activeKey, activeDir) + + v := cloneValues(base) + v.Set("sort", c.Key) + v.Set("dir", next) + + aria := "none" + if active { + aria = "descending" + if activeDir == metrics.SortAsc { + aria = "ascending" + } + } + out = append(out, sortHeader{ + Label: c.Label, + Title: c.Title, + Numeric: c.Numeric, + Active: active, + Ascending: active && activeDir == metrics.SortAsc, + Href: template.URL("/repositories?" + v.Encode()), + AriaSort: aria, + }) + } + return out +} + type repositoryView struct { layoutData Repository models.RepositoryStats diff --git a/internal/http/handlers_test.go b/internal/http/handlers_test.go index ee22cb2..b6a6063 100644 --- a/internal/http/handlers_test.go +++ b/internal/http/handlers_test.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "net/url" "os" "strconv" "strings" @@ -18,6 +19,7 @@ import ( "github.com/relaxart/dev-pulse/internal/config" "github.com/relaxart/dev-pulse/internal/database" "github.com/relaxart/dev-pulse/internal/github" + "github.com/relaxart/dev-pulse/internal/metrics" "github.com/relaxart/dev-pulse/internal/models" "github.com/relaxart/dev-pulse/migrations" "github.com/relaxart/dev-pulse/web" @@ -482,3 +484,183 @@ func TestReportBeforeTheFirstSyncIsAnEmptyDocumentNotAnError(t *testing.T) { t.Fatal("an empty report must not reach for GitHub to fill itself in") } } + +// countTag returns how many times an HTML tag opens inside the given fragment. +func countTag(fragment, tag string) int { + return strings.Count(fragment, "<"+tag+" ") + strings.Count(fragment, "<"+tag+">") +} + +func TestRepositoryTableHeadersAreSortLinks(t *testing.T) { + ts := newTestServer(t) + body := ts.get(t, "/repositories?period=12m").Body.String() + + for _, col := range []string{ + "name", "contributors", "commits", "additions", + "prs_opened", "prs_merged", "reviews", "last_activity", "status", + } { + if !strings.Contains(body, "sort="+col) { + t.Errorf("the repositories table offers no sort link for %q", col) + } + } + if !strings.Contains(body, `aria-sort="descending"`) { + t.Error("the active column should expose aria-sort for screen readers") + } + // Every header link must carry the current date filter. + if strings.Count(body, "period=12m") < 9 { + t.Error("header links drop the selected period") + } +} + +// The header list and the table body are written in two different places, so a +// column added to one and not the other would silently misalign every cell. +func TestRepositoryHeaderCountMatchesTheBodyColumns(t *testing.T) { + ts := newTestServer(t) + body := ts.get(t, "/repositories?period=12m").Body.String() + + head := body[strings.Index(body, ""):strings.Index(body, "")] + headers := countTag(head, "th") + + rest := body[strings.Index(body, "
"):] + firstRow := rest[:strings.Index(rest, "")] + cells := countTag(firstRow, "td") + + if headers == 0 || cells == 0 { + t.Fatalf("could not read the table: %d headers, %d cells", headers, cells) + } + if headers != cells { + t.Errorf("the table has %d headers but %d cells per row", headers, cells) + } + if want := len(metrics.RepositoryColumns()); headers != want { + t.Errorf("rendered %d headers, want %d sortable columns", headers, want) + } +} + +func TestRepositorySortChangesTheOrder(t *testing.T) { + ts := newTestServer(t) + + // The seed has "api" (active, with commits) and "legacy" (archived, empty). + byName := ts.get(t, "/repositories?period=12m&sort=name&dir=asc").Body.String() + byNameDesc := ts.get(t, "/repositories?period=12m&sort=name&dir=desc").Body.String() + + apiFirst := strings.Index(byName, ">api<") < strings.Index(byName, ">legacy<") + legacyFirst := strings.Index(byNameDesc, ">legacy<") < strings.Index(byNameDesc, ">api<") + if !apiFirst { + t.Error("ascending name sort did not put api before legacy") + } + if !legacyFirst { + t.Error("descending name sort did not put legacy before api") + } +} + +// headerHrefs extracts the repositories table header links from a page. +func headerHrefs(t *testing.T, body string) []url.Values { + t.Helper() + var out []url.Values + const marker = `href="/repositories?` + for i := strings.Index(body, marker); i >= 0; { + rest := body[i+len(marker):] + raw := rest[:strings.Index(rest, `"`)] + // The template escapes & as & in attribute values. + q, err := url.ParseQuery(strings.ReplaceAll(raw, "&", "&")) + if err != nil { + t.Fatalf("header link %q is not a valid query: %v", raw, err) + } + out = append(out, q) + next := strings.Index(rest, marker) + if next < 0 { + break + } + i = i + len(marker) + next + } + if len(out) == 0 { + t.Fatal("no repositories header links were rendered") + } + return out +} + +// hasLink reports whether any header link asks for exactly this column and +// direction. +func hasLink(links []url.Values, sortKey, dir string) bool { + for _, q := range links { + if q.Get("sort") == sortKey && q.Get("dir") == dir { + return true + } + } + return false +} + +func TestRepositoryHeaderTogglesDirection(t *testing.T) { + ts := newTestServer(t) + + // While sorted by commits descending, the commits header must offer ascending. + links := headerHrefs(t, ts.get(t, "/repositories?period=12m&sort=commits&dir=desc").Body.String()) + if !hasLink(links, "commits", "asc") { + t.Error("the active commits header does not toggle to ascending") + } + // An inactive column offers its own default rather than the active direction. + if !hasLink(links, "name", "asc") { + t.Error("the inactive name header should start ascending") + } + if !hasLink(links, "last_activity", "desc") { + t.Error("the inactive last activity header should start descending") + } + + body := ts.get(t, "/repositories?period=12m&sort=commits&dir=asc").Body.String() + if !hasLink(headerHrefs(t, body), "commits", "desc") { + t.Error("an ascending commits header does not toggle back to descending") + } + if !strings.Contains(body, `aria-sort="ascending"`) { + t.Error("an ascending column should report aria-sort=ascending") + } + + // Every header link keeps the selected period. + for _, q := range headerHrefs(t, body) { + if q.Get("period") != "12m" { + t.Errorf("header link for %q dropped the period: %v", q.Get("sort"), q) + } + } +} + +func TestRepositorySortSurvivesAPeriodChange(t *testing.T) { + ts := newTestServer(t) + body := ts.get(t, "/repositories?period=12m&sort=reviews&dir=asc").Body.String() + + // The period form posts every other parameter back as a hidden input. + if !strings.Contains(body, ``) { + t.Error("the period picker drops the chosen sort column") + } + if !strings.Contains(body, ``) { + t.Error("the period picker drops the chosen sort direction") + } +} + +func TestInvalidRepositorySortFallsBackWithoutFailing(t *testing.T) { + ts := newTestServer(t) + for _, q := range []string{ + "?sort=nonsense", "?sort=name;DROP+TABLE+repositories", "?sort=commits&dir=sideways", "?dir=asc", + } { + w := ts.get(t, "/repositories"+q) + if w.Code != http.StatusOK { + t.Errorf("GET /repositories%s = %d, want 200", q, w.Code) + } + if !strings.Contains(w.Body.String(), "sorted by") { + t.Errorf("GET /repositories%s did not render the table", q) + } + } + + // An unknown column falls back to the documented default. + body := ts.get(t, "/repositories?sort=nonsense").Body.String() + if !strings.Contains(body, "sorted by Commits") { + t.Error("an unknown column should fall back to the default Commits sort") + } +} + +func TestOnlyTheRepositoriesTableIsSortable(t *testing.T) { + ts := newTestServer(t) + // The dashboard's repository panel is a fixed top-N list, not a sortable + // table; adding links there would suggest a sort that does not exist. + body := ts.get(t, "/?period=12m").Body.String() + if strings.Contains(body, `aria-sort=`) { + t.Error("the dashboard should not advertise sortable headers") + } +} diff --git a/internal/metrics/repositories.go b/internal/metrics/repositories.go new file mode 100644 index 0000000..6489786 --- /dev/null +++ b/internal/metrics/repositories.go @@ -0,0 +1,108 @@ +package metrics + +// Sort directions accepted by the repositories table. +const ( + SortAsc = "asc" + SortDesc = "desc" +) + +// RepositoryColumn documents one sortable column of the repositories table. +type RepositoryColumn struct { + Key string + Label string + // Title explains a column whose label is too short to be obvious. + Title string + // Numeric columns are right-aligned in the table. + Numeric bool + // SortExpr is the SQL expression used to order by this column. It comes from + // this fixed table only and is never built from user input. + SortExpr string + // DefaultDir is the direction applied the first time a column is chosen: + // biggest-first for counts, A-Z for names. + DefaultDir string +} + +// repositoryColumns is the complete allow-list, in table order. The repositories +// template renders one header per entry, so this list also fixes the column +// order of the page. +var repositoryColumns = []RepositoryColumn{ + {Key: "name", Label: "Repository", SortExpr: "lower(r.name)", DefaultDir: SortAsc}, + {Key: "contributors", Label: "Contributors", Numeric: true, + SortExpr: "COALESCE(stats.contributors, 0)", DefaultDir: SortDesc}, + {Key: "commits", Label: "Commits", Numeric: true, + SortExpr: "COALESCE(stats.commits, 0)", DefaultDir: SortDesc}, + {Key: "additions", Label: "+/−", Title: "Sort by lines added", Numeric: true, + SortExpr: "COALESCE(stats.additions, 0)", DefaultDir: SortDesc}, + {Key: "prs_opened", Label: "PRs opened", Numeric: true, + SortExpr: "COALESCE(stats.prs_opened, 0)", DefaultDir: SortDesc}, + {Key: "prs_merged", Label: "PRs merged", Numeric: true, + SortExpr: "COALESCE(stats.prs_merged, 0)", DefaultDir: SortDesc}, + {Key: "reviews", Label: "Reviews", Numeric: true, + SortExpr: "COALESCE(stats.reviews_submitted, 0)", DefaultDir: SortDesc}, + {Key: "last_activity", Label: "Last activity", Numeric: true, + SortExpr: "stats.last_activity", DefaultDir: SortDesc}, + {Key: "status", Label: "Status", Title: "Sort active repositories before archived ones", + SortExpr: "r.is_archived", DefaultDir: SortAsc}, +} + +// DefaultRepositorySort is applied when no (or an unknown) column is requested. +const DefaultRepositorySort = "commits" + +var repositoryColumnsByKey = func() map[string]RepositoryColumn { + m := make(map[string]RepositoryColumn, len(repositoryColumns)) + for _, c := range repositoryColumns { + m[c.Key] = c + } + return m +}() + +// RepositoryColumns returns every sortable column in table order. +func RepositoryColumns() []RepositoryColumn { + out := make([]RepositoryColumn, len(repositoryColumns)) + copy(out, repositoryColumns) + return out +} + +// IsValidRepositorySort reports whether key names a known column. +func IsValidRepositorySort(key string) bool { + _, ok := repositoryColumnsByKey[key] + return ok +} + +// ResolveRepositorySort maps a requested column and direction onto the +// allow-list. Unknown values fall back to the default, so a hand-edited URL can +// never reach the SQL builder. +func ResolveRepositorySort(key, dir string) (RepositoryColumn, string) { + col, ok := repositoryColumnsByKey[key] + if !ok { + col = repositoryColumnsByKey[DefaultRepositorySort] + return col, col.DefaultDir + } + switch dir { + case SortAsc, SortDesc: + return col, dir + default: + return col, col.DefaultDir + } +} + +// SQLDirection converts a resolved direction into a SQL keyword. Only the two +// allow-listed values can reach it. +func SQLDirection(dir string) string { + if dir == SortAsc { + return "ASC" + } + return "DESC" +} + +// ToggleDirection is the direction a header link should request: the opposite of +// the current one when the column is already sorted, its default otherwise. +func (c RepositoryColumn) ToggleDirection(activeKey, activeDir string) string { + if c.Key != activeKey { + return c.DefaultDir + } + if activeDir == SortAsc { + return SortDesc + } + return SortAsc +} diff --git a/internal/metrics/repositories_test.go b/internal/metrics/repositories_test.go new file mode 100644 index 0000000..4477fe7 --- /dev/null +++ b/internal/metrics/repositories_test.go @@ -0,0 +1,136 @@ +package metrics + +import ( + "regexp" + "strings" + "testing" +) + +// repositoryTableColumns is the set of columns the repositories page must let a +// user sort by. A regression here silently removes a header link. +var repositoryTableColumns = []string{ + "name", "contributors", "commits", "additions", + "prs_opened", "prs_merged", "reviews", "last_activity", "status", +} + +func TestEverySortableRepositoryColumnExists(t *testing.T) { + for _, key := range repositoryTableColumns { + if !IsValidRepositorySort(key) { + t.Errorf("repository column %q is not sortable", key) + } + col, _ := ResolveRepositorySort(key, "") + if col.Key != key { + t.Errorf("ResolveRepositorySort(%q).Key = %q", key, col.Key) + } + } + if len(RepositoryColumns()) != len(repositoryTableColumns) { + t.Errorf("RepositoryColumns() has %d entries, want %d", + len(RepositoryColumns()), len(repositoryTableColumns)) + } +} + +func TestRepositoryColumnsKeepTableOrder(t *testing.T) { + cols := RepositoryColumns() + for i, want := range repositoryTableColumns { + if cols[i].Key != want { + t.Fatalf("column %d is %q, want %q: the header order must match the table body", + i, cols[i].Key, want) + } + } +} + +func TestUnknownRepositorySortFallsBackToTheDefault(t *testing.T) { + // The column and the direction are both interpolated into an ORDER BY + // clause, so anything outside the allow-list must be discarded. + for _, key := range []string{ + "", "score", "r.name; DROP TABLE repositories", + "(SELECT 1)", "1) --", + } { + col, dir := ResolveRepositorySort(key, "desc") + if col.Key != DefaultRepositorySort { + t.Errorf("ResolveRepositorySort(%q) = %q, want the default %q", key, col.Key, DefaultRepositorySort) + } + if dir != SortDesc { + t.Errorf("ResolveRepositorySort(%q) direction = %q", key, dir) + } + if IsValidRepositorySort(key) { + t.Errorf("IsValidRepositorySort(%q) must be false", key) + } + } +} + +func TestUnknownDirectionFallsBackToTheColumnDefault(t *testing.T) { + for _, dir := range []string{"", "sideways", "ASC; DROP TABLE repositories", "descending"} { + if _, got := ResolveRepositorySort("name", dir); got != SortAsc { + t.Errorf("direction %q on name resolved to %q, want the column default asc", dir, got) + } + if _, got := ResolveRepositorySort("commits", dir); got != SortDesc { + t.Errorf("direction %q on commits resolved to %q, want the column default desc", dir, got) + } + } + // A valid direction is honoured on every column. + for _, key := range repositoryTableColumns { + if _, got := ResolveRepositorySort(key, SortAsc); got != SortAsc { + t.Errorf("%s did not accept an explicit ascending sort", key) + } + } +} + +func TestSQLDirectionOnlyEverEmitsTwoKeywords(t *testing.T) { + if got := SQLDirection(SortAsc); got != "ASC" { + t.Errorf("SQLDirection(asc) = %q", got) + } + for _, dir := range []string{SortDesc, "", "nonsense", "ASC --"} { + if got := SQLDirection(dir); got != "DESC" && got != "ASC" { + t.Errorf("SQLDirection(%q) = %q, which is not a bare SQL keyword", dir, got) + } + } +} + +// safeOrderExpr allows the column references and COALESCE wrappers the table +// uses, and nothing that could carry an injection. +var safeOrderExpr = regexp.MustCompile(`^(lower\()?(r|stats)\.[a-z_]+\)?$|^COALESCE\((r|stats)\.[a-z_]+, 0\)$`) + +func TestRepositorySortExpressionsAreFixedColumnReferences(t *testing.T) { + for _, c := range RepositoryColumns() { + if !safeOrderExpr.MatchString(c.SortExpr) { + t.Errorf("column %q has an unexpected SQL expression %q", c.Key, c.SortExpr) + } + for _, bad := range []string{";", "--", "/*", "'"} { + if strings.Contains(c.SortExpr, bad) { + t.Errorf("column %q expression contains %q", c.Key, bad) + } + } + } +} + +func TestToggleDirection(t *testing.T) { + commits, _ := ResolveRepositorySort("commits", "") + name, _ := ResolveRepositorySort("name", "") + + // An inactive column starts at its own default. + if got := commits.ToggleDirection("name", SortAsc); got != SortDesc { + t.Errorf("inactive commits toggles to %q, want desc", got) + } + if got := name.ToggleDirection("commits", SortDesc); got != SortAsc { + t.Errorf("inactive name toggles to %q, want asc", got) + } + // The active column flips. + if got := commits.ToggleDirection("commits", SortDesc); got != SortAsc { + t.Errorf("active commits desc toggles to %q, want asc", got) + } + if got := commits.ToggleDirection("commits", SortAsc); got != SortDesc { + t.Errorf("active commits asc toggles to %q, want desc", got) + } +} + +func TestEveryRepositoryColumnIsLabelled(t *testing.T) { + for _, c := range RepositoryColumns() { + if c.Label == "" { + t.Errorf("column %q has no header label", c.Key) + } + if c.DefaultDir != SortAsc && c.DefaultDir != SortDesc { + t.Errorf("column %q has an invalid default direction %q", c.Key, c.DefaultDir) + } + } +} diff --git a/internal/report/report.go b/internal/report/report.go index 118d3bd..4705cdf 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -21,7 +21,7 @@ type Store interface { Overview(ctx context.Context, f database.Filter) (models.OverviewStats, error) TimeSeries(ctx context.Context, f database.Filter, g metrics.Granularity, contributorID, repositoryID *int64) ([]models.TimePoint, error) ContributorRanking(ctx context.Context, f database.Filter, sortKey string, limit, offset int) ([]models.ContributorStats, error) - RepositoryRanking(ctx context.Context, f database.Filter) ([]models.RepositoryStats, error) + RepositoryRanking(ctx context.Context, f database.Filter, sortKey, sortDir string) ([]models.RepositoryStats, error) } // Request describes the report to produce. @@ -137,7 +137,10 @@ func Collect(ctx context.Context, store Store, req Request) (*Data, error) { } d.Contributors = contributors - repositories, err := store.RepositoryRanking(ctx, req.Filter) + // The report always lists repositories by activity; the table header sort is + // an on-screen affordance. + repositories, err := store.RepositoryRanking(ctx, req.Filter, + metrics.DefaultRepositorySort, metrics.SortDesc) if err != nil { return nil, fmt.Errorf("report repository ranking: %w", err) } diff --git a/internal/report/report_test.go b/internal/report/report_test.go index ded8ea7..5ac6939 100644 --- a/internal/report/report_test.go +++ b/internal/report/report_test.go @@ -57,7 +57,7 @@ func (f *fakeStore) ContributorRanking(ctx context.Context, filter database.Filt return f.contributors, nil } -func (f *fakeStore) RepositoryRanking(ctx context.Context, filter database.Filter) ([]models.RepositoryStats, error) { +func (f *fakeStore) RepositoryRanking(ctx context.Context, filter database.Filter, sortKey, sortDir string) ([]models.RepositoryStats, error) { f.filters = append(f.filters, filter) return f.repositories, f.err } diff --git a/web/static/css/app.css b/web/static/css/app.css index 83a332c..5e7f170 100644 --- a/web/static/css/app.css +++ b/web/static/css/app.css @@ -220,6 +220,9 @@ main { flex: 1 0 auto; } .table > thead th a:hover { color: var(--md-primary); } .table > thead th.sorted a { color: var(--md-primary); font-weight: 700; } .table > thead th.sorted::after { content: " ▼"; color: var(--md-primary); font-size: .6rem; } +.table > thead th.sorted.asc::after { content: " ▲"; } +.table > thead th.sortable a { display: inline-block; } +.table > thead th.sortable:hover { background: var(--md-primary-softer); } .table > tbody td { border-color: var(--md-outline-soft); font-size: .9rem; } .ranking-table td, .ranking-table th { padding-left: .5rem; padding-right: .5rem; } .row-archived { opacity: .62; } diff --git a/web/templates/repositories.html b/web/templates/repositories.html index 4853c36..33d866f 100644 --- a/web/templates/repositories.html +++ b/web/templates/repositories.html @@ -4,7 +4,10 @@{{.Org}} · {{.Range.Label}}
++ {{.Org}} · {{.Range.Label}} · sorted by {{.SortLabel}} + ({{if eq .SortDir "asc"}}ascending{{else}}descending{{end}}) +
| Repository | -Contributors | -Commits | -+/− | -PRs opened | -PRs merged | -Reviews | -Last activity | -Status | + {{range .Headers}} ++ {{.Label}} + | + {{end}}
|---|