Full Code of air-verse/air for AI

master cc5781144c59 cached
65 files
294.9 KB
92.1k tokens
300 symbols
1 requests
Download .txt
Showing preview only (312K chars total). Download the full file or copy to clipboard to get everything.
Repository: air-verse/air
Branch: master
Commit: cc5781144c59
Files: 65
Total size: 294.9 KB

Directory structure:
gitextract_7s9z9yf2/

├── .dockerignore
├── .editorconfig
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build.yml
│       ├── release.yml
│       ├── smoke_test.yml
│       └── smoke_test_reuse_job.yml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── AGENTS.md
├── Dockerfile
├── LICENSE
├── Makefile
├── README-ja.md
├── README-zh_cn.md
├── README-zh_tw.md
├── README.md
├── air_example.toml
├── go.mod
├── go.sum
├── hack/
│   └── check.sh
├── hooks/
│   └── pre-commit
├── install.sh
├── main.go
├── runner/
│   ├── _testdata/
│   │   ├── both/
│   │   │   └── .air.toml
│   │   ├── child.sh
│   │   ├── grandchild.sh
│   │   ├── invalid_toml/
│   │   │   └── .air.toml
│   │   ├── run-detached-process.sh
│   │   ├── run-many-processes.sh
│   │   ├── toml/
│   │   │   └── .air.toml
│   │   └── watching/
│   │       └── inner/
│   │           └── test.txt
│   ├── cmdarg_test.go
│   ├── common.go
│   ├── config.go
│   ├── config_test.go
│   ├── engine.go
│   ├── engine_test.go
│   ├── exiter.go
│   ├── flag.go
│   ├── flag_test.go
│   ├── logger.go
│   ├── proxy.go
│   ├── proxy.js
│   ├── proxy_stream.go
│   ├── proxy_stream_test.go
│   ├── proxy_test.go
│   ├── test_util.go
│   ├── util.go
│   ├── util_linux.go
│   ├── util_linux_test.go
│   ├── util_test.go
│   ├── util_unix.go
│   ├── util_windows.go
│   ├── util_windows_test.go
│   ├── watcher.go
│   └── worker.js
├── smoke_test/
│   ├── check_rebuild/
│   │   ├── go.mod
│   │   ├── go.sum
│   │   └── main.go
│   └── smoke_test.py
└── version.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .dockerignore
================================================
bin
vendor
tmp
air

================================================
FILE: .editorconfig
================================================
root = true

[Makefile]
indent_style = tab

[*.go]
indent_style = tab
indent_size = 4


================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

patreon: cosmtrek
github: xiantang
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: xiantang

---

**Describe the bug**  
Provide a clear and concise description of the issue you encountered.

