diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..a9ab296 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Question or idea + url: https://github.com/vidya381/devcheck/discussions + about: Ask a question or talk through an idea before opening an issue. diff --git a/.github/ISSUE_TEMPLATE/new_check.md b/.github/ISSUE_TEMPLATE/new_check.md index 6eb4580..9b1a5fd 100644 --- a/.github/ISSUE_TEMPLATE/new_check.md +++ b/.github/ISSUE_TEMPLATE/new_check.md @@ -7,9 +7,14 @@ labels: checker, good first issue ## What does it check? ## When should it run? - + -## What does passing look like? +## Pass message -## What does failing look like? - +## Warn or fail message + + +## Fix text + + +## Anything else diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..d4db14c --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +## What this changes + + + +Closes # + +## Checklist + +- [ ] `go build ./...` passes +- [ ] `go test ./...` passes +- [ ] `go vet ./...` passes +- [ ] Tests cover the pass case and the fail case +- [ ] The issue is linked above diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1814ecb..83fcf1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,3 +24,5 @@ jobs: - name: Vet run: go vet ./... + - name: Format + run: test -z "$(gofmt -l .)" \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c75a690..0a5e013 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,9 @@ on: tags: - "v*.*.*" +permissions: + contents: write + jobs: release: runs-on: ubuntu-latest @@ -23,6 +26,12 @@ jobs: GOOS=darwin GOARCH=arm64 go build -ldflags="-X main.version=${{ github.ref_name }}" -o dist/devcheck-darwin-arm64 ./cmd/devcheck GOOS=windows GOARCH=amd64 go build -ldflags="-X main.version=${{ github.ref_name }}" -o dist/devcheck-windows-amd64.exe ./cmd/devcheck + - name: Generate checksums + run: | + cd dist + sha256sum devcheck-* > checksums.txt + cat checksums.txt + - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml new file mode 100644 index 0000000..916fea5 --- /dev/null +++ b/.pre-commit-hooks.yaml @@ -0,0 +1,7 @@ +- id: devcheck + name: devcheck + description: Check the dev environment has everything this project needs + entry: devcheck --ci + language: golang + pass_filenames: false + always_run: true diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..30a658d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +## Unreleased + +## v0.1.0 + +First release. + +- Detects Go, Node, Python, Ruby, Rust, Java, Docker and Docker Compose from project files, and Postgres, MySQL, MongoDB and Redis from environment variables. +- Checks binaries are on PATH: go, golangci-lint, node, npm/pnpm/yarn, python3, pip, ruby, bundler, rustc, cargo, java, mvn, gradle, docker. +- Version checks for Go (`go.mod`), Node (`.nvmrc` or `engines.node`) and Rust (`rust-toolchain.toml`). +- Dependency checks for Go, Node, Python and Ruby. +- Checks every path under `use` in `go.work` exists and has a `go.mod`. +- Checks `.env` has every key from `.env.example`, and warns on empty values. Handles quoted and multi-line values. +- Checks `.gitignore` covers `.env`, `*.log`, and `node_modules` or `__pycache__`. +- Checks for configured git hooks: `.husky` for Node, `pre-commit` for Python. +- Checks the Docker daemon responds, Compose services are running and Compose images are pulled. +- Port and ping checks for Postgres, MySQL, MongoDB and Redis. +- `devcheck.yml` with `require` for extra binaries and `skip` to drop checks by name. +- Flags: `--fix`, `--json`, `--ci`, `--verbose`, `--version`. +- Release binaries for linux, darwin and windows with `checksums.txt`, an install script, and a GitHub Action. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ee01535..1cdbb2d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,54 +1,69 @@ # Contributing -All contributions are welcome — new checks, bug fixes, docs, whatever. +New checks, bug fixes and docs are all welcome. I reply to issues and pull requests within a day or two. -## Setup - -Fork the repo first, then clone your fork: +## Build and test ```bash git clone https://github.com/YOUR_USERNAME/devcheck cd devcheck -go build ./cmd/devcheck +go build ./... go test ./... +go vet ./... ``` -## Adding a new check +`go build -o devcheck ./cmd/devcheck` gives you a binary to try in another directory. The repo gitignores `/devcheck` so it will not show up in your diff. + +## Adding a check -Most contributions are new checks. Here's how: +Every check is a struct with two methods, in `internal/check/`. Read [`internal/check/binary.go`](internal/check/binary.go) first, it is the smallest one. [`internal/check/gowork.go`](internal/check/gowork.go) is a good second example: it parses a file and reports which entries are missing. -1. Create `internal/checks/yourcheck.go` -2. Implement the `Check` interface: +1. Add `internal/check/yourcheck.go` in package `check`: ```go -type YourCheck struct{} +type YourCheck struct { + Dir string +} func (c *YourCheck) Name() string { return "your check name" } -func (c *YourCheck) Run(ctx context.Context) check.Result { - return check.Result{ - Name: c.Name(), - Status: check.StatusPass, - Message: "looks good", - Fix: "", // shown with --fix if this fails - } +func (c *YourCheck) Run(_ context.Context) Result { + return Result{ + Name: c.Name(), + Status: StatusPass, + Message: "what is true right now", + Fix: "", // printed under the failure when --fix is passed + } } ``` -3. Register it in `internal/check/registry.go` under the right stack condition -4. Add a test in `internal/checks/yourcheck_test.go` — cover both pass and fail -5. Run `go test ./...` and make sure everything passes -6. Open a PR referencing the issue (e.g. "Closes #5") +2. Register it in [`internal/check/registry.go`](internal/check/registry.go), inside the `if` for the stack it belongs to. If it needs a file that may not exist, guard it with `fileExists`. +3. If the check needs to detect something new, add the field to `DetectedStack` in [`internal/detector/detector.go`](internal/detector/detector.go) and set it in `Detect`. +4. Add `internal/check/yourcheck_test.go`. + +Statuses: `StatusPass`, `StatusWarn` for something worth mentioning that will not stop you working, `StatusFail` for something that will, and `StatusSkipped` when the check could not run at all. Skipped results are hidden unless `--verbose` is passed. + +Messages are lowercase and say what is true, not what to do. The `Fix` field is where the instruction goes. + +## Tests + +Cover at least the pass case and the fail case. Use `t.TempDir()` for anything that reads files. + +Do not make a test depend on a running service. Checks that talk to something take an injectable function so you can stub it: see `dialer` in `port.go` and `pinger` in `redis.go`. For a real connection failure without a server, dial a closed port on localhost. + +## Pull requests -Before you start on something, leave a comment on the issue so nobody duplicates work. +Fill in the checklist in the template. Link the issue in the description, for example "Closes #31". Comment on an issue before you start so two people do not write the same check. -## PR checklist +## Labels -- `go build ./...` passes -- `go test ./...` passes -- `go vet ./...` passes -- Test covers pass and fail cases +- `good first issue` — self-contained, nothing to ask me first +- `checker` — adds or changes a check +- `help wanted` — needs a judgement call or a service to test against +- `enhancement` — a feature that is not a check +- `bug` — something is broken +- `documentation` — docs only ## Questions -Open a GitHub Discussion or leave a comment on the issue. +Open a Discussion or comment on the issue. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5a6c4c0 --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +BIN := devcheck + +.PHONY: build test vet install + +build: + go build -o $(BIN) ./cmd/devcheck + +test: + go test ./... + +vet: + go vet ./... + +install: + go install ./cmd/devcheck diff --git a/README.md b/README.md index c9eba27..8bf408e 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,123 @@ # devcheck -Check if your local dev environment is ready to run a project. +[![CI](https://github.com/vidya381/devcheck/actions/workflows/ci.yml/badge.svg)](https://github.com/vidya381/devcheck/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/vidya381/devcheck)](https://github.com/vidya381/devcheck/releases) [![Go Report Card](https://goreportcard.com/badge/github.com/vidya381/devcheck)](https://goreportcard.com/report/github.com/vidya381/devcheck) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) -``` -$ devcheck +devcheck looks at the files in a project, works out what stack it uses, and tells you what is missing or not running before you try to start it. -Detected: Go, Docker +## Output -✅ go installed -✅ Docker daemon running -❌ .env missing keys: DB_PASSWORD, API_KEY +Run it in a project directory with no arguments. +``` +$ devcheck +✅ node is installed +✅ npm is installed +✅ Node 22.23.2 installed (need 20.11.0) +❌ node_modules directory not found +⚠️ .husky directory not found; git hooks for Node are not configured +✅ docker is installed +❌ Docker daemon is not running +❌ missing keys: API_KEY +⚠️ Missing 1 sensitive file pattern ──────────────────────────────────────── -2 passed 0 warnings 1 failed -Run devcheck --fix for suggestions + 4 passed 2 warnings 3 failed + Run `devcheck --fix` for suggestions ``` -Run it in any project directory. devcheck looks at your project files, figures out what stack you're using, and checks that everything is actually running and configured before you waste time debugging. - ---- - ## Install -**One-liner:** ```bash curl -fsSL https://raw.githubusercontent.com/vidya381/devcheck/main/scripts/install.sh | bash ``` -**Go install:** +Or with Go: + ```bash go install github.com/vidya381/devcheck/cmd/devcheck@latest ``` -Or grab a binary from [releases](https://github.com/vidya381/devcheck/releases) — linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64. - ---- +Binaries for linux/amd64, linux/arm64, darwin/amd64, darwin/arm64 and windows/amd64 are on the [releases page](https://github.com/vidya381/devcheck/releases). ## Usage -```bash -devcheck # run all checks -devcheck --fix # show a suggested fix for each failure -devcheck --json # output results as JSON -devcheck --ci # exit code 1 on any failure (for CI pipelines) -devcheck --verbose # show skipped checks too ``` - ---- +devcheck run every check that applies to this project +devcheck --fix print a suggested fix under each failure +devcheck --json print results as JSON +devcheck --ci exit 1 if any check failed +devcheck --verbose also print checks that were skipped +devcheck --version print the version +``` ## What it checks -devcheck detects your stack from project files and runs the relevant checks automatically — no config needed. +Nothing is configured. devcheck picks checks based on what it finds in the directory. | Detected from | Checks | -|---------------|--------| -| `go.mod` | go binary, go version | -| `package.json` | node, npm, node version | -| `requirements.txt` / `pyproject.toml` | python3, pip | -| `pom.xml` / `build.gradle` | java, mvn or gradle | -| `Dockerfile` / `docker-compose.yml` | docker binary, daemon running | -| `DATABASE_URL` in env | PostgreSQL reachable | -| `REDIS_URL` in env | Redis reachable | -| `.env.example` present | all keys exist in .env | +|---|---| +| `go.mod` | `go` on PATH, version against the `go` directive, module cache populated or `vendor/` present | +| `.golangci.yml` | `golangci-lint` on PATH | +| `go.work` | every path under `use` exists and has a `go.mod` | +| `package.json` | `node` and the right package manager on PATH, version against `.nvmrc` or `engines.node`, `node_modules` present, `.husky` present | +| `requirements.txt` / `pyproject.toml` | `python3` and `pip` on PATH, `venv`/`.venv` present, `pip check` clean, every requirement installed, `.pre-commit-config.yaml` and `pre-commit` present | +| `Gemfile` | `ruby` and `bundler` on PATH, `Gemfile.lock` or `vendor/bundle` present | +| `Cargo.toml` | `rustc` and `cargo` on PATH, version against `rust-toolchain.toml` | +| `pom.xml` / `build.gradle` | `java` on PATH, plus `mvn` or `gradle` | +| `Dockerfile` | `docker` on PATH, daemon responding | +| `docker-compose.yml` / `compose.yml` | every service running, every image pulled | +| `DATABASE_URL` containing `postgres` | port open, server answers a ping | +| `DATABASE_URL` containing `mysql`, or `MYSQL_URL` | port open, server answers a ping | +| `MONGODB_URI` / `MONGO_URL` | port open, server answers a ping | +| `REDIS_URL` / `REDIS_URI` | port open, server answers a ping | +| `.env.example` | every key also exists in `.env`, warn on empty values | +| `.gitignore` | covers `.env`, `*.log`, and `node_modules` or `__pycache__` for those stacks | + +The package manager comes from the lockfile: `pnpm-lock.yaml`, `yarn.lock`, or npm otherwise. + +### devcheck.yml + +Optional. Put it in the project root. + +```yaml +require: + - terraform + - kubectl +skip: + - "Git hooks configured for Node" +``` + +`require` adds a PATH check for each binary. `skip` drops checks by the name they report. + +## Use in CI + +```yaml +- uses: vidya381/devcheck@v0.1.0 +``` + +Or with inputs: ---- +```yaml +- uses: vidya381/devcheck@v0.1.0 + with: + version: v0.1.0 + args: --fix +``` -## CI usage +The action downloads the release binary for the runner and runs `devcheck --ci`, so the job fails if any check fails. If you would rather install it yourself: ```yaml -- name: Check dev environment - run: devcheck --ci +- run: go install github.com/vidya381/devcheck/cmd/devcheck@latest +- run: devcheck --ci ``` -Exits with code 1 if any check fails, so your pipeline stops early. +## Why I made it ---- +Every time I set up a project I had not touched in a while, I lost half an hour to something small. Postgres not running, a key missing from `.env`, the wrong Node version. The error you get is never the error you have. I wanted one command that tells me all of it at once, before I run anything. ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md). Adding a new check is straightforward — each check is a small self-contained struct. Issues labeled `good first issue` are a good place to start. +See [CONTRIBUTING.md](CONTRIBUTING.md). Issues labeled `good first issue` are the easiest place to start, and most of them are a single new check with a test. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c40ebfc --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security + +If you find a security problem in devcheck, please do not open a public issue. + +Use GitHub's [private vulnerability reporting](https://github.com/vidya381/devcheck/security/advisories/new). + +I will reply within a few days and let you know when a fix is out. diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..c50d444 --- /dev/null +++ b/action.yml @@ -0,0 +1,80 @@ +name: devcheck +description: Check that the environment has everything the project needs +branding: + icon: check-circle + color: green + +inputs: + version: + description: Release tag to download, e.g. v0.1.0. Defaults to the latest release. + required: false + default: latest + args: + description: Extra arguments to pass to devcheck. --ci is always passed. + required: false + default: "" + +runs: + using: composite + steps: + - name: Install devcheck + shell: bash + env: + DEVCHECK_VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + + case "$RUNNER_OS" in + Linux) os=linux ;; + macOS) os=darwin ;; + Windows) os=windows ;; + *) echo "devcheck has no binary for $RUNNER_OS"; exit 1 ;; + esac + + case "$RUNNER_ARCH" in + X64) arch=amd64 ;; + ARM64) arch=arm64 ;; + *) echo "devcheck has no binary for $RUNNER_ARCH"; exit 1 ;; + esac + + ext="" + if [ "$os" = "windows" ]; then + ext=".exe" + if [ "$arch" != "amd64" ]; then + echo "devcheck only publishes a windows/amd64 binary" + exit 1 + fi + fi + + name="devcheck-${os}-${arch}${ext}" + + if [ "$DEVCHECK_VERSION" = "latest" ]; then + base="https://github.com/vidya381/devcheck/releases/latest/download" + else + base="https://github.com/vidya381/devcheck/releases/download/${DEVCHECK_VERSION}" + fi + + dir="$RUNNER_TEMP/devcheck" + mkdir -p "$dir" + curl -fsSL "$base/$name" -o "$dir/devcheck$ext" + + # verify against the release checksums when they are published + if curl -fsSL "$base/checksums.txt" -o "$dir/checksums.txt"; then + expected=$(grep " $name\$" "$dir/checksums.txt" | awk '{print $1}') + if [ -n "$expected" ]; then + actual=$(sha256sum "$dir/devcheck$ext" | awk '{print $1}') + if [ "$expected" != "$actual" ]; then + echo "checksum mismatch for $name" + exit 1 + fi + fi + fi + + chmod +x "$dir/devcheck$ext" + echo "$dir" >> "$GITHUB_PATH" + + - name: Run devcheck + shell: bash + env: + DEVCHECK_ARGS: ${{ inputs.args }} + run: devcheck --ci $DEVCHECK_ARGS diff --git a/cmd/devcheck/main.go b/cmd/devcheck/main.go index a0db0a0..d88e6bf 100644 --- a/cmd/devcheck/main.go +++ b/cmd/devcheck/main.go @@ -2,8 +2,10 @@ package main import ( "context" + "errors" "fmt" "os" + "runtime/debug" "sync" "github.com/spf13/cobra" @@ -13,8 +15,31 @@ import ( "github.com/vidya381/devcheck/internal/reporter" ) +// version is set by the release workflow via -ldflags. For `go install` +// builds it stays "dev" and buildVersion falls back to the module version. var version = "dev" +// buildVersion returns the ldflags version when one was injected, otherwise +// the version the module system recorded. That covers `go install pkg@vX.Y.Z` +// and gives a pseudo-version for local builds. +func buildVersion() string { + if version != "dev" && version != "" { + return version + } + info, ok := debug.ReadBuildInfo() + if !ok { + return version + } + if v := info.Main.Version; v != "" && v != "(devel)" { + return v + } + return version +} + +// errCheckFailed is returned by run when --ci is set and a check failed. +// It is a signal, not a real error, so main exits 1 without printing it. +var errCheckFailed = errors.New("checks failed") + var ( flagVerbose bool flagJSON bool @@ -26,7 +51,7 @@ func main() { root := &cobra.Command{ Use: "devcheck", Short: "Check if your dev environment is ready to run this project", - Version: version, + Version: buildVersion(), RunE: run, } @@ -35,7 +60,13 @@ func main() { root.Flags().BoolVar(&flagFix, "fix", false, "Show suggested fix for each failure") root.Flags().BoolVar(&flagCI, "ci", false, "Exit with code 1 on any failure (for CI pipelines)") + root.SilenceErrors = true + root.SilenceUsage = true + if err := root.Execute(); err != nil { + if !errors.Is(err, errCheckFailed) { + fmt.Fprintln(os.Stderr, "Error:", err) + } os.Exit(1) } } @@ -83,13 +114,13 @@ func run(cmd *cobra.Command, args []string) error { if flagJSON { reporter.RenderJSON(results) } else { - reporter.Render(results, flagFix) + reporter.Render(results, flagFix, flagVerbose) } if flagCI { for _, r := range results { if r.Status == check.StatusFail { - os.Exit(1) + return errCheckFailed } } } diff --git a/internal/check/deps.go b/internal/check/deps.go index 2c01fb2..400f786 100644 --- a/internal/check/deps.go +++ b/internal/check/deps.go @@ -31,9 +31,9 @@ type DepsCheck struct { Dir string Stack string // "node", "python", or "go" PackageManager string // "npm", "pnpm", or "yarn" (Node only; defaults to "npm") - goCheck func(dir string) error - pipFreeze func(pipBin string) ([]byte, error) - pipCheck func(pipBin string) error + goCheck func(dir string) error + pipFreeze func(pipBin string) ([]byte, error) + pipCheck func(pipBin string) error } func (c *DepsCheck) Name() string { @@ -306,4 +306,4 @@ func (c *DepsCheck) runGo() Result { Status: StatusPass, Message: "Go module cache is populated", } -} \ No newline at end of file +} diff --git a/internal/check/deps_test.go b/internal/check/deps_test.go index 7fb7d41..7a54047 100644 --- a/internal/check/deps_test.go +++ b/internal/check/deps_test.go @@ -5,8 +5,8 @@ import ( "errors" "os" "path/filepath" - "testing" "strings" + "testing" ) func TestDepsCheck_Node_PassAndFail(t *testing.T) { @@ -150,8 +150,8 @@ func TestDepsCheck_Python_VenvNoRequirements_StillPass(t *testing.T) { func TestDepsCheck_Python_AllPackagesPresent(t *testing.T) { dir, pipBin := setupPythonDir(t, "requests==2.31.0\nflask>=2.0\n# comment\n") c := &DepsCheck{ - Dir: dir, - Stack: "python", + Dir: dir, + Stack: "python", pipCheck: func(_ string) error { return nil }, pipFreeze: func(_ string) ([]byte, error) { return []byte("requests==2.31.0\nFlask==2.3.0\n"), nil @@ -167,8 +167,8 @@ func TestDepsCheck_Python_AllPackagesPresent(t *testing.T) { func TestDepsCheck_Python_MissingPackage(t *testing.T) { dir, _ := setupPythonDir(t, "requests==2.31.0\ncelery>=5.0\n") c := &DepsCheck{ - Dir: dir, - Stack: "python", + Dir: dir, + Stack: "python", pipCheck: func(_ string) error { return nil }, pipFreeze: func(_ string) ([]byte, error) { return []byte("requests==2.31.0\n"), nil // celery absent @@ -200,8 +200,8 @@ func TestDepsCheck_Python_CaseInsensitiveMatch(t *testing.T) { // requirements.txt uses "Requests"; freeze returns "requests" — should still pass. dir, _ := setupPythonDir(t, "Requests>=2.0\n") c := &DepsCheck{ - Dir: dir, - Stack: "python", + Dir: dir, + Stack: "python", pipCheck: func(_ string) error { return nil }, pipFreeze: func(_ string) ([]byte, error) { return []byte("requests==2.31.0\n"), nil @@ -216,8 +216,8 @@ func TestDepsCheck_Python_CaseInsensitiveMatch(t *testing.T) { func TestDepsCheck_Python_EditableInstall(t *testing.T) { dir, _ := setupPythonDir(t, "mylib\n") c := &DepsCheck{ - Dir: dir, - Stack: "python", + Dir: dir, + Stack: "python", pipCheck: func(_ string) error { return nil }, pipFreeze: func(_ string) ([]byte, error) { return []byte("-e git+https://github.com/org/mylib.git@main#egg=mylib\n"), nil @@ -300,4 +300,4 @@ func TestDepsCheck_Ruby_VendorBundle_Takes_Priority(t *testing.T) { if !strings.Contains(r.Message, "vendor/bundle") { t.Errorf("expected vendor/bundle message to take priority, got: %s", r.Message) } -} \ No newline at end of file +} diff --git a/internal/check/githooks.go b/internal/check/githooks.go index 2d53d92..7c5f043 100644 --- a/internal/check/githooks.go +++ b/internal/check/githooks.go @@ -107,4 +107,3 @@ func dirExists(path string) bool { } return info.IsDir() } - diff --git a/internal/check/githooks_test.go b/internal/check/githooks_test.go index e4d7a7d..ee568fc 100644 --- a/internal/check/githooks_test.go +++ b/internal/check/githooks_test.go @@ -73,4 +73,3 @@ func TestGitHooksCheck_Python_PassAndWarn(t *testing.T) { t.Errorf("expected warn when pre-commit missing, got %v: %s", result.Status, result.Message) } } - diff --git a/internal/check/gitignore.go b/internal/check/gitignore.go index 54ad1d9..6d3ff2b 100644 --- a/internal/check/gitignore.go +++ b/internal/check/gitignore.go @@ -22,6 +22,13 @@ func (c *GitignoreCheck) Name() string { return ".gitignore covers sensitive files" } +func pluralPatterns(n int) string { + if n == 1 { + return "pattern" + } + return "patterns" +} + func (c *GitignoreCheck) Run(_ context.Context) Result { gitignorePath := c.Dir + "/.gitignore" @@ -73,7 +80,7 @@ func (c *GitignoreCheck) Run(_ context.Context) Result { return Result{ Name: c.Name(), Status: StatusWarn, - Message: fmt.Sprintf("Missing %d sensitive file patterns", len(missing)), + Message: fmt.Sprintf("Missing %d sensitive file %s", len(missing), pluralPatterns(len(missing))), Fix: fmt.Sprintf("Add these patterns to .gitignore:\n %s", strings.Join(missing, "\n ")), } } diff --git a/internal/check/gitignore_test.go b/internal/check/gitignore_test.go index 490b16f..2409bc1 100644 --- a/internal/check/gitignore_test.go +++ b/internal/check/gitignore_test.go @@ -193,4 +193,12 @@ func TestGitignoreCheck_NoGitignoreFile(t *testing.T) { if result.Status != StatusFail { t.Errorf("expected fail when .gitignore missing, got %v", result.Status) } -} \ No newline at end of file +} +func TestPluralPatterns(t *testing.T) { + if got := pluralPatterns(1); got != "pattern" { + t.Errorf("pluralPatterns(1) = %q, want %q", got, "pattern") + } + if got := pluralPatterns(2); got != "patterns" { + t.Errorf("pluralPatterns(2) = %q, want %q", got, "patterns") + } +} diff --git a/internal/check/gowork.go b/internal/check/gowork.go index ef7f060..77e373b 100644 --- a/internal/check/gowork.go +++ b/internal/check/gowork.go @@ -111,4 +111,4 @@ func parseGoWorkUse(path string) ([]string, error) { } return paths, scanner.Err() -} \ No newline at end of file +} diff --git a/internal/check/gowork_test.go b/internal/check/gowork_test.go index 0f9fd18..ca1a7ff 100644 --- a/internal/check/gowork_test.go +++ b/internal/check/gowork_test.go @@ -134,4 +134,4 @@ func TestParseGoWorkUse_BlockAndSingle(t *testing.T) { t.Errorf("paths[%d]: expected %q, got %q", i, want[i], p) } } -} \ No newline at end of file +} diff --git a/internal/check/registry.go b/internal/check/registry.go index 0749e81..294d3b4 100644 --- a/internal/check/registry.go +++ b/internal/check/registry.go @@ -103,7 +103,6 @@ func Build(stack detector.DetectedStack) []Check { cs = append(cs, &EnvCheck{Dir: "."}) } - // Check .gitignore for sensitive file patterns if fileExists(".gitignore") { gitignorePatterns := []requiredPattern{ @@ -132,4 +131,4 @@ func Build(stack detector.DetectedStack) []Check { func fileExists(path string) bool { _, err := os.Stat(path) return err == nil -} \ No newline at end of file +} diff --git a/internal/check/version.go b/internal/check/version.go index 8aa76a5..2394ed3 100644 --- a/internal/check/version.go +++ b/internal/check/version.go @@ -239,4 +239,4 @@ func readRustRequired(dir string) (string, error) { } } return "", fmt.Errorf("channel not found in rust-toolchain.toml") -} \ No newline at end of file +} diff --git a/internal/check/version_test.go b/internal/check/version_test.go index ec4edbd..06f5651 100644 --- a/internal/check/version_test.go +++ b/internal/check/version_test.go @@ -159,4 +159,4 @@ func TestReadRustRequired_NoFile_Error(t *testing.T) { if err == nil { t.Error("expected error when no toolchain file present") } -} \ No newline at end of file +} diff --git a/internal/config/config.go b/internal/config/config.go index 252679d..4e4d91a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -46,4 +46,4 @@ func (c Config) SkipSet() map[string]struct{} { s[name] = struct{}{} } return s -} \ No newline at end of file +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 17a3818..7f6be26 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -107,4 +107,4 @@ func writeFile(t *testing.T, path, content string) { if err := os.WriteFile(path, []byte(content), 0o644); err != nil { t.Fatalf("writeFile %s: %v", path, err) } -} \ No newline at end of file +} diff --git a/internal/detector/detector.go b/internal/detector/detector.go index 29f1aac..3d4cca0 100644 --- a/internal/detector/detector.go +++ b/internal/detector/detector.go @@ -7,25 +7,25 @@ import ( ) type DetectedStack struct { - Go bool - GoWork bool - Node bool + Go bool + GoWork bool + Node bool // PackageManager is the Node package manager inferred from the lockfile. // Possible values: "npm", "pnpm", "yarn". Empty string when Node is false. PackageManager string - Python bool - Ruby bool - Rust bool - Java bool - Maven bool - Gradle bool - Docker bool - DockerCompose bool - Postgres bool - Redis bool - MySQL bool - MongoDB bool - EnvExample bool + Python bool + Ruby bool + Rust bool + Java bool + Maven bool + Gradle bool + Docker bool + DockerCompose bool + Postgres bool + Redis bool + MySQL bool + MongoDB bool + EnvExample bool } func Detect(dir string) DetectedStack { @@ -70,4 +70,4 @@ func Detect(dir string) DetectedStack { func fileExists(path string) bool { _, err := os.Stat(path) return err == nil -} \ No newline at end of file +} diff --git a/internal/detector/detector_test.go b/internal/detector/detector_test.go index 572ab9d..c3fec4d 100644 --- a/internal/detector/detector_test.go +++ b/internal/detector/detector_test.go @@ -174,4 +174,4 @@ func TestDetect_Rust_false_when_absent(t *testing.T) { if stack.Rust { t.Error("expected Rust=false when no Cargo.toml present") } -} \ No newline at end of file +} diff --git a/internal/reporter/terminal.go b/internal/reporter/terminal.go index 8c62a65..4c30861 100644 --- a/internal/reporter/terminal.go +++ b/internal/reporter/terminal.go @@ -14,7 +14,9 @@ var ( skipStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#6b7280")) ) -func Render(results []check.Result, showFix bool) { +// Render prints results to stdout. Skipped checks are only printed when +// showSkipped is set (the --verbose flag). +func Render(results []check.Result, showFix, showSkipped bool) { passed, warned, failed := 0, 0, 0 for _, r := range results { @@ -32,13 +34,26 @@ func Render(results []check.Result, showFix bool) { } failed++ case check.StatusSkipped: - fmt.Printf("%s %s\n", skipStyle.Render("–"), r.Message) + if showSkipped { + fmt.Printf("%s %s\n", skipStyle.Render("–"), r.Message) + } } } fmt.Println("────────────────────────────────────────") - fmt.Printf(" %d passed %d warning %d failed\n", passed, warned, failed) + fmt.Println(summaryLine(passed, warned, failed)) if failed > 0 && !showFix { fmt.Println(" Run `devcheck --fix` for suggestions") } } + +func summaryLine(passed, warned, failed int) string { + return fmt.Sprintf(" %d passed %d %s %d failed", passed, warned, plural(warned, "warning"), failed) +} + +func plural(n int, word string) string { + if n == 1 { + return word + } + return word + "s" +} diff --git a/internal/reporter/terminal_test.go b/internal/reporter/terminal_test.go new file mode 100644 index 0000000..0fa58a0 --- /dev/null +++ b/internal/reporter/terminal_test.go @@ -0,0 +1,19 @@ +package reporter + +import "testing" + +func TestSummaryLine(t *testing.T) { + tests := []struct { + passed, warned, failed int + want string + }{ + {4, 0, 0, " 4 passed 0 warnings 0 failed"}, + {3, 1, 1, " 3 passed 1 warning 1 failed"}, + {0, 2, 0, " 0 passed 2 warnings 0 failed"}, + } + for _, tt := range tests { + if got := summaryLine(tt.passed, tt.warned, tt.failed); got != tt.want { + t.Errorf("summaryLine(%d,%d,%d) = %q, want %q", tt.passed, tt.warned, tt.failed, got, tt.want) + } + } +} diff --git a/scripts/install.sh b/scripts/install.sh index 900a076..ff86eab 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -4,13 +4,18 @@ set -e REPO="vidya381/devcheck" BIN="devcheck" -INSTALL_DIR="/usr/local/bin" # detect OS OS=$(uname -s | tr '[:upper:]' '[:lower:]') case "$OS" in linux) OS="linux" ;; darwin) OS="darwin" ;; + mingw* | msys* | cygwin* | windows*) + echo "This installer does not support Windows." + echo "Download devcheck-windows-amd64.exe from https://github.com/$REPO/releases/latest" + echo "then put it somewhere on your PATH." + exit 1 + ;; *) echo "Unsupported OS: $OS"; exit 1 ;; esac @@ -32,19 +37,55 @@ if [ -z "$TAG" ]; then fi FILENAME="${BIN}-${OS}-${ARCH}" -URL="https://github.com/$REPO/releases/download/$TAG/$FILENAME" +BASE="https://github.com/$REPO/releases/download/$TAG" + +TMPDIR=$(mktemp -d) +trap 'rm -rf "$TMPDIR"' EXIT -# download -TMP=$(mktemp) echo "Downloading $BIN $TAG ($OS/$ARCH)..." -curl -fsSL "$URL" -o "$TMP" -chmod +x "$TMP" +curl -fsSL "$BASE/$FILENAME" -o "$TMPDIR/$FILENAME" -# install +# verify the checksum if we have a tool for it and the release published one +SHA_TOOL="" +if command -v sha256sum >/dev/null 2>&1; then + SHA_TOOL="sha256sum" +elif command -v shasum >/dev/null 2>&1; then + SHA_TOOL="shasum -a 256" +fi + +if [ -n "$SHA_TOOL" ] && curl -fsSL "$BASE/checksums.txt" -o "$TMPDIR/checksums.txt" 2>/dev/null; then + EXPECTED=$(grep " $FILENAME\$" "$TMPDIR/checksums.txt" | awk '{print $1}') + if [ -z "$EXPECTED" ]; then + echo "Warning: $FILENAME is not listed in checksums.txt, skipping verification." + else + ACTUAL=$($SHA_TOOL "$TMPDIR/$FILENAME" | awk '{print $1}') + if [ "$EXPECTED" != "$ACTUAL" ]; then + echo "Checksum mismatch for $FILENAME." + echo " expected: $EXPECTED" + echo " got: $ACTUAL" + exit 1 + fi + echo "Checksum verified." + fi +else + echo "Skipping checksum verification (no checksum tool or no checksums.txt)." +fi + +chmod +x "$TMPDIR/$FILENAME" + +# pick an install directory +INSTALL_DIR="/usr/local/bin" if [ -w "$INSTALL_DIR" ]; then - mv "$TMP" "$INSTALL_DIR/$BIN" + mv "$TMPDIR/$FILENAME" "$INSTALL_DIR/$BIN" +elif command -v sudo >/dev/null 2>&1; then + sudo mv "$TMPDIR/$FILENAME" "$INSTALL_DIR/$BIN" else - sudo mv "$TMP" "$INSTALL_DIR/$BIN" + INSTALL_DIR="$HOME/.local/bin" + mkdir -p "$INSTALL_DIR" + mv "$TMPDIR/$FILENAME" "$INSTALL_DIR/$BIN" + echo + echo "$INSTALL_DIR is not on your PATH by default. Add this to your shell profile:" + echo " export PATH=\"\$HOME/.local/bin:\$PATH\"" fi echo "Installed $BIN $TAG to $INSTALL_DIR/$BIN"