[
  {
    "path": ".dockerignore",
    "content": "bin\nvendor\ntmp\nair"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[Makefile]\nindent_style = tab\n\n[*.go]\nindent_style = tab\nindent_size = 4\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\npatreon: cosmtrek\ngithub: xiantang\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: xiantang\n\n---\n\n**Describe the bug**  \nProvide a clear and concise description of the issue you encountered.\n\n**To Reproduce**  \n- [ ] Provide a minimal reproducible example (ideally as a PR to https://github.com/air-verse/air-reproducible-example).  \n- [ ] Include relevant parts of your `.air.toml` (redact secrets) **or** the exact `air` command you ran.  \n- [ ] Describe the steps to reproduce the issue clearly in that example.\n\n**Expected behavior**  \nDescribe clearly and concisely what you expected to happen.\n\n**Screenshots**  \nIf applicable, include screenshots to help illustrate the issue.\n\n**Desktop (please complete the following information):**  \n- OS: [e.g., macOS 13.3.1]  \n- Air Version: [e.g., v1.63.2]\n\n**Additional context**  \n- Please ensure your issue is written in English as the primary language.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build\n\non:\n  push:\n  pull_request:\n    branches: [master]\n\njobs:\n  build:\n    strategy:\n      matrix:\n        os: [ubuntu-latest, macos-latest]\n    name: Build\n    runs-on: ${{ matrix.os }}\n    steps:\n      - name: Check out code\n        uses: actions/checkout@v4\n      - name: Setup Go\n        id: go\n        uses: actions/setup-go@v5\n        with:\n          go-version: ^1.25\n      - name: golangci-lint\n        uses: golangci/golangci-lint-action@v8\n        with:\n          # Build golangci-lint from source with the configured Go version\n          install-mode: goinstall\n          version: latest\n      - name: Install dependency\n        run: if [ $(uname) == \"Darwin\" ]; then brew install gnu-sed ;fi\n      - name: Build\n        run: make build\n      - name: Run unit tests\n        env:\n          CI: \"true\"\n        run: go install github.com/go-delve/delve/cmd/dlv@latest && go test ./... -v -timeout=5m -covermode=count -coverprofile=coverage.txt\n      - name: Upload Coverage report to CodeCov\n        uses: codecov/codecov-action@v4\n        with:\n          token: ${{ secrets.CODECOV_TOKEN }}\n          file: ./coverage.txt\n          verbose: true\n\n  unit_tests_windows:\n    name: Unit Tests (Windows)\n    runs-on: windows-latest\n    steps:\n      - name: Check out code\n        uses: actions/checkout@v4\n      - name: Normalize line endings (Windows)\n        if: runner.os == 'Windows'\n        run: |\n          git config core.autocrlf false\n          git config core.eol lf\n          git checkout-index -f -a\n      - name: Setup Go\n        id: go\n        uses: actions/setup-go@v5\n        with:\n          go-version: ^1.25\n      - name: golangci-lint\n        uses: golangci/golangci-lint-action@v8\n        with:\n          install-mode: goinstall\n          version: latest\n      - name: Run unit tests\n        env:\n          CI: \"true\"\n        run: go install github.com/go-delve/delve/cmd/dlv@latest && go test ./... -v -timeout=5m -covermode=count -coverprofile=coverage.txt\n\n  push_to_docker_latest:\n    name: Push master code to docker latest image\n    if: github.event_name == 'push' && github.ref == 'refs/heads/master'\n    runs-on: ubuntu-latest\n    steps:\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n      - name: Login to DockerHub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      - name: Build and push\n        id: docker_build\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          platforms: linux/amd64,linux/arm64\n          tags: cosmtrek/air:latest\n      - name: Show image digest\n        run: echo ${{ steps.docker_build.outputs.digest }}\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\n\non:\n  push:\n  pull_request:\n    branches: [master]\n\njobs:\n  release:\n    name: Release\n    runs-on: ubuntu-latest\n    if: startsWith(github.ref, 'refs/tags/v')\n    steps:\n      - name: Check out code\n        uses: actions/checkout@v4\n      - name: Normalize line endings (Windows)\n        if: runner.os == 'Windows'\n        run: |\n          git config core.autocrlf false\n          git config core.eol lf\n          git checkout-index -f -a\n      - name: Setup Go\n        uses: actions/setup-go@v5\n        with:\n          go-version: ^1.25\n\n      - name: Set GOVERSION\n        run: echo \"GOVERSION=$(go version | sed -r 's/go version go(.*)\\ .*/\\1/')\" >> $GITHUB_ENV\n      - name: Set AirVersion\n        run: echo \"VERSION=${GITHUB_REF#refs/tags/}\" >> $GITHUB_ENV\n      - name: Show version\n        run: echo ${{ env.GOVERSION }} ${{ env.VERSION }}\n\n      - name: Run GoReleaser\n        uses: goreleaser/goreleaser-action@v5\n        with:\n          distribution: goreleaser\n          version: latest\n          args: release --clean\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n      - name: Login to DockerHub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      - name: Push to DockerHub\n        id: docker_build\n        uses: docker/build-push-action@v5\n        with:\n          push: true\n          platforms: linux/amd64,linux/arm64\n          tags: cosmtrek/air:${{ env.VERSION }}\n      - name: Show docker image digest\n        run: echo ${{ steps.docker_build.outputs.digest }}\n"
  },
  {
    "path": ".github/workflows/smoke_test.yml",
    "content": "name: Smoke test\n\non:\n  push:\n  pull_request:\n\njobs:\n  smoke_test_ubuntu:\n    uses: ./.github/workflows/smoke_test_reuse_job.yml\n    with:\n      run_on: ubuntu-latest\n  smoke_test_macos:\n    uses: ./.github/workflows/smoke_test_reuse_job.yml\n    with:\n      run_on: macos-latest\n  smoke_test_windows:\n    uses: ./.github/workflows/smoke_test_reuse_job.yml\n    with:\n      run_on: windows-latest\n"
  },
  {
    "path": ".github/workflows/smoke_test_reuse_job.yml",
    "content": "name: Reusable smoke test\n\non:\n  workflow_call:\n    inputs:\n      run_on:\n        required: true\n        type: string\n\njobs:\n  smoke_test:\n    name: Smoke test\n    runs-on: ${{ inputs.run_on }}\n    steps:\n      - name: Check out code\n        uses: actions/checkout@v5\n      - name: Normalize line endings (Windows)\n        if: runner.os == 'Windows'\n        run: |\n          git config core.autocrlf false\n          git config core.eol lf\n          git checkout-index -f -a\n      - name: Setup Go\n        id: go\n        uses: actions/setup-go@v6\n        with:\n          go-version: ^1.25\n      - name: golangci-lint\n        uses: golangci/golangci-lint-action@v8\n        with:\n          install-mode: goinstall\n          version: latest\n      - name: Install\n        if: runner.os != 'Windows'\n        run: make install\n      - name: Install (Windows)\n        if: runner.os == 'Windows'\n        run: go install .\n      - name: Check rebuild\n        if: runner.os != 'Windows'\n        id: check_rebuild_unix\n        working-directory: ./smoke_test/check_rebuild\n        run: |\n          nohup air > nohup.out 2> nohup.err < /dev/null &\n          sleep 15\n          echo \"\" >> main.go\n          sleep 5\n          cat nohup.out\n          count=$(grep \"running\" nohup.out | wc -l)\n          if [ \"$count\" -eq \"2\" ]; then\n            echo \"value=PASS\" >> \"$GITHUB_OUTPUT\"\n          else\n            echo \"value=FAIL\" >> \"$GITHUB_OUTPUT\"\n          fi\n      - name: Check rebuild (Windows)\n        if: runner.os == 'Windows'\n        id: check_rebuild_windows\n        working-directory: ./smoke_test/check_rebuild\n        shell: pwsh\n        run: |\n          $log = \"nohup.out\"\n          $err = \"nohup.err\"\n          $goPath = (go env GOPATH)\n          $airPath = Join-Path $goPath \"bin\\air.exe\"\n          $process = Start-Process -FilePath $airPath -WorkingDirectory (Get-Location) -RedirectStandardOutput $log -RedirectStandardError $err -NoNewWindow -PassThru\n          Start-Sleep -Seconds 15\n          Add-Content -Path \"main.go\" -Value \"`n\"\n          Start-Sleep -Seconds 5\n          if (Test-Path $log) { Get-Content $log }\n          if (Test-Path $log) {\n            $count = (Select-String -Path $log -Pattern \"running\" | Measure-Object).Count\n          } else {\n            $count = 0\n          }\n          if ($count -eq 2) {\n            \"value=PASS\" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8\n          } else {\n            \"value=FAIL\" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8\n          }\n          if ($process -and -not $process.HasExited) { $process.Kill() }\n      - uses: nick-invision/assert-action@v2\n        with:\n          expected: \"PASS\"\n          actual: ${{ steps.check_rebuild_unix.outputs.value || steps.check_rebuild_windows.outputs.value }}\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\n*.a\n*.so\n*.test\n*.prof\n*.out\n\nvendor/\ntmp/\n\n# IDE specific files\n.vscode\n.idea\n\n# build output\nair"
  },
  {
    "path": ".golangci.yml",
    "content": "version: \"2\"\nlinters:\n  default: none\n  enable:\n    - copyloopvar\n    - errcheck\n    - ineffassign\n    - misspell\n    - revive\n    - staticcheck\n    - testifylint\n    - unconvert\n    - unused\n  exclusions:\n    generated: lax\n    presets:\n      - comments\n      - common-false-positives\n      - legacy\n      - std-error-handling\n    paths:\n      - third_party$\n      - builtin$\n      - examples$\nformatters:\n  enable:\n    - goimports\n  exclusions:\n    generated: lax\n    paths:\n      - third_party$\n      - builtin$\n      - examples$\n"
  },
  {
    "path": ".goreleaser.yml",
    "content": "builds:\n  - goos:\n      - linux\n      - windows\n      - darwin\n    ignore:\n      - goos: darwin\n        goarch: 386\n    ldflags:\n      - -s -w -X \"main.airVersion={{.Version}}\"\n      - -s -w -X \"main.goVersion={{.Env.GOVERSION}}\"\n    env:\n      - CGO_ENABLED=0\narchives:\n  - id: tar.gz\n    format: tar.gz\n  - id: binary\n    format: binary\n"
  },
  {
    "path": "AGENTS.md",
    "content": "# AGENTS\n\nGuidelines for contributors and AI coding agents working in this repository.\n\n## Goals\n\n- Keep changes minimal, focused, and idiomatic to Go.\n- When adding changes, do NOT break existing behavior.\n- Make changes small and easy to review.\n- Code and comments must be written in English.\n- Prefer root-cause fixes over band-aids; do not refactor unrelated code.\n- Maintain user-facing behavior and CLI flags unless explicitly changing them.\n\n## Project Snapshot\n\n- Language: Go (modules enabled; `go 1.25` in `go.mod`).\n- Module path: `github.com/air-verse/air`.\n- Entry: `main.go`.\n- Core package: `runner/` (watcher, engine, flags, config, proxy).\n- Docs: `README*.md`, `air_example.toml`, `docs/`.\n- Tooling: `Makefile`, `hack/check.sh`, `hooks/pre-commit`, `.golangci.yml`.\n- Default config file: `.air.toml` (generated by `air init`).\n\n## Repository Layout\n\n- `main.go`: CLI entrypoint and flag parsing.\n- `runner/engine.go`: build/run loop and watcher orchestration.\n- `runner/config.go`: config schema, defaults, parsing, validation.\n- `runner/flag.go`: CLI flag wiring.\n- `runner/watcher.go`: fsnotify vs polling watcher selection.\n- `runner/proxy*.go`: live-reload proxy, SSE stream, embedded JS.\n- `runner/util*.go`: platform helpers, process control, misc utilities.\n- `runner/*_test.go`: unit tests and platform-specific tests.\n- `hack/check.sh`: goimports + golangci-lint driver.\n- `hooks/pre-commit`: runs `hack/check.sh` on staged files.\n\n## Build / Lint / Test\n\n- Install tools + hook: `make init` (goimports + golangci-lint v2.6.1).\n- Format + lint staged Go files: `make check`.\n- Format + lint all Go files: `make check scope=all`.\n- Build binary: `make build` (runs `make check` first).\n- Install locally: `make install` (runs `make check` first).\n- CI prep (module tidy): `make ci`.\n- Full test suite: `go test ./...` or `make test` (race + timeout).\n- CI tests: `make test-ci` (CI=true, longer timeout).\n- Pre-commit hook: runs `./hack/check.sh` on staged files.\n\n### Single Test Recipes\n\n- Single package: `go test ./runner -v`.\n- Single test: `go test ./runner -run '^TestName$' -count=1 -v`.\n- Subtest: `go test ./runner -run '^TestName$/Subcase$' -count=1`.\n- All packages, one test: `go test ./... -run '^TestName$' -count=1`.\n- Add `-race` or `-timeout=3m` when debugging flakiness.\n\n## Code Style (Go)\n\n- Formatting: run `goimports` (it also applies `gofmt`).\n- Imports: let `goimports` group stdlib, third-party, local imports.\n- Naming: `CamelCase` for exported, `lowerCamel` for unexported.\n- Initialisms: use standard forms (ID, URL, HTTP, JSON).\n- Receivers: keep receiver names short and consistent (`cfg`, `e`, `p`).\n- Types: prefer concrete types over `any`; avoid needless interfaces.\n- Constants: use `const` for defaults; use `0o755` style perms.\n- Zero values: design structs so zero values are valid when possible.\n- Early returns: avoid deeply nested `else` blocks.\n- Paths: use `filepath` for OS-safe path handling.\n- Shelling out: prefer `exec.Command` with args; use `/bin/sh -c` only when needed.\n- Platform code: maintain `*_linux.go`, `*_windows.go`, build tags parity.\n- Comments: keep short, English, and explain \"why\" more than \"what\".\n- Use `time.Duration` for timeouts and backoffs.\n- Prefer value receivers unless mutation or large copies require pointers.\n- Avoid globals except for constants and small immutable vars.\n- Treat nil slices as empty; do not rely on non-nil defaults.\n- Keep TOML/JSON tags aligned with field names and usage strings.\n\n## Error Handling & Logging\n\n- Wrap errors with context: `fmt.Errorf(\"read config: %w\", err)`.\n- Use `errors.Is/As` for comparisons, `errors.Join` for aggregates.\n- Avoid panics in packages; `log.Fatal` only at CLI entrypoints.\n- Log via `mainLog`, `buildLog`, `runnerLog`, `watcherLog` in `runner`.\n- Keep log output concise and consistent with existing prefixes.\n\n## Concurrency & State\n\n- Guard shared state with `sync.Mutex` or `sync/atomic`.\n- Avoid data races; keep goroutines bounded and cancellable.\n- Use channels for signaling (see `buildRunCh` in `runner/engine.go`).\n- Use `context` and timeouts for operations that may block on I/O.\n\n## Tests\n\n- Location: alongside code as `*_test.go`.\n- Style: table-driven tests with `t.Run` where it improves clarity.\n- Parallelism: use `t.Parallel()` only for isolated tests.\n- Helpers: use `t.Helper`, `t.TempDir`, `t.Setenv`, `t.Cleanup`.\n- Assertions: use `testify/require` for fatal checks, `testify/assert` for soft checks.\n- Fixtures: prefer `_testdata` and temp dirs; avoid network dependencies.\n- OS coverage: use `*_windows_test.go`, `*_linux_test.go` for platform behavior.\n\n## Config / CLI Discipline\n\n- Config fields: edit `runner/config.go`, update parsing/defaults/tests.\n- CLI flags: update `runner/flag.go`, sync help text, update README usage.\n- Keep `air_example.toml` aligned with any config changes.\n- Behavior changes must include README updates and tests.\n\n## Documentation\n\n- Update `README.md` for user-visible changes (flags, config, examples).\n- Keep `docs/` content accurate when behavior changes.\n- Add concise migration notes for breaking or behavioral changes.\n- Mention new environment variables or defaults in docs.\n\n## Tooling and Linters\n\n- `make check` runs `hack/check.sh` -> `goimports` + `golangci-lint`.\n- Enabled linters include: `errcheck`, `revive`, `staticcheck`, `testifylint`, `unused`.\n- Fix lint warnings rather than suppressing unless clearly justified.\n- Keep changes compatible with the current Go version in `go.mod`.\n\n## Scope and Safety\n\n- Avoid touching `vendor/`, `third_party/`, or generated files.\n- Do not change CLI output or flags unless explicitly requested.\n- Avoid broad refactors; keep changes localized to the feature/bug.\n- Prefer root-cause fixes over temporary workarounds.\n- Do not add dependencies unless there is a clear, reviewed need.\n- Assume offline mode; no external network usage.\n\n## Cursor / Copilot Rules\n\n- No `.cursor/rules/`, `.cursorrules`, or `.github/copilot-instructions.md` found.\n- If any are added later, follow them and copy key points here.\n\n## For AI Coding Agents (Codex CLI)\n\n- For multi-step tasks, maintain an explicit plan and mark progress.\n- Keep edits in a single focused patch per logical change.\n- Briefly state what you are about to do before running commands.\n- Prefer `rg` for searches and keep file reads to small chunks.\n- Validate with `make check` and `go test ./...` when changes touch Go code.\n- Avoid touching unrelated files; do not reformat the repo wholesale.\n\n## Release Notes (maintainers)\n\n- Follow the README \"Release\" section for tagging; CI performs builds.\n\n---\n\nQuestions or uncertain scope? Open an issue or ask for clarification before implementing.\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM golang:1.26 AS builder\r\n\r\nLABEL maintainer=\"Rick Yu <cosmtrek@gmail.com>\"\r\n\r\nENV GOPATH /go\r\nENV GO111MODULE on\r\n\r\nCOPY . /go/src/github.com/air-verse/air\r\nWORKDIR /go/src/github.com/air-verse/air\r\n\r\nRUN --mount=type=cache,target=/go/pkg/mod go mod download\r\n\r\nRUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build make ci && make install\r\n\r\nFROM golang:1.26\r\n\r\nCOPY --from=builder /go/bin/air  /go/bin/air\r\n\r\nENTRYPOINT [\"/go/bin/air\"]\r\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "Makefile",
    "content": "AIRVER := $(shell git describe --tags)\nLDFLAGS += -X \"main.BuildTimestamp=$(shell date -u \"+%Y-%m-%d %H:%M:%S\")\"\nLDFLAGS += -X \"main.airVersion=$(AIRVER)\"\nLDFLAGS += -X \"main.goVersion=$(shell go version | sed -r 's/go version go(.*)\\ .*/\\1/')\"\n\nGO := GO111MODULE=on CGO_ENABLED=0 go\nGOLANGCI_LINT_VERSION = v2.6.1\nGOLANGCI_LINT_CURRENT := $(shell golangci-lint --version 2>/dev/null | sed -n 's/.*version \\([0-9.]*\\).*/v\\1/p')\n\n.PHONY: init\ninit: install-golangci-lint\n\tgo install golang.org/x/tools/cmd/goimports@latest\n\t@echo \"Install pre-commit hook\"\n\t@ln -s $(shell pwd)/hooks/pre-commit $(shell pwd)/.git/hooks/pre-commit || true\n\t@chmod +x ./hack/check.sh\n\n.PHONY: install-golangci-lint\ninstall-golangci-lint:\n\t@echo \"Installing golangci-lint $(GOLANGCI_LINT_VERSION)\"\n\t@GO111MODULE=on go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)\n\n.PHONY: setup\nsetup: init\n\tgit init\n\n.PHONY: check\ncheck:\n\t@./hack/check.sh ${scope}\n\n.PHONY: test\ntest:\n\t@go test ./... -v -race -timeout=3m\n\n.PHONY: test-ci\ntest-ci:\n\t@CI=true go test ./... -v -timeout=5m\n\n.PHONY: ci\nci: init\n\t@$(GO) mod tidy\n\n.PHONY: build\nbuild: check\n\t$(GO) build -ldflags '$(LDFLAGS)'\n\n.PHONY: install\ninstall: check\n\t@echo \"Installing air...\"\n\t@$(GO) install -ldflags '$(LDFLAGS)'\n\n.PHONY: release\nrelease: check\n\tGOOS=darwin GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/darwin/air\n\tGOOS=linux GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/linux/air\n\tGOOS=windows GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/windows/air.exe\n\n.PHONY: docker-image\ndocker-image:\n\tdocker build -t cosmtrek/air:$(AIRVER) -f ./Dockerfile .\n\n.PHONY: push-docker-image\npush-docker-image:\n\tdocker push cosmtrek/air:$(AIRVER)\n"
  },
  {
    "path": "README-ja.md",
    "content": "# :cloud: Air - Go アプリケーションのためのライブリロード\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)](https://github.com/air-verse/air/actions?query=workflow%3AGo+branch%3Amaster) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/dcb95264cc504cad9c2a3d8b0795a7f8)](https://www.codacy.com/gh/air-verse/air/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=air-verse/air&amp;utm_campaign=Badge_Grade) [![Go Report Card](https://goreportcard.com/badge/github.com/air-verse/air)](https://goreportcard.com/report/github.com/air-verse/air) [![codecov](https://codecov.io/gh/air-verse/air/branch/master/graph/badge.svg)](https://codecov.io/gh/air-verse/air)\n\n![air](docs/air.png)\n\nEnglish | [简体中文](README-zh_cn.md) | [繁體中文](README-zh_tw.md) | [日本語](README-ja.md)\n\n## 動機\n\nGo でウェブサイトを開発し始め、 [gin](https://github.com/gin-gonic/gin) を使っていた時、gin にはライブリロード機能がないのが残念でした。\n\nそこで探し回って [fresh](https://github.com/pilu/fresh) を試してみましたが、あまり柔軟ではないようでした。なので、もっと良いものを書くことにしました。そうして、 Air が誕生しました。\n\n加えて、 [pilu](https:///github.com/pilu) に感謝します。fresh がなければ、 Air もありませんでした。:)\n\nAir は Go アプリケーション開発用のライブリロードコマンドラインユーティリティです。プロジェクトのルートディレクトリで `air` を実行し、放置し、コードに集中してください。\n\n注：このツールは本番環境へのホットデプロイとは無関係です。\n\n## 特徴\n\n- カラフルなログ出力\n- ビルドやその他のコマンドをカスタマイズ\n- サブディレクトリを除外することをサポート\n- Air 起動後は新しいディレクトリを監視します\n- より良いビルドプロセス\n\n### 引数から指定された設定を上書き\n\nair は引数による設定をサポートします:\n\n利用可能なコマンドライン引数を以下のコマンドで確認できます：\n\n```\nair -h\n```\nまたは\n```\nair --help\n```\n\nもしビルドコマンドと起動コマンドを設定したい場合は、設定ファイルを使わずに以下のようにコマンドを使うことができます:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\"\n```\n\n入力値としてリストを取る引数には、アイテムを区切るためにコンマを使用します:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\" --build.exclude_dir \"templates,build\"\n```\n\n従来の `build.bin` フィールドは非推奨で、今後のリリースで削除される予定です。代わりに `build.entrypoint` を使ってください。\n\n`build.entrypoint` は実行ファイルだけを指定する文字列、または実行ファイルとデフォルト引数を並べた文字列配列のどちらでも指定できます。\n\n## インストール\n\n### `go install` を使う場合（推奨）\n\ngo 1.25以上を使う場合:\n\n```shell\ngo install github.com/air-verse/air@latest\n```\n\n### `go get -tool` を使う場合\n\ngo 1.25以上を使う場合:\n\n```shell\ngo get -tool github.com/air-verse/air@latest\n\n# 使い方は以下の通りです:\ngo tool air -v\n```\n\n### `install.sh` を使う場合\n\n```shell\n# バイナリは $(go env GOPATH)/bin/air にインストールされます\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin\n\n# または./bin/にインストールすることもできます\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s\n\nair -v\n```\n\n### [goblin.run](https://goblin.run) を使う場合\n\n```shell\n# バイナリは /usr/local/bin/air にインストールされます\ncurl -sSfL https://goblin.run/github.com/air-verse/air | sh\n\n# 任意のパスに配置することもできます\ncurl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh\n```\n\n### ソフトウェアパッケージマネージャー [mise](https://github.com/jdx/mise) を使う場合\n\n```shell\nmise use -g air\n```\n\n### Docker/Podman\n\n[cosmtrek/air](https://hub.docker.com/r/cosmtrek/air) という Docker イメージをプルしてください。\n\n```shell\ndocker/podman run -it --rm \\\n    -w \"<PROJECT>\" \\\n    -e \"air_wd=<PROJECT>\" \\\n    -v $(pwd):<PROJECT> \\\n    -p <PORT>:<APP SERVER PORT> \\\n    cosmtrek/air\n    -c <CONF>\n```\n\n#### Docker/Podman .${SHELL}rc\n\n通常のアプリケーションのように継続的に air を使いたい場合は、 ${SHELL}rc (Bash, Zsh, etc…)に関数を作成してください。\n\n```shell\nair() {\n  podman/docker run -it --rm \\\n    -w \"$PWD\" -v \"$PWD\":\"$PWD\" \\\n    -p \"$AIR_PORT\":\"$AIR_PORT\" \\\n    docker.io/cosmtrek/air \"$@\"\n}\n```\n\n`<PROJECT>`はコンテナ内のプロジェクトのパスです。 例：`/go/example`\nコンテナに接続したい場合は、 `--entrypoint=bash` を追加してください。\n\n<details>\n  <summary>例</summary>\n\nDocker で動作するとあるプロジェクト：\n\n```shell\ndocker run -it --rm \\\n  -w \"/go/src/github.com/cosmtrek/hub\" \\\n  -v $(pwd):/go/src/github.com/cosmtrek/hub \\\n  -p 9090:9090 \\\n  cosmtrek/air\n```\n\n別の例:\n\n```shell\ncd /go/src/github.com/cosmtrek/hub\nAIR_PORT=8080 air -c \"config.toml\"\n```\n\nこれは `$PWD` を現在のディレクトリに置き換え、 `$AIR_PORT` は公開するポートを指定し、 `$@` は-cのようなアプリケーション自体の引数を受け取るためのものです。\n\n</details>\n\n## 使い方\n\n`.bashrc` または `.zshrc` に `alias air='~/.air'` を追加すると、入力の手間が省けます。\n\nまずプロジェクトを移動します。\n\n```shell\ncd /path/to/your_project\n```\n\n最もシンプルな使い方は以下の通りです。\n\n```shell\n# カレントディレクトリの `.air.toml` を優先し、見つからない場合はデフォルト値を使います\nair\n```\n\n特定の設定ファイルを明示的に使う場合は `-c` を指定します。\n\n```shell\nair -c .air.toml\n```\n\n次のコマンドを実行することで、カレントディレクトリに `.air.toml` 設定ファイルを初期化できます。\n\n```shell\nair init\n```\n\nその次に、追加の引数なしで `air` コマンドを実行すると、 `.air.toml` ファイルが設定として使用されます。\n\n```shell\nair\n```\n\n[air_example.toml](air_example.toml)を参考にして設定を編集します。\n\n### 実行時引数\n\nair コマンドの後に引数を追加することで、ビルドしたバイナリを実行するための引数を渡すことができる。\n\n```shell\n# ./tmp/main benchを実行します\nair bench\n\n# ./tmp/main server --port 8080を実行します\nair server --port 8080\n```\n\nair コマンドに渡す引数とビルドするバイナリを `--` 引数で区切ることができる。\n\n```shell\n# ./tmp/main -hを実行します\nair -- -h\n\n# カスタム設定で air を実行し、ビルドされたバイナリに -h 引数を渡す\nair -c .air.toml -- -h\n```\n\n### Docker Compose\n\n```yaml\nservices:\n  my-project-with-air:\n    image: cosmtrek/air\n    # working_dir の値はマップされたボリュームの値と同じでなければなりません\n    working_dir: /project-package\n    ports:\n      - <any>:<any>\n    environment:\n      - ENV_A=${ENV_A}\n      - ENV_B=${ENV_B}\n      - ENV_C=${ENV_C}\n    volumes:\n      - ./project-relative-path/:/project-package/\n```\n\n### デバッグ\n\n`air -d`は全てのログを出力します。\n\n## air イメージを使いたくない Docker ユーザーのためのインストールと使い方\n\n`Dockerfile`\n\n```Dockerfile\n# 1.25以上の任意のバージョンを選択してください\nFROM golang:1.25-alpine\n\nWORKDIR /app\n\nRUN go install github.com/air-verse/air@latest\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCMD [\"air\", \"-c\", \".air.toml\"]\n```\n\n`docker-compose.yaml`\n\n```yaml\nversion: \"3.8\"\nservices:\n  web:\n    build:\n      context: .\n      # Dockerfile へのパスを正してください\n      dockerfile: Dockerfile\n    ports:\n      - 8080:3000\n    # ライブリロードのために、コードベースディレクトリを /app ディレクトリにバインド/マウントすることが重要です\n    volumes:\n      - ./:/app\n```\n\n## Q&A\n\n### \"command not found: air\" または \"No such file or directory\"\n\n```shell\nexport GOPATH=$HOME/xxxxx\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nexport PATH=$PATH:$(go env GOPATH)/bin #この設定を .profile で確認し、追加した場合は .profile を source するのを忘れないでください!!!\n```\n\n### bin に ' が含まれる場合の wsl でのエラー\n\nbin の\\`'をエスケープするには`\\`を使用したほうが良いです。関連する issue: [#305](https://github.com/air-verse/air/issues/305)\n\n### 質問: ホットコンパイルのみを行い、何も実行しない方法は？\n\n[#365](https://github.com/air-verse/air/issues/365)\n\n```toml\n[build]\n  cmd = \"/usr/bin/true\"\n```\n\n### 静的ファイルの変更時にブラウザを自動的にリロードする方法\n\n詳細のために [#512](https://github.com/air-verse/air/issues/512) の issue を参照してください。\n\n- 静的ファイルを `include_dir` 、`include_ext` 、`include_file` に配置していることを確かめてください。\n- HTML に `</body>` タグがあることを確かめてください。\n- プロキシを有効にするには、以下の設定を行います：\n\n```toml\n[proxy]\n  enabled = true\n  proxy_port = <air proxy port>\n  app_port = <your server port>\n```\n\n## 開発\n\n必要な Go のバージョンは 1.25+ です（`go.mod` を参照）。\n\n```shell\n# プロジェクトをフォークしてください\n\n# クローンしてください\nmkdir -p $GOPATH/src/github.com/cosmtrek\ncd $GOPATH/src/github.com/cosmtrek\ngit clone git@github.com:<YOUR USERNAME>/air.git\n\n# 依存関係をインストールしてください\ncd air\nmake ci\n\n# コードを探検してコーディングを楽しんでください！\nmake install\n```\n\nPull Request を受け付けています。\n\n### リリース\n\n```shell\n# master にチェックアウトします\ngit checkout master\n\n# リリースに必要なバージョンタグを付与します\ngit tag v1.xx.x\n\n# リモートにプッシュします\ngit push origin v1.xx.x\n\n# CI が実行され、新しいバージョンがリリースされます。約5分待つと最新バージョンを取得できます\n```\n\n## スターヒストリー\n\n[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)\n\n## スポンサー\n\n[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)\n\n多くのサポーターの方々に心から感謝します。私はいつも皆さんの優しさを忘れません。\n\n## ライセンス\n\n[GNU General Public License v3.0](LICENSE)\n"
  },
  {
    "path": "README-zh_cn.md",
    "content": "# Air [![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)](https://github.com/air-verse/air/actions?query=workflow%3AGo+branch%3Amaster) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/dcb95264cc504cad9c2a3d8b0795a7f8)](https://www.codacy.com/gh/air-verse/air/dashboard?utm_source=github.com&utm_medium=referral&utm_content=air-verse/air&utm_campaign=Badge_Grade) [![Go Report Card](https://goreportcard.com/badge/github.com/air-verse/air)](https://goreportcard.com/report/github.com/air-verse/air) [![codecov](https://codecov.io/gh/air-verse/air/branch/master/graph/badge.svg)](https://codecov.io/gh/air-verse/air)\n\n:cloud: 热重载 Go 应用的工具\n\n![air](docs/air.png)\n\n[English](README.md) | 简体中文 | [繁體中文](README-zh_tw.md)\n\n## 开发动机\n\n当我用 Go 和 [gin](https://github.com/gin-gonic/gin) 框架开发网站时，gin 缺乏实时重载的功能是令人遗憾的。我曾经尝试过 [fresh](https://github.com/pilu/fresh) ，但是它用起来不太灵活，所以我试着用更好的方式来重写它。Air 就这样诞生了。此外，非常感谢 [pilu](https://github.com/pilu)。没有 fresh 就不会有 air :)\n\nAir 是为 Go 应用开发设计的另外一个热重载的命令行工具。只需在你的项目根目录下输入 `air`，然后把它放在一边，专注于你的代码即可。\n\n**注意**：该工具与生产环境的热部署无关。\n\n## 特色\n\n- 彩色的日志输出\n- 自定义构建或必要的命令\n- 支持外部子目录\n- 在 Air 启动之后，允许监听新创建的路径\n- 更棒的构建过程\n\n### 使用参数覆盖指定配置\n\n支持使用参数来配置 air 字段:\n\n如果你只是想配置构建命令和运行命令，您可以直接使用以下命令，而无需配置文件:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\"\n```\n\n对于以列表形式输入的参数，使用逗号来分隔项目:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\" --build.exclude_dir \"templates,build\"\n```\n\n旧的 `build.bin` 字段已弃用，将在未来移除，请改用 `build.entrypoint`。\n\n`build.entrypoint` 可以写成单个字符串（只指定可执行文件），也可以写成字符串数组（可执行文件和默认参数）。\n\n## 安装\n\n### 使用 `go install` （推荐）\n\n使用 go 1.25 或更高版本:\n\n```shell\ngo install github.com/air-verse/air@latest\n```\n\n### 使用 `go get -tool`\n\n使用 go 1.25 或更高版本:\n\n```shell\ngo get -tool github.com/air-verse/air@latest\n\n# 然后像这样使用：\ngo tool air -v\n```\n\n### 使用 install.sh\n\n```shell\n# binary 文件会是在 $(go env GOPATH)/bin/air\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin\n\n# 或者把它安装在 ./bin/ 路径下\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s\n\nair -v\n```\n\n### 使用 [goblin.run](https://goblin.run)\n\n```shell\n# binary 将会安装到 /usr/local/bin/air\ncurl -sSfL https://goblin.run/github.com/cosmtrek/air | sh\n\n# 自定义路径安装\ncurl -sSfL https://goblin.run/github.com/cosmtrek/air | PREFIX=/tmp sh\n```\n\n### 使用软件包管理器 [mise](https://github.com/jdx/mise)\n\n```shell\nmise use -g air\n```\n\n### Docker/Podman\n\n请拉取这个 Docker 镜像 [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).\n\n```shell\ndocker run -it --rm \\\n    -w \"<PROJECT>\" \\\n    -e \"air_wd=<PROJECT>\" \\\n    -v $(pwd):<PROJECT> \\\n    -p <PORT>:<APP SERVER PORT> \\\n    cosmtrek/air\n    -c <CONF>\n```\n\n#### Docker/Podman .${SHELL}rc\n\n如果你想像正常应用程序一样连续使用 air，你可以在你的 ${SHELL}rc（Bash, Zsh 等）中创建一个函数\n\n```shell\nair() {\n  podman/docker run -it --rm \\\n    -w \"$PWD\" -v \"$PWD\":\"$PWD\" \\\n    -p \"$AIR_PORT\":\"$AIR_PORT\" \\\n    docker.io/cosmtrek/air \"$@\"\n}\n```\n\n`<PROJECT>` 是容器中的项目路径，例如：`/go/example`\n如果你想进入容器，请添加 `--entrypoint=bash`。\n\n<details>\n  <summary>例如</summary>\n\n我的一个项目运行在 Docker 中：\n\n```shell\ndocker run -it --rm \\\n  -w \"/go/src/github.com/cosmtrek/hub\" \\\n  -v $(pwd):/go/src/github.com/cosmtrek/hub \\\n  -p 9090:9090 \\\n  cosmtrek/air\n```\n\n另一个例子：\n\n```shell\ncd /go/src/github.com/cosmtrek/hub\nAIR_PORT=8080 air -c \"config.toml\"\n```\n\n这将用当前目录替换 `$PWD`，`$AIR_PORT` 是要发布的端口，而 `$@` 用于接受应用程序本身的参数，例如 `-c`\n\n</details>\n\n## 使用方法\n\n为了方便输入，您可以添加 `alias air='~/.air'` 到您的 `.bashrc` 或 `.zshrc` 文件中.\n\n首先，进入你的项目文件夹\n\n```shell\ncd /path/to/your_project\n```\n\n最简单的方法是执行\n\n```shell\n# 先尝试读取当前目录中的 `.air.toml`；如果不存在，则使用默认配置\nair\n```\n\n如果要显式指定配置文件，可以使用：\n\n```shell\nair -c .air.toml\n```\n\n您可以运行以下命令，将具有默认设置的 `.air.toml` 配置文件初始化到当前目录。\n\n```shell\nair init\n```\n\n在这之后，你只需执行 `air` 命令，无需额外参数，它就能使用 `.air.toml` 文件中的配置了。\n\n```shell\nair\n```\n\n如欲修改配置信息，请参考 [air_example.toml](air_example.toml) 文件.\n\n### 运行时参数\n\n您可以通过把变量添加在 air 命令之后来传递参数。\n\n```shell\n# 会执行 ./tmp/main bench\nair bench\n\n# 会执行 ./tmp/main server --port 8080\nair server --port 8080\n```\n\n你可以使用 `--` 参数分隔传递给 air 命令和已构建二进制文件的参数。\n\n```shell\n# 会运行 ./tmp/main -h\nair -- -h\n\n# 会使用个性化配置来运行 air，然后把 -h 后的变量和值添加到运行的参数中\nair -c .air.toml -- -h\n```\n\n### Docker Compose\n\n```yaml\nservices:\n  my-project-with-air:\n    image: cosmtrek/air\n    # working_dir value has to be the same of mapped volume\n    working_dir: /project-package\n    ports:\n      - <any>:<any>\n    environment:\n      - ENV_A=${ENV_A}\n      - ENV_B=${ENV_B}\n      - ENV_C=${ENV_C}\n    volumes:\n      - ./project-relative-path/:/project-package/\n```\n\n### 调试\n\n`air -d` 命令能打印所有日志。\n\n## Docker 用户安装和使用指南（如果不想使用 air 镜像）\n\n`Dockerfile`\n\n```Dockerfile\n# 选择你想要的版本，>= 1.25\nFROM golang:1.25-alpine\n\nWORKDIR /app\n\nRUN go install github.com/air-verse/air@latest\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCMD [\"air\", \"-c\", \".air.toml\"]\n```\n\n`docker-compose.yaml`\n\n```yaml\nversion: \"3.8\"\nservices:\n  web:\n    build:\n      context: .\n      # 修改为你的 Dockerfile 路径\n      dockerfile: Dockerfile\n    ports:\n      - 8080:3000\n    # 为了实时重载，将代码目录绑定到 /app 目录是很重要的\n    volumes:\n      - ./:/app\n```\n\n## Q&A\n\n### 遇到 \"command not found: air\" 或 \"No such file or directory\" 该怎么办？\n\n```shell\nexport GOPATH=$HOME/xxxxx\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nexport PATH=$PATH:$(go env GOPATH)/bin <---- 请确认这行在您的配置信息中！！！\n```\n\n### 在 wsl 下 bin 中包含 ' 时的错误\n\n应该使用 `\\` 来转义 bin 中的 `'`。相关问题：[#305](https://github.com/cosmtrek/air/issues/305)\n\n### 问题：如何只进行热编译而不运行？\n\n[#365](https://github.com/cosmtrek/air/issues/365)\n\n```toml\n[build]\n  cmd = \"/usr/bin/true\"\n```\n\n### 如何在静态文件更改时自动重新加载浏览器?\n\n请参考 [#512](https://github.com/cosmtrek/air/issues/512).\n\n- 确保你的静态文件在 `include_dir`、`include_ext` 或 `include_file` 中。\n- 确保你的 HTML 有一个 `</body>` 标签。\n- 通过配置以下内容开启代理：\n\n```toml\n[proxy]\n  enabled = true\n  proxy_port = <air proxy port>\n  app_port = <your server port>\n```\n\n## 开发\n\n请注意：当前需要 Go 1.25+（见 `go.mod`）。\n\n```shell\n# 1. 首先复刻（fork）这个项目\n\n# 2. 其次克隆（clone）它\nmkdir -p $GOPATH/src/github.com/cosmtrek\ncd $GOPATH/src/github.com/cosmtrek\ngit clone git@github.com:<YOUR USERNAME>/air.git\n\n# 3. 安装依赖\ncd air\nmake ci\n\n# 4. 这样就可以快乐地探索和玩耍啦！\nmake install\n```\n\n顺便说一句: 欢迎 PR~\n\n### 发布新版本\n\n```shell\n# 1. checkout 到 master 分支\ngit checkout master\n\n# 2. 添加需要发布的版本号\ngit tag v1.xx.x\n\n# 3. 推送到远程\ngit push origin v1.xx.x\n\nCI 将处理并发布新版本。等待大约 5 分钟，你就可以获取最新版本了。\n```\n\n## Star 历史\n\n[![Star History Chart](https://api.star-history.com/svg?repos=cosmtrek/air&type=Date)](https://star-history.com/#cosmtrek/air&Date)\n\n## 赞助\n\n[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)\n\n非常感谢众多支持者。我一直铭记你们的善意。\n\n## 许可证\n\n[GNU General Public License v3.0](LICENSE)\n"
  },
  {
    "path": "README-zh_tw.md",
    "content": "# :cloud: Air - Live reload for Go apps\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)](https://github.com/air-verse/air/actions?query=workflow%3AGo+branch%3Amaster) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/dcb95264cc504cad9c2a3d8b0795a7f8)](https://www.codacy.com/gh/air-verse/air/dashboard?utm_source=github.com&utm_medium=referral&utm_content=air-verse/air&utm_campaign=Badge_Grade) [![Go Report Card](https://goreportcard.com/badge/github.com/air-verse/air)](https://goreportcard.com/report/github.com/air-verse/air) [![codecov](https://codecov.io/gh/air-verse/air/branch/master/graph/badge.svg)](https://codecov.io/gh/air-verse/air)\n\n![air](docs/air.png)\n\n[English](README.md) | [简体中文](README-zh_cn.md) | 繁體中文\n\n## 開發動機\n\n當我開始用 Go 開發網站並使用[gin](https://github.com/gin-gonic/gin)框架時，感到可惜的是 gin 缺乏自動重新編譯執行的方式。因此，我四處搜尋並嘗試使用[fresh](https://github.com/pilu/fresh)，但它似乎不夠彈性，所以我打算重新寫得更好。最後，Air 就這麼誕生了。另外，非常感謝[pilu](https://github.com/pilu)，如果沒有 fresh，就不會有 air :)\n\nAir 是一個另類的自動重新編譯執行命令列工具，用於開發 Go 應用。在你的項目根目錄下運行 `air`，將它執行於背景中，並專注於你的程式碼。\n\n注意：此工具與生產環境的熱部署無關。\n\n## 功能列表\n\n- 彩色的日誌輸出\n- 自訂建立或任何命令\n- 支援排除子目錄\n- 允許在 Air 開始後監視新目錄\n- 更佳的建置過程\n\n### 用參數覆寫指定的配置\n\n支援將 air 做為參數的配置字段：\n\n如果你想設定建置命令和執行命令，你可以在不需要配置檔案的情況下如下使用命令：\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\"\n```\n\n對於需要輸入列表的參數，可以使用逗號將項目分隔：\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\" --build.exclude_dir \"templates,build\"\n```\n\n舊的 `build.bin` 欄位已被棄用，未來版本會移除，請改用 `build.entrypoint`。\n\n`build.entrypoint` 可以寫成單一字串（只指定執行檔），也可以寫成字串陣列（執行檔加上預設參數）。\n\n## 安裝\n\n### 使用 `go install` （推薦）\n\n需要使用 go 1.25 或更高版本：\n\n```shell\ngo install github.com/air-verse/air@latest\n```\n\n### 使用 `go get -tool`\n\n需要使用 go 1.25 或更高版本：\n\n```shell\ngo get -tool github.com/air-verse/air@latest\n\n# 然後這樣使用：\ngo tool air -v\n```\n\n### 透過 install.sh\n\n```shell\n# binary will be $(go env GOPATH)/bin/air\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin\n\n# or install it into ./bin/\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s\n\nair -v\n```\n\n### 透過 [goblin.run](https://goblin.run)\n\n```shell\n# binary will be /usr/local/bin/air\ncurl -sSfL https://goblin.run/github.com/air-verse/air | sh\n\n# to put to a custom path\ncurl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh\n```\n\n### 使用軟體套件管理器 [mise](https://github.com/jdx/mise)\n\n```shell\nmise use -g air\n```\n\n### 透過 `go install`\n\n使用 go 1.25 或更高版本:\n\n```bash\ngo install github.com/air-verse/air@latest\n```\n\n### Docker/Podman\n\n請讀取 Docker 映像檔 [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).\n\n```shell\ndocker/podman run -it --rm \\\n    -w \"<PROJECT>\" \\\n    -e \"air_wd=<PROJECT>\" \\\n    -v $(pwd):<PROJECT> \\\n    -p <PORT>:<APP SERVER PORT> \\\n    cosmtrek/air\n    -c <CONF>\n```\n\n#### Docker/Podman .${SHELL}rc\n\n如果你想像常規應用程式一樣持續使用 air，你可以在你的 ${SHELL}rc (Bash, Zsh, etc…) 中創建一個函數。\n\n```shell\nair() {\n  podman/docker run -it --rm \\\n    -w \"$PWD\" -v \"$PWD\":\"$PWD\" \\\n    -p \"$AIR_PORT\":\"$AIR_PORT\" \\\n    docker.io/cosmtrek/air \"$@\"\n}\n```\n\n`<PROJECT>` 是你的容器中的專案路徑，例如：/go/example 如果你想要進入容器，請加上 --entrypoint=bash。\n\n<details>\n  <summary>For example</summary>\n\n我其中一個專案是在 Docker 中運行\n\n```shell\ndocker run -it --rm \\\n  -w \"/go/src/github.com/cosmtrek/hub\" \\\n  -v $(pwd):/go/src/github.com/cosmtrek/hub \\\n  -p 9090:9090 \\\n  cosmtrek/air\n```\n\n另一個例子\n\n```shell\ncd /go/src/github.com/cosmtrek/hub\nAIR_PORT=8080 air -c \"config.toml\"\n```\n\n這將會用當前目錄替換 `$PWD`，`$AIR_PORT` 是發佈的端口，`$@` 是用來接受應用程式本身的參數，例如 -c\n\n</details>\n\n## 使用方式\n\n為了減少輸入，你可以將 `alias air='~/.air'` 加到你的 `.bashrc` 或者 `.zshrc`。\n\n首先，進入你的專案目錄\n\n```shell\ncd /path/to/your_project\n```\n\n最簡單的使用方式是運行\n\n```shell\n# 先嘗試讀取目前目錄中的 `.air.toml`；如果不存在，則使用預設配置\nair\n```\n\n如果要明確指定配置檔，可以使用：\n\n```shell\nair -c .air.toml\n```\n\n你可以用以下命令初始化 `.air.toml` 配置檔到當前目錄，並使用預設設置。\n\n```shell\nair init\n```\n\n此後，你可以只運行 `air` 命令，而不需要額外的參數，它將使用 `.air.toml` 檔案作為配置。\n\n```shell\nair\n```\n\n要修改配置，請參閱 [air_example.toml](air_example.toml) 檔案。\n\n### 運行時參數\n\n你可以在 air 命令後添加參數來運行已構建的二進制檔。\n\n```shell\n# Will run ./tmp/main bench\nair bench\n\n# Will run ./tmp/main server --port 8080\nair server --port 8080\n```\n\n你可以使用 `--` 參數來分隔傳遞給 air 命令和已建構的二進制檔的參數。\n\n```shell\n# Will run ./tmp/main -h\nair -- -h\n\n# Will run air with custom config and pass -h argument to the built binary\nair -c .air.toml -- -h\n```\n\n### Docker Compose\n\n```yaml\nservices:\n  my-project-with-air:\n    image: cosmtrek/air\n    # working_dir value has to be the same of mapped volume\n    working_dir: /project-package\n    ports:\n      - <any>:<any>\n    environment:\n      - ENV_A=${ENV_A}\n      - ENV_B=${ENV_B}\n      - ENV_C=${ENV_C}\n    volumes:\n      - ./project-relative-path/:/project-package/\n```\n\n### 除錯\n\n`air -d` prints all logs.\n\n## 對於不想使用 air 映像的 Docker 使用者的安裝與使用方法\n\n`Dockerfile`\n\n```Dockerfile\n# Choose whatever you want, version >= 1.25\nFROM golang:1.25-alpine\n\nWORKDIR /app\n\nRUN go install github.com/air-verse/air@latest\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCMD [\"air\", \"-c\", \".air.toml\"]\n```\n\n`docker-compose.yaml`\n\n```yaml\nversion: \"3.8\"\nservices:\n  web:\n    build:\n      context: .\n      # Correct the path to your Dockerfile\n      dockerfile: Dockerfile\n    ports:\n      - 8080:3000\n    # Important to bind/mount your codebase dir to /app dir for live reload\n    volumes:\n      - ./:/app\n```\n\n## Q&A\n\n### \"找不到命令：air\" 或者 \"找不到檔案或目錄\"\n\n```shell\nexport GOPATH=$HOME/xxxxx\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nexport PATH=$PATH:$(go env GOPATH)/bin <---- Confirm this line in you profile!!!\n```\n\n### 當 bin 中包含 ' 時，在 wsl 下的錯誤\n\n應該使用 `\\` 來轉義 bin 中的 `'。相關議題：[#305](https://github.com/air-verse/air/issues/305)\n\n## 開發\n\n請注意：目前需要 Go 1.25+（請參考 `go.mod`）。\n\n```shell\n# Fork this project\n\n# Clone it\nmkdir -p $GOPATH/src/github.com/cosmtrek\ncd $GOPATH/src/github.com/cosmtrek\ngit clone git@github.com:<YOUR USERNAME>/air.git\n\n# Install dependencies\ncd air\nmake ci\n\n# Explore it and happy hacking!\nmake install\n```\n\n歡迎提出 Pull Request\n\n### 發佈版本\n\n```shell\n# Checkout to master\ngit checkout master\n\n# Add the version that needs to be released\ngit tag v1.xx.x\n\n# Push to remote\ngit push origin v1.xx.x\n\n# The CI will process and release a new version. Wait about 5 min, and you can fetch the latest version\n```\n\n## 星星歷史\n\n[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)\n\n## 贊助專案\n\n[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)\n\n非常感謝大量的支持者。我一直記得你們的善意。\n\n## 授權\n\n[GNU General Public License v3.0](LICENSE)\n"
  },
  {
    "path": "README.md",
    "content": "# :cloud: Air - Live reload for Go apps\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)](https://github.com/air-verse/air/actions?query=workflow%3AGo+branch%3Amaster) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/dcb95264cc504cad9c2a3d8b0795a7f8)](https://www.codacy.com/gh/air-verse/air/dashboard?utm_source=github.com&utm_medium=referral&utm_content=air-verse/air&utm_campaign=Badge_Grade) [![Go Report Card](https://goreportcard.com/badge/github.com/air-verse/air)](https://goreportcard.com/report/github.com/air-verse/air) [![codecov](https://codecov.io/gh/air-verse/air/branch/master/graph/badge.svg)](https://codecov.io/gh/air-verse/air)\n\n![air](docs/air.png)\n\nEnglish | [简体中文](README-zh_cn.md) | [繁體中文](README-zh_tw.md) | [日本語](README-ja.md)\n\n## Motivation\n\nWhen I started developing websites in Go and using [gin](https://github.com/gin-gonic/gin) framework, it was a pity\nthat gin lacked a live-reloading function. So I searched around and tried [fresh](https://github.com/pilu/fresh), it seems not much\nflexible, so I intended to rewrite it better. Finally, Air's born.\nIn addition, great thanks to [pilu](https://github.com/pilu), no fresh, no air :)\n\nAir is yet another live-reloading command line utility for developing Go applications. Run `air` in your project root directory, leave it alone,\nand focus on your code.\n\nNote: This tool has nothing to do with hot-deploy for production.\n\n## Features\n\n- Colorful log output\n- Customize build or any command\n- Support excluding subdirectories\n- Allow watching new directories after Air started\n- Better building process\n- Configurable `.env` file loading\n\n### Overwrite specify configuration from arguments\n\nSupport air config fields as arguments:\n\nYou can view the available command-line arguments by running the following commands:  \n\n```\nair -h\n```\nor  \n```\nair --help\n```\n\nIf you want to config build command and run command, you can use like the following command without the config file:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\"\n```\n\nUse a comma to separate items for arguments that take a list as input:\n\n```shell\nair --build.cmd \"go build -o bin/api cmd/run.go\" --build.entrypoint \"./bin/api\" --build.exclude_dir \"templates,build\"\n```\n\n## Installation\n\n### Via `go install` (Recommended)\n\nWith go 1.25 or higher:\n\n```shell\ngo install github.com/air-verse/air@latest\n```\n\n### Via `go get -tool` (project install)\n\nWith go 1.25 or higher:\n\n```shell\ngo get -tool github.com/air-verse/air@latest\n\n# then use it like so:\ngo tool air -v\n```\n\n### Via install.sh\n\n```shell\n# binary will be $(go env GOPATH)/bin/air\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin\n\n# or install it into ./bin/\ncurl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s\n\nair -v\n```\n\n### Via [goblin.run](https://goblin.run)\n\n```shell\n# binary will be /usr/local/bin/air\ncurl -sSfL https://goblin.run/github.com/air-verse/air | sh\n\n# to put to a custom path\ncurl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh\n```\n\n### Via [Homebrew](https://github.com/Homebrew/brew)\n\n```shell\nbrew install go-air\n```\n\n### Using software package manager [mise](https://github.com/jdx/mise)\n\n```shell\nmise use -g air\n```\n\n### Docker/Podman\n\nPlease pull this Docker image [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).\n\n```shell\ndocker/podman run -it --rm \\\n    -w \"<PROJECT>\" \\\n    -e \"air_wd=<PROJECT>\" \\\n    -v $(pwd):<PROJECT> \\\n    -p <PORT>:<APP SERVER PORT> \\\n    cosmtrek/air\n    -c <CONF>\n```\n\n#### Docker/Podman .${SHELL}rc\n\nif you want to use air continuously like a normal app, you can create a function in your ${SHELL}rc (Bash, Zsh, etc…)\n\n```shell\nair() {\n  podman/docker run -it --rm \\\n    -w \"$PWD\" -v \"$PWD\":\"$PWD\" \\\n    -p \"$AIR_PORT\":\"$AIR_PORT\" \\\n    docker.io/cosmtrek/air \"$@\"\n}\n```\n\n`<PROJECT>` is your project path in container, eg: /go/example\nif you want to enter the container, Please add --entrypoint=bash.\n\n<details>\n  <summary>For example</summary>\n\nOne of my project runs in Docker:\n\n```shell\ndocker run -it --rm \\\n  -w \"/go/src/github.com/cosmtrek/hub\" \\\n  -v $(pwd):/go/src/github.com/cosmtrek/hub \\\n  -p 9090:9090 \\\n  cosmtrek/air\n```\n\nAnother example:\n\n```shell\ncd /go/src/github.com/cosmtrek/hub\nAIR_PORT=8080 air -c \"config.toml\"\n```\n\nthis will replace `$PWD` with the current directory, `$AIR_PORT` is the port where to publish and `$@` is to accept arguments of the application itself for example -c\n\n</details>\n\n## Usage\n\nFor less typing, you could add `alias air='~/.air'` to your `.bashrc` or `.zshrc`.\n\nFirst enter into your project\n\n```shell\ncd /path/to/your_project\n```\n\nThe simplest usage is to run\n\n```shell\n# first tries `.air.toml` in current directory; if not found, uses defaults\nair\n```\n\nTo use a specific config file explicitly, pass `-c`:\n\n```shell\nair -c .air.toml\n```\n\nYou can initialize the `.air.toml` configuration file to the current directory with the default settings running the following command.\n\n```shell\nair init\n```\n\nAfter this, you can just run the `air` command without additional arguments, and it will use the `.air.toml` file for configuration.\n\n```shell\nair\n```\n\nFor modifying the configuration refer to the [air_example.toml](air_example.toml) file.\n\n### Runtime arguments\n\nYou can pass arguments for running the built binary by adding them after the air command.\n\n```shell\n# Will run ./tmp/main bench\nair bench\n\n# Will run ./tmp/main server --port 8080\nair server --port 8080\n```\n\nYou can separate the arguments passed for the air command and the built binary with `--` argument.\n\n```shell\n# Will run ./tmp/main -h\nair -- -h\n\n# Will run air with custom config and pass -h argument to the built binary\nair -c .air.toml -- -h\n```\n\n### Entrypoint\n\nUse `build.entrypoint` to point at the binary generated by `build.cmd` and describe how it should be executed. The value can be either a string (just the executable) or an array of strings. When using an array, the first element is the executable (resolved relative to `root` unless it lacks a path separator, in which case `$PATH` is consulted) and every subsequent element is treated as a default argument. Values from `build.args_bin` and the command line are appended after the inline arguments. The legacy `build.bin` field is deprecated and will be removed in a future release, so prefer the entrypoint form going forward.\n\n```toml\n[build]\nentrypoint = [\"./tmp/main\"]\nargs_bin = [\"server\", \":8080\"]\n\n# Inline the default arguments directly after the binary.\nentrypoint = [\"./tmp/main\", \"server\", \":8080\"]\n\n# Use PATH-resolved tools like dlv by omitting path separators.\nentrypoint = [\n  \"dlv\", \"exec\", \"--accept-multiclient\", \"--log\", \"--headless\", \"--continue\",\n  \"--listen=:8999\", \"--api-version\", \"2\", \"./tmp/main\",\n]\n```\n\n### Environment Files\n\nAir can automatically load environment variables from `.env` files before both building and running when `env_files` is configured.\n\n```toml\n# Loads .env.development and then .env files.\n# Values in the lattermost file overwrite any preceding ones.\n# Does not overwrite variables that were present before running air.\nenv_files = [\".env.development\", \".env\"]\n```\n\n### Docker Compose\n\n```yaml\nservices:\n  my-project-with-air:\n    image: cosmtrek/air\n    # working_dir value has to be the same of mapped volume\n    working_dir: /project-package\n    ports:\n      - <any>:<any>\n    environment:\n      - ENV_A=${ENV_A}\n      - ENV_B=${ENV_B}\n      - ENV_C=${ENV_C}\n    volumes:\n      - ./project-relative-path/:/project-package/\n```\n\n### Debug\n\n`air -d` prints all logs.\n\n## Installation and Usage for Docker users who don't want to use air image\n\n`Dockerfile`\n\n```Dockerfile\n# Choose whatever you want, version >= 1.25\nFROM golang:1.25-alpine\n\nWORKDIR /app\n\nRUN go install github.com/air-verse/air@latest\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCMD [\"air\", \"-c\", \".air.toml\"]\n```\n\n`docker-compose.yaml`\n\n```yaml\nversion: \"3.8\"\nservices:\n  web:\n    build:\n      context: .\n      # Correct the path to your Dockerfile\n      dockerfile: Dockerfile\n    ports:\n      - 8080:3000\n    # Important to bind/mount your codebase dir to /app dir for live reload\n    volumes:\n      - ./:/app\n```\n\n## Q&A\n\n### \"command not found: air\" or \"No such file or directory\"\n\n```shell\nexport GOPATH=$HOME/xxxxx\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nexport PATH=$PATH:$(go env GOPATH)/bin #Confirm this line in your .profile and make sure to source the .profile if you add it!!!\n```\n\n### Error under wsl when ' is included in the bin\n\nShould use `\\` to escape the `'` in the bin. related issue: [#305](https://github.com/air-verse/air/issues/305)\n\n### Question: how to do hot compile only and do not run anything?\n\n[#365](https://github.com/air-verse/air/issues/365)\n\n```toml\n[build]\n  cmd = \"/usr/bin/true\"\n```\n\n### How to Reload the Browser Automatically on Static File Changes\n\nRefer to issue [#512](https://github.com/air-verse/air/issues/512) for additional details.\n\n- Ensure your static files in `include_dir`, `include_ext`, or `include_file`.\n- Ensure your HTML has a `</body>` tag\n- Activate the proxy by configuring the following config:\n\n```toml\n[proxy]\n  enabled = true\n  proxy_port = <air proxy port>\n  app_port = <your server port>\n```\n\n## Development\n\nPlease note that it requires Go 1.25+ (see `go.mod`).\n\n```shell\n# Fork this project\n\n# Clone it\nmkdir -p $GOPATH/src/github.com/cosmtrek\ncd $GOPATH/src/github.com/cosmtrek\ngit clone git@github.com:<YOUR USERNAME>/air.git\n\n# Install dependencies\ncd air\nmake ci\n\n# Explore it and happy hacking!\nmake install\n```\n\nPull requests are welcome.\n\n### Release\n\n```shell\n# Checkout to master\ngit checkout master\n\n# Add the version that needs to be released\ngit tag v1.xx.x\n\n# Push to remote\ngit push origin v1.xx.x\n\n# The CI will process and release a new version. Wait about 5 min, and you can fetch the latest version\n```\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)\n\n## Sponsor\n\n[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)\n\nGive huge thanks to lots of supporters. I've always been remembering your kindness.\n\n## License\n\n[GNU General Public License v3.0](LICENSE)\n"
  },
  {
    "path": "air_example.toml",
    "content": "#:schema https://json.schemastore.org/any.json\n\n# Config file for [Air](https://github.com/air-verse/air) in TOML format\n\n# Working directory\n# . or absolute path, please note that the directories following must be under root.\nroot = \".\"\ntmp_dir = \"tmp\"\n\n# Remove to not load any files whatsoever\n# Non-existing files are safely ignored\nenv_files = [\".env\"]\n\n[build]\n# Array of commands to run before each build\npre_cmd = [\"echo 'hello air' > pre_cmd.txt\"]\n# Just plain old shell command. You could use `make` as well.\ncmd = \"go build -o ./tmp/main .\"\n# Array of commands to run after ^C\npost_cmd = [\"echo 'hello air' > post_cmd.txt\"]\n# Binary file yields from 'cmd', will be deprecated soon, recommend using entrypoint.\nbin = \"tmp/main\"\n# Entrypoint binary relative to root. First item is the executable, more items are default arguments.\nentrypoint = [\"./tmp/main\"]\n# Customize binary, can setup environment variables when run your app.\nfull_bin = \"APP_ENV=dev APP_USER=air ./tmp/main\"\n# Add additional arguments when running binary (bin/full_bin). Will run './tmp/main hello world'.\nargs_bin = [\"hello\", \"world\"]\n# Watch these filename extensions. Use [\"*\"] to watch all file extensions.\ninclude_ext = [\"go\", \"tpl\", \"tmpl\", \"html\"]\n# Ignore these filename extensions or directories.\nexclude_dir = [\"assets\", \"tmp\", \"vendor\", \"frontend/node_modules\"]\n# Watch these directories if you specified.\ninclude_dir = []\n# Watch these files.\ninclude_file = []\n# Exclude files.\nexclude_file = []\n# Exclude specific regular expressions.\nexclude_regex = [\"_test\\\\.go\"]\n# Exclude unchanged files.\nexclude_unchanged = true\n# Ignore dangerous root directory that could cause excessive file watching\nignore_dangerous_root_dir = false\n# Follow symlink for directories\nfollow_symlink = true\n# This log file is placed in your tmp_dir.\nlog = \"air.log\"\n# Poll files for changes instead of using fsnotify.\npoll = false\n# Poll interval (defaults to the minimum interval of 500ms).\npoll_interval = 500 # ms\n# It's not necessary to trigger build each time file changes if it's too frequent.\ndelay = 0 # ms\n# Stop running old binary when build errors occur.\nstop_on_error = true\n# Send Interrupt signal before killing process (ignored on Windows; uses TASKKILL)\nsend_interrupt = false\n# Delay after sending Interrupt signal\nkill_delay = 500 # nanosecond\n# Rerun binary or not\nrerun = false\n# Delay after each execution\nrerun_delay = 500\n\n[log]\n# Show log time\ntime = false\n# Only show main log (silences watcher, build, runner)\nmain_only = false\n# silence all logs produced by air \nsilent = false\n\n[color]\n# Customize each part's color. If no color found, use the raw app log.\nmain = \"magenta\"\nwatcher = \"cyan\"\nbuild = \"yellow\"\nrunner = \"green\"\n\n[misc]\n# Delete tmp directory on exit\nclean_on_exit = true\n\n[screen]\nclear_on_rebuild = true\nkeep_scroll = true\n\n[proxy]\n# Enable live-reloading on the browser.\nenabled = true\nproxy_port = 8090\napp_port = 8080\n# Timeout in milliseconds for waiting for the app to start and become available.\n# Useful when your app has slow startup time (e.g., database connections, config loading).\n# The proxy will retry connecting to your app for this duration before giving up.\n# Default is 5000ms (5 seconds). Increase this if you see \"unable to reach app\" errors.\napp_start_timeout = 5000\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/air-verse/air\n\ngo 1.25\n\nrequire (\n\tdario.cat/mergo v1.0.2\n\tgithub.com/andybalholm/brotli v1.2.0\n\tgithub.com/fatih/color v1.18.0\n\tgithub.com/fsnotify/fsnotify v1.9.0\n\tgithub.com/gohugoio/hugo v0.149.1\n\tgithub.com/joho/godotenv v1.5.1\n\tgithub.com/pelletier/go-toml v1.9.5\n\tgithub.com/stretchr/testify v1.11.1\n\tgolang.org/x/sys v0.35.0\n)\n\nrequire (\n\tgithub.com/bep/debounce v1.2.1 // indirect\n\tgithub.com/bep/godartsass/v2 v2.5.0 // indirect\n\tgithub.com/bep/golibsass v1.2.0 // indirect\n\tgithub.com/bep/gowebp v0.4.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/mattn/go-colorable v0.1.14 // indirect\n\tgithub.com/mattn/go-isatty v0.0.20 // indirect\n\tgithub.com/pelletier/go-toml/v2 v2.2.4 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rivo/uniseg v0.4.7 // indirect\n\tgithub.com/spf13/afero v1.14.0 // indirect\n\tgithub.com/spf13/cast v1.9.2 // indirect\n\tgithub.com/tdewolff/parse/v2 v2.8.3 // indirect\n\tgolang.org/x/text v0.28.0 // indirect\n\tgoogle.golang.org/protobuf v1.36.8 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=\ndario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=\ngithub.com/BurntSushi/locker v0.0.0-20171006230638-a6e239ea1c69 h1:+tu3HOoMXB7RXEINRVIpxJCT+KdYiI7LAEAUrOw3dIU=\ngithub.com/BurntSushi/locker v0.0.0-20171006230638-a6e239ea1c69/go.mod h1:L1AbZdiDllfyYH5l5OkAaZtk7VkWe89bPJFmnDBNHxg=\ngithub.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=\ngithub.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=\ngithub.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=\ngithub.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=\ngithub.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c h1:651/eoCRnQ7YtSjAnSzRucrJz+3iGEFt+ysraELS81M=\ngithub.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=\ngithub.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=\ngithub.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=\ngithub.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=\ngithub.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=\ngithub.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=\ngithub.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=\ngithub.com/bep/gitmap v1.9.0 h1:2pyb1ex+cdwF6c4tsrhEgEKfyNfxE34d5K+s2sa9byc=\ngithub.com/bep/gitmap v1.9.0/go.mod h1:Juq6e1qqCRvc1W7nzgadPGI9IGV13ZncEebg5atj4Vo=\ngithub.com/bep/goat v0.5.0 h1:S8jLXHCVy/EHIoCY+btKkmcxcXFd34a0Q63/0D4TKeA=\ngithub.com/bep/goat v0.5.0/go.mod h1:Md9x7gRxiWKs85yHlVTvHQw9rg86Bm+Y4SuYE8CTH7c=\ngithub.com/bep/godartsass/v2 v2.5.0 h1:tKRvwVdyjCIr48qgtLa4gHEdtRkPF8H1OeEhJAEv7xg=\ngithub.com/bep/godartsass/v2 v2.5.0/go.mod h1:rjsi1YSXAl/UbsGL85RLDEjRKdIKUlMQHr6ChUNYOFU=\ngithub.com/bep/golibsass v1.2.0 h1:nyZUkKP/0psr8nT6GR2cnmt99xS93Ji82ZD9AgOK6VI=\ngithub.com/bep/golibsass v1.2.0/go.mod h1:DL87K8Un/+pWUS75ggYv41bliGiolxzDKWJAq3eJ1MA=\ngithub.com/bep/goportabletext v0.1.0 h1:8dqym2So1cEqVZiBa4ZnMM1R9l/DnC1h4ONg4J5kujw=\ngithub.com/bep/goportabletext v0.1.0/go.mod h1:6lzSTsSue75bbcyvVc0zqd1CdApuT+xkZQ6Re5DzZFg=\ngithub.com/bep/gowebp v0.4.0 h1:QihuVnvIKbRoeBNQkN0JPMM8ClLmD6V2jMftTFwSK3Q=\ngithub.com/bep/gowebp v0.4.0/go.mod h1:95gtYkAA8iIn1t3HkAPurRCVGV/6NhgaHJ1urz0iIwc=\ngithub.com/bep/helpers v0.6.0 h1:qtqMCK8XPFNM9hp5Ztu9piPjxNNkk8PIyUVjg6v8Bsw=\ngithub.com/bep/helpers v0.6.0/go.mod h1:IOZlgx5PM/R/2wgyCatfsgg5qQ6rNZJNDpWGXqDR044=\ngithub.com/bep/imagemeta v0.12.0 h1:ARf+igs5B7pf079LrqRnwzQ/wEB8Q9v4NSDRZO1/F5k=\ngithub.com/bep/imagemeta v0.12.0/go.mod h1:23AF6O+4fUi9avjiydpKLStUNtJr5hJB4rarG18JpN8=\ngithub.com/bep/lazycache v0.8.0 h1:lE5frnRjxaOFbkPZ1YL6nijzOPPz6zeXasJq8WpG4L8=\ngithub.com/bep/lazycache v0.8.0/go.mod h1:BQ5WZepss7Ko91CGdWz8GQZi/fFnCcyWupv8gyTeKwk=\ngithub.com/bep/logg v0.4.0 h1:luAo5mO4ZkhA5M1iDVDqDqnBBnlHjmtZF6VAyTp+nCQ=\ngithub.com/bep/logg v0.4.0/go.mod h1:Ccp9yP3wbR1mm++Kpxet91hAZBEQgmWgFgnXX3GkIV0=\ngithub.com/bep/overlayfs v0.10.0 h1:wS3eQ6bRsLX+4AAmwGjvoFSAQoeheamxofFiJ2SthSE=\ngithub.com/bep/overlayfs v0.10.0/go.mod h1:ouu4nu6fFJaL0sPzNICzxYsBeWwrjiTdFZdK4lI3tro=\ngithub.com/bep/tmc v0.5.1 h1:CsQnSC6MsomH64gw0cT5f+EwQDcvZz4AazKunFwTpuI=\ngithub.com/bep/tmc v0.5.1/go.mod h1:tGYHN8fS85aJPhDLgXETVKp+PR382OvFi2+q2GkGsq0=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME=\ngithub.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvdZ6pc=\ngithub.com/disintegration/gift v1.2.1/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI=\ngithub.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=\ngithub.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=\ngithub.com/evanw/esbuild v0.25.9 h1:aU7GVC4lxJGC1AyaPwySWjSIaNLAdVEEuq3chD0Khxs=\ngithub.com/evanw/esbuild v0.25.9/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=\ngithub.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=\ngithub.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=\ngithub.com/frankban/quicktest v1.7.2/go.mod h1:jaStnuzAqU1AJdCO0l53JDCJrVDKcS03DbaAcR7Ks/o=\ngithub.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=\ngithub.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=\ngithub.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=\ngithub.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=\ngithub.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=\ngithub.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=\ngithub.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=\ngithub.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=\ngithub.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=\ngithub.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4=\ngithub.com/gobuffalo/flect v1.0.3/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e h1:QArsSubW7eDh8APMXkByjQWvuljwPGAGQpJEFn0F0wY=\ngithub.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e/go.mod h1:3Ltoo9Banwq0gOtcOwxuHG6omk+AwsQPADyw2vQYOJQ=\ngithub.com/gohugoio/hashstructure v0.5.0 h1:G2fjSBU36RdwEJBWJ+919ERvOVqAg9tfcYp47K9swqg=\ngithub.com/gohugoio/hashstructure v0.5.0/go.mod h1:Ser0TniXuu/eauYmrwM4o64EBvySxNzITEOLlm4igec=\ngithub.com/gohugoio/httpcache v0.7.0 h1:ukPnn04Rgvx48JIinZvZetBfHaWE7I01JR2Q2RrQ3Vs=\ngithub.com/gohugoio/httpcache v0.7.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI=\ngithub.com/gohugoio/hugo v0.149.1 h1:uWOc8Ve4h4e48FyYhBquRoHCJviyxA5yGrFJLT48yio=\ngithub.com/gohugoio/hugo v0.149.1/go.mod h1:HS6BP6e8FGxungP4CHC3zeLDvhBLnTJIjHJZWTZjs7o=\ngithub.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0 h1:dco+7YiOryRoPOMXwwaf+kktZSCtlFtreNdiJbETvYE=\ngithub.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0/go.mod h1:CRrxQTKeM3imw+UoS4EHKyrqB7Zp6sAJiqHit+aMGTE=\ngithub.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1 h1:nUzXfRTszLliZuN0JTKeunXTRaiFX6ksaWP0puLLYAY=\ngithub.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1/go.mod h1:Wy8ThAA8p2/w1DY05vEzq6EIeI2mzDjvHsu7ULBVwog=\ngithub.com/gohugoio/locales v0.14.0 h1:Q0gpsZwfv7ATHMbcTNepFd59H7GoykzWJIxi113XGDc=\ngithub.com/gohugoio/locales v0.14.0/go.mod h1:ip8cCAv/cnmVLzzXtiTpPwgJ4xhKZranqNqtoIu0b/4=\ngithub.com/gohugoio/localescompressed v1.0.1 h1:KTYMi8fCWYLswFyJAeOtuk/EkXR/KPTHHNN9OS+RTxo=\ngithub.com/gohugoio/localescompressed v1.0.1/go.mod h1:jBF6q8D7a0vaEmcWPNcAjUZLJaIVNiwvM3WlmTvooB0=\ngithub.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=\ngithub.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=\ngithub.com/hairyhenderson/go-codeowners v0.7.0 h1:s0W4wF8bdsBEjTWzwzSlsatSthWtTAF2xLgo4a4RwAo=\ngithub.com/hairyhenderson/go-codeowners v0.7.0/go.mod h1:wUlNgQ3QjqC4z8DnM5nnCYVq/icpqXJyJOukKx5U8/Q=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/jdkato/prose v1.2.1 h1:Fp3UnJmLVISmlc57BgKUzdjr0lOtjqTZicL3PaYy6cU=\ngithub.com/jdkato/prose v1.2.1/go.mod h1:AiRHgVagnEx2JbQRQowVBKjG0bcs/vtkGCH1dYAL1rA=\ngithub.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=\ngithub.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=\ngithub.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=\ngithub.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=\ngithub.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kyokomi/emoji/v2 v2.2.13 h1:GhTfQa67venUUvmleTNFnb+bi7S3aocF7ZCXU9fSO7U=\ngithub.com/kyokomi/emoji/v2 v2.2.13/go.mod h1:JUcn42DTdsXJo1SWanHh4HKDEyPaR5CqkmoirZZP9qE=\ngithub.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=\ngithub.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=\ngithub.com/makeworld-the-better-one/dither/v2 v2.4.0 h1:Az/dYXiTcwcRSe59Hzw4RI1rSnAZns+1msaCXetrMFE=\ngithub.com/makeworld-the-better-one/dither/v2 v2.4.0/go.mod h1:VBtN8DXO7SNtyGmLiGA7IsFeKrBkQPze1/iAeM95arc=\ngithub.com/marekm4/color-extractor v1.2.1 h1:3Zb2tQsn6bITZ8MBVhc33Qn1k5/SEuZ18mrXGUqIwn0=\ngithub.com/marekm4/color-extractor v1.2.1/go.mod h1:90VjmiHI6M8ez9eYUaXLdcKnS+BAOp7w+NpwBdkJmpA=\ngithub.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=\ngithub.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=\ngithub.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=\ngithub.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=\ngithub.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=\ngithub.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=\ngithub.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=\ngithub.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c h1:cqn374mizHuIWj+OSJCajGr/phAmuMug9qIX3l9CflE=\ngithub.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=\ngithub.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=\ngithub.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=\ngithub.com/muesli/smartcrop v0.3.0 h1:JTlSkmxWg/oQ1TcLDoypuirdE8Y/jzNirQeLkxpA6Oc=\ngithub.com/muesli/smartcrop v0.3.0/go.mod h1:i2fCI/UorTfgEpPPLWiFBv4pye+YAG78RwcQLUkocpI=\ngithub.com/niklasfasching/go-org v1.9.1 h1:/3s4uTPOF06pImGa2Yvlp24yKXZoTYM+nsIlMzfpg/0=\ngithub.com/niklasfasching/go-org v1.9.1/go.mod h1:ZAGFFkWvUQcpazmi/8nHqwvARpr1xpb+Es67oUGX/48=\ngithub.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY=\ngithub.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw=\ngithub.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c=\ngithub.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=\ngithub.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=\ngithub.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=\ngithub.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=\ngithub.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=\ngithub.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=\ngithub.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=\ngithub.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=\ngithub.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=\ngithub.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=\ngithub.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=\ngithub.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=\ngithub.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=\ngithub.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=\ngithub.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=\ngithub.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=\ngithub.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=\ngithub.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=\ngithub.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=\ngithub.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=\ngithub.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tdewolff/minify/v2 v2.24.2 h1:vnY3nTulEAbCAAlxTxPPDkzG24rsq31SOzp63yT+7mo=\ngithub.com/tdewolff/minify/v2 v2.24.2/go.mod h1:1JrCtoZXaDbqioQZfk3Jdmr0GPJKiU7c1Apmb+7tCeE=\ngithub.com/tdewolff/parse/v2 v2.8.3 h1:5VbvtJ83cfb289A1HzRA9sf02iT8YyUwN84ezjkdY1I=\ngithub.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo=\ngithub.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE=\ngithub.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=\ngithub.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=\ngithub.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=\ngithub.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0=\ngithub.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds=\ngithub.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=\ngithub.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=\ngithub.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=\ngithub.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=\ngithub.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs=\ngithub.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA=\ngolang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b h1:DXr+pvt3nC887026GRP39Ej11UATqWDmWuS99x26cD0=\ngolang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=\ngolang.org/x/image v0.30.0 h1:jD5RhkmVAnjqaCUXfbGBrn3lpxbknfN9w2UhHHU+5B4=\ngolang.org/x/image v0.30.0/go.mod h1:SAEUTxCCMWSrJcCy/4HwavEsfZZJlYxeHLc6tTiAe/c=\ngolang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=\ngolang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=\ngolang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=\ngolang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=\ngolang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=\ngolang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=\ngolang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=\ngolang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=\ngolang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=\ngolang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=\ngolang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=\ngoogle.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=\ngoogle.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\nrsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=\nrsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=\n"
  },
  {
    "path": "hack/check.sh",
    "content": "#!/usr/bin/env bash\n\nreadonly reset=$(tput sgr0)\nreadonly red=$(tput bold; tput setaf 1)\nreadonly green=$(tput bold; tput setaf 2)\n\nexit_code=0\ncheck_scope=$1\nif [[ \"${check_scope}\" = \"all\" ]]; then\n    echo \"all\"\n    files=($(git ls-files | grep \"\\.go$\" | grep -v -e \"^third_party\" -e \"^vendor\"))\nelse\n    files=($(git diff --cached --name-only --diff-filter ACM | grep \"\\.go$\" | grep -v -e \"^third_party\" -e \"^vendor\"))\nfi\n\necho -e \"${green}1. Formatting code style\"\nif [[ \"${#files[@]}\" -ne 0 ]]; then\n    goimports -w ${files[@]}\nfi\n\necho -e \"${green}2. Linting\"\nif ! command -v golangci-lint &> /dev/null; then\n    echo \"${red}golangci-lint command not found. Please install it first.\"\n    exit_code=1\nelse\n    # If golangci-lint was built with an older Go than the module target, hint to upgrade\n    lint_go_ver=$(golangci-lint --version 2>/dev/null | sed -n 's/.*built with go\\([0-9]\\+\\.[0-9]\\+\\).*/\\1/p')\n    mod_go_ver=$(sed -n 's/^go \\([0-9]\\+\\.[0-9]\\+\\).*/\\1/p' go.mod | head -n1)\n    if [[ -n \"${lint_go_ver}\" && -n \"${mod_go_ver}\" ]]; then\n        lint_minor=$(echo \"${lint_go_ver}\" | cut -d. -f2)\n        mod_minor=$(echo \"${mod_go_ver}\" | cut -d. -f2)\n        if [[ ${lint_minor} -lt ${mod_minor} ]]; then\n            echo \"${red}can't load config: the Go language version (go${lint_go_ver}) used to build golangci-lint is lower than the targeted Go version (${mod_go_ver})\"\n            echo \"${red}Hint: upgrade golangci-lint (run: make init)\"\n            exit_code=1\n        fi\n    fi\n\n    if [[ ${exit_code} -eq 0 ]] && ! golangci-lint run; then\n        echo \"${red}Linting issues found.\"\n        exit_code=1\n    fi\nfi\n\nif [[ ${exit_code} -ne 0 ]]; then\n    echo \"${red}Please fix the errors above :)\"\nelse\n    echo \"${green}Nice!\"\nfi\necho \"${reset}\"\n\nexit ${exit_code}\n"
  },
  {
    "path": "hooks/pre-commit",
    "content": "#!/usr/bin/env bash\n\nset -e\n\n./hack/check.sh\nexit $?\n"
  },
  {
    "path": "install.sh",
    "content": "#!/bin/sh\nset -e\n# Code generated by godownloader on 2020-08-12T16:16:22Z. DO NOT EDIT.\n#\n\nusage() {\n  this=$1\n  cat <<EOF\n$this: download go binaries for air-verse/air\n\nUsage: $this [-b] bindir [-d] [tag]\n  -b sets bindir or installation directory, Defaults to ./bin\n  -d turns on debug logging\n   [tag] is a tag from\n   https://github.com/air-verse/air/releases\n   If tag is missing, then the latest will be used.\n\n Generated by godownloader\n  https://github.com/goreleaser/godownloader\n\nEOF\n  exit 2\n}\n\nparse_args() {\n  #BINDIR is ./bin unless set be ENV\n  # over-ridden by flag below\n\n  BINDIR=${BINDIR:-./bin}\n  while getopts \"b:dh?x\" arg; do\n    case \"$arg\" in\n      b) BINDIR=\"$OPTARG\" ;;\n      d) log_set_priority 10 ;;\n      h | \\?) usage \"$0\" ;;\n      x) set -x ;;\n    esac\n  done\n  shift $((OPTIND - 1))\n  TAG=$1\n}\n# this function wraps all the destructive operations\n# if a curl|bash cuts off the end of the script due to\n# network, either nothing will happen or will syntax error\n# out preventing half-done work\nexecute() {\n  tmpdir=$(mktemp -d)\n  log_debug \"downloading files into ${tmpdir}\"\n  http_download \"${tmpdir}/${TARBALL}\" \"${TARBALL_URL}\"\n  http_download \"${tmpdir}/${CHECKSUM}\" \"${CHECKSUM_URL}\"\n  hash_sha256_verify \"${tmpdir}/${TARBALL}\" \"${tmpdir}/${CHECKSUM}\"\n  srcdir=\"${tmpdir}\"\n  (cd \"${tmpdir}\" && untar \"${TARBALL}\")\n  test ! -d \"${BINDIR}\" && install -d \"${BINDIR}\"\n  for binexe in $BINARIES; do\n    if [ \"$OS\" = \"windows\" ]; then\n      binexe=\"${binexe}.exe\"\n    fi\n    install \"${srcdir}/${binexe}\" \"${BINDIR}/\"\n    log_info \"installed ${BINDIR}/${binexe}\"\n  done\n  rm -rf \"${tmpdir}\"\n}\nget_binaries() {\n  case \"$PLATFORM\" in\n    darwin/amd64) BINARIES=\"air\" ;;\n    darwin/arm64) BINARIES=\"air\" ;;\n    linux/386) BINARIES=\"air\" ;;\n    linux/amd64) BINARIES=\"air\" ;;\n    linux/arm64) BINARIES=\"air\" ;;\n    windows/386) BINARIES=\"air\" ;;\n    windows/amd64) BINARIES=\"air\" ;;\n    *)\n      log_crit \"platform $PLATFORM is not supported.  Make sure this script is up-to-date and file request at https://github.com/${PREFIX}/issues/new\"\n      exit 1\n      ;;\n  esac\n}\ntag_to_version() {\n  if [ -z \"${TAG}\" ]; then\n    log_info \"checking GitHub for latest tag\"\n  else\n    log_info \"checking GitHub for tag '${TAG}'\"\n  fi\n  REALTAG=$(github_release \"$OWNER/$REPO\" \"${TAG}\") && true\n  if test -z \"$REALTAG\"; then\n    log_crit \"unable to find '${TAG}' - use 'latest' or see https://github.com/${PREFIX}/releases for details\"\n    exit 1\n  fi\n  # if version starts with 'v', remove it\n  TAG=\"$REALTAG\"\n  VERSION=${TAG#v}\n}\nadjust_format() {\n  # change format (tar.gz or zip) based on OS\n  true\n}\nadjust_os() {\n  # adjust archive name based on OS\n  true\n}\nadjust_arch() {\n  # adjust archive name based on ARCH\n  true\n}\n\ncat /dev/null <<EOF\n------------------------------------------------------------------------\nhttps://github.com/client9/shlib - portable posix shell functions\nPublic domain - http://unlicense.org\nhttps://github.com/client9/shlib/blob/master/LICENSE.md\nbut credit (and pull requests) appreciated.\n------------------------------------------------------------------------\nEOF\nis_command() {\n  command -v \"$1\" >/dev/null\n}\nechoerr() {\n  echo \"$@\" 1>&2\n}\nlog_prefix() {\n  echo \"$0\"\n}\n_logp=6\nlog_set_priority() {\n  _logp=\"$1\"\n}\nlog_priority() {\n  if test -z \"$1\"; then\n    echo \"$_logp\"\n    return\n  fi\n  [ \"$1\" -le \"$_logp\" ]\n}\nlog_tag() {\n  case $1 in\n    0) echo \"emerg\" ;;\n    1) echo \"alert\" ;;\n    2) echo \"crit\" ;;\n    3) echo \"err\" ;;\n    4) echo \"warning\" ;;\n    5) echo \"notice\" ;;\n    6) echo \"info\" ;;\n    7) echo \"debug\" ;;\n    *) echo \"$1\" ;;\n  esac\n}\nlog_debug() {\n  log_priority 7 || return 0\n  echoerr \"$(log_prefix)\" \"$(log_tag 7)\" \"$@\"\n}\nlog_info() {\n  log_priority 6 || return 0\n  echoerr \"$(log_prefix)\" \"$(log_tag 6)\" \"$@\"\n}\nlog_err() {\n  log_priority 3 || return 0\n  echoerr \"$(log_prefix)\" \"$(log_tag 3)\" \"$@\"\n}\nlog_crit() {\n  log_priority 2 || return 0\n  echoerr \"$(log_prefix)\" \"$(log_tag 2)\" \"$@\"\n}\nuname_os() {\n  os=$(uname -s | tr '[:upper:]' '[:lower:]')\n  case \"$os\" in\n    cygwin_nt*) os=\"windows\" ;;\n    mingw*) os=\"windows\" ;;\n    msys_nt*) os=\"windows\" ;;\n  esac\n  echo \"$os\"\n}\nuname_arch() {\n  arch=$(uname -m)\n  case $arch in\n    x86_64) arch=\"amd64\" ;;\n    x86) arch=\"386\" ;;\n    i686) arch=\"386\" ;;\n    i386) arch=\"386\" ;;\n    aarch64) arch=\"arm64\" ;;\n    armv5*) arch=\"armv5\" ;;\n    armv6*) arch=\"armv6\" ;;\n    armv7*) arch=\"armv7\" ;;\n  esac\n  echo ${arch}\n}\nuname_os_check() {\n  os=$(uname_os)\n  case \"$os\" in\n    darwin) return 0 ;;\n    dragonfly) return 0 ;;\n    freebsd) return 0 ;;\n    linux) return 0 ;;\n    android) return 0 ;;\n    nacl) return 0 ;;\n    netbsd) return 0 ;;\n    openbsd) return 0 ;;\n    plan9) return 0 ;;\n    solaris) return 0 ;;\n    windows) return 0 ;;\n  esac\n  log_crit \"uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib\"\n  return 1\n}\nuname_arch_check() {\n  arch=$(uname_arch)\n  case \"$arch\" in\n    386) return 0 ;;\n    amd64) return 0 ;;\n    arm64) return 0 ;;\n    armv5) return 0 ;;\n    armv6) return 0 ;;\n    armv7) return 0 ;;\n    ppc64) return 0 ;;\n    ppc64le) return 0 ;;\n    mips) return 0 ;;\n    mipsle) return 0 ;;\n    mips64) return 0 ;;\n    mips64le) return 0 ;;\n    s390x) return 0 ;;\n    amd64p32) return 0 ;;\n  esac\n  log_crit \"uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value.  Please file bug report at https://github.com/client9/shlib\"\n  return 1\n}\nuntar() {\n  tarball=$1\n  case \"${tarball}\" in\n    *.tar.gz | *.tgz) tar --no-same-owner -xzf \"${tarball}\" ;;\n    *.tar) tar --no-same-owner -xf \"${tarball}\" ;;\n    *.zip) unzip \"${tarball}\" ;;\n    *)\n      log_err \"untar unknown archive format for ${tarball}\"\n      return 1\n      ;;\n  esac\n}\nhttp_download_curl() {\n  local_file=$1\n  source_url=$2\n  header=$3\n  if [ -z \"$header\" ]; then\n    code=$(curl -w '%{http_code}' -sL -o \"$local_file\" \"$source_url\")\n  else\n    code=$(curl -w '%{http_code}' -sL -H \"$header\" -o \"$local_file\" \"$source_url\")\n  fi\n  if [ \"$code\" != \"200\" ]; then\n    log_debug \"http_download_curl received HTTP status $code\"\n    return 1\n  fi\n  return 0\n}\nhttp_download_wget() {\n  local_file=$1\n  source_url=$2\n  header=$3\n  if [ -z \"$header\" ]; then\n    wget -q -O \"$local_file\" \"$source_url\"\n  else\n    wget -q --header \"$header\" -O \"$local_file\" \"$source_url\"\n  fi\n}\nhttp_download() {\n  log_debug \"http_download $2\"\n  if is_command curl; then\n    http_download_curl \"$@\"\n    return\n  elif is_command wget; then\n    http_download_wget \"$@\"\n    return\n  fi\n  log_crit \"http_download unable to find wget or curl\"\n  return 1\n}\nhttp_copy() {\n  tmp=$(mktemp)\n  http_download \"${tmp}\" \"$1\" \"$2\" || return 1\n  body=$(cat \"$tmp\")\n  rm -f \"${tmp}\"\n  echo \"$body\"\n}\ngithub_release() {\n  owner_repo=$1\n  version=$2\n  test -z \"$version\" && version=\"latest\"\n  giturl=\"https://github.com/${owner_repo}/releases/${version}\"\n  json=$(http_copy \"$giturl\" \"Accept:application/json\")\n  test -z \"$json\" && return 1\n  version=$(echo \"$json\" | tr -s '\\n' ' ' | sed 's/.*\"tag_name\":\"//' | sed 's/\".*//')\n  test -z \"$version\" && return 1\n  echo \"$version\"\n}\nhash_sha256() {\n  TARGET=${1:-/dev/stdin}\n  if is_command gsha256sum; then\n    hash=$(gsha256sum \"$TARGET\") || return 1\n    echo \"$hash\" | cut -d ' ' -f 1\n  elif is_command sha256sum; then\n    hash=$(sha256sum \"$TARGET\") || return 1\n    echo \"$hash\" | cut -d ' ' -f 1\n  elif is_command shasum; then\n    hash=$(shasum -a 256 \"$TARGET\" 2>/dev/null) || return 1\n    echo \"$hash\" | cut -d ' ' -f 1\n  elif is_command openssl; then\n    hash=$(openssl -dst openssl dgst -sha256 \"$TARGET\") || return 1\n    echo \"$hash\" | cut -d ' ' -f a\n  else\n    log_crit \"hash_sha256 unable to find command to compute sha-256 hash\"\n    return 1\n  fi\n}\nhash_sha256_verify() {\n  TARGET=$1\n  checksums=$2\n  if [ -z \"$checksums\" ]; then\n    log_err \"hash_sha256_verify checksum file not specified in arg2\"\n    return 1\n  fi\n  BASENAME=${TARGET##*/}\n  want=$(grep \"${BASENAME}\" \"${checksums}\" 2>/dev/null | tr '\\t' ' ' | cut -d ' ' -f 1)\n  if [ -z \"$want\" ]; then\n    log_err \"hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'\"\n    return 1\n  fi\n  got=$(hash_sha256 \"$TARGET\")\n  if [ \"$want\" != \"$got\" ]; then\n    log_err \"hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got\"\n    return 1\n  fi\n}\ncat /dev/null <<EOF\n------------------------------------------------------------------------\nEnd of functions from https://github.com/client9/shlib\n------------------------------------------------------------------------\nEOF\n\nPROJECT_NAME=\"air\"\nOWNER=cosmtrek\nREPO=\"air\"\nBINARY=air\nFORMAT=tar.gz\nOS=$(uname_os)\nARCH=$(uname_arch)\nPREFIX=\"$OWNER/$REPO\"\n\n# use in logging routines\nlog_prefix() {\n\techo \"$PREFIX\"\n}\nPLATFORM=\"${OS}/${ARCH}\"\nGITHUB_DOWNLOAD=https://github.com/${OWNER}/${REPO}/releases/download\n\nuname_os_check \"$OS\"\nuname_arch_check \"$ARCH\"\n\nparse_args \"$@\"\n\nget_binaries\n\ntag_to_version\n\nadjust_format\n\nadjust_os\n\nadjust_arch\n\nlog_info \"found version: ${VERSION} for ${TAG}/${OS}/${ARCH}\"\n\nNAME=${PROJECT_NAME}_${VERSION}_${OS}_${ARCH}\nTARBALL=${NAME}.${FORMAT}\nTARBALL_URL=${GITHUB_DOWNLOAD}/${TAG}/${TARBALL}\nCHECKSUM=${PROJECT_NAME}_${VERSION}_checksums.txt\nCHECKSUM_URL=${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUM}\n\n\nexecute\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"syscall\"\n\n\t\"github.com/air-verse/air/runner\"\n\t\"github.com/fatih/color\"\n)\n\nvar (\n\tcfgPath     string\n\tdebugMode   bool\n\tshowVersion bool\n\tcolorMode   string\n\tcmdArgs     map[string]runner.TomlInfo\n)\n\nfunc helpMessage() {\n\tfmt.Fprintf(flag.CommandLine.Output(), \"Usage of %s:\\n\\n\", os.Args[0])\n\tfmt.Printf(\"If no command is provided %s will start the runner with the provided flags\\n\\n\", os.Args[0])\n\tfmt.Println(\"Commands:\")\n\tfmt.Print(\"  init\tcreates a .air.toml file with default settings to the current directory\\n\\n\")\n\n\tfmt.Println(\"Flags:\")\n\tflag.PrintDefaults()\n}\n\nfunc init() {\n\tparseFlag(os.Args[1:])\n}\n\nfunc parseFlag(args []string) {\n\tflag.Usage = helpMessage\n\tflag.StringVar(&cfgPath, \"c\", \"\", \"config path\")\n\tflag.BoolVar(&debugMode, \"d\", false, \"debug mode\")\n\tflag.BoolVar(&showVersion, \"v\", false, \"show version\")\n\tflag.StringVar(&colorMode, \"color\", \"auto\", \"colored output: auto, always, never\")\n\tcmd := flag.CommandLine\n\tcmdArgs = runner.ParseConfigFlag(cmd)\n\tif err := flag.CommandLine.Parse(args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype versionInfo struct {\n\tairVersion string\n\tgoVersion  string\n}\n\nfunc GetVersionInfo() versionInfo { //revive:disable:unexported-return\n\tif len(airVersion) != 0 && len(goVersion) != 0 {\n\t\treturn versionInfo{\n\t\t\tairVersion: airVersion,\n\t\t\tgoVersion:  goVersion,\n\t\t}\n\t}\n\tif info, ok := debug.ReadBuildInfo(); ok {\n\t\treturn versionInfo{\n\t\t\tairVersion: info.Main.Version,\n\t\t\tgoVersion:  runtime.Version(),\n\t\t}\n\t}\n\treturn versionInfo{\n\t\tairVersion: \"(unknown)\",\n\t\tgoVersion:  runtime.Version(),\n\t}\n}\n\nfunc printSplash() {\n\tversionInfo := GetVersionInfo()\n\tfmt.Printf(`\n  __    _   ___  \n / /\\  | | | |_) \n/_/--\\ |_| |_| \\_ %s, built with Go %s\n\n`, versionInfo.airVersion, versionInfo.goVersion)\n}\n\nfunc main() {\n\tswitch colorMode {\n\tcase \"always\":\n\t\tcolor.NoColor = false\n\tcase \"never\":\n\t\tcolor.NoColor = true\n\tcase \"auto\", \"\":\n\t\t// do nothing\n\tdefault:\n\t\tlog.Fatal(\"unsupported color mode: use always, never, auto\")\n\t}\n\tif showVersion {\n\t\tprintSplash()\n\t\treturn\n\t}\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)\n\n\tvar err error\n\tcfg, err := runner.InitConfig(cfgPath, cmdArgs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tif !cfg.Log.Silent {\n\t\tprintSplash()\n\t}\n\tif debugMode && !cfg.Log.Silent {\n\t\tfmt.Println(\"[debug] mode\")\n\t}\n\tr, err := runner.NewEngineWithConfig(cfg, debugMode)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tgo func() {\n\t\t<-sigs\n\t\tr.Stop()\n\t}()\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tlog.Fatalf(\"PANIC: %+v\", e)\n\t\t}\n\t}()\n\n\tr.Run()\n}\n"
  },
  {
    "path": "runner/_testdata/both/.air.toml",
    "content": "#:schema https://json.schemastore.org/any.json\n\nroot = \"both_root\"\n"
  },
  {
    "path": "runner/_testdata/child.sh",
    "content": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\n./_testdata/grandchild.sh background &\n./_testdata/grandchild.sh foreground\necho \"ProcessID=$$ ends ($0)\""
  },
  {
    "path": "runner/_testdata/grandchild.sh",
    "content": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\nsleep 9999\necho \"ProcessID=$$ ends ($0)\""
  },
  {
    "path": "runner/_testdata/invalid_toml/.air.toml",
    "content": "# Config file with duplicate key to trigger parse error\nroot = \".\"\n\n[build]\ndelay = 1000\ndelay = 2000\n"
  },
  {
    "path": "runner/_testdata/run-detached-process.sh",
    "content": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\nsetsid sh -c './_testdata/grandchild.sh detached' >/dev/null 2>&1 &\nDETACHED_PID=$!\necho \"$DETACHED_PID\" >> pid\nsleep 9999\necho \"ProcessID=$$ ends ($0)\"\n"
  },
  {
    "path": "runner/_testdata/run-many-processes.sh",
    "content": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\n./_testdata/child.sh background &\n./_testdata/child.sh foreground\necho \"ProcessID=$$ ends ($0)\""
  },
  {
    "path": "runner/_testdata/toml/.air.toml",
    "content": "#:schema https://json.schemastore.org/any.json\n\nroot = \"toml_root\"\n"
  },
  {
    "path": "runner/_testdata/watching/inner/test.txt",
    "content": ""
  },
  {
    "path": "runner/cmdarg_test.go",
    "content": "package runner\n"
  },
  {
    "path": "runner/common.go",
    "content": "package runner\n\nconst (\n\t//PlatformWindows const for windows\n\tPlatformWindows = \"windows\"\n)\n"
  },
  {
    "path": "runner/config.go",
    "content": "package runner\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"dario.cat/mergo\"\n\t\"github.com/pelletier/go-toml\"\n)\n\nconst (\n\tdftTOML = \".air.toml\"\n\tairWd   = \"air_wd\"\n\n\tdefaultProxyAppStartTimeout = 5000\n\n\tschemaHeader = \"#:schema https://json.schemastore.org/any.json\"\n)\n\n// Config is the main configuration structure for Air.\ntype Config struct {\n\tRoot        string    `toml:\"root\" usage:\"Working directory, . or absolute path, please note that the directories following must be under root\"`\n\tTmpDir      string    `toml:\"tmp_dir\" usage:\"Temporary directory for air\"`\n\tTestDataDir string    `toml:\"testdata_dir\"`\n\tEnvFiles    []string  `toml:\"env_files\" usage:\"Paths to .env files to load before build/run\"`\n\tBuild       cfgBuild  `toml:\"build\"`\n\tColor       cfgColor  `toml:\"color\"`\n\tLog         cfgLog    `toml:\"log\"`\n\tMisc        cfgMisc   `toml:\"misc\"`\n\tScreen      cfgScreen `toml:\"screen\"`\n\tProxy       cfgProxy  `toml:\"proxy\"`\n}\n\ntype entrypoint []string\n\nfunc (e *entrypoint) UnmarshalTOML(v interface{}) error {\n\tswitch val := v.(type) {\n\tcase nil:\n\t\t*e = nil\n\t\treturn nil\n\tcase string:\n\t\t*e = []string{val}\n\t\treturn nil\n\tcase []interface{}:\n\t\tvalues := make([]string, len(val))\n\t\tfor i, raw := range val {\n\t\t\ts, ok := raw.(string)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"entrypoint values must be strings, got %T\", raw)\n\t\t\t}\n\t\t\tvalues[i] = s\n\t\t}\n\t\t*e = values\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"entrypoint must be a string or array of strings, got %T\", v)\n\t}\n}\n\nfunc (e entrypoint) binary() string {\n\tif len(e) == 0 {\n\t\treturn \"\"\n\t}\n\treturn e[0]\n}\n\nfunc (e entrypoint) args() []string {\n\tif len(e) <= 1 {\n\t\treturn nil\n\t}\n\treturn e[1:]\n}\n\ntype cfgBuild struct {\n\tPreCmd                 []string      `toml:\"pre_cmd\" usage:\"Array of commands to run before each build\"`\n\tCmd                    string        `toml:\"cmd\" usage:\"Just plain old shell command. You could use 'make' as well\"`\n\tPostCmd                []string      `toml:\"post_cmd\" usage:\"Array of commands to run after ^C\"`\n\tBin                    string        `toml:\"bin\" usage:\"Binary file yields from 'cmd', will be deprecated soon, recommend using entrypoint.\"`\n\tEntrypoint             entrypoint    `toml:\"entrypoint\" usage:\"Binary file plus optional arguments relative to root, prefer [\\\"./tmp/main\\\", \\\"arg\\\"] form\"`\n\tFullBin                string        `toml:\"full_bin\" usage:\"Customize binary, can setup environment variables when run your app\"`\n\tArgsBin                []string      `toml:\"args_bin\" usage:\"Add additional arguments when running binary (bin/full_bin).\"`\n\tLog                    string        `toml:\"log\" usage:\"This log file is placed in your tmp_dir\"`\n\tIncludeExt             []string      `toml:\"include_ext\" usage:\"Watch these filename extensions\"`\n\tExcludeDir             []string      `toml:\"exclude_dir\" usage:\"Ignore these filename extensions or directories\"`\n\tIncludeDir             []string      `toml:\"include_dir\" usage:\"Watch these directories if you specified\"`\n\tExcludeFile            []string      `toml:\"exclude_file\" usage:\"Exclude files\"`\n\tIncludeFile            []string      `toml:\"include_file\" usage:\"Watch these files\"`\n\tExcludeRegex           []string      `toml:\"exclude_regex\" usage:\"Exclude specific regular expressions\"`\n\tExcludeUnchanged       bool          `toml:\"exclude_unchanged\" usage:\"Exclude unchanged files\"`\n\tIgnoreDangerousRootDir bool          `toml:\"ignore_dangerous_root_dir\" usage:\"Ignore dangerous root directory that could cause excessive file watching\"`\n\tFollowSymlink          bool          `toml:\"follow_symlink\" usage:\"Follow symlink for directories\"`\n\tPoll                   bool          `toml:\"poll\" usage:\"Poll files for changes instead of using fsnotify\"`\n\tPollInterval           int           `toml:\"poll_interval\" usage:\"Poll interval (defaults to the minimum interval of 500ms)\"`\n\tDelay                  int           `toml:\"delay\" usage:\"It's not necessary to trigger build each time file changes if it's too frequent\"`\n\tStopOnError            bool          `toml:\"stop_on_error\" usage:\"Stop running old binary when build errors occur\"`\n\tSendInterrupt          bool          `toml:\"send_interrupt\" usage:\"Send Interrupt signal before killing process (ignored on Windows; uses TASKKILL)\"`\n\tKillDelay              time.Duration `toml:\"kill_delay\" usage:\"Delay after sending Interrupt signal\"`\n\tRerun                  bool          `toml:\"rerun\" usage:\"Rerun binary or not\"`\n\tRerunDelay             int           `toml:\"rerun_delay\" usage:\"Delay after each execution\"`\n\tregexCompiled          []*regexp.Regexp\n\tincludeDirAbs          []string\n\textraIncludeDirs       []string\n}\n\nfunc (c *cfgBuild) RegexCompiled() ([]*regexp.Regexp, error) {\n\treturn c.regexCompiled, nil\n}\n\nfunc (c *cfgBuild) normalizeIncludeDirs(root string) {\n\tc.includeDirAbs = c.includeDirAbs[:0]\n\tc.extraIncludeDirs = c.extraIncludeDirs[:0]\n\tif root == \"\" {\n\t\treturn\n\t}\n\tfor _, dir := range c.IncludeDir {\n\t\tdir = cleanPath(dir)\n\t\tif dir == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdir = filepath.Clean(dir)\n\t\tabs := dir\n\t\tif !filepath.IsAbs(dir) {\n\t\t\tabs = filepath.Join(root, dir)\n\t\t}\n\t\tabs = filepath.Clean(abs)\n\t\tif isSubPath(root, abs) {\n\t\t\tc.includeDirAbs = append(c.includeDirAbs, abs)\n\t\t\tcontinue\n\t\t}\n\t\tc.extraIncludeDirs = append(c.extraIncludeDirs, abs)\n\t}\n}\n\ntype cfgLog struct {\n\tAddTime  bool `toml:\"time\" usage:\"Show log time\"`\n\tMainOnly bool `toml:\"main_only\" usage:\"Only show main log (silences watcher, build, runner)\"`\n\tSilent   bool `toml:\"silent\" usage:\"silence all logs produced by air\"`\n}\n\ntype cfgColor struct {\n\tMain    string `toml:\"main\" usage:\"Customize main part's color. If no color found, use the raw app log\"`\n\tWatcher string `toml:\"watcher\" usage:\"Customize watcher part's color\"`\n\tBuild   string `toml:\"build\" usage:\"Customize build part's color\"`\n\tRunner  string `toml:\"runner\" usage:\"Customize runner part's color\"`\n\tApp     string `toml:\"app\"`\n}\n\ntype cfgMisc struct {\n\tCleanOnExit bool `toml:\"clean_on_exit\" usage:\"Delete tmp directory on exit\"`\n}\n\ntype cfgScreen struct {\n\tClearOnRebuild bool `toml:\"clear_on_rebuild\" usage:\"Clear screen on rebuild\"`\n\tKeepScroll     bool `toml:\"keep_scroll\" usage:\"Keep scroll position after rebuild\"`\n}\n\ntype cfgProxy struct {\n\tEnabled         bool `toml:\"enabled\" usage:\"Enable live-reloading on the browser\"`\n\tProxyPort       int  `toml:\"proxy_port\" usage:\"Port for proxy server\"`\n\tAppPort         int  `toml:\"app_port\" usage:\"Port for your app\"`\n\tAppStartTimeout int  `toml:\"app_start_timeout\" usage:\"Timeout for waiting for app to start in milliseconds (default 5000)\"`\n}\n\ntype sliceTransformer struct{}\n\nfunc (t sliceTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {\n\tif typ.Kind() == reflect.Slice {\n\t\treturn func(dst, src reflect.Value) error {\n\t\t\tif !src.IsZero() {\n\t\t\t\tdst.Set(src)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}\n\n// InitConfig initializes the configuration.\nfunc InitConfig(path string, cmdArgs map[string]TomlInfo) (cfg *Config, err error) {\n\tif path == \"\" {\n\t\tcfg, err = defaultPathConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tcfg, err = readConfigOrDefault(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\twarnDeprecatedBin(cfg)\n\tconfig := defaultConfig()\n\t// get addr\n\tret := &config\n\terr = mergo.Merge(ret, cfg, func(config *mergo.Config) {\n\t\t// mergo.Merge will overwrite the fields if it is Empty\n\t\t// So need use this to avoid that none-zero slice will be overwritten.\n\t\t// https://dario.cat/mergo#transformers\n\t\tconfig.Transformers = sliceTransformer{}\n\t\tconfig.Overwrite = true\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ret.preprocess(cmdArgs)\n\treturn ret, err\n}\n\nfunc writeDefaultConfig() (string, error) {\n\tfstat, err := os.Stat(dftTOML)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"failed to check for existing configuration: %w\", err)\n\t}\n\tif err == nil && fstat != nil {\n\t\treturn \"\", errors.New(\"configuration already exists\")\n\t}\n\n\tfile, err := os.Create(dftTOML)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create a new configuration: %w\", err)\n\t}\n\tdefer file.Close()\n\n\tconfig := defaultConfig()\n\tif len(config.Build.Entrypoint) == 0 && config.Build.Bin != \"\" {\n\t\tconfig.Build.Entrypoint = entrypoint{config.Build.Bin}\n\t}\n\tconfigFile, err := toml.Marshal(config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal the default configuration: %w\", err)\n\t}\n\n\theaders := []byte(schemaHeader + \"\\n\\n\")\n\tcontent := append(headers, configFile...)\n\n\t_, err = file.Write(content)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to write to %s: %w\", dftTOML, err)\n\t}\n\n\treturn dftTOML, nil\n}\n\nfunc defaultPathConfig() (*Config, error) {\n\t// when path is blank, first find `.air.toml` in `air_wd` and current working directory, if not found, use defaults\n\tcfg, err := readConfByName(dftTOML)\n\tif err == nil {\n\t\treturn cfg, nil\n\t}\n\n\t// If the config file exists but failed to parse, report the error\n\t// Only use defaults if no config file exists\n\tif !os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"failed to parse %s: %w\", dftTOML, err)\n\t}\n\n\tdftCfg := defaultConfig()\n\treturn &dftCfg, nil\n}\n\nfunc readConfByName(name string) (*Config, error) {\n\tvar path string\n\tif wd := os.Getenv(airWd); wd != \"\" {\n\t\tpath = filepath.Join(wd, name)\n\t} else {\n\t\twd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpath = filepath.Join(wd, name)\n\t}\n\tcfg, err := readConfig(path)\n\treturn cfg, err\n}\n\nfunc defaultConfig() Config {\n\tbuild := cfgBuild{\n\t\tCmd:          \"go build -o ./tmp/main .\",\n\t\tBin:          \"./tmp/main\",\n\t\tEntrypoint:   entrypoint{},\n\t\tLog:          \"build-errors.log\",\n\t\tIncludeExt:   []string{\"go\", \"tpl\", \"tmpl\", \"html\"},\n\t\tIncludeDir:   []string{},\n\t\tPreCmd:       []string{},\n\t\tPostCmd:      []string{},\n\t\tExcludeFile:  []string{},\n\t\tIncludeFile:  []string{},\n\t\tExcludeDir:   []string{\"assets\", \"tmp\", \"vendor\", \"testdata\"},\n\t\tArgsBin:      []string{},\n\t\tExcludeRegex: []string{\"_test.go\"},\n\t\tDelay:        1000,\n\t\tRerun:        false,\n\t\tRerunDelay:   500,\n\t}\n\tif runtime.GOOS == PlatformWindows {\n\t\tbuild.Bin = `tmp\\main.exe`\n\t\tbuild.Cmd = \"go build -o ./tmp/main.exe .\"\n\t}\n\tlog := cfgLog{\n\t\tAddTime:  false,\n\t\tMainOnly: false,\n\t\tSilent:   false,\n\t}\n\tcolor := cfgColor{\n\t\tMain:    \"magenta\",\n\t\tWatcher: \"cyan\",\n\t\tBuild:   \"yellow\",\n\t\tRunner:  \"green\",\n\t}\n\tmisc := cfgMisc{\n\t\tCleanOnExit: false,\n\t}\n\treturn Config{\n\t\tRoot:        \".\",\n\t\tTmpDir:      \"tmp\",\n\t\tTestDataDir: \"testdata\",\n\t\tEnvFiles:    []string{},\n\t\tBuild:       build,\n\t\tColor:       color,\n\t\tLog:         log,\n\t\tMisc:        misc,\n\t\tScreen: cfgScreen{\n\t\t\tClearOnRebuild: false,\n\t\t\tKeepScroll:     true,\n\t\t},\n\t}\n}\n\nfunc readConfig(path string) (*Config, error) {\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := new(Config)\n\tif err = toml.Unmarshal(data, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}\n\nfunc readConfigOrDefault(path string) (*Config, error) {\n\tdftCfg := defaultConfig()\n\tcfg, err := readConfig(path)\n\tif err != nil {\n\t\treturn &dftCfg, err\n\t}\n\n\treturn cfg, nil\n}\n\nfunc (c *Config) preprocess(args map[string]TomlInfo) error {\n\tvar err error\n\n\tif args != nil {\n\t\tc.withArgs(args)\n\t}\n\tcwd := os.Getenv(airWd)\n\tif cwd != \"\" {\n\t\tif err = os.Chdir(cwd); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Root = cwd\n\t}\n\tc.Root, err = expandPath(c.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check for dangerous root directories that could cause excessive file watching\n\tif isDangerous, dirName := isDangerousRoot(c.Root); isDangerous {\n\t\tif !c.Build.IgnoreDangerousRootDir {\n\t\t\treturn fmt.Errorf(\"refusing to run in %s - this would watch too many files. Please run air in a project directory\", dirName)\n\t\t}\n\t\tfmt.Fprintln(os.Stdout, \"[warning] ignoring root directory protections. This could cause excessive file watching. It is recommended to run air in a project directory\")\n\t}\n\n\tif c.TmpDir == \"\" {\n\t\tc.TmpDir = \"tmp\"\n\t}\n\tif c.TestDataDir == \"\" {\n\t\tc.TestDataDir = \"testdata\"\n\t}\n\ted := c.Build.ExcludeDir\n\tfor i := range ed {\n\t\ted[i] = cleanPath(ed[i])\n\t}\n\n\tif len(c.Build.Entrypoint) > 0 {\n\t\tentry := c.Build.Entrypoint.binary()\n\t\tif !filepath.IsAbs(entry) {\n\t\t\tif resolved := resolveCommandPath(entry); resolved != \"\" {\n\t\t\t\tentry = resolved\n\t\t\t} else {\n\t\t\t\tentry = joinPath(c.Root, entry)\n\t\t\t}\n\t\t}\n\n\t\tentry, err = filepath.Abs(entry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Build.Entrypoint[0] = entry\n\t}\n\n\tadaptToVariousPlatforms(c)\n\tc.Build.normalizeIncludeDirs(c.Root)\n\n\t// Join runtime arguments with the configuration arguments\n\truntimeArgs := flag.Args()\n\tc.Build.ArgsBin = append(c.Build.ArgsBin, runtimeArgs...)\n\n\t// Compile the exclude regexes if there are any patterns in the config file\n\tif len(c.Build.ExcludeRegex) > 0 {\n\t\tregexCompiled := make([]*regexp.Regexp, len(c.Build.ExcludeRegex))\n\t\tfor idx, expr := range c.Build.ExcludeRegex {\n\t\t\tre, err := regexp.Compile(expr)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to compile regex %s\", expr)\n\t\t\t}\n\t\t\tregexCompiled[idx] = re\n\t\t}\n\t\tc.Build.regexCompiled = regexCompiled\n\t}\n\n\tc.Build.ExcludeDir = ed\n\tif len(c.Build.FullBin) > 0 {\n\t\tc.Build.Bin = c.Build.FullBin\n\t\treturn err\n\t}\n\t// Fix windows CMD processor\n\t// CMD will not recognize relative path like ./tmp/server\n\tc.Build.Bin, err = filepath.Abs(c.Build.Bin)\n\n\treturn err\n}\n\nfunc (c *Config) colorInfo() map[string]string {\n\treturn map[string]string{\n\t\t\"main\":    c.Color.Main,\n\t\t\"build\":   c.Color.Build,\n\t\t\"runner\":  c.Color.Runner,\n\t\t\"watcher\": c.Color.Watcher,\n\t}\n}\n\nfunc (c *Config) buildLogPath() string {\n\treturn joinPath(c.tmpPath(), c.Build.Log)\n}\n\nfunc (c *Config) buildDelay() time.Duration {\n\treturn time.Duration(c.Build.Delay) * time.Millisecond\n}\n\nfunc (c *Config) rerunDelay() time.Duration {\n\treturn time.Duration(c.Build.RerunDelay) * time.Millisecond\n}\n\nfunc (c *Config) killDelay() time.Duration {\n\t// kill_delay can be specified as an integer or duration string\n\t// interpret as milliseconds if less than the value of 1 millisecond\n\tif c.Build.KillDelay < time.Millisecond {\n\t\treturn c.Build.KillDelay * time.Millisecond\n\t}\n\t// normalize kill delay to milliseconds\n\treturn time.Duration(c.Build.KillDelay.Milliseconds()) * time.Millisecond\n}\n\nfunc (c *Config) binPath() string {\n\tif len(c.Build.Entrypoint) > 0 {\n\t\treturn c.Build.Entrypoint.binary()\n\t}\n\treturn joinPath(c.Root, c.Build.Bin)\n}\n\nfunc (c *Config) runnerBin() string {\n\tif len(c.Build.Entrypoint) > 0 && len(c.Build.FullBin) == 0 {\n\t\treturn c.Build.Entrypoint.binary()\n\t}\n\treturn c.Build.Bin\n}\n\nfunc (c *Config) tmpPath() string {\n\treturn joinPath(c.Root, c.TmpDir)\n}\n\nfunc (c *Config) testDataPath() string {\n\treturn joinPath(c.Root, c.TestDataDir)\n}\n\nfunc (c *Config) rel(path string) string {\n\ts, err := filepath.Rel(c.Root, path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc resolveCommandPath(entry string) string {\n\tif entry == \"\" || strings.ContainsAny(entry, `/\\`) {\n\t\treturn \"\"\n\t}\n\n\tpath, err := exec.LookPath(entry)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn path\n}\n\n// withArgs returns a new config with the given arguments added to the configuration.\nfunc (c *Config) withArgs(args map[string]TomlInfo) {\n\tfor _, value := range args {\n\t\t// Ignore values that match the default configuration.\n\t\t// This ensures user-specified configurations are not overwritten by default values.\n\t\tif value.Value != nil && *value.Value != value.fieldValue {\n\t\t\tv := reflect.ValueOf(c)\n\t\t\tsetValue2Struct(v, value.fieldPath, *value.Value)\n\t\t}\n\t}\n\n}\n\nfunc warnDeprecatedBin(cfg *Config) {\n\tif cfg == nil {\n\t\treturn\n\t}\n\tif cfg.Build.Bin == \"\" || len(cfg.Build.Entrypoint) > 0 {\n\t\treturn\n\t}\n\tfmt.Fprintln(os.Stdout, \"[warning] build.bin is deprecated; set build.entrypoint instead\")\n}\n"
  },
  {
    "path": "runner/config_test.go",
    "content": "package runner\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tbin = `./tmp/main`\n\tcmd = \"go build -o ./tmp/main .\"\n)\n\nfunc getWindowsConfig() Config {\n\tbuild := cfgBuild{\n\t\tPreCmd:       []string{\"echo Hello Air\"},\n\t\tCmd:          \"go build -o ./tmp/main .\",\n\t\tBin:          \"./tmp/main\",\n\t\tLog:          \"build-errors.log\",\n\t\tIncludeExt:   []string{\"go\", \"tpl\", \"tmpl\", \"html\"},\n\t\tExcludeDir:   []string{\"assets\", \"tmp\", \"vendor\", \"testdata\"},\n\t\tExcludeRegex: []string{\"_test.go\"},\n\t\tDelay:        1000,\n\t\tStopOnError:  true,\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tbuild.Bin = bin\n\t\tbuild.Cmd = cmd\n\t}\n\n\treturn Config{\n\t\tRoot:        \".\",\n\t\tTmpDir:      \"tmp\",\n\t\tTestDataDir: \"testdata\",\n\t\tBuild:       build,\n\t}\n}\n\nfunc TestBinCmdPath(t *testing.T) {\n\tt.Parallel()\n\tvar err error\n\n\tc := getWindowsConfig()\n\terr = c.preprocess(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\tif strings.HasSuffix(c.Build.Bin, \"exe\") {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif strings.Contains(c.Build.Bin, \"exe\") {\n\t\t\tt.Fail()\n\t\t}\n\t} else {\n\n\t\tif strings.HasSuffix(c.Build.Bin, \"exe\") {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif strings.Contains(c.Build.Bin, \"exe\") {\n\t\t\tt.Fail()\n\t\t}\n\t}\n}\n\nfunc TestDefaultPathConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tpath string\n\t\troot string\n\t}{{\n\t\tname: \"Invalid Path\",\n\t\tpath: \"invalid/path\",\n\t\troot: \".\",\n\t}, {\n\t\tname: \"TOML\",\n\t\tpath: \"_testdata/toml\",\n\t\troot: \"toml_root\",\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Setenv(airWd, tt.path)\n\t\t\tc, err := defaultPathConfig()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t\t\t}\n\n\t\t\tif got, want := c.Root, tt.root; got != want {\n\t\t\t\tt.Fatalf(\"Root is %s, but want %s.\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReadConfByName(t *testing.T) {\n\t_ = os.Unsetenv(airWd)\n\tconfig, _ := readConfByName(dftTOML)\n\tif config != nil {\n\t\tt.Fatalf(\"expect Config is nil,but get a not nil Config\")\n\t}\n}\n\nfunc TestDefaultPathConfigWithInvalidTOML(t *testing.T) {\n\t// Test that defaultPathConfig returns an error when .air.toml exists but has parse errors\n\t// This is a regression test for issue #678\n\tt.Setenv(airWd, \"_testdata/invalid_toml\")\n\t_, err := defaultPathConfig()\n\tif err == nil {\n\t\tt.Fatal(\"expected error when .air.toml has parse errors, but got nil\")\n\t}\n\tif !strings.Contains(err.Error(), \"failed to parse\") {\n\t\tt.Fatalf(\"expected error message to contain 'failed to parse', got: %s\", err.Error())\n\t}\n\tif !strings.Contains(err.Error(), \"defined twice\") {\n\t\tt.Fatalf(\"expected error message to contain 'defined twice', got: %s\", err.Error())\n\t}\n}\n\nfunc TestConfPreprocess(t *testing.T) {\n\tt.Setenv(airWd, \"_testdata/toml\")\n\toriginalDir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to getwd: %v\", err)\n\t}\n\tt.Cleanup(func() {\n\t\tif err := os.Chdir(originalDir); err != nil {\n\t\t\tt.Fatalf(\"failed to restore working directory: %v\", err)\n\t\t}\n\t})\n\n\tdf := defaultConfig()\n\terr = df.preprocess(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"preprocess error %v\", err)\n\t}\n\tsuffix := filepath.Join(\"_testdata\", \"toml\", \"tmp\", \"main\")\n\tif runtime.GOOS == \"windows\" {\n\t\tsuffix += \".exe\"\n\t}\n\tbinPath := df.Build.Bin\n\tif !strings.HasSuffix(binPath, suffix) {\n\t\tt.Fatalf(\"bin path is %s, but not have suffix  %s.\", binPath, suffix)\n\t}\n}\n\nfunc TestEntrypointResolvesAbsolutePath(t *testing.T) {\n\tt.Parallel()\n\tbase := t.TempDir()\n\trootWithSpace := filepath.Join(base, \"with space\")\n\tif err := os.MkdirAll(filepath.Join(rootWithSpace, \"tmp\"), 0o755); err != nil {\n\t\tt.Fatalf(\"failed to prepare tmp dir: %v\", err)\n\t}\n\n\tcfg := defaultConfig()\n\tcfg.Root = rootWithSpace\n\tcfg.Build.Entrypoint = entrypoint{\"./tmp/main\"}\n\n\tif err := cfg.preprocess(nil); err != nil {\n\t\tt.Fatalf(\"preprocess error %v\", err)\n\t}\n\n\twant := filepath.Join(rootWithSpace, \"tmp\", \"main\")\n\tif got := cfg.Build.Entrypoint.binary(); got != want {\n\t\tt.Fatalf(\"entrypoint is %s, but want %s\", got, want)\n\t}\n\n\tif cfg.binPath() != want {\n\t\tt.Fatalf(\"bin path is %s, but want %s\", cfg.binPath(), want)\n\t}\n}\n\nfunc TestEntrypointResolvesFromPath(t *testing.T) {\n\troot := t.TempDir()\n\tpathDir := t.TempDir()\n\n\tbinName := \"air-entrypoint-path\"\n\tfileName := binName\n\tfileContents := \"#!/bin/sh\\nexit 0\\n\"\n\tif runtime.GOOS == \"windows\" {\n\t\tfileName += \".bat\"\n\t\tfileContents = \"@echo off\\r\\n\"\n\t\tt.Setenv(\"PATHEXT\", \".BAT;.EXE\")\n\t}\n\tfullPath := filepath.Join(pathDir, fileName)\n\tif err := os.WriteFile(fullPath, []byte(fileContents), 0o755); err != nil {\n\t\tt.Fatalf(\"failed to write fake binary: %v\", err)\n\t}\n\tif runtime.GOOS != \"windows\" {\n\t\tif err := os.Chmod(fullPath, 0o755); err != nil {\n\t\t\tt.Fatalf(\"failed to make fake binary executable: %v\", err)\n\t\t}\n\t}\n\n\tt.Setenv(\"PATH\", pathDir+string(os.PathListSeparator)+os.Getenv(\"PATH\"))\n\n\tcfg := defaultConfig()\n\tcfg.Root = root\n\tcfg.Build.Entrypoint = entrypoint{binName}\n\n\tif err := cfg.preprocess(nil); err != nil {\n\t\tt.Fatalf(\"preprocess error %v\", err)\n\t}\n\n\twant := fullPath\n\tif got := cfg.Build.Entrypoint.binary(); got != want {\n\t\tt.Fatalf(\"entrypoint resolved to %s, want %s\", got, want)\n\t}\n}\n\nfunc TestEntrypointPreservesArgs(t *testing.T) {\n\tt.Parallel()\n\troot := t.TempDir()\n\tcfg := defaultConfig()\n\tcfg.Root = root\n\tcfg.Build.Entrypoint = entrypoint{\"./tmp/main\", \"server\", \":8080\"}\n\n\tif err := cfg.preprocess(nil); err != nil {\n\t\tt.Fatalf(\"preprocess error %v\", err)\n\t}\n\n\twantBin := filepath.Join(root, \"tmp\", \"main\")\n\tif cfg.Build.Entrypoint.binary() != wantBin {\n\t\tt.Fatalf(\"entrypoint binary is %s, want %s\", cfg.Build.Entrypoint.binary(), wantBin)\n\t}\n\n\twantArgs := []string{\"server\", \":8080\"}\n\tif got := cfg.Build.Entrypoint.args(); !reflect.DeepEqual(got, wantArgs) {\n\t\tt.Fatalf(\"entrypoint args mismatch, got %v want %v\", got, wantArgs)\n\t}\n}\n\nfunc TestConfigWithRuntimeArgs(t *testing.T) {\n\truntimeArg := \"-flag=value\"\n\n\t// inject runtime arg\n\toldArgs := os.Args\n\tdefer func() {\n\t\tos.Args = oldArgs\n\t\tflag.Parse()\n\t}()\n\tos.Args = []string{\"air\", \"--\", runtimeArg}\n\tflag.Parse()\n\n\tt.Run(\"when using bin\", func(t *testing.T) {\n\t\tdf := defaultConfig()\n\t\tif err := df.preprocess(nil); err != nil {\n\t\t\tt.Fatalf(\"preprocess error %v\", err)\n\t\t}\n\n\t\tif !contains(df.Build.ArgsBin, runtimeArg) {\n\t\t\tt.Fatalf(\"missing expected runtime arg: %s\", runtimeArg)\n\t\t}\n\t})\n\n\tt.Run(\"when using full_bin\", func(t *testing.T) {\n\t\tdf := defaultConfig()\n\t\tdf.Build.FullBin = \"./tmp/main\"\n\t\tif err := df.preprocess(nil); err != nil {\n\t\t\tt.Fatalf(\"preprocess error %v\", err)\n\t\t}\n\n\t\tif !contains(df.Build.ArgsBin, runtimeArg) {\n\t\t\tt.Fatalf(\"missing expected runtime arg: %s\", runtimeArg)\n\t\t}\n\t})\n}\n\nfunc TestReadConfigWithWrongPath(t *testing.T) {\n\tt.Parallel()\n\tc, err := readConfig(\"xxxx\")\n\tif err == nil {\n\t\tt.Fatal(\"need throw a error\")\n\t}\n\tif c != nil {\n\t\tt.Fatal(\"expect is nil but got a conf\")\n\t}\n}\n\nfunc TestKillDelay(t *testing.T) {\n\tt.Parallel()\n\tconfig := Config{\n\t\tBuild: cfgBuild{\n\t\t\tKillDelay: 1000,\n\t\t},\n\t}\n\tif config.killDelay() != (1000 * time.Millisecond) {\n\t\tt.Fatal(\"expect KillDelay 1000 to be interpreted as 1000 milliseconds, got \", config.killDelay())\n\t}\n\tconfig.Build.KillDelay = 1\n\tif config.killDelay() != (1 * time.Millisecond) {\n\t\tt.Fatal(\"expect KillDelay 1 to be interpreted as 1 millisecond, got \", config.killDelay())\n\t}\n\tconfig.Build.KillDelay = 1_000_000\n\tif config.killDelay() != (1 * time.Millisecond) {\n\t\tt.Fatal(\"expect KillDelay 1_000_000 to be interpreted as 1 millisecond, got \", config.killDelay())\n\t}\n\tconfig.Build.KillDelay = 100_000_000\n\tif config.killDelay() != (100 * time.Millisecond) {\n\t\tt.Fatal(\"expect KillDelay 100_000_000 to be interpreted as 100 milliseconds, got \", config.killDelay())\n\t}\n\tconfig.Build.KillDelay = 0\n\tif config.killDelay() != 0 {\n\t\tt.Fatal(\"expect KillDelay 0 to be interpreted as 0, got \", config.killDelay())\n\t}\n}\n\nfunc contains(sl []string, target string) bool {\n\tfor _, c := range sl {\n\t\tif c == target {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TestWarnDeprecatedBin(t *testing.T) {\n\tt.Parallel()\n\ttmpDir := t.TempDir()\n\tcfgPath := filepath.Join(tmpDir, \".air.toml\")\n\tcfgContent := `\n[build]\nbin = \"./tmp/main\"\ncmd = \"go build -o ./tmp/main .\"\n`\n\tif err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {\n\t\tt.Fatalf(\"failed to write config: %v\", err)\n\t}\n\n\toldStdout := os.Stdout\n\tr, w, err := os.Pipe()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create pipe: %v\", err)\n\t}\n\tos.Stdout = w\n\n\t_, _ = InitConfig(cfgPath, nil)\n\n\tif err := w.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close writer: %v\", err)\n\t}\n\tos.Stdout = oldStdout\n\n\tout, err := io.ReadAll(r)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to read output: %v\", err)\n\t}\n\toutput := string(out)\n\tif !strings.Contains(output, \"build.bin is deprecated\") {\n\t\tt.Fatalf(\"missing bin deprecation warning in output: %q\", output)\n\t}\n}\n\nfunc TestWarnIgnoreDangerousRootDirProtection(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"root dir protection uses Unix root path\")\n\t}\n\n\ttmpDir := t.TempDir()\n\tt.Setenv(\"HOME\", tmpDir)\n\tt.Run(\"when ignore_dangerous_root_dir is true\", func(t *testing.T) {\n\t\tcfgPath := filepath.Join(tmpDir, \".air.toml\")\n\t\tcfgContent := `\nroot = \"/\"\n\n[build]\nentrypoint = \"tmp/main\"\ncmd = \"go build -o ./tmp/main .\"\nignore_dangerous_root_dir = true\n`\n\t\tif err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {\n\t\t\tt.Fatalf(\"failed to write config: %v\", err)\n\t\t}\n\n\t\toldStdout := os.Stdout\n\t\tr, w, err := os.Pipe()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to create pipe: %v\", err)\n\t\t}\n\t\tos.Stdout = w\n\n\t\t_, _ = InitConfig(cfgPath, nil)\n\n\t\tif err := w.Close(); err != nil {\n\t\t\tt.Fatalf(\"failed to close writer: %v\", err)\n\t\t}\n\t\tos.Stdout = oldStdout\n\n\t\tout, err := io.ReadAll(r)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to read output: %v\", err)\n\t\t}\n\t\toutput := string(out)\n\t\tif !strings.Contains(output, \"ignoring root directory protections. This could cause excessive file watching. It is recommended to run air in a project directory\") {\n\t\t\tt.Fatalf(\"missing root directory protection warning in output: %q\", output)\n\t\t}\n\t})\n\tt.Run(\"when ignore_dangerous_root_dir is false\", func(t *testing.T) {\n\t\tcfgPath := filepath.Join(tmpDir, \".air.toml\")\n\t\tcfgContent := `\nroot = \"/\"\n\n[build]\nentrypoint = \"tmp/main\"\ncmd = \"go build -o ./tmp/main .\"\nignore_dangerous_root_dir = false\n`\n\t\tif err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {\n\t\t\tt.Fatalf(\"failed to write config: %v\", err)\n\t\t}\n\n\t\toldStdout := os.Stdout\n\t\tr, w, err := os.Pipe()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to create pipe: %v\", err)\n\t\t}\n\t\tos.Stdout = w\n\n\t\t_, _ = InitConfig(cfgPath, nil)\n\n\t\tif err := w.Close(); err != nil {\n\t\t\tt.Fatalf(\"failed to close writer: %v\", err)\n\t\t}\n\t\tos.Stdout = oldStdout\n\n\t\tout, err := io.ReadAll(r)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to read output: %v\", err)\n\t\t}\n\t\toutput := string(out)\n\t\tif strings.Contains(output, \"ignoring root directory protections\") {\n\t\t\tt.Fatalf(\"unexpected root directory protection warning in output: %q\", output)\n\t\t}\n\t})\n\n\tt.Run(\"when ignore_dangerous_root_dir is not set\", func(t *testing.T) {\n\t\tcfgPath := filepath.Join(tmpDir, \".air.toml\")\n\t\tcfgContent := `\nroot = \"/\"\n\n[build]\nentrypoint = \"tmp/main\"\ncmd = \"go build -o ./tmp/main .\"\n`\n\t\tif err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {\n\t\t\tt.Fatalf(\"failed to write config: %v\", err)\n\t\t}\n\n\t\toldStdout := os.Stdout\n\t\tr, w, err := os.Pipe()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to create pipe: %v\", err)\n\t\t}\n\t\tos.Stdout = w\n\n\t\t_, _ = InitConfig(cfgPath, nil)\n\n\t\tif err := w.Close(); err != nil {\n\t\t\tt.Fatalf(\"failed to close writer: %v\", err)\n\t\t}\n\t\tos.Stdout = oldStdout\n\n\t\tout, err := io.ReadAll(r)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to read output: %v\", err)\n\t\t}\n\t\toutput := string(out)\n\t\tif strings.Contains(output, \"ignoring root directory protections\") {\n\t\t\tt.Fatalf(\"unexpected root directory protection warning in output: %q\", output)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "runner/engine.go",
    "content": "package runner\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/gohugoio/hugo/watcher/filenotify\"\n\t\"github.com/joho/godotenv\"\n)\n\n// Engine ...\ntype Engine struct {\n\tconfig *Config\n\n\texiter    exiter\n\tproxy     *Proxy\n\tlogger    *logger\n\twatcher   filenotify.FileWatcher\n\tdebugMode bool\n\trunArgs   []string\n\trunning   atomic.Bool\n\n\teventCh       chan string\n\twatcherStopCh chan bool\n\t// buildRunCh serves dual purpose:\n\t// 1. As a semaphore ensuring only one build runs at a time (buffer size 1)\n\t// 2. Carries each build's unique stop channel for cancellation\n\t// When a new build starts, it retrieves the previous build's stop channel,\n\t// closes it to signal cancellation, then inserts its own fresh channel.\n\t// This prevents the race condition where a new build could consume a stop\n\t// signal meant for a previous build (issue #784).\n\tbuildRunCh chan chan struct{}\n\t// binStopCh is a channel for process termination control\n\t// Type chan<- chan int indicates it's a send-only channel that transmits another channel(chan int)\n\tbinStopCh chan<- chan int\n\texitCh    chan bool\n\n\tmu            sync.RWMutex\n\twatchers      uint\n\tfileChecksums *checksumMap\n\n\tll sync.Mutex // lock for logger\n\n\t// globalEnv stores the original env values before air modified them\n\t// key:original value (empty string means it was unset)\n\tglobalEnv map[string]*string\n\t// loadedEnv tracks env values that were set by the last env file load\n\tloadedEnv map[string]string\n}\n\n// NewEngineWithConfig ...\nfunc NewEngineWithConfig(cfg *Config, debugMode bool) (*Engine, error) {\n\tlogger := newLogger(cfg)\n\twatcher, err := newWatcher(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar entryArgs []string\n\tif len(cfg.Build.FullBin) == 0 {\n\t\tentryArgs = cfg.Build.Entrypoint.args()\n\t}\n\trunArgs := make([]string, 0, len(entryArgs)+len(cfg.Build.ArgsBin))\n\tif len(entryArgs) > 0 {\n\t\trunArgs = append(runArgs, entryArgs...)\n\t}\n\trunArgs = append(runArgs, cfg.Build.ArgsBin...)\n\te := Engine{\n\t\tconfig:        cfg,\n\t\texiter:        defaultExiter{},\n\t\tproxy:         NewProxy(&cfg.Proxy),\n\t\tlogger:        logger,\n\t\twatcher:       watcher,\n\t\tdebugMode:     debugMode,\n\t\trunArgs:       runArgs,\n\t\teventCh:       make(chan string, 1000),\n\t\twatcherStopCh: make(chan bool, 10),\n\t\tbuildRunCh:    make(chan chan struct{}, 1),\n\t\texitCh:        make(chan bool),\n\t\tfileChecksums: &checksumMap{m: make(map[string]string)},\n\t\twatchers:      0,\n\t\tglobalEnv:     map[string]*string{},\n\t}\n\n\treturn &e, nil\n}\n\n// NewEngine ...\nfunc NewEngine(cfgPath string, args map[string]TomlInfo, debugMode bool) (*Engine, error) {\n\tvar err error\n\tcfg, err := InitConfig(cfgPath, args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewEngineWithConfig(cfg, debugMode)\n}\n\n// Run run run\nfunc (e *Engine) Run() {\n\tif len(os.Args) > 1 && os.Args[1] == \"init\" {\n\t\tconfigName, err := writeDefaultConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed writing default config: %+v\", err)\n\t\t}\n\t\tfmt.Printf(\"%s file created to the current directory with the default settings\\n\", configName)\n\t\treturn\n\t}\n\n\te.mainDebug(\"CWD: %s\", e.config.Root)\n\n\tvar err error\n\tif err = e.checkRunEnv(); err != nil {\n\t\tos.Exit(1)\n\t}\n\tif err = e.watchConfiguredDirs(); err != nil {\n\t\tos.Exit(1)\n\t}\n\n\te.start()\n\te.cleanup()\n}\n\nfunc (e *Engine) checkRunEnv() error {\n\tp := e.config.tmpPath()\n\tif _, err := os.Stat(p); os.IsNotExist(err) {\n\t\te.runnerLog(\"mkdir %s\", p)\n\t\tif err := os.MkdirAll(p, 0o755); err != nil {\n\t\t\te.runnerLog(\"failed to mkdir, error: %s\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Engine) watchConfiguredDirs() error {\n\ttype watchTarget struct {\n\t\tpath     string\n\t\toptional bool\n\t}\n\ttargets := []watchTarget{{path: e.config.Root, optional: false}}\n\tfor _, dir := range e.config.Build.extraIncludeDirs {\n\t\ttargets = append(targets, watchTarget{path: dir, optional: true})\n\t}\n\n\tseen := make(map[string]struct{}, len(targets))\n\tfor _, target := range targets {\n\t\tif target.path == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned := filepath.Clean(target.path)\n\t\tif _, ok := seen[cleaned]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := os.Stat(cleaned); err != nil {\n\t\t\tif os.IsNotExist(err) && target.optional {\n\t\t\t\te.watcherLog(\"include_dir %s does not exist, skipping\", e.config.rel(cleaned))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err := e.watching(cleaned); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tseen[cleaned] = struct{}{}\n\t}\n\treturn nil\n}\n\nfunc (e *Engine) watching(root string) error {\n\treturn filepath.Walk(root, func(path string, info os.FileInfo, _ error) error {\n\t\t// NOTE: path is absolute\n\t\tif info != nil && !info.IsDir() {\n\t\t\tif e.checkIncludeFile(path) {\n\t\t\t\treturn e.watchPath(path)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\t// exclude tmp dir\n\t\tif e.isTmpDir(path) {\n\t\t\te.watcherLog(\"!exclude %s\", e.config.rel(path))\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\t// exclude testdata dir\n\t\tif e.isTestDataDir(path) {\n\t\t\te.watcherLog(\"!exclude %s\", e.config.rel(path))\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\t// exclude hidden directories like .git, .idea, etc.\n\t\tif isHiddenDirectory(path) {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\t// exclude user specified directories\n\t\tif e.isExcludeDir(path) {\n\t\t\te.watcherLog(\"!exclude %s\", e.config.rel(path))\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tisIn, walkDir := e.checkIncludeDir(path)\n\t\tif !walkDir {\n\t\t\te.watcherLog(\"!exclude %s\", e.config.rel(path))\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tif isIn {\n\t\t\treturn e.watchPath(path)\n\t\t}\n\t\treturn nil\n\t})\n}\n\n// cacheFileChecksums calculates and stores checksums for each non-excluded file it finds from root.\nfunc (e *Engine) cacheFileChecksums(root string) error {\n\treturn filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tif info == nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tif !info.Mode().IsRegular() {\n\t\t\tif e.isTmpDir(path) || e.isTestDataDir(path) || isHiddenDirectory(path) || e.isExcludeDir(path) {\n\t\t\t\te.watcherDebug(\"!exclude checksum %s\", e.config.rel(path))\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\t// Follow symbolic link\n\t\t\tif e.config.Build.FollowSymlink && (info.Mode()&os.ModeSymlink) > 0 {\n\t\t\t\tlink, err := filepath.EvalSymlinks(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlinkInfo, err := os.Stat(link)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif linkInfo.IsDir() {\n\t\t\t\t\terr = e.watchPath(link)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif e.isExcludeFile(path) || !e.isIncludeExt(path) && !e.checkIncludeFile(path) {\n\t\t\te.watcherDebug(\"!exclude checksum %s\", e.config.rel(path))\n\t\t\treturn nil\n\t\t}\n\n\t\texcludeRegex, err := e.isExcludeRegex(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif excludeRegex {\n\t\t\te.watcherDebug(\"!exclude checksum %s\", e.config.rel(path))\n\t\t\treturn nil\n\t\t}\n\n\t\t// update the checksum cache for the current file\n\t\t_ = e.isModified(path)\n\n\t\treturn nil\n\t})\n}\n\nfunc (e *Engine) watchPath(path string) error {\n\tif err := e.watcher.Add(path); err != nil {\n\t\te.watcherLog(\"failed to watch %s, error: %s\", path, err.Error())\n\t\treturn err\n\t}\n\te.watcherLog(\"watching %s\", e.config.rel(path))\n\n\tgo func() {\n\t\te.withLock(func() {\n\t\t\te.watchers++\n\t\t})\n\t\tdefer func() {\n\t\t\te.withLock(func() {\n\t\t\t\te.watchers--\n\t\t\t})\n\t\t}()\n\n\t\tif e.config.Build.ExcludeUnchanged {\n\t\t\terr := e.cacheFileChecksums(path)\n\t\t\tif err != nil {\n\t\t\t\te.watcherLog(\"error building checksum cache: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-e.watcherStopCh:\n\t\t\t\treturn\n\t\t\tcase ev := <-e.watcher.Events():\n\t\t\t\te.mainDebug(\"event: %+v\", ev)\n\t\t\t\tif !validEvent(ev) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif isDir(ev.Name) {\n\t\t\t\t\te.watchNewDir(ev.Name, removeEvent(ev))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif e.isExcludeFile(ev.Name) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\texcludeRegex, _ := e.isExcludeRegex(ev.Name)\n\t\t\t\tif excludeRegex {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !e.isIncludeExt(ev.Name) && !e.checkIncludeFile(ev.Name) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te.watcherDebug(\"%s has changed\", e.config.rel(ev.Name))\n\t\t\t\te.eventCh <- ev.Name\n\t\t\tcase err := <-e.watcher.Errors():\n\t\t\t\te.watcherLog(\"error: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}\n\nfunc (e *Engine) watchNewDir(dir string, removeDir bool) {\n\tif e.isTmpDir(dir) {\n\t\treturn\n\t}\n\tif e.isTestDataDir(dir) {\n\t\treturn\n\t}\n\tif isHiddenDirectory(dir) || e.isExcludeDir(dir) {\n\t\te.watcherLog(\"!exclude %s\", e.config.rel(dir))\n\t\treturn\n\t}\n\tif removeDir {\n\t\tif err := e.watcher.Remove(dir); err != nil {\n\t\t\te.watcherLog(\"failed to stop watching %s, error: %s\", dir, err.Error())\n\t\t}\n\t\treturn\n\t}\n\tgo func(dir string) {\n\t\tif err := e.watching(dir); err != nil {\n\t\t\te.watcherLog(\"failed to watching %s, error: %s\", dir, err.Error())\n\t\t}\n\t}(dir)\n}\n\nfunc (e *Engine) isModified(filename string) bool {\n\tnewChecksum, err := fileChecksum(filename)\n\tif err != nil {\n\t\te.watcherDebug(\"can't determine if file was changed: %v - assuming it did without updating cache\", err)\n\t\treturn true\n\t}\n\n\tif e.fileChecksums.updateFileChecksum(filename, newChecksum) {\n\t\te.watcherDebug(\"stored checksum for %s: %s\", e.config.rel(filename), newChecksum)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// Endless loop and never return\nfunc (e *Engine) start() {\n\tif e.config.Proxy.Enabled {\n\t\tgo e.proxy.Run()\n\t\te.mainLog(\"Proxy server listening on http://localhost%s\", e.proxy.server.Addr)\n\t}\n\n\te.running.Store(true)\n\tfirstRunCh := make(chan bool, 1)\n\tfirstRunCh <- true\n\n\tfor {\n\t\tvar filename string\n\n\t\tselect {\n\t\tcase <-e.exitCh:\n\t\t\te.mainDebug(\"exit in start\")\n\t\t\treturn\n\t\tcase filename = <-e.eventCh:\n\t\t\tif !e.isIncludeExt(filename) && !e.checkIncludeFile(filename) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif e.config.Build.ExcludeUnchanged {\n\t\t\t\tif !e.isModified(filename) {\n\t\t\t\t\te.mainLog(\"skipping %s because contents unchanged\", e.config.rel(filename))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// cannot set buildDelay to 0, because when the write multiple events received in short time\n\t\t\t// it will start Multiple buildRuns: https://github.com/air-verse/air/issues/473\n\t\t\ttime.Sleep(e.config.buildDelay())\n\t\t\te.flushEvents()\n\n\t\t\tif e.config.Screen.ClearOnRebuild {\n\t\t\t\tif e.config.Screen.KeepScroll {\n\t\t\t\t\t// https://stackoverflow.com/questions/22891644/how-can-i-clear-the-terminal-screen-in-go\n\t\t\t\t\tfmt.Print(\"\\033[2J\")\n\t\t\t\t} else {\n\t\t\t\t\t// https://stackoverflow.com/questions/5367068/clear-a-terminal-screen-for-real/5367075#5367075\n\t\t\t\t\tfmt.Print(\"\\033c\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.mainLog(\"%s has changed\", e.config.rel(filename))\n\t\tcase <-firstRunCh:\n\t\t\t// go down\n\t\t}\n\n\t\t// Stop any currently running build by closing its stop channel\n\t\tselect {\n\t\tcase oldStopCh := <-e.buildRunCh:\n\t\t\t// Close the old build's stop channel to signal it to stop\n\t\t\tclose(oldStopCh)\n\t\tdefault:\n\t\t\t// No build is currently running\n\t\t}\n\n\t\t// if current app is running, stop it\n\t\te.stopBin()\n\n\t\tgo e.buildRun()\n\t}\n}\n\nfunc (e *Engine) loadEnvFile() {\n\tif len(e.config.EnvFiles) == 0 {\n\t\treturn\n\t}\n\n\t// assume refreshed env is as big as the loaded env\n\tnewEnv := make(map[string]string, len(e.loadedEnv))\n\n\tfor _, envPath := range e.config.EnvFiles {\n\t\tif !filepath.IsAbs(envPath) {\n\t\t\tenvPath = filepath.Join(e.config.Root, envPath)\n\t\t}\n\t\tfile, err := os.Open(envPath)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\te.mainDebug(\"env file %q does not exist, skipping\", envPath)\n\t\t\t} else {\n\t\t\t\te.runnerLog(\"failed to open env file %q: %s\", envPath, err.Error())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdefer file.Close()\n\t\tfileEnv, err := godotenv.Parse(file)\n\t\tif err != nil {\n\t\t\te.runnerLog(\"failed to parse env file %q: %s\", envPath, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tfor k, v := range fileEnv {\n\t\t\tif v, tracked := e.globalEnv[k]; !tracked {\n\t\t\t\torigVal, exists := os.LookupEnv(k)\n\t\t\t\tif exists {\n\t\t\t\t\t// not used yet, but might be useful for a future \"override\" feature\n\t\t\t\t\te.globalEnv[k] = &origVal\n\t\t\t\t\tcontinue // untracked env values are likely global - don't override them\n\t\t\t\t}\n\t\t\t\t// on first encounter of a key, if no global value exists, mark as nil so\n\t\t\t\t// that on next load of .env file, globalEnv map value will not be overwritten\n\t\t\t\te.globalEnv[k] = nil\n\t\t\t} else if tracked && v != nil {\n\t\t\t\t// only set values from file if not already present in the environment\n\t\t\t\te.mainDebug(\"key %q already exists in the environment, skipping\", k)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := os.Setenv(k, v); err != nil {\n\t\t\t\te.runnerLog(\"failed to set env key %q: %s\", k, err.Error())\n\t\t\t}\n\t\t\tnewEnv[k] = v\n\t\t}\n\t}\n\n\t// unset any keys that were removed from .env file,\n\t// but ignore those that were set before air was run\n\tfor k := range e.loadedEnv {\n\t\tif _, exists := newEnv[k]; !exists {\n\t\t\tif orig := e.globalEnv[k]; orig == nil {\n\t\t\t\tif err := os.Unsetenv(k); err != nil {\n\t\t\t\t\te.runnerLog(\"failed to restore env key %q: %s\", k, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\te.loadedEnv = newEnv\n}\n\nfunc (e *Engine) buildRun() {\n\t// Create this build's unique stop channel\n\tmyStopCh := make(chan struct{})\n\n\t// Put our stop channel in buildRunCh (acts as semaphore + carries our stop token)\n\te.buildRunCh <- myStopCh\n\tdefer func() {\n\t\t<-e.buildRunCh\n\t}()\n\n\t// Check if we were already signaled to stop before we even started\n\tselect {\n\tcase <-myStopCh:\n\t\treturn\n\tcase <-e.exitCh:\n\t\te.mainDebug(\"exit in buildRun before pre_cmd\")\n\t\treturn\n\tdefault:\n\t}\n\n\te.loadEnvFile()\n\n\tvar err error\n\tif err = e.runPreCmd(); err != nil {\n\t\te.runnerLog(\"failed to execute pre_cmd: %s\", err.Error())\n\t\tif e.config.Build.StopOnError {\n\t\t\treturn\n\t\t}\n\t}\n\tif output, err := e.building(); err != nil {\n\t\te.buildLog(\"failed to build, error: %s\", err.Error())\n\t\t_ = e.writeBuildErrorLog(err.Error())\n\t\tif e.config.Build.StopOnError {\n\t\t\t// It only makes sense to run it if we stop on error. Otherwise when\n\t\t\t// running the binary again the error modal will be overwritten by\n\t\t\t// the reload.\n\t\t\tif e.config.Proxy.Enabled {\n\t\t\t\te.proxy.BuildFailed(BuildFailedMsg{\n\t\t\t\t\tError:   err.Error(),\n\t\t\t\t\tCommand: e.config.Build.Cmd,\n\t\t\t\t\tOutput:  output,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Check again before running the binary\n\tselect {\n\tcase <-myStopCh:\n\t\treturn\n\tcase <-e.exitCh:\n\t\te.mainDebug(\"exit in buildRun after build\")\n\t\treturn\n\tdefault:\n\t}\n\n\tif err = e.runBin(); err != nil {\n\t\te.runnerLog(\"failed to run, error: %s\", err.Error())\n\t}\n}\n\nfunc (e *Engine) flushEvents() {\n\tfor {\n\t\tselect {\n\t\tcase <-e.eventCh:\n\t\t\te.mainDebug(\"flushing events\")\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// utility to execute commands, such as cmd & pre_cmd\nfunc (e *Engine) runCommand(command string) error {\n\tcmd, stdout, stderr, err := e.startCmd(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tstdout.Close()\n\t\tstderr.Close()\n\t}()\n\n\tcopyOutput(os.Stdout, stdout)\n\tcopyOutput(os.Stderr, stderr)\n\n\t// wait for command to finish\n\treturn cmd.Wait()\n}\n\nfunc (e *Engine) runCommandCopyOutput(command string) (string, error) {\n\t// both stdout and stderr are piped to the same buffer, so ignore the second\n\t// one\n\tcmd, stdout, _, err := e.startCmd(command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() {\n\t\tstdout.Close()\n\t}()\n\n\tstdoutBytes, _ := io.ReadAll(stdout)\n\t_, _ = io.Copy(os.Stdout, strings.NewReader(string(stdoutBytes)))\n\n\t// wait for command to finish\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn string(stdoutBytes), err\n\t}\n\treturn string(stdoutBytes), nil\n}\n\n// run cmd option in .air.toml\nfunc (e *Engine) building() (string, error) {\n\te.buildLog(\"building...\")\n\toutput, err := e.runCommandCopyOutput(e.config.Build.Cmd)\n\tif err != nil {\n\t\treturn output, err\n\t}\n\treturn output, nil\n}\n\n// run pre_cmd option in .air.toml\nfunc (e *Engine) runPreCmd() error {\n\tfor _, command := range e.config.Build.PreCmd {\n\t\te.runnerLog(\"> %s\", command)\n\t\terr := e.runCommand(command)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// run post_cmd option in .air.toml\nfunc (e *Engine) runPostCmd() error {\n\tfor _, command := range e.config.Build.PostCmd {\n\t\te.runnerLog(\"> %s\", command)\n\t\terr := e.runCommand(command)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Engine) runBin() error {\n\t// killFunc returns a chan of chan of int that should be used to shutdown the bin currently being run\n\t// The chan int that is passed in will be used to signal completion of the shutdown\n\tkillFunc := func(cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, killCh chan<- struct{}, processExit <-chan struct{}) chan<- chan int {\n\t\tshutdown := make(chan chan int)\n\t\tvar closer chan int\n\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tstdout.Close()\n\t\t\t\tstderr.Close()\n\t\t\t}()\n\n\t\t\tselect {\n\t\t\tcase closer = <-shutdown:\n\t\t\t\t// stopBin has been called from start or cleanup\n\t\t\t\t// defer the signalling of shutdown completion before attempting to kill further down\n\t\t\t\tdefer close(closer)\n\t\t\t\tdefer close(killCh)\n\t\t\tcase <-processExit:\n\t\t\t\t// the process is exited, return\n\t\t\t\te.withLock(func() {\n\t\t\t\t\t// Avoid deadlocking any racing shutdown request\n\t\t\t\t\tselect {\n\t\t\t\t\tcase c := <-shutdown:\n\t\t\t\t\t\tclose(c)\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\te.binStopCh = nil\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\te.mainDebug(\"trying to kill pid %d, cmd %+v\", cmd.Process.Pid, cmd.Args)\n\n\t\t\tpid, err := e.killCmd(cmd)\n\t\t\tif err != nil {\n\t\t\t\te.mainDebug(\"failed to kill PID %d, error: %s\", pid, err.Error())\n\t\t\t\tif cmd.ProcessState != nil && !cmd.ProcessState.Exited() {\n\t\t\t\t\t// Pass a non zero exit code to the closer to delegate the\n\t\t\t\t\t// decision wether to os.Exit or not\n\t\t\t\t\tcloser <- 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.mainDebug(\"cmd killed, pid: %d\", pid)\n\t\t\t}\n\n\t\t\tif e.config.Build.StopOnError {\n\t\t\t\trelBinPath := e.config.rel(e.config.binPath())\n\t\t\t\tif relBinPath == \"\" || strings.HasPrefix(relBinPath, \"..\") {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcmdBinPath := cmdPath(relBinPath)\n\t\t\t\tif _, err = os.Stat(cmdBinPath); os.IsNotExist(err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err = os.Remove(cmdBinPath); err != nil {\n\t\t\t\t\te.mainLog(\"failed to remove %s, error: %s\", relBinPath, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn shutdown\n\t}\n\n\te.runnerLog(\"running...\")\n\tgo func() {\n\n\t\tdefer func() {\n\t\t\tselect {\n\t\t\tcase <-e.exitCh:\n\t\t\t\te.mainDebug(\"exit in runBin\")\n\t\t\tdefault:\n\t\t\t}\n\t\t}()\n\n\t\t// control killFunc should be kill or not\n\t\tkillCh := make(chan struct{})\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-killCh:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tformattedBin := formatPath(e.config.runnerBin())\n\t\t\t\tcommand := strings.Join(append([]string{formattedBin}, e.runArgs...), \" \")\n\t\t\t\tcmd, stdout, stderr, err := e.startCmd(command)\n\t\t\t\tif err != nil {\n\t\t\t\t\te.mainLog(\"failed to start %s, error: %s\", e.config.rel(e.config.binPath()), err.Error())\n\t\t\t\t\tclose(killCh)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprocessExit := make(chan struct{})\n\t\t\t\te.mainDebug(\"running process pid %v\", cmd.Process.Pid)\n\t\t\t\tif e.config.Proxy.Enabled {\n\t\t\t\t\te.mainDebug(\"reloading proxy\")\n\t\t\t\t\te.proxy.Reload()\n\t\t\t\t}\n\n\t\t\t\te.stopBin()\n\t\t\t\te.withLock(func() {\n\t\t\t\t\te.binStopCh = killFunc(cmd, stdout, stderr, killCh, processExit)\n\t\t\t\t})\n\n\t\t\t\tgo copyOutput(os.Stdout, stdout)\n\t\t\t\tgo copyOutput(os.Stderr, stderr)\n\n\t\t\t\tstate, _ := cmd.Process.Wait()\n\t\t\t\tclose(processExit)\n\n\t\t\t\tswitch state.ExitCode() {\n\t\t\t\tcase 0:\n\t\t\t\t\te.runnerLog(\"Process Exit with Code 0\")\n\t\t\t\tcase -1:\n\t\t\t\t\t// because when we use ctrl + c to stop will return -1\n\t\t\t\tdefault:\n\t\t\t\t\te.runnerLog(\"Process Exit with Code: %v\", state.ExitCode())\n\t\t\t\t}\n\n\t\t\t\tif !e.config.Build.Rerun {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttime.Sleep(e.config.rerunDelay())\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc (e *Engine) stopBin() {\n\te.mainDebug(\"initiating shutdown sequence\")\n\tstart := time.Now()\n\te.mainDebug(\"shutdown completed in %v\", time.Since(start))\n\n\texitCode := make(chan int)\n\n\te.withLock(func() {\n\t\tif e.binStopCh != nil {\n\t\t\te.mainDebug(\"sending shutdown command to killfunc\")\n\t\t\te.binStopCh <- exitCode\n\t\t\te.binStopCh = nil\n\t\t} else {\n\t\t\tclose(exitCode)\n\t\t}\n\t})\n\n\tselect {\n\tcase ret := <-exitCode:\n\t\tif ret != 0 {\n\t\t\te.exiter.Exit(ret) // Use exiter instead of direct os.Exit, it's for tests purpose.\n\t\t}\n\tcase <-time.After(5 * time.Second):\n\t\te.mainDebug(\"timed out waiting for process exit\")\n\t}\n}\n\nfunc (e *Engine) cleanup() {\n\te.mainLog(\"cleaning...\")\n\tdefer e.mainLog(\"see you again~\")\n\tdefer e.mainDebug(\"exited\")\n\n\tif e.config.Proxy.Enabled {\n\t\te.mainDebug(\"powering down the proxy...\")\n\t\tif err := e.proxy.Stop(); err != nil {\n\t\t\te.mainLog(\"failed to stop proxy: %+v\", err)\n\t\t}\n\t}\n\n\te.stopBin()\n\te.mainDebug(\"waiting for close watchers..\")\n\n\te.withLock(func() {\n\t\tfor i := 0; i < int(e.watchers); i++ {\n\t\t\te.watcherStopCh <- true\n\t\t}\n\t})\n\n\te.mainDebug(\"waiting for buildRun...\")\n\tvar err error\n\tif err = e.watcher.Close(); err != nil {\n\t\te.mainLog(\"failed to close watcher, error: %s\", err.Error())\n\t}\n\n\te.mainDebug(\"waiting for clean ...\")\n\n\tif e.config.Misc.CleanOnExit {\n\t\te.mainLog(\"deleting %s\", e.config.tmpPath())\n\t\tif err = os.RemoveAll(e.config.tmpPath()); err != nil {\n\t\t\te.mainLog(\"failed to delete tmp dir, err: %+v\", err)\n\t\t}\n\t}\n\n\te.running.Store(false)\n}\n\n// Stop the air\nfunc (e *Engine) Stop() {\n\tif err := e.runPostCmd(); err != nil {\n\t\te.runnerLog(\"failed to execute post_cmd, error: %s\", err.Error())\n\t}\n\tclose(e.exitCh)\n}\n"
  },
  {
    "path": "runner/engine_test.go",
    "content": "package runner\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/pelletier/go-toml\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewEngine(t *testing.T) {\n\t_ = os.Unsetenv(airWd)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif engine.logger == nil {\n\t\tt.Fatal(\"logger should not be nil\")\n\t}\n\tif engine.config == nil {\n\t\tt.Fatal(\"Config should not be nil\")\n\t}\n\tif engine.watcher == nil {\n\t\tt.Fatal(\"watcher should not be nil\")\n\t}\n}\n\nfunc TestCheckRunEnv(t *testing.T) {\n\t_ = os.Unsetenv(airWd)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tnestedTmpDir := filepath.Join(t.TempDir(), \"nested\", \"build\")\n\tengine.config.TmpDir = nestedTmpDir\n\n\terr = engine.checkRunEnv()\n\trequire.NoError(t, err)\n\tassert.DirExists(t, nestedTmpDir)\n}\n\nfunc TestWatching(t *testing.T) {\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tpath = strings.Replace(path, filepath.Join(\"_testdata\", \"toml\"), \"\", 1)\n\terr = engine.watching(filepath.Join(path, \"_testdata\", \"watching\"))\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n}\n\nfunc TestRegexes(t *testing.T) {\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tengine.config.Build.ExcludeRegex = []string{\"foo\\\\.html$\", \"bar\", \"_test\\\\.go\"}\n\terr = engine.config.preprocess(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tresult, err := engine.isExcludeRegex(\"./test/foo.html\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif result != true {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n\n\tresult, err = engine.isExcludeRegex(\"./test/bar/index.html\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif result != true {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n\n\tresult, err = engine.isExcludeRegex(\"./test/unrelated.html\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif result {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", false, result)\n\t}\n\n\tresult, err = engine.isExcludeRegex(\"./myPackage/goFile_testxgo\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif result {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", false, result)\n\t}\n\tresult, err = engine.isExcludeRegex(\"./myPackage/goFile_test.go\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif result != true {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n}\n\nfunc TestRunCommand(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires touch\")\n\t}\n\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\terr = engine.runCommand(\"touch test.txt\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif _, err := os.Stat(\"./test.txt\"); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t\t}\n\t}\n}\n\nfunc TestRunPreCmd(t *testing.T) {\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tengine.config.Build.PreCmd = []string{`cmd.exe /c \"echo hello air > pre_cmd.txt\"`}\n\t} else {\n\t\tengine.config.Build.PreCmd = []string{\"echo 'hello air' > pre_cmd.txt\"}\n\t}\n\terr = engine.runPreCmd()\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif _, err := os.Stat(\"./pre_cmd.txt\"); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t\t}\n\t}\n}\n\nfunc TestRunPostCmd(t *testing.T) {\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tengine.config.Build.PostCmd = []string{`cmd.exe /c \"echo hello air > post_cmd.txt\"`}\n\t} else {\n\t\tengine.config.Build.PostCmd = []string{\"echo 'hello air' > post_cmd.txt\"}\n\t}\n\terr = engine.runPostCmd()\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tif _, err := os.Stat(\"./post_cmd.txt\"); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t\t}\n\t}\n}\n\nfunc TestRunBin(t *testing.T) {\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\terr = engine.runBin()\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n}\n\nfunc GetPort() (int, func()) {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tport := l.Addr().(*net.TCPAddr).Port\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn port, func() {\n\t\t_ = l.Close()\n\t}\n}\n\nfunc TestRebuild(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"unstable on Windows\")\n\t}\n\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tengine.config.Build.ExcludeUnchanged = true\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tengine.Run()\n\t\tt.Logf(\"engine stopped\")\n\t\twg.Done()\n\t}()\n\terr = waitingPortReady(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tt.Logf(\"port is ready\")\n\n\t// start rebuild\n\n\tt.Logf(\"start change main.go\")\n\t// change file of main.go\n\t// just append a new empty line to main.go\n\tfile, err := os.OpenFile(\"main.go\", os.O_APPEND|os.O_WRONLY, 0o644)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tdefer file.Close()\n\t_, err = file.WriteString(\"\\n\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\terr = waitingPortConnectionRefused(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"timeout: %s.\", err)\n\t}\n\tt.Logf(\"connection refused\")\n\terr = waitingPortReady(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tt.Logf(\"port is ready\")\n\t// stop engine\n\tengine.Stop()\n\tt.Logf(\"engine stopped\")\n\t// Wait for engine to fully stop\n\terr = waitForEngineState(t, engine, false, time.Second*3)\n\tif err != nil {\n\t\tt.Fatalf(\"engine did not stop: %s.\", err)\n\t}\n\twg.Wait()\n\tassert.True(t, checkPortConnectionRefused(port))\n}\n\nfunc waitingPortConnectionRefused(t *testing.T, port int, timeout time.Duration) error {\n\tt.Helper()\n\tt.Logf(\"waiting port %d connection refused\", port)\n\n\t// Use environment-aware timeout for CI compatibility\n\ttimeoutMultiplier := 1.0\n\tif os.Getenv(\"CI\") != \"\" {\n\t\ttimeoutMultiplier = 2.0\n\t}\n\tadjustedTimeout := time.Duration(float64(timeout) * timeoutMultiplier)\n\n\tdeadline := time.Now().Add(adjustedTimeout)\n\tticker := time.NewTicker(20 * time.Millisecond) // Reduced from 100ms to 20ms\n\tdefer ticker.Stop()\n\n\tfor {\n\t\t_, err := net.Dial(\"tcp\", fmt.Sprintf(\"localhost:%d\", port))\n\t\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif time.Now().After(deadline) {\n\t\t\treturn fmt.Errorf(\"timeout waiting for port %d connection refused (timeout: %v)\", port, adjustedTimeout)\n\t\t}\n\n\t\t<-ticker.C\n\t}\n}\n\nfunc TestCtrlCWhenHaveKillDelay(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"unstable on Windows\")\n\t}\n\n\t// fix https://github.com/air-verse/air/issues/278\n\t// generate a random port\n\tdata := []byte(\"[build]\\n  kill_delay = \\\"2s\\\"\")\n\tc := Config{}\n\tif err := toml.Unmarshal(data, &c); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tengine.config.Build.KillDelay = c.Build.KillDelay\n\tengine.config.Build.Delay = 2000\n\tengine.config.Build.SendInterrupt = true\n\tif err := engine.config.preprocess(nil); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tgo func() {\n\t\tengine.Run()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)\n\tgo func() {\n\t\t<-sigs\n\t\tengine.Stop()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\tif err := waitingPortReady(t, port, time.Second*10); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tsigs <- syscall.SIGINT\n\terr = waitingPortConnectionRefused(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\t// Wait for engine to fully stop - the test has kill_delay=\"2s\"\n\terr = waitForEngineState(t, engine, false, time.Second*5)\n\tif err != nil {\n\t\tt.Logf(\"engine may not have stopped in time: %s\", err)\n\t}\n\tassert.False(t, engine.running.Load())\n}\n\nfunc TestCtrlCWhenREngineIsRunning(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"unstable on Windows\")\n\t}\n\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tgo func() {\n\t\tengine.Run()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\t<-sigs\n\t\tengine.Stop()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\tif err := waitingPortReady(t, port, time.Second*10); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tsigs <- syscall.SIGINT\n\ttime.Sleep(time.Second * 1)\n\terr = waitingPortConnectionRefused(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tassert.False(t, engine.running.Load())\n}\n\nfunc TestCtrlCWithFailedBin(t *testing.T) {\n\ttimeout := 5 * time.Second\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdir := initWithQuickExitGoCode(t)\n\t\tchdir(t, dir)\n\t\tengine, err := NewEngine(\"\", nil, true)\n\t\tassert.NoError(t, err)\n\t\tengine.config.Build.Bin = \"<WRONGCOMAMND>\"\n\t\tsigs := make(chan os.Signal, 1)\n\t\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tengine.Run()\n\t\t\tt.Logf(\"engine stopped\")\n\t\t\twg.Done()\n\t\t}()\n\t\tgo func() {\n\t\t\t<-sigs\n\t\t\tengine.Stop()\n\t\t\tt.Logf(\"engine stopped\")\n\t\t}()\n\t\ttime.Sleep(time.Second * 1)\n\t\tsigs <- syscall.SIGINT\n\t\twg.Wait()\n\t\tclose(done)\n\t}()\n\tselect {\n\tcase <-done:\n\tcase <-time.After(timeout):\n\t\tt.Error(\"Test timed out\")\n\t}\n}\n\nfunc TestFixCloseOfChannelAfterCtrlC(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"unstable on Windows\")\n\t}\n\n\t// fix https://github.com/air-verse/air/issues/294\n\tdir := initWithBuildFailedCode(t)\n\tchdir(t, dir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\t// Silence engine logs to keep this test output readable.\n\tengine.config.Log.Silent = true\n\tsilenceBuildCmd(engine.config)\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\tdefer signal.Stop(sigs)\n\tgo func() {\n\t\tengine.Run()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\n\tgo func() {\n\t\t<-sigs\n\t\tengine.Stop()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\tbuildLogPath := engine.config.buildLogPath()\n\tif err := waitForCondition(t, time.Second*5, func() bool {\n\t\tinfo, err := os.Stat(buildLogPath)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn info.Size() > 0\n\t}, \"first build failure log\"); err != nil {\n\t\tt.Fatalf(\"build did not fail as expected: %s\", err)\n\t}\n\tport, f := GetPort()\n\tf()\n\t// correct code\n\terr = generateGoCode(dir, port)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tif err := waitingPortReady(t, port, time.Second*10); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\t// ctrl + c\n\tsigs <- syscall.SIGINT\n\tif err := waitingPortConnectionRefused(t, port, time.Second*10); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tif err := waitForEngineState(t, engine, false, time.Second*5); err != nil {\n\t\tt.Fatalf(\"engine did not stop: %s\", err)\n\t}\n\tassert.False(t, engine.running.Load())\n}\n\nfunc TestFixCloseOfChannelAfterTwoFailedBuild(t *testing.T) {\n\t// fix https://github.com/air-verse/air/issues/294\n\t// happens after two failed builds\n\tdir := initWithBuildFailedCode(t)\n\t// change dir to tmpDir\n\tchdir(t, dir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tengine.config.Log.Silent = true\n\tsilenceBuildCmd(engine.config)\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tengine.Run()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\n\tgo func() {\n\t\t<-sigs\n\t\tengine.Stop()\n\t\tt.Logf(\"engine stopped\")\n\t}()\n\n\t// Wait for first build to complete (with error) - reduced from 3s to 1s\n\t// Since the build fails immediately, 1s is sufficient\n\ttime.Sleep(time.Millisecond * 500)\n\n\t// edit *.go file to create build error again\n\tfile, err := os.OpenFile(\"main.go\", os.O_APPEND|os.O_WRONLY, 0o644)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tdefer file.Close()\n\t_, err = file.WriteString(\"\\n\")\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\t// Wait for second build attempt - reduced from 3s to 500ms\n\ttime.Sleep(time.Millisecond * 500)\n\t// ctrl + c\n\tsigs <- syscall.SIGINT\n\t// Wait for engine to stop\n\terr = waitForEngineState(t, engine, false, time.Second*3)\n\tif err != nil {\n\t\tt.Logf(\"engine may not have stopped cleanly: %s\", err)\n\t}\n\tassert.False(t, engine.running.Load())\n}\n\n// waitingPortReady waits until the port is ready to be used.\nfunc waitingPortReady(t *testing.T, port int, timeout time.Duration) error {\n\tt.Helper()\n\tt.Logf(\"waiting port %d ready\", port)\n\n\t// Use environment-aware timeout for CI compatibility\n\ttimeoutMultiplier := 1.0\n\tif os.Getenv(\"CI\") != \"\" {\n\t\ttimeoutMultiplier = 2.0\n\t}\n\tadjustedTimeout := time.Duration(float64(timeout) * timeoutMultiplier)\n\n\tdeadline := time.Now().Add(adjustedTimeout)\n\tticker := time.NewTicker(20 * time.Millisecond) // Reduced from 100ms to 20ms\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"localhost:%d\", port))\n\t\tif err == nil {\n\t\t\t_ = conn.Close()\n\t\t\treturn nil\n\t\t}\n\n\t\tif time.Now().After(deadline) {\n\t\t\treturn fmt.Errorf(\"timeout waiting for port %d ready (timeout: %v)\", port, adjustedTimeout)\n\t\t}\n\n\t\t<-ticker.C\n\t}\n}\n\nfunc TestRun(t *testing.T) {\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\n\t// Wait for port to be ready instead of fixed sleep\n\terr = waitingPortReady(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tassert.True(t, checkPortHaveBeenUsed(port))\n\tt.Logf(\"try to stop\")\n\tengine.Stop()\n\n\t// Wait for engine to stop instead of fixed sleep\n\terr = waitForEngineState(t, engine, false, time.Second*3)\n\tif err != nil {\n\t\tt.Fatalf(\"engine did not stop: %s.\", err)\n\t}\n\tassert.False(t, checkPortHaveBeenUsed(port))\n\tt.Logf(\"stopped\")\n}\n\nfunc checkPortConnectionRefused(port int) bool {\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"localhost:%d\", port))\n\tdefer func() {\n\t\tif conn != nil {\n\t\t\t_ = conn.Close()\n\t\t}\n\t}()\n\treturn errors.Is(err, syscall.ECONNREFUSED)\n}\n\nfunc checkPortHaveBeenUsed(port int) bool {\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"localhost:%d\", port))\n\tif err != nil {\n\t\treturn false\n\t}\n\t_ = conn.Close()\n\treturn true\n}\n\nfunc initTestEnv(t *testing.T, port int) string {\n\ttempDir := t.TempDir()\n\tt.Setenv(airWd, tempDir)\n\tt.Logf(\"tempDir: %s\", tempDir)\n\t// generate golang code to tempdir\n\terr := generateGoCode(tempDir, port)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\treturn tempDir\n}\n\nfunc initWithBuildFailedCode(t *testing.T) string {\n\ttempDir := t.TempDir()\n\tt.Setenv(airWd, tempDir)\n\tt.Logf(\"tempDir: %s\", tempDir)\n\t// generate golang code to tempdir\n\terr := generateBuildErrorGoCode(tempDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\treturn tempDir\n}\n\nfunc initWithQuickExitGoCode(t *testing.T) string {\n\ttempDir := t.TempDir()\n\tt.Setenv(airWd, tempDir)\n\tt.Logf(\"tempDir: %s\", tempDir)\n\t// generate golang code to tempdir\n\terr := generateQuickExitGoCode(tempDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\treturn tempDir\n}\n\nfunc generateQuickExitGoCode(dir string) error {\n\tcode := `package main\n// You can edit this code!\n// Click here and start typing.\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, 世界\")\n}\n`\n\tfile, err := os.Create(dir + \"/main.go\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(code)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t// generate go mod file\n\tmod := `module air.sample.com\n\ngo 1.17\n`\n\tfile, err = os.Create(dir + \"/go.mod\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(mod)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc generateBuildErrorGoCode(dir string) error {\n\tcode := `package main\n// You can edit this code!\n// Click here and start typing.\n\nfunc main() {\n\tPrintln(\"Hello, 世界\")\n\n}\n`\n\tfile, err := os.Create(dir + \"/main.go\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(code)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t// generate go mod file\n\tmod := `module air.sample.com\n\ngo 1.17\n`\n\tfile, err = os.Create(dir + \"/go.mod\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(mod)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// generateGoCode generates golang code to tempdir\nfunc generateGoCode(dir string, port int) error {\n\tcode := fmt.Sprintf(`package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\tlog.Fatal(http.ListenAndServe(\"127.0.0.1:%v\", nil))\n}\n`, port)\n\tfile, err := os.Create(dir + \"/main.go\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(code)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t// generate go mod file\n\tmod := `module air.sample.com\n\ngo 1.17\n`\n\tfile, err = os.Create(dir + \"/go.mod\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = file.WriteString(mod)\n\tif err != nil {\n\t\t_ = file.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc silenceBuildCmd(cfg *Config) {\n\tif cfg == nil {\n\t\treturn\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tcfg.Build.Cmd = fmt.Sprintf(\"%s > $null 2>&1\", cfg.Build.Cmd)\n\t\treturn\n\t}\n\tcfg.Build.Cmd = fmt.Sprintf(\"%s >/dev/null 2>&1\", cfg.Build.Cmd)\n}\n\nfunc TestRebuildWhenRunCmdUsingDLV(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires touch\")\n\t}\n\n\tif _, err := exec.LookPath(\"dlv\"); err != nil {\n\t\tt.Skip(\"dlv not available in PATH\")\n\t}\n\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tengine.config.Build.Cmd = \"go build -gcflags='all=-N -l' -o ./tmp/main .\"\n\tengine.config.Build.Bin = \"\"\n\tdlvPort, f := GetPort()\n\tf()\n\tengine.config.Build.FullBin = fmt.Sprintf(\"dlv exec --accept-multiclient --log --headless --continue --listen :%d --api-version 2 ./tmp/main\", dlvPort)\n\t_ = engine.config.preprocess(nil)\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\tif err := waitingPortReady(t, port, time.Second*40); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tt.Logf(\"start change main.go\")\n\t// change file of main.go\n\t// just append a new empty line to main.go\n\tgo func() {\n\t\tfile, err := os.OpenFile(\"main.go\", os.O_APPEND|os.O_WRONLY, 0o644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Should not be fail: %s.\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\t_, err = file.WriteString(\"\\n\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Should not be fail: %s.\", err)\n\t\t}\n\t}()\n\terr = waitingPortConnectionRefused(t, port, time.Second*10)\n\tif err != nil {\n\t\tt.Fatalf(\"timeout: %s.\", err)\n\t}\n\tt.Logf(\"connection refused\")\n\terr = waitingPortReady(t, port, time.Second*40)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\tt.Logf(\"port is ready\")\n\t// stop engine\n\tengine.Stop()\n\t// Wait for engine to stop\n\terr = waitForEngineState(t, engine, false, time.Second*5)\n\tif err != nil {\n\t\tt.Fatalf(\"engine did not stop: %s.\", err)\n\t}\n\tt.Logf(\"engine stopped\")\n\tassert.True(t, checkPortConnectionRefused(port))\n}\n\nfunc TestWriteDefaultConfig(t *testing.T) {\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tconfigName, err := writeDefaultConfig()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// check the file exists\n\tif _, err := os.Stat(configName); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\traw, err := os.ReadFile(configName)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpectedPrefix := schemaHeader + \"\\n\\n\"\n\tassert.True(t, strings.HasPrefix(string(raw), expectedPrefix), \"config should start with schema header\")\n\n\t// check the file content is right\n\tactual, err := readConfig(configName)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpect := defaultConfig()\n\tif len(expect.Build.Entrypoint) == 0 && expect.Build.Bin != \"\" {\n\t\texpect.Build.Entrypoint = entrypoint{expect.Build.Bin}\n\t}\n\n\tassert.Equal(t, expect, *actual)\n}\n\nfunc TestCheckNilSliceShouldBeenOverwrite(t *testing.T) {\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\n\t// write easy config file\n\n\tconfig := `\n[build]\ncmd = \"go build .\"\nbin = \"tmp/main\"\nexclude_regex = []\nexclude_dir = [\"test\"]\nexclude_file = [\"main.go\"]\ninclude_file = [\"test/not_a_test.go\"]\n\n`\n\tif err := os.WriteFile(dftTOML, []byte(config), 0o644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tengine, err := NewEngine(\".air.toml\", nil, true)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.Equal(t, []string{\"go\", \"tpl\", \"tmpl\", \"html\"}, engine.config.Build.IncludeExt)\n\tassert.Equal(t, []string{}, engine.config.Build.ExcludeRegex)\n\tassert.Equal(t, []string{\"test\"}, engine.config.Build.ExcludeDir)\n\t// add new config\n\tassert.Equal(t, []string{\"main.go\"}, engine.config.Build.ExcludeFile)\n\tassert.Equal(t, []string{\"test/not_a_test.go\"}, engine.config.Build.IncludeFile)\n\tassert.Equal(t, \"go build .\", engine.config.Build.Cmd)\n}\n\nfunc TestShouldIncludeGoTestFile(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires sed\")\n\t}\n\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\t_, err := writeDefaultConfig()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// write go test file\n\tfile, err := os.Create(\"main_test.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = file.WriteString(`package main\n\nimport \"testing\"\n\nfunc Test(t *testing.T) {\n\tt.Log(\"testing\")\n}\n`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// run sed\n\t// check the file exists\n\tif _, err := os.Stat(dftTOML); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// check is MacOS\n\tvar cmd *exec.Cmd\n\ttoolName := \"sed\"\n\n\tif runtime.GOOS == \"darwin\" {\n\t\ttoolName = \"gsed\"\n\t}\n\n\tcmd = exec.Command(toolName, \"-i\", \"s/\\\"_test.*go\\\"//g\", \".air.toml\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tt.Skipf(\"unable to run %s, make sure the tool is installed to run this test\", toolName)\n\t}\n\n\ttime.Sleep(time.Second * 2)\n\tengine, err := NewEngine(\".air.toml\", nil, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\n\tt.Logf(\"start change main_test.go\")\n\t// change file of main_test.go\n\t// just append a new empty line to main_test.go\n\tif err = waitingPortReady(t, port, time.Second*40); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo func() {\n\t\tfile, err = os.OpenFile(\"main_test.go\", os.O_APPEND|os.O_WRONLY, 0o644)\n\t\tassert.NoError(t, err)\n\t\tdefer file.Close()\n\t\t_, err = file.WriteString(\"\\n\")\n\t\tassert.NoError(t, err)\n\t}()\n\t// should Have rebuild\n\tif err = waitingPortReady(t, port, time.Second*10); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateNewDir(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires touch\")\n\t}\n\n\t// generate a random port\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\t// change dir to tmpDir\n\tchdir(t, tmpDir)\n\tengine, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\tif err := waitingPortReady(t, port, 5*time.Second); err != nil {\n\t\tt.Fatalf(\"Should not be fail: %s.\", err)\n\t}\n\n\t// create a new dir make dir\n\tif err = os.Mkdir(tmpDir+\"/dir\", 0o644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// no need reload\n\tif err = waitingPortConnectionRefused(t, port, 3*time.Second); err == nil {\n\t\tt.Fatal(\"should raise a error\")\n\t}\n\tengine.Stop()\n\ttime.Sleep(2 * time.Second)\n}\n\nfunc TestShouldIncludeIncludedFile(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires sh\")\n\t}\n\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\n\tchdir(t, tmpDir)\n\n\tconfig := `\n[build]\ncmd = \"true\" # do nothing\nfull_bin = \"sh main.sh\"\ninclude_ext = [\"sh\"]\ninclude_dir = [\"nonexist\"] # prevent default \".\" watch from taking effect\ninclude_file = [\"main.sh\"]\n`\n\tif err := os.WriteFile(dftTOML, []byte(config), 0o644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr := os.WriteFile(\"main.sh\", []byte(\"#!/bin/sh\\nprintf original > output\"), 0o755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tengine, err := NewEngine(dftTOML, nil, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\n\ttime.Sleep(time.Second * 1)\n\n\tbytes, err := os.ReadFile(\"output\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.Equal(t, []byte(\"original\"), bytes)\n\n\tt.Logf(\"start change main.sh\")\n\tgo func() {\n\t\terr := os.WriteFile(\"main.sh\", []byte(\"#!/bin/sh\\nprintf modified > output\"), 0o755)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error updating file: %s.\", err)\n\t\t}\n\t}()\n\n\ttime.Sleep(time.Second * 3)\n\n\tbytes, err = os.ReadFile(\"output\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.Equal(t, []byte(\"modified\"), bytes)\n}\n\nfunc TestShouldIncludeIncludedFileWithoutIncludedExt(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires sh\")\n\t}\n\n\tport, f := GetPort()\n\tf()\n\tt.Logf(\"port: %d\", port)\n\n\ttmpDir := initTestEnv(t, port)\n\n\tchdir(t, tmpDir)\n\n\tconfig := `\n[build]\ncmd = \"true\" # do nothing\nfull_bin = \"sh main.sh\"\ninclude_ext = [\"go\"]\ninclude_dir = [\"nonexist\"] # prevent default \".\" watch from taking effect\ninclude_file = [\"main.sh\"]\n`\n\tif err := os.WriteFile(dftTOML, []byte(config), 0o644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr := os.WriteFile(\"main.sh\", []byte(\"#!/bin/sh\\nprintf original > output\"), 0o755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tengine, err := NewEngine(dftTOML, nil, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo func() {\n\t\tengine.Run()\n\t}()\n\n\ttime.Sleep(time.Second * 1)\n\n\tbytes, err := os.ReadFile(\"output\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.Equal(t, []byte(\"original\"), bytes)\n\n\tt.Logf(\"start change main.sh\")\n\tgo func() {\n\t\terr = os.WriteFile(\"main.sh\", []byte(\"#!/bin/sh\\nprintf modified > output\"), 0o755)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error updating file: %s.\", err)\n\t\t}\n\t}()\n\n\ttime.Sleep(time.Second * 3)\n\n\tbytes, err = os.ReadFile(\"output\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassert.Equal(t, []byte(\"modified\"), bytes)\n}\n\ntype testExiter struct {\n\tt          *testing.T\n\tcalled     bool\n\texpectCode int\n}\n\nfunc (te *testExiter) Exit(code int) {\n\tte.called = true\n\tif code != te.expectCode {\n\t\tte.t.Fatalf(\"expected exit code %d, got %d\", te.expectCode, code)\n\t}\n}\n\nfunc TestEngineExit(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tsetup      func(*Engine, chan<- int)\n\t\texpectCode int\n\t\twantCalled bool\n\t}{\n\t\t{\n\t\t\tname: \"normal exit - no error\",\n\t\t\tsetup: func(_ *Engine, exitCode chan<- int) {\n\t\t\t\tgo func() {\n\t\t\t\t\texitCode <- 0\n\t\t\t\t}()\n\t\t\t},\n\t\t\texpectCode: 0,\n\t\t\twantCalled: false,\n\t\t},\n\t\t{\n\t\t\tname: \"error exit - non-zero code\",\n\t\t\tsetup: func(_ *Engine, exitCode chan<- int) {\n\t\t\t\tgo func() {\n\t\t\t\t\texitCode <- 1\n\t\t\t\t}()\n\t\t\t},\n\t\t\texpectCode: 1,\n\t\t\twantCalled: true,\n\t\t},\n\t\t{\n\t\t\tname: \"process timeout\",\n\t\t\tsetup: func(_ *Engine, _ chan<- int) {\n\t\t\t},\n\t\t\texpectCode: 0,\n\t\t\twantCalled: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\te, err := NewEngine(\"\", nil, true)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\texiter := &testExiter{\n\t\t\t\tt:          t,\n\t\t\t\texpectCode: tt.expectCode,\n\t\t\t}\n\t\t\te.exiter = exiter\n\n\t\t\texitCode := make(chan int)\n\n\t\t\tif tt.setup != nil {\n\t\t\t\ttt.setup(e, exitCode)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase ret := <-exitCode:\n\t\t\t\tif ret != 0 {\n\t\t\t\t\te.exiter.Exit(ret)\n\t\t\t\t}\n\t\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\t\t// timeout case\n\t\t\t}\n\n\t\t\tif tt.wantCalled != exiter.called {\n\t\t\t\tt.Errorf(\"Exit() called = %v, want %v\", exiter.called, tt.wantCalled)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestBuildRunRaceCondition tests that a new build does not receive\n// stop signals meant for a previous build. This is a regression test for issue #784.\n//\n// The fix uses a channel-of-channels pattern where each build gets its own unique\n// stop channel. When a new build is triggered, it retrieves the previous build's\n// stop channel and closes it to signal cancellation.\nfunc TestBuildRunRaceCondition(t *testing.T) {\n\te, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\te.config.Log.Silent = true\n\n\t// Simulate the race condition scenario from issue #784:\n\t// 1. Build A starts and puts its stop channel in buildRunCh\n\t// 2. Build B is triggered, retrieves Build A's channel and closes it\n\t// 3. Build B puts its own fresh channel in buildRunCh\n\t// 4. Build B should NOT be affected by Build A's closed channel\n\n\t// Simulate Build A putting its stop channel in buildRunCh\n\tbuildAStopCh := make(chan struct{})\n\te.buildRunCh <- buildAStopCh\n\n\t// Simulate Build B being triggered (mimics what start() does)\n\tvar retrievedChannel chan struct{}\n\tselect {\n\tcase retrievedChannel = <-e.buildRunCh:\n\t\tclose(retrievedChannel) // Signal Build A to stop\n\tdefault:\n\t\tt.Fatal(\"Expected Build A's stop channel to be in buildRunCh\")\n\t}\n\n\t// Verify we got Build A's channel\n\tif retrievedChannel != buildAStopCh {\n\t\tt.Error(\"Should have retrieved Build A's stop channel\")\n\t}\n\n\t// Verify Build A's channel is closed\n\tselect {\n\tcase <-buildAStopCh:\n\t\t// Good - Build A was signaled to stop\n\tdefault:\n\t\tt.Error(\"Build A's stop channel should have been closed\")\n\t}\n\n\t// Now simulate Build B starting with its own channel\n\tbuildBStopCh := make(chan struct{})\n\te.buildRunCh <- buildBStopCh\n\n\t// Build B should NOT be affected by Build A's closed channel\n\tselect {\n\tcase <-buildBStopCh:\n\t\tt.Error(\"Build B's stop channel should NOT be closed yet\")\n\tcase <-time.After(50 * time.Millisecond):\n\t\t// Good - Build B is still running\n\t}\n\n\t// Test that closing Build B's channel does signal Build B to stop\n\tclose(buildBStopCh)\n\tselect {\n\tcase <-buildBStopCh:\n\t\t// Good - Build B received the stop signal\n\tcase <-time.After(50 * time.Millisecond):\n\t\tt.Error(\"Build B should have been stopped when its channel was closed\")\n\t}\n\n\t// Clean up - remove Build B's channel from buildRunCh\n\tselect {\n\tcase <-e.buildRunCh:\n\t\t// Successfully cleaned up\n\tdefault:\n\t\tt.Error(\"Expected Build B's channel to still be in buildRunCh\")\n\t}\n}\n\n// TestBuildRunRaceConditionRapidChanges tests rapid file changes don't cause deadlock\nfunc TestBuildRunRaceConditionRapidChanges(t *testing.T) {\n\te, err := NewEngine(\"\", nil, true)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\te.config.Log.Silent = true\n\n\t// Simulate 5 rapid builds in succession\n\tchannels := make([]chan struct{}, 5)\n\n\tfor i := 0; i < 5; i++ {\n\t\t// If there's a previous build, stop it\n\t\tselect {\n\t\tcase oldCh := <-e.buildRunCh:\n\t\t\tclose(oldCh)\n\t\tdefault:\n\t\t}\n\n\t\t// Start new build\n\t\tchannels[i] = make(chan struct{})\n\t\te.buildRunCh <- channels[i]\n\t}\n\n\t// All previous builds should be signaled to stop\n\tfor i := 0; i < 4; i++ {\n\t\tselect {\n\t\tcase <-channels[i]:\n\t\t\t// Good - was signaled to stop\n\t\tdefault:\n\t\t\tt.Errorf(\"Build %d should have been signaled to stop\", i)\n\t\t}\n\t}\n\n\t// Last build should NOT be stopped\n\tselect {\n\tcase <-channels[4]:\n\t\tt.Error(\"Last build should still be running\")\n\tdefault:\n\t\t// Good\n\t}\n\n\t// Clean up\n\t<-e.buildRunCh\n}\n\nfunc TestEngineLoadEnvFile(t *testing.T) {\n\ttmpDir := t.TempDir()\n\tenvPath := filepath.Join(tmpDir, \".env\")\n\n\toriginalValue := \"original_global_value\"\n\tt.Setenv(\"TEST_GLOBAL_VAR\", originalValue)\n\n\tconst initialEnv = `TEST_VAR1=value1\nTEST_VAR2=value2\nTEST_GLOBAL_VAR=overridden_value\n`\n\n\terr := os.WriteFile(envPath, []byte(initialEnv), 0o644)\n\trequire.NoError(t, err)\n\n\tcfg := defaultConfig()\n\tcfg.Root = tmpDir\n\tcfg.EnvFiles = []string{\".env\"}\n\n\tengine, err := NewEngineWithConfig(&cfg, false)\n\trequire.NoError(t, err)\n\n\tengine.loadEnvFile()\n\n\tassert.Equal(t, \"value1\", os.Getenv(\"TEST_VAR1\"), \"TEST_VAR1 should be set\")\n\tassert.Equal(t, \"value2\", os.Getenv(\"TEST_VAR2\"), \"TEST_VAR2 should be set\")\n\tassert.Equal(t, \"original_global_value\", os.Getenv(\"TEST_GLOBAL_VAR\"), \"TEST_GLOBAL_VAR should NOT be overridden\")\n\n\t// remove TEST_VAR2\n\tconst updatedEnv = `TEST_VAR1=updated_value1\nTEST_GLOBAL_VAR=still_overridden\n`\n\terr = os.WriteFile(envPath, []byte(updatedEnv), 0o644)\n\trequire.NoError(t, err)\n\n\tengine.loadEnvFile()\n\n\tassert.Equal(t, \"updated_value1\", os.Getenv(\"TEST_VAR1\"), \"TEST_VAR1 should be updated\")\n\t// since TEST_VAR2 only exists in environment thanks to air, it should get unset on removal\n\t_, exists := os.LookupEnv(\"TEST_VAR2\")\n\tassert.False(t, exists, \"TEST_VAR2 should be unset after removal from .env\")\n\tassert.Equal(t, \"original_global_value\", os.Getenv(\"TEST_GLOBAL_VAR\"), \"TEST_GLOBAL_VAR should NOT be overridden\")\n\n\tconst finalEnv = `TEST_VAR1=final_value`\n\terr = os.WriteFile(envPath, []byte(finalEnv), 0o644)\n\trequire.NoError(t, err)\n\n\tengine.loadEnvFile()\n\n\tassert.Equal(t, \"final_value\", os.Getenv(\"TEST_VAR1\"), \"TEST_VAR1 should be final\")\n\tassert.Equal(t, originalValue, os.Getenv(\"TEST_GLOBAL_VAR\"), \"TEST_GLOBAL_VAR should be restored to original value\")\n}\n"
  },
  {
    "path": "runner/exiter.go",
    "content": "package runner\n\nimport \"os\"\n\ntype exiter interface {\n\tExit(code int)\n}\n\ntype defaultExiter struct{}\n\nfunc (d defaultExiter) Exit(code int) {\n\tos.Exit(code)\n}\n"
  },
  {
    "path": "runner/flag.go",
    "content": "package runner\n\nimport (\n\t\"flag\"\n)\n\n// ParseConfigFlag parse toml information for flag\nfunc ParseConfigFlag(f *flag.FlagSet) map[string]TomlInfo {\n\tc := defaultConfig()\n\tm := flatConfig(c)\n\tfor k, v := range m {\n\t\tf.StringVar(v.Value, k, v.fieldValue, v.usage)\n\t}\n\treturn m\n}\n"
  },
  {
    "path": "runner/flag_test.go",
    "content": "package runner\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestFlag(t *testing.T) {\n\tt.Parallel()\n\t// table driven tests\n\ttype testCase struct {\n\t\tname     string\n\t\targs     []string\n\t\texpected string\n\t\tkey      string\n\t}\n\ttestCases := []testCase{\n\t\t{\n\t\t\tname:     \"test1\",\n\t\t\targs:     []string{\"--build.cmd\", \"go build -o ./tmp/main .\"},\n\t\t\texpected: \"go build -o ./tmp/main .\",\n\t\t\tkey:      \"build.cmd\",\n\t\t},\n\t\t{\n\t\t\tname:     \"tmp dir test\",\n\t\t\targs:     []string{\"--tmp_dir\", \"test\"},\n\t\t\texpected: \"test\",\n\t\t\tkey:      \"tmp_dir\",\n\t\t},\n\t\t{\n\t\t\tname:     \"check bool\",\n\t\t\targs:     []string{\"--build.exclude_unchanged\", \"true\"},\n\t\t\texpected: \"true\",\n\t\t\tkey:      \"build.exclude_unchanged\",\n\t\t},\n\t\t{\n\t\t\tname:     \"check int\",\n\t\t\targs:     []string{\"--build.kill_delay\", \"1000\"},\n\t\t\texpected: \"1000\",\n\t\t\tkey:      \"build.kill_delay\",\n\t\t},\n\t\t{\n\t\t\tname:     \"check exclude_regex\",\n\t\t\targs:     []string{\"--build.exclude_regex\", `[\"_test.go\"]`},\n\t\t\texpected: `[\"_test.go\"]`,\n\t\t\tkey:      \"build.exclude_regex\",\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tflag := flag.NewFlagSet(t.Name(), flag.ExitOnError)\n\t\t\tcmdArgs := ParseConfigFlag(flag)\n\t\t\trequire.NoError(t, flag.Parse(tc.args))\n\t\t\tassert.Equal(t, tc.expected, *cmdArgs[tc.key].Value)\n\t\t})\n\t}\n}\n\nfunc TestConfigRuntimeArgs(t *testing.T) {\n\t// table driven tests\n\ttype testCase struct {\n\t\tname  string\n\t\targs  []string\n\t\tkey   string\n\t\tcheck func(t *testing.T, conf *Config)\n\t}\n\ttestCases := []testCase{\n\t\t{\n\t\t\tname: \"test1\",\n\t\t\targs: []string{\"--build.cmd\", \"go build -o ./tmp/main .\"},\n\t\t\tkey:  \"build.cmd\",\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, \"go build -o ./tmp/main .\", conf.Build.Cmd)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"tmp dir test\",\n\t\t\targs: []string{\"--tmp_dir\", \"test\"},\n\t\t\tkey:  \"tmp_dir\",\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, \"test\", conf.TmpDir)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check int64\",\n\t\t\targs: []string{\"--build.kill_delay\", \"1000\"},\n\t\t\tkey:  \"build.kill_delay\",\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, time.Duration(1000), conf.Build.KillDelay)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check bool\",\n\t\t\targs: []string{\"--build.exclude_unchanged\", \"true\"},\n\t\t\tkey:  \"build.exclude_unchanged\",\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.True(t, conf.Build.ExcludeUnchanged)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check exclude_regex\",\n\t\t\targs: []string{\"--build.exclude_regex\", \"_test.go,.html\"},\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, []string{\"_test.go\", \".html\"}, conf.Build.ExcludeRegex)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check exclude_regex with empty string\",\n\t\t\targs: []string{\"--build.exclude_regex\", \"\"},\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, []string{}, conf.Build.ExcludeRegex)\n\t\t\t\tt.Logf(\"%+v\", conf.Build.ExcludeDir)\n\t\t\t\tassert.NotEqual(t, []string{}, conf.Build.ExcludeDir)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check full_bin\",\n\t\t\targs: []string{\"--build.full_bin\", \"APP_ENV=dev APP_USER=air ./tmp/main\"},\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\twant := \"APP_ENV=dev APP_USER=air ./tmp/main\"\n\t\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\t\twant += \".exe\"\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, want, conf.Build.Bin)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"check exclude_regex patterns compiled\",\n\t\t\targs: []string{\"--build.exclude_regex\", \"test_pattern\\\\.go\"},\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\tassert.Equal(t, []string{\"test_pattern\\\\.go\"}, conf.Build.ExcludeRegex)\n\t\t\t\tpatterns, err := conf.Build.RegexCompiled()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, patterns)\n\t\t\t\trequire.Len(t, patterns, 1)\n\t\t\t\tassert.True(t, patterns[0].MatchString(\"test_pattern.go\"), \"regex should match test_pattern.go\")\n\t\t\t\tassert.False(t, patterns[0].MatchString(\"other_file.go\"), \"regex shouldn't match other_file.go\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"check entrypoint flag\",\n\t\t\targs: []string{\"--build.entrypoint\", \"./tmp/server\"},\n\t\t\tcheck: func(t *testing.T, conf *Config) {\n\t\t\t\twant := filepath.Join(\"tmp\", \"server\")\n\t\t\t\tassert.True(t, strings.HasSuffix(conf.Build.Entrypoint.binary(), want), \"entrypoint %s does not end with %s\", conf.Build.Entrypoint.binary(), want)\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tdir := t.TempDir()\n\t\t\tchdir(t, dir)\n\t\t\tflag := flag.NewFlagSet(t.Name(), flag.ExitOnError)\n\t\t\tcmdArgs := ParseConfigFlag(flag)\n\t\t\t_ = flag.Parse(tc.args)\n\t\t\tcfg, err := InitConfig(\"\", cmdArgs)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttc.check(t, cfg)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "runner/logger.go",
    "content": "package runner\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/fatih/color\"\n)\n\nvar (\n\trawColor = \"raw\"\n\t// TODO: support more colors\n\tcolorMap = map[string]color.Attribute{\n\t\t\"red\":     color.FgRed,\n\t\t\"green\":   color.FgGreen,\n\t\t\"yellow\":  color.FgYellow,\n\t\t\"blue\":    color.FgBlue,\n\t\t\"magenta\": color.FgMagenta,\n\t\t\"cyan\":    color.FgCyan,\n\t\t\"white\":   color.FgWhite,\n\t}\n)\n\ntype logFunc func(string, ...interface{})\n\ntype logger struct {\n\tconfig  *Config\n\tcolors  map[string]string\n\tloggers map[string]logFunc\n}\n\nfunc newLogger(cfg *Config) *logger {\n\tif cfg == nil {\n\t\treturn nil\n\t}\n\n\tcolors := cfg.colorInfo()\n\tloggers := make(map[string]logFunc, len(colors))\n\tfor name, nameColor := range colors {\n\t\tloggers[name] = newLogFunc(nameColor, cfg.Log)\n\t}\n\tloggers[\"default\"] = defaultLogger()\n\treturn &logger{\n\t\tconfig:  cfg,\n\t\tcolors:  colors,\n\t\tloggers: loggers,\n\t}\n}\n\nfunc newLogFunc(colorname string, cfg cfgLog) logFunc {\n\treturn func(msg string, v ...interface{}) {\n\t\t// There are some escape sequences to format color in terminal, so cannot\n\t\t// just trim new line from right.\n\t\tif cfg.Silent {\n\t\t\treturn\n\t\t}\n\t\tmsg = strings.ReplaceAll(msg, \"\\n\", \"\")\n\t\tmsg = strings.TrimSpace(msg)\n\t\tif len(msg) == 0 {\n\t\t\treturn\n\t\t}\n\t\t// TODO: filter msg by regex\n\t\tmsg = msg + \"\\n\"\n\t\tif cfg.AddTime {\n\t\t\tt := time.Now().Format(\"15:04:05\")\n\t\t\tmsg = fmt.Sprintf(\"[%s] %s\", t, msg)\n\t\t}\n\t\tif colorname == rawColor {\n\t\t\tfmt.Fprintf(os.Stdout, msg, v...)\n\t\t} else {\n\t\t\tcolor.New(getColor(colorname)).Fprintf(color.Output, msg, v...)\n\t\t}\n\t}\n}\n\nfunc getColor(name string) color.Attribute {\n\tif v, ok := colorMap[name]; ok {\n\t\treturn v\n\t}\n\treturn color.FgWhite\n}\n\nfunc (l *logger) main() logFunc {\n\treturn l.getLogger(\"main\")\n}\n\nfunc (l *logger) build() logFunc {\n\treturn l.getLogger(\"build\")\n}\n\nfunc (l *logger) runner() logFunc {\n\treturn l.getLogger(\"runner\")\n}\n\nfunc (l *logger) watcher() logFunc {\n\treturn l.getLogger(\"watcher\")\n}\n\nfunc rawLogger() logFunc {\n\treturn newLogFunc(\"raw\", defaultConfig().Log)\n}\n\nfunc defaultLogger() logFunc {\n\treturn newLogFunc(\"white\", defaultConfig().Log)\n}\n\nfunc (l *logger) getLogger(name string) logFunc {\n\tv, ok := l.loggers[name]\n\tif !ok {\n\t\treturn rawLogger()\n\t}\n\treturn v\n}\n"
  },
  {
    "path": "runner/proxy.go",
    "content": "package runner\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"context\"\n\t_ \"embed\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/andybalholm/brotli\"\n)\n\nvar (\n\t//go:embed proxy.js\n\tProxyScript string\n\n\t//go:embed worker.js\n\tWorkerScript string\n)\n\ntype Streamer interface {\n\tAddSubscriber() *Subscriber\n\tRemoveSubscriber(id int32)\n\tReload()\n\tBuildFailed(msg BuildFailedMsg)\n\tStop()\n}\n\n// contentEncoding represents the type of content encoding used in HTTP responses.\ntype contentEncoding int\n\nconst (\n\tencodingNone contentEncoding = iota\n\tencodingGzip\n\tencodingBrotli\n)\n\ntype Proxy struct {\n\tserver *http.Server\n\tclient *http.Client\n\tconfig *cfgProxy\n\tstream Streamer\n}\n\nfunc NewProxy(cfg *cfgProxy) *Proxy {\n\tp := &Proxy{\n\t\tconfig: cfg,\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", cfg.ProxyPort),\n\t\t},\n\t\tclient: &http.Client{\n\t\t\tCheckRedirect: func(_ *http.Request, _ []*http.Request) error {\n\t\t\t\treturn http.ErrUseLastResponse\n\t\t\t},\n\t\t},\n\t\tstream: NewProxyStream(),\n\t}\n\treturn p\n}\n\nfunc (p *Proxy) Run() {\n\thttp.HandleFunc(\"/\", p.proxyHandler)\n\thttp.HandleFunc(\"/__air_internal/sse\", p.reloadHandler)\n\thttp.HandleFunc(\"GET /__air_internal/worker.js\", p.workerScriptHandler)\n\tif err := p.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\tlog.Fatal(p.Stop())\n\t}\n}\n\nfunc (p *Proxy) Reload() {\n\tp.stream.Reload()\n}\n\nfunc (p *Proxy) BuildFailed(msg BuildFailedMsg) {\n\tp.stream.BuildFailed(msg)\n}\n\nfunc (p *Proxy) injectLiveReload(resp *http.Response) (string, bool, error) {\n\tvar reader io.Reader = resp.Body\n\tdecoded := false\n\n\tswitch detectContentEncoding(resp.Header) {\n\tcase encodingGzip:\n\t\tgzipReader, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", false, fmt.Errorf(\"proxy inject: failed to init gzip reader: %w\", err)\n\t\t}\n\t\tdefer gzipReader.Close()\n\t\treader = gzipReader\n\t\tdecoded = true\n\tcase encodingBrotli:\n\t\treader = brotli.NewReader(resp.Body)\n\t\tdecoded = true\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tif _, err := buf.ReadFrom(reader); err != nil {\n\t\treturn \"\", decoded, fmt.Errorf(\"proxy inject: failed to read body from http response: %w\", err)\n\t}\n\tpage := buf.String()\n\n\t// the script will be injected before the end of the body tag. In case the tag is missing, the injection will be skipped with no error.\n\tbody := strings.LastIndex(page, \"</body>\")\n\tif body == -1 {\n\t\treturn page, decoded, nil\n\t}\n\n\tscript := \"<script>\" + ProxyScript + \"</script>\"\n\treturn page[:body] + script + page[body:], decoded, nil\n}\n\nfunc (p *Proxy) proxyHandler(w http.ResponseWriter, r *http.Request) {\n\tappURL := r.URL\n\tappURL.Scheme = \"http\"\n\tappURL.Host = fmt.Sprintf(\"localhost:%d\", p.config.AppPort)\n\n\tif err := r.ParseForm(); err != nil {\n\t\thttp.Error(w, \"proxy handler: bad form\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar body io.Reader\n\tif len(r.Form) > 0 {\n\t\tbody = strings.NewReader(r.Form.Encode())\n\t} else {\n\t\tbody = r.Body\n\t}\n\treq, err := http.NewRequest(r.Method, appURL.String(), body)\n\tif err != nil {\n\t\thttp.Error(w, \"proxy handler: unable to create request\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Copy the headers from the original request\n\tfor name, values := range r.Header {\n\t\tfor _, value := range values {\n\t\t\treq.Header.Add(name, value)\n\t\t}\n\t}\n\treq.Header.Set(\"X-Forwarded-For\", r.RemoteAddr)\n\n\t// set the via header\n\tviaHeaderValue := fmt.Sprintf(\"%s %s\", r.Proto, r.Host)\n\treq.Header.Set(\"Via\", viaHeaderValue)\n\n\t// air will restart the server. it may take a few seconds for it to start back up.\n\t// therefore, we retry until the server becomes available or this retry loop exits with an error.\n\ttimeout := time.Duration(p.config.AppStartTimeout) * time.Millisecond\n\tif timeout == 0 {\n\t\ttimeout = defaultProxyAppStartTimeout * time.Millisecond\n\t}\n\tctx, cancel := context.WithTimeout(r.Context(), timeout)\n\tdefer cancel()\n\n\tvar resp *http.Response\n\tresp, err = p.client.Do(req.WithContext(ctx))\n\tfor err != nil {\n\t\t// Check if timeout has been exceeded\n\t\tif ctx.Err() != nil {\n\t\t\terr = ctx.Err()\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tresp, err = p.client.Do(req.WithContext(ctx))\n\t}\n\tif err != nil {\n\t\thttp.Error(w, \"proxy handler: unable to reach app (try increasing the proxy.app_start_timeout)\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t// Copy the headers from the proxy response except Content-Length\n\tfor k, vv := range resp.Header {\n\t\tfor _, v := range vv {\n\t\t\tif k == \"Content-Length\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Header().Add(k, v)\n\t\t}\n\t}\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Via\", viaHeaderValue)\n\n\t// Determine if this is a streaming response\n\tstreaming := isStreamingResponse(resp)\n\n\t// Handle non-HTML responses\n\tif !strings.Contains(resp.Header.Get(\"Content-Type\"), \"text/html\") {\n\t\t// Check flusher support BEFORE writing headers for streaming responses\n\t\tvar flusher http.Flusher\n\t\tif streaming {\n\t\t\tvar ok bool\n\t\t\tflusher, ok = w.(http.Flusher)\n\t\t\tif !ok {\n\t\t\t\thttp.Error(w, \"proxy handler: streaming not supported\", http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// Set Content-Length only for non-streaming responses\n\t\tif !streaming {\n\t\t\tif cl := resp.Header.Get(\"Content-Length\"); cl != \"\" {\n\t\t\t\tw.Header().Set(\"Content-Length\", cl)\n\t\t\t}\n\t\t}\n\n\t\tw.WriteHeader(resp.StatusCode)\n\n\t\tif streaming {\n\t\t\t// Use streaming copy with immediate flushing\n\t\t\t_ = streamCopy(w, resp.Body, flusher)\n\t\t\treturn\n\t\t}\n\t\t// Use standard copy for non-streaming responses\n\t\tif _, err := io.Copy(w, resp.Body); err != nil {\n\t\t\thttp.Error(w, \"proxy handler: failed to forward the response body\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// HTML: inject live reload script\n\t\tpage, decoded, err := p.injectLiveReload(resp)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif decoded {\n\t\t\tw.Header().Del(\"Content-Encoding\")\n\t\t}\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa((len([]byte(page)))))\n\t\tw.WriteHeader(resp.StatusCode)\n\t\tif _, err := io.WriteString(w, page); err != nil {\n\t\t\thttp.Error(w, \"proxy handler: unable to inject live reload script\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// detectContentEncoding determines the content encoding type from HTTP headers.\n// Returns encodingNone for unsupported or multiple encodings (e.g., \"gzip, br\").\nfunc detectContentEncoding(header http.Header) contentEncoding {\n\tencoding := header.Get(\"Content-Encoding\")\n\tif encoding == \"\" {\n\t\treturn encodingNone\n\t}\n\n\t// Only support single encoding; multiple encodings (e.g., \"gzip, br\") are rare\n\t// and complex to handle, so we skip injection in those cases.\n\ttrimmed := strings.TrimSpace(strings.ToLower(encoding))\n\tswitch trimmed {\n\tcase \"gzip\", \"x-gzip\":\n\t\treturn encodingGzip\n\tcase \"br\":\n\t\treturn encodingBrotli\n\tdefault:\n\t\treturn encodingNone\n\t}\n}\n\nfunc (p *Proxy) reloadHandler(w http.ResponseWriter, r *http.Request) {\n\tflusher, err := w.(http.Flusher)\n\tif !err {\n\t\thttp.Error(w, \"reload handler: streaming unsupported\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\n\tsub := p.stream.AddSubscriber()\n\tgo func() {\n\t\t<-r.Context().Done()\n\t\tp.stream.RemoveSubscriber(sub.id)\n\t}()\n\n\tw.WriteHeader(http.StatusOK)\n\tflusher.Flush()\n\n\tfor msg := range sub.msgCh {\n\t\tfmt.Fprint(w, msg.AsSSE())\n\t\tflusher.Flush()\n\t}\n}\n\nfunc (p *Proxy) workerScriptHandler(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/javascript\")\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = io.WriteString(w, WorkerScript)\n}\n\nfunc (p *Proxy) Stop() error {\n\tp.stream.Stop()\n\treturn p.server.Close()\n}\n\n// isStreamingResponse determines if the response should be streamed immediately\n// without buffering. This applies to:\n// 1. Server-Sent Events (SSE): Content-Type contains \"text/event-stream\"\n// 2. Chunked transfer encoding: Transfer-Encoding is \"chunked\"\nfunc isStreamingResponse(resp *http.Response) bool {\n\t// Check for SSE\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif strings.Contains(contentType, \"text/event-stream\") {\n\t\treturn true\n\t}\n\n\t// Check for chunked encoding\n\ttransferEncoding := resp.Header.Get(\"Transfer-Encoding\")\n\treturn transferEncoding == \"chunked\"\n}\n\n// streamCopy copies data from src to dst, flushing after each read.\n// This ensures real-time delivery for streaming responses like SSE.\n// Uses a 512-byte buffer to balance between latency and performance.\nfunc streamCopy(dst io.Writer, src io.Reader, flusher http.Flusher) error {\n\t// Use 512-byte buffer for better responsiveness\n\tbuf := make([]byte, 512)\n\n\tfor {\n\t\tnr, readErr := src.Read(buf)\n\t\tif nr > 0 {\n\t\t\tnw, writeErr := dst.Write(buf[:nr])\n\t\t\tif writeErr != nil {\n\t\t\t\treturn writeErr\n\t\t\t}\n\t\t\tif nr != nw {\n\t\t\t\treturn io.ErrShortWrite\n\t\t\t}\n\n\t\t\t// Flush immediately after each write\n\t\t\tflusher.Flush()\n\t\t}\n\n\t\tif readErr != nil {\n\t\t\tif readErr == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn readErr\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runner/proxy.js",
    "content": "(() => {\n    let worker = null;\n\n    const disconnectWorker = () => {\n        if (worker) {\n            worker.port.postMessage('disconnect');\n        }\n    };\n\n    // Try to use SharedWorker for shared SSE connection across all windows\n    if (window.SharedWorker) {\n        try {\n            worker = new SharedWorker('/__air_internal/worker.js', { name: 'air-sse-worker' });\n            worker.port.onmessage = (event) => {\n                const message = event.data;\n\n                switch (message.type) {\n                    case 'reload':\n                        location.reload();\n                        break;\n                    case 'build-failed':\n                        const data = parseBuildFailed(message.data);\n                        showErrorInModal(data);\n                        break;\n                }\n            };\n            worker.port.start();\n\n            // Gracefully disconnect from SharedWorker when the window is closed\n            window.addEventListener('beforeunload', disconnectWorker);\n            window.addEventListener('pagehide', disconnectWorker);\n        } catch (e) {\n            // Setting up SharedWorker failed, so fall back to per-window EventSource\n            console.warn('air: SharedWorker setup failed, falling back to EventSource', e);\n            worker = null;\n        }\n    }\n\n    // SharedWorker is not available or failed somehow. Use per-window EventSource as fallback\n    if (!worker) {\n        const eventSource = new EventSource(\"/__air_internal/sse\");\n\n        window.addEventListener('beforeunload', function () {\n            eventSource.close();\n        });\n        window.addEventListener('pagehide', function () {\n            eventSource.close();\n        });\n\n        eventSource.addEventListener('reload', () => {\n            location.reload();\n        });\n\n        eventSource.addEventListener('build-failed', (event) => {\n            const data = parseBuildFailed(event.data);\n            showErrorInModal(data);\n        });\n    }\n\n    function parseBuildFailed(raw) {\n        try {\n            const parsed = JSON.parse(raw);\n            return {\n                error: parsed.error ?? \"Build failed\",\n                command: parsed.command ?? \"\",\n                output: parsed.output ?? \"\",\n            };\n        } catch (e) {\n            console.warn(\"air: failed to parse build-failed payload\", e);\n            return {\n                error: \"Build failed\",\n                command: \"\",\n                output: String(raw),\n            };\n        }\n    }\n\n    function showErrorInModal(data) {\n        document.body.insertAdjacentHTML(`beforeend`, `\n            <style>\n                .air__modal {\n                    display: none;\n                    position: fixed;\n                    z-index: 1000;\n                    left: 0;\n                    top: 0;\n                    width: 100%;\n                    height: 100%;\n                    background-color: rgba(0, 0, 0, 0.5);\n                    justify-content: center;\n                    align-items: center;\n                }\n                .air__modal-content {\n                    background-color: white;\n                    color: black;\n                    padding: 20px;\n                    border-radius: 5px;\n                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);\n                    width: 80%;\n                }\n                .air__modal-header {\n                    font-size: 1.5em;\n                    margin-bottom: 10px;\n                }\n                .air__modal-body {\n                    margin-bottom: 20px;\n                    overflow-x: auto;\n                }\n                .air__modal-close {\n                    background-color: #007bff;\n                    color: white;\n                    border: none;\n                    padding: 10px 15px;\n                    border-radius: 5px;\n                    cursor: pointer;\n                }\n                .air__modal pre {\n                    background-color: #1e1e1e;\n                    color: #f8f8f2;\n                    padding: 10px;\n                    border-radius: 5px;\n                    overflow-x: auto;\n                    white-space: pre;\n                }\n                .air__modal code {\n                    font-family: 'Courier New', Courier, monospace;\n                }\n            </style>\n            <div class=\"air__modal\" id=\"air__modal\">\n                <div class=\"air__modal-content\">\n                    <div class=\"air__modal-header\">Build Error</div>\n                    <div class=\"air__modal-body\" id=\"air__modal-body\"></div>\n                    <button class=\"air__modal-close\" id=\"air__modal-close\">Close</button>\n                </div>\n            </div>\n        `);\n        const modal = document.getElementById('air__modal');\n        const modalBody = document.getElementById('air__modal-body');\n        const modalClose = document.getElementById('air__modal-close');\n        modalBody.innerHTML = `\n            <strong>Build Cmd:</strong> <pre><code>${data.command}</code></pre><br>\n            <strong>Output:</strong> <pre><code>${data.output}</code></pre><br>\n            <strong>Error:</strong> <pre><code>${data.error}</code></pre>\n        `;\n        modal.style.display = 'flex';\n\n        modalClose.addEventListener('click', () => {\n            modal.style.display = 'none';\n        });\n    }\n})();\n"
  },
  {
    "path": "runner/proxy_stream.go",
    "content": "package runner\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype ProxyStream struct {\n\tmu          sync.Mutex\n\tsubscribers map[int32]*Subscriber\n\tcount       atomic.Int32\n}\n\ntype StreamMessageType string\n\nconst (\n\tStreamMessageReload      StreamMessageType = \"reload\"\n\tStreamMessageBuildFailed StreamMessageType = \"build-failed\"\n)\n\ntype StreamMessage struct {\n\tType StreamMessageType\n\tData interface{}\n}\n\ntype BuildFailedMsg struct {\n\tError   string `json:\"error\"`\n\tCommand string `json:\"command\"`\n\tOutput  string `json:\"output\"`\n}\n\ntype Subscriber struct {\n\tid    int32\n\tmsgCh chan StreamMessage\n}\n\nfunc NewProxyStream() *ProxyStream {\n\treturn &ProxyStream{subscribers: make(map[int32]*Subscriber)}\n}\n\nfunc (stream *ProxyStream) Stop() {\n\tfor id := range stream.subscribers {\n\t\tstream.RemoveSubscriber(id)\n\t}\n\tstream.count = atomic.Int32{}\n}\n\nfunc (stream *ProxyStream) AddSubscriber() *Subscriber {\n\tstream.mu.Lock()\n\tdefer stream.mu.Unlock()\n\tstream.count.Add(1)\n\n\tsub := &Subscriber{id: stream.count.Load(), msgCh: make(chan StreamMessage)}\n\tstream.subscribers[stream.count.Load()] = sub\n\treturn sub\n}\n\nfunc (stream *ProxyStream) RemoveSubscriber(id int32) {\n\tstream.mu.Lock()\n\tdefer stream.mu.Unlock()\n\n\tif _, ok := stream.subscribers[id]; ok {\n\t\tclose(stream.subscribers[id].msgCh)\n\t\tdelete(stream.subscribers, id)\n\t}\n}\n\nfunc (stream *ProxyStream) Reload() {\n\tfor _, sub := range stream.subscribers {\n\t\tsub.msgCh <- StreamMessage{\n\t\t\tType: StreamMessageReload,\n\t\t\tData: nil,\n\t\t}\n\t}\n}\n\nfunc (stream *ProxyStream) BuildFailed(err BuildFailedMsg) {\n\tfor _, sub := range stream.subscribers {\n\t\tsub.msgCh <- StreamMessage{\n\t\t\tType: StreamMessageBuildFailed,\n\t\t\tData: err,\n\t\t}\n\t}\n}\n\nfunc (m StreamMessage) AsSSE() string {\n\ts := \"event: \" + string(m.Type) + \"\\n\"\n\ts += \"data: \" + stringify(m.Data) + \"\\n\"\n\treturn s + \"\\n\"\n}\n\nfunc stringify(v any) string {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"{\\\"error\\\":\\\"Failed to marshal message: %s\\\"}\", err)\n\t}\n\treturn string(b)\n}\n"
  },
  {
    "path": "runner/proxy_stream_test.go",
    "content": "package runner\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc find(s map[int32]*Subscriber, id int32) bool {\n\tfor _, sub := range s {\n\t\tif sub.id == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TestProxyStream(t *testing.T) {\n\tstream := NewProxyStream()\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo func(_ int) {\n\t\t\tdefer wg.Done()\n\t\t\t_ = stream.AddSubscriber()\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\tif got, exp := len(stream.subscribers), 10; got != exp {\n\t\tt.Errorf(\"expect subscribers count to be %d, got %d\", exp, got)\n\t}\n\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tstream.Reload()\n\t\tdoneCh <- struct{}{}\n\t}()\n\n\tvar reloadCount atomic.Int32\n\tfor _, sub := range stream.subscribers {\n\t\twg.Add(1)\n\t\tgo func(sub *Subscriber) {\n\t\t\tdefer wg.Done()\n\t\t\t<-sub.msgCh\n\t\t\treloadCount.Add(1)\n\t\t}(sub)\n\t}\n\twg.Wait()\n\t<-doneCh\n\n\tif got, exp := reloadCount.Load(), int32(10); got != exp {\n\t\tt.Errorf(\"expect reloadCount %d, got %d\", exp, got)\n\t}\n\n\tstream.RemoveSubscriber(2)\n\tif find(stream.subscribers, 2) {\n\t\tt.Errorf(\"expected subscriber 2 not to be found\")\n\t}\n\n\tstream.AddSubscriber()\n\tif !find(stream.subscribers, 11) {\n\t\tt.Errorf(\"expected subscriber 11 to be found\")\n\t}\n\n\tstream.Stop()\n\tif got, exp := len(stream.subscribers), 0; got != exp {\n\t\tt.Errorf(\"expected subscribers count to be %d, got %d\", exp, got)\n\t}\n}\n\nfunc TestBuildFailureMessage(t *testing.T) {\n\tstream := NewProxyStream()\n\tsub := stream.AddSubscriber()\n\n\tmsg := BuildFailedMsg{\n\t\tError:   \"build failed\",\n\t\tCommand: \"go build\",\n\t\tOutput:  \"error output\",\n\t}\n\n\tgo stream.BuildFailed(msg)\n\n\treceived := <-sub.msgCh\n\tassert.Equal(t, StreamMessageBuildFailed, received.Type)\n\tassert.Equal(t, msg, received.Data)\n}\n"
  },
  {
    "path": "runner/proxy_test.go",
    "content": "package runner\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/andybalholm/brotli\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype reloader struct {\n\tsubCh    chan struct{}\n\treloadCh chan StreamMessage\n}\n\nfunc (r *reloader) AddSubscriber() *Subscriber {\n\tr.subCh <- struct{}{}\n\treturn &Subscriber{msgCh: r.reloadCh}\n}\n\nfunc (r *reloader) RemoveSubscriber(_ int32) {\n\tclose(r.subCh)\n}\n\nfunc (r *reloader) Reload()                    {}\nfunc (r *reloader) BuildFailed(BuildFailedMsg) {}\nfunc (r *reloader) Stop()                      {}\n\nvar proxyPort = 8090\n\nfunc getServerPort(t *testing.T, srv *httptest.Server) int {\n\tmockURL, err := url.Parse(srv.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tport, err := strconv.Atoi(mockURL.Port())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn port\n}\n\nfunc TestProxy_run(t *testing.T) {\n\t_ = os.Unsetenv(airWd)\n\tcfg := &cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: 1111,\n\t\tAppPort:   2222,\n\t}\n\tproxy := NewProxy(cfg)\n\tif proxy.config == nil {\n\t\tt.Fatal(\"config should not be nil\")\n\t}\n\tif proxy.server.Addr == \"\" {\n\t\tt.Fatal(\"server address should not be nil\")\n\t}\n\tgo func() {\n\t\tproxy.Run()\n\t}()\n\tif err := proxy.Stop(); err != nil {\n\t\tt.Errorf(\"failed stopping the proxy: %v\", err)\n\t}\n}\n\nfunc TestProxy_proxyHandler(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\treq    func() *http.Request\n\t\tassert func(*http.Request)\n\t}{\n\t\t{\n\t\t\tname: \"get_request_with_headers\",\n\t\t\treq: func() *http.Request {\n\t\t\t\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d\", proxyPort), nil)\n\t\t\t\treq.Header.Set(\"foo\", \"bar\")\n\t\t\t\treturn req\n\t\t\t},\n\t\t\tassert: func(resp *http.Request) {\n\t\t\t\tassert.Equal(t, \"bar\", resp.Header.Get(\"foo\"))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"post_form_request\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tformData := url.Values{}\n\t\t\t\tformData.Add(\"foo\", \"bar\")\n\t\t\t\treq := httptest.NewRequest(\"POST\", fmt.Sprintf(\"http://localhost:%d\", proxyPort), strings.NewReader(formData.Encode()))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t\t\t\treturn req\n\t\t\t},\n\t\t\tassert: func(resp *http.Request) {\n\t\t\t\trequire.NoError(t, resp.ParseForm())\n\t\t\t\tassert.Equal(t, \"bar\", resp.Form.Get(\"foo\"))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"get_request_with_query_string\",\n\t\t\treq: func() *http.Request {\n\t\t\t\treturn httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d?q=%s\", proxyPort, \"air\"), nil)\n\t\t\t},\n\t\t\tassert: func(resp *http.Request) {\n\t\t\t\tq := resp.URL.Query()\n\t\t\t\tassert.Equal(t, \"q=air\", q.Encode())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"put_json_request\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tbody := []byte(`{\"foo\": \"bar\"}`)\n\t\t\t\treq := httptest.NewRequest(\"PUT\", fmt.Sprintf(\"http://localhost:%d/a/b/c\", proxyPort), bytes.NewBuffer(body))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\t\treturn req\n\t\t\t},\n\t\t\tassert: func(resp *http.Request) {\n\t\t\t\ttype Response struct {\n\t\t\t\t\tFoo string `json:\"foo\"`\n\t\t\t\t}\n\t\t\t\tvar r Response\n\t\t\t\trequire.NoError(t, json.NewDecoder(resp.Body).Decode(&r))\n\t\t\t\tassert.Equal(t, \"/a/b/c\", resp.URL.Path)\n\t\t\t\tassert.Equal(t, \"bar\", r.Foo)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set_via_header\",\n\t\t\treq: func() *http.Request {\n\t\t\t\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d\", proxyPort), nil)\n\t\t\t\treturn req\n\t\t\t},\n\t\t\tassert: func(resp *http.Request) {\n\t\t\t\tassert.Equal(t, fmt.Sprintf(\"HTTP/1.1 localhost:%d\", proxyPort), resp.Header.Get(\"Via\"))\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {\n\t\t\t\ttt.assert(r)\n\t\t\t}))\n\t\t\tdefer srv.Close()\n\t\t\tsrvPort := getServerPort(t, srv)\n\t\t\tproxy := NewProxy(&cfgProxy{\n\t\t\t\tEnabled:   true,\n\t\t\t\tProxyPort: proxyPort,\n\t\t\t\tAppPort:   srvPort,\n\t\t\t})\n\t\t\tproxy.proxyHandler(httptest.NewRecorder(), tt.req())\n\t\t})\n\t}\n}\n\nfunc TestProxy_injectLiveReload(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tgiven  *http.Response\n\t\texpect string\n\t}{\n\t\t{\n\t\t\tname: \"when_no_body_should_not_be_injected\",\n\t\t\tgiven: &http.Response{\n\t\t\t\tProto:      \"HTTP/1.1\",\n\t\t\t\tProtoMajor: 1,\n\t\t\t\tProtoMinor: 1,\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody:       http.NoBody,\n\t\t\t},\n\t\t\texpect: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"when_missing_body_should_not_be_injected\",\n\t\t\tgiven: &http.Response{\n\t\t\t\tProto:      \"HTTP/1.1\",\n\t\t\t\tProtoMajor: 1,\n\t\t\t\tProtoMinor: 1,\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text/html\"},\n\t\t\t\t},\n\t\t\t\tBody: io.NopCloser(strings.NewReader(`<h1>test</h1>`)),\n\t\t\t},\n\t\t\texpect: \"<h1>test</h1>\",\n\t\t},\n\t\t{\n\t\t\tname: \"when_text_html_and_body_is_present_should_be_injected\",\n\t\t\tgiven: &http.Response{\n\t\t\t\tProto:      \"HTTP/1.1\",\n\t\t\t\tProtoMajor: 1,\n\t\t\t\tProtoMinor: 1,\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text/html\"},\n\t\t\t\t},\n\t\t\t\tBody: io.NopCloser(strings.NewReader(`<body><h1>test</h1></body>`)),\n\t\t\t},\n\t\t\texpect: fmt.Sprintf(`<body><h1>test</h1><script>%s</script></body>`, ProxyScript),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tproxy := NewProxy(&cfgProxy{\n\t\t\t\tEnabled:   true,\n\t\t\t\tProxyPort: 1111,\n\t\t\t\tAppPort:   2222,\n\t\t\t})\n\t\t\tgot, _, _ := proxy.injectLiveReload(tt.given)\n\t\t\tif got != tt.expect {\n\t\t\t\t// Use a more descriptive error message\n\t\t\t\tif len(got) > 100 || len(tt.expect) > 100 {\n\t\t\t\t\tt.Errorf(\"Script injection mismatch.\\nGot length: %d\\nExpected length: %d\",\n\t\t\t\t\t\tlen(got), len(tt.expect))\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"expected page %+v, got %v\", tt.expect, got)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestProxy_reloadHandler(t *testing.T) {\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tfmt.Fprint(w, \"thin air\")\n\t}))\n\tsrvPort := getServerPort(t, srv)\n\tdefer srv.Close()\n\n\treloader := &reloader{subCh: make(chan struct{}), reloadCh: make(chan StreamMessage)}\n\tcfg := &cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t}\n\tproxy := &Proxy{\n\t\tconfig: cfg,\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\"localhost:%d\", proxyPort),\n\t\t},\n\t\tstream: reloader,\n\t}\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/internal/reload\", proxyPort), nil)\n\trec := httptest.NewRecorder()\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tproxy.reloadHandler(rec, req)\n\t}()\n\n\t<-reloader.subCh\n\n\treloader.reloadCh <- StreamMessage{\n\t\tType: StreamMessageReload,\n\t\tData: nil,\n\t}\n\tclose(reloader.reloadCh)\n\twg.Wait()\n\n\tif !rec.Flushed {\n\t\tt.Errorf(\"request should have been flushed\")\n\t}\n\n\tresp := rec.Result()\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Errorf(\"reading body: %v\", err)\n\t}\n\n\texpected := \"event: reload\\ndata: null\\n\\n\"\n\tif got := string(bodyBytes); got != expected {\n\t\tt.Errorf(\"expected %q but got %q\", expected, got)\n\t}\n\n\texpectedHeaders := map[string]string{\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Content-Type\":                \"text/event-stream\",\n\t\t\"Cache-Control\":               \"no-cache\",\n\t\t\"Connection\":                  \"keep-alive\",\n\t}\n\n\tfor key, value := range expectedHeaders {\n\t\tif got := resp.Header.Get(key); got != value {\n\t\t\tt.Errorf(\"expected header %s to be %q but got %q\", key, value, got)\n\t\t}\n\t}\n}\n\nfunc TestProxy_proxyHandler_GzipHTML(t *testing.T) {\n\tbody := \"<body><h1>gzip</h1></body>\"\n\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgzipWriter := gzip.NewWriter(w)\n\t\tif _, err := io.WriteString(gzipWriter, body); err != nil {\n\t\t\tt.Errorf(\"write gzip body: %v\", err)\n\t\t}\n\t\tif err := gzipWriter.Close(); err != nil {\n\t\t\tt.Errorf(\"close gzip writer: %v\", err)\n\t\t}\n\t}))\n\tdefer srv.Close()\n\n\tsrvPort := getServerPort(t, srv)\n\tproxy := NewProxy(&cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t})\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/\", proxyPort), nil)\n\treq.Header.Set(\"Accept-Encoding\", \"gzip\")\n\trec := httptest.NewRecorder()\n\tproxy.proxyHandler(rec, req)\n\n\tresp := rec.Result()\n\tdefer resp.Body.Close()\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\tassert.Empty(t, resp.Header.Get(\"Content-Encoding\"))\n\n\tresponseBody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\tassert.Contains(t, string(responseBody), ProxyScript)\n}\n\nfunc TestProxy_proxyHandler_BrotliHTML(t *testing.T) {\n\tbody := \"<body><h1>brotli</h1></body>\"\n\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tw.Header().Set(\"Content-Encoding\", \"br\")\n\t\tbrotliWriter := brotli.NewWriter(w)\n\t\tif _, err := io.WriteString(brotliWriter, body); err != nil {\n\t\t\tt.Errorf(\"write brotli body: %v\", err)\n\t\t}\n\t\tif err := brotliWriter.Close(); err != nil {\n\t\t\tt.Errorf(\"close brotli writer: %v\", err)\n\t\t}\n\t}))\n\tdefer srv.Close()\n\n\tsrvPort := getServerPort(t, srv)\n\tproxy := NewProxy(&cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t})\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/\", proxyPort), nil)\n\treq.Header.Set(\"Accept-Encoding\", \"br\")\n\trec := httptest.NewRecorder()\n\tproxy.proxyHandler(rec, req)\n\n\tresp := rec.Result()\n\tdefer resp.Body.Close()\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\tassert.Empty(t, resp.Header.Get(\"Content-Encoding\"))\n\n\tresponseBody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\tassert.Contains(t, string(responseBody), ProxyScript)\n}\n\nfunc TestDetectContentEncoding(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tencoding string\n\t\texpected contentEncoding\n\t}{\n\t\t{name: \"empty\", encoding: \"\", expected: encodingNone},\n\t\t{name: \"gzip\", encoding: \"gzip\", expected: encodingGzip},\n\t\t{name: \"x-gzip\", encoding: \"x-gzip\", expected: encodingGzip},\n\t\t{name: \"gzip_uppercase\", encoding: \"GZIP\", expected: encodingGzip},\n\t\t{name: \"brotli\", encoding: \"br\", expected: encodingBrotli},\n\t\t{name: \"brotli_uppercase\", encoding: \"BR\", expected: encodingBrotli},\n\t\t{name: \"deflate_unsupported\", encoding: \"deflate\", expected: encodingNone},\n\t\t{name: \"multiple_encodings\", encoding: \"gzip, br\", expected: encodingNone},\n\t\t{name: \"unknown\", encoding: \"unknown\", expected: encodingNone},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\theader := http.Header{}\n\t\t\tif tt.encoding != \"\" {\n\t\t\t\theader.Set(\"Content-Encoding\", tt.encoding)\n\t\t\t}\n\t\t\tresult := detectContentEncoding(header)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestProxy_proxyHandler_SSE(t *testing.T) {\n\tevents := []string{\n\t\t\"event: message\\ndata: {\\\"id\\\":1}\\n\\n\",\n\t\t\"event: message\\ndata: {\\\"id\\\":2}\\n\\n\",\n\t}\n\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\tw.Header().Set(\"Connection\", \"keep-alive\")\n\t\tflusher, ok := w.(http.Flusher)\n\t\tif !ok {\n\t\t\tt.Fatal(\"expected flusher\")\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfor _, event := range events {\n\t\t\tfmt.Fprint(w, event)\n\t\t\tflusher.Flush()\n\t\t}\n\t}))\n\tdefer srv.Close()\n\n\tsrvPort := getServerPort(t, srv)\n\tproxy := NewProxy(&cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t})\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/events\", proxyPort), nil)\n\trec := httptest.NewRecorder()\n\tproxy.proxyHandler(rec, req)\n\n\tresp := rec.Result()\n\tdefer resp.Body.Close()\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\tassert.Equal(t, \"text/event-stream\", resp.Header.Get(\"Content-Type\"))\n\n\tbody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\n\texpected := strings.Join(events, \"\")\n\tassert.Equal(t, expected, string(body))\n}\n\nfunc TestIsStreamingResponse(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\theaders  http.Header\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname: \"SSE content type\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Content-Type\": []string{\"text/event-stream\"},\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"SSE with charset\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Content-Type\": []string{\"text/event-stream; charset=utf-8\"},\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"chunked encoding\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Transfer-Encoding\": []string{\"chunked\"},\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"both SSE and chunked\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Content-Type\":      []string{\"text/event-stream\"},\n\t\t\t\t\"Transfer-Encoding\": []string{\"chunked\"},\n\t\t\t},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"regular JSON\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Content-Type\": []string{\"application/json\"},\n\t\t\t},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"regular HTML\",\n\t\t\theaders: http.Header{\n\t\t\t\t\"Content-Type\": []string{\"text/html\"},\n\t\t\t},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"no headers\",\n\t\t\theaders:  http.Header{},\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresp := &http.Response{\n\t\t\t\tHeader: tt.headers,\n\t\t\t}\n\t\t\tresult := isStreamingResponse(resp)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\n// mockFlusher is a simple mock implementation of http.Flusher for testing\ntype mockFlusher struct {\n\tflushed bool\n}\n\nfunc (m *mockFlusher) Flush() {\n\tm.flushed = true\n}\n\nfunc TestStreamCopy(t *testing.T) {\n\tt.Run(\"copies data and flushes\", func(t *testing.T) {\n\t\tdata := []byte(\"test data for streaming\")\n\t\tsrc := bytes.NewReader(data)\n\t\tdst := &bytes.Buffer{}\n\t\tflusher := &mockFlusher{}\n\n\t\terr := streamCopy(dst, src, flusher)\n\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, data, dst.Bytes())\n\t\tassert.True(t, flusher.flushed, \"should have called Flush\")\n\t})\n\n\tt.Run(\"handles empty source\", func(t *testing.T) {\n\t\tsrc := bytes.NewReader([]byte{})\n\t\tdst := &bytes.Buffer{}\n\t\tflusher := &mockFlusher{}\n\n\t\terr := streamCopy(dst, src, flusher)\n\n\t\trequire.NoError(t, err)\n\t\tassert.Empty(t, dst.Bytes())\n\t})\n\n\tt.Run(\"handles large data\", func(t *testing.T) {\n\t\t// Create data larger than buffer size (512 bytes)\n\t\tdata := bytes.Repeat([]byte(\"x\"), 2048)\n\t\tsrc := bytes.NewReader(data)\n\t\tdst := &bytes.Buffer{}\n\t\tflusher := &mockFlusher{}\n\n\t\terr := streamCopy(dst, src, flusher)\n\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, data, dst.Bytes())\n\t\tassert.True(t, flusher.flushed)\n\t})\n}\n\nfunc TestProxy_proxyHandler_Chunked(t *testing.T) {\n\tchunks := []string{\"chunk1\", \"chunk2\", \"chunk3\"}\n\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\t\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\n\t\tflusher, ok := w.(http.Flusher)\n\t\tassert.True(t, ok, \"expected flusher\")\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfor _, chunk := range chunks {\n\t\t\tfmt.Fprint(w, chunk)\n\t\t\tflusher.Flush()\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t}))\n\tdefer srv.Close()\n\n\tsrvPort := getServerPort(t, srv)\n\tproxy := NewProxy(&cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t})\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/stream\", proxyPort), nil)\n\trec := httptest.NewRecorder()\n\tproxy.proxyHandler(rec, req)\n\n\tresp := rec.Result()\n\tdefer resp.Body.Close()\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\t// Note: httptest.ResponseRecorder may not preserve Transfer-Encoding header\n\t// but the actual HTTP response will work correctly\n\tassert.Empty(t, resp.Header.Get(\"Content-Length\"), \"streaming response should not have Content-Length\")\n\n\tbody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"chunk1chunk2chunk3\", string(body))\n}\n\nfunc TestProxy_proxyHandler_NonStreaming(t *testing.T) {\n\tcontent := \"regular response content\"\n\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(content)))\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprint(w, content)\n\t}))\n\tdefer srv.Close()\n\n\tsrvPort := getServerPort(t, srv)\n\tproxy := NewProxy(&cfgProxy{\n\t\tEnabled:   true,\n\t\tProxyPort: proxyPort,\n\t\tAppPort:   srvPort,\n\t})\n\n\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/api\", proxyPort), nil)\n\trec := httptest.NewRecorder()\n\tproxy.proxyHandler(rec, req)\n\n\tresp := rec.Result()\n\tdefer resp.Body.Close()\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\tassert.Equal(t, \"application/json\", resp.Header.Get(\"Content-Type\"))\n\tassert.Equal(t, strconv.Itoa(len(content)), resp.Header.Get(\"Content-Length\"))\n\n\tbody, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\tassert.Equal(t, content, string(body))\n}\n\nfunc TestProxy_appStartTimeout(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tappStartDelay   int // milliseconds - simulated app startup delay\n\t\tconfigTimeout   int // milliseconds - configured timeout (0 = use default)\n\t\texpectSuccess   bool\n\t\texpectInBody    string\n\t\texpectNotInBody string\n\t}{\n\t\t{\n\t\t\tname:          \"fast_startup_succeeds\",\n\t\t\tappStartDelay: 50,\n\t\t\tconfigTimeout: 1000,\n\t\t\texpectSuccess: true,\n\t\t\texpectInBody:  \"OK\",\n\t\t},\n\t\t{\n\t\t\tname:          \"slow_startup_within_timeout_succeeds\",\n\t\t\tappStartDelay: 500,\n\t\t\tconfigTimeout: 1000,\n\t\t\texpectSuccess: true,\n\t\t\texpectInBody:  \"OK\",\n\t\t},\n\t\t{\n\t\t\tname:            \"slow_startup_exceeds_timeout_fails\",\n\t\t\tappStartDelay:   1500,\n\t\t\tconfigTimeout:   500,\n\t\t\texpectSuccess:   false,\n\t\t\texpectInBody:    \"unable to reach app\",\n\t\t\texpectNotInBody: \"OK\",\n\t\t},\n\t\t{\n\t\t\tname:          \"uses_default_timeout_when_zero\",\n\t\t\tappStartDelay: 500,\n\t\t\tconfigTimeout: 0, // Should use defaultProxyAppStartTimeout (5000ms)\n\t\t\texpectSuccess: true,\n\t\t\texpectInBody:  \"OK\",\n\t\t},\n\t\t{\n\t\t\tname:          \"custom_timeout_respected\",\n\t\t\tappStartDelay: 800,\n\t\t\tconfigTimeout: 1000,\n\t\t\texpectSuccess: true,\n\t\t\texpectInBody:  \"OK\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Track whether server has \"started\"\n\t\t\tvar serverReady sync.WaitGroup\n\t\t\tserverReady.Add(1)\n\n\t\t\t// Create a test server that delays before responding\n\t\t\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\t\t// Wait for simulated startup delay on first request\n\t\t\t\tserverReady.Wait()\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\tfmt.Fprint(w, \"OK\")\n\t\t\t}))\n\t\t\tdefer srv.Close()\n\n\t\t\t// Simulate app startup delay in background\n\t\t\tgo func() {\n\t\t\t\tif tt.appStartDelay > 0 {\n\t\t\t\t\t// Sleep to simulate app initialization time\n\t\t\t\t\ttime.Sleep(time.Duration(tt.appStartDelay) * time.Millisecond)\n\t\t\t\t}\n\t\t\t\tserverReady.Done()\n\t\t\t}()\n\n\t\t\tsrvPort := getServerPort(t, srv)\n\t\t\tproxy := NewProxy(&cfgProxy{\n\t\t\t\tEnabled:         true,\n\t\t\t\tProxyPort:       proxyPort,\n\t\t\t\tAppPort:         srvPort,\n\t\t\t\tAppStartTimeout: tt.configTimeout,\n\t\t\t})\n\n\t\t\treq := httptest.NewRequest(\"GET\", fmt.Sprintf(\"http://localhost:%d/\", proxyPort), nil)\n\t\t\trec := httptest.NewRecorder()\n\n\t\t\tproxy.proxyHandler(rec, req)\n\n\t\t\tresp := rec.Result()\n\t\t\tbodyBytes, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\t\t\tbody := string(bodyBytes)\n\n\t\t\tif tt.expectSuccess {\n\t\t\t\tassert.Equal(t, http.StatusOK, resp.StatusCode, \"expected successful response\")\n\t\t\t\tassert.Contains(t, body, tt.expectInBody, \"response body should contain expected content\")\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, http.StatusInternalServerError, resp.StatusCode, \"expected error response\")\n\t\t\t\tassert.Contains(t, body, tt.expectInBody, \"error message should contain expected text\")\n\t\t\t\tif tt.expectNotInBody != \"\" {\n\t\t\t\t\tassert.NotContains(t, body, tt.expectNotInBody, \"response should not contain unexpected content\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "runner/test_util.go",
    "content": "// Package runner …\npackage runner\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc chdir(t *testing.T, targetDir string) {\n\toriginalDir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to getwd: %v\", err)\n\t}\n\tif err := os.Chdir(targetDir); err != nil {\n\t\tt.Fatalf(\"failed to change working directory: %v\", err)\n\t}\n\tt.Cleanup(func() {\n\t\tif err := os.Chdir(originalDir); err != nil {\n\t\t\tt.Fatalf(\"failed to restore working directory: %v\", err)\n\t\t}\n\t})\n}\n\n// waitForCondition waits for a condition to be true with fast polling.\n// Uses environment-aware timeout multiplier for CI compatibility.\nfunc waitForCondition(t *testing.T, timeout time.Duration, condition func() bool, description string) error {\n\tt.Helper()\n\n\t// CI environments may be slower, use 2x timeout\n\ttimeoutMultiplier := 1.0\n\tif os.Getenv(\"CI\") != \"\" {\n\t\ttimeoutMultiplier = 2.0\n\t}\n\n\tadjustedTimeout := time.Duration(float64(timeout) * timeoutMultiplier)\n\tdeadline := time.Now().Add(adjustedTimeout)\n\tticker := time.NewTicker(20 * time.Millisecond) // Fast polling: 20ms\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tif condition() {\n\t\t\treturn nil\n\t\t}\n\t\tif time.Now().After(deadline) {\n\t\t\treturn fmt.Errorf(\"timeout waiting for: %s (timeout: %v)\", description, adjustedTimeout)\n\t\t}\n\t\t<-ticker.C\n\t}\n}\n\n// waitForEngineState waits for engine to reach the specified running state.\nfunc waitForEngineState(t *testing.T, engine *Engine, running bool, timeout time.Duration) error {\n\tt.Helper()\n\treturn waitForCondition(t, timeout, func() bool {\n\t\treturn engine.running.Load() == running\n\t}, fmt.Sprintf(\"engine running=%v\", running))\n}\n"
  },
  {
    "path": "runner/util.go",
    "content": "package runner\n\nimport (\n\t\"bufio\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/fsnotify/fsnotify\"\n)\n\nconst (\n\tsliceCmdArgSeparator = \",\"\n\t// extWildcard is used in include_ext to match all file extensions\n\textWildcard = \"*\"\n)\n\nfunc (e *Engine) mainLog(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\te.logWithLock(func() {\n\t\te.logger.main()(format, v...)\n\t})\n}\n\nfunc (e *Engine) mainDebug(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\tif e.debugMode {\n\t\te.mainLog(format, v...)\n\t}\n}\n\nfunc (e *Engine) buildLog(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\tif e.debugMode || !e.config.Log.MainOnly {\n\t\te.logWithLock(func() {\n\t\t\te.logger.build()(format, v...)\n\t\t})\n\t}\n}\n\nfunc (e *Engine) runnerLog(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\tif e.debugMode || !e.config.Log.MainOnly {\n\t\te.logWithLock(func() {\n\t\t\te.logger.runner()(format, v...)\n\t\t})\n\t}\n}\n\nfunc (e *Engine) watcherLog(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\tif e.debugMode || !e.config.Log.MainOnly {\n\t\te.logWithLock(func() {\n\t\t\te.logger.watcher()(format, v...)\n\t\t})\n\t}\n}\n\nfunc (e *Engine) watcherDebug(format string, v ...interface{}) {\n\tif e.config.Log.Silent {\n\t\treturn\n\t}\n\tif e.debugMode {\n\t\te.watcherLog(format, v...)\n\t}\n}\n\nfunc (e *Engine) isTmpDir(path string) bool {\n\treturn path == e.config.tmpPath()\n}\n\nfunc (e *Engine) isTestDataDir(path string) bool {\n\treturn path == e.config.testDataPath()\n}\n\nfunc isHiddenDirectory(path string) bool {\n\treturn len(path) > 1 && strings.HasPrefix(filepath.Base(path), \".\") && filepath.Base(path) != \"..\"\n}\n\nfunc cleanPath(path string) string {\n\treturn strings.TrimSuffix(strings.TrimSpace(path), \"/\")\n}\n\nfunc isSubPath(base, target string) bool {\n\tif base == \"\" || target == \"\" {\n\t\treturn false\n\t}\n\tbase = filepath.Clean(base)\n\ttarget = filepath.Clean(target)\n\trel, err := filepath.Rel(base, target)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif rel == \".\" {\n\t\treturn true\n\t}\n\trel = filepath.Clean(rel)\n\tprefix := \"..\" + string(os.PathSeparator)\n\treturn rel != \"..\" && !strings.HasPrefix(rel, prefix)\n}\n\nfunc (e *Engine) isExcludeDir(path string) bool {\n\tcleanName := cleanPath(e.config.rel(path))\n\tfor _, d := range e.config.Build.ExcludeDir {\n\t\tif cleanName == d {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// return isIncludeDir, walkDir\nfunc (e *Engine) checkIncludeDir(path string) (bool, bool) {\n\tpath = filepath.Clean(path)\n\n\tif len(e.config.Build.includeDirAbs) == 0 {\n\t\treturn true, true\n\t}\n\n\tif !isSubPath(e.config.Root, path) {\n\t\treturn true, true\n\t}\n\n\twalkDir := false\n\tfor _, dir := range e.config.Build.includeDirAbs {\n\t\tdir = filepath.Clean(dir)\n\t\tif isSubPath(dir, path) {\n\t\t\treturn true, true\n\t\t}\n\t\tif isSubPath(path, dir) {\n\t\t\twalkDir = true\n\t\t}\n\t}\n\treturn false, walkDir\n}\n\nfunc (e *Engine) checkIncludeFile(path string) bool {\n\tcleanName := cleanPath(e.config.rel(path))\n\tiFile := e.config.Build.IncludeFile\n\tif len(iFile) == 0 { // ignore empty\n\t\treturn false\n\t}\n\tif cleanName == \".\" {\n\t\treturn false\n\t}\n\tfor _, d := range iFile {\n\t\tif d == cleanName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (e *Engine) isIncludeExt(path string) bool {\n\text := filepath.Ext(path)\n\tfor _, v := range e.config.Build.IncludeExt {\n\t\tif strings.TrimSpace(v) == extWildcard {\n\t\t\t// Wildcard matches all files, but exclude the binary file\n\t\t\treturn !e.isBinPath(path)\n\t\t}\n\t\tif ext == \".\"+strings.TrimSpace(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// isBinPath checks if the given path is the binary file path\nfunc (e *Engine) isBinPath(path string) bool {\n\tbinPath := e.config.binPath()\n\tif binPath == \"\" {\n\t\treturn false\n\t}\n\t// Normalize the path for comparison\n\tabsPath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\tabsBinPath, err := filepath.Abs(binPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn absPath == absBinPath\n}\n\nfunc (e *Engine) isExcludeRegex(path string) (bool, error) {\n\tregexes, err := e.config.Build.RegexCompiled()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, re := range regexes {\n\t\tif re.Match([]byte(path)) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc (e *Engine) isExcludeFile(path string) bool {\n\tcleanName := cleanPath(e.config.rel(path))\n\tfor _, d := range e.config.Build.ExcludeFile {\n\t\tmatched, err := filepath.Match(d, cleanName)\n\t\tif err == nil && matched {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (e *Engine) writeBuildErrorLog(msg string) error {\n\tvar err error\n\tf, err := os.OpenFile(e.config.buildLogPath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = f.Write([]byte(msg)); err != nil {\n\t\treturn err\n\t}\n\treturn f.Close()\n}\n\nfunc (e *Engine) withLock(f func()) {\n\te.mu.Lock()\n\tf()\n\te.mu.Unlock()\n}\n\nfunc (e *Engine) logWithLock(f func()) {\n\te.ll.Lock()\n\tf()\n\te.ll.Unlock()\n}\n\nfunc copyOutput(dst io.Writer, src io.Reader) {\n\tscanner := bufio.NewScanner(src)\n\tfor scanner.Scan() {\n\t\t_, _ = dst.Write([]byte(scanner.Text() + \"\\n\"))\n\t}\n}\n\nfunc expandPath(path string) (string, error) {\n\tif strings.HasPrefix(path, \"~/\") {\n\t\thome := os.Getenv(\"HOME\")\n\t\treturn home + path[1:], nil\n\t}\n\tvar err error\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif path == \".\" {\n\t\treturn wd, nil\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\treturn wd + path[1:], nil\n\t}\n\treturn path, nil\n}\n\nfunc isDir(path string) bool {\n\ti, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn i.IsDir()\n}\n\nfunc validEvent(ev fsnotify.Event) bool {\n\treturn ev.Op&fsnotify.Create == fsnotify.Create ||\n\t\tev.Op&fsnotify.Write == fsnotify.Write ||\n\t\tev.Op&fsnotify.Remove == fsnotify.Remove\n}\n\nfunc removeEvent(ev fsnotify.Event) bool {\n\treturn ev.Op&fsnotify.Remove == fsnotify.Remove\n}\n\nfunc cmdPath(path string) string {\n\treturn strings.Split(path, \" \")[0]\n}\n\nfunc adaptToVariousPlatforms(c *Config) {\n\t// Fix the default configuration is not used in Windows\n\t// Use the unix configuration on Windows\n\tif runtime.GOOS == PlatformWindows {\n\t\textName := \".exe\"\n\t\toriginBin := c.Build.Bin\n\n\t\tif 0 < len(c.Build.FullBin) {\n\n\t\t\tif !strings.HasSuffix(c.Build.FullBin, extName) {\n\t\t\t\tc.Build.FullBin += extName\n\t\t\t}\n\t\t}\n\n\t\t// bin=/tmp/main  cmd=go build -o ./tmp/main.exe main.go\n\t\tif !strings.Contains(c.Build.Cmd, c.Build.Bin) && strings.Contains(c.Build.Cmd, originBin) {\n\t\t\tc.Build.Cmd = strings.Replace(c.Build.Cmd, originBin, c.Build.Bin, 1)\n\t\t}\n\t}\n}\n\n// fileChecksum returns a checksum for the given file's contents.\nfunc fileChecksum(filename string) (checksum string, err error) {\n\tcontents, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// If the file is empty, an editor might've been in the process of rewriting the file when we read it.\n\t// This can happen often if editors are configured to run format after save.\n\t// Instead of calculating a new checksum, we'll assume the file was unchanged, but return an error to force a rebuild anyway.\n\tif len(contents) == 0 {\n\t\treturn \"\", errors.New(\"empty file, forcing rebuild without updating checksum\")\n\t}\n\n\th := sha256.New()\n\tif _, err := h.Write(contents); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn hex.EncodeToString(h.Sum(nil)), nil\n}\n\n// checksumMap is a thread-safe map to store file checksums.\ntype checksumMap struct {\n\tl sync.Mutex\n\tm map[string]string\n}\n\n// updateFileChecksum updates the filename with the given checksum if different.\nfunc (a *checksumMap) updateFileChecksum(filename, newChecksum string) (ok bool) {\n\ta.l.Lock()\n\tdefer a.l.Unlock()\n\toldChecksum, ok := a.m[filename]\n\tif !ok || oldChecksum != newChecksum {\n\t\ta.m[filename] = newChecksum\n\t\treturn true\n\t}\n\treturn false\n}\n\n// TomlInfo is a struct for toml config file\ntype TomlInfo struct {\n\tfieldPath  string\n\tfield      reflect.StructField\n\tValue      *string\n\tfieldValue string\n\tusage      string\n}\n\nfunc setValue2Struct(v reflect.Value, fieldName string, value string) {\n\tindex := strings.Index(fieldName, \".\")\n\tif index == -1 && len(fieldName) == 0 {\n\t\treturn\n\t}\n\tfields := strings.Split(fieldName, \".\")\n\tvar addressableVal reflect.Value\n\tswitch v.Type().String() {\n\tcase \"*runner.Config\":\n\t\taddressableVal = v.Elem()\n\tdefault:\n\t\taddressableVal = v\n\t}\n\tif len(fields) == 1 {\n\t\t// string slice int switch case\n\t\tfield := addressableVal.FieldByName(fieldName)\n\t\tswitch field.Kind() {\n\t\tcase reflect.String:\n\t\t\tfield.SetString(value)\n\t\tcase reflect.Slice:\n\t\t\tvar parts []string\n\t\t\tif len(value) == 0 {\n\t\t\t\tparts = []string{}\n\t\t\t} else {\n\t\t\t\tparts = strings.Split(value, sliceCmdArgSeparator)\n\t\t\t}\n\t\t\tslice := reflect.MakeSlice(field.Type(), len(parts), len(parts))\n\t\t\tfor i, part := range parts {\n\t\t\t\tslice.Index(i).Set(reflect.ValueOf(part))\n\t\t\t}\n\t\t\tfield.Set(slice)\n\t\tcase reflect.Int64:\n\t\t\ti, _ := strconv.ParseInt(value, 10, 64)\n\t\t\tfield.SetInt(i)\n\t\tcase reflect.Int:\n\t\t\ti, _ := strconv.Atoi(value)\n\t\t\tfield.SetInt(int64(i))\n\t\tcase reflect.Bool:\n\t\t\tb, _ := strconv.ParseBool(value)\n\t\t\tfield.SetBool(b)\n\t\tcase reflect.Ptr:\n\t\t\tfield.SetString(value)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"unsupported type %s\", v.FieldByName(fields[0]).Kind())\n\t\t}\n\t} else if len(fields) == 0 {\n\t\treturn\n\t} else {\n\t\tfield := addressableVal.FieldByName(fields[0])\n\t\ts2 := fieldName[index+1:]\n\t\tsetValue2Struct(field, s2, value)\n\t}\n}\n\n// flatConfig ...\nfunc flatConfig(stut interface{}) map[string]TomlInfo {\n\tm := make(map[string]TomlInfo)\n\tt := reflect.TypeOf(stut)\n\tv := reflect.ValueOf(stut)\n\tsetTage2Map(\"\", t, v, m, \"\")\n\treturn m\n}\n\nfunc getFieldValueString(fieldValue reflect.Value) string {\n\tswitch fieldValue.Kind() {\n\tcase reflect.Slice:\n\t\tsliceLen := fieldValue.Len()\n\t\tstrSlice := make([]string, sliceLen)\n\t\tfor j := 0; j < sliceLen; j++ {\n\t\t\tstrSlice[j] = fmt.Sprintf(\"%v\", fieldValue.Index(j).Interface())\n\t\t}\n\t\treturn strings.Join(strSlice, \",\")\n\tdefault:\n\t\treturn fmt.Sprintf(\"%v\", fieldValue.Interface())\n\t}\n}\n\nfunc setTage2Map(root string, t reflect.Type, v reflect.Value, m map[string]TomlInfo, fieldPath string) {\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tfieldValue := v.Field(i)\n\t\ttomlVal := field.Tag.Get(\"toml\")\n\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\tpath := fieldPath + field.Name + \".\"\n\t\t\tsetTage2Map(root+tomlVal+\".\", field.Type, fieldValue, m, path)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tomlVal == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\ttomlPath := root + tomlVal\n\t\tpath := fieldPath + field.Name\n\t\tvar v *string\n\t\tstr := \"\"\n\t\tv = &str\n\n\t\tfieldValueStr := getFieldValueString(fieldValue)\n\t\tusage := field.Tag.Get(\"usage\")\n\t\tm[tomlPath] = TomlInfo{field: field, Value: v, fieldPath: path, fieldValue: fieldValueStr, usage: usage}\n\t}\n}\n\nfunc joinPath(root, path string) string {\n\tif filepath.IsAbs(path) {\n\t\treturn path\n\t}\n\n\treturn filepath.Join(root, path)\n}\n\nfunc formatPath(path string) string {\n\tif !filepath.IsAbs(path) || !strings.Contains(path, \" \") {\n\t\treturn path\n\t}\n\n\tquotedPath := fmt.Sprintf(`\"%s\"`, path)\n\n\tif runtime.GOOS == PlatformWindows {\n\t\treturn fmt.Sprintf(`& %s`, quotedPath)\n\t}\n\n\treturn quotedPath\n}\n\n// isDangerousRoot checks if the given path is a dangerous root directory\n// that could cause excessive file watching (home dir, root dir, etc.)\n// Returns true and a description if the path is dangerous.\nfunc isDangerousRoot(path string) (bool, string) {\n\t// Get absolute path\n\tabsPath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn false, \"\"\n\t}\n\tabsPath = filepath.Clean(absPath)\n\n\t// Check root directory\n\tif absPath == \"/\" {\n\t\treturn true, \"root directory (/)\"\n\t}\n\n\t// Check home directory\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thome = filepath.Clean(home)\n\t\tif absPath == home {\n\t\t\treturn true, \"home directory (~)\"\n\t\t}\n\t}\n\n\t// Check /root (root user's home, in case UserHomeDir returns something else)\n\tif absPath == \"/root\" {\n\t\treturn true, \"/root directory\"\n\t}\n\n\treturn false, \"\"\n}\n"
  },
  {
    "path": "runner/util_linux.go",
    "content": "package runner\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {\n\tpid = cmd.Process.Pid\n\n\t// Start a goroutine to wait for the process to exit\n\tdone := make(chan struct{})\n\tgo func() {\n\t\t_, _ = cmd.Process.Wait()\n\t\tclose(done)\n\t}()\n\n\t// If not using send_interrupt, just kill immediately\n\tif !e.config.Build.SendInterrupt {\n\t\te.mainDebug(\"sending SIGKILL to process tree\")\n\t\terr = sendSignalToProcessTree(pid, syscall.SIGKILL)\n\t\t<-done // Wait for process to exit\n\t\treturn\n\t}\n\n\t// Send SIGINT first to allow graceful shutdown\n\te.mainDebug(\"sending interrupt to process tree\")\n\tif err = sendSignalToProcessTree(pid, syscall.SIGINT); err != nil {\n\t\treturn\n\t}\n\n\tkillDelay := e.config.killDelay()\n\te.mainDebug(\"waiting up to %s for graceful shutdown\", killDelay.String())\n\n\t// Wait for either the process to exit gracefully or the kill delay to expire\n\tselect {\n\tcase <-done:\n\t\t// Process exited gracefully after SIGINT - excellent!\n\t\te.mainDebug(\"process exited gracefully after SIGINT\")\n\t\treturn\n\tcase <-time.After(killDelay):\n\t\t// Timeout expired, need to force kill\n\t\te.mainDebug(\"kill delay expired, sending SIGKILL\")\n\t\terr = sendSignalToProcessTree(pid, syscall.SIGKILL)\n\t\t<-done // Wait for process to exit after SIGKILL\n\t\treturn\n\t}\n}\n\nfunc (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.ReadCloser, error) {\n\tc := exec.Command(\"/bin/sh\", \"-c\", cmd)\n\t// Set Setpgid to create a new process group (not possible when using pty)\n\tc.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\n\tstderr, err := c.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tstdout, err := c.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\n\terr = c.Start()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn c, stdout, stderr, nil\n}\n\nfunc sendSignalToProcessTree(pid int, sig syscall.Signal) error {\n\tdescendants, descendantsErr := collectDescendantPIDs(pid)\n\tvar errs []error\n\n\tif descendantsErr != nil && !errors.Is(descendantsErr, os.ErrNotExist) {\n\t\terrs = append(errs, descendantsErr)\n\t}\n\n\t// Try to signal the whole process group first.\n\tgroupErr := syscall.Kill(-pid, sig)\n\tif groupErr != nil && !errors.Is(groupErr, syscall.EPERM) && !errors.Is(groupErr, syscall.ESRCH) {\n\t\terrs = append(errs, groupErr)\n\t}\n\n\t// Always signal the root pid as well in case it moved to another process group.\n\tprocErr := syscall.Kill(pid, sig)\n\tif procErr != nil && !errors.Is(procErr, syscall.ESRCH) {\n\t\terrs = append(errs, procErr)\n\t}\n\n\t// Send signals to descendants concurrently for better performance\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tfor _, child := range descendants {\n\t\twg.Add(1)\n\t\tgo func(childPID int) {\n\t\t\tdefer wg.Done()\n\t\t\tif err := syscall.Kill(childPID, sig); err != nil && !errors.Is(err, syscall.ESRCH) {\n\t\t\t\tmu.Lock()\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tmu.Unlock()\n\t\t\t}\n\t\t}(child)\n\t}\n\twg.Wait()\n\n\tif len(errs) == 0 && errors.Is(groupErr, syscall.ESRCH) && errors.Is(procErr, syscall.ESRCH) {\n\t\treturn syscall.ESRCH\n\t}\n\n\treturn errors.Join(errs...)\n}\n\nfunc collectDescendantPIDs(pid int) ([]int, error) {\n\tchildren, err := readChildPIDs(pid)\n\tif err != nil {\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tallChildren = make([]int, 0, len(children))\n\t\terrs        []error\n\t)\n\tfor _, child := range children {\n\t\tallChildren = append(allChildren, child)\n\t\tdescendants, err := collectDescendantPIDs(child)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tallChildren = append(allChildren, descendants...)\n\t}\n\n\treturn allChildren, errors.Join(errs...)\n}\n\nfunc readChildPIDs(pid int) ([]int, error) {\n\tpath := fmt.Sprintf(\"/proc/%d/task/%d/children\", pid, pid)\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfields := strings.Fields(string(data))\n\tchildren := make([]int, 0, len(fields))\n\tfor _, field := range fields {\n\t\tchildPID, err := strconv.Atoi(field)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tchildren = append(children, childPID)\n\t}\n\n\treturn children, nil\n}\n"
  },
  {
    "path": "runner/util_linux_test.go",
    "content": "package runner\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Test_sendSignalToProcessTree_ConcurrentSignalSending(t *testing.T) {\n\tif runtime.GOOS != \"linux\" {\n\t\tt.Skip(\"requires /proc\")\n\t}\n\n\t_, b, _, _ := runtime.Caller(0)\n\tdir := filepath.Dir(b)\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't change directory: %v\", err)\n\t}\n\n\t_ = os.Remove(\"pid\")\n\tdefer os.Remove(\"pid\")\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: false,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Start a process tree with multiple children\n\tstartChan := make(chan *exec.Cmd)\n\tgo func() {\n\t\tcmd, _, _, err := e.startCmd(\"sh _testdata/run-many-processes.sh\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to start command: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tstartChan <- cmd\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tt.Logf(\"wait returned: %v\", err)\n\t\t}\n\t}()\n\n\tcmd := <-startChan\n\tpid := cmd.Process.Pid\n\ttime.Sleep(2 * time.Second)\n\n\t// Send signal using the concurrent implementation\n\terr = sendSignalToProcessTree(pid, syscall.SIGKILL)\n\n\t// Should not return an error for successful kill\n\tif err != nil && !errors.Is(err, syscall.ESRCH) {\n\t\tt.Errorf(\"unexpected error from sendSignalToProcessTree: %v\", err)\n\t}\n\n\t// Verify all processes were killed\n\tbytesRead, err := os.ReadFile(\"pid\")\n\trequire.NoError(t, err)\n\tlines := strings.Split(string(bytesRead), \"\\n\")\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := strconv.Atoi(line); err != nil {\n\t\t\tt.Logf(\"failed to convert str to int %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, err = exec.Command(\"ps\", \"-p\", line, \"-o\", \"comm= \").Output()\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"process should be killed %v\", line)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runner/util_test.go",
    "content": "package runner\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestIsDirRootPath(t *testing.T) {\n\tresult := isDir(\".\")\n\tif result != true {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n}\n\nfunc TestIsDirMainFile(t *testing.T) {\n\tresult := isDir(\"main.go\")\n\tif result != false {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n}\n\nfunc TestIsDirFileNot(t *testing.T) {\n\tresult := isDir(\"main.go\")\n\tif result != false {\n\t\tt.Errorf(\"expected '%t' but got '%t'\", true, result)\n\t}\n}\n\nfunc TestExpandPathWithDot(t *testing.T) {\n\tpath, _ := expandPath(\".\")\n\twd, _ := os.Getwd()\n\tif path != wd {\n\t\tt.Errorf(\"expected '%s' but got '%s'\", wd, path)\n\t}\n}\n\nfunc TestExpandPathWithHomePath(t *testing.T) {\n\tpath := \"~/.conf\"\n\tresult, _ := expandPath(path)\n\thome := os.Getenv(\"HOME\")\n\twant := home + path[1:]\n\tif result != want {\n\t\tt.Errorf(\"expected '%s' but got '%s'\", want, result)\n\t}\n}\n\nfunc TestNormalizeIncludeDirOutsideRoot(t *testing.T) {\n\tt.Parallel()\n\troot := t.TempDir()\n\tparent := filepath.Dir(root)\n\texternal := filepath.Join(parent, \"pkg\")\n\n\tcfg := &Config{\n\t\tRoot: root,\n\t\tBuild: cfgBuild{\n\t\t\tIncludeDir: []string{\"../pkg\"},\n\t\t},\n\t}\n\tcfg.Build.normalizeIncludeDirs(cfg.Root)\n\n\trequire.Empty(t, cfg.Build.includeDirAbs)\n\trequire.Equal(t, []string{filepath.Clean(external)}, cfg.Build.extraIncludeDirs)\n\n\tengine := &Engine{config: cfg}\n\tisIn, walk := engine.checkIncludeDir(filepath.Join(root, \"runner\"))\n\trequire.True(t, isIn)\n\trequire.True(t, walk)\n}\n\nfunc TestCheckIncludeDirRestrictsWithinRoot(t *testing.T) {\n\tt.Parallel()\n\troot := t.TempDir()\n\trunnerDir := filepath.Join(root, \"runner\")\n\trequire.NoError(t, os.Mkdir(runnerDir, 0o755))\n\totherDir := filepath.Join(root, \"other\")\n\trequire.NoError(t, os.Mkdir(otherDir, 0o755))\n\n\tcfg := &Config{\n\t\tRoot: root,\n\t\tBuild: cfgBuild{\n\t\t\tIncludeDir: []string{\"runner\"},\n\t\t},\n\t}\n\tcfg.Build.normalizeIncludeDirs(cfg.Root)\n\n\tengine := &Engine{config: cfg}\n\tisIn, walk := engine.checkIncludeDir(runnerDir)\n\trequire.True(t, isIn)\n\trequire.True(t, walk)\n\n\tisIn, walk = engine.checkIncludeDir(otherDir)\n\trequire.False(t, isIn)\n\trequire.False(t, walk)\n}\n\nfunc TestFileChecksum(t *testing.T) {\n\tt.Parallel()\n\ttests := []struct {\n\t\tname                  string\n\t\tfileContents          []byte\n\t\texpectedChecksum      string\n\t\texpectedChecksumError string\n\t}{\n\t\t{\n\t\t\tname:                  \"empty\",\n\t\t\tfileContents:          []byte(``),\n\t\t\texpectedChecksum:      \"\",\n\t\t\texpectedChecksumError: \"empty file, forcing rebuild without updating checksum\",\n\t\t},\n\t\t{\n\t\t\tname:                  \"simple\",\n\t\t\tfileContents:          []byte(`foo`),\n\t\t\texpectedChecksum:      \"2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae\",\n\t\t\texpectedChecksumError: \"\",\n\t\t},\n\t\t{\n\t\t\tname:                  \"binary\",\n\t\t\tfileContents:          []byte{0xF}, // invalid UTF-8 codepoint\n\t\t\texpectedChecksum:      \"dc0e9c3658a1a3ed1ec94274d8b19925c93e1abb7ddba294923ad9bde30f8cb8\",\n\t\t\texpectedChecksumError: \"\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tf, err := os.CreateTemp(\"\", \"\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"couldn't create temp file for test: %v\", err)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tif err := f.Close(); err != nil {\n\t\t\t\t\tt.Errorf(\"error closing temp file: %v\", err)\n\t\t\t\t}\n\t\t\t\tif err := os.Remove(f.Name()); err != nil {\n\t\t\t\t\tt.Errorf(\"error removing temp file: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t_, err = f.Write(test.fileContents)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"couldn't write to temp file for test: %v\", err)\n\t\t\t}\n\n\t\t\tchecksum, err := fileChecksum(f.Name())\n\t\t\tif err != nil && err.Error() != test.expectedChecksumError {\n\t\t\t\tt.Errorf(\"expected '%s' but got '%s'\", test.expectedChecksumError, err.Error())\n\t\t\t}\n\n\t\t\tif checksum != test.expectedChecksum {\n\t\t\t\tt.Errorf(\"expected '%s' but got '%s'\", test.expectedChecksum, checksum)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestChecksumMap(t *testing.T) {\n\tt.Parallel()\n\tm := &checksumMap{m: make(map[string]string, 3)}\n\n\tif !m.updateFileChecksum(\"foo.txt\", \"abcxyz\") {\n\t\tt.Errorf(\"expected no entry for foo.txt, but had one\")\n\t}\n\n\tif m.updateFileChecksum(\"foo.txt\", \"abcxyz\") {\n\t\tt.Errorf(\"expected matching entry for foo.txt\")\n\t}\n\n\tif !m.updateFileChecksum(\"foo.txt\", \"123456\") {\n\t\tt.Errorf(\"expected matching entry for foo.txt\")\n\t}\n\n\tif !m.updateFileChecksum(\"bar.txt\", \"123456\") {\n\t\tt.Errorf(\"expected no entry for bar.txt, but had one\")\n\t}\n}\n\nfunc TestAdaptToVariousPlatforms(t *testing.T) {\n\tt.Parallel()\n\tconfig := &Config{\n\t\tBuild: cfgBuild{\n\t\t\tBin: \"tmp\\\\main.exe  -dev\",\n\t\t},\n\t}\n\tadaptToVariousPlatforms(config)\n\tif config.Build.Bin != \"tmp\\\\main.exe  -dev\" {\n\t\tt.Errorf(\"expected '%s' but got '%s'\", \"tmp\\\\main.exe  -dev\", config.Build.Bin)\n\t}\n}\n\nfunc Test_killCmd_SendInterrupt_false(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"requires sh\")\n\t}\n\n\t_, b, _, _ := runtime.Caller(0)\n\n\t// Root folder of this project\n\tdir := filepath.Dir(b)\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't change directory: %v\", err)\n\t}\n\n\t// clean file before test\n\tos.Remove(\"pid\")\n\tdefer os.Remove(\"pid\")\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: false,\n\t\t\t},\n\t\t},\n\t}\n\tstartChan := make(chan struct {\n\t\tpid int\n\t\tcmd *exec.Cmd\n\t})\n\tgo func() {\n\t\tcmd, _, _, err := e.startCmd(\"sh _testdata/run-many-processes.sh\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to start command: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tpid := cmd.Process.Pid\n\t\tt.Logf(\"process pid is %v\", pid)\n\t\tstartChan <- struct {\n\t\t\tpid int\n\t\t\tcmd *exec.Cmd\n\t\t}{pid: pid, cmd: cmd}\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tt.Logf(\"failed to wait command: %v\", err)\n\t\t}\n\t\tt.Logf(\"wait finished\")\n\t}()\n\tresp := <-startChan\n\tt.Logf(\"process started. checking pid %v\", resp.pid)\n\ttime.Sleep(2 * time.Second)\n\tt.Logf(\"%v\", resp.cmd.Process.Pid)\n\tpid, _ := e.killCmd(resp.cmd)\n\tt.Logf(\"%v was been killed\", pid)\n\t// check processes were being killed\n\t// read pids from file\n\tbytesRead, err := os.ReadFile(\"pid\")\n\trequire.NoError(t, err)\n\tlines := strings.Split(string(bytesRead), \"\\n\")\n\tfor _, line := range lines {\n\t\t_, err := strconv.Atoi(line)\n\t\tif err != nil {\n\t\t\tt.Logf(\"failed to convert str to int %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, err = exec.Command(\"ps\", \"-p\", line, \"-o\", \"comm= \").Output()\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"process should be killed %v\", line)\n\t\t}\n\t}\n}\n\nfunc Test_killCmd_KillsDetachedChildren(t *testing.T) {\n\tif runtime.GOOS != \"linux\" {\n\t\tt.Skip(\"requires /proc\")\n\t}\n\n\t_, b, _, _ := runtime.Caller(0)\n\tdir := filepath.Dir(b)\n\terr := os.Chdir(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't change directory: %v\", err)\n\t}\n\n\t_ = os.Remove(\"pid\")\n\tdefer os.Remove(\"pid\")\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: false,\n\t\t\t},\n\t\t},\n\t}\n\n\tstartChan := make(chan *exec.Cmd)\n\tgo func() {\n\t\tcmd, _, _, err := e.startCmd(\"sh _testdata/run-detached-process.sh\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to start command: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tstartChan <- cmd\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tt.Logf(\"failed to wait command: %v\", err)\n\t\t}\n\t}()\n\n\tcmd := <-startChan\n\ttime.Sleep(2 * time.Second)\n\n\tif _, err := e.killCmd(cmd); err != nil {\n\t\tt.Fatalf(\"failed to kill command: %v\", err)\n\t}\n\n\tbytesRead, err := os.ReadFile(\"pid\")\n\trequire.NoError(t, err)\n\tlines := strings.Split(string(bytesRead), \"\\n\")\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := strconv.Atoi(line); err != nil {\n\t\t\tt.Logf(\"failed to convert str to int %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, err = exec.Command(\"ps\", \"-p\", line, \"-o\", \"comm= \").Output()\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"process should be killed %v\", line)\n\t\t}\n\t}\n}\n\nfunc TestGetStructureFieldTagMap(t *testing.T) {\n\tt.Parallel()\n\tc := Config{}\n\ttagMap := flatConfig(c)\n\tassert.NotEmpty(t, tagMap)\n\tfor _, i2 := range tagMap {\n\t\tfmt.Printf(\"%v\\n\", i2.fieldPath)\n\t}\n}\n\nfunc TestSetStructValue(t *testing.T) {\n\tt.Parallel()\n\tc := Config{}\n\tv := reflect.ValueOf(&c)\n\tsetValue2Struct(v, \"TmpDir\", \"asdasd\")\n\tassert.Equal(t, \"asdasd\", c.TmpDir)\n}\n\nfunc TestNestStructValue(t *testing.T) {\n\tt.Parallel()\n\tc := Config{}\n\tv := reflect.ValueOf(&c)\n\tsetValue2Struct(v, \"Build.Cmd\", \"asdasd\")\n\tassert.Equal(t, \"asdasd\", c.Build.Cmd)\n}\n\nfunc TestNestStructArrayValue(t *testing.T) {\n\tt.Parallel()\n\tc := Config{}\n\tv := reflect.ValueOf(&c)\n\tsetValue2Struct(v, \"Build.ExcludeDir\", \"dir1,dir2\")\n\tassert.Equal(t, []string{\"dir1\", \"dir2\"}, c.Build.ExcludeDir)\n}\n\nfunc TestNestStructArrayValueOverride(t *testing.T) {\n\tt.Parallel()\n\tc := Config{\n\t\tBuild: cfgBuild{\n\t\t\tExcludeDir: []string{\"default1\", \"default2\"},\n\t\t},\n\t}\n\tv := reflect.ValueOf(&c)\n\tsetValue2Struct(v, \"Build.ExcludeDir\", \"dir1,dir2\")\n\tassert.Equal(t, []string{\"dir1\", \"dir2\"}, c.Build.ExcludeDir)\n}\n\nfunc TestCheckIncludeFile(t *testing.T) {\n\tt.Parallel()\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tIncludeFile: []string{\"main.go\"},\n\t\t\t},\n\t\t},\n\t}\n\tassert.True(t, e.checkIncludeFile(\"main.go\"))\n\tassert.False(t, e.checkIncludeFile(\"no.go\"))\n\tassert.False(t, e.checkIncludeFile(\".\"))\n}\n\nfunc TestIsIncludeExt(t *testing.T) {\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tIncludeExt: []string{\"go\", \"html\"},\n\t\t\t},\n\t\t},\n\t}\n\tassert.True(t, e.isIncludeExt(\"main.go\"))\n\tassert.True(t, e.isIncludeExt(\"/path/to/file.html\"))\n\tassert.False(t, e.isIncludeExt(\"main.js\"))\n\tassert.False(t, e.isIncludeExt(\"file\"))\n}\n\nfunc TestIsIncludeExtWildcard(t *testing.T) {\n\ttmpDir := t.TempDir()\n\tbinPath := filepath.Join(tmpDir, \"tmp\", \"main\")\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tRoot: tmpDir,\n\t\t\tBuild: cfgBuild{\n\t\t\t\tIncludeExt: []string{\"*\"},\n\t\t\t\tEntrypoint: entrypoint{binPath},\n\t\t\t},\n\t\t},\n\t}\n\t// Wildcard should match all file extensions\n\tassert.True(t, e.isIncludeExt(\"main.go\"))\n\tassert.True(t, e.isIncludeExt(\"/path/to/file.html\"))\n\tassert.True(t, e.isIncludeExt(\"main.js\"))\n\tassert.True(t, e.isIncludeExt(\"file.css\"))\n\tassert.True(t, e.isIncludeExt(\"file\"))           // files without extension\n\tassert.True(t, e.isIncludeExt(\"/path/noext\"))    // files without extension\n\tassert.False(t, e.isIncludeExt(binPath))         // binary file should be excluded\n\tassert.True(t, e.isIncludeExt(\"some/other/bin\")) // other files without extension are ok\n}\n\nfunc TestIsIncludeExtWildcardWithSpaces(t *testing.T) {\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tIncludeExt: []string{\" * \"},\n\t\t\t\tEntrypoint: entrypoint{\"/tmp/main\"},\n\t\t\t},\n\t\t},\n\t}\n\t// Wildcard with spaces should still work\n\tassert.True(t, e.isIncludeExt(\"main.go\"))\n\tassert.True(t, e.isIncludeExt(\"file.html\"))\n}\n\nfunc TestIsBinPath(t *testing.T) {\n\ttmpDir := t.TempDir()\n\tbinPath := filepath.Join(tmpDir, \"tmp\", \"main\")\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tRoot: tmpDir,\n\t\t\tBuild: cfgBuild{\n\t\t\t\tEntrypoint: entrypoint{binPath},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Test matching path returns true\n\tassert.True(t, e.isBinPath(binPath))\n\t// Test non-matching paths return false\n\tassert.False(t, e.isBinPath(filepath.Join(tmpDir, \"other\", \"file\")))\n\tassert.False(t, e.isBinPath(\"unrelated.go\"))\n}\n\nfunc TestIsBinPathEmptyBinPath(t *testing.T) {\n\t// Test when binPath is empty (no entrypoint configured)\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tEntrypoint: entrypoint{}, // empty entrypoint\n\t\t\t},\n\t\t},\n\t}\n\n\t// Should return false when binPath is empty\n\tassert.False(t, e.isBinPath(\"/some/path\"))\n\tassert.False(t, e.isBinPath(\"main.go\"))\n}\n\nfunc TestJoinPathRelative(t *testing.T) {\n\tt.Parallel()\n\troot, err := filepath.Abs(\"test\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't get absolute path for testing: %v\", err)\n\t}\n\n\tresult := joinPath(root, \"x\")\n\n\tassert.Equal(t, result, filepath.Join(root, \"x\"))\n}\n\nfunc TestJoinPathAbsolute(t *testing.T) {\n\troot, err := filepath.Abs(\"test\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't get absolute path for testing: %v\", err)\n\t}\n\n\tpath, err := filepath.Abs(\"x\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't get absolute path for testing: %v\", err)\n\t}\n\n\tresult := joinPath(root, path)\n\n\tassert.Equal(t, result, path)\n}\n\nfunc TestFormatPath(t *testing.T) {\n\tt.Parallel()\n\ttype testCase struct {\n\t\tname     string\n\t\tpath     string\n\t\texpected string\n\t}\n\n\trunTests := func(t *testing.T, tests []testCase) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tresult := formatPath(tt.path)\n\t\t\t\tif result != tt.expected {\n\t\t\t\t\tt.Errorf(\"formatPath(%q) = %q, want %q\", tt.path, result, tt.expected)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tt.Run(\"PathPlatformSpecific\", func(t *testing.T) {\n\t\tif runtime.GOOS == PlatformWindows {\n\t\t\t// Windows-specific tests\n\t\t\ttests := []testCase{\n\t\t\t\t{\n\t\t\t\t\tname:     \"Windows style absolute path with spaces\",\n\t\t\t\t\tpath:     `C:\\My Documents\\My Project\\tmp\\app.exe`,\n\t\t\t\t\texpected: `& \"C:\\My Documents\\My Project\\tmp\\app.exe\"`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname:     \"Windows style relative path with spaces\",\n\t\t\t\t\tpath:     `My Project\\tmp\\app.exe`,\n\t\t\t\t\texpected: `My Project\\tmp\\app.exe`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname:     \"Windows style absolute path without spaces\",\n\t\t\t\t\tpath:     `C:\\Documents\\Project\\tmp\\app.exe`,\n\t\t\t\t\texpected: `C:\\Documents\\Project\\tmp\\app.exe`,\n\t\t\t\t},\n\t\t\t}\n\t\t\trunTests(t, tests)\n\t\t} else {\n\t\t\t// Unix-specific tests\n\t\t\ttests := []testCase{\n\t\t\t\t{\n\t\t\t\t\tname:     \"Unix style absolute path with spaces\",\n\t\t\t\t\tpath:     `/usr/local/my project/tmp/main`,\n\t\t\t\t\texpected: `\"/usr/local/my project/tmp/main\"`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname:     \"Unix style relative path with spaces\",\n\t\t\t\t\tpath:     \"./my project/tmp/main\",\n\t\t\t\t\texpected: \"./my project/tmp/main\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname:     \"Unix style absolute path without spaces\",\n\t\t\t\t\tpath:     `/usr/local/project/tmp/main`,\n\t\t\t\t\texpected: `/usr/local/project/tmp/main`,\n\t\t\t\t},\n\t\t\t}\n\t\t\trunTests(t, tests)\n\t\t}\n\t})\n\n\tt.Run(\"CommonCases\", func(t *testing.T) {\n\t\ttests := []testCase{\n\t\t\t{\n\t\t\t\tname:     \"Empty path\",\n\t\t\t\tpath:     \"\",\n\t\t\t\texpected: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:     \"Simple path\",\n\t\t\t\tpath:     \"main.go\",\n\t\t\t\texpected: \"main.go\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:     \"TestShouldIncludeIncludedFile\",\n\t\t\t\tpath:     \"sh main.sh\",\n\t\t\t\texpected: \"sh main.sh\",\n\t\t\t},\n\t\t}\n\t\trunTests(t, tests)\n\t})\n}\n\n// Test_killCmd_SendInterrupt_FastGracefulExit is a regression test for issue #671.\n// It verifies that when a process exits quickly after receiving SIGINT, Air detects\n// this and returns immediately instead of waiting the full kill_delay.\n//\n// This optimization was implemented in commit 4d26204 (2024-11-01) by Isak Styf.\n// Before the fix, Air would always sleep for the full kill_delay (wasting time).\n// After the fix, Air uses goroutines to detect process exit and returns early.\n//\n// Related: https://github.com/air-verse/air/issues/671\nfunc Test_killCmd_SendInterrupt_FastGracefulExit(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"send_interrupt not supported on windows\")\n\t}\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: true,\n\t\t\t\tKillDelay:     2 * time.Second, // Set high to make the waste observable\n\t\t\t},\n\t\t},\n\t}\n\n\t// Process that exits immediately on SIGINT\n\t// trap \"exit 0\" INT means: exit cleanly when receiving SIGINT\n\t// sleep 100 means: if no signal, run for 100 seconds\n\tcmd, _, _, err := e.startCmd(`sh -c 'trap \"exit 0\" INT; sleep 100'`)\n\trequire.NoError(t, err, \"failed to start command\")\n\n\t// Give the process a moment to start and set up the signal handler\n\ttime.Sleep(100 * time.Millisecond)\n\n\tstart := time.Now()\n\tpid, err := e.killCmd(cmd)\n\telapsed := time.Since(start)\n\n\trequire.NoError(t, err, \"killCmd should succeed\")\n\tassert.Positive(t, pid, \"should return valid pid\")\n\n\t// Core assertion: should complete in much less than 2 seconds\n\t// Process exits immediately on SIGINT, so should finish in <500ms\n\t// With the fix (commit 4d26204), this should PASS\n\t// Without the fix, this would FAIL (would take 2+ seconds)\n\tassert.Less(t, elapsed, 500*time.Millisecond,\n\t\t\"killCmd should return quickly when process exits gracefully on SIGINT, \"+\n\t\t\t\"but took %v (expected < 500ms). Regression of issue #671!\",\n\t\telapsed)\n\n\tt.Logf(\"✅ PASS: Process exited gracefully in %v (kill_delay was 2s, saved ~%.1fs)\",\n\t\telapsed, 2.0-elapsed.Seconds())\n}\n\n// Test_killCmd_SendInterrupt_IgnoresSIGINT is a regression test for issue #671.\n// It verifies that processes which ignore SIGINT are still killed with SIGKILL\n// after kill_delay. This ensures the optimization (commit 4d26204) doesn't break\n// the fallback behavior for misbehaving processes.\n//\n// Related: https://github.com/air-verse/air/issues/671\nfunc Test_killCmd_SendInterrupt_IgnoresSIGINT(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"send_interrupt not supported on windows\")\n\t}\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: true,\n\t\t\t\tKillDelay:     500 * time.Millisecond,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Process that ignores SIGINT\n\t// trap \"\" INT means: ignore SIGINT signal\n\tcmd, _, _, err := e.startCmd(`sh -c 'trap \"\" INT; sleep 100'`)\n\trequire.NoError(t, err, \"failed to start command\")\n\n\t// Give the process a moment to start and set up the signal handler\n\ttime.Sleep(100 * time.Millisecond)\n\n\tstart := time.Now()\n\tpid, err := e.killCmd(cmd)\n\telapsed := time.Since(start)\n\n\trequire.NoError(t, err, \"killCmd should succeed\")\n\tassert.Positive(t, pid, \"should return valid pid\")\n\n\t// Should wait at least kill_delay before sending SIGKILL\n\tassert.GreaterOrEqual(t, elapsed, 500*time.Millisecond,\n\t\t\"killCmd should wait at least kill_delay when process ignores SIGINT\")\n\n\t// But should not wait too long after SIGKILL\n\tassert.Less(t, elapsed, 1*time.Second,\n\t\t\"killCmd should not wait too long after sending SIGKILL, \"+\n\t\t\t\"but took %v\", elapsed)\n\n\tt.Logf(\"✅ PASS: Process ignored SIGINT, killed with SIGKILL after %v (expected behavior)\", elapsed)\n}\n\n// Test_killCmd_SendInterrupt_SlowGracefulExit is a regression test for issue #671.\n// It verifies that when a process takes some time to clean up after receiving\n// SIGINT but still exits within kill_delay, Air returns as soon as the process exits\n// (not waiting the full kill_delay).\n//\n// This optimization was implemented in commit 4d26204 (2024-11-01).\n// Related: https://github.com/air-verse/air/issues/671\nfunc Test_killCmd_SendInterrupt_SlowGracefulExit(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"send_interrupt not supported on windows\")\n\t}\n\n\te := Engine{\n\t\tconfig: &Config{\n\t\t\tBuild: cfgBuild{\n\t\t\t\tSendInterrupt: true,\n\t\t\t\tKillDelay:     1 * time.Second,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Process that takes 300ms to exit after SIGINT (simulating cleanup)\n\t// trap \"sleep 0.3; exit 0\" INT means: when SIGINT received, sleep 300ms then exit\n\tcmd, _, _, err := e.startCmd(`sh -c 'trap \"sleep 0.3; exit 0\" INT; sleep 100'`)\n\trequire.NoError(t, err, \"failed to start command\")\n\n\t// Give the process a moment to start and set up the signal handler\n\ttime.Sleep(100 * time.Millisecond)\n\n\tstart := time.Now()\n\tpid, err := e.killCmd(cmd)\n\telapsed := time.Since(start)\n\n\trequire.NoError(t, err, \"killCmd should succeed\")\n\tassert.Positive(t, pid, \"should return valid pid\")\n\n\t// Should wait at least for the process cleanup time (~300ms)\n\tassert.Greater(t, elapsed, 250*time.Millisecond,\n\t\t\"should wait at least for process cleanup time (~300ms)\")\n\n\t// Should return shortly after process exits (~300-500ms)\n\t// With the fix (commit 4d26204), this should PASS\n\t// Without the fix, this would FAIL (would take 1+ seconds)\n\tassert.Less(t, elapsed, 600*time.Millisecond,\n\t\t\"killCmd should return soon after process exits, \"+\n\t\t\t\"but took %v (expected ~300-500ms). Regression of issue #671!\",\n\t\telapsed)\n\n\tt.Logf(\"✅ PASS: Process exited gracefully in %v after cleanup (kill_delay was 1s, saved ~%.1fs)\",\n\t\telapsed, 1.0-elapsed.Seconds())\n}\n\nfunc TestIsDangerousRoot(t *testing.T) {\n\tt.Parallel()\n\n\thomeDir, err := os.UserHomeDir()\n\trequire.NoError(t, err, \"failed to get user home directory\")\n\n\tvar tests []struct {\n\t\tname        string\n\t\tpath        string\n\t\tisDangerous bool\n\t\tdescription string\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\ttests = []struct {\n\t\t\tname        string\n\t\t\tpath        string\n\t\t\tisDangerous bool\n\t\t\tdescription string\n\t\t}{\n\t\t\t{\n\t\t\t\tname:        \"user home directory\",\n\t\t\t\tpath:        homeDir,\n\t\t\t\tisDangerous: true,\n\t\t\t\tdescription: \"home directory (~)\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"normal project directory\",\n\t\t\t\tpath:        filepath.Join(homeDir, \"work\", \"myapp\"),\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"current directory in project\",\n\t\t\t\tpath:        \".\",\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"subdirectory of home\",\n\t\t\t\tpath:        filepath.Join(homeDir, \"projects\", \"myapp\"),\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t}\n\t} else {\n\t\ttests = []struct {\n\t\t\tname        string\n\t\t\tpath        string\n\t\t\tisDangerous bool\n\t\t\tdescription string\n\t\t}{\n\t\t\t{\n\t\t\t\tname:        \"root directory\",\n\t\t\t\tpath:        \"/\",\n\t\t\t\tisDangerous: true,\n\t\t\t\tdescription: \"root directory (/)\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"root user home\",\n\t\t\t\tpath:        \"/root\",\n\t\t\t\tisDangerous: true,\n\t\t\t\tdescription: \"/root directory\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"user home directory\",\n\t\t\t\tpath:        homeDir,\n\t\t\t\tisDangerous: true,\n\t\t\t\tdescription: \"home directory (~)\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"normal project directory\",\n\t\t\t\tpath:        \"/home/user/myproject\",\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"tmp directory\",\n\t\t\t\tpath:        \"/tmp/test-project\",\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"current directory in project\",\n\t\t\t\tpath:        \".\",\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:        \"subdirectory of home\",\n\t\t\t\tpath:        filepath.Join(homeDir, \"projects\", \"myapp\"),\n\t\t\t\tisDangerous: false,\n\t\t\t\tdescription: \"\",\n\t\t\t},\n\t\t}\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tisDangerous, desc := isDangerousRoot(tt.path)\n\t\t\tassert.Equal(t, tt.isDangerous, isDangerous, \"isDangerous mismatch for path %s\", tt.path)\n\t\t\tif tt.isDangerous {\n\t\t\t\tassert.Equal(t, tt.description, desc, \"description mismatch for path %s\", tt.path)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "runner/util_unix.go",
    "content": "//go:build unix && !linux\n\npackage runner\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {\n\tpid = cmd.Process.Pid\n\n\t// Start a goroutine to wait for the process to exit\n\tdone := make(chan struct{})\n\tgo func() {\n\t\t_, _ = cmd.Process.Wait()\n\t\tclose(done)\n\t}()\n\n\t// If not using send_interrupt, just kill immediately\n\tif !e.config.Build.SendInterrupt {\n\t\te.mainDebug(\"sending SIGKILL to process %d\", pid)\n\t\t// https://stackoverflow.com/questions/22470193/why-wont-go-kill-a-child-process-correctly\n\t\terr = syscall.Kill(-pid, syscall.SIGKILL)\n\t\t<-done // Wait for process to exit\n\t\treturn\n\t}\n\n\t// Send SIGINT first to allow graceful shutdown\n\te.mainDebug(\"sending interrupt to process %d\", pid)\n\tif err = syscall.Kill(-pid, syscall.SIGINT); err != nil {\n\t\treturn\n\t}\n\n\tkillDelay := e.config.killDelay()\n\te.mainDebug(\"waiting up to %s for graceful shutdown\", killDelay.String())\n\n\t// Wait for either the process to exit gracefully or the kill delay to expire\n\tselect {\n\tcase <-done:\n\t\t// Process exited gracefully after SIGINT - excellent!\n\t\te.mainDebug(\"process exited gracefully after SIGINT\")\n\t\treturn\n\tcase <-time.After(killDelay):\n\t\t// Timeout expired, need to force kill\n\t\te.mainDebug(\"kill delay expired, sending SIGKILL\")\n\t\t// https://stackoverflow.com/questions/22470193/why-wont-go-kill-a-child-process-correctly\n\t\terr = syscall.Kill(-pid, syscall.SIGKILL)\n\t\t<-done // Wait for process to exit after SIGKILL\n\t\treturn\n\t}\n}\n\nfunc (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.ReadCloser, error) {\n\tc := exec.Command(\"/bin/sh\", \"-c\", cmd)\n\t// because using pty cannot have same pgid\n\tc.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\n\tstderr, err := c.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tstdout, err := c.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\n\terr = c.Start()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn c, stdout, stderr, nil\n}\n"
  },
  {
    "path": "runner/util_windows.go",
    "content": "//go:build windows\n\npackage runner\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\nfunc (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {\n\tpid = cmd.Process.Pid\n\n\t// On Windows, SIGINT is not supported for process trees\n\t// Use TASKKILL to forcefully terminate the process hierarchy\n\tif e.config.Build.SendInterrupt {\n\t\te.mainLog(\"send_interrupt is not supported on Windows, using TASKKILL instead\")\n\t}\n\n\t// Single TASKKILL execution to avoid double-kill bug\n\te.mainDebug(\"sending TASKKILL to process tree\")\n\tkillCmd := exec.Command(\"TASKKILL\", \"/F\", \"/T\", \"/PID\", strconv.Itoa(pid))\n\n\t// Hide the taskkill console window\n\tkillCmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tHideWindow:    true,\n\t\tCreationFlags: windows.CREATE_NO_WINDOW,\n\t}\n\n\terr = killCmd.Run()\n\n\t// Wait for process to terminate and release resources\n\t_, _ = cmd.Process.Wait()\n\n\treturn pid, err\n}\n\nfunc (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.ReadCloser, error) {\n\tvar err error\n\n\tif !strings.Contains(cmd, \".exe\") {\n\t\te.runnerLog(\"CMD will not recognize non .exe file for execution, path: %s\", cmd)\n\t}\n\n\t// Keep PowerShell to avoid cmd.exe sound issues (#707)\n\t// Use -NoProfile and -NonInteractive for better performance\n\tc := exec.Command(\"powershell\", \"-NoProfile\", \"-NonInteractive\", \"-Command\", cmd)\n\n\tstderr, err := c.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tstdout, err := c.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\n\terr = c.Start()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn c, stdout, stderr, err\n}\n"
  },
  {
    "path": "runner/util_windows_test.go",
    "content": "package runner\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestAdaptToVariousPlatformsFullBinWindows(t *testing.T) {\n\tif runtime.GOOS != PlatformWindows {\n\t\tt.Skip(\"windows-only behavior\")\n\t}\n\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tname     string\n\t\tfullBin  string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"exe already\",\n\t\t\tfullBin:  `.\\tmp\\main.exe`,\n\t\t\texpected: `.\\tmp\\main.exe`,\n\t\t},\n\t\t{\n\t\t\tname:     \"append exe\",\n\t\t\tfullBin:  `.\\tmp\\main`,\n\t\t\texpected: `.\\tmp\\main.exe`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tconfig := &Config{\n\t\t\t\tBuild: cfgBuild{\n\t\t\t\t\tFullBin: tt.fullBin,\n\t\t\t\t},\n\t\t\t}\n\t\t\tadaptToVariousPlatforms(config)\n\t\t\tif config.Build.FullBin != tt.expected {\n\t\t\t\tt.Fatalf(\"expected full_bin %q, got %q\", tt.expected, config.Build.FullBin)\n\t\t\t}\n\t\t\tif strings.HasPrefix(strings.ToLower(config.Build.FullBin), \"start \") {\n\t\t\t\tt.Fatalf(\"unexpected start prefix in full_bin: %q\", config.Build.FullBin)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "runner/watcher.go",
    "content": "package runner\n\nimport (\n\t\"time\"\n\n\t\"github.com/gohugoio/hugo/watcher/filenotify\"\n)\n\nfunc newWatcher(cfg *Config) (filenotify.FileWatcher, error) {\n\tif !cfg.Build.Poll {\n\t\treturn filenotify.NewEventWatcher()\n\t}\n\n\t// Get the poll interval from the config.\n\tinterval := cfg.Build.PollInterval\n\n\t// Make sure the interval is at least 500ms.\n\tif interval < 500 {\n\t\tinterval = 500\n\t}\n\tpollInterval := time.Duration(interval) * time.Millisecond\n\n\treturn filenotify.NewPollingWatcher(pollInterval), nil\n}\n"
  },
  {
    "path": "runner/worker.js",
    "content": "(() => {\n    const ports = new Set();\n    let sse = null;\n    let terminationTimer = null;\n    let reconnectTimer = null;\n    let reconnectAttempts = 0;\n\n    self.onconnect = (event) => {\n        const port = event.ports[0];\n        ports.add(port);\n\n        if (terminationTimer) { // We're still alive\n            cancelTermination();\n        }\n\n        // Initialize the EventSource once\n        if (!sse) {\n            initSSE();\n        }\n\n        // Handle graceful disconnect message from port\n        port.onmessage = (e) => {\n            if (e.data === 'disconnect') {\n                ports.delete(port);\n                if (ports.size === 0) {\n                    scheduleTermination();\n                }\n            }\n        };\n\n        port.start();\n    };\n\n\n    function initSSE() {\n        if (sse) {\n            return;\n        }\n\n        sse = new EventSource(\"/__air_internal/sse\");\n\n        sse.addEventListener('reload', () => {\n            broadcast({ type: 'reload' });\n        });\n\n        sse.addEventListener('build-failed', (e) => {\n            broadcast({ type: 'build-failed', data: e.data });\n        });\n\n        sse.onopen = () => {\n            reconnectAttempts = 0;\n        };\n\n        sse.onerror = () => {\n            if (sse) {\n                sse.close();\n                sse = null;\n            }\n            scheduleReconnect();\n        };\n    }\n\n    function scheduleReconnect() {\n        if (reconnectTimer || ports.size === 0) {\n            return;\n        }\n\n        const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 10000);\n        reconnectAttempts += 1;\n        reconnectTimer = setTimeout(() => {\n            reconnectTimer = null;\n            if (ports.size === 0) {\n                return;\n            }\n            initSSE();\n        }, delay);\n    }\n\n    function clearReconnect() {\n        if (reconnectTimer) {\n            clearTimeout(reconnectTimer);\n            reconnectTimer = null;\n        }\n        reconnectAttempts = 0;\n    }\n\n    function broadcast(data) {\n        ports.forEach(port => {\n            try {\n                port.postMessage(data)\n            } catch (e) {\n                // This port is dead so we remove it. If this was the last port, schedule termination.\n                ports.delete(port);\n\n                if (ports.size === 0) {\n                    scheduleTermination();\n                }\n            }\n        });\n    }\n    \n    function cancelTermination() {\n        clearTimeout(terminationTimer);\n        terminationTimer = null;\n    }\n\n    function scheduleTermination() {\n        if (terminationTimer) { // Already scheduled\n            return\n        }\n\n        clearReconnect();\n        terminationTimer = setTimeout(() => {\n            if (sse) {\n                sse.close();\n                sse = null;\n            }\n            clearReconnect();\n            self.close();\n        }, 3000);\n    }\n})();\n"
  },
  {
    "path": "smoke_test/check_rebuild/go.mod",
    "content": "module air.sample.com\n\ngo 1.17\n"
  },
  {
    "path": "smoke_test/check_rebuild/go.sum",
    "content": ""
  },
  {
    "path": "smoke_test/check_rebuild/main.go",
    "content": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n"
  },
  {
    "path": "smoke_test/smoke_test.py",
    "content": "import os\nfrom pexpect.popen_spawn import PopenSpawn\n\nprint(os.getcwd())\nos.chdir(os.getcwd() + \"\\check_rebuild\")\nprint(os.getcwd())\n\nchild = PopenSpawn(\"air\")\nchild.expect\n\na = child.expect(\"running\", timeout=300)\nif a == 0:\n     with open(\"main.go\", \"a\") as f:\n        f.write(\"\\n\\n\")\nelse:\n    exit(0)\n\na = child.expect(\"running\", timeout=300)\nif a == 0:\n    print(\"::set-output name=value::PASS\")\nelse:\n    print(\"::set-output name=value::FAIL\")\n    exit(0)\n"
  },
  {
    "path": "version.go",
    "content": "package main\n\nvar (\n\tairVersion string\n\tgoVersion  string\n)\n"
  }
]