**To Reproduce**  
- [ ] Provide a minimal reproducible example (ideally as a PR to https://github.com/air-verse/air-reproducible-example).  
- [ ] Include relevant parts of your `.air.toml` (redact secrets) **or** the exact `air` command you ran.  
- [ ] Describe the steps to reproduce the issue clearly in that example.

**Expected behavior**  
Describe clearly and concisely what you expected to happen.

**Screenshots**  
If applicable, include screenshots to help illustrate the issue.

**Desktop (please complete the following information):**  
- OS: [e.g., macOS 13.3.1]  
- Air Version: [e.g., v1.63.2]

**Additional context**  
- Please ensure your issue is written in English as the primary language.


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.


================================================
FILE: .github/workflows/build.yml
================================================
name: Build

on:
  push:
  pull_request:
    branches: [master]

jobs:
  build:
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
    name: Build
    runs-on: ${{ matrix.os }}
    steps:
      - name: Check out code
        uses: actions/checkout@v4
      - name: Setup Go
        id: go
        uses: actions/setup-go@v5
        with:
          go-version: ^1.25
      - name: golangci-lint
        uses: golangci/golangci-lint-action@v8
        with:
          # Build golangci-lint from source with the configured Go version
          install-mode: goinstall
          version: latest
      - name: Install dependency
        run: if [ $(uname) == "Darwin" ]; then brew install gnu-sed ;fi
      - name: Build
        run: make build
      - name: Run unit tests
        env:
          CI: "true"
        run: go install github.com/go-delve/delve/cmd/dlv@latest && go test ./... -v -timeout=5m -covermode=count -coverprofile=coverage.txt
      - name: Upload Coverage report to CodeCov
        uses: codecov/codecov-action@v4
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          file: ./coverage.txt
          verbose: true

  unit_tests_windows:
    name: Unit Tests (Windows)
    runs-on: windows-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v4
      - name: Normalize line endings (Windows)
        if: runner.os == 'Windows'
        run: |
          git config core.autocrlf false
          git config core.eol lf
          git checkout-index -f -a
      - name: Setup Go
        id: go
        uses: actions/setup-go@v5
        with:
          go-version: ^1.25
      - name: golangci-lint
        uses: golangci/golangci-lint-action@v8
        with:
          install-mode: goinstall
          version: latest
      - name: Run unit tests
        env:
          CI: "true"
        run: go install github.com/go-delve/delve/cmd/dlv@latest && go test ./... -v -timeout=5m -covermode=count -coverprofile=coverage.txt

  push_to_docker_latest:
    name: Push master code to docker latest image
    if: github.event_name == 'push' && github.ref == 'refs/heads/master'
    runs-on: ubuntu-latest
    steps:
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Build and push
        id: docker_build
        uses: docker/build-push-action@v5
        with:
          push: true
          platforms: linux/amd64,linux/arm64
          tags: cosmtrek/air:latest
      - name: Show image digest
        run: echo ${{ steps.docker_build.outputs.digest }}


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

on:
  push:
  pull_request:
    branches: [master]

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - name: Check out code
        uses: actions/checkout@v4
      - name: Normalize line endings (Windows)
        if: runner.os == 'Windows'
        run: |
          git config core.autocrlf false
          git config core.eol lf
          git checkout-index -f -a
      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: ^1.25

      - name: Set GOVERSION
        run: echo "GOVERSION=$(go version | sed -r 's/go version go(.*)\ .*/\1/')" >> $GITHUB_ENV
      - name: Set AirVersion
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
      - name: Show version
        run: echo ${{ env.GOVERSION }} ${{ env.VERSION }}

      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v5
        with:
          distribution: goreleaser
          version: latest
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Push to DockerHub
        id: docker_build
        uses: docker/build-push-action@v5
        with:
          push: true
          platforms: linux/amd64,linux/arm64
          tags: cosmtrek/air:${{ env.VERSION }}
      - name: Show docker image digest
        run: echo ${{ steps.docker_build.outputs.digest }}


================================================
FILE: .github/workflows/smoke_test.yml
================================================
name: Smoke test

on:
  push:
  pull_request:

jobs:
  smoke_test_ubuntu:
    uses: ./.github/workflows/smoke_test_reuse_job.yml
    with:
      run_on: ubuntu-latest
  smoke_test_macos:
    uses: ./.github/workflows/smoke_test_reuse_job.yml
    with:
      run_on: macos-latest
  smoke_test_windows:
    uses: ./.github/workflows/smoke_test_reuse_job.yml
    with:
      run_on: windows-latest


================================================
FILE: .github/workflows/smoke_test_reuse_job.yml
================================================
name: Reusable smoke test

on:
  workflow_call:
    inputs:
      run_on:
        required: true
        type: string

jobs:
  smoke_test:
    name: Smoke test
    runs-on: ${{ inputs.run_on }}
    steps:
      - name: Check out code
        uses: actions/checkout@v5
      - name: Normalize line endings (Windows)
        if: runner.os == 'Windows'
        run: |
          git config core.autocrlf false
          git config core.eol lf
          git checkout-index -f -a
      - name: Setup Go
        id: go
        uses: actions/setup-go@v6
        with:
          go-version: ^1.25
      - name: golangci-lint
        uses: golangci/golangci-lint-action@v8
        with:
          install-mode: goinstall
          version: latest
      - name: Install
        if: runner.os != 'Windows'
        run: make install
      - name: Install (Windows)
        if: runner.os == 'Windows'
        run: go install .
      - name: Check rebuild
        if: runner.os != 'Windows'
        id: check_rebuild_unix
        working-directory: ./smoke_test/check_rebuild
        run: |
          nohup air > nohup.out 2> nohup.err < /dev/null &
          sleep 15
          echo "" >> main.go
          sleep 5
          cat nohup.out
          count=$(grep "running" nohup.out | wc -l)
          if [ "$count" -eq "2" ]; then
            echo "value=PASS" >> "$GITHUB_OUTPUT"
          else
            echo "value=FAIL" >> "$GITHUB_OUTPUT"
          fi
      - name: Check rebuild (Windows)
        if: runner.os == 'Windows'
        id: check_rebuild_windows
        working-directory: ./smoke_test/check_rebuild
        shell: pwsh
        run: |
          $log = "nohup.out"
          $err = "nohup.err"
          $goPath = (go env GOPATH)
          $airPath = Join-Path $goPath "bin\air.exe"
          $process = Start-Process -FilePath $airPath -WorkingDirectory (Get-Location) -RedirectStandardOutput $log -RedirectStandardError $err -NoNewWindow -PassThru
          Start-Sleep -Seconds 15
          Add-Content -Path "main.go" -Value "`n"
          Start-Sleep -Seconds 5
          if (Test-Path $log) { Get-Content $log }
          if (Test-Path $log) {
            $count = (Select-String -Path $log -Pattern "running" | Measure-Object).Count
          } else {
            $count = 0
          }
          if ($count -eq 2) {
            "value=PASS" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
          } else {
            "value=FAIL" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
          }
          if ($process -and -not $process.HasExited) { $process.Kill() }
      - uses: nick-invision/assert-action@v2
        with:
          expected: "PASS"
          actual: ${{ steps.check_rebuild_unix.outputs.value || steps.check_rebuild_windows.outputs.value }}


================================================
FILE: .gitignore
================================================
*.o
*.a
*.so
*.test
*.prof
*.out

vendor/
tmp/

# IDE specific files
.vscode
.idea

# build output
air

================================================
FILE: .golangci.yml
================================================
version: "2"
linters:
  default: none
  enable:
    - copyloopvar
    - errcheck
    - ineffassign
    - misspell
    - revive
    - staticcheck
    - testifylint
    - unconvert
    - unused
  exclusions:
    generated: lax
    presets:
      - comments
      - common-false-positives
      - legacy
      - std-error-handling
    paths:
      - third_party$
      - builtin$
      - examples$
formatters:
  enable:
    - goimports
  exclusions:
    generated: lax
    paths:
      - third_party$
      - builtin$
      - examples$


================================================
FILE: .goreleaser.yml
================================================
builds:
  - goos:
      - linux
      - windows
      - darwin
    ignore:
      - goos: darwin
        goarch: 386
    ldflags:
      - -s -w -X "main.airVersion={{.Version}}"
      - -s -w -X "main.goVersion={{.Env.GOVERSION}}"
    env:
      - CGO_ENABLED=0
archives:
  - id: tar.gz
    format: tar.gz
  - id: binary
    format: binary


================================================
FILE: AGENTS.md
================================================
# AGENTS

Guidelines for contributors and AI coding agents working in this repository.

## Goals

- Keep changes minimal, focused, and idiomatic to Go.
- When adding changes, do NOT break existing behavior.
- Make changes small and easy to review.
- Code and comments must be written in English.
- Prefer root-cause fixes over band-aids; do not refactor unrelated code.
- Maintain user-facing behavior and CLI flags unless explicitly changing them.

## Project Snapshot

- Language: Go (modules enabled; `go 1.25` in `go.mod`).
- Module path: `github.com/air-verse/air`.
- Entry: `main.go`.
- Core package: `runner/` (watcher, engine, flags, config, proxy).
- Docs: `README*.md`, `air_example.toml`, `docs/`.
- Tooling: `Makefile`, `hack/check.sh`, `hooks/pre-commit`, `.golangci.yml`.
- Default config file: `.air.toml` (generated by `air init`).

## Repository Layout

- `main.go`: CLI entrypoint and flag parsing.
- `runner/engine.go`: build/run loop and watcher orchestration.
- `runner/config.go`: config schema, defaults, parsing, validation.
- `runner/flag.go`: CLI flag wiring.
- `runner/watcher.go`: fsnotify vs polling watcher selection.
- `runner/proxy*.go`: live-reload proxy, SSE stream, embedded JS.
- `runner/util*.go`: platform helpers, process control, misc utilities.
- `runner/*_test.go`: unit tests and platform-specific tests.
- `hack/check.sh`: goimports + golangci-lint driver.
- `hooks/pre-commit`: runs `hack/check.sh` on staged files.

## Build / Lint / Test

- Install tools + hook: `make init` (goimports + golangci-lint v2.6.1).
- Format + lint staged Go files: `make check`.
- Format + lint all Go files: `make check scope=all`.
- Build binary: `make build` (runs `make check` first).
- Install locally: `make install` (runs `make check` first).
- CI prep (module tidy): `make ci`.
- Full test suite: `go test ./...` or `make test` (race + timeout).
- CI tests: `make test-ci` (CI=true, longer timeout).
- Pre-commit hook: runs `./hack/check.sh` on staged files.

### Single Test Recipes

- Single package: `go test ./runner -v`.
- Single test: `go test ./runner -run '^TestName$' -count=1 -v`.
- Subtest: `go test ./runner -run '^TestName$/Subcase$' -count=1`.
- All packages, one test: `go test ./... -run '^TestName$' -count=1`.
- Add `-race` or `-timeout=3m` when debugging flakiness.

## Code Style (Go)

- Formatting: run `goimports` (it also applies `gofmt`).
- Imports: let `goimports` group stdlib, third-party, local imports.
- Naming: `CamelCase` for exported, `lowerCamel` for unexported.
- Initialisms: use standard forms (ID, URL, HTTP, JSON).
- Receivers: keep receiver names short and consistent (`cfg`, `e`, `p`).
- Types: prefer concrete types over `any`; avoid needless interfaces.
- Constants: use `const` for defaults; use `0o755` style perms.
- Zero values: design structs so zero values are valid when possible.
- Early returns: avoid deeply nested `else` blocks.
- Paths: use `filepath` for OS-safe path handling.
- Shelling out: prefer `exec.Command` with args; use `/bin/sh -c` only when needed.
- Platform code: maintain `*_linux.go`, `*_windows.go`, build tags parity.
- Comments: keep short, English, and explain "why" more than "what".
- Use `time.Duration` for timeouts and backoffs.
- Prefer value receivers unless mutation or large copies require pointers.
- Avoid globals except for constants and small immutable vars.
- Treat nil slices as empty; do not rely on non-nil defaults.
- Keep TOML/JSON tags aligned with field names and usage strings.

## Error Handling & Logging

- Wrap errors with context: `fmt.Errorf("read config: %w", err)`.
- Use `errors.Is/As` for comparisons, `errors.Join` for aggregates.
- Avoid panics in packages; `log.Fatal` only at CLI entrypoints.
- Log via `mainLog`, `buildLog`, `runnerLog`, `watcherLog` in `runner`.
- Keep log output concise and consistent with existing prefixes.

## Concurrency & State

- Guard shared state with `sync.Mutex` or `sync/atomic`.
- Avoid data races; keep goroutines bounded and cancellable.
- Use channels for signaling (see `buildRunCh` in `runner/engine.go`).
- Use `context` and timeouts for operations that may block on I/O.

## Tests

- Location: alongside code as `*_test.go`.
- Style: table-driven tests with `t.Run` where it improves clarity.
- Parallelism: use `t.Parallel()` only for isolated tests.
- Helpers: use `t.Helper`, `t.TempDir`, `t.Setenv`, `t.Cleanup`.
- Assertions: use `testify/require` for fatal checks, `testify/assert` for soft checks.
- Fixtures: prefer `_testdata` and temp dirs; avoid network dependencies.
- OS coverage: use `*_windows_test.go`, `*_linux_test.go` for platform behavior.

## Config / CLI Discipline

- Config fields: edit `runner/config.go`, update parsing/defaults/tests.
- CLI flags: update `runner/flag.go`, sync help text, update README usage.
- Keep `air_example.toml` aligned with any config changes.
- Behavior changes must include README updates and tests.

## Documentation

- Update `README.md` for user-visible changes (flags, config, examples).
- Keep `docs/` content accurate when behavior changes.
- Add concise migration notes for breaking or behavioral changes.
- Mention new environment variables or defaults in docs.

## Tooling and Linters

- `make check` runs `hack/check.sh` -> `goimports` + `golangci-lint`.
- Enabled linters include: `errcheck`, `revive`, `staticcheck`, `testifylint`, `unused`.
- Fix lint warnings rather than suppressing unless clearly justified.
- Keep changes compatible with the current Go version in `go.mod`.

## Scope and Safety

- Avoid touching `vendor/`, `third_party/`, or generated files.
- Do not change CLI output or flags unless explicitly requested.
- Avoid broad refactors; keep changes localized to the feature/bug.
- Prefer root-cause fixes over temporary workarounds.
- Do not add dependencies unless there is a clear, reviewed need.
- Assume offline mode; no external network usage.

## Cursor / Copilot Rules

- No `.cursor/rules/`, `.cursorrules`, or `.github/copilot-instructions.md` found.
- If any are added later, follow them and copy key points here.

## For AI Coding Agents (Codex CLI)

- For multi-step tasks, maintain an explicit plan and mark progress.
- Keep edits in a single focused patch per logical change.
- Briefly state what you are about to do before running commands.
- Prefer `rg` for searches and keep file reads to small chunks.
- Validate with `make check` and `go test ./...` when changes touch Go code.
- Avoid touching unrelated files; do not reformat the repo wholesale.

## Release Notes (maintainers)

- Follow the README "Release" section for tagging; CI performs builds.

---

Questions or uncertain scope? Open an issue or ask for clarification before implementing.


================================================
FILE: Dockerfile
================================================
FROM golang:1.26 AS builder

LABEL maintainer="Rick Yu <cosmtrek@gmail.com>"

ENV GOPATH /go
ENV GO111MODULE on

COPY . /go/src/github.com/air-verse/air
WORKDIR /go/src/github.com/air-verse/air

RUN --mount=type=cache,target=/go/pkg/mod go mod download

RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build make ci && make install

FROM golang:1.26

COPY --from=builder /go/bin/air  /go/bin/air

ENTRYPOINT ["/go/bin/air"]


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    {one line to give the program's name and a brief idea of what it does.}
    Copyright (C) {year}  {name of author}

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    {project}  Copyright (C) {year}  {fullname}
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.



================================================
FILE: Makefile
================================================
AIRVER := $(shell git describe --tags)
LDFLAGS += -X "main.BuildTimestamp=$(shell date -u "+%Y-%m-%d %H:%M:%S")"
LDFLAGS += -X "main.airVersion=$(AIRVER)"
LDFLAGS += -X "main.goVersion=$(shell go version | sed -r 's/go version go(.*)\ .*/\1/')"

GO := GO111MODULE=on CGO_ENABLED=0 go
GOLANGCI_LINT_VERSION = v2.6.1
GOLANGCI_LINT_CURRENT := $(shell golangci-lint --version 2>/dev/null | sed -n 's/.*version \([0-9.]*\).*/v\1/p')

.PHONY: init
init: install-golangci-lint
	go install golang.org/x/tools/cmd/goimports@latest
	@echo "Install pre-commit hook"
	@ln -s $(shell pwd)/hooks/pre-commit $(shell pwd)/.git/hooks/pre-commit || true
	@chmod +x ./hack/check.sh

.PHONY: install-golangci-lint
install-golangci-lint:
	@echo "Installing golangci-lint $(GOLANGCI_LINT_VERSION)"
	@GO111MODULE=on go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)

.PHONY: setup
setup: init
	git init

.PHONY: check
check:
	@./hack/check.sh ${scope}

.PHONY: test
test:
	@go test ./... -v -race -timeout=3m

.PHONY: test-ci
test-ci:
	@CI=true go test ./... -v -timeout=5m

.PHONY: ci
ci: init
	@$(GO) mod tidy

.PHONY: build
build: check
	$(GO) build -ldflags '$(LDFLAGS)'

.PHONY: install
install: check
	@echo "Installing air..."
	@$(GO) install -ldflags '$(LDFLAGS)'

.PHONY: release
release: check
	GOOS=darwin GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/darwin/air
	GOOS=linux GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/linux/air
	GOOS=windows GOARCH=amd64 $(GO) build -ldflags '$(LDFLAGS)' -o bin/windows/air.exe

.PHONY: docker-image
docker-image:
	docker build -t cosmtrek/air:$(AIRVER) -f ./Dockerfile .

.PHONY: push-docker-image
push-docker-image:
	docker push cosmtrek/air:$(AIRVER)


================================================
FILE: README-ja.md
================================================
# :cloud: Air - Go アプリケーションのためのライブリロード

[![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)

![air](docs/air.png)

English | [简体中文](README-zh_cn.md) | [繁體中文](README-zh_tw.md) | [日本語](README-ja.md)

## 動機

Go でウェブサイトを開発し始め、 [gin](https://github.com/gin-gonic/gin) を使っていた時、gin にはライブリロード機能がないのが残念でした。

そこで探し回って [fresh](https://github.com/pilu/fresh) を試してみましたが、あまり柔軟ではないようでした。なので、もっと良いものを書くことにしました。そうして、 Air が誕生しました。

加えて、 [pilu](https:///github.com/pilu) に感謝します。fresh がなければ、 Air もありませんでした。:)

Air は Go アプリケーション開発用のライブリロードコマンドラインユーティリティです。プロジェクトのルートディレクトリで `air` を実行し、放置し、コードに集中してください。

注:このツールは本番環境へのホットデプロイとは無関係です。

## 特徴

- カラフルなログ出力
- ビルドやその他のコマンドをカスタマイズ
- サブディレクトリを除外することをサポート
- Air 起動後は新しいディレクトリを監視します
- より良いビルドプロセス

### 引数から指定された設定を上書き

air は引数による設定をサポートします:

利用可能なコマンドライン引数を以下のコマンドで確認できます:

```
air -h
```
または
```
air --help
```

もしビルドコマンドと起動コマンドを設定したい場合は、設定ファイルを使わずに以下のようにコマンドを使うことができます:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api"
```

入力値としてリストを取る引数には、アイテムを区切るためにコンマを使用します:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api" --build.exclude_dir "templates,build"
```

従来の `build.bin` フィールドは非推奨で、今後のリリースで削除される予定です。代わりに `build.entrypoint` を使ってください。

`build.entrypoint` は実行ファイルだけを指定する文字列、または実行ファイルとデフォルト引数を並べた文字列配列のどちらでも指定できます。

## インストール

### `go install` を使う場合(推奨)

go 1.25以上を使う場合:

```shell
go install github.com/air-verse/air@latest
```

### `go get -tool` を使う場合

go 1.25以上を使う場合:

```shell
go get -tool github.com/air-verse/air@latest

# 使い方は以下の通りです:
go tool air -v
```

### `install.sh` を使う場合

```shell
# バイナリは $(go env GOPATH)/bin/air にインストールされます
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# または./bin/にインストールすることもできます
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

air -v
```

### [goblin.run](https://goblin.run) を使う場合

```shell
# バイナリは /usr/local/bin/air にインストールされます
curl -sSfL https://goblin.run/github.com/air-verse/air | sh

# 任意のパスに配置することもできます
curl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh
```

### ソフトウェアパッケージマネージャー [mise](https://github.com/jdx/mise) を使う場合

```shell
mise use -g air
```

### Docker/Podman

[cosmtrek/air](https://hub.docker.com/r/cosmtrek/air) という Docker イメージをプルしてください。

```shell
docker/podman run -it --rm \
    -w "<PROJECT>" \
    -e "air_wd=<PROJECT>" \
    -v $(pwd):<PROJECT> \
    -p <PORT>:<APP SERVER PORT> \
    cosmtrek/air
    -c <CONF>
```

#### Docker/Podman .${SHELL}rc

通常のアプリケーションのように継続的に air を使いたい場合は、 ${SHELL}rc (Bash, Zsh, etc…)に関数を作成してください。

```shell
air() {
  podman/docker run -it --rm \
    -w "$PWD" -v "$PWD":"$PWD" \
    -p "$AIR_PORT":"$AIR_PORT" \
    docker.io/cosmtrek/air "$@"
}
```

`<PROJECT>`はコンテナ内のプロジェクトのパスです。 例:`/go/example`
コンテナに接続したい場合は、 `--entrypoint=bash` を追加してください。

<details>
  <summary>例</summary>

Docker で動作するとあるプロジェクト:

```shell
docker run -it --rm \
  -w "/go/src/github.com/cosmtrek/hub" \
  -v $(pwd):/go/src/github.com/cosmtrek/hub \
  -p 9090:9090 \
  cosmtrek/air
```

別の例:

```shell
cd /go/src/github.com/cosmtrek/hub
AIR_PORT=8080 air -c "config.toml"
```

これは `$PWD` を現在のディレクトリに置き換え、 `$AIR_PORT` は公開するポートを指定し、 `$@` は-cのようなアプリケーション自体の引数を受け取るためのものです。

</details>

## 使い方

`.bashrc` または `.zshrc` に `alias air='~/.air'` を追加すると、入力の手間が省けます。

まずプロジェクトを移動します。

```shell
cd /path/to/your_project
```

最もシンプルな使い方は以下の通りです。

```shell
# カレントディレクトリの `.air.toml` を優先し、見つからない場合はデフォルト値を使います
air
```

特定の設定ファイルを明示的に使う場合は `-c` を指定します。

```shell
air -c .air.toml
```

次のコマンドを実行することで、カレントディレクトリに `.air.toml` 設定ファイルを初期化できます。

```shell
air init
```

その次に、追加の引数なしで `air` コマンドを実行すると、 `.air.toml` ファイルが設定として使用されます。

```shell
air
```

[air_example.toml](air_example.toml)を参考にして設定を編集します。

### 実行時引数

air コマンドの後に引数を追加することで、ビルドしたバイナリを実行するための引数を渡すことができる。

```shell
# ./tmp/main benchを実行します
air bench

# ./tmp/main server --port 8080を実行します
air server --port 8080
```

air コマンドに渡す引数とビルドするバイナリを `--` 引数で区切ることができる。

```shell
# ./tmp/main -hを実行します
air -- -h

# カスタム設定で air を実行し、ビルドされたバイナリに -h 引数を渡す
air -c .air.toml -- -h
```

### Docker Compose

```yaml
services:
  my-project-with-air:
    image: cosmtrek/air
    # working_dir の値はマップされたボリュームの値と同じでなければなりません
    working_dir: /project-package
    ports:
      - <any>:<any>
    environment:
      - ENV_A=${ENV_A}
      - ENV_B=${ENV_B}
      - ENV_C=${ENV_C}
    volumes:
      - ./project-relative-path/:/project-package/
```

### デバッグ

`air -d`は全てのログを出力します。

## air イメージを使いたくない Docker ユーザーのためのインストールと使い方

`Dockerfile`

```Dockerfile
# 1.25以上の任意のバージョンを選択してください
FROM golang:1.25-alpine

WORKDIR /app

RUN go install github.com/air-verse/air@latest

COPY go.mod go.sum ./
RUN go mod download

CMD ["air", "-c", ".air.toml"]
```

`docker-compose.yaml`

```yaml
version: "3.8"
services:
  web:
    build:
      context: .
      # Dockerfile へのパスを正してください
      dockerfile: Dockerfile
    ports:
      - 8080:3000
    # ライブリロードのために、コードベースディレクトリを /app ディレクトリにバインド/マウントすることが重要です
    volumes:
      - ./:/app
```

## Q&A

### "command not found: air" または "No such file or directory"

```shell
export GOPATH=$HOME/xxxxx
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
export PATH=$PATH:$(go env GOPATH)/bin #この設定を .profile で確認し、追加した場合は .profile を source するのを忘れないでください!!!
```

### bin に ' が含まれる場合の wsl でのエラー

bin の\`'をエスケープするには`\`を使用したほうが良いです。関連する issue: [#305](https://github.com/air-verse/air/issues/305)

### 質問: ホットコンパイルのみを行い、何も実行しない方法は?

[#365](https://github.com/air-verse/air/issues/365)

```toml
[build]
  cmd = "/usr/bin/true"
```

### 静的ファイルの変更時にブラウザを自動的にリロードする方法

詳細のために [#512](https://github.com/air-verse/air/issues/512) の issue を参照してください。

- 静的ファイルを `include_dir` 、`include_ext` 、`include_file` に配置していることを確かめてください。
- HTML に `</body>` タグがあることを確かめてください。
- プロキシを有効にするには、以下の設定を行います:

```toml
[proxy]
  enabled = true
  proxy_port = <air proxy port>
  app_port = <your server port>
```

## 開発

必要な Go のバージョンは 1.25+ です(`go.mod` を参照)。

```shell
# プロジェクトをフォークしてください

# クローンしてください
mkdir -p $GOPATH/src/github.com/cosmtrek
cd $GOPATH/src/github.com/cosmtrek
git clone git@github.com:<YOUR USERNAME>/air.git

# 依存関係をインストールしてください
cd air
make ci

# コードを探検してコーディングを楽しんでください!
make install
```

Pull Request を受け付けています。

### リリース

```shell
# master にチェックアウトします
git checkout master

# リリースに必要なバージョンタグを付与します
git tag v1.xx.x

# リモートにプッシュします
git push origin v1.xx.x

# CI が実行され、新しいバージョンがリリースされます。約5分待つと最新バージョンを取得できます
```

## スターヒストリー

[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)

## スポンサー

[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)

多くのサポーターの方々に心から感謝します。私はいつも皆さんの優しさを忘れません。

## ライセンス

[GNU General Public License v3.0](LICENSE)


================================================
FILE: README-zh_cn.md
================================================
# 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)

:cloud: 热重载 Go 应用的工具

![air](docs/air.png)

[English](README.md) | 简体中文 | [繁體中文](README-zh_tw.md)

## 开发动机

当我用 Go 和 [gin](https://github.com/gin-gonic/gin) 框架开发网站时,gin 缺乏实时重载的功能是令人遗憾的。我曾经尝试过 [fresh](https://github.com/pilu/fresh) ,但是它用起来不太灵活,所以我试着用更好的方式来重写它。Air 就这样诞生了。此外,非常感谢 [pilu](https://github.com/pilu)。没有 fresh 就不会有 air :)

Air 是为 Go 应用开发设计的另外一个热重载的命令行工具。只需在你的项目根目录下输入 `air`,然后把它放在一边,专注于你的代码即可。

**注意**:该工具与生产环境的热部署无关。

## 特色

- 彩色的日志输出
- 自定义构建或必要的命令
- 支持外部子目录
- 在 Air 启动之后,允许监听新创建的路径
- 更棒的构建过程

### 使用参数覆盖指定配置

支持使用参数来配置 air 字段:

如果你只是想配置构建命令和运行命令,您可以直接使用以下命令,而无需配置文件:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api"
```

对于以列表形式输入的参数,使用逗号来分隔项目:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api" --build.exclude_dir "templates,build"
```

旧的 `build.bin` 字段已弃用,将在未来移除,请改用 `build.entrypoint`。

`build.entrypoint` 可以写成单个字符串(只指定可执行文件),也可以写成字符串数组(可执行文件和默认参数)。

## 安装

### 使用 `go install` (推荐)

使用 go 1.25 或更高版本:

```shell
go install github.com/air-verse/air@latest
```

### 使用 `go get -tool`

使用 go 1.25 或更高版本:

```shell
go get -tool github.com/air-verse/air@latest

# 然后像这样使用:
go tool air -v
```

### 使用 install.sh

```shell
# binary 文件会是在 $(go env GOPATH)/bin/air
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# 或者把它安装在 ./bin/ 路径下
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

air -v
```

### 使用 [goblin.run](https://goblin.run)

```shell
# binary 将会安装到 /usr/local/bin/air
curl -sSfL https://goblin.run/github.com/cosmtrek/air | sh

# 自定义路径安装
curl -sSfL https://goblin.run/github.com/cosmtrek/air | PREFIX=/tmp sh
```

### 使用软件包管理器 [mise](https://github.com/jdx/mise)

```shell
mise use -g air
```

### Docker/Podman

请拉取这个 Docker 镜像 [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).

```shell
docker run -it --rm \
    -w "<PROJECT>" \
    -e "air_wd=<PROJECT>" \
    -v $(pwd):<PROJECT> \
    -p <PORT>:<APP SERVER PORT> \
    cosmtrek/air
    -c <CONF>
```

#### Docker/Podman .${SHELL}rc

如果你想像正常应用程序一样连续使用 air,你可以在你的 ${SHELL}rc(Bash, Zsh 等)中创建一个函数

```shell
air() {
  podman/docker run -it --rm \
    -w "$PWD" -v "$PWD":"$PWD" \
    -p "$AIR_PORT":"$AIR_PORT" \
    docker.io/cosmtrek/air "$@"
}
```

`<PROJECT>` 是容器中的项目路径,例如:`/go/example`
如果你想进入容器,请添加 `--entrypoint=bash`。

<details>
  <summary>例如</summary>

我的一个项目运行在 Docker 中:

```shell
docker run -it --rm \
  -w "/go/src/github.com/cosmtrek/hub" \
  -v $(pwd):/go/src/github.com/cosmtrek/hub \
  -p 9090:9090 \
  cosmtrek/air
```

另一个例子:

```shell
cd /go/src/github.com/cosmtrek/hub
AIR_PORT=8080 air -c "config.toml"
```

这将用当前目录替换 `$PWD`,`$AIR_PORT` 是要发布的端口,而 `$@` 用于接受应用程序本身的参数,例如 `-c`

</details>

## 使用方法

为了方便输入,您可以添加 `alias air='~/.air'` 到您的 `.bashrc` 或 `.zshrc` 文件中.

首先,进入你的项目文件夹

```shell
cd /path/to/your_project
```

最简单的方法是执行

```shell
# 先尝试读取当前目录中的 `.air.toml`;如果不存在,则使用默认配置
air
```

如果要显式指定配置文件,可以使用:

```shell
air -c .air.toml
```

您可以运行以下命令,将具有默认设置的 `.air.toml` 配置文件初始化到当前目录。

```shell
air init
```

在这之后,你只需执行 `air` 命令,无需额外参数,它就能使用 `.air.toml` 文件中的配置了。

```shell
air
```

如欲修改配置信息,请参考 [air_example.toml](air_example.toml) 文件.

### 运行时参数

您可以通过把变量添加在 air 命令之后来传递参数。

```shell
# 会执行 ./tmp/main bench
air bench

# 会执行 ./tmp/main server --port 8080
air server --port 8080
```

你可以使用 `--` 参数分隔传递给 air 命令和已构建二进制文件的参数。

```shell
# 会运行 ./tmp/main -h
air -- -h

# 会使用个性化配置来运行 air,然后把 -h 后的变量和值添加到运行的参数中
air -c .air.toml -- -h
```

### Docker Compose

```yaml
services:
  my-project-with-air:
    image: cosmtrek/air
    # working_dir value has to be the same of mapped volume
    working_dir: /project-package
    ports:
      - <any>:<any>
    environment:
      - ENV_A=${ENV_A}
      - ENV_B=${ENV_B}
      - ENV_C=${ENV_C}
    volumes:
      - ./project-relative-path/:/project-package/
```

### 调试

`air -d` 命令能打印所有日志。

## Docker 用户安装和使用指南(如果不想使用 air 镜像)

`Dockerfile`

```Dockerfile
# 选择你想要的版本,>= 1.25
FROM golang:1.25-alpine

WORKDIR /app

RUN go install github.com/air-verse/air@latest

COPY go.mod go.sum ./
RUN go mod download

CMD ["air", "-c", ".air.toml"]
```

`docker-compose.yaml`

```yaml
version: "3.8"
services:
  web:
    build:
      context: .
      # 修改为你的 Dockerfile 路径
      dockerfile: Dockerfile
    ports:
      - 8080:3000
    # 为了实时重载,将代码目录绑定到 /app 目录是很重要的
    volumes:
      - ./:/app
```

## Q&A

### 遇到 "command not found: air" 或 "No such file or directory" 该怎么办?

```shell
export GOPATH=$HOME/xxxxx
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
export PATH=$PATH:$(go env GOPATH)/bin <---- 请确认这行在您的配置信息中!!!
```

### 在 wsl 下 bin 中包含 ' 时的错误

应该使用 `\` 来转义 bin 中的 `'`。相关问题:[#305](https://github.com/cosmtrek/air/issues/305)

### 问题:如何只进行热编译而不运行?

[#365](https://github.com/cosmtrek/air/issues/365)

```toml
[build]
  cmd = "/usr/bin/true"
```

### 如何在静态文件更改时自动重新加载浏览器?

请参考 [#512](https://github.com/cosmtrek/air/issues/512).

- 确保你的静态文件在 `include_dir`、`include_ext` 或 `include_file` 中。
- 确保你的 HTML 有一个 `</body>` 标签。
- 通过配置以下内容开启代理:

```toml
[proxy]
  enabled = true
  proxy_port = <air proxy port>
  app_port = <your server port>
```

## 开发

请注意:当前需要 Go 1.25+(见 `go.mod`)。

```shell
# 1. 首先复刻(fork)这个项目

# 2. 其次克隆(clone)它
mkdir -p $GOPATH/src/github.com/cosmtrek
cd $GOPATH/src/github.com/cosmtrek
git clone git@github.com:<YOUR USERNAME>/air.git

# 3. 安装依赖
cd air
make ci

# 4. 这样就可以快乐地探索和玩耍啦!
make install
```

顺便说一句: 欢迎 PR~

### 发布新版本

```shell
# 1. checkout 到 master 分支
git checkout master

# 2. 添加需要发布的版本号
git tag v1.xx.x

# 3. 推送到远程
git push origin v1.xx.x

CI 将处理并发布新版本。等待大约 5 分钟,你就可以获取最新版本了。
```

## Star 历史

[![Star History Chart](https://api.star-history.com/svg?repos=cosmtrek/air&type=Date)](https://star-history.com/#cosmtrek/air&Date)

## 赞助

[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)

非常感谢众多支持者。我一直铭记你们的善意。

## 许可证

[GNU General Public License v3.0](LICENSE)


================================================
FILE: README-zh_tw.md
================================================
# :cloud: Air - Live reload for Go apps

[![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)

![air](docs/air.png)

[English](README.md) | [简体中文](README-zh_cn.md) | 繁體中文

## 開發動機

當我開始用 Go 開發網站並使用[gin](https://github.com/gin-gonic/gin)框架時,感到可惜的是 gin 缺乏自動重新編譯執行的方式。因此,我四處搜尋並嘗試使用[fresh](https://github.com/pilu/fresh),但它似乎不夠彈性,所以我打算重新寫得更好。最後,Air 就這麼誕生了。另外,非常感謝[pilu](https://github.com/pilu),如果沒有 fresh,就不會有 air :)

Air 是一個另類的自動重新編譯執行命令列工具,用於開發 Go 應用。在你的項目根目錄下運行 `air`,將它執行於背景中,並專注於你的程式碼。

注意:此工具與生產環境的熱部署無關。

## 功能列表

- 彩色的日誌輸出
- 自訂建立或任何命令
- 支援排除子目錄
- 允許在 Air 開始後監視新目錄
- 更佳的建置過程

### 用參數覆寫指定的配置

支援將 air 做為參數的配置字段:

如果你想設定建置命令和執行命令,你可以在不需要配置檔案的情況下如下使用命令:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api"
```

對於需要輸入列表的參數,可以使用逗號將項目分隔:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api" --build.exclude_dir "templates,build"
```

舊的 `build.bin` 欄位已被棄用,未來版本會移除,請改用 `build.entrypoint`。

`build.entrypoint` 可以寫成單一字串(只指定執行檔),也可以寫成字串陣列(執行檔加上預設參數)。

## 安裝

### 使用 `go install` (推薦)

需要使用 go 1.25 或更高版本:

```shell
go install github.com/air-verse/air@latest
```

### 使用 `go get -tool`

需要使用 go 1.25 或更高版本:

```shell
go get -tool github.com/air-verse/air@latest

# 然後這樣使用:
go tool air -v
```

### 透過 install.sh

```shell
# binary will be $(go env GOPATH)/bin/air
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# or install it into ./bin/
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

air -v
```

### 透過 [goblin.run](https://goblin.run)

```shell
# binary will be /usr/local/bin/air
curl -sSfL https://goblin.run/github.com/air-verse/air | sh

# to put to a custom path
curl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh
```

### 使用軟體套件管理器 [mise](https://github.com/jdx/mise)

```shell
mise use -g air
```

### 透過 `go install`

使用 go 1.25 或更高版本:

```bash
go install github.com/air-verse/air@latest
```

### Docker/Podman

請讀取 Docker 映像檔 [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).

```shell
docker/podman run -it --rm \
    -w "<PROJECT>" \
    -e "air_wd=<PROJECT>" \
    -v $(pwd):<PROJECT> \
    -p <PORT>:<APP SERVER PORT> \
    cosmtrek/air
    -c <CONF>
```

#### Docker/Podman .${SHELL}rc

如果你想像常規應用程式一樣持續使用 air,你可以在你的 ${SHELL}rc (Bash, Zsh, etc…) 中創建一個函數。

```shell
air() {
  podman/docker run -it --rm \
    -w "$PWD" -v "$PWD":"$PWD" \
    -p "$AIR_PORT":"$AIR_PORT" \
    docker.io/cosmtrek/air "$@"
}
```

`<PROJECT>` 是你的容器中的專案路徑,例如:/go/example 如果你想要進入容器,請加上 --entrypoint=bash。

<details>
  <summary>For example</summary>

我其中一個專案是在 Docker 中運行

```shell
docker run -it --rm \
  -w "/go/src/github.com/cosmtrek/hub" \
  -v $(pwd):/go/src/github.com/cosmtrek/hub \
  -p 9090:9090 \
  cosmtrek/air
```

另一個例子

```shell
cd /go/src/github.com/cosmtrek/hub
AIR_PORT=8080 air -c "config.toml"
```

這將會用當前目錄替換 `$PWD`,`$AIR_PORT` 是發佈的端口,`$@` 是用來接受應用程式本身的參數,例如 -c

</details>

## 使用方式

為了減少輸入,你可以將 `alias air='~/.air'` 加到你的 `.bashrc` 或者 `.zshrc`。

首先,進入你的專案目錄

```shell
cd /path/to/your_project
```

最簡單的使用方式是運行

```shell
# 先嘗試讀取目前目錄中的 `.air.toml`;如果不存在,則使用預設配置
air
```

如果要明確指定配置檔,可以使用:

```shell
air -c .air.toml
```

你可以用以下命令初始化 `.air.toml` 配置檔到當前目錄,並使用預設設置。

```shell
air init
```

此後,你可以只運行 `air` 命令,而不需要額外的參數,它將使用 `.air.toml` 檔案作為配置。

```shell
air
```

要修改配置,請參閱 [air_example.toml](air_example.toml) 檔案。

### 運行時參數

你可以在 air 命令後添加參數來運行已構建的二進制檔。

```shell
# Will run ./tmp/main bench
air bench

# Will run ./tmp/main server --port 8080
air server --port 8080
```

你可以使用 `--` 參數來分隔傳遞給 air 命令和已建構的二進制檔的參數。

```shell
# Will run ./tmp/main -h
air -- -h

# Will run air with custom config and pass -h argument to the built binary
air -c .air.toml -- -h
```

### Docker Compose

```yaml
services:
  my-project-with-air:
    image: cosmtrek/air
    # working_dir value has to be the same of mapped volume
    working_dir: /project-package
    ports:
      - <any>:<any>
    environment:
      - ENV_A=${ENV_A}
      - ENV_B=${ENV_B}
      - ENV_C=${ENV_C}
    volumes:
      - ./project-relative-path/:/project-package/
```

### 除錯

`air -d` prints all logs.

## 對於不想使用 air 映像的 Docker 使用者的安裝與使用方法

`Dockerfile`

```Dockerfile
# Choose whatever you want, version >= 1.25
FROM golang:1.25-alpine

WORKDIR /app

RUN go install github.com/air-verse/air@latest

COPY go.mod go.sum ./
RUN go mod download

CMD ["air", "-c", ".air.toml"]
```

`docker-compose.yaml`

```yaml
version: "3.8"
services:
  web:
    build:
      context: .
      # Correct the path to your Dockerfile
      dockerfile: Dockerfile
    ports:
      - 8080:3000
    # Important to bind/mount your codebase dir to /app dir for live reload
    volumes:
      - ./:/app
```

## Q&A

### "找不到命令:air" 或者 "找不到檔案或目錄"

```shell
export GOPATH=$HOME/xxxxx
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
export PATH=$PATH:$(go env GOPATH)/bin <---- Confirm this line in you profile!!!
```

### 當 bin 中包含 ' 時,在 wsl 下的錯誤

應該使用 `\` 來轉義 bin 中的 `'。相關議題:[#305](https://github.com/air-verse/air/issues/305)

## 開發

請注意:目前需要 Go 1.25+(請參考 `go.mod`)。

```shell
# Fork this project

# Clone it
mkdir -p $GOPATH/src/github.com/cosmtrek
cd $GOPATH/src/github.com/cosmtrek
git clone git@github.com:<YOUR USERNAME>/air.git

# Install dependencies
cd air
make ci

# Explore it and happy hacking!
make install
```

歡迎提出 Pull Request

### 發佈版本

```shell
# Checkout to master
git checkout master

# Add the version that needs to be released
git tag v1.xx.x

# Push to remote
git push origin v1.xx.x

# The CI will process and release a new version. Wait about 5 min, and you can fetch the latest version
```

## 星星歷史

[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)

## 贊助專案

[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)

非常感謝大量的支持者。我一直記得你們的善意。

## 授權

[GNU General Public License v3.0](LICENSE)


================================================
FILE: README.md
================================================
# :cloud: Air - Live reload for Go apps

[![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)

![air](docs/air.png)

English | [简体中文](README-zh_cn.md) | [繁體中文](README-zh_tw.md) | [日本語](README-ja.md)

## Motivation

When I started developing websites in Go and using [gin](https://github.com/gin-gonic/gin) framework, it was a pity
that gin lacked a live-reloading function. So I searched around and tried [fresh](https://github.com/pilu/fresh), it seems not much
flexible, so I intended to rewrite it better. Finally, Air's born.
In addition, great thanks to [pilu](https://github.com/pilu), no fresh, no air :)

Air is yet another live-reloading command line utility for developing Go applications. Run `air` in your project root directory, leave it alone,
and focus on your code.

Note: This tool has nothing to do with hot-deploy for production.

## Features

- Colorful log output
- Customize build or any command
- Support excluding subdirectories
- Allow watching new directories after Air started
- Better building process
- Configurable `.env` file loading

### Overwrite specify configuration from arguments

Support air config fields as arguments:

You can view the available command-line arguments by running the following commands:  

```
air -h
```
or  
```
air --help
```

If you want to config build command and run command, you can use like the following command without the config file:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api"
```

Use a comma to separate items for arguments that take a list as input:

```shell
air --build.cmd "go build -o bin/api cmd/run.go" --build.entrypoint "./bin/api" --build.exclude_dir "templates,build"
```

## Installation

### Via `go install` (Recommended)

With go 1.25 or higher:

```shell
go install github.com/air-verse/air@latest
```

### Via `go get -tool` (project install)

With go 1.25 or higher:

```shell
go get -tool github.com/air-verse/air@latest

# then use it like so:
go tool air -v
```

### Via install.sh

```shell
# binary will be $(go env GOPATH)/bin/air
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin

# or install it into ./bin/
curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

air -v
```

### Via [goblin.run](https://goblin.run)

```shell
# binary will be /usr/local/bin/air
curl -sSfL https://goblin.run/github.com/air-verse/air | sh

# to put to a custom path
curl -sSfL https://goblin.run/github.com/air-verse/air | PREFIX=/tmp sh
```

### Via [Homebrew](https://github.com/Homebrew/brew)

```shell
brew install go-air
```

### Using software package manager [mise](https://github.com/jdx/mise)

```shell
mise use -g air
```

### Docker/Podman

Please pull this Docker image [cosmtrek/air](https://hub.docker.com/r/cosmtrek/air).

```shell
docker/podman run -it --rm \
    -w "<PROJECT>" \
    -e "air_wd=<PROJECT>" \
    -v $(pwd):<PROJECT> \
    -p <PORT>:<APP SERVER PORT> \
    cosmtrek/air
    -c <CONF>
```

#### Docker/Podman .${SHELL}rc

if you want to use air continuously like a normal app, you can create a function in your ${SHELL}rc (Bash, Zsh, etc…)

```shell
air() {
  podman/docker run -it --rm \
    -w "$PWD" -v "$PWD":"$PWD" \
    -p "$AIR_PORT":"$AIR_PORT" \
    docker.io/cosmtrek/air "$@"
}
```

`<PROJECT>` is your project path in container, eg: /go/example
if you want to enter the container, Please add --entrypoint=bash.

<details>
  <summary>For example</summary>

One of my project runs in Docker:

```shell
docker run -it --rm \
  -w "/go/src/github.com/cosmtrek/hub" \
  -v $(pwd):/go/src/github.com/cosmtrek/hub \
  -p 9090:9090 \
  cosmtrek/air
```

Another example:

```shell
cd /go/src/github.com/cosmtrek/hub
AIR_PORT=8080 air -c "config.toml"
```

this 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

</details>

## Usage

For less typing, you could add `alias air='~/.air'` to your `.bashrc` or `.zshrc`.

First enter into your project

```shell
cd /path/to/your_project
```

The simplest usage is to run

```shell
# first tries `.air.toml` in current directory; if not found, uses defaults
air
```

To use a specific config file explicitly, pass `-c`:

```shell
air -c .air.toml
```

You can initialize the `.air.toml` configuration file to the current directory with the default settings running the following command.

```shell
air init
```

After this, you can just run the `air` command without additional arguments, and it will use the `.air.toml` file for configuration.

```shell
air
```

For modifying the configuration refer to the [air_example.toml](air_example.toml) file.

### Runtime arguments

You can pass arguments for running the built binary by adding them after the air command.

```shell
# Will run ./tmp/main bench
air bench

# Will run ./tmp/main server --port 8080
air server --port 8080
```

You can separate the arguments passed for the air command and the built binary with `--` argument.

```shell
# Will run ./tmp/main -h
air -- -h

# Will run air with custom config and pass -h argument to the built binary
air -c .air.toml -- -h
```

### Entrypoint

Use `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.

```toml
[build]
entrypoint = ["./tmp/main"]
args_bin = ["server", ":8080"]

# Inline the default arguments directly after the binary.
entrypoint = ["./tmp/main", "server", ":8080"]

# Use PATH-resolved tools like dlv by omitting path separators.
entrypoint = [
  "dlv", "exec", "--accept-multiclient", "--log", "--headless", "--continue",
  "--listen=:8999", "--api-version", "2", "./tmp/main",
]
```

### Environment Files

Air can automatically load environment variables from `.env` files before both building and running when `env_files` is configured.

```toml
# Loads .env.development and then .env files.
# Values in the lattermost file overwrite any preceding ones.
# Does not overwrite variables that were present before running air.
env_files = [".env.development", ".env"]
```

### Docker Compose

```yaml
services:
  my-project-with-air:
    image: cosmtrek/air
    # working_dir value has to be the same of mapped volume
    working_dir: /project-package
    ports:
      - <any>:<any>
    environment:
      - ENV_A=${ENV_A}
      - ENV_B=${ENV_B}
      - ENV_C=${ENV_C}
    volumes:
      - ./project-relative-path/:/project-package/
```

### Debug

`air -d` prints all logs.

## Installation and Usage for Docker users who don't want to use air image

`Dockerfile`

```Dockerfile
# Choose whatever you want, version >= 1.25
FROM golang:1.25-alpine

WORKDIR /app

RUN go install github.com/air-verse/air@latest

COPY go.mod go.sum ./
RUN go mod download

CMD ["air", "-c", ".air.toml"]
```

`docker-compose.yaml`

```yaml
version: "3.8"
services:
  web:
    build:
      context: .
      # Correct the path to your Dockerfile
      dockerfile: Dockerfile
    ports:
      - 8080:3000
    # Important to bind/mount your codebase dir to /app dir for live reload
    volumes:
      - ./:/app
```

## Q&A

### "command not found: air" or "No such file or directory"

```shell
export GOPATH=$HOME/xxxxx
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
export PATH=$PATH:$(go env GOPATH)/bin #Confirm this line in your .profile and make sure to source the .profile if you add it!!!
```

### Error under wsl when ' is included in the bin

Should use `\` to escape the `'` in the bin. related issue: [#305](https://github.com/air-verse/air/issues/305)

### Question: how to do hot compile only and do not run anything?

[#365](https://github.com/air-verse/air/issues/365)

```toml
[build]
  cmd = "/usr/bin/true"
```

### How to Reload the Browser Automatically on Static File Changes

Refer to issue [#512](https://github.com/air-verse/air/issues/512) for additional details.

- Ensure your static files in `include_dir`, `include_ext`, or `include_file`.
- Ensure your HTML has a `</body>` tag
- Activate the proxy by configuring the following config:

```toml
[proxy]
  enabled = true
  proxy_port = <air proxy port>
  app_port = <your server port>
```

## Development

Please note that it requires Go 1.25+ (see `go.mod`).

```shell
# Fork this project

# Clone it
mkdir -p $GOPATH/src/github.com/cosmtrek
cd $GOPATH/src/github.com/cosmtrek
git clone git@github.com:<YOUR USERNAME>/air.git

# Install dependencies
cd air
make ci

# Explore it and happy hacking!
make install
```

Pull requests are welcome.

### Release

```shell
# Checkout to master
git checkout master

# Add the version that needs to be released
git tag v1.xx.x

# Push to remote
git push origin v1.xx.x

# The CI will process and release a new version. Wait about 5 min, and you can fetch the latest version
```

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=air-verse/air&type=Date)](https://star-history.com/#air-verse/air&Date)

## Sponsor

[![Buy Me A Coffee](https://cdn.buymeacoffee.com/buttons/default-orange.png)](https://www.buymeacoffee.com/cosmtrek)

Give huge thanks to lots of supporters. I've always been remembering your kindness.

## License

[GNU General Public License v3.0](LICENSE)


================================================
FILE: air_example.toml
================================================
#:schema https://json.schemastore.org/any.json

# Config file for [Air](https://github.com/air-verse/air) in TOML format

# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "."
tmp_dir = "tmp"

# Remove to not load any files whatsoever
# Non-existing files are safely ignored
env_files = [".env"]

[build]
# Array of commands to run before each build
pre_cmd = ["echo 'hello air' > pre_cmd.txt"]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./tmp/main ."
# Array of commands to run after ^C
post_cmd = ["echo 'hello air' > post_cmd.txt"]
# Binary file yields from 'cmd', will be deprecated soon, recommend using entrypoint.
bin = "tmp/main"
# Entrypoint binary relative to root. First item is the executable, more items are default arguments.
entrypoint = ["./tmp/main"]
# Customize binary, can setup environment variables when run your app.
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Add additional arguments when running binary (bin/full_bin). Will run './tmp/main hello world'.
args_bin = ["hello", "world"]
# Watch these filename extensions. Use ["*"] to watch all file extensions.
include_ext = ["go", "tpl", "tmpl", "html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
# Watch these directories if you specified.
include_dir = []
# Watch these files.
include_file = []
# Exclude files.
exclude_file = []
# Exclude specific regular expressions.
exclude_regex = ["_test\\.go"]
# Exclude unchanged files.
exclude_unchanged = true
# Ignore dangerous root directory that could cause excessive file watching
ignore_dangerous_root_dir = false
# Follow symlink for directories
follow_symlink = true
# This log file is placed in your tmp_dir.
log = "air.log"
# Poll files for changes instead of using fsnotify.
poll = false
# Poll interval (defaults to the minimum interval of 500ms).
poll_interval = 500 # ms
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 0 # ms
# Stop running old binary when build errors occur.
stop_on_error = true
# Send Interrupt signal before killing process (ignored on Windows; uses TASKKILL)
send_interrupt = false
# Delay after sending Interrupt signal
kill_delay = 500 # nanosecond
# Rerun binary or not
rerun = false
# Delay after each execution
rerun_delay = 500

[log]
# Show log time
time = false
# Only show main log (silences watcher, build, runner)
main_only = false
# silence all logs produced by air 
silent = false

[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# Delete tmp directory on exit
clean_on_exit = true

[screen]
clear_on_rebuild = true
keep_scroll = true

[proxy]
# Enable live-reloading on the browser.
enabled = true
proxy_port = 8090
app_port = 8080
# Timeout in milliseconds for waiting for the app to start and become available.
# Useful when your app has slow startup time (e.g., database connections, config loading).
# The proxy will retry connecting to your app for this duration before giving up.
# Default is 5000ms (5 seconds). Increase this if you see "unable to reach app" errors.
app_start_timeout = 5000


================================================
FILE: go.mod
================================================
module github.com/air-verse/air

go 1.25

require (
	dario.cat/mergo v1.0.2
	github.com/andybalholm/brotli v1.2.0
	github.com/fatih/color v1.18.0
	github.com/fsnotify/fsnotify v1.9.0
	github.com/gohugoio/hugo v0.149.1
	github.com/joho/godotenv v1.5.1
	github.com/pelletier/go-toml v1.9.5
	github.com/stretchr/testify v1.11.1
	golang.org/x/sys v0.35.0
)

require (
	github.com/bep/debounce v1.2.1 // indirect
	github.com/bep/godartsass/v2 v2.5.0 // indirect
	github.com/bep/golibsass v1.2.0 // indirect
	github.com/bep/gowebp v0.4.0 // indirect
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/gobwas/glob v0.2.3 // indirect
	github.com/mattn/go-colorable v0.1.14 // indirect
	github.com/mattn/go-isatty v0.0.20 // indirect
	github.com/pelletier/go-toml/v2 v2.2.4 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/rivo/uniseg v0.4.7 // indirect
	github.com/spf13/afero v1.14.0 // indirect
	github.com/spf13/cast v1.9.2 // indirect
	github.com/tdewolff/parse/v2 v2.8.3 // indirect
	golang.org/x/text v0.28.0 // indirect
	google.golang.org/protobuf v1.36.8 // indirect
	gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)


================================================
FILE: go.sum
================================================
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/BurntSushi/locker v0.0.0-20171006230638-a6e239ea1c69 h1:+tu3HOoMXB7RXEINRVIpxJCT+KdYiI7LAEAUrOw3dIU=
github.com/BurntSushi/locker v0.0.0-20171006230638-a6e239ea1c69/go.mod h1:L1AbZdiDllfyYH5l5OkAaZtk7VkWe89bPJFmnDBNHxg=
github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c h1:651/eoCRnQ7YtSjAnSzRucrJz+3iGEFt+ysraELS81M=
github.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=
github.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/bep/gitmap v1.9.0 h1:2pyb1ex+cdwF6c4tsrhEgEKfyNfxE34d5K+s2sa9byc=
github.com/bep/gitmap v1.9.0/go.mod h1:Juq6e1qqCRvc1W7nzgadPGI9IGV13ZncEebg5atj4Vo=
github.com/bep/goat v0.5.0 h1:S8jLXHCVy/EHIoCY+btKkmcxcXFd34a0Q63/0D4TKeA=
github.com/bep/goat v0.5.0/go.mod h1:Md9x7gRxiWKs85yHlVTvHQw9rg86Bm+Y4SuYE8CTH7c=
github.com/bep/godartsass/v2 v2.5.0 h1:tKRvwVdyjCIr48qgtLa4gHEdtRkPF8H1OeEhJAEv7xg=
github.com/bep/godartsass/v2 v2.5.0/go.mod h1:rjsi1YSXAl/UbsGL85RLDEjRKdIKUlMQHr6ChUNYOFU=
github.com/bep/golibsass v1.2.0 h1:nyZUkKP/0psr8nT6GR2cnmt99xS93Ji82ZD9AgOK6VI=
github.com/bep/golibsass v1.2.0/go.mod h1:DL87K8Un/+pWUS75ggYv41bliGiolxzDKWJAq3eJ1MA=
github.com/bep/goportabletext v0.1.0 h1:8dqym2So1cEqVZiBa4ZnMM1R9l/DnC1h4ONg4J5kujw=
github.com/bep/goportabletext v0.1.0/go.mod h1:6lzSTsSue75bbcyvVc0zqd1CdApuT+xkZQ6Re5DzZFg=
github.com/bep/gowebp v0.4.0 h1:QihuVnvIKbRoeBNQkN0JPMM8ClLmD6V2jMftTFwSK3Q=
github.com/bep/gowebp v0.4.0/go.mod h1:95gtYkAA8iIn1t3HkAPurRCVGV/6NhgaHJ1urz0iIwc=
github.com/bep/helpers v0.6.0 h1:qtqMCK8XPFNM9hp5Ztu9piPjxNNkk8PIyUVjg6v8Bsw=
github.com/bep/helpers v0.6.0/go.mod h1:IOZlgx5PM/R/2wgyCatfsgg5qQ6rNZJNDpWGXqDR044=
github.com/bep/imagemeta v0.12.0 h1:ARf+igs5B7pf079LrqRnwzQ/wEB8Q9v4NSDRZO1/F5k=
github.com/bep/imagemeta v0.12.0/go.mod h1:23AF6O+4fUi9avjiydpKLStUNtJr5hJB4rarG18JpN8=
github.com/bep/lazycache v0.8.0 h1:lE5frnRjxaOFbkPZ1YL6nijzOPPz6zeXasJq8WpG4L8=
github.com/bep/lazycache v0.8.0/go.mod h1:BQ5WZepss7Ko91CGdWz8GQZi/fFnCcyWupv8gyTeKwk=
github.com/bep/logg v0.4.0 h1:luAo5mO4ZkhA5M1iDVDqDqnBBnlHjmtZF6VAyTp+nCQ=
github.com/bep/logg v0.4.0/go.mod h1:Ccp9yP3wbR1mm++Kpxet91hAZBEQgmWgFgnXX3GkIV0=
github.com/bep/overlayfs v0.10.0 h1:wS3eQ6bRsLX+4AAmwGjvoFSAQoeheamxofFiJ2SthSE=
github.com/bep/overlayfs v0.10.0/go.mod h1:ouu4nu6fFJaL0sPzNICzxYsBeWwrjiTdFZdK4lI3tro=
github.com/bep/tmc v0.5.1 h1:CsQnSC6MsomH64gw0cT5f+EwQDcvZz4AazKunFwTpuI=
github.com/bep/tmc v0.5.1/go.mod h1:tGYHN8fS85aJPhDLgXETVKp+PR382OvFi2+q2GkGsq0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME=
github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvdZ6pc=
github.com/disintegration/gift v1.2.1/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/evanw/esbuild v0.25.9 h1:aU7GVC4lxJGC1AyaPwySWjSIaNLAdVEEuq3chD0Khxs=
github.com/evanw/esbuild v0.25.9/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/frankban/quicktest v1.7.2/go.mod h1:jaStnuzAqU1AJdCO0l53JDCJrVDKcS03DbaAcR7Ks/o=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4=
github.com/gobuffalo/flect v1.0.3/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e h1:QArsSubW7eDh8APMXkByjQWvuljwPGAGQpJEFn0F0wY=
github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e/go.mod h1:3Ltoo9Banwq0gOtcOwxuHG6omk+AwsQPADyw2vQYOJQ=
github.com/gohugoio/hashstructure v0.5.0 h1:G2fjSBU36RdwEJBWJ+919ERvOVqAg9tfcYp47K9swqg=
github.com/gohugoio/hashstructure v0.5.0/go.mod h1:Ser0TniXuu/eauYmrwM4o64EBvySxNzITEOLlm4igec=
github.com/gohugoio/httpcache v0.7.0 h1:ukPnn04Rgvx48JIinZvZetBfHaWE7I01JR2Q2RrQ3Vs=
github.com/gohugoio/httpcache v0.7.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI=
github.com/gohugoio/hugo v0.149.1 h1:uWOc8Ve4h4e48FyYhBquRoHCJviyxA5yGrFJLT48yio=
github.com/gohugoio/hugo v0.149.1/go.mod h1:HS6BP6e8FGxungP4CHC3zeLDvhBLnTJIjHJZWTZjs7o=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0 h1:dco+7YiOryRoPOMXwwaf+kktZSCtlFtreNdiJbETvYE=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0/go.mod h1:CRrxQTKeM3imw+UoS4EHKyrqB7Zp6sAJiqHit+aMGTE=
github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1 h1:nUzXfRTszLliZuN0JTKeunXTRaiFX6ksaWP0puLLYAY=
github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1/go.mod h1:Wy8ThAA8p2/w1DY05vEzq6EIeI2mzDjvHsu7ULBVwog=
github.com/gohugoio/locales v0.14.0 h1:Q0gpsZwfv7ATHMbcTNepFd59H7GoykzWJIxi113XGDc=
github.com/gohugoio/locales v0.14.0/go.mod h1:ip8cCAv/cnmVLzzXtiTpPwgJ4xhKZranqNqtoIu0b/4=
github.com/gohugoio/localescompressed v1.0.1 h1:KTYMi8fCWYLswFyJAeOtuk/EkXR/KPTHHNN9OS+RTxo=
github.com/gohugoio/localescompressed v1.0.1/go.mod h1:jBF6q8D7a0vaEmcWPNcAjUZLJaIVNiwvM3WlmTvooB0=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/hairyhenderson/go-codeowners v0.7.0 h1:s0W4wF8bdsBEjTWzwzSlsatSthWtTAF2xLgo4a4RwAo=
github.com/hairyhenderson/go-codeowners v0.7.0/go.mod h1:wUlNgQ3QjqC4z8DnM5nnCYVq/icpqXJyJOukKx5U8/Q=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jdkato/prose v1.2.1 h1:Fp3UnJmLVISmlc57BgKUzdjr0lOtjqTZicL3PaYy6cU=
github.com/jdkato/prose v1.2.1/go.mod h1:AiRHgVagnEx2JbQRQowVBKjG0bcs/vtkGCH1dYAL1rA=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kyokomi/emoji/v2 v2.2.13 h1:GhTfQa67venUUvmleTNFnb+bi7S3aocF7ZCXU9fSO7U=
github.com/kyokomi/emoji/v2 v2.2.13/go.mod h1:JUcn42DTdsXJo1SWanHh4HKDEyPaR5CqkmoirZZP9qE=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/makeworld-the-better-one/dither/v2 v2.4.0 h1:Az/dYXiTcwcRSe59Hzw4RI1rSnAZns+1msaCXetrMFE=
github.com/makeworld-the-better-one/dither/v2 v2.4.0/go.mod h1:VBtN8DXO7SNtyGmLiGA7IsFeKrBkQPze1/iAeM95arc=
github.com/marekm4/color-extractor v1.2.1 h1:3Zb2tQsn6bITZ8MBVhc33Qn1k5/SEuZ18mrXGUqIwn0=
github.com/marekm4/color-extractor v1.2.1/go.mod h1:90VjmiHI6M8ez9eYUaXLdcKnS+BAOp7w+NpwBdkJmpA=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c h1:cqn374mizHuIWj+OSJCajGr/phAmuMug9qIX3l9CflE=
github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/muesli/smartcrop v0.3.0 h1:JTlSkmxWg/oQ1TcLDoypuirdE8Y/jzNirQeLkxpA6Oc=
github.com/muesli/smartcrop v0.3.0/go.mod h1:i2fCI/UorTfgEpPPLWiFBv4pye+YAG78RwcQLUkocpI=
github.com/niklasfasching/go-org v1.9.1 h1:/3s4uTPOF06pImGa2Yvlp24yKXZoTYM+nsIlMzfpg/0=
github.com/niklasfasching/go-org v1.9.1/go.mod h1:ZAGFFkWvUQcpazmi/8nHqwvARpr1xpb+Es67oUGX/48=
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY=
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw=
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c=
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=
github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tdewolff/minify/v2 v2.24.2 h1:vnY3nTulEAbCAAlxTxPPDkzG24rsq31SOzp63yT+7mo=
github.com/tdewolff/minify/v2 v2.24.2/go.mod h1:1JrCtoZXaDbqioQZfk3Jdmr0GPJKiU7c1Apmb+7tCeE=
github.com/tdewolff/parse/v2 v2.8.3 h1:5VbvtJ83cfb289A1HzRA9sf02iT8YyUwN84ezjkdY1I=
github.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo=
github.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE=
github.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
github.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0=
github.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs=
github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b h1:DXr+pvt3nC887026GRP39Ej11UATqWDmWuS99x26cD0=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
golang.org/x/image v0.30.0 h1:jD5RhkmVAnjqaCUXfbGBrn3lpxbknfN9w2UhHHU+5B4=
golang.org/x/image v0.30.0/go.mod h1:SAEUTxCCMWSrJcCy/4HwavEsfZZJlYxeHLc6tTiAe/c=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=


================================================
FILE: hack/check.sh
================================================
#!/usr/bin/env bash

readonly reset=$(tput sgr0)
readonly red=$(tput bold; tput setaf 1)
readonly green=$(tput bold; tput setaf 2)

exit_code=0
check_scope=$1
if [[ "${check_scope}" = "all" ]]; then
    echo "all"
    files=($(git ls-files | grep "\.go$" | grep -v -e "^third_party" -e "^vendor"))
else
    files=($(git diff --cached --name-only --diff-filter ACM | grep "\.go$" | grep -v -e "^third_party" -e "^vendor"))
fi

echo -e "${green}1. Formatting code style"
if [[ "${#files[@]}" -ne 0 ]]; then
    goimports -w ${files[@]}
fi

echo -e "${green}2. Linting"
if ! command -v golangci-lint &> /dev/null; then
    echo "${red}golangci-lint command not found. Please install it first."
    exit_code=1
else
    # If golangci-lint was built with an older Go than the module target, hint to upgrade
    lint_go_ver=$(golangci-lint --version 2>/dev/null | sed -n 's/.*built with go\([0-9]\+\.[0-9]\+\).*/\1/p')
    mod_go_ver=$(sed -n 's/^go \([0-9]\+\.[0-9]\+\).*/\1/p' go.mod | head -n1)
    if [[ -n "${lint_go_ver}" && -n "${mod_go_ver}" ]]; then
        lint_minor=$(echo "${lint_go_ver}" | cut -d. -f2)
        mod_minor=$(echo "${mod_go_ver}" | cut -d. -f2)
        if [[ ${lint_minor} -lt ${mod_minor} ]]; then
            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})"
            echo "${red}Hint: upgrade golangci-lint (run: make init)"
            exit_code=1
        fi
    fi

    if [[ ${exit_code} -eq 0 ]] && ! golangci-lint run; then
        echo "${red}Linting issues found."
        exit_code=1
    fi
fi

if [[ ${exit_code} -ne 0 ]]; then
    echo "${red}Please fix the errors above :)"
else
    echo "${green}Nice!"
fi
echo "${reset}"

exit ${exit_code}


================================================
FILE: hooks/pre-commit
================================================
#!/usr/bin/env bash

set -e

./hack/check.sh
exit $?


================================================
FILE: install.sh
================================================
#!/bin/sh
set -e
# Code generated by godownloader on 2020-08-12T16:16:22Z. DO NOT EDIT.
#

usage() {
  this=$1
  cat <<EOF
$this: download go binaries for air-verse/air

Usage: $this [-b] bindir [-d] [tag]
  -b sets bindir or installation directory, Defaults to ./bin
  -d turns on debug logging
   [tag] is a tag from
   https://github.com/air-verse/air/releases
   If tag is missing, then the latest will be used.

 Generated by godownloader
  https://github.com/goreleaser/godownloader

EOF
  exit 2
}

parse_args() {
  #BINDIR is ./bin unless set be ENV
  # over-ridden by flag below

  BINDIR=${BINDIR:-./bin}
  while getopts "b:dh?x" arg; do
    case "$arg" in
      b) BINDIR="$OPTARG" ;;
      d) log_set_priority 10 ;;
      h | \?) usage "$0" ;;
      x) set -x ;;
    esac
  done
  shift $((OPTIND - 1))
  TAG=$1
}
# this function wraps all the destructive operations
# if a curl|bash cuts off the end of the script due to
# network, either nothing will happen or will syntax error
# out preventing half-done work
execute() {
  tmpdir=$(mktemp -d)
  log_debug "downloading files into ${tmpdir}"
  http_download "${tmpdir}/${TARBALL}" "${TARBALL_URL}"
  http_download "${tmpdir}/${CHECKSUM}" "${CHECKSUM_URL}"
  hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUM}"
  srcdir="${tmpdir}"
  (cd "${tmpdir}" && untar "${TARBALL}")
  test ! -d "${BINDIR}" && install -d "${BINDIR}"
  for binexe in $BINARIES; do
    if [ "$OS" = "windows" ]; then
      binexe="${binexe}.exe"
    fi
    install "${srcdir}/${binexe}" "${BINDIR}/"
    log_info "installed ${BINDIR}/${binexe}"
  done
  rm -rf "${tmpdir}"
}
get_binaries() {
  case "$PLATFORM" in
    darwin/amd64) BINARIES="air" ;;
    darwin/arm64) BINARIES="air" ;;
    linux/386) BINARIES="air" ;;
    linux/amd64) BINARIES="air" ;;
    linux/arm64) BINARIES="air" ;;
    windows/386) BINARIES="air" ;;
    windows/amd64) BINARIES="air" ;;
    *)
      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"
      exit 1
      ;;
  esac
}
tag_to_version() {
  if [ -z "${TAG}" ]; then
    log_info "checking GitHub for latest tag"
  else
    log_info "checking GitHub for tag '${TAG}'"
  fi
  REALTAG=$(github_release "$OWNER/$REPO" "${TAG}") && true
  if test -z "$REALTAG"; then
    log_crit "unable to find '${TAG}' - use 'latest' or see https://github.com/${PREFIX}/releases for details"
    exit 1
  fi
  # if version starts with 'v', remove it
  TAG="$REALTAG"
  VERSION=${TAG#v}
}
adjust_format() {
  # change format (tar.gz or zip) based on OS
  true
}
adjust_os() {
  # adjust archive name based on OS
  true
}
adjust_arch() {
  # adjust archive name based on ARCH
  true
}

cat /dev/null <<EOF
------------------------------------------------------------------------
https://github.com/client9/shlib - portable posix shell functions
Public domain - http://unlicense.org
https://github.com/client9/shlib/blob/master/LICENSE.md
but credit (and pull requests) appreciated.
------------------------------------------------------------------------
EOF
is_command() {
  command -v "$1" >/dev/null
}
echoerr() {
  echo "$@" 1>&2
}
log_prefix() {
  echo "$0"
}
_logp=6
log_set_priority() {
  _logp="$1"
}
log_priority() {
  if test -z "$1"; then
    echo "$_logp"
    return
  fi
  [ "$1" -le "$_logp" ]
}
log_tag() {
  case $1 in
    0) echo "emerg" ;;
    1) echo "alert" ;;
    2) echo "crit" ;;
    3) echo "err" ;;
    4) echo "warning" ;;
    5) echo "notice" ;;
    6) echo "info" ;;
    7) echo "debug" ;;
    *) echo "$1" ;;
  esac
}
log_debug() {
  log_priority 7 || return 0
  echoerr "$(log_prefix)" "$(log_tag 7)" "$@"
}
log_info() {
  log_priority 6 || return 0
  echoerr "$(log_prefix)" "$(log_tag 6)" "$@"
}
log_err() {
  log_priority 3 || return 0
  echoerr "$(log_prefix)" "$(log_tag 3)" "$@"
}
log_crit() {
  log_priority 2 || return 0
  echoerr "$(log_prefix)" "$(log_tag 2)" "$@"
}
uname_os() {
  os=$(uname -s | tr '[:upper:]' '[:lower:]')
  case "$os" in
    cygwin_nt*) os="windows" ;;
    mingw*) os="windows" ;;
    msys_nt*) os="windows" ;;
  esac
  echo "$os"
}
uname_arch() {
  arch=$(uname -m)
  case $arch in
    x86_64) arch="amd64" ;;
    x86) arch="386" ;;
    i686) arch="386" ;;
    i386) arch="386" ;;
    aarch64) arch="arm64" ;;
    armv5*) arch="armv5" ;;
    armv6*) arch="armv6" ;;
    armv7*) arch="armv7" ;;
  esac
  echo ${arch}
}
uname_os_check() {
  os=$(uname_os)
  case "$os" in
    darwin) return 0 ;;
    dragonfly) return 0 ;;
    freebsd) return 0 ;;
    linux) return 0 ;;
    android) return 0 ;;
    nacl) return 0 ;;
    netbsd) return 0 ;;
    openbsd) return 0 ;;
    plan9) return 0 ;;
    solaris) return 0 ;;
    windows) return 0 ;;
  esac
  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"
  return 1
}
uname_arch_check() {
  arch=$(uname_arch)
  case "$arch" in
    386) return 0 ;;
    amd64) return 0 ;;
    arm64) return 0 ;;
    armv5) return 0 ;;
    armv6) return 0 ;;
    armv7) return 0 ;;
    ppc64) return 0 ;;
    ppc64le) return 0 ;;
    mips) return 0 ;;
    mipsle) return 0 ;;
    mips64) return 0 ;;
    mips64le) return 0 ;;
    s390x) return 0 ;;
    amd64p32) return 0 ;;
  esac
  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"
  return 1
}
untar() {
  tarball=$1
  case "${tarball}" in
    *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;;
    *.tar) tar --no-same-owner -xf "${tarball}" ;;
    *.zip) unzip "${tarball}" ;;
    *)
      log_err "untar unknown archive format for ${tarball}"
      return 1
      ;;
  esac
}
http_download_curl() {
  local_file=$1
  source_url=$2
  header=$3
  if [ -z "$header" ]; then
    code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url")
  else
    code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url")
  fi
  if [ "$code" != "200" ]; then
    log_debug "http_download_curl received HTTP status $code"
    return 1
  fi
  return 0
}
http_download_wget() {
  local_file=$1
  source_url=$2
  header=$3
  if [ -z "$header" ]; then
    wget -q -O "$local_file" "$source_url"
  else
    wget -q --header "$header" -O "$local_file" "$source_url"
  fi
}
http_download() {
  log_debug "http_download $2"
  if is_command curl; then
    http_download_curl "$@"
    return
  elif is_command wget; then
    http_download_wget "$@"
    return
  fi
  log_crit "http_download unable to find wget or curl"
  return 1
}
http_copy() {
  tmp=$(mktemp)
  http_download "${tmp}" "$1" "$2" || return 1
  body=$(cat "$tmp")
  rm -f "${tmp}"
  echo "$body"
}
github_release() {
  owner_repo=$1
  version=$2
  test -z "$version" && version="latest"
  giturl="https://github.com/${owner_repo}/releases/${version}"
  json=$(http_copy "$giturl" "Accept:application/json")
  test -z "$json" && return 1
  version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//')
  test -z "$version" && return 1
  echo "$version"
}
hash_sha256() {
  TARGET=${1:-/dev/stdin}
  if is_command gsha256sum; then
    hash=$(gsha256sum "$TARGET") || return 1
    echo "$hash" | cut -d ' ' -f 1
  elif is_command sha256sum; then
    hash=$(sha256sum "$TARGET") || return 1
    echo "$hash" | cut -d ' ' -f 1
  elif is_command shasum; then
    hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1
    echo "$hash" | cut -d ' ' -f 1
  elif is_command openssl; then
    hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1
    echo "$hash" | cut -d ' ' -f a
  else
    log_crit "hash_sha256 unable to find command to compute sha-256 hash"
    return 1
  fi
}
hash_sha256_verify() {
  TARGET=$1
  checksums=$2
  if [ -z "$checksums" ]; then
    log_err "hash_sha256_verify checksum file not specified in arg2"
    return 1
  fi
  BASENAME=${TARGET##*/}
  want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1)
  if [ -z "$want" ]; then
    log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'"
    return 1
  fi
  got=$(hash_sha256 "$TARGET")
  if [ "$want" != "$got" ]; then
    log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got"
    return 1
  fi
}
cat /dev/null <<EOF
------------------------------------------------------------------------
End of functions from https://github.com/client9/shlib
------------------------------------------------------------------------
EOF

