diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 271e043..95cc09c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,17 @@ jobs: - name: Verify modules run: make verify + - name: Install Tailwind CSS + env: + TAILWIND_VERSION: v4.3.5 # keep in sync with the header of static/app.css + run: | + curl -sSfL -o "$RUNNER_TEMP/tailwindcss" \ + "https://github.com/tailwindlabs/tailwindcss/releases/download/${TAILWIND_VERSION}/tailwindcss-linux-x64" + chmod +x "$RUNNER_TEMP/tailwindcss" + + - name: CSS is up to date + run: make css-check TAILWIND="$RUNNER_TEMP/tailwindcss" + - name: Lint run: make lint diff --git a/Makefile b/Makefile index 6d9bb6f..a78161d 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,18 @@ # golangci-lint must be installed and in PATH (CI installs it via # golangci/golangci-lint-action). Override with: make lint GOLANGCI_LINT=/path/to/bin GOLANGCI_LINT ?= golangci-lint +# The Tailwind CSS v4 standalone CLI is only needed to rebuild or check +# static/app.css. CI pins its version; use the same one locally, since +# css-check compares the output byte for byte. +# Override with: make css TAILWIND=/path/to/tailwindcss +TAILWIND ?= tailwindcss APP := fromscope CMD := . .DEFAULT_GOAL := help -.PHONY: help require-golangci-lint fmt lint test cover vuln tidy-check verify check build clean +.PHONY: help require-golangci-lint fmt lint test cover vuln tidy-check verify check build require-tailwind css css-check clean help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | \ @@ -20,6 +25,13 @@ require-golangci-lint: exit 1; \ } +require-tailwind: + @command -v $(TAILWIND) >/dev/null 2>&1 || { \ + echo "error: '$(TAILWIND)' not found in PATH." >&2; \ + echo "Install it: https://tailwindcss.com/docs/installation/tailwind-cli" >&2; \ + exit 1; \ + } + fmt: require-golangci-lint ## Format code (gofumpt + goimports) $(GOLANGCI_LINT) fmt @@ -47,5 +59,16 @@ check: tidy-check verify lint test vuln ## Run every quality check (used by CI) build: ## Build the binary go build -trimpath -o $(APP) $(CMD) +css: require-tailwind ## Build static/app.css from input.css and the templates + $(TAILWIND) -i input.css -o static/app.css --minify + +css-check: require-tailwind ## Fail if static/app.css is out of date with the templates + @tmp=$$(mktemp) || exit 1; trap 'rm -f "$$tmp"' EXIT; \ + $(TAILWIND) -i input.css -o "$$tmp" --minify || exit 1; \ + cmp -s "$$tmp" static/app.css || { \ + echo "error: static/app.css is out of date, run: make css" >&2; \ + exit 1; \ + } + clean: ## Remove build artifacts rm -f $(APP) cover.out diff --git a/README.md b/README.md index bee777a..17f3db8 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,11 @@ load any CSV and offer filtering and grouping on arbitrary columns. Early development. What works today: - Loading a CSV file with a header row into memory. -- Dropping rows whose `tiene_from` column is `no`. +- Dropping rows whose `tiene_from` column is `no`, then hiding that column. +- Serving the resulting table as a web page on `-addr` (default `:8080`). Planned: -- Web interface to browse the data (served on `-addr`, default `:8080`). - Filters and groupings by column. - Support for arbitrary CSV formats. @@ -30,7 +30,8 @@ Planned: - First line is a header with the column names (surrounding spaces are trimmed). - Every row must have the same number of fields as the header. -- A `tiene_from` column must exist; rows where it equals `no` are discarded. +- A `tiene_from` column must exist; rows where it equals `no` are discarded, + and the column itself is not shown in the web view. Example: @@ -56,12 +57,14 @@ go build ./fromscope -csv path/to/file.csv ``` +Then open in your browser. + ### Flags | Flag | Default | Description | |---------|---------|-------------------------------------| | `-csv` | — | CSV file to load (required) | -| `-addr` | `:8080` | TCP address to listen on (planned) | +| `-addr` | `:8080` | TCP address to listen on | ## Development @@ -73,8 +76,20 @@ make help # list the available targets make fmt # format the code (fixes most lint issues) make check # run every quality check, the same as CI make build # build the fromscope binary +make css # rebuild static/app.css after changing classes in templates/ ``` +The stylesheet is built with the [Tailwind CSS](https://tailwindcss.com/docs/installation/tailwind-cli) +v4 standalone CLI (override the binary with `make css TAILWIND=/path/to/tailwindcss`). +The generated `static/app.css` is committed, so building the Go binary does not +require Tailwind. CI runs `make css-check` to make sure it matches the templates; +use the same Tailwind version as CI (pinned in `.github/workflows/ci.yml`), since +the output is compared byte for byte. + +[htmx](https://htmx.org/) 4.0.2 is vendored in `static/htmx.min.js` (the +minified file does not include its version). To update it, replace the file +with the `dist/htmx.min.js` of the new release and change the version here. + ## License [MIT](LICENSE) diff --git a/data.go b/data.go index c150dce..c2c436d 100644 --- a/data.go +++ b/data.go @@ -86,3 +86,20 @@ func (t *Table) DropRows(column, value string) (int, error) { return before - len(t.Rows), nil } + +// DropColumn removes the named column from Columns and from every row. +// It returns an error, leaving the table unchanged, if the column doesn't exist. +func (t *Table) DropColumn(column string) error { + idx := t.ColumnIndex(column) + if idx == -1 { + return fmt.Errorf("column %q not found", column) + } + + t.Columns = slices.Delete(t.Columns, idx, idx+1) + + for i, row := range t.Rows { + t.Rows[i] = slices.Delete(row, idx, idx+1) + } + + return nil +} diff --git a/data_test.go b/data_test.go index a3af097..7584166 100644 --- a/data_test.go +++ b/data_test.go @@ -149,3 +149,68 @@ func TestDropRows(t *testing.T) { } }) } + +func TestDropColumn(t *testing.T) { + newTable := func() *Table { + return &Table{ + Columns: []string{"repo", "has_from", "image"}, + Rows: [][]string{ + {"a", "yes", "alpine"}, + {"b", "no", "debian"}, + }, + } + } + + tests := []struct { + name string + column string + wantColumns []string + wantRows [][]string + }{ + { + name: "middle column", + column: "has_from", + wantColumns: []string{"repo", "image"}, + wantRows: [][]string{{"a", "alpine"}, {"b", "debian"}}, + }, + { + name: "first column", + column: "repo", + wantColumns: []string{"has_from", "image"}, + wantRows: [][]string{{"yes", "alpine"}, {"no", "debian"}}, + }, + { + name: "last column", + column: "image", + wantColumns: []string{"repo", "has_from"}, + wantRows: [][]string{{"a", "yes"}, {"b", "no"}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + table := newTable() + + if err := table.DropColumn(tt.column); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !slices.Equal(table.Columns, tt.wantColumns) { + t.Errorf("columns = %q, want %q", table.Columns, tt.wantColumns) + } + if !slices.EqualFunc(table.Rows, tt.wantRows, slices.Equal) { + t.Errorf("rows = %q, want %q", table.Rows, tt.wantRows) + } + }) + } + + t.Run("unknown column", func(t *testing.T) { + table := newTable() + + if err := table.DropColumn("missing"); err == nil { + t.Fatal("expected an error, got nil") + } + if len(table.Columns) != 3 || len(table.Rows[0]) != 3 { + t.Errorf("table changed: columns = %q, rows = %q", table.Columns, table.Rows) + } + }) +} diff --git a/go.mod b/go.mod index 9ba105f..a937cb0 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,8 @@ module github.com/angelabad/fromscope go 1.27.0 +toolchain go1.27.4 + tool golang.org/x/vuln/cmd/govulncheck require ( diff --git a/handlers.go b/handlers.go new file mode 100644 index 0000000..9cc8342 --- /dev/null +++ b/handlers.go @@ -0,0 +1,65 @@ +package main + +import ( + "bytes" + "embed" + "html/template" + "log" + "net/http" +) + +// assets holds the HTML templates and the static files (CSS, JS), +// embedded in the binary so it runs without any files next to it. +// +//go:embed templates static +var assets embed.FS + +// tmpl holds every page template, parsed once at startup. +// Templates are named after their file, e.g. "index.html". +var tmpl = template.Must(template.ParseFS(assets, "templates/*.html")) + +// server holds the state shared by the HTTP handlers. +type server struct { + table *Table // read-only after startup, safe for concurrent requests +} + +// newServer returns a server that serves the given table. +func newServer(t *Table) *server { + return &server{t} +} + +// routes returns the HTTP handler with every route registered. +func (s *server) routes() http.Handler { + router := http.NewServeMux() + + router.HandleFunc("GET /{$}", s.handleIndex) // {$} matches "/" only, anything else is a 404 + router.Handle("GET /static/", http.FileServer(http.FS(assets))) + + return router +} + +// handleIndex renders the full page with every row of the table. +func (s *server) handleIndex(w http.ResponseWriter, _ *http.Request) { + render(w, "index.html", s.table) +} + +// render executes the named template with data and writes it to w. +// The output is buffered first, so a template error replies with a +// clean 500 instead of a half-written page with a 200 status. +func render(w http.ResponseWriter, name string, data any) { + var buf bytes.Buffer + + if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil { + log.Printf("rendering %s: %v", name, err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, err := w.Write(buf.Bytes()) + if err != nil { + // Headers are already sent, so all we can do is log it + // (usually the client closed the connection). + log.Printf("writing response: %v", err) + } +} diff --git a/handlers_test.go b/handlers_test.go new file mode 100644 index 0000000..6a5b8fc --- /dev/null +++ b/handlers_test.go @@ -0,0 +1,116 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// newTestTable returns a small table; one cell contains HTML +// to check that templates escape it. +func newTestTable() *Table { + return &Table{ + Columns: []string{"repo", "image"}, + Rows: [][]string{ + {"app", "alpine:3.20"}, + {"web", ""}, + {"api", ""}, + }, + } +} + +// serve sends a request through the full router and returns the recorded response. +func serve(t *testing.T, table *Table, method, target string) *httptest.ResponseRecorder { + t.Helper() + + req := httptest.NewRequestWithContext(t.Context(), method, target, http.NoBody) + rec := httptest.NewRecorder() + newServer(table).routes().ServeHTTP(rec, req) + + return rec +} + +func TestHandleIndex(t *testing.T) { + rec := serve(t, newTestTable(), http.MethodGet, "/") + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + if got := rec.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") { + t.Errorf("Content-Type = %q, want text/html", got) + } + + body := rec.Body.String() + for _, want := range []string{ + ">repo", // header from Columns + ">image", // header from Columns + "alpine:3.20", // a cell value + ">3", // row counter + "<script>alert(1)</script>", // HTML in cells is escaped + } { + if !strings.Contains(body, want) { + t.Errorf("body does not contain %q", want) + } + } + if strings.Contains(body, " + + +
+
+
+

fromscope

+

Dockerfile base images by repository and branch

+
+

+ {{len .Rows}} rows +

+
+ +
+ + + + {{range .Columns}}{{end}} + + + + {{template "rows.html" .}} + +
{{.}}
+
+
+ + diff --git a/templates/rows.html b/templates/rows.html new file mode 100644 index 0000000..216fb9b --- /dev/null +++ b/templates/rows.html @@ -0,0 +1,9 @@ +{{range .Rows}} + + {{range .}}{{if .}}{{.}}{{else}}—{{end}}{{end}} + +{{else}} + + No matching rows + +{{end}}