PROJECT_NAME="air"
OWNER=cosmtrek
REPO="air"
BINARY=air
FORMAT=tar.gz
OS=$(uname_os)
ARCH=$(uname_arch)
PREFIX="$OWNER/$REPO"

# use in logging routines
log_prefix() {
	echo "$PREFIX"
}
PLATFORM="${OS}/${ARCH}"
GITHUB_DOWNLOAD=https://github.com/${OWNER}/${REPO}/releases/download

uname_os_check "$OS"
uname_arch_check "$ARCH"

parse_args "$@"

get_binaries

tag_to_version

adjust_format

adjust_os

adjust_arch

log_info "found version: ${VERSION} for ${TAG}/${OS}/${ARCH}"

NAME=${PROJECT_NAME}_${VERSION}_${OS}_${ARCH}
TARBALL=${NAME}.${FORMAT}
TARBALL_URL=${GITHUB_DOWNLOAD}/${TAG}/${TARBALL}
CHECKSUM=${PROJECT_NAME}_${VERSION}_checksums.txt
CHECKSUM_URL=${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUM}


execute


================================================
FILE: main.go
================================================
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"runtime"
	"runtime/debug"
	"syscall"

	"github.com/air-verse/air/runner"
	"github.com/fatih/color"
)

var (
	cfgPath     string
	debugMode   bool
	showVersion bool
	colorMode   string
	cmdArgs     map[string]runner.TomlInfo
)

func helpMessage() {
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n\n", os.Args[0])
	fmt.Printf("If no command is provided %s will start the runner with the provided flags\n\n", os.Args[0])
	fmt.Println("Commands:")
	fmt.Print("  init	creates a .air.toml file with default settings to the current directory\n\n")

	fmt.Println("Flags:")
	flag.PrintDefaults()
}

func init() {
	parseFlag(os.Args[1:])
}

func parseFlag(args []string) {
	flag.Usage = helpMessage
	flag.StringVar(&cfgPath, "c", "", "config path")
	flag.BoolVar(&debugMode, "d", false, "debug mode")
	flag.BoolVar(&showVersion, "v", false, "show version")
	flag.StringVar(&colorMode, "color", "auto", "colored output: auto, always, never")
	cmd := flag.CommandLine
	cmdArgs = runner.ParseConfigFlag(cmd)
	if err := flag.CommandLine.Parse(args); err != nil {
		log.Fatal(err)
	}
}

type versionInfo struct {
	airVersion string
	goVersion  string
}

func GetVersionInfo() versionInfo { //revive:disable:unexported-return
	if len(airVersion) != 0 && len(goVersion) != 0 {
		return versionInfo{
			airVersion: airVersion,
			goVersion:  goVersion,
		}
	}
	if info, ok := debug.ReadBuildInfo(); ok {
		return versionInfo{
			airVersion: info.Main.Version,
			goVersion:  runtime.Version(),
		}
	}
	return versionInfo{
		airVersion: "(unknown)",
		goVersion:  runtime.Version(),
	}
}

func printSplash() {
	versionInfo := GetVersionInfo()
	fmt.Printf(`
  __    _   ___  
 / /\  | | | |_) 
/_/--\ |_| |_| \_ %s, built with Go %s

`, versionInfo.airVersion, versionInfo.goVersion)
}

func main() {
	switch colorMode {
	case "always":
		color.NoColor = false
	case "never":
		color.NoColor = true
	case "auto", "":
		// do nothing
	default:
		log.Fatal("unsupported color mode: use always, never, auto")
	}
	if showVersion {
		printSplash()
		return
	}
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

	var err error
	cfg, err := runner.InitConfig(cfgPath, cmdArgs)
	if err != nil {
		log.Fatal(err)
		return
	}
	if !cfg.Log.Silent {
		printSplash()
	}
	if debugMode && !cfg.Log.Silent {
		fmt.Println("[debug] mode")
	}
	r, err := runner.NewEngineWithConfig(cfg, debugMode)
	if err != nil {
		log.Fatal(err)
		return
	}
	go func() {
		<-sigs
		r.Stop()
	}()

	defer func() {
		if e := recover(); e != nil {
			log.Fatalf("PANIC: %+v", e)
		}
	}()

	r.Run()
}


================================================
FILE: runner/_testdata/both/.air.toml
================================================
#:schema https://json.schemastore.org/any.json

root = "both_root"


================================================
FILE: runner/_testdata/child.sh
================================================
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
echo "$$" >> pid
./_testdata/grandchild.sh background &
./_testdata/grandchild.sh foreground
echo "ProcessID=$$ ends ($0)"

================================================
FILE: runner/_testdata/grandchild.sh
================================================
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
echo "$$" >> pid
sleep 9999
echo "ProcessID=$$ ends ($0)"

================================================
FILE: runner/_testdata/invalid_toml/.air.toml
================================================
# Config file with duplicate key to trigger parse error
root = "."

[build]
delay = 1000
delay = 2000


================================================
FILE: runner/_testdata/run-detached-process.sh
================================================
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
echo "$$" >> pid
setsid sh -c './_testdata/grandchild.sh detached' >/dev/null 2>&1 &
DETACHED_PID=$!
echo "$DETACHED_PID" >> pid
sleep 9999
echo "ProcessID=$$ ends ($0)"


================================================
FILE: runner/_testdata/run-many-processes.sh
================================================
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
./_testdata/child.sh background &
./_testdata/child.sh foreground
echo "ProcessID=$$ ends ($0)"

================================================
FILE: runner/_testdata/toml/.air.toml
================================================
#:schema https://json.schemastore.org/any.json

root = "toml_root"


================================================
FILE: runner/_testdata/watching/inner/test.txt
================================================


================================================
FILE: runner/cmdarg_test.go
================================================
package runner


================================================
FILE: runner/common.go
================================================
package runner

const (
	//PlatformWindows const for windows
	PlatformWindows = "windows"
)


================================================
FILE: runner/config.go
================================================
package runner

import (
	"errors"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"regexp"
	"runtime"
	"strings"
	"time"

	"dario.cat/mergo"
	"github.com/pelletier/go-toml"
)

const (
	dftTOML = ".air.toml"
	airWd   = "air_wd"

	defaultProxyAppStartTimeout = 5000

	schemaHeader = "#:schema https://json.schemastore.org/any.json"
)

// Config is the main configuration structure for Air.
type Config struct {
	Root        string    `toml:"root" usage:"Working directory, . or absolute path, please note that the directories following must be under root"`
	TmpDir      string    `toml:"tmp_dir" usage:"Temporary directory for air"`
	TestDataDir string    `toml:"testdata_dir"`
	EnvFiles    []string  `toml:"env_files" usage:"Paths to .env files to load before build/run"`
	Build       cfgBuild  `toml:"build"`
	Color       cfgColor  `toml:"color"`
	Log         cfgLog    `toml:"log"`
	Misc        cfgMisc   `toml:"misc"`
	Screen      cfgScreen `toml:"screen"`
	Proxy       cfgProxy  `toml:"proxy"`
}

type entrypoint []string

func (e *entrypoint) UnmarshalTOML(v interface{}) error {
	switch val := v.(type) {
	case nil:
		*e = nil
		return nil
	case string:
		*e = []string{val}
		return nil
	case []interface{}:
		values := make([]string, len(val))
		for i, raw := range val {
			s, ok := raw.(string)
			if !ok {
				return fmt.Errorf("entrypoint values must be strings, got %T", raw)
			}
			values[i] = s
		}
		*e = values
		return nil
	default:
		return fmt.Errorf("entrypoint must be a string or array of strings, got %T", v)
	}
}

func (e entrypoint) binary() string {
	if len(e) == 0 {
		return ""
	}
	return e[0]
}

func (e entrypoint) args() []string {
	if len(e) <= 1 {
		return nil
	}
	return e[1:]
}

type cfgBuild struct {
	PreCmd                 []string      `toml:"pre_cmd" usage:"Array of commands to run before each build"`
	Cmd                    string        `toml:"cmd" usage:"Just plain old shell command. You could use 'make' as well"`
	PostCmd                []string      `toml:"post_cmd" usage:"Array of commands to run after ^C"`
	Bin                    string        `toml:"bin" usage:"Binary file yields from 'cmd', will be deprecated soon, recommend using entrypoint."`
	Entrypoint             entrypoint    `toml:"entrypoint" usage:"Binary file plus optional arguments relative to root, prefer [\"./tmp/main\", \"arg\"] form"`
	FullBin                string        `toml:"full_bin" usage:"Customize binary, can setup environment variables when run your app"`
	ArgsBin                []string      `toml:"args_bin" usage:"Add additional arguments when running binary (bin/full_bin)."`
	Log                    string        `toml:"log" usage:"This log file is placed in your tmp_dir"`
	IncludeExt             []string      `toml:"include_ext" usage:"Watch these filename extensions"`
	ExcludeDir             []string      `toml:"exclude_dir" usage:"Ignore these filename extensions or directories"`
	IncludeDir             []string      `toml:"include_dir" usage:"Watch these directories if you specified"`
	ExcludeFile            []string      `toml:"exclude_file" usage:"Exclude files"`
	IncludeFile            []string      `toml:"include_file" usage:"Watch these files"`
	ExcludeRegex           []string      `toml:"exclude_regex" usage:"Exclude specific regular expressions"`
	ExcludeUnchanged       bool          `toml:"exclude_unchanged" usage:"Exclude unchanged files"`
	IgnoreDangerousRootDir bool          `toml:"ignore_dangerous_root_dir" usage:"Ignore dangerous root directory that could cause excessive file watching"`
	FollowSymlink          bool          `toml:"follow_symlink" usage:"Follow symlink for directories"`
	Poll                   bool          `toml:"poll" usage:"Poll files for changes instead of using fsnotify"`
	PollInterval           int           `toml:"poll_interval" usage:"Poll interval (defaults to the minimum interval of 500ms)"`
	Delay                  int           `toml:"delay" usage:"It's not necessary to trigger build each time file changes if it's too frequent"`
	StopOnError            bool          `toml:"stop_on_error" usage:"Stop running old binary when build errors occur"`
	SendInterrupt          bool          `toml:"send_interrupt" usage:"Send Interrupt signal before killing process (ignored on Windows; uses TASKKILL)"`
	KillDelay              time.Duration `toml:"kill_delay" usage:"Delay after sending Interrupt signal"`
	Rerun                  bool          `toml:"rerun" usage:"Rerun binary or not"`
	RerunDelay             int           `toml:"rerun_delay" usage:"Delay after each execution"`
	regexCompiled          []*regexp.Regexp
	includeDirAbs          []string
	extraIncludeDirs       []string
}

func (c *cfgBuild) RegexCompiled() ([]*regexp.Regexp, error) {
	return c.regexCompiled, nil
}

func (c *cfgBuild) normalizeIncludeDirs(root string) {
	c.includeDirAbs = c.includeDirAbs[:0]
	c.extraIncludeDirs = c.extraIncludeDirs[:0]
	if root == "" {
		return
	}
	for _, dir := range c.IncludeDir {
		dir = cleanPath(dir)
		if dir == "" {
			continue
		}
		dir = filepath.Clean(dir)
		abs := dir
		if !filepath.IsAbs(dir) {
			abs = filepath.Join(root, dir)
		}
		abs = filepath.Clean(abs)
		if isSubPath(root, abs) {
			c.includeDirAbs = append(c.includeDirAbs, abs)
			continue
		}
		c.extraIncludeDirs = append(c.extraIncludeDirs, abs)
	}
}

type cfgLog struct {
	AddTime  bool `toml:"time" usage:"Show log time"`
	MainOnly bool `toml:"main_only" usage:"Only show main log (silences watcher, build, runner)"`
	Silent   bool `toml:"silent" usage:"silence all logs produced by air"`
}

type cfgColor struct {
	Main    string `toml:"main" usage:"Customize main part's color. If no color found, use the raw app log"`
	Watcher string `toml:"watcher" usage:"Customize watcher part's color"`
	Build   string `toml:"build" usage:"Customize build part's color"`
	Runner  string `toml:"runner" usage:"Customize runner part's color"`
	App     string `toml:"app"`
}

type cfgMisc struct {
	CleanOnExit bool `toml:"clean_on_exit" usage:"Delete tmp directory on exit"`
}

type cfgScreen struct {
	ClearOnRebuild bool `toml:"clear_on_rebuild" usage:"Clear screen on rebuild"`
	KeepScroll     bool `toml:"keep_scroll" usage:"Keep scroll position after rebuild"`
}

type cfgProxy struct {
	Enabled         bool `toml:"enabled" usage:"Enable live-reloading on the browser"`
	ProxyPort       int  `toml:"proxy_port" usage:"Port for proxy server"`
	AppPort         int  `toml:"app_port" usage:"Port for your app"`
	AppStartTimeout int  `toml:"app_start_timeout" usage:"Timeout for waiting for app to start in milliseconds (default 5000)"`
}

type sliceTransformer struct{}

func (t sliceTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
	if typ.Kind() == reflect.Slice {
		return func(dst, src reflect.Value) error {
			if !src.IsZero() {
				dst.Set(src)
			}
			return nil
		}
	}
	return nil
}

// InitConfig initializes the configuration.
func InitConfig(path string, cmdArgs map[string]TomlInfo) (cfg *Config, err error) {
	if path == "" {
		cfg, err = defaultPathConfig()
		if err != nil {
			return nil, err
		}
	} else {
		cfg, err = readConfigOrDefault(path)
		if err != nil {
			return nil, err
		}
	}
	warnDeprecatedBin(cfg)
	config := defaultConfig()
	// get addr
	ret := &config
	err = mergo.Merge(ret, cfg, func(config *mergo.Config) {
		// mergo.Merge will overwrite the fields if it is Empty
		// So need use this to avoid that none-zero slice will be overwritten.
		// https://dario.cat/mergo#transformers
		config.Transformers = sliceTransformer{}
		config.Overwrite = true
	})
	if err != nil {
		return nil, err
	}

	err = ret.preprocess(cmdArgs)
	return ret, err
}

func writeDefaultConfig() (string, error) {
	fstat, err := os.Stat(dftTOML)
	if err != nil && !os.IsNotExist(err) {
		return "", fmt.Errorf("failed to check for existing configuration: %w", err)
	}
	if err == nil && fstat != nil {
		return "", errors.New("configuration already exists")
	}

	file, err := os.Create(dftTOML)
	if err != nil {
		return "", fmt.Errorf("failed to create a new configuration: %w", err)
	}
	defer file.Close()

	config := defaultConfig()
	if len(config.Build.Entrypoint) == 0 && config.Build.Bin != "" {
		config.Build.Entrypoint = entrypoint{config.Build.Bin}
	}
	configFile, err := toml.Marshal(config)
	if err != nil {
		return "", fmt.Errorf("failed to marshal the default configuration: %w", err)
	}

	headers := []byte(schemaHeader + "\n\n")
	content := append(headers, configFile...)

	_, err = file.Write(content)
	if err != nil {
		return "", fmt.Errorf("failed to write to %s: %w", dftTOML, err)
	}

	return dftTOML, nil
}

func defaultPathConfig() (*Config, error) {
	// when path is blank, first find `.air.toml` in `air_wd` and current working directory, if not found, use defaults
	cfg, err := readConfByName(dftTOML)
	if err == nil {
		return cfg, nil
	}

	// If the config file exists but failed to parse, report the error
	// Only use defaults if no config file exists
	if !os.IsNotExist(err) {
		return nil, fmt.Errorf("failed to parse %s: %w", dftTOML, err)
	}

	dftCfg := defaultConfig()
	return &dftCfg, nil
}

func readConfByName(name string) (*Config, error) {
	var path string
	if wd := os.Getenv(airWd); wd != "" {
		path = filepath.Join(wd, name)
	} else {
		wd, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		path = filepath.Join(wd, name)
	}
	cfg, err := readConfig(path)
	return cfg, err
}

func defaultConfig() Config {
	build := cfgBuild{
		Cmd:          "go build -o ./tmp/main .",
		Bin:          "./tmp/main",
		Entrypoint:   entrypoint{},
		Log:          "build-errors.log",
		IncludeExt:   []string{"go", "tpl", "tmpl", "html"},
		IncludeDir:   []string{},
		PreCmd:       []string{},
		PostCmd:      []string{},
		ExcludeFile:  []string{},
		IncludeFile:  []string{},
		ExcludeDir:   []string{"assets", "tmp", "vendor", "testdata"},
		ArgsBin:      []string{},
		ExcludeRegex: []string{"_test.go"},
		Delay:        1000,
		Rerun:        false,
		RerunDelay:   500,
	}
	if runtime.GOOS == PlatformWindows {
		build.Bin = `tmp\main.exe`
		build.Cmd = "go build -o ./tmp/main.exe ."
	}
	log := cfgLog{
		AddTime:  false,
		MainOnly: false,
		Silent:   false,
	}
	color := cfgColor{
		Main:    "magenta",
		Watcher: "cyan",
		Build:   "yellow",
		Runner:  "green",
	}
	misc := cfgMisc{
		CleanOnExit: false,
	}
	return Config{
		Root:        ".",
		TmpDir:      "tmp",
		TestDataDir: "testdata",
		EnvFiles:    []string{},
		Build:       build,
		Color:       color,
		Log:         log,
		Misc:        misc,
		Screen: cfgScreen{
			ClearOnRebuild: false,
			KeepScroll:     true,
		},
	}
}

func readConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	cfg := new(Config)
	if err = toml.Unmarshal(data, cfg); err != nil {
		return nil, err
	}

	return cfg, nil
}

func readConfigOrDefault(path string) (*Config, error) {
	dftCfg := defaultConfig()
	cfg, err := readConfig(path)
	if err != nil {
		return &dftCfg, err
	}

	return cfg, nil
}

func (c *Config) preprocess(args map[string]TomlInfo) error {
	var err error

	if args != nil {
		c.withArgs(args)
	}
	cwd := os.Getenv(airWd)
	if cwd != "" {
		if err = os.Chdir(cwd); err != nil {
			return err
		}
		c.Root = cwd
	}
	c.Root, err = expandPath(c.Root)
	if err != nil {
		return err
	}

	// Check for dangerous root directories that could cause excessive file watching
	if isDangerous, dirName := isDangerousRoot(c.Root); isDangerous {
		if !c.Build.IgnoreDangerousRootDir {
			return fmt.Errorf("refusing to run in %s - this would watch too many files. Please run air in a project directory", dirName)
		}
		fmt.Fprintln(os.Stdout, "[warning] ignoring root directory protections. This could cause excessive file watching. It is recommended to run air in a project directory")
	}

	if c.TmpDir == "" {
		c.TmpDir = "tmp"
	}
	if c.TestDataDir == "" {
		c.TestDataDir = "testdata"
	}
	ed := c.Build.ExcludeDir
	for i := range ed {
		ed[i] = cleanPath(ed[i])
	}

	if len(c.Build.Entrypoint) > 0 {
		entry := c.Build.Entrypoint.binary()
		if !filepath.IsAbs(entry) {
			if resolved := resolveCommandPath(entry); resolved != "" {
				entry = resolved
			} else {
				entry = joinPath(c.Root, entry)
			}
		}

		entry, err = filepath.Abs(entry)
		if err != nil {
			return err
		}
		c.Build.Entrypoint[0] = entry
	}

	adaptToVariousPlatforms(c)
	c.Build.normalizeIncludeDirs(c.Root)

	// Join runtime arguments with the configuration arguments
	runtimeArgs := flag.Args()
	c.Build.ArgsBin = append(c.Build.ArgsBin, runtimeArgs...)

	// Compile the exclude regexes if there are any patterns in the config file
	if len(c.Build.ExcludeRegex) > 0 {
		regexCompiled := make([]*regexp.Regexp, len(c.Build.ExcludeRegex))
		for idx, expr := range c.Build.ExcludeRegex {
			re, err := regexp.Compile(expr)
			if err != nil {
				return fmt.Errorf("failed to compile regex %s", expr)
			}
			regexCompiled[idx] = re
		}
		c.Build.regexCompiled = regexCompiled
	}

	c.Build.ExcludeDir = ed
	if len(c.Build.FullBin) > 0 {
		c.Build.Bin = c.Build.FullBin
		return err
	}
	// Fix windows CMD processor
	// CMD will not recognize relative path like ./tmp/server
	c.Build.Bin, err = filepath.Abs(c.Build.Bin)

	return err
}

func (c *Config) colorInfo() map[string]string {
	return map[string]string{
		"main":    c.Color.Main,
		"build":   c.Color.Build,
		"runner":  c.Color.Runner,
		"watcher": c.Color.Watcher,
	}
}

func (c *Config) buildLogPath() string {
	return joinPath(c.tmpPath(), c.Build.Log)
}

func (c *Config) buildDelay() time.Duration {
	return time.Duration(c.Build.Delay) * time.Millisecond
}

func (c *Config) rerunDelay() time.Duration {
	return time.Duration(c.Build.RerunDelay) * time.Millisecond
}

func (c *Config) killDelay() time.Duration {
	// kill_delay can be specified as an integer or duration string
	// interpret as milliseconds if less than the value of 1 millisecond
	if c.Build.KillDelay < time.Millisecond {
		return c.Build.KillDelay * time.Millisecond
	}
	// normalize kill delay to milliseconds
	return time.Duration(c.Build.KillDelay.Milliseconds()) * time.Millisecond
}

func (c *Config) binPath() string {
	if len(c.Build.Entrypoint) > 0 {
		return c.Build.Entrypoint.binary()
	}
	return joinPath(c.Root, c.Build.Bin)
}

func (c *Config) runnerBin() string {
	if len(c.Build.Entrypoint) > 0 && len(c.Build.FullBin) == 0 {
		return c.Build.Entrypoint.binary()
	}
	return c.Build.Bin
}

func (c *Config) tmpPath() string {
	return joinPath(c.Root, c.TmpDir)
}

func (c *Config) testDataPath() string {
	return joinPath(c.Root, c.TestDataDir)
}

func (c *Config) rel(path string) string {
	s, err := filepath.Rel(c.Root, path)
	if err != nil {
		return ""
	}
	return s
}

func resolveCommandPath(entry string) string {
	if entry == "" || strings.ContainsAny(entry, `/\`) {
		return ""
	}

	path, err := exec.LookPath(entry)
	if err != nil {
		return ""
	}
	return path
}

// withArgs returns a new config with the given arguments added to the configuration.
func (c *Config) withArgs(args map[string]TomlInfo) {
	for _, value := range args {
		// Ignore values that match the default configuration.
		// This ensures user-specified configurations are not overwritten by default values.
		if value.Value != nil && *value.Value != value.fieldValue {
			v := reflect.ValueOf(c)
			setValue2Struct(v, value.fieldPath, *value.Value)
		}
	}

}

func warnDeprecatedBin(cfg *Config) {
	if cfg == nil {
		return
	}
	if cfg.Build.Bin == "" || len(cfg.Build.Entrypoint) > 0 {
		return
	}
	fmt.Fprintln(os.Stdout, "[warning] build.bin is deprecated; set build.entrypoint instead")
}


================================================
FILE: runner/config_test.go
================================================
package runner

import (
	"flag"
	"io"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
	"testing"
	"time"
)

const (
	bin = `./tmp/main`
	cmd = "go build -o ./tmp/main ."
)

func getWindowsConfig() Config {
	build := cfgBuild{
		PreCmd:       []string{"echo Hello Air"},
		Cmd:          "go build -o ./tmp/main .",
		Bin:          "./tmp/main",
		Log:          "build-errors.log",
		IncludeExt:   []string{"go", "tpl", "tmpl", "html"},
		ExcludeDir:   []string{"assets", "tmp", "vendor", "testdata"},
		ExcludeRegex: []string{"_test.go"},
		Delay:        1000,
		StopOnError:  true,
	}
	if runtime.GOOS == "windows" {
		build.Bin = bin
		build.Cmd = cmd
	}

	return Config{
		Root:        ".",
		TmpDir:      "tmp",
		TestDataDir: "testdata",
		Build:       build,
	}
}

func TestBinCmdPath(t *testing.T) {
	t.Parallel()
	var err error

	c := getWindowsConfig()
	err = c.preprocess(nil)
	if err != nil {
		t.Fatal(err)
	}

	if runtime.GOOS == "windows" {
		if strings.HasSuffix(c.Build.Bin, "exe") {
			t.Fail()
		}

		if strings.Contains(c.Build.Bin, "exe") {
			t.Fail()
		}
	} else {

		if strings.HasSuffix(c.Build.Bin, "exe") {
			t.Fail()
		}

		if strings.Contains(c.Build.Bin, "exe") {
			t.Fail()
		}
	}
}

func TestDefaultPathConfig(t *testing.T) {
	tests := []struct {
		name string
		path string
		root string
	}{{
		name: "Invalid Path",
		path: "invalid/path",
		root: ".",
	}, {
		name: "TOML",
		path: "_testdata/toml",
		root: "toml_root",
	}}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Setenv(airWd, tt.path)
			c, err := defaultPathConfig()
			if err != nil {
				t.Fatalf("Should not be fail: %s.", err)
			}

			if got, want := c.Root, tt.root; got != want {
				t.Fatalf("Root is %s, but want %s.", got, want)
			}
		})
	}
}

func TestReadConfByName(t *testing.T) {
	_ = os.Unsetenv(airWd)
	config, _ := readConfByName(dftTOML)
	if config != nil {
		t.Fatalf("expect Config is nil,but get a not nil Config")
	}
}

func TestDefaultPathConfigWithInvalidTOML(t *testing.T) {
	// Test that defaultPathConfig returns an error when .air.toml exists but has parse errors
	// This is a regression test for issue #678
	t.Setenv(airWd, "_testdata/invalid_toml")
	_, err := defaultPathConfig()
	if err == nil {
		t.Fatal("expected error when .air.toml has parse errors, but got nil")
	}
	if !strings.Contains(err.Error(), "failed to parse") {
		t.Fatalf("expected error message to contain 'failed to parse', got: %s", err.Error())
	}
	if !strings.Contains(err.Error(), "defined twice") {
		t.Fatalf("expected error message to contain 'defined twice', got: %s", err.Error())
	}
}

func TestConfPreprocess(t *testing.T) {
	t.Setenv(airWd, "_testdata/toml")
	originalDir, err := os.Getwd()
	if err != nil {
		t.Fatalf("failed to getwd: %v", err)
	}
	t.Cleanup(func() {
		if err := os.Chdir(originalDir); err != nil {
			t.Fatalf("failed to restore working directory: %v", err)
		}
	})

	df := defaultConfig()
	err = df.preprocess(nil)
	if err != nil {
		t.Fatalf("preprocess error %v", err)
	}
	suffix := filepath.Join("_testdata", "toml", "tmp", "main")
	if runtime.GOOS == "windows" {
		suffix += ".exe"
	}
	binPath := df.Build.Bin
	if !strings.HasSuffix(binPath, suffix) {
		t.Fatalf("bin path is %s, but not have suffix  %s.", binPath, suffix)
	}
}

func TestEntrypointResolvesAbsolutePath(t *testing.T) {
	t.Parallel()
	base := t.TempDir()
	rootWithSpace := filepath.Join(base, "with space")
	if err := os.MkdirAll(filepath.Join(rootWithSpace, "tmp"), 0o755); err != nil {
		t.Fatalf("failed to prepare tmp dir: %v", err)
	}

	cfg := defaultConfig()
	cfg.Root = rootWithSpace
	cfg.Build.Entrypoint = entrypoint{"./tmp/main"}

	if err := cfg.preprocess(nil); err != nil {
		t.Fatalf("preprocess error %v", err)
	}

	want := filepath.Join(rootWithSpace, "tmp", "main")
	if got := cfg.Build.Entrypoint.binary(); got != want {
		t.Fatalf("entrypoint is %s, but want %s", got, want)
	}

	if cfg.binPath() != want {
		t.Fatalf("bin path is %s, but want %s", cfg.binPath(), want)
	}
}

func TestEntrypointResolvesFromPath(t *testing.T) {
	root := t.TempDir()
	pathDir := t.TempDir()

	binName := "air-entrypoint-path"
	fileName := binName
	fileContents := "#!/bin/sh\nexit 0\n"
	if runtime.GOOS == "windows" {
		fileName += ".bat"
		fileContents = "@echo off\r\n"
		t.Setenv("PATHEXT", ".BAT;.EXE")
	}
	fullPath := filepath.Join(pathDir, fileName)
	if err := os.WriteFile(fullPath, []byte(fileContents), 0o755); err != nil {
		t.Fatalf("failed to write fake binary: %v", err)
	}
	if runtime.GOOS != "windows" {
		if err := os.Chmod(fullPath, 0o755); err != nil {
			t.Fatalf("failed to make fake binary executable: %v", err)
		}
	}

	t.Setenv("PATH", pathDir+string(os.PathListSeparator)+os.Getenv("PATH"))

	cfg := defaultConfig()
	cfg.Root = root
	cfg.Build.Entrypoint = entrypoint{binName}

	if err := cfg.preprocess(nil); err != nil {
		t.Fatalf("preprocess error %v", err)
	}

	want := fullPath
	if got := cfg.Build.Entrypoint.binary(); got != want {
		t.Fatalf("entrypoint resolved to %s, want %s", got, want)
	}
}

func TestEntrypointPreservesArgs(t *testing.T) {
	t.Parallel()
	root := t.TempDir()
	cfg := defaultConfig()
	cfg.Root = root
	cfg.Build.Entrypoint = entrypoint{"./tmp/main", "server", ":8080"}

	if err := cfg.preprocess(nil); err != nil {
		t.Fatalf("preprocess error %v", err)
	}

	wantBin := filepath.Join(root, "tmp", "main")
	if cfg.Build.Entrypoint.binary() != wantBin {
		t.Fatalf("entrypoint binary is %s, want %s", cfg.Build.Entrypoint.binary(), wantBin)
	}

	wantArgs := []string{"server", ":8080"}
	if got := cfg.Build.Entrypoint.args(); !reflect.DeepEqual(got, wantArgs) {
		t.Fatalf("entrypoint args mismatch, got %v want %v", got, wantArgs)
	}
}

func TestConfigWithRuntimeArgs(t *testing.T) {
	runtimeArg := "-flag=value"

	// inject runtime arg
	oldArgs := os.Args
	defer func() {
		os.Args = oldArgs
		flag.Parse()
	}()
	os.Args = []string{"air", "--", runtimeArg}
	flag.Parse()

	t.Run("when using bin", func(t *testing.T) {
		df := defaultConfig()
		if err := df.preprocess(nil); err != nil {
			t.Fatalf("preprocess error %v", err)
		}

		if !contains(df.Build.ArgsBin, runtimeArg) {
			t.Fatalf("missing expected runtime arg: %s", runtimeArg)
		}
	})

	t.Run("when using full_bin", func(t *testing.T) {
		df := defaultConfig()
		df.Build.FullBin = "./tmp/main"
		if err := df.preprocess(nil); err != nil {
			t.Fatalf("preprocess error %v", err)
		}

		if !contains(df.Build.ArgsBin, runtimeArg) {
			t.Fatalf("missing expected runtime arg: %s", runtimeArg)
		}
	})
}

func TestReadConfigWithWrongPath(t *testing.T) {
	t.Parallel()
	c, err := readConfig("xxxx")
	if err == nil {
		t.Fatal("need throw a error")
	}
	if c != nil {
		t.Fatal("expect is nil but got a conf")
	}
}

func TestKillDelay(t *testing.T) {
	t.Parallel()
	config := Config{
		Build: cfgBuild{
			KillDelay: 1000,
		},
	}
	if config.killDelay() != (1000 * time.Millisecond) {
		t.Fatal("expect KillDelay 1000 to be interpreted as 1000 milliseconds, got ", config.killDelay())
	}
	config.Build.KillDelay = 1
	if config.killDelay() != (1 * time.Millisecond) {
		t.Fatal("expect KillDelay 1 to be interpreted as 1 millisecond, got ", config.killDelay())
	}
	config.Build.KillDelay = 1_000_000
	if config.killDelay() != (1 * time.Millisecond) {
		t.Fatal("expect KillDelay 1_000_000 to be interpreted as 1 millisecond, got ", config.killDelay())
	}
	config.Build.KillDelay = 100_000_000
	if config.killDelay() != (100 * time.Millisecond) {
		t.Fatal("expect KillDelay 100_000_000 to be interpreted as 100 milliseconds, got ", config.killDelay())
	}
	config.Build.KillDelay = 0
	if config.killDelay() != 0 {
		t.Fatal("expect KillDelay 0 to be interpreted as 0, got ", config.killDelay())
	}
}

func contains(sl []string, target string) bool {
	for _, c := range sl {
		if c == target {
			return true
		}
	}
	return false
}

func TestWarnDeprecatedBin(t *testing.T) {
	t.Parallel()
	tmpDir := t.TempDir()
	cfgPath := filepath.Join(tmpDir, ".air.toml")
	cfgContent := `
[build]
bin = "./tmp/main"
cmd = "go build -o ./tmp/main ."
`
	if err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {
		t.Fatalf("failed to write config: %v", err)
	}

	oldStdout := os.Stdout
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatalf("failed to create pipe: %v", err)
	}
	os.Stdout = w

	_, _ = InitConfig(cfgPath, nil)

	if err := w.Close(); err != nil {
		t.Fatalf("failed to close writer: %v", err)
	}
	os.Stdout = oldStdout

	out, err := io.ReadAll(r)
	if err != nil {
		t.Fatalf("failed to read output: %v", err)
	}
	output := string(out)
	if !strings.Contains(output, "build.bin is deprecated") {
		t.Fatalf("missing bin deprecation warning in output: %q", output)
	}
}

func TestWarnIgnoreDangerousRootDirProtection(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("root dir protection uses Unix root path")
	}

	tmpDir := t.TempDir()
	t.Setenv("HOME", tmpDir)
	t.Run("when ignore_dangerous_root_dir is true", func(t *testing.T) {
		cfgPath := filepath.Join(tmpDir, ".air.toml")
		cfgContent := `
root = "/"

[build]
entrypoint = "tmp/main"
cmd = "go build -o ./tmp/main ."
ignore_dangerous_root_dir = true
`
		if err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {
			t.Fatalf("failed to write config: %v", err)
		}

		oldStdout := os.Stdout
		r, w, err := os.Pipe()
		if err != nil {
			t.Fatalf("failed to create pipe: %v", err)
		}
		os.Stdout = w

		_, _ = InitConfig(cfgPath, nil)

		if err := w.Close(); err != nil {
			t.Fatalf("failed to close writer: %v", err)
		}
		os.Stdout = oldStdout

		out, err := io.ReadAll(r)
		if err != nil {
			t.Fatalf("failed to read output: %v", err)
		}
		output := string(out)
		if !strings.Contains(output, "ignoring root directory protections. This could cause excessive file watching. It is recommended to run air in a project directory") {
			t.Fatalf("missing root directory protection warning in output: %q", output)
		}
	})
	t.Run("when ignore_dangerous_root_dir is false", func(t *testing.T) {
		cfgPath := filepath.Join(tmpDir, ".air.toml")
		cfgContent := `
root = "/"

[build]
entrypoint = "tmp/main"
cmd = "go build -o ./tmp/main ."
ignore_dangerous_root_dir = false
`
		if err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {
			t.Fatalf("failed to write config: %v", err)
		}

		oldStdout := os.Stdout
		r, w, err := os.Pipe()
		if err != nil {
			t.Fatalf("failed to create pipe: %v", err)
		}
		os.Stdout = w

		_, _ = InitConfig(cfgPath, nil)

		if err := w.Close(); err != nil {
			t.Fatalf("failed to close writer: %v", err)
		}
		os.Stdout = oldStdout

		out, err := io.ReadAll(r)
		if err != nil {
			t.Fatalf("failed to read output: %v", err)
		}
		output := string(out)
		if strings.Contains(output, "ignoring root directory protections") {
			t.Fatalf("unexpected root directory protection warning in output: %q", output)
		}
	})

	t.Run("when ignore_dangerous_root_dir is not set", func(t *testing.T) {
		cfgPath := filepath.Join(tmpDir, ".air.toml")
		cfgContent := `
root = "/"

[build]
entrypoint = "tmp/main"
cmd = "go build -o ./tmp/main ."
`
		if err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {
			t.Fatalf("failed to write config: %v", err)
		}

		oldStdout := os.Stdout
		r, w, err := os.Pipe()
		if err != nil {
			t.Fatalf("failed to create pipe: %v", err)
		}
		os.Stdout = w

		_, _ = InitConfig(cfgPath, nil)

		if err := w.Close(); err != nil {
			t.Fatalf("failed to close writer: %v", err)
		}
		os.Stdout = oldStdout

		out, err := io.ReadAll(r)
		if err != nil {
			t.Fatalf("failed to read output: %v", err)
		}
		output := string(out)
		if strings.Contains(output, "ignoring root directory protections") {
			t.Fatalf("unexpected root directory protection warning in output: %q", output)
		}
	})
}


================================================
FILE: runner/engine.go
================================================
package runner

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/gohugoio/hugo/watcher/filenotify"
	"github.com/joho/godotenv"
)

// Engine ...
type Engine struct {
	config *Config

	exiter    exiter
	proxy     *Proxy
	logger    *logger
	watcher   filenotify.FileWatcher
	debugMode bool
	runArgs   []string
	running   atomic.Bool

	eventCh       chan string
	watcherStopCh chan bool
	// buildRunCh serves dual purpose:
	// 1. As a semaphore ensuring only one build runs at a time (buffer size 1)
	// 2. Carries each build's unique stop channel for cancellation
	// When a new build starts, it retrieves the previous build's stop channel,
	// closes it to signal cancellation, then inserts its own fresh channel.
	// This prevents the race condition where a new build could consume a stop
	// signal meant for a previous build (issue #784).
	buildRunCh chan chan struct{}
	// binStopCh is a channel for process termination control
	// Type chan<- chan int indicates it's a send-only channel that transmits another channel(chan int)
	binStopCh chan<- chan int
	exitCh    chan bool

	mu            sync.RWMutex
	watchers      uint
	fileChecksums *checksumMap

	ll sync.Mutex // lock for logger

	// globalEnv stores the original env values before air modified them
	// key:original value (empty string means it was unset)
	globalEnv map[string]*string
	// loadedEnv tracks env values that were set by the last env file load
	loadedEnv map[string]string
}

// NewEngineWithConfig ...
func NewEngineWithConfig(cfg *Config, debugMode bool) (*Engine, error) {
	logger := newLogger(cfg)
	watcher, err := newWatcher(cfg)
	if err != nil {
		return nil, err
	}
	var entryArgs []string
	if len(cfg.Build.FullBin) == 0 {
		entryArgs = cfg.Build.Entrypoint.args()
	}
	runArgs := make([]string, 0, len(entryArgs)+len(cfg.Build.ArgsBin))
	if len(entryArgs) > 0 {
		runArgs = append(runArgs, entryArgs...)
	}
	runArgs = append(runArgs, cfg.Build.ArgsBin...)
	e := Engine{
		config:        cfg,
		exiter:        defaultExiter{},
		proxy:         NewProxy(&cfg.Proxy),
		logger:        logger,
		watcher:       watcher,
		debugMode:     debugMode,
		runArgs:       runArgs,
		eventCh:       make(chan string, 1000),
		watcherStopCh: make(chan bool, 10),
		buildRunCh:    make(chan chan struct{}, 1),
		exitCh:        make(chan bool),
		fileChecksums: &checksumMap{m: make(map[string]string)},
		watchers:      0,
		globalEnv:     map[string]*string{},
	}

	return &e, nil
}

// NewEngine ...
func NewEngine(cfgPath string, args map[string]TomlInfo, debugMode bool) (*Engine, error) {
	var err error
	cfg, err := InitConfig(cfgPath, args)
	if err != nil {
		return nil, err
	}
	return NewEngineWithConfig(cfg, debugMode)
}

// Run run run
func (e *Engine) Run() {
	if len(os.Args) > 1 && os.Args[1] == "init" {
		configName, err := writeDefaultConfig()
		if err != nil {
			log.Fatalf("Failed writing default config: %+v", err)
		}
		fmt.Printf("%s file created to the current directory with the default settings\n", configName)
		return
	}

	e.mainDebug("CWD: %s", e.config.Root)

	var err error
	if err = e.checkRunEnv(); err != nil {
		os.Exit(1)
	}
	if err = e.watchConfiguredDirs(); err != nil {
		os.Exit(1)
	}

	e.start()
	e.cleanup()
}

func (e *Engine) checkRunEnv() error {
	p := e.config.tmpPath()
	if _, err := os.Stat(p); os.IsNotExist(err) {
		e.runnerLog("mkdir %s", p)
		if err := os.MkdirAll(p, 0o755); err != nil {
			e.runnerLog("failed to mkdir, error: %s", err.Error())
			return err
		}
	}
	return nil
}

func (e *Engine) watchConfiguredDirs() error {
	type watchTarget struct {
		path     string
		optional bool
	}
	targets := []watchTarget{{path: e.config.Root, optional: false}}
	for _, dir := range e.config.Build.extraIncludeDirs {
		targets = append(targets, watchTarget{path: dir, optional: true})
	}

	seen := make(map[string]struct{}, len(targets))
	for _, target := range targets {
		if target.path == "" {
			continue
		}
		cleaned := filepath.Clean(target.path)
		if _, ok := seen[cleaned]; ok {
			continue
		}
		if _, err := os.Stat(cleaned); err != nil {
			if os.IsNotExist(err) && target.optional {
				e.watcherLog("include_dir %s does not exist, skipping", e.config.rel(cleaned))
				continue
			}
			return err
		}
		if err := e.watching(cleaned); err != nil {
			return err
		}
		seen[cleaned] = struct{}{}
	}
	return nil
}

func (e *Engine) watching(root string) error {
	return filepath.Walk(root, func(path string, info os.FileInfo, _ error) error {
		// NOTE: path is absolute
		if info != nil && !info.IsDir() {
			if e.checkIncludeFile(path) {
				return e.watchPath(path)
			}
			return nil
		}
		// exclude tmp dir
		if e.isTmpDir(path) {
			e.watcherLog("!exclude %s", e.config.rel(path))
			return filepath.SkipDir
		}
		// exclude testdata dir
		if e.isTestDataDir(path) {
			e.watcherLog("!exclude %s", e.config.rel(path))
			return filepath.SkipDir
		}
		// exclude hidden directories like .git, .idea, etc.
		if isHiddenDirectory(path) {
			return filepath.SkipDir
		}
		// exclude user specified directories
		if e.isExcludeDir(path) {
			e.watcherLog("!exclude %s", e.config.rel(path))
			return filepath.SkipDir
		}
		isIn, walkDir := e.checkIncludeDir(path)
		if !walkDir {
			e.watcherLog("!exclude %s", e.config.rel(path))
			return filepath.SkipDir
		}
		if isIn {
			return e.watchPath(path)
		}
		return nil
	})
}

// cacheFileChecksums calculates and stores checksums for each non-excluded file it finds from root.
func (e *Engine) cacheFileChecksums(root string) error {
	return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			if info == nil {
				return err
			}
			if info.IsDir() {
				return filepath.SkipDir
			}
			return err
		}

		if !info.Mode().IsRegular() {
			if e.isTmpDir(path) || e.isTestDataDir(path) || isHiddenDirectory(path) || e.isExcludeDir(path) {
				e.watcherDebug("!exclude checksum %s", e.config.rel(path))
				return filepath.SkipDir
			}

			// Follow symbolic link
			if e.config.Build.FollowSymlink && (info.Mode()&os.ModeSymlink) > 0 {
				link, err := filepath.EvalSymlinks(path)
				if err != nil {
					return err
				}
				linkInfo, err := os.Stat(link)
				if err != nil {
					return err
				}
				if linkInfo.IsDir() {
					err = e.watchPath(link)
					if err != nil {
						return err
					}
				}
				return nil
			}
		}

		if e.isExcludeFile(path) || !e.isIncludeExt(path) && !e.checkIncludeFile(path) {
			e.watcherDebug("!exclude checksum %s", e.config.rel(path))
			return nil
		}

		excludeRegex, err := e.isExcludeRegex(path)
		if err != nil {
			return err
		}
		if excludeRegex {
			e.watcherDebug("!exclude checksum %s", e.config.rel(path))
			return nil
		}

		// update the checksum cache for the current file
		_ = e.isModified(path)

		return nil
	})
}

func (e *Engine) watchPath(path string) error {
	if err := e.watcher.Add(path); err != nil {
		e.watcherLog("failed to watch %s, error: %s", path, err.Error())
		return err
	}
	e.watcherLog("watching %s", e.config.rel(path))

	go func() {
		e.withLock(func() {
			e.watchers++
		})
		defer func() {
			e.withLock(func() {
				e.watchers--
			})
		}()

		if e.config.Build.ExcludeUnchanged {
			err := e.cacheFileChecksums(path)
			if err != nil {
				e.watcherLog("error building checksum cache: %v", err)
			}
		}

		for {
			select {
			case <-e.watcherStopCh:
				return
			case ev := <-e.watcher.Events():
				e.mainDebug("event: %+v", ev)
				if !validEvent(ev) {
					break
				}
				if isDir(ev.Name) {
					e.watchNewDir(ev.Name, removeEvent(ev))
					break
				}
				if e.isExcludeFile(ev.Name) {
					break
				}
				excludeRegex, _ := e.isExcludeRegex(ev.Name)
				if excludeRegex {
					break
				}
				if !e.isIncludeExt(ev.Name) && !e.checkIncludeFile(ev.Name) {
					break
				}
				e.watcherDebug("%s has changed", e.config.rel(ev.Name))
				e.eventCh <- ev.Name
			case err := <-e.watcher.Errors():
				e.watcherLog("error: %s", err.Error())
			}
		}
	}()
	return nil
}

func (e *Engine) watchNewDir(dir string, removeDir bool) {
	if e.isTmpDir(dir) {
		return
	}
	if e.isTestDataDir(dir) {
		return
	}
	if isHiddenDirectory(dir) || e.isExcludeDir(dir) {
		e.watcherLog("!exclude %s", e.config.rel(dir))
		return
	}
	if removeDir {
		if err := e.watcher.Remove(dir); err != nil {
			e.watcherLog("failed to stop watching %s, error: %s", dir, err.Error())
		}
		return
	}
	go func(dir string) {
		if err := e.watching(dir); err != nil {
			e.watcherLog("failed to watching %s, error: %s", dir, err.Error())
		}
	}(dir)
}

func (e *Engine) isModified(filename string) bool {
	newChecksum, err := fileChecksum(filename)
	if err != nil {
		e.watcherDebug("can't determine if file was changed: %v - assuming it did without updating cache", err)
		return true
	}

	if e.fileChecksums.updateFileChecksum(filename, newChecksum) {
		e.watcherDebug("stored checksum for %s: %s", e.config.rel(filename), newChecksum)
		return true
	}

	return false
}

// Endless loop and never return
func (e *Engine) start() {
	if e.config.Proxy.Enabled {
		go e.proxy.Run()
		e.mainLog("Proxy server listening on http://localhost%s", e.proxy.server.Addr)
	}

	e.running.Store(true)
	firstRunCh := make(chan bool, 1)
	firstRunCh <- true

	for {
		var filename string

		select {
		case <-e.exitCh:
			e.mainDebug("exit in start")
			return
		case filename = <-e.eventCh:
			if !e.isIncludeExt(filename) && !e.checkIncludeFile(filename) {
				continue
			}
			if e.config.Build.ExcludeUnchanged {
				if !e.isModified(filename) {
					e.mainLog("skipping %s because contents unchanged", e.config.rel(filename))
					continue
				}
			}

			// cannot set buildDelay to 0, because when the write multiple events received in short time
			// it will start Multiple buildRuns: https://github.com/air-verse/air/issues/473
			time.Sleep(e.config.buildDelay())
			e.flushEvents()

			if e.config.Screen.ClearOnRebuild {
				if e.config.Screen.KeepScroll {
					// https://stackoverflow.com/questions/22891644/how-can-i-clear-the-terminal-screen-in-go
					fmt.Print("\033[2J")
				} else {
					// https://stackoverflow.com/questions/5367068/clear-a-terminal-screen-for-real/5367075#5367075
					fmt.Print("\033c")
				}
			}

			e.mainLog("%s has changed", e.config.rel(filename))
		case <-firstRunCh:
			// go down
		}

		// Stop any currently running build by closing its stop channel
		select {
		case oldStopCh := <-e.buildRunCh:
			// Close the old build's stop channel to signal it to stop
			close(oldStopCh)
		default:
			// No build is currently running
		}

		// if current app is running, stop it
		e.stopBin()

		go e.buildRun()
	}
}

func (e *Engine) loadEnvFile() {
	if len(e.config.EnvFiles) == 0 {
		return
	}

	// assume refreshed env is as big as the loaded env
	newEnv := make(map[string]string, len(e.loadedEnv))

	for _, envPath := range e.config.EnvFiles {
		if !filepath.IsAbs(envPath) {
			envPath = filepath.Join(e.config.Root, envPath)
		}
		file, err := os.Open(envPath)
		if err != nil {
			if os.IsNotExist(err) {
				e.mainDebug("env file %q does not exist, skipping", envPath)
			} else {
				e.runnerLog("failed to open env file %q: %s", envPath, err.Error())
			}
			continue
		}
		defer file.Close()
		fileEnv, err := godotenv.Parse(file)
		if err != nil {
			e.runnerLog("failed to parse env file %q: %s", envPath, err.Error())
			return
		}

		for k, v := range fileEnv {
			if v, tracked := e.globalEnv[k]; !tracked {
				origVal, exists := os.LookupEnv(k)
				if exists {
					// not used yet, but might be useful for a future "override" feature
					e.globalEnv[k] = &origVal
					continue // untracked env values are likely global - don't override them
				}
				// on first encounter of a key, if no global value exists, mark as nil so
				// that on next load of .env file, globalEnv map value will not be overwritten
				e.globalEnv[k] = nil
			} else if tracked && v != nil {
				// only set values from file if not already present in the environment
				e.mainDebug("key %q already exists in the environment, skipping", k)
				continue
			}
			if err := os.Setenv(k, v); err != nil {
				e.runnerLog("failed to set env key %q: %s", k, err.Error())
			}
			newEnv[k] = v
		}
	}

	// unset any keys that were removed from .env file,
	// but ignore those that were set before air was run
	for k := range e.loadedEnv {
		if _, exists := newEnv[k]; !exists {
			if orig := e.globalEnv[k]; orig == nil {
				if err := os.Unsetenv(k); err != nil {
					e.runnerLog("failed to restore env key %q: %s", k, err.Error())
				}
			}
		}
	}

	e.loadedEnv = newEnv
}

func (e *Engine) buildRun() {
	// Create this build's unique stop channel
	myStopCh := make(chan struct{})

	// Put our stop channel in buildRunCh (acts as semaphore + carries our stop token)
	e.buildRunCh <- myStopCh
	defer func() {
		<-e.buildRunCh
	}()

	// Check if we were already signaled to stop before we even started
	select {
	case <-myStopCh:
		return
	case <-e.exitCh:
		e.mainDebug("exit in buildRun before pre_cmd")
		return
	default:
	}

	e.loadEnvFile()

	var err error
	if err = e.runPreCmd(); err != nil {
		e.runnerLog("failed to execute pre_cmd: %s", err.Error())
		if e.config.Build.StopOnError {
			return
		}
	}
	if output, err := e.building(); err != nil {
		e.buildLog("failed to build, error: %s", err.Error())
		_ = e.writeBuildErrorLog(err.Error())
		if e.config.Build.StopOnError {
			// It only makes sense to run it if we stop on error. Otherwise when
			// running the binary again the error modal will be overwritten by
			// the reload.
			if e.config.Proxy.Enabled {
				e.proxy.BuildFailed(BuildFailedMsg{
					Error:   err.Error(),
					Command: e.config.Build.Cmd,
					Output:  output,
				})
			}
			return
		}
	}

	// Check again before running the binary
	select {
	case <-myStopCh:
		return
	case <-e.exitCh:
		e.mainDebug("exit in buildRun after build")
		return
	default:
	}

	if err = e.runBin(); err != nil {
		e.runnerLog("failed to run, error: %s", err.Error())
	}
}

func (e *Engine) flushEvents() {
	for {
		select {
		case <-e.eventCh:
			e.mainDebug("flushing events")
		default:
			return
		}
	}
}

// utility to execute commands, such as cmd & pre_cmd
func (e *Engine) runCommand(command string) error {
	cmd, stdout, stderr, err := e.startCmd(command)
	if err != nil {
		return err
	}
	defer func() {
		stdout.Close()
		stderr.Close()
	}()

	copyOutput(os.Stdout, stdout)
	copyOutput(os.Stderr, stderr)

	// wait for command to finish
	return cmd.Wait()
}

func (e *Engine) runCommandCopyOutput(command string) (string, error) {
	// both stdout and stderr are piped to the same buffer, so ignore the second
	// one
	cmd, stdout, _, err := e.startCmd(command)
	if err != nil {
		return "", err
	}
	defer func() {
		stdout.Close()
	}()

	stdoutBytes, _ := io.ReadAll(stdout)
	_, _ = io.Copy(os.Stdout, strings.NewReader(string(stdoutBytes)))

	// wait for command to finish
	err = cmd.Wait()
	if err != nil {
		return string(stdoutBytes), err
	}
	return string(stdoutBytes), nil
}

// run cmd option in .air.toml
func (e *Engine) building() (string, error) {
	e.buildLog("building...")
	output, err := e.runCommandCopyOutput(e.config.Build.Cmd)
	if err != nil {
		return output, err
	}
	return output, nil
}

// run pre_cmd option in .air.toml
func (e *Engine) runPreCmd() error {
	for _, command := range e.config.Build.PreCmd {
		e.runnerLog("> %s", command)
		err := e.runCommand(command)
		if err != nil {
			return err
		}
	}
	return nil
}

// run post_cmd option in .air.toml
func (e *Engine) runPostCmd() error {
	for _, command := range e.config.Build.PostCmd {
		e.runnerLog("> %s", command)
		err := e.runCommand(command)
		if err != nil {
			return err
		}
	}
	return nil
}

func (e *Engine) runBin() error {
	// killFunc returns a chan of chan of int that should be used to shutdown the bin currently being run
	// The chan int that is passed in will be used to signal completion of the shutdown
	killFunc := func(cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, killCh chan<- struct{}, processExit <-chan struct{}) chan<- chan int {
		shutdown := make(chan chan int)
		var closer chan int

		go func() {
			defer func() {
				stdout.Close()
				stderr.Close()
			}()

			select {
			case closer = <-shutdown:
				// stopBin has been called from start or cleanup
				// defer the signalling of shutdown completion before attempting to kill further down
				defer close(closer)
				defer close(killCh)
			case <-processExit:
				// the process is exited, return
				e.withLock(func() {
					// Avoid deadlocking any racing shutdown request
					select {
					case c := <-shutdown:
						close(c)
					default:
					}
					e.binStopCh = nil
				})
				return
			}

			e.mainDebug("trying to kill pid %d, cmd %+v", cmd.Process.Pid, cmd.Args)

			pid, err := e.killCmd(cmd)
			if err != nil {
				e.mainDebug("failed to kill PID %d, error: %s", pid, err.Error())
				if cmd.ProcessState != nil && !cmd.ProcessState.Exited() {
					// Pass a non zero exit code to the closer to delegate the
					// decision wether to os.Exit or not
					closer <- 1
				}
			} else {
				e.mainDebug("cmd killed, pid: %d", pid)
			}

			if e.config.Build.StopOnError {
				relBinPath := e.config.rel(e.config.binPath())
				if relBinPath == "" || strings.HasPrefix(relBinPath, "..") {
					return
				}
				cmdBinPath := cmdPath(relBinPath)
				if _, err = os.Stat(cmdBinPath); os.IsNotExist(err) {
					return
				}
				if err = os.Remove(cmdBinPath); err != nil {
					e.mainLog("failed to remove %s, error: %s", relBinPath, err)
				}
			}
		}()

		return shutdown
	}

	e.runnerLog("running...")
	go func() {

		defer func() {
			select {
			case <-e.exitCh:
				e.mainDebug("exit in runBin")
			default:
			}
		}()

		// control killFunc should be kill or not
		killCh := make(chan struct{})
		for {
			select {
			case <-killCh:
				return
			default:
				formattedBin := formatPath(e.config.runnerBin())
				command := strings.Join(append([]string{formattedBin}, e.runArgs...), " ")
				cmd, stdout, stderr, err := e.startCmd(command)
				if err != nil {
					e.mainLog("failed to start %s, error: %s", e.config.rel(e.config.binPath()), err.Error())
					close(killCh)
					continue
				}

				processExit := make(chan struct{})
				e.mainDebug("running process pid %v", cmd.Process.Pid)
				if e.config.Proxy.Enabled {
					e.mainDebug("reloading proxy")
					e.proxy.Reload()
				}

				e.stopBin()
				e.withLock(func() {
					e.binStopCh = killFunc(cmd, stdout, stderr, killCh, processExit)
				})

				go copyOutput(os.Stdout, stdout)
				go copyOutput(os.Stderr, stderr)

				state, _ := cmd.Process.Wait()
				close(processExit)

				switch state.ExitCode() {
				case 0:
					e.runnerLog("Process Exit with Code 0")
				case -1:
					// because when we use ctrl + c to stop will return -1
				default:
					e.runnerLog("Process Exit with Code: %v", state.ExitCode())
				}

				if !e.config.Build.Rerun {
					return
				}
				time.Sleep(e.config.rerunDelay())
			}
		}
	}()

	return nil
}

func (e *Engine) stopBin() {
	e.mainDebug("initiating shutdown sequence")
	start := time.Now()
	e.mainDebug("shutdown completed in %v", time.Since(start))

	exitCode := make(chan int)

	e.withLock(func() {
		if e.binStopCh != nil {
			e.mainDebug("sending shutdown command to killfunc")
			e.binStopCh <- exitCode
			e.binStopCh = nil
		} else {
			close(exitCode)
		}
	})

	select {
	case ret := <-exitCode:
		if ret != 0 {
			e.exiter.Exit(ret) // Use exiter instead of direct os.Exit, it's for tests purpose.
		}
	case <-time.After(5 * time.Second):
		e.mainDebug("timed out waiting for process exit")
	}
}

func (e *Engine) cleanup() {
	e.mainLog("cleaning...")
	defer e.mainLog("see you again~")
	defer e.mainDebug("exited")

	if e.config.Proxy.Enabled {
		e.mainDebug("powering down the proxy...")
		if err := e.proxy.Stop(); err != nil {
			e.mainLog("failed to stop proxy: %+v", err)
		}
	}

	e.stopBin()
	e.mainDebug("waiting for close watchers..")

	e.withLock(func() {
		for i := 0; i < int(e.watchers); i++ {
			e.watcherStopCh <- true
		}
	})

	e.mainDebug("waiting for buildRun...")
	var err error
	if err = e.watcher.Close(); err != nil {
		e.mainLog("failed to close watcher, error: %s", err.Error())
	}

	e.mainDebug("waiting for clean ...")

	if e.config.Misc.CleanOnExit {
		e.mainLog("deleting %s", e.config.tmpPath())
		if err = os.RemoveAll(e.config.tmpPath()); err != nil {
			e.mainLog("failed to delete tmp dir, err: %+v", err)
		}
	}

	e.running.Store(false)
}

// Stop the air
func (e *Engine) Stop() {
	if err := e.runPostCmd(); err != nil {
		e.runnerLog("failed to execute post_cmd, error: %s", err.Error())
	}
	close(e.exitCh)
}


================================================
FILE: runner/engine_test.go
================================================
package runner

import (
	"errors"
	"fmt"
	"log"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"syscall"
	"testing"
	"time"

	"github.com/pelletier/go-toml"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestNewEngine(t *testing.T) {
	_ = os.Unsetenv(airWd)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if engine.logger == nil {
		t.Fatal("logger should not be nil")
	}
	if engine.config == nil {
		t.Fatal("Config should not be nil")
	}
	if engine.watcher == nil {
		t.Fatal("watcher should not be nil")
	}
}

func TestCheckRunEnv(t *testing.T) {
	_ = os.Unsetenv(airWd)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	nestedTmpDir := filepath.Join(t.TempDir(), "nested", "build")
	engine.config.TmpDir = nestedTmpDir

	err = engine.checkRunEnv()
	require.NoError(t, err)
	assert.DirExists(t, nestedTmpDir)
}

func TestWatching(t *testing.T) {
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	path, err := os.Getwd()
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	path = strings.Replace(path, filepath.Join("_testdata", "toml"), "", 1)
	err = engine.watching(filepath.Join(path, "_testdata", "watching"))
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
}

func TestRegexes(t *testing.T) {
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	engine.config.Build.ExcludeRegex = []string{"foo\\.html$", "bar", "_test\\.go"}
	err = engine.config.preprocess(nil)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	result, err := engine.isExcludeRegex("./test/foo.html")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if result != true {
		t.Errorf("expected '%t' but got '%t'", true, result)
	}

	result, err = engine.isExcludeRegex("./test/bar/index.html")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if result != true {
		t.Errorf("expected '%t' but got '%t'", true, result)
	}

	result, err = engine.isExcludeRegex("./test/unrelated.html")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if result {
		t.Errorf("expected '%t' but got '%t'", false, result)
	}

	result, err = engine.isExcludeRegex("./myPackage/goFile_testxgo")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if result {
		t.Errorf("expected '%t' but got '%t'", false, result)
	}
	result, err = engine.isExcludeRegex("./myPackage/goFile_test.go")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if result != true {
		t.Errorf("expected '%t' but got '%t'", true, result)
	}
}

func TestRunCommand(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("requires touch")
	}

	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)
	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	err = engine.runCommand("touch test.txt")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if _, err := os.Stat("./test.txt"); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Should not be fail: %s.", err)
		}
	}
}

func TestRunPreCmd(t *testing.T) {
	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)
	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if runtime.GOOS == "windows" {
		engine.config.Build.PreCmd = []string{`cmd.exe /c "echo hello air > pre_cmd.txt"`}
	} else {
		engine.config.Build.PreCmd = []string{"echo 'hello air' > pre_cmd.txt"}
	}
	err = engine.runPreCmd()
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if _, err := os.Stat("./pre_cmd.txt"); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Should not be fail: %s.", err)
		}
	}
}

func TestRunPostCmd(t *testing.T) {
	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)
	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)

	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if runtime.GOOS == "windows" {
		engine.config.Build.PostCmd = []string{`cmd.exe /c "echo hello air > post_cmd.txt"`}
	} else {
		engine.config.Build.PostCmd = []string{"echo 'hello air' > post_cmd.txt"}
	}
	err = engine.runPostCmd()
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	if _, err := os.Stat("./post_cmd.txt"); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Should not be fail: %s.", err)
		}
	}
}

func TestRunBin(t *testing.T) {
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	err = engine.runBin()
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
}

func GetPort() (int, func()) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	port := l.Addr().(*net.TCPAddr).Port
	if err != nil {
		panic(err)
	}
	return port, func() {
		_ = l.Close()
	}
}

func TestRebuild(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("unstable on Windows")
	}

	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	engine.config.Build.ExcludeUnchanged = true
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		engine.Run()
		t.Logf("engine stopped")
		wg.Done()
	}()
	err = waitingPortReady(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	t.Logf("port is ready")

	// start rebuild

	t.Logf("start change main.go")
	// change file of main.go
	// just append a new empty line to main.go
	file, err := os.OpenFile("main.go", os.O_APPEND|os.O_WRONLY, 0o644)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	defer file.Close()
	_, err = file.WriteString("\n")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	err = waitingPortConnectionRefused(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("timeout: %s.", err)
	}
	t.Logf("connection refused")
	err = waitingPortReady(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	t.Logf("port is ready")
	// stop engine
	engine.Stop()
	t.Logf("engine stopped")
	// Wait for engine to fully stop
	err = waitForEngineState(t, engine, false, time.Second*3)
	if err != nil {
		t.Fatalf("engine did not stop: %s.", err)
	}
	wg.Wait()
	assert.True(t, checkPortConnectionRefused(port))
}

func waitingPortConnectionRefused(t *testing.T, port int, timeout time.Duration) error {
	t.Helper()
	t.Logf("waiting port %d connection refused", port)

	// Use environment-aware timeout for CI compatibility
	timeoutMultiplier := 1.0
	if os.Getenv("CI") != "" {
		timeoutMultiplier = 2.0
	}
	adjustedTimeout := time.Duration(float64(timeout) * timeoutMultiplier)

	deadline := time.Now().Add(adjustedTimeout)
	ticker := time.NewTicker(20 * time.Millisecond) // Reduced from 100ms to 20ms
	defer ticker.Stop()

	for {
		_, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
		if errors.Is(err, syscall.ECONNREFUSED) {
			return nil
		}

		if time.Now().After(deadline) {
			return fmt.Errorf("timeout waiting for port %d connection refused (timeout: %v)", port, adjustedTimeout)
		}

		<-ticker.C
	}
}

func TestCtrlCWhenHaveKillDelay(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("unstable on Windows")
	}

	// fix https://github.com/air-verse/air/issues/278
	// generate a random port
	data := []byte("[build]\n  kill_delay = \"2s\"")
	c := Config{}
	if err := toml.Unmarshal(data, &c); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	engine.config.Build.KillDelay = c.Build.KillDelay
	engine.config.Build.Delay = 2000
	engine.config.Build.SendInterrupt = true
	if err := engine.config.preprocess(nil); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	go func() {
		engine.Run()
		t.Logf("engine stopped")
	}()
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	go func() {
		<-sigs
		engine.Stop()
		t.Logf("engine stopped")
	}()
	if err := waitingPortReady(t, port, time.Second*10); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	sigs <- syscall.SIGINT
	err = waitingPortConnectionRefused(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	// Wait for engine to fully stop - the test has kill_delay="2s"
	err = waitForEngineState(t, engine, false, time.Second*5)
	if err != nil {
		t.Logf("engine may not have stopped in time: %s", err)
	}
	assert.False(t, engine.running.Load())
}

func TestCtrlCWhenREngineIsRunning(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("unstable on Windows")
	}

	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	go func() {
		engine.Run()
		t.Logf("engine stopped")
	}()
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigs
		engine.Stop()
		t.Logf("engine stopped")
	}()
	if err := waitingPortReady(t, port, time.Second*10); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	sigs <- syscall.SIGINT
	time.Sleep(time.Second * 1)
	err = waitingPortConnectionRefused(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	assert.False(t, engine.running.Load())
}

func TestCtrlCWithFailedBin(t *testing.T) {
	timeout := 5 * time.Second
	done := make(chan struct{})
	go func() {
		dir := initWithQuickExitGoCode(t)
		chdir(t, dir)
		engine, err := NewEngine("", nil, true)
		assert.NoError(t, err)
		engine.config.Build.Bin = "<WRONGCOMAMND>"
		sigs := make(chan os.Signal, 1)
		signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
		var wg sync.WaitGroup
		wg.Add(1)
		go func() {
			engine.Run()
			t.Logf("engine stopped")
			wg.Done()
		}()
		go func() {
			<-sigs
			engine.Stop()
			t.Logf("engine stopped")
		}()
		time.Sleep(time.Second * 1)
		sigs <- syscall.SIGINT
		wg.Wait()
		close(done)
	}()
	select {
	case <-done:
	case <-time.After(timeout):
		t.Error("Test timed out")
	}
}

func TestFixCloseOfChannelAfterCtrlC(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("unstable on Windows")
	}

	// fix https://github.com/air-verse/air/issues/294
	dir := initWithBuildFailedCode(t)
	chdir(t, dir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	// Silence engine logs to keep this test output readable.
	engine.config.Log.Silent = true
	silenceBuildCmd(engine.config)
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	defer signal.Stop(sigs)
	go func() {
		engine.Run()
		t.Logf("engine stopped")
	}()

	go func() {
		<-sigs
		engine.Stop()
		t.Logf("engine stopped")
	}()
	buildLogPath := engine.config.buildLogPath()
	if err := waitForCondition(t, time.Second*5, func() bool {
		info, err := os.Stat(buildLogPath)
		if err != nil {
			return false
		}
		return info.Size() > 0
	}, "first build failure log"); err != nil {
		t.Fatalf("build did not fail as expected: %s", err)
	}
	port, f := GetPort()
	f()
	// correct code
	err = generateGoCode(dir, port)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	if err := waitingPortReady(t, port, time.Second*10); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	// ctrl + c
	sigs <- syscall.SIGINT
	if err := waitingPortConnectionRefused(t, port, time.Second*10); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	if err := waitForEngineState(t, engine, false, time.Second*5); err != nil {
		t.Fatalf("engine did not stop: %s", err)
	}
	assert.False(t, engine.running.Load())
}

func TestFixCloseOfChannelAfterTwoFailedBuild(t *testing.T) {
	// fix https://github.com/air-verse/air/issues/294
	// happens after two failed builds
	dir := initWithBuildFailedCode(t)
	// change dir to tmpDir
	chdir(t, dir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	engine.config.Log.Silent = true
	silenceBuildCmd(engine.config)
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		engine.Run()
		t.Logf("engine stopped")
	}()

	go func() {
		<-sigs
		engine.Stop()
		t.Logf("engine stopped")
	}()

	// Wait for first build to complete (with error) - reduced from 3s to 1s
	// Since the build fails immediately, 1s is sufficient
	time.Sleep(time.Millisecond * 500)

	// edit *.go file to create build error again
	file, err := os.OpenFile("main.go", os.O_APPEND|os.O_WRONLY, 0o644)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	defer file.Close()
	_, err = file.WriteString("\n")
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	// Wait for second build attempt - reduced from 3s to 500ms
	time.Sleep(time.Millisecond * 500)
	// ctrl + c
	sigs <- syscall.SIGINT
	// Wait for engine to stop
	err = waitForEngineState(t, engine, false, time.Second*3)
	if err != nil {
		t.Logf("engine may not have stopped cleanly: %s", err)
	}
	assert.False(t, engine.running.Load())
}

// waitingPortReady waits until the port is ready to be used.
func waitingPortReady(t *testing.T, port int, timeout time.Duration) error {
	t.Helper()
	t.Logf("waiting port %d ready", port)

	// Use environment-aware timeout for CI compatibility
	timeoutMultiplier := 1.0
	if os.Getenv("CI") != "" {
		timeoutMultiplier = 2.0
	}
	adjustedTimeout := time.Duration(float64(timeout) * timeoutMultiplier)

	deadline := time.Now().Add(adjustedTimeout)
	ticker := time.NewTicker(20 * time.Millisecond) // Reduced from 100ms to 20ms
	defer ticker.Stop()

	for {
		conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
		if err == nil {
			_ = conn.Close()
			return nil
		}

		if time.Now().After(deadline) {
			return fmt.Errorf("timeout waiting for port %d ready (timeout: %v)", port, adjustedTimeout)
		}

		<-ticker.C
	}
}

func TestRun(t *testing.T) {
	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	go func() {
		engine.Run()
	}()

	// Wait for port to be ready instead of fixed sleep
	err = waitingPortReady(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	assert.True(t, checkPortHaveBeenUsed(port))
	t.Logf("try to stop")
	engine.Stop()

	// Wait for engine to stop instead of fixed sleep
	err = waitForEngineState(t, engine, false, time.Second*3)
	if err != nil {
		t.Fatalf("engine did not stop: %s.", err)
	}
	assert.False(t, checkPortHaveBeenUsed(port))
	t.Logf("stopped")
}

func checkPortConnectionRefused(port int) bool {
	conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
	defer func() {
		if conn != nil {
			_ = conn.Close()
		}
	}()
	return errors.Is(err, syscall.ECONNREFUSED)
}

func checkPortHaveBeenUsed(port int) bool {
	conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
	if err != nil {
		return false
	}
	_ = conn.Close()
	return true
}

func initTestEnv(t *testing.T, port int) string {
	tempDir := t.TempDir()
	t.Setenv(airWd, tempDir)
	t.Logf("tempDir: %s", tempDir)
	// generate golang code to tempdir
	err := generateGoCode(tempDir, port)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	return tempDir
}

func initWithBuildFailedCode(t *testing.T) string {
	tempDir := t.TempDir()
	t.Setenv(airWd, tempDir)
	t.Logf("tempDir: %s", tempDir)
	// generate golang code to tempdir
	err := generateBuildErrorGoCode(tempDir)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	return tempDir
}

func initWithQuickExitGoCode(t *testing.T) string {
	tempDir := t.TempDir()
	t.Setenv(airWd, tempDir)
	t.Logf("tempDir: %s", tempDir)
	// generate golang code to tempdir
	err := generateQuickExitGoCode(tempDir)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	return tempDir
}

func generateQuickExitGoCode(dir string) error {
	code := `package main
// You can edit this code!
// Click here and start typing.

import "fmt"

func main() {
	fmt.Println("Hello, 世界")
}
`
	file, err := os.Create(dir + "/main.go")
	if err != nil {
		return err
	}
	_, err = file.WriteString(code)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}

	// generate go mod file
	mod := `module air.sample.com

go 1.17
`
	file, err = os.Create(dir + "/go.mod")
	if err != nil {
		return err
	}
	_, err = file.WriteString(mod)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}
	return nil
}

func generateBuildErrorGoCode(dir string) error {
	code := `package main
// You can edit this code!
// Click here and start typing.

func main() {
	Println("Hello, 世界")

}
`
	file, err := os.Create(dir + "/main.go")
	if err != nil {
		return err
	}
	_, err = file.WriteString(code)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}

	// generate go mod file
	mod := `module air.sample.com

go 1.17
`
	file, err = os.Create(dir + "/go.mod")
	if err != nil {
		return err
	}
	_, err = file.WriteString(mod)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}
	return nil
}

// generateGoCode generates golang code to tempdir
func generateGoCode(dir string, port int) error {
	code := fmt.Sprintf(`package main

import (
	"log"
	"net/http"
)

func main() {
	log.Fatal(http.ListenAndServe("127.0.0.1:%v", nil))
}
`, port)
	file, err := os.Create(dir + "/main.go")
	if err != nil {
		return err
	}
	_, err = file.WriteString(code)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}

	// generate go mod file
	mod := `module air.sample.com

go 1.17
`
	file, err = os.Create(dir + "/go.mod")
	if err != nil {
		return err
	}
	_, err = file.WriteString(mod)
	if err != nil {
		_ = file.Close()
		return err
	}
	if err := file.Close(); err != nil {
		return err
	}
	return nil
}

func silenceBuildCmd(cfg *Config) {
	if cfg == nil {
		return
	}
	if runtime.GOOS == "windows" {
		cfg.Build.Cmd = fmt.Sprintf("%s > $null 2>&1", cfg.Build.Cmd)
		return
	}
	cfg.Build.Cmd = fmt.Sprintf("%s >/dev/null 2>&1", cfg.Build.Cmd)
}

func TestRebuildWhenRunCmdUsingDLV(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("requires touch")
	}

	if _, err := exec.LookPath("dlv"); err != nil {
		t.Skip("dlv not available in PATH")
	}

	// generate a random port
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)
	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	engine, err := NewEngine("", nil, true)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	engine.config.Build.Cmd = "go build -gcflags='all=-N -l' -o ./tmp/main ."
	engine.config.Build.Bin = ""
	dlvPort, f := GetPort()
	f()
	engine.config.Build.FullBin = fmt.Sprintf("dlv exec --accept-multiclient --log --headless --continue --listen :%d --api-version 2 ./tmp/main", dlvPort)
	_ = engine.config.preprocess(nil)
	go func() {
		engine.Run()
	}()
	if err := waitingPortReady(t, port, time.Second*40); err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}

	t.Logf("start change main.go")
	// change file of main.go
	// just append a new empty line to main.go
	go func() {
		file, err := os.OpenFile("main.go", os.O_APPEND|os.O_WRONLY, 0o644)
		if err != nil {
			log.Fatalf("Should not be fail: %s.", err)
		}
		defer file.Close()
		_, err = file.WriteString("\n")
		if err != nil {
			log.Fatalf("Should not be fail: %s.", err)
		}
	}()
	err = waitingPortConnectionRefused(t, port, time.Second*10)
	if err != nil {
		t.Fatalf("timeout: %s.", err)
	}
	t.Logf("connection refused")
	err = waitingPortReady(t, port, time.Second*40)
	if err != nil {
		t.Fatalf("Should not be fail: %s.", err)
	}
	t.Logf("port is ready")
	// stop engine
	engine.Stop()
	// Wait for engine to stop
	err = waitForEngineState(t, engine, false, time.Second*5)
	if err != nil {
		t.Fatalf("engine did not stop: %s.", err)
	}
	t.Logf("engine stopped")
	assert.True(t, checkPortConnectionRefused(port))
}

func TestWriteDefaultConfig(t *testing.T) {
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)
	// change dir to tmpDir
	chdir(t, tmpDir)
	configName, err := writeDefaultConfig()
	if err != nil {
		t.Fatal(err)
	}
	// check the file exists
	if _, err := os.Stat(configName); err != nil {
		t.Fatal(err)
	}

	raw, err := os.ReadFile(configName)
	if err != nil {
		t.Fatal(err)
	}
	expectedPrefix := schemaHeader + "\n\n"
	assert.True(t, strings.HasPrefix(string(raw), expectedPrefix), "config should start with schema header")

	// check the file content is right
	actual, err := readConfig(configName)
	if err != nil {
		t.Fatal(err)
	}
	expect := defaultConfig()
	if len(expect.Build.Entrypoint) == 0 && expect.Build.Bin != "" {
		expect.Build.Entrypoint = entrypoint{expect.Build.Bin}
	}

	assert.Equal(t, expect, *actual)
}

func TestCheckNilSliceShouldBeenOverwrite(t *testing.T) {
	port, f := GetPort()
	f()
	t.Logf("port: %d", port)

	tmpDir := initTestEnv(t, port)

	// change dir to tmpDir
	chdir(t, tmpDir)

	// write easy config file

	config := `
[build]
cmd = "go build ."
bin = "tmp/main"
exclude_regex = []
exclude_dir = ["test"]
exclude_file = ["main.go"]
include_file = ["test/not_a_test.go"]

`
	if err := os.WriteFile(dftTOML, []byte(config), 0o644); err != nil {
		t.Fatal(err)
	}
	engine, err := NewEngine(".air.toml", nil, true)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, []string{"go", "tpl", "tmpl", "html"}, engine.config.Build.IncludeExt)
	assert.Equal(t, []string{}, engine.config.Build.ExcludeReg
Download .txt
gitextract_7s9z9yf2/

├── .dockerignore
├── .editorconfig
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build.yml
│       ├── release.yml
│       ├── smoke_test.yml
│       └── smoke_test_reuse_job.yml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── AGENTS.md
├── Dockerfile
├── LICENSE
├── Makefile
├── README-ja.md
├── README-zh_cn.md
├── README-zh_tw.md
├── README.md
├── air_example.toml
├── go.mod
├── go.sum
├── hack/
│   └── check.sh
├── hooks/
│   └── pre-commit
├── install.sh
├── main.go
├── runner/
│   ├── _testdata/
│   │   ├── both/
│   │   │   └── .air.toml
│   │   ├── child.sh
│   │   ├── grandchild.sh
│   │   ├── invalid_toml/
│   │   │   └── .air.toml
│   │   ├── run-detached-process.sh
│   │   ├── run-many-processes.sh
│   │   ├── toml/
│   │   │   └── .air.toml
│   │   └── watching/
│   │       └── inner/
│   │           └── test.txt
│   ├── cmdarg_test.go
│   ├── common.go
│   ├── config.go
│   ├── config_test.go
│   ├── engine.go
│   ├── engine_test.go
│   ├── exiter.go
│   ├── flag.go
│   ├── flag_test.go
│   ├── logger.go
│   ├── proxy.go
│   ├── proxy.js
│   ├── proxy_stream.go
│   ├── proxy_stream_test.go
│   ├── proxy_test.go
│   ├── test_util.go
│   ├── util.go
│   ├── util_linux.go
│   ├── util_linux_test.go
│   ├── util_test.go
│   ├── util_unix.go
│   ├── util_windows.go
│   ├── util_windows_test.go
│   ├── watcher.go
│   └── worker.js
├── smoke_test/
│   ├── check_rebuild/
│   │   ├── go.mod
│   │   ├── go.sum
│   │   └── main.go
│   └── smoke_test.py
└── version.go
Download .txt
SYMBOL INDEX (300 symbols across 26 files)

FILE: main.go
  function helpMessage (line 25) | func helpMessage() {
  function init (line 35) | func init() {
  function parseFlag (line 39) | func parseFlag(args []string) {
  type versionInfo (line 52) | type versionInfo struct
  function GetVersionInfo (line 57) | func GetVersionInfo() versionInfo { //revive:disable:unexported-return
  function printSplash (line 76) | func printSplash() {
  function main (line 86) | func main() {

FILE: runner/common.go
  constant PlatformWindows (line 5) | PlatformWindows = "windows"

FILE: runner/config.go
  constant dftTOML (line 21) | dftTOML = ".air.toml"
  constant airWd (line 22) | airWd   = "air_wd"
  constant defaultProxyAppStartTimeout (line 24) | defaultProxyAppStartTimeout = 5000
  constant schemaHeader (line 26) | schemaHeader = "#:schema https://json.schemastore.org/any.json"
  type Config (line 30) | type Config struct
    method preprocess (line 363) | func (c *Config) preprocess(args map[string]TomlInfo) error {
    method colorInfo (line 449) | func (c *Config) colorInfo() map[string]string {
    method buildLogPath (line 458) | func (c *Config) buildLogPath() string {
    method buildDelay (line 462) | func (c *Config) buildDelay() time.Duration {
    method rerunDelay (line 466) | func (c *Config) rerunDelay() time.Duration {
    method killDelay (line 470) | func (c *Config) killDelay() time.Duration {
    method binPath (line 480) | func (c *Config) binPath() string {
    method runnerBin (line 487) | func (c *Config) runnerBin() string {
    method tmpPath (line 494) | func (c *Config) tmpPath() string {
    method testDataPath (line 498) | func (c *Config) testDataPath() string {
    method rel (line 502) | func (c *Config) rel(path string) string {
    method withArgs (line 523) | func (c *Config) withArgs(args map[string]TomlInfo) {
  type entrypoint (line 43) | type entrypoint
    method UnmarshalTOML (line 45) | func (e *entrypoint) UnmarshalTOML(v interface{}) error {
    method binary (line 69) | func (e entrypoint) binary() string {
    method args (line 76) | func (e entrypoint) args() []string {
  type cfgBuild (line 83) | type cfgBuild struct
    method RegexCompiled (line 114) | func (c *cfgBuild) RegexCompiled() ([]*regexp.Regexp, error) {
    method normalizeIncludeDirs (line 118) | func (c *cfgBuild) normalizeIncludeDirs(root string) {
  type cfgLog (line 143) | type cfgLog struct
  type cfgColor (line 149) | type cfgColor struct
  type cfgMisc (line 157) | type cfgMisc struct
  type cfgScreen (line 161) | type cfgScreen struct
  type cfgProxy (line 166) | type cfgProxy struct
  type sliceTransformer (line 173) | type sliceTransformer struct
    method Transformer (line 175) | func (t sliceTransformer) Transformer(typ reflect.Type) func(dst, src ...
  function InitConfig (line 188) | func InitConfig(path string, cmdArgs map[string]TomlInfo) (cfg *Config, ...
  function writeDefaultConfig (line 219) | func writeDefaultConfig() (string, error) {
  function defaultPathConfig (line 254) | func defaultPathConfig() (*Config, error) {
  function readConfByName (line 271) | func readConfByName(name string) (*Config, error) {
  function defaultConfig (line 286) | func defaultConfig() Config {
  function readConfig (line 339) | func readConfig(path string) (*Config, error) {
  function readConfigOrDefault (line 353) | func readConfigOrDefault(path string) (*Config, error) {
  function resolveCommandPath (line 510) | func resolveCommandPath(entry string) string {
  function warnDeprecatedBin (line 535) | func warnDeprecatedBin(cfg *Config) {

FILE: runner/config_test.go
  constant bin (line 16) | bin = `./tmp/main`
  constant cmd (line 17) | cmd = "go build -o ./tmp/main ."
  function getWindowsConfig (line 20) | func getWindowsConfig() Config {
  function TestBinCmdPath (line 45) | func TestBinCmdPath(t *testing.T) {
  function TestDefaultPathConfig (line 75) | func TestDefaultPathConfig(t *testing.T) {
  function TestReadConfByName (line 105) | func TestReadConfByName(t *testing.T) {
  function TestDefaultPathConfigWithInvalidTOML (line 113) | func TestDefaultPathConfigWithInvalidTOML(t *testing.T) {
  function TestConfPreprocess (line 129) | func TestConfPreprocess(t *testing.T) {
  function TestEntrypointResolvesAbsolutePath (line 156) | func TestEntrypointResolvesAbsolutePath(t *testing.T) {
  function TestEntrypointResolvesFromPath (line 182) | func TestEntrypointResolvesFromPath(t *testing.T) {
  function TestEntrypointPreservesArgs (line 220) | func TestEntrypointPreservesArgs(t *testing.T) {
  function TestConfigWithRuntimeArgs (line 242) | func TestConfigWithRuntimeArgs(t *testing.T) {
  function TestReadConfigWithWrongPath (line 278) | func TestReadConfigWithWrongPath(t *testing.T) {
  function TestKillDelay (line 289) | func TestKillDelay(t *testing.T) {
  function contains (line 317) | func contains(sl []string, target string) bool {
  function TestWarnDeprecatedBin (line 326) | func TestWarnDeprecatedBin(t *testing.T) {
  function TestWarnIgnoreDangerousRootDirProtection (line 363) | func TestWarnIgnoreDangerousRootDirProtection(t *testing.T) {

FILE: runner/engine.go
  type Engine (line 20) | type Engine struct
    method Run (line 106) | func (e *Engine) Run() {
    method checkRunEnv (line 130) | func (e *Engine) checkRunEnv() error {
    method watchConfiguredDirs (line 142) | func (e *Engine) watchConfiguredDirs() error {
    method watching (line 176) | func (e *Engine) watching(root string) error {
    method cacheFileChecksums (line 217) | func (e *Engine) cacheFileChecksums(root string) error {
    method watchPath (line 276) | func (e *Engine) watchPath(path string) error {
    method watchNewDir (line 333) | func (e *Engine) watchNewDir(dir string, removeDir bool) {
    method isModified (line 357) | func (e *Engine) isModified(filename string) bool {
    method start (line 373) | func (e *Engine) start() {
    method loadEnvFile (line 437) | func (e *Engine) loadEnvFile() {
    method buildRun (line 503) | func (e *Engine) buildRun() {
    method flushEvents (line 565) | func (e *Engine) flushEvents() {
    method runCommand (line 577) | func (e *Engine) runCommand(command string) error {
    method runCommandCopyOutput (line 594) | func (e *Engine) runCommandCopyOutput(command string) (string, error) {
    method building (line 617) | func (e *Engine) building() (string, error) {
    method runPreCmd (line 627) | func (e *Engine) runPreCmd() error {
    method runPostCmd (line 639) | func (e *Engine) runPostCmd() error {
    method runBin (line 650) | func (e *Engine) runBin() error {
    method stopBin (line 780) | func (e *Engine) stopBin() {
    method cleanup (line 807) | func (e *Engine) cleanup() {
    method Stop (line 847) | func (e *Engine) Stop() {
  function NewEngineWithConfig (line 60) | func NewEngineWithConfig(cfg *Config, debugMode bool) (*Engine, error) {
  function NewEngine (line 96) | func NewEngine(cfgPath string, args map[string]TomlInfo, debugMode bool)...

FILE: runner/engine_test.go
  function TestNewEngine (line 24) | func TestNewEngine(t *testing.T) {
  function TestCheckRunEnv (line 41) | func TestCheckRunEnv(t *testing.T) {
  function TestWatching (line 55) | func TestWatching(t *testing.T) {
  function TestRegexes (line 71) | func TestRegexes(t *testing.T) {
  function TestRunCommand (line 122) | func TestRunCommand(t *testing.T) {
  function TestRunPreCmd (line 149) | func TestRunPreCmd(t *testing.T) {
  function TestRunPostCmd (line 177) | func TestRunPostCmd(t *testing.T) {
  function TestRunBin (line 207) | func TestRunBin(t *testing.T) {
  function GetPort (line 219) | func GetPort() (int, func()) {
  function TestRebuild (line 230) | func TestRebuild(t *testing.T) {
  function waitingPortConnectionRefused (line 297) | func waitingPortConnectionRefused(t *testing.T, port int, timeout time.D...
  function TestCtrlCWhenHaveKillDelay (line 326) | func TestCtrlCWhenHaveKillDelay(t *testing.T) {
  function TestCtrlCWhenREngineIsRunning (line 384) | func TestCtrlCWhenREngineIsRunning(t *testing.T) {
  function TestCtrlCWithFailedBin (line 424) | func TestCtrlCWithFailedBin(t *testing.T) {
  function TestFixCloseOfChannelAfterCtrlC (line 459) | func TestFixCloseOfChannelAfterCtrlC(t *testing.T) {
  function TestFixCloseOfChannelAfterTwoFailedBuild (line 520) | func TestFixCloseOfChannelAfterTwoFailedBuild(t *testing.T) {
  function waitingPortReady (line 572) | func waitingPortReady(t *testing.T, port int, timeout time.Duration) err...
  function TestRun (line 602) | func TestRun(t *testing.T) {
  function checkPortConnectionRefused (line 638) | func checkPortConnectionRefused(port int) bool {
  function checkPortHaveBeenUsed (line 648) | func checkPortHaveBeenUsed(port int) bool {
  function initTestEnv (line 657) | func initTestEnv(t *testing.T, port int) string {
  function initWithBuildFailedCode (line 669) | func initWithBuildFailedCode(t *testing.T) string {
  function initWithQuickExitGoCode (line 681) | func initWithQuickExitGoCode(t *testing.T) string {
  function generateQuickExitGoCode (line 693) | func generateQuickExitGoCode(dir string) error {
  function generateBuildErrorGoCode (line 737) | func generateBuildErrorGoCode(dir string) error {
  function generateGoCode (line 781) | func generateGoCode(dir string, port int) error {
  function silenceBuildCmd (line 826) | func silenceBuildCmd(cfg *Config) {
  function TestRebuildWhenRunCmdUsingDLV (line 837) | func TestRebuildWhenRunCmdUsingDLV(t *testing.T) {
  function TestWriteDefaultConfig (line 905) | func TestWriteDefaultConfig(t *testing.T) {
  function TestCheckNilSliceShouldBeenOverwrite (line 942) | func TestCheckNilSliceShouldBeenOverwrite(t *testing.T) {
  function TestShouldIncludeGoTestFile (line 980) | func TestShouldIncludeGoTestFile(t *testing.T) {
  function TestCreateNewDir (line 1061) | func TestCreateNewDir(t *testing.T) {
  function TestShouldIncludeIncludedFile (line 1099) | func TestShouldIncludeIncludedFile(t *testing.T) {
  function TestShouldIncludeIncludedFileWithoutIncludedExt (line 1162) | func TestShouldIncludeIncludedFileWithoutIncludedExt(t *testing.T) {
  type testExiter (line 1225) | type testExiter struct
    method Exit (line 1231) | func (te *testExiter) Exit(code int) {
  function TestEngineExit (line 1238) | func TestEngineExit(t *testing.T) {
  function TestBuildRunRaceCondition (line 1314) | func TestBuildRunRaceCondition(t *testing.T) {
  function TestBuildRunRaceConditionRapidChanges (line 1384) | func TestBuildRunRaceConditionRapidChanges(t *testing.T) {
  function TestEngineLoadEnvFile (line 1429) | func TestEngineLoadEnvFile(t *testing.T) {

FILE: runner/exiter.go
  type exiter (line 5) | type exiter interface
  type defaultExiter (line 9) | type defaultExiter struct
    method Exit (line 11) | func (d defaultExiter) Exit(code int) {

FILE: runner/flag.go
  function ParseConfigFlag (line 8) | func ParseConfigFlag(f *flag.FlagSet) map[string]TomlInfo {

FILE: runner/flag_test.go
  function TestFlag (line 16) | func TestFlag(t *testing.T) {
  function TestConfigRuntimeArgs (line 68) | func TestConfigRuntimeArgs(t *testing.T) {

FILE: runner/logger.go
  type logFunc (line 26) | type logFunc
  type logger (line 28) | type logger struct
    method main (line 85) | func (l *logger) main() logFunc {
    method build (line 89) | func (l *logger) build() logFunc {
    method runner (line 93) | func (l *logger) runner() logFunc {
    method watcher (line 97) | func (l *logger) watcher() logFunc {
    method getLogger (line 109) | func (l *logger) getLogger(name string) logFunc {
  function newLogger (line 34) | func newLogger(cfg *Config) *logger {
  function newLogFunc (line 52) | func newLogFunc(colorname string, cfg cfgLog) logFunc {
  function getColor (line 78) | func getColor(name string) color.Attribute {
  function rawLogger (line 101) | func rawLogger() logFunc {
  function defaultLogger (line 105) | func defaultLogger() logFunc {

FILE: runner/proxy.go
  type Streamer (line 27) | type Streamer interface
  type contentEncoding (line 36) | type contentEncoding
  constant encodingNone (line 39) | encodingNone contentEncoding = iota
  constant encodingGzip (line 40) | encodingGzip
  constant encodingBrotli (line 41) | encodingBrotli
  type Proxy (line 44) | type Proxy struct
    method Run (line 67) | func (p *Proxy) Run() {
    method Reload (line 76) | func (p *Proxy) Reload() {
    method BuildFailed (line 80) | func (p *Proxy) BuildFailed(msg BuildFailedMsg) {
    method injectLiveReload (line 84) | func (p *Proxy) injectLiveReload(resp *http.Response) (string, bool, e...
    method proxyHandler (line 118) | func (p *Proxy) proxyHandler(w http.ResponseWriter, r *http.Request) {
    method reloadHandler (line 264) | func (p *Proxy) reloadHandler(w http.ResponseWriter, r *http.Request) {
    method workerScriptHandler (line 291) | func (p *Proxy) workerScriptHandler(w http.ResponseWriter, _ *http.Req...
    method Stop (line 297) | func (p *Proxy) Stop() error {
  function NewProxy (line 51) | func NewProxy(cfg *cfgProxy) *Proxy {
  function detectContentEncoding (line 245) | func detectContentEncoding(header http.Header) contentEncoding {
  function isStreamingResponse (line 306) | func isStreamingResponse(resp *http.Response) bool {
  function streamCopy (line 321) | func streamCopy(dst io.Writer, src io.Reader, flusher http.Flusher) error {

FILE: runner/proxy.js
  function parseBuildFailed (line 60) | function parseBuildFailed(raw) {
  function showErrorInModal (line 78) | function showErrorInModal(data) {

FILE: runner/proxy_stream.go
  type ProxyStream (line 10) | type ProxyStream struct
    method Stop (line 43) | func (stream *ProxyStream) Stop() {
    method AddSubscriber (line 50) | func (stream *ProxyStream) AddSubscriber() *Subscriber {
    method RemoveSubscriber (line 60) | func (stream *ProxyStream) RemoveSubscriber(id int32) {
    method Reload (line 70) | func (stream *ProxyStream) Reload() {
    method BuildFailed (line 79) | func (stream *ProxyStream) BuildFailed(err BuildFailedMsg) {
  type StreamMessageType (line 16) | type StreamMessageType
  constant StreamMessageReload (line 19) | StreamMessageReload      StreamMessageType = "reload"
  constant StreamMessageBuildFailed (line 20) | StreamMessageBuildFailed StreamMessageType = "build-failed"
  type StreamMessage (line 23) | type StreamMessage struct
    method AsSSE (line 88) | func (m StreamMessage) AsSSE() string {
  type BuildFailedMsg (line 28) | type BuildFailedMsg struct
  type Subscriber (line 34) | type Subscriber struct
  function NewProxyStream (line 39) | func NewProxyStream() *ProxyStream {
  function stringify (line 94) | func stringify(v any) string {

FILE: runner/proxy_stream_test.go
  function find (line 11) | func find(s map[int32]*Subscriber, id int32) bool {
  function TestProxyStream (line 20) | func TestProxyStream(t *testing.T) {
  function TestBuildFailureMessage (line 75) | func TestBuildFailureMessage(t *testing.T) {

FILE: runner/proxy_test.go
  type reloader (line 24) | type reloader struct
    method AddSubscriber (line 29) | func (r *reloader) AddSubscriber() *Subscriber {
    method RemoveSubscriber (line 34) | func (r *reloader) RemoveSubscriber(_ int32) {
    method Reload (line 38) | func (r *reloader) Reload()                    {}
    method BuildFailed (line 39) | func (r *reloader) BuildFailed(BuildFailedMsg) {}
    method Stop (line 40) | func (r *reloader) Stop()                      {}
  function getServerPort (line 44) | func getServerPort(t *testing.T, srv *httptest.Server) int {
  function TestProxy_run (line 56) | func TestProxy_run(t *testing.T) {
  function TestProxy_proxyHandler (line 78) | func TestProxy_proxyHandler(t *testing.T) {
  function TestProxy_injectLiveReload (line 165) | func TestProxy_injectLiveReload(t *testing.T) {
  function TestProxy_reloadHandler (line 232) | func TestProxy_reloadHandler(t *testing.T) {
  function TestProxy_proxyHandler_GzipHTML (line 300) | func TestProxy_proxyHandler_GzipHTML(t *testing.T) {
  function TestProxy_proxyHandler_BrotliHTML (line 339) | func TestProxy_proxyHandler_BrotliHTML(t *testing.T) {
  function TestDetectContentEncoding (line 378) | func TestDetectContentEncoding(t *testing.T) {
  function TestProxy_proxyHandler_SSE (line 407) | func TestProxy_proxyHandler_SSE(t *testing.T) {
  function TestIsStreamingResponse (line 453) | func TestIsStreamingResponse(t *testing.T) {
  type mockFlusher (line 521) | type mockFlusher struct
    method Flush (line 525) | func (m *mockFlusher) Flush() {
  function TestStreamCopy (line 529) | func TestStreamCopy(t *testing.T) {
  function TestProxy_proxyHandler_Chunked (line 569) | func TestProxy_proxyHandler_Chunked(t *testing.T) {
  function TestProxy_proxyHandler_NonStreaming (line 612) | func TestProxy_proxyHandler_NonStreaming(t *testing.T) {
  function TestProxy_appStartTimeout (line 646) | func TestProxy_appStartTimeout(t *testing.T) {

FILE: runner/test_util.go
  function chdir (line 11) | func chdir(t *testing.T, targetDir string) {
  function waitForCondition (line 28) | func waitForCondition(t *testing.T, timeout time.Duration, condition fun...
  function waitForEngineState (line 54) | func waitForEngineState(t *testing.T, engine *Engine, running bool, time...

FILE: runner/util.go
  constant sliceCmdArgSeparator (line 23) | sliceCmdArgSeparator = ","
  constant extWildcard (line 25) | extWildcard = "*"
  method mainLog (line 28) | func (e *Engine) mainLog(format string, v ...interface{}) {
  method mainDebug (line 37) | func (e *Engine) mainDebug(format string, v ...interface{}) {
  method buildLog (line 46) | func (e *Engine) buildLog(format string, v ...interface{}) {
  method runnerLog (line 57) | func (e *Engine) runnerLog(format string, v ...interface{}) {
  method watcherLog (line 68) | func (e *Engine) watcherLog(format string, v ...interface{}) {
  method watcherDebug (line 79) | func (e *Engine) watcherDebug(format string, v ...interface{}) {
  method isTmpDir (line 88) | func (e *Engine) isTmpDir(path string) bool {
  method isTestDataDir (line 92) | func (e *Engine) isTestDataDir(path string) bool {
  function isHiddenDirectory (line 96) | func isHiddenDirectory(path string) bool {
  function cleanPath (line 100) | func cleanPath(path string) string {
  function isSubPath (line 104) | func isSubPath(base, target string) bool {
  method isExcludeDir (line 122) | func (e *Engine) isExcludeDir(path string) bool {
  method checkIncludeDir (line 133) | func (e *Engine) checkIncludeDir(path string) (bool, bool) {
  method checkIncludeFile (line 157) | func (e *Engine) checkIncludeFile(path string) bool {
  method isIncludeExt (line 174) | func (e *Engine) isIncludeExt(path string) bool {
  method isBinPath (line 189) | func (e *Engine) isBinPath(path string) bool {
  method isExcludeRegex (line 206) | func (e *Engine) isExcludeRegex(path string) (bool, error) {
  method isExcludeFile (line 219) | func (e *Engine) isExcludeFile(path string) bool {
  method writeBuildErrorLog (line 230) | func (e *Engine) writeBuildErrorLog(msg string) error {
  method withLock (line 242) | func (e *Engine) withLock(f func()) {
  method logWithLock (line 248) | func (e *Engine) logWithLock(f func()) {
  function copyOutput (line 254) | func copyOutput(dst io.Writer, src io.Reader) {
  function expandPath (line 261) | func expandPath(path string) (string, error) {
  function isDir (line 280) | func isDir(path string) bool {
  function validEvent (line 288) | func validEvent(ev fsnotify.Event) bool {
  function removeEvent (line 294) | func removeEvent(ev fsnotify.Event) bool {
  function cmdPath (line 298) | func cmdPath(path string) string {
  function adaptToVariousPlatforms (line 302) | func adaptToVariousPlatforms(c *Config) {
  function fileChecksum (line 324) | func fileChecksum(filename string) (checksum string, err error) {
  type checksumMap (line 346) | type checksumMap struct
    method updateFileChecksum (line 352) | func (a *checksumMap) updateFileChecksum(filename, newChecksum string)...
  type TomlInfo (line 364) | type TomlInfo struct
  function setValue2Struct (line 372) | func setValue2Struct(v reflect.Value, fieldName string, value string) {
  function flatConfig (line 427) | func flatConfig(stut interface{}) map[string]TomlInfo {
  function getFieldValueString (line 435) | func getFieldValueString(fieldValue reflect.Value) string {
  function setTage2Map (line 449) | func setTage2Map(root string, t reflect.Type, v reflect.Value, m map[str...
  function joinPath (line 477) | func joinPath(root, path string) string {
  function formatPath (line 485) | func formatPath(path string) string {
  function isDangerousRoot (line 502) | func isDangerousRoot(path string) (bool, string) {

FILE: runner/util_linux.go
  method killCmd (line 16) | func (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {
  method startCmd (line 58) | func (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.Read...
  function sendSignalToProcessTree (line 84) | func sendSignalToProcessTree(pid int, sig syscall.Signal) error {
  function collectDescendantPIDs (line 127) | func collectDescendantPIDs(pid int) ([]int, error) {
  function readChildPIDs (line 156) | func readChildPIDs(pid int) ([]int, error) {

FILE: runner/util_linux_test.go
  function Test_sendSignalToProcessTree_ConcurrentSignalSending (line 18) | func Test_sendSignalToProcessTree_ConcurrentSignalSending(t *testing.T) {

FILE: runner/util_test.go
  function TestIsDirRootPath (line 19) | func TestIsDirRootPath(t *testing.T) {
  function TestIsDirMainFile (line 26) | func TestIsDirMainFile(t *testing.T) {
  function TestIsDirFileNot (line 33) | func TestIsDirFileNot(t *testing.T) {
  function TestExpandPathWithDot (line 40) | func TestExpandPathWithDot(t *testing.T) {
  function TestExpandPathWithHomePath (line 48) | func TestExpandPathWithHomePath(t *testing.T) {
  function TestNormalizeIncludeDirOutsideRoot (line 58) | func TestNormalizeIncludeDirOutsideRoot(t *testing.T) {
  function TestCheckIncludeDirRestrictsWithinRoot (line 81) | func TestCheckIncludeDirRestrictsWithinRoot(t *testing.T) {
  function TestFileChecksum (line 107) | func TestFileChecksum(t *testing.T) {
  function TestChecksumMap (line 168) | func TestChecksumMap(t *testing.T) {
  function TestAdaptToVariousPlatforms (line 189) | func TestAdaptToVariousPlatforms(t *testing.T) {
  function Test_killCmd_SendInterrupt_false (line 202) | func Test_killCmd_SendInterrupt_false(t *testing.T) {
  function Test_killCmd_KillsDetachedChildren (line 271) | func Test_killCmd_KillsDetachedChildren(t *testing.T) {
  function TestGetStructureFieldTagMap (line 333) | func TestGetStructureFieldTagMap(t *testing.T) {
  function TestSetStructValue (line 343) | func TestSetStructValue(t *testing.T) {
  function TestNestStructValue (line 351) | func TestNestStructValue(t *testing.T) {
  function TestNestStructArrayValue (line 359) | func TestNestStructArrayValue(t *testing.T) {
  function TestNestStructArrayValueOverride (line 367) | func TestNestStructArrayValueOverride(t *testing.T) {
  function TestCheckIncludeFile (line 379) | func TestCheckIncludeFile(t *testing.T) {
  function TestIsIncludeExt (line 393) | func TestIsIncludeExt(t *testing.T) {
  function TestIsIncludeExtWildcard (line 407) | func TestIsIncludeExtWildcard(t *testing.T) {
  function TestIsIncludeExtWildcardWithSpaces (line 431) | func TestIsIncludeExtWildcardWithSpaces(t *testing.T) {
  function TestIsBinPath (line 445) | func TestIsBinPath(t *testing.T) {
  function TestIsBinPathEmptyBinPath (line 465) | func TestIsBinPathEmptyBinPath(t *testing.T) {
  function TestJoinPathRelative (line 480) | func TestJoinPathRelative(t *testing.T) {
  function TestJoinPathAbsolute (line 493) | func TestJoinPathAbsolute(t *testing.T) {
  function TestFormatPath (line 511) | func TestFormatPath(t *testing.T) {
  function Test_killCmd_SendInterrupt_FastGracefulExit (line 605) | func Test_killCmd_SendInterrupt_FastGracefulExit(t *testing.T) {
  function Test_killCmd_SendInterrupt_IgnoresSIGINT (line 654) | func Test_killCmd_SendInterrupt_IgnoresSIGINT(t *testing.T) {
  function Test_killCmd_SendInterrupt_SlowGracefulExit (line 702) | func Test_killCmd_SendInterrupt_SlowGracefulExit(t *testing.T) {
  function TestIsDangerousRoot (line 747) | func TestIsDangerousRoot(t *testing.T) {

FILE: runner/util_unix.go
  method killCmd (line 13) | func (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {
  method startCmd (line 57) | func (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.Read...

FILE: runner/util_windows.go
  method killCmd (line 16) | func (e *Engine) killCmd(cmd *exec.Cmd) (pid int, err error) {
  method startCmd (line 43) | func (e *Engine) startCmd(cmd string) (*exec.Cmd, io.ReadCloser, io.Read...

FILE: runner/util_windows_test.go
  function TestAdaptToVariousPlatformsFullBinWindows (line 9) | func TestAdaptToVariousPlatformsFullBinWindows(t *testing.T) {

FILE: runner/watcher.go
  function newWatcher (line 9) | func newWatcher(cfg *Config) (filenotify.FileWatcher, error) {

FILE: runner/worker.js
  function initSSE (line 35) | function initSSE() {
  function scheduleReconnect (line 63) | function scheduleReconnect() {
  function clearReconnect (line 79) | function clearReconnect() {
  function broadcast (line 87) | function broadcast(data) {
  function cancelTermination (line 102) | function cancelTermination() {
  function scheduleTermination (line 107) | function scheduleTermination() {

FILE: smoke_test/check_rebuild/main.go
  function main (line 8) | func main() {
Condensed preview — 65 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (330K chars).
[
  {
    "path": ".dockerignore",
    "chars": 18,
    "preview": "bin\nvendor\ntmp\nair"
  },
  {
    "path": ".editorconfig",
    "chars": 86,
    "preview": "root = true\n\n[Makefile]\nindent_style = tab\n\n[*.go]\nindent_style = tab\nindent_size = 4\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 610,
    "preview": "# These are supported funding model platforms\n\npatreon: cosmtrek\ngithub: xiantang\nopen_collective: # Replace with a sing"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 916,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: xiantang\n\n---\n\n**Describe"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 595,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your fea"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 2819,
    "preview": "name: Build\n\non:\n  push:\n  pull_request:\n    branches: [master]\n\njobs:\n  build:\n    strategy:\n      matrix:\n        os: "
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 1773,
    "preview": "name: Release\n\non:\n  push:\n  pull_request:\n    branches: [master]\n\njobs:\n  release:\n    name: Release\n    runs-on: ubunt"
  },
  {
    "path": ".github/workflows/smoke_test.yml",
    "chars": 395,
    "preview": "name: Smoke test\n\non:\n  push:\n  pull_request:\n\njobs:\n  smoke_test_ubuntu:\n    uses: ./.github/workflows/smoke_test_reuse"
  },
  {
    "path": ".github/workflows/smoke_test_reuse_job.yml",
    "chars": 2804,
    "preview": "name: Reusable smoke test\n\non:\n  workflow_call:\n    inputs:\n      run_on:\n        required: true\n        type: string\n\nj"
  },
  {
    "path": ".gitignore",
    "chars": 102,
    "preview": "*.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",
    "chars": 533,
    "preview": "version: \"2\"\nlinters:\n  default: none\n  enable:\n    - copyloopvar\n    - errcheck\n    - ineffassign\n    - misspell\n    - "
  },
  {
    "path": ".goreleaser.yml",
    "chars": 339,
    "preview": "builds:\n  - goos:\n      - linux\n      - windows\n      - darwin\n    ignore:\n      - goos: darwin\n        goarch: 386\n    "
  },
  {
    "path": "AGENTS.md",
    "chars": 6739,
    "preview": "# AGENTS\n\nGuidelines for contributors and AI coding agents working in this repository.\n\n## Goals\n\n- Keep changes minimal"
  },
  {
    "path": "Dockerfile",
    "chars": 479,
    "preview": "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\n"
  },
  {
    "path": "LICENSE",
    "chars": 35142,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "Makefile",
    "chars": 1736,
    "preview": "AIRVER := $(shell git describe --tags)\nLDFLAGS += -X \"main.BuildTimestamp=$(shell date -u \"+%Y-%m-%d %H:%M:%S\")\"\nLDFLAGS"
  },
  {
    "path": "README-ja.md",
    "chars": 7409,
    "preview": "# :cloud: Air - Go アプリケーションのためのライブリロード\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)"
  },
  {
    "path": "README-zh_cn.md",
    "chars": 6603,
    "preview": "# Air [![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg)](https://github.com/air-verse/air"
  },
  {
    "path": "README-zh_tw.md",
    "chars": 6590,
    "preview": "# :cloud: Air - Live reload for Go apps\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg"
  },
  {
    "path": "README.md",
    "chars": 10399,
    "preview": "# :cloud: Air - Live reload for Go apps\n\n[![Go](https://github.com/air-verse/air/actions/workflows/release.yml/badge.svg"
  },
  {
    "path": "air_example.toml",
    "chars": 3299,
    "preview": "#:schema https://json.schemastore.org/any.json\n\n# Config file for [Air](https://github.com/air-verse/air) in TOML format"
  },
  {
    "path": "go.mod",
    "chars": 1205,
    "preview": "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\tgithu"
  },
  {
    "path": "go.sum",
    "chars": 18590,
    "preview": "dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=\ndario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMI"
  },
  {
    "path": "hack/check.sh",
    "chars": 1788,
    "preview": "#!/usr/bin/env bash\n\nreadonly reset=$(tput sgr0)\nreadonly red=$(tput bold; tput setaf 1)\nreadonly green=$(tput bold; tpu"
  },
  {
    "path": "hooks/pre-commit",
    "chars": 53,
    "preview": "#!/usr/bin/env bash\n\nset -e\n\n./hack/check.sh\nexit $?\n"
  },
  {
    "path": "install.sh",
    "chars": 9299,
    "preview": "#!/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 <<E"
  },
  {
    "path": "main.go",
    "chars": 2671,
    "preview": "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"
  },
  {
    "path": "runner/_testdata/both/.air.toml",
    "chars": 67,
    "preview": "#:schema https://json.schemastore.org/any.json\n\nroot = \"both_root\"\n"
  },
  {
    "path": "runner/_testdata/child.sh",
    "chars": 164,
    "preview": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\n./_testdata/grandchild.sh background &\n./_testdata/grandchild"
  },
  {
    "path": "runner/_testdata/grandchild.sh",
    "chars": 99,
    "preview": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\nsleep 9999\necho \"ProcessID=$$ ends ($0)\""
  },
  {
    "path": "runner/_testdata/invalid_toml/.air.toml",
    "chars": 102,
    "preview": "# 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",
    "chars": 212,
    "preview": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\necho \"$$\" >> pid\nsetsid sh -c './_testdata/grandchild.sh detached' >/dev/null "
  },
  {
    "path": "runner/_testdata/run-many-processes.sh",
    "chars": 137,
    "preview": "#!/bin/sh\necho \"ProcessID=$$ begins ($0)\"\n./_testdata/child.sh background &\n./_testdata/child.sh foreground\necho \"Proces"
  },
  {
    "path": "runner/_testdata/toml/.air.toml",
    "chars": 67,
    "preview": "#:schema https://json.schemastore.org/any.json\n\nroot = \"toml_root\"\n"
  },
  {
    "path": "runner/_testdata/watching/inner/test.txt",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "runner/cmdarg_test.go",
    "chars": 15,
    "preview": "package runner\n"
  },
  {
    "path": "runner/common.go",
    "chars": 92,
    "preview": "package runner\n\nconst (\n\t//PlatformWindows const for windows\n\tPlatformWindows = \"windows\"\n)\n"
  },
  {
    "path": "runner/config.go",
    "chars": 15688,
    "preview": "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\"st"
  },
  {
    "path": "runner/config_test.go",
    "chars": 11806,
    "preview": "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\ncon"
  },
  {
    "path": "runner/engine.go",
    "chars": 20776,
    "preview": "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\""
  },
  {
    "path": "runner/engine_test.go",
    "chars": 34512,
    "preview": "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\"stri"
  },
  {
    "path": "runner/exiter.go",
    "chars": 158,
    "preview": "package runner\n\nimport \"os\"\n\ntype exiter interface {\n\tExit(code int)\n}\n\ntype defaultExiter struct{}\n\nfunc (d defaultExit"
  },
  {
    "path": "runner/flag.go",
    "chars": 276,
    "preview": "package runner\n\nimport (\n\t\"flag\"\n)\n\n// ParseConfigFlag parse toml information for flag\nfunc ParseConfigFlag(f *flag.Flag"
  },
  {
    "path": "runner/flag_test.go",
    "chars": 4649,
    "preview": "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"
  },
  {
    "path": "runner/logger.go",
    "chars": 2207,
    "preview": "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:"
  },
  {
    "path": "runner/proxy.go",
    "chars": 9027,
    "preview": "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\"st"
  },
  {
    "path": "runner/proxy.js",
    "chars": 5397,
    "preview": "(() => {\n    let worker = null;\n\n    const disconnectWorker = () => {\n        if (worker) {\n            worker.port.post"
  },
  {
    "path": "runner/proxy_stream.go",
    "chars": 2013,
    "preview": "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.M"
  },
  {
    "path": "runner/proxy_stream_test.go",
    "chars": 1733,
    "preview": "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[int"
  },
  {
    "path": "runner/proxy_test.go",
    "chars": 19595,
    "preview": "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/"
  },
  {
    "path": "runner/test_util.go",
    "chars": 1590,
    "preview": "// 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 strin"
  },
  {
    "path": "runner/util.go",
    "chars": 11835,
    "preview": "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"
  },
  {
    "path": "runner/util_linux.go",
    "chars": 4200,
    "preview": "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\nfun"
  },
  {
    "path": "runner/util_linux_test.go",
    "chars": 1805,
    "preview": "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\"testi"
  },
  {
    "path": "runner/util_test.go",
    "chars": 22065,
    "preview": "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\""
  },
  {
    "path": "runner/util_unix.go",
    "chars": 2032,
    "preview": "//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) killCm"
  },
  {
    "path": "runner/util_windows.go",
    "chars": 1655,
    "preview": "//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"
  },
  {
    "path": "runner/util_windows_test.go",
    "chars": 970,
    "preview": "package runner\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestAdaptToVariousPlatformsFullBinWindows(t *testing.T"
  },
  {
    "path": "runner/watcher.go",
    "chars": 497,
    "preview": "package runner\n\nimport (\n\t\"time\"\n\n\t\"github.com/gohugoio/hugo/watcher/filenotify\"\n)\n\nfunc newWatcher(cfg *Config) (fileno"
  },
  {
    "path": "runner/worker.js",
    "chars": 2912,
    "preview": "(() => {\n    const ports = new Set();\n    let sse = null;\n    let terminationTimer = null;\n    let reconnectTimer = null"
  },
  {
    "path": "smoke_test/check_rebuild/go.mod",
    "chars": 31,
    "preview": "module air.sample.com\n\ngo 1.17\n"
  },
  {
    "path": "smoke_test/check_rebuild/go.sum",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "smoke_test/check_rebuild/main.go",
    "chars": 107,
    "preview": "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",
    "chars": 462,
    "preview": "import os\nfrom pexpect.popen_spawn import PopenSpawn\n\nprint(os.getcwd())\nos.chdir(os.getcwd() + \"\\check_rebuild\")\nprint("
  },
  {
    "path": "version.go",
    "chars": 60,
    "preview": "package main\n\nvar (\n\tairVersion string\n\tgoVersion  string\n)\n"
  }
]

About this extraction

This page contains the full source code of the air-verse/air GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 65 files (294.9 KB), approximately 92.1k tokens, and a symbol index with 300 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!