├── .cargo └── config.toml ├── .dockerignore ├── .editorconfig ├── .github ├── FUNDING.yml ├── actions │ ├── docker-push-by-digest │ │ └── action.yml │ └── docker-release │ │ └── action.yml ├── semantic.yml └── workflows │ ├── ci.yml │ ├── docker.yml │ └── release.yml ├── .gitignore ├── .pre-commit-hooks.yaml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── action.yml ├── cli ├── Cargo.toml ├── build.rs └── src │ ├── main.rs │ ├── subcommand.rs │ └── version.rs ├── fmt ├── Cargo.toml ├── src │ ├── config │ │ └── mod.rs │ ├── document │ │ ├── defaults.toml │ │ ├── factory.rs │ │ ├── mod.rs │ │ └── model.rs │ ├── git.rs │ ├── header │ │ ├── defaults.toml │ │ ├── matcher.rs │ │ ├── mod.rs │ │ ├── model.rs │ │ └── parser.rs │ ├── lib.rs │ ├── license │ │ ├── Apache-2.0-ASF.txt │ │ ├── Apache-2.0.txt │ │ ├── Elastic-2.0.txt │ │ └── mod.rs │ ├── processor.rs │ └── selection.rs └── tests │ ├── content │ ├── empty.py │ └── two_headers.rs │ └── tests.rs ├── licenserc.toml ├── pyproject.toml ├── rust-toolchain.toml ├── rustfmt.toml └── tests ├── .gitignore ├── attrs_and_props ├── license.txt ├── licenserc.toml ├── main.rs └── main.rs.expected ├── bom_issue ├── headless_bom.cs ├── headless_bom.cs.expected ├── license.txt ├── licenserc.toml └── style.toml ├── disk_file_creation_year ├── license.txt ├── licenserc.toml ├── main.rs └── main.rs.expected ├── it.py ├── load_header_path ├── license.txt ├── licenserc.toml ├── main.rs └── main.rs.expected ├── regression_blank_line ├── licenserc.toml ├── main.rs └── main.rs.expected └── regression_no_blank_lines ├── licenserc.toml ├── repro.py └── repro.py.expected /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # See also https://github.com/rust-lang/rust/issues/44991 16 | 17 | [target.x86_64-unknown-linux-musl] 18 | rustflags = ["-C", "target-feature=-crt-static"] 19 | 20 | [target.aarch64-unknown-linux-musl] 21 | rustflags = ["-C", "target-feature=-crt-static"] 22 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !**/src/main/**/target/ 3 | !**/src/test/**/target/ 4 | dependency-reduced-pom.xml 5 | 6 | ### IntelliJ IDEA ### 7 | .idea/modules.xml 8 | .idea/jarRepositories.xml 9 | .idea/compiler.xml 10 | .idea/libraries/ 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | ### Mac OS ### 16 | .DS_Store 17 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | root = true 16 | 17 | [*] 18 | end_of_line = lf 19 | indent_style = space 20 | insert_final_newline = true 21 | trim_trailing_whitespace = true 22 | 23 | [*.txt] 24 | insert_final_newline = false 25 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | github: tisonkun 16 | -------------------------------------------------------------------------------- /.github/actions/docker-push-by-digest/action.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Docker push by digest 16 | description: Build and push Docker image by digest 17 | 18 | inputs: 19 | name: 20 | description: The name of Docker image 21 | required: true 22 | file: 23 | description: The name of Dockerfile in use 24 | required: true 25 | 26 | outputs: 27 | digest: 28 | description: Docker image digest if pushed 29 | value: ${{ steps.push.outputs.digest }} 30 | 31 | runs: 32 | using: composite 33 | steps: 34 | - uses: docker/setup-buildx-action@v2 35 | - uses: docker/login-action@v2 36 | with: 37 | registry: ghcr.io 38 | username: ${{ github.actor }} 39 | password: ${{ github.token }} 40 | - name: Docker meta 41 | id: meta 42 | uses: docker/metadata-action@v4 43 | with: 44 | images: ghcr.io/${{ github.repository_owner }}/${{ inputs.name }} 45 | - name: Build and push 46 | id: push 47 | uses: docker/build-push-action@v5 48 | with: 49 | context: . 50 | file: ${{ inputs.file }} 51 | tags: ghcr.io/${{ github.repository_owner }}/${{ inputs.name }} 52 | labels: ${{ steps.meta.outputs.labels }} 53 | outputs: type=image,push=true,push-by-digest=true 54 | -------------------------------------------------------------------------------- /.github/actions/docker-release/action.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Docker release 16 | description: Release Docker Images 17 | 18 | inputs: 19 | name: 20 | description: The name of Docker image 21 | required: true 22 | digests: 23 | description: The digest of images to be merged 24 | required: true 25 | 26 | runs: 27 | using: composite 28 | steps: 29 | - uses: docker/setup-buildx-action@v2 30 | - uses: docker/login-action@v2 31 | with: 32 | registry: ghcr.io 33 | username: ${{ github.actor }} 34 | password: ${{ github.token }} 35 | - name: Docker meta 36 | id: meta 37 | uses: docker/metadata-action@v4 38 | with: 39 | images: ghcr.io/${{ github.repository_owner }}/${{ inputs.name }} 40 | sep-tags: ' ' 41 | tags: | 42 | type=semver,pattern={{raw}} 43 | type=semver,pattern=v{{major}} 44 | type=edge,branch=main 45 | - name: Push manifest 46 | shell: bash 47 | run: | 48 | for tag in ${{ steps.meta.outputs.tags }}; do 49 | echo "Preparing manifest for tag: $tag..." 50 | docker buildx imagetools create -t $tag ${{ inputs.digests }} 51 | done 52 | -------------------------------------------------------------------------------- /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # The pull request's title should be fulfilled the following pattern: 16 | # 17 | # [optional scope]: 18 | # 19 | # ... where valid types and scopes can be found below; for example: 20 | # 21 | # build(maven): One level down for native profile 22 | # 23 | # More about configurations on https://github.com/Ezard/semantic-prs#configuration 24 | 25 | enabled: true 26 | 27 | titleOnly: true 28 | 29 | types: 30 | - feat 31 | - fix 32 | - docs 33 | - style 34 | - refactor 35 | - perf 36 | - test 37 | - build 38 | - ci 39 | - chore 40 | - revert 41 | 42 | targetUrl: https://github.com/korandoru/hawkeye/blob/main/.github/semantic.yml 43 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: CI 16 | on: 17 | pull_request: 18 | branches: [ main ] 19 | push: 20 | branches: [ main ] 21 | 22 | # Concurrency strategy: 23 | # github.workflow: distinguish this workflow from others 24 | # github.event_name: distinguish `push` event from `pull_request` event 25 | # github.event.number: set to the number of the pull request if `pull_request` event 26 | # github.run_id: otherwise, it's a `push` event, only cancel if we rerun the workflow 27 | # 28 | # Reference: 29 | # https://docs.github.com/en/actions/using-jobs/using-concurrency 30 | # https://docs.github.com/en/actions/learn-github-actions/contexts#github-context 31 | concurrency: 32 | group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.run_id }} 33 | cancel-in-progress: true 34 | 35 | jobs: 36 | check: 37 | name: Check 38 | runs-on: ubuntu-24.04 39 | steps: 40 | - uses: actions/checkout@v4 41 | - uses: Swatinem/rust-cache@v2 42 | - uses: dtolnay/rust-toolchain@nightly 43 | - name: Check Clippy 44 | run: cargo clippy --tests --all-features --all-targets --workspace -- -D warnings 45 | - name: Check format 46 | run: cargo fmt --all --check 47 | 48 | test: 49 | strategy: 50 | matrix: 51 | rust-version: ["1.85.0", "stable"] 52 | name: Build and test 53 | runs-on: ubuntu-24.04 54 | steps: 55 | - uses: actions/checkout@v4 56 | - uses: Swatinem/rust-cache@v2 57 | - name: Delete rust-toolchain.toml 58 | run: rm rust-toolchain.toml 59 | - run: cargo build --workspace --all-features --bins --tests --examples --benches 60 | - name: Run tests 61 | run: cargo test --workspace -- --nocapture 62 | - name: Run benches 63 | run: cargo bench --workspace -- --test 64 | 65 | docker: 66 | strategy: 67 | fail-fast: false 68 | matrix: 69 | os: [ ubuntu-24.04 ] 70 | runs-on: ${{matrix.os}} 71 | name: Docker sanity check on ${{ matrix.os }} 72 | steps: 73 | - uses: actions/checkout@v4 74 | with: 75 | fetch-depth: 0 76 | - name: Build and load 77 | uses: docker/build-push-action@v5 78 | with: 79 | context: . 80 | file: Dockerfile 81 | tags: hawkeye:ci 82 | outputs: type=docker 83 | - name: Save image 84 | run: docker save hawkeye:ci -o /tmp/hawkeye-${{matrix.os}}.tar 85 | - name: Upload artifact 86 | uses: actions/upload-artifact@v4 87 | with: 88 | name: hawkeye-${{matrix.os}} 89 | path: /tmp/hawkeye-${{matrix.os}}.tar 90 | - name: Sanity check 91 | run: | 92 | cp action.yml action.yml.bak 93 | docker image inspect hawkeye:ci --format='{{.Size}}' 94 | docker run --rm -v $(pwd):/github/workspace hawkeye:ci -V 95 | docker run --rm -v $(pwd):/github/workspace hawkeye:ci check --fail-if-unknown 96 | 97 | smoke: 98 | strategy: 99 | fail-fast: false 100 | matrix: 101 | os: [ubuntu-24.04, windows-2022, macos-14] 102 | runs-on: ${{ matrix.os }} 103 | name: Smoke test on ${{ matrix.os }} 104 | steps: 105 | - uses: actions/checkout@v4 106 | with: 107 | fetch-depth: 0 108 | - uses: Swatinem/rust-cache@v2 109 | - name: Dog feed license check 110 | shell: bash 111 | run: | 112 | cargo run --bin hawkeye -- -V 113 | cargo run --bin hawkeye -- check --fail-if-unknown 114 | - uses: actions/setup-python@v5 115 | with: 116 | python-version: '3.12' 117 | - name: Run integration tests 118 | shell: bash 119 | run: ./tests/it.py 120 | 121 | gha: 122 | strategy: 123 | fail-fast: false 124 | matrix: 125 | os: [ubuntu-24.04, windows-2022, macos-14] 126 | runs-on: ${{ matrix.os }} 127 | name: Smoke test for GitHub Actions on ${{ matrix.os }} 128 | steps: 129 | - uses: actions/checkout@v4 130 | with: 131 | fetch-depth: 0 132 | - name: Check and fail if unknown 133 | uses: ./ 134 | with: 135 | args: --fail-if-unknown 136 | - name: Check default config works 137 | uses: ./ 138 | 139 | required: 140 | name: Required 141 | runs-on: ubuntu-24.04 142 | if: ${{ always() }} 143 | needs: 144 | - check 145 | - docker 146 | - gha 147 | - smoke 148 | - test 149 | steps: 150 | - name: Guardian 151 | run: | 152 | if [[ ! ( \ 153 | "${{ needs.check.result }}" == "success" \ 154 | && "${{ needs.docker.result }}" == "success" \ 155 | && "${{ needs.gha.result }}" == "success" \ 156 | && "${{ needs.smoke.result }}" == "success" \ 157 | && "${{ needs.test.result }}" == "success" \ 158 | ) ]]; then 159 | echo "Required jobs haven't been completed successfully." 160 | exit -1 161 | fi 162 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: Build and Push Docker Images 16 | 17 | on: 18 | push: 19 | branches: ['main'] 20 | tags: ['v*.*'] 21 | workflow_dispatch: 22 | 23 | jobs: 24 | build-and-push-hawkeye-amd64: 25 | runs-on: ubuntu-24.04 26 | permissions: 27 | packages: write 28 | steps: 29 | - uses: actions/checkout@v4 30 | - name: Build and push by digest 31 | uses: ./.github/actions/docker-push-by-digest 32 | id: build 33 | with: 34 | name: hawkeye 35 | file: Dockerfile 36 | outputs: 37 | digest: ${{ steps.build.outputs.digest }} 38 | 39 | build-and-push-hawkeye-arm64: 40 | runs-on: ubuntu-24.04-arm 41 | permissions: 42 | packages: write 43 | steps: 44 | - uses: actions/checkout@v4 45 | - name: Build and push by digest 46 | uses: ./.github/actions/docker-push-by-digest 47 | id: build 48 | with: 49 | name: hawkeye 50 | file: Dockerfile 51 | outputs: 52 | digest: ${{ steps.build.outputs.digest }} 53 | 54 | release-hawkeye: 55 | runs-on: ubuntu-24.04 56 | permissions: 57 | packages: write 58 | needs: 59 | - build-and-push-hawkeye-amd64 60 | - build-and-push-hawkeye-arm64 61 | steps: 62 | - uses: actions/checkout@v4 63 | - name: Merge and push manifest 64 | uses: ./.github/actions/docker-release 65 | with: 66 | name: hawkeye 67 | digests: > 68 | ${{needs.build-and-push-hawkeye-amd64.outputs.digest}} 69 | ${{needs.build-and-push-hawkeye-arm64.outputs.digest}} 70 | 71 | release-native: 72 | runs-on: ubuntu-24.04 73 | permissions: 74 | packages: write 75 | needs: 76 | - build-and-push-hawkeye-amd64 77 | - build-and-push-hawkeye-arm64 78 | steps: 79 | - uses: actions/checkout@v4 80 | - name: Merge and push manifest 81 | uses: ./.github/actions/docker-release 82 | with: 83 | name: hawkeye-native 84 | digests: > 85 | ghcr.io/${{ github.repository_owner }}/hawkeye@${{needs.build-and-push-hawkeye-amd64.outputs.digest}} 86 | ghcr.io/${{ github.repository_owner }}/hawkeye@${{needs.build-and-push-hawkeye-arm64.outputs.digest}} 87 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # This file was autogenerated by cargo-dist: https://opensource.axo.dev/cargo-dist/ 2 | # 3 | # Copyright 2022-2024, axodotdev 4 | # SPDX-License-Identifier: MIT or Apache-2.0 5 | # 6 | # CI that: 7 | # 8 | # * checks for a Git Tag that looks like a release 9 | # * builds artifacts with cargo-dist (archives, installers, hashes) 10 | # * uploads those artifacts to temporary workflow zip 11 | # * on success, uploads the artifacts to a GitHub Release 12 | # 13 | # Note that the GitHub Release will be created with a generated 14 | # title/body based on your changelogs. 15 | 16 | name: Release 17 | permissions: 18 | "contents": "write" 19 | 20 | # This task will run whenever you push a git tag that looks like a version 21 | # like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc. 22 | # Various formats will be parsed into a VERSION and an optional PACKAGE_NAME, where 23 | # PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION 24 | # must be a Cargo-style SemVer Version (must have at least major.minor.patch). 25 | # 26 | # If PACKAGE_NAME is specified, then the announcement will be for that 27 | # package (erroring out if it doesn't have the given version or isn't cargo-dist-able). 28 | # 29 | # If PACKAGE_NAME isn't specified, then the announcement will be for all 30 | # (cargo-dist-able) packages in the workspace with that version (this mode is 31 | # intended for workspaces with only one dist-able package, or with all dist-able 32 | # packages versioned/released in lockstep). 33 | # 34 | # If you push multiple tags at once, separate instances of this workflow will 35 | # spin up, creating an independent announcement for each one. However, GitHub 36 | # will hard limit this to 3 tags per commit, as it will assume more tags is a 37 | # mistake. 38 | # 39 | # If there's a prerelease-style suffix to the version, then the release(s) 40 | # will be marked as a prerelease. 41 | on: 42 | pull_request: 43 | push: 44 | tags: 45 | - '**[0-9]+.[0-9]+.[0-9]+*' 46 | 47 | jobs: 48 | # Run 'cargo dist plan' (or host) to determine what tasks we need to do 49 | plan: 50 | runs-on: "ubuntu-22.04" 51 | outputs: 52 | val: ${{ steps.plan.outputs.manifest }} 53 | tag: ${{ !github.event.pull_request && github.ref_name || '' }} 54 | tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }} 55 | publishing: ${{ !github.event.pull_request }} 56 | env: 57 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 58 | steps: 59 | - uses: actions/checkout@v4 60 | with: 61 | submodules: recursive 62 | - name: Install cargo-dist 63 | # we specify bash to get pipefail; it guards against the `curl` command 64 | # failing. otherwise `sh` won't catch that `curl` returned non-0 65 | shell: bash 66 | run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.22.1/cargo-dist-installer.sh | sh" 67 | - name: Cache cargo-dist 68 | uses: actions/upload-artifact@v4 69 | with: 70 | name: cargo-dist-cache 71 | path: ~/.cargo/bin/cargo-dist 72 | # sure would be cool if github gave us proper conditionals... 73 | # so here's a doubly-nested ternary-via-truthiness to try to provide the best possible 74 | # functionality based on whether this is a pull_request, and whether it's from a fork. 75 | # (PRs run on the *source* but secrets are usually on the *target* -- that's *good* 76 | # but also really annoying to build CI around when it needs secrets to work right.) 77 | - id: plan 78 | run: | 79 | cargo dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json 80 | echo "cargo dist ran successfully" 81 | cat plan-dist-manifest.json 82 | echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT" 83 | - name: "Upload dist-manifest.json" 84 | uses: actions/upload-artifact@v4 85 | with: 86 | name: artifacts-plan-dist-manifest 87 | path: plan-dist-manifest.json 88 | 89 | # Build and packages all the platform-specific things 90 | build-local-artifacts: 91 | name: build-local-artifacts (${{ join(matrix.targets, ', ') }}) 92 | # Let the initial task tell us to not run (currently very blunt) 93 | needs: 94 | - plan 95 | if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }} 96 | strategy: 97 | fail-fast: false 98 | # Target platforms/runners are computed by cargo-dist in create-release. 99 | # Each member of the matrix has the following arguments: 100 | # 101 | # - runner: the github runner 102 | # - dist-args: cli flags to pass to cargo dist 103 | # - install-dist: expression to run to install cargo-dist on the runner 104 | # 105 | # Typically there will be: 106 | # - 1 "global" task that builds universal installers 107 | # - N "local" tasks that build each platform's binaries and platform-specific installers 108 | matrix: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix }} 109 | runs-on: ${{ matrix.runner }} 110 | env: 111 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 112 | BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json 113 | steps: 114 | - name: enable windows longpaths 115 | run: | 116 | git config --global core.longpaths true 117 | - uses: actions/checkout@v4 118 | with: 119 | submodules: recursive 120 | - name: Install cargo-dist 121 | run: ${{ matrix.install_dist }} 122 | # Get the dist-manifest 123 | - name: Fetch local artifacts 124 | uses: actions/download-artifact@v4 125 | with: 126 | pattern: artifacts-* 127 | path: target/distrib/ 128 | merge-multiple: true 129 | - name: Install dependencies 130 | run: | 131 | ${{ matrix.packages_install }} 132 | - name: Build artifacts 133 | run: | 134 | # Actually do builds and make zips and whatnot 135 | cargo dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json 136 | echo "cargo dist ran successfully" 137 | - id: cargo-dist 138 | name: Post-build 139 | # We force bash here just because github makes it really hard to get values up 140 | # to "real" actions without writing to env-vars, and writing to env-vars has 141 | # inconsistent syntax between shell and powershell. 142 | shell: bash 143 | run: | 144 | # Parse out what we just built and upload it to scratch storage 145 | echo "paths<> "$GITHUB_OUTPUT" 146 | jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" 147 | echo "EOF" >> "$GITHUB_OUTPUT" 148 | 149 | cp dist-manifest.json "$BUILD_MANIFEST_NAME" 150 | - name: "Upload artifacts" 151 | uses: actions/upload-artifact@v4 152 | with: 153 | name: artifacts-build-local-${{ join(matrix.targets, '_') }} 154 | path: | 155 | ${{ steps.cargo-dist.outputs.paths }} 156 | ${{ env.BUILD_MANIFEST_NAME }} 157 | 158 | # Build and package all the platform-agnostic(ish) things 159 | build-global-artifacts: 160 | needs: 161 | - plan 162 | - build-local-artifacts 163 | runs-on: "ubuntu-22.04" 164 | env: 165 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 166 | BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json 167 | steps: 168 | - uses: actions/checkout@v4 169 | with: 170 | submodules: recursive 171 | - name: Install cached cargo-dist 172 | uses: actions/download-artifact@v4 173 | with: 174 | name: cargo-dist-cache 175 | path: ~/.cargo/bin/ 176 | - run: chmod +x ~/.cargo/bin/cargo-dist 177 | # Get all the local artifacts for the global tasks to use (for e.g. checksums) 178 | - name: Fetch local artifacts 179 | uses: actions/download-artifact@v4 180 | with: 181 | pattern: artifacts-* 182 | path: target/distrib/ 183 | merge-multiple: true 184 | - id: cargo-dist 185 | shell: bash 186 | run: | 187 | cargo dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json 188 | echo "cargo dist ran successfully" 189 | 190 | # Parse out what we just built and upload it to scratch storage 191 | echo "paths<> "$GITHUB_OUTPUT" 192 | jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" 193 | echo "EOF" >> "$GITHUB_OUTPUT" 194 | 195 | cp dist-manifest.json "$BUILD_MANIFEST_NAME" 196 | - name: "Upload artifacts" 197 | uses: actions/upload-artifact@v4 198 | with: 199 | name: artifacts-build-global 200 | path: | 201 | ${{ steps.cargo-dist.outputs.paths }} 202 | ${{ env.BUILD_MANIFEST_NAME }} 203 | # Determines if we should publish/announce 204 | host: 205 | needs: 206 | - plan 207 | - build-local-artifacts 208 | - build-global-artifacts 209 | # Only run if we're "publishing", and only if local and global didn't fail (skipped is fine) 210 | if: ${{ always() && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} 211 | env: 212 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 213 | runs-on: "ubuntu-22.04" 214 | outputs: 215 | val: ${{ steps.host.outputs.manifest }} 216 | steps: 217 | - uses: actions/checkout@v4 218 | with: 219 | submodules: recursive 220 | - name: Install cached cargo-dist 221 | uses: actions/download-artifact@v4 222 | with: 223 | name: cargo-dist-cache 224 | path: ~/.cargo/bin/ 225 | - run: chmod +x ~/.cargo/bin/cargo-dist 226 | # Fetch artifacts from scratch-storage 227 | - name: Fetch artifacts 228 | uses: actions/download-artifact@v4 229 | with: 230 | pattern: artifacts-* 231 | path: target/distrib/ 232 | merge-multiple: true 233 | - id: host 234 | shell: bash 235 | run: | 236 | cargo dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json 237 | echo "artifacts uploaded and released successfully" 238 | cat dist-manifest.json 239 | echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT" 240 | - name: "Upload dist-manifest.json" 241 | uses: actions/upload-artifact@v4 242 | with: 243 | # Overwrite the previous copy 244 | name: artifacts-dist-manifest 245 | path: dist-manifest.json 246 | # Create a GitHub Release while uploading all files to it 247 | - name: "Download GitHub Artifacts" 248 | uses: actions/download-artifact@v4 249 | with: 250 | pattern: artifacts-* 251 | path: artifacts 252 | merge-multiple: true 253 | - name: Cleanup 254 | run: | 255 | # Remove the granular manifests 256 | rm -f artifacts/*-dist-manifest.json 257 | - name: Create GitHub Release 258 | env: 259 | PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}" 260 | ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}" 261 | ANNOUNCEMENT_BODY: "${{ fromJson(steps.host.outputs.manifest).announcement_github_body }}" 262 | RELEASE_COMMIT: "${{ github.sha }}" 263 | run: | 264 | # Write and read notes from a file to avoid quoting breaking things 265 | echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt 266 | 267 | gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* 268 | 269 | announce: 270 | needs: 271 | - plan 272 | - host 273 | # use "always() && ..." to allow us to wait for all publish jobs while 274 | # still allowing individual publish jobs to skip themselves (for prereleases). 275 | # "host" however must run to completion, no skipping allowed! 276 | if: ${{ always() && needs.host.result == 'success' }} 277 | runs-on: "ubuntu-22.04" 278 | env: 279 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 280 | steps: 281 | - uses: actions/checkout@v4 282 | with: 283 | submodules: recursive 284 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | *.bak 3 | -------------------------------------------------------------------------------- /.pre-commit-hooks.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | - id: hawkeye-format 16 | name: hawkeye-format 17 | description: "Run `hawkeye format` for license header formatting" 18 | entry: hawkeye format 19 | language: python 20 | args: [] 21 | pass_filenames: false 22 | require_serial: true 23 | additional_dependencies: [] 24 | minimum_pre_commit_version: "2.9.2" 25 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [6.1.0] 2025-06-06 6 | 7 | New properties: 8 | 9 | * `attrs.disk_file_creation_year` can be used to replace not existing git history attrs values like `{{attrs.git_file_created_year if attrs.git_file_created_year else attrs.disk_file_creation_year }}` 10 | 11 | ## [6.0.0] 2025-01-28 12 | 13 | ### Breaking changes 14 | 15 | Now, HawkEye uses MiniJinja as the template engine. 16 | 17 | All the `properties` configured will be passed to the template engine as the `props` value, and thus: 18 | 19 | * Previous `${property}` should be replaced with `{{ props["property"] }}`. 20 | * Previous built-in variables `hawkeye.core.filename` is now `attrs.filename`. 21 | * Previous built-in variables `hawkeye.git.fileCreatedYear` is now `attrs.git_file_created_year`. 22 | * Previous built-in variables `hawkeye.git.fileModifiedYear` is now `attrs.git_file_modified_year`. 23 | 24 | New properties: 25 | 26 | * `attrs.git_authors` is a collection of authors of the file. You can join them with `, ` to get a string by `{{ attrs.git_authors | join(", ") }}`. 27 | 28 | ### Notable changes 29 | 30 | Now, HawkEye would detect a leading BOM (Byte Order Mark) and remove it if it exists (#166). I tend to treat this as a bug fix, but it may affect the output of the header. 31 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | Thanks for your help in improving the project! 4 | 5 | There are two typical contributions to this project: 6 | 7 | 1. Add support for new languages. You can refer to https://github.com/korandoru/hawkeye/pull/124 as an example. 8 | 2. Add support for new license templates. You can refer to https://github.com/korandoru/hawkeye/pull/148 as an example. 9 | 10 | You can find the core concepts with names listed below to understand the design better: 11 | 12 | * `DocumentType` defines how a file in a specific type should be handled. 13 | * `HeaderDef` defines the format of a specific header; for example, `SCRIPT_STYLE` will construct the header format for scripts like `.sh` or `.py` files. 14 | * `HeaderStyle` is the serde layer for `HeaderDef`. 15 | * `Selection` describes how to find the files to be handled. 16 | * `HeaderParser` extracts the header slice from a source file. 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [workspace] 16 | members = ["cli", "fmt"] 17 | resolver = "2" 18 | 19 | [workspace.package] 20 | version = "6.0.4" 21 | edition = "2021" 22 | authors = ["tison "] 23 | readme = "README.md" 24 | license = "Apache-2.0" 25 | repository = "https://github.com/korandoru/hawkeye/" 26 | rust-version = "1.85.0" 27 | 28 | [workspace.dependencies] 29 | hawkeye-fmt = { version = "6.0.4", path = "fmt" } 30 | 31 | anyhow = { version = "1.0.94" } 32 | build-data = { version = "0.3.0" } 33 | clap = { version = "4.5.23", features = ["derive"] } 34 | const_format = { version = "0.2.34" } 35 | log = { version = "0.4.22", features = ["kv_serde", "serde"] } 36 | shadow-rs = { version = "1.1.1" } 37 | toml = { version = "0.8.19" } 38 | 39 | [workspace.metadata.release] 40 | sign-tag = true 41 | shared-version = true 42 | tag-name = "v{{version}}" 43 | pre-release-commit-message = "chore: release v{{version}}" 44 | 45 | # Config for 'cargo dist' 46 | [workspace.metadata.dist] 47 | # The preferred cargo-dist version to use in CI (Cargo.toml SemVer syntax) 48 | cargo-dist-version = "0.22.1" 49 | # CI backends to support 50 | ci = "github" 51 | # The installers to generate for each app 52 | installers = ["shell"] 53 | # Target platforms to build apps for (Rust target-triple syntax) 54 | targets = [ 55 | "aarch64-apple-darwin", 56 | "aarch64-unknown-linux-gnu", 57 | "x86_64-apple-darwin", 58 | "x86_64-unknown-linux-gnu", 59 | "x86_64-pc-windows-msvc", 60 | ] 61 | # Which actions to run on pull requests 62 | pr-run-mode = "plan" 63 | # Whether to install an updater program 64 | install-updater = false 65 | # Path that installers should place binaries in 66 | install-path = "CARGO_HOME" 67 | 68 | [workspace.metadata.dist.github-custom-runners] 69 | x86_64-unknown-linux-gnu = "ubuntu-22.04" 70 | aarch64-unknown-linux-gnu = "ubuntu-22.04-arm" 71 | aarch64-apple-darwin = "macos-14" 72 | x86_64-apple-darwin = "macos-14" 73 | x86_64-pc-windows-msvc = "windows-2022" 74 | global = "ubuntu-22.04" 75 | 76 | # 'cargo dist' build with this profile 77 | [profile.dist] 78 | inherits = "release" 79 | lto = "thin" 80 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | FROM public.ecr.aws/docker/library/rust:1.81.0-alpine3.20 as build 16 | ENV RUSTFLAGS="-C target-feature=-crt-static" 17 | WORKDIR /build 18 | COPY . . 19 | RUN apk fix && \ 20 | apk --no-cache --update add git musl-dev && \ 21 | cargo build --release --bin hawkeye 22 | 23 | FROM public.ecr.aws/docker/library/alpine:3.20.0 24 | COPY --from=build /build/target/release/hawkeye /bin/ 25 | RUN apk fix && apk --no-cache --update add libgcc git 26 | WORKDIR /github/workspace/ 27 | ENTRYPOINT ["/bin/hawkeye"] 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HawkEye 2 | 3 | Simple license header checker and formatter, in multiple distribution forms. 4 | 5 | ## Usage 6 | 7 | You can use HawkEye in GitHub Actions or in your local machine. HawkEye provides three basic commands: 8 | 9 | ```bash 10 | # check license headers 11 | hawkeye check 12 | 13 | # format license headers (auto-fix all files that failed the check) 14 | hawkeye format 15 | 16 | # remove license headers 17 | hawkeye remove 18 | ``` 19 | 20 | You can use `-h` or `--help` to list out all config options. 21 | 22 | ### GitHub Actions 23 | 24 | The HawkEye GitHub Action enables users to run license header check by HawkEye with a config file. 25 | 26 | First of all, add a `licenserc.toml` file in the root of your project. The simplest config for projects licensed under Apache License 2.0 is as below: 27 | 28 | > [!NOTE] 29 | > The full configurations can be found in [the configuration section](#configurations). 30 | 31 | ```toml 32 | headerPath = "Apache-2.0.txt" 33 | 34 | [properties] 35 | inceptionYear = 2023 36 | copyrightOwner = "tison " 37 | ``` 38 | 39 | You should change the copyright line according to your information. 40 | 41 | To check license headers in GitHub Actions, add a step in your GitHub workflow: 42 | 43 | ```yaml 44 | - name: Check License Header 45 | uses: korandoru/hawkeye@v6 46 | ``` 47 | 48 | ### Docker 49 | 50 | Alpine image (~18MB): 51 | 52 | ```shell 53 | docker run -it --rm -v $(pwd):/github/workspace ghcr.io/korandoru/hawkeye check 54 | ``` 55 | 56 | ### Arch Linux 57 | 58 | > [!NOTE] 59 | > Reach out to the maintainer ([@orhun](https://github.com/orhun)) of the [package](https://archlinux.org/packages/extra/x86_64/hawkeye/) or report issues on [Arch Linux GitLab](https://gitlab.archlinux.org/archlinux/packaging/packages/hawkeye) in the case of packaging-related problems. 60 | 61 | `hawkeye` can be installed with [pacman](https://wiki.archlinux.org/title/Pacman): 62 | 63 | ```shell 64 | pacman -S hawkeye 65 | ``` 66 | 67 | ### Cargo Install 68 | 69 | The `hawkeye` executable can be installed by: 70 | 71 | ```shell 72 | cargo install hawkeye 73 | ``` 74 | 75 | ### Prebuilt Binary 76 | 77 | Instead of `cargo install`, you can install `hawkeye` as a prebuilt binary by: 78 | 79 | ```shell 80 | export VERSION=v6.0.0 81 | curl --proto '=https' --tlsv1.2 -LsSf https://github.com/korandoru/hawkeye/releases/download/$VERSION/hawkeye-installer.sh | sh 82 | ``` 83 | 84 | It would retain more build info (output by `hawkeye -V`) than `cargo install`. 85 | 86 | ## Build 87 | 88 | This steps requires Rust toolchain. 89 | 90 | ```shell 91 | cargo build --workspace --all-features --bin --tests --examples --benches 92 | ``` 93 | 94 | Build Docker image: 95 | 96 | ```shell 97 | docker build . -t hawkeye 98 | ``` 99 | 100 | ## Configurations 101 | 102 | ### Config file 103 | 104 | ```toml 105 | # Base directory for the whole execution. 106 | # All relative paths is based on this path. 107 | # default: current working directory 108 | baseDir = "." 109 | 110 | # Inline header template. 111 | # Either inlineHeader or headerPath should be configured, and inlineHeader is prioritized. 112 | inlineHeader = "..." 113 | 114 | # Path to the header template file. 115 | # Either inlineHeader or headerPath should be configured, and inlineHeader is prioritized. 116 | # This path is resolved by the ResourceFinder. Check ResourceFinder for the concrete strategy. 117 | # The header template file is skipped on any execution. 118 | headerPath = "path/to/header.txt" 119 | 120 | # On enabled, check the license header matches exactly with whitespace. 121 | # Otherwise, strip the header in one line and check. 122 | # default: true 123 | strictCheck = true 124 | 125 | # Whether you use the default excludes. Check Default.EXCLUDES for the completed list. 126 | # To suppress part of excludes in the list, declare exact the same pattern in `includes` list. 127 | # default: true 128 | useDefaultExcludes = true 129 | 130 | # The supported patterns of includes and excludes follow gitignore pattern format, plus that: 131 | # 1. `includes` does not support `!` 132 | # 2. backslash does not escape letter 133 | # 3. whitespaces and `#` are normal since we configure line by line 134 | # See also https://git-scm.com/docs/gitignore#_pattern_format 135 | 136 | # Patterns of path to be included on execution. 137 | # default: all the files under `baseDir`. 138 | includes = ["..."] 139 | 140 | # Patterns of path to be excluded on execution. A leading bang (!) indicates an invert exclude rule. 141 | # default: empty; if useDefaultExcludes is true, append default excludes. 142 | excludes = ["..."] 143 | 144 | # Keywords that should occur in the header, case-insensitive. 145 | # default: ["copyright"] 146 | keywords = ["copyright", "..."] 147 | 148 | # Whether you use the default mapping. Check DocumentType.defaultMapping() for the completed list. 149 | # default: true 150 | useDefaultMapping = true 151 | 152 | # Paths to additional header style files. The model of user-defined header style can be found below. 153 | # default: empty 154 | additionalHeaders = ["..."] 155 | 156 | # Mapping rules (repeated). 157 | # 158 | # The key of a mapping rule is a header style type (case-insensitive). 159 | # 160 | # Available header style types consist of those defined at `HeaderType` and user-defined ones in `additionalHeaders`. 161 | # The name of header style type is case-insensitive. 162 | # 163 | # If useDefaultMapping is true, the mapping rules defined here can override the default one. 164 | [mapping.STYLE_NAME] 165 | filenames = ["..."] # e.g. "Dockerfile.native" 166 | extensions = ["..."] # e.g. "cc" 167 | 168 | # Properties to fulfill the template. 169 | # For a defined key-value pair, you can use {{props["key"]}} in the header template, which will be 170 | # substituted with the corresponding value. 171 | [properties] 172 | inceptionYear = 2023 173 | 174 | # There are also preset attributes that can be used in the header template (no need to surround them with `props[]`).: 175 | # * 'attrs.filename' is the current file name, like: pom.xml. 176 | 177 | # Options to configure Git features. 178 | [git] 179 | # If enabled, do not process files that are ignored by Git; possible value: ['auto', 'enable', 'disable'] 180 | # 'auto' means this feature tries to be enabled with: 181 | # * gix - if `basedir` is in a Git repository. 182 | # * ignore crate's gitignore rules - if `basedir` is not in a Git repository. 183 | # 'enable' means always enabled with gix; failed if it is impossible. 184 | # default: 'auto' 185 | ignore = 'auto' 186 | # If enabled, populate file attrs determinated by Git; possible value: ['auto', 'enable', 'disable'] 187 | # Attributes contains: 188 | # * 'attrs.git_file_created_year' 189 | # * 'attrs.git_file_modified_year' 190 | # 'auto' means this feature tries to be enabled with: 191 | # * gix - if `basedir` is in a Git repository. 192 | # 'enable' means always enabled with gix; failed if it is impossible. 193 | # default: 'disable' 194 | attrs = 'disable' 195 | ``` 196 | 197 | ### Header style file 198 | 199 | ```toml 200 | # [REQUIRED] The name of this header. 201 | [my_header_style] 202 | 203 | # The first fixed line of this header. Default to none. 204 | firstLine = "..." 205 | 206 | # The last fixed line of this header. Default to none. 207 | endLine = "..." 208 | 209 | # The characters to prepend before each license header lines. Default to empty. 210 | beforeEachLine = "..." 211 | 212 | # The characters to append after each license header lines. Default to empty. 213 | afterEachLine = "..." 214 | 215 | # Only for multi-line comments: specify if blank lines are allowed. 216 | # Default to false because most of the time, a header has some characters on each line. 217 | allowBlankLines = false 218 | 219 | # Specify whether this is a multi-line comment style or not. 220 | # 221 | # A multi-line comment style is equivalent to what we have in Java, where a first line and line will delimit 222 | # a whole multi-line comment section. 223 | # 224 | # A style that is not multi-line is usually repeating in each line the characters before and after each line 225 | # to delimit a one-line comment. 226 | # 227 | # Defaulut to true. 228 | multipleLines = true 229 | 230 | # Only for non multi-line comments: specify if some spaces should be added after the header line and before 231 | # the `afterEachLine` characters so that all the lines are aligned. 232 | # 233 | # Default to false. 234 | padLines = false 235 | 236 | # A regex to define a first line in a file that should be skipped and kept untouched, like the XML declaration 237 | # at the top of XML documents. 238 | # 239 | # Default to none. 240 | skipLinePattern = "..." 241 | 242 | # [REQUIRED] The regex used to detect the start of a header section or line. 243 | firstLineDetectionPattern = "..." 244 | 245 | # [REQUIRED] The regex used to detect the end of a header section or line. 246 | lastLineDetectionPattern = "..." 247 | ``` 248 | 249 | ## License 250 | 251 | [Apache License 2.0](LICENSE) 252 | 253 | ## History 254 | 255 | This software is originally from [license-maven-plugin](https://github.com/mathieucarbou/license-maven-plugin), with an initial motivation to bring it beyond a Maven plugin. The core abstractions like `Document`, `Header`, and `HeaderParser` are originally copied from the license-maven-plugin sources under the terms of Apache License 2.0. 256 | 257 | Later, when I started focusing on the Docker image's size and integration with Git, I found that Rust is better than Java (GraalVM Native Image) for this purpose. So, I rewrote the core logic in Rust while keeping a slim image. (The old Java implementation is achieved at the [archive-native-image](https://github.com/korandoru/hawkeye/tree/archive-native-image) branch) 258 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: HawkEye Action 16 | description: 'Check, format, or remove license headers.' 17 | author: 'tison ' 18 | branding: 19 | icon: 'code' 20 | color: 'blue' 21 | 22 | inputs: 23 | config: 24 | description: The configuration file 25 | required: false 26 | default: licenserc.toml 27 | mode: 28 | description: | 29 | Which mode License Eye should be run in. Choices are `check`, `format`, or `remove`. The 30 | default value is `check`. 31 | required: false 32 | default: check 33 | args: 34 | description: | 35 | Other arguments to be passed to the command, such as `--dry-run`, `--fail-if-unknown`, 36 | `--fail-if-updated`, etc. The default value is empty. 37 | required: false 38 | 39 | runs: 40 | using: "composite" 41 | steps: 42 | - name: Build HawkEye CLI 43 | run: cargo install --path cli 44 | shell: bash 45 | working-directory: ${{ github.action_path }} 46 | - shell: bash 47 | run: hawkeye ${{ inputs.mode }} --config ${{ inputs.config }} ${{ inputs.args }} 48 | -------------------------------------------------------------------------------- /cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "hawkeye" 17 | description = "Simple license header checker and formatter, in multiple distribution forms." 18 | version.workspace = true 19 | edition.workspace = true 20 | authors.workspace = true 21 | readme.workspace = true 22 | license.workspace = true 23 | repository.workspace = true 24 | 25 | [dependencies] 26 | anyhow = { workspace = true } 27 | clap = { workspace = true } 28 | const_format = { workspace = true } 29 | hawkeye-fmt = { workspace = true } 30 | log = { workspace = true } 31 | logforth = { version = "0.25.0" } 32 | shadow-rs = { workspace = true } 33 | 34 | [build-dependencies] 35 | build-data = { workspace = true } 36 | shadow-rs = { workspace = true } 37 | gix-discover = { version = "0.40.1" } 38 | -------------------------------------------------------------------------------- /cli/build.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::BTreeSet; 16 | use std::env; 17 | use std::path::Path; 18 | 19 | use build_data::format_timestamp; 20 | use build_data::get_source_time; 21 | use shadow_rs::CARGO_METADATA; 22 | use shadow_rs::CARGO_TREE; 23 | 24 | fn configure_rerun_if_head_commit_changed() { 25 | let mut current = Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf(); 26 | 27 | // skip if no valid-looking git repository could be found 28 | while let Ok((dir, _)) = gix_discover::upwards(current.as_path()) { 29 | match dir { 30 | gix_discover::repository::Path::Repository(git_dir) => { 31 | unreachable!( 32 | "build.rs should never be placed in a git bare repository: {}", 33 | git_dir.display() 34 | ); 35 | } 36 | gix_discover::repository::Path::WorkTree(work_dir) => { 37 | let git_refs_heads = work_dir.join(".git/refs/heads"); 38 | println!("cargo:rerun-if-changed={}", git_refs_heads.display()); 39 | break; 40 | } 41 | gix_discover::repository::Path::LinkedWorkTree { work_dir, .. } => { 42 | current = work_dir 43 | .parent() 44 | .expect("submodule's work_dir must have parent") 45 | .to_path_buf(); 46 | continue; 47 | } 48 | }; 49 | } 50 | } 51 | 52 | fn main() -> shadow_rs::SdResult<()> { 53 | configure_rerun_if_head_commit_changed(); 54 | 55 | println!( 56 | "cargo::rustc-env=SOURCE_TIMESTAMP={}", 57 | if let Ok(t) = get_source_time() { 58 | format_timestamp(t)? 59 | } else { 60 | "".to_string() 61 | } 62 | ); 63 | build_data::set_BUILD_TIMESTAMP(); 64 | 65 | // The "CARGO_WORKSPACE_DIR" is set manually (not by Rust itself) in Cargo config file, to 66 | // solve the problem where the "CARGO_MANIFEST_DIR" is not what we want when this repo is 67 | // made as a submodule in another repo. 68 | let src_path = env::var("CARGO_WORKSPACE_DIR").or_else(|_| env::var("CARGO_MANIFEST_DIR"))?; 69 | let out_path = env::var("OUT_DIR")?; 70 | shadow_rs::ShadowBuilder::builder() 71 | .src_path(src_path) 72 | .out_path(out_path) 73 | // exclude these two large constants that we don't need 74 | .deny_const(BTreeSet::from([CARGO_METADATA, CARGO_TREE])) 75 | .build()?; 76 | Ok(()) 77 | } 78 | -------------------------------------------------------------------------------- /cli/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use clap::FromArgMatches; 16 | use clap::Subcommand; 17 | use logforth::append; 18 | use logforth::filter::EnvFilter; 19 | 20 | use crate::subcommand::SubCommand; 21 | 22 | pub mod subcommand; 23 | pub mod version; 24 | 25 | fn main() { 26 | logforth::builder() 27 | .dispatch(|b| { 28 | b.filter(EnvFilter::from_default_env_or("info")) 29 | .append(append::Stderr::default()) 30 | }) 31 | .apply(); 32 | 33 | let build_info = version::build_info(); 34 | let command = clap::Command::new("hawkeye") 35 | .subcommand_required(true) 36 | .about(build_info.description) 37 | .version(build_info.version) 38 | .long_version(version::version()); 39 | let command = SubCommand::augment_subcommands(command); 40 | let args = command.get_matches(); 41 | match SubCommand::from_arg_matches(&args) { 42 | Ok(cmd) => cmd.run(), 43 | Err(e) => e.exit(), 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /cli/src/subcommand.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::path::Path; 16 | use std::path::PathBuf; 17 | 18 | use clap::Args; 19 | use clap::Parser; 20 | use hawkeye_fmt::document::Document; 21 | use hawkeye_fmt::header::matcher::HeaderMatcher; 22 | use hawkeye_fmt::processor::check_license_header; 23 | use hawkeye_fmt::processor::Callback; 24 | 25 | #[derive(Parser)] 26 | pub enum SubCommand { 27 | #[clap(name = "check", about = "check license header")] 28 | Check(CommandCheck), 29 | #[clap(name = "format", about = "format license header")] 30 | Format(CommandFormat), 31 | #[clap(name = "remove", about = "remove license header")] 32 | Remove(CommandRemove), 33 | } 34 | 35 | #[derive(Args)] 36 | struct SharedOptions { 37 | #[arg(long, help = "path to the config file")] 38 | config: Option, 39 | #[arg(long, help = "fail if process unknown files", default_value_t = false)] 40 | fail_if_unknown: bool, 41 | } 42 | 43 | #[derive(Args)] 44 | struct SharedEditOptions { 45 | #[arg(long, help = "whether update file in place", default_value_t = false)] 46 | dry_run: bool, 47 | #[arg( 48 | long, 49 | help = "whether to exit with non-zero code if files updated", 50 | action = clap::ArgAction::Set, 51 | default_value_t = true 52 | )] 53 | fail_if_updated: bool, 54 | } 55 | 56 | impl SubCommand { 57 | pub fn run(self) { 58 | match self { 59 | SubCommand::Check(cmd) => cmd.run(), 60 | SubCommand::Format(cmd) => cmd.run(), 61 | SubCommand::Remove(cmd) => cmd.run(), 62 | } 63 | } 64 | } 65 | 66 | #[derive(Parser)] 67 | pub struct CommandCheck { 68 | #[command(flatten)] 69 | shared: SharedOptions, 70 | #[arg( 71 | long, 72 | help = "whether to exit with non-zero code if missing headers", 73 | action = clap::ArgAction::Set, 74 | default_value_t = true 75 | )] 76 | fail_if_missing: bool, 77 | } 78 | 79 | struct CheckContext { 80 | unknown: Vec, 81 | missing: Vec, 82 | } 83 | 84 | impl Callback for CheckContext { 85 | fn on_unknown(&mut self, path: &Path) { 86 | self.unknown.push(path.display().to_string()); 87 | } 88 | 89 | fn on_matched(&mut self, _: &HeaderMatcher, _: Document) -> anyhow::Result<()> { 90 | Ok(()) 91 | } 92 | 93 | fn on_not_matched(&mut self, _: &HeaderMatcher, document: Document) -> anyhow::Result<()> { 94 | self.missing.push(document.filepath.display().to_string()); 95 | Ok(()) 96 | } 97 | } 98 | 99 | impl CommandCheck { 100 | fn run(self) { 101 | let config = self.shared.config.unwrap_or_else(default_config); 102 | let mut context = CheckContext { 103 | unknown: vec![], 104 | missing: vec![], 105 | }; 106 | check_license_header(config, &mut context).unwrap(); 107 | 108 | let mut failed = check_unknown_files(context.unknown, self.shared.fail_if_unknown); 109 | if !context.missing.is_empty() { 110 | log::error!("Found header missing in files: {:?}", context.missing); 111 | failed |= self.fail_if_missing; 112 | } 113 | if failed { 114 | std::process::exit(1); 115 | } 116 | log::info!("No missing header file has been found."); 117 | } 118 | } 119 | 120 | #[derive(Parser)] 121 | pub struct CommandFormat { 122 | #[command(flatten)] 123 | shared: SharedOptions, 124 | #[command(flatten)] 125 | shared_edit: SharedEditOptions, 126 | } 127 | 128 | struct FormatContext { 129 | dry_run: bool, 130 | unknown: Vec, 131 | updated: Vec, 132 | } 133 | 134 | impl Callback for FormatContext { 135 | fn on_unknown(&mut self, path: &Path) { 136 | self.unknown.push(path.display().to_string()); 137 | } 138 | 139 | fn on_matched(&mut self, _: &HeaderMatcher, _: Document) -> anyhow::Result<()> { 140 | Ok(()) 141 | } 142 | 143 | fn on_not_matched(&mut self, header: &HeaderMatcher, mut doc: Document) -> anyhow::Result<()> { 144 | if doc.header_detected() { 145 | doc.remove_header(); 146 | doc.update_header(header)?; 147 | self.updated 148 | .push(format!("{}=replaced", doc.filepath.display())); 149 | } else { 150 | doc.update_header(header)?; 151 | self.updated 152 | .push(format!("{}=added", doc.filepath.display())); 153 | } 154 | 155 | if self.dry_run { 156 | let mut extension = doc.filepath.extension().unwrap_or_default().to_os_string(); 157 | extension.push(".formatted"); 158 | let copied = doc.filepath.with_extension(extension); 159 | doc.save(Some(&copied)) 160 | } else { 161 | doc.save(None) 162 | } 163 | } 164 | } 165 | 166 | impl CommandFormat { 167 | fn run(self) { 168 | let config = self.shared.config.unwrap_or_else(default_config); 169 | let mut context = FormatContext { 170 | dry_run: self.shared_edit.dry_run, 171 | unknown: vec![], 172 | updated: vec![], 173 | }; 174 | check_license_header(config, &mut context).unwrap(); 175 | 176 | let mut failed = check_unknown_files(context.unknown, self.shared.fail_if_unknown); 177 | if !context.updated.is_empty() { 178 | log::info!( 179 | "Updated header for files (dryRun={}): {:?}", 180 | self.shared_edit.dry_run, 181 | context.updated 182 | ); 183 | failed |= self.shared_edit.fail_if_updated; 184 | } 185 | if failed { 186 | std::process::exit(1); 187 | } 188 | log::info!("All files have proper header."); 189 | } 190 | } 191 | 192 | #[derive(Parser)] 193 | pub struct CommandRemove { 194 | #[command(flatten)] 195 | shared: SharedOptions, 196 | #[command(flatten)] 197 | shared_edit: SharedEditOptions, 198 | } 199 | 200 | struct RemoveContext { 201 | dry_run: bool, 202 | unknown: Vec, 203 | removed: Vec, 204 | } 205 | 206 | impl RemoveContext { 207 | fn remove(&mut self, doc: &mut Document) -> anyhow::Result<()> { 208 | if !doc.header_detected() { 209 | return Ok(()); 210 | } 211 | doc.remove_header(); 212 | self.removed 213 | .push(format!("{}=removed", doc.filepath.display())); 214 | if self.dry_run { 215 | let mut extension = doc.filepath.extension().unwrap_or_default().to_os_string(); 216 | extension.push(".removed"); 217 | let copied = doc.filepath.with_extension(extension); 218 | doc.save(Some(&copied)) 219 | } else { 220 | doc.save(None) 221 | } 222 | } 223 | } 224 | 225 | impl Callback for RemoveContext { 226 | fn on_unknown(&mut self, path: &Path) { 227 | self.unknown.push(path.display().to_string()); 228 | } 229 | 230 | fn on_matched(&mut self, _: &HeaderMatcher, mut doc: Document) -> anyhow::Result<()> { 231 | self.remove(&mut doc) 232 | } 233 | 234 | fn on_not_matched(&mut self, _: &HeaderMatcher, mut doc: Document) -> anyhow::Result<()> { 235 | self.remove(&mut doc) 236 | } 237 | } 238 | 239 | impl CommandRemove { 240 | fn run(self) { 241 | let config = self.shared.config.unwrap_or_else(default_config); 242 | let mut context = RemoveContext { 243 | dry_run: self.shared_edit.dry_run, 244 | unknown: vec![], 245 | removed: vec![], 246 | }; 247 | check_license_header(config, &mut context).unwrap(); 248 | 249 | let mut failed = check_unknown_files(context.unknown, self.shared.fail_if_unknown); 250 | if !context.removed.is_empty() { 251 | log::info!( 252 | "Removed header for files (dryRun={}): {:?}", 253 | self.shared_edit.dry_run, 254 | context.removed 255 | ); 256 | failed |= self.shared_edit.fail_if_updated; 257 | } 258 | if failed { 259 | std::process::exit(1); 260 | } 261 | log::info!("No file has been removed header."); 262 | } 263 | } 264 | 265 | fn check_unknown_files(unknown: Vec, fail_if_unknown: bool) -> bool { 266 | if !unknown.is_empty() { 267 | if fail_if_unknown { 268 | log::error!("Processing unknown files: {:?}", unknown); 269 | return true; 270 | } else { 271 | log::warn!("Processing unknown files: {:?}", unknown); 272 | } 273 | } 274 | false 275 | } 276 | 277 | fn default_config() -> PathBuf { 278 | PathBuf::new().join("licenserc.toml") 279 | } 280 | -------------------------------------------------------------------------------- /cli/src/version.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use shadow_rs::shadow; 16 | 17 | shadow!(build); 18 | 19 | #[derive(Clone, Debug, PartialEq)] 20 | pub struct BuildInfo { 21 | pub branch: &'static str, 22 | pub commit: &'static str, 23 | pub commit_short: &'static str, 24 | pub clean: bool, 25 | pub description: &'static str, 26 | pub source_time: &'static str, 27 | pub build_time: &'static str, 28 | pub rustc: &'static str, 29 | pub target: &'static str, 30 | pub version: &'static str, 31 | } 32 | 33 | pub const fn build_info() -> BuildInfo { 34 | BuildInfo { 35 | branch: build::BRANCH, 36 | commit: build::COMMIT_HASH, 37 | commit_short: build::SHORT_COMMIT, 38 | clean: build::GIT_CLEAN, 39 | description: build::PKG_DESCRIPTION, 40 | source_time: env!("SOURCE_TIMESTAMP"), 41 | build_time: env!("BUILD_TIMESTAMP"), 42 | rustc: build::RUST_VERSION, 43 | target: build::BUILD_TARGET, 44 | version: build::PKG_VERSION, 45 | } 46 | } 47 | 48 | pub const fn version() -> &'static str { 49 | const BUILD_INFO: BuildInfo = build_info(); 50 | 51 | const_format::formatcp!( 52 | "\nversion: {}\nbranch: {}\ncommit: {}\nclean: {}\nsource_time: {}\nbuild_time: {}\nrustc: {}\ntarget: {}", 53 | BUILD_INFO.version, 54 | BUILD_INFO.branch, 55 | BUILD_INFO.commit, 56 | BUILD_INFO.clean, 57 | BUILD_INFO.source_time, 58 | BUILD_INFO.build_time, 59 | BUILD_INFO.rustc, 60 | BUILD_INFO.target, 61 | ) 62 | } 63 | -------------------------------------------------------------------------------- /fmt/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "hawkeye-fmt" 17 | description = "The formatter library for hawkeye cli." 18 | version.workspace = true 19 | edition.workspace = true 20 | authors.workspace = true 21 | readme.workspace = true 22 | license.workspace = true 23 | repository.workspace = true 24 | 25 | [dependencies] 26 | anyhow = { workspace = true } 27 | chrono = "0.4.41" 28 | gix = { version = "0.72.1", default-features = false, features = [ 29 | "blob-diff", 30 | "excludes", 31 | ] } 32 | ignore = { version = "0.4.23" } 33 | log = { workspace = true } 34 | minijinja = { version = "2.5.0" } 35 | regex = { version = "1.11.1" } 36 | serde = { version = "1.0.216", features = ["derive"] } 37 | toml = { workspace = true } 38 | walkdir = { version = "2.5.0" } 39 | -------------------------------------------------------------------------------- /fmt/src/config/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::HashMap; 16 | use std::collections::HashSet; 17 | use std::hash::Hash; 18 | use std::hash::Hasher; 19 | use std::path::PathBuf; 20 | 21 | use serde::de::Error; 22 | use serde::Deserialize; 23 | use serde::Deserializer; 24 | use toml::Value; 25 | 26 | use crate::default_true; 27 | 28 | #[derive(Debug, Clone, Default, Deserialize)] 29 | #[serde(default, deny_unknown_fields, rename_all = "camelCase")] 30 | pub struct Config { 31 | #[serde(default = "default_cwd")] 32 | pub base_dir: PathBuf, 33 | 34 | pub inline_header: Option, 35 | pub header_path: Option, 36 | 37 | #[serde(default = "default_true")] 38 | pub strict_check: bool, 39 | #[serde(default = "default_true")] 40 | pub use_default_excludes: bool, 41 | #[serde(default = "default_true")] 42 | pub use_default_mapping: bool, 43 | #[serde(default = "default_keywords")] 44 | pub keywords: Vec, 45 | 46 | pub includes: Vec, 47 | pub excludes: Vec, 48 | 49 | #[serde(deserialize_with = "de_properties")] 50 | pub properties: HashMap, 51 | #[serde(deserialize_with = "de_mapping")] 52 | pub mapping: HashSet, 53 | 54 | pub git: Git, 55 | 56 | pub additional_headers: Vec, 57 | } 58 | 59 | #[derive(Debug, Clone, Copy, Deserialize)] 60 | pub struct Git { 61 | pub attrs: FeatureGate, 62 | pub ignore: FeatureGate, 63 | } 64 | 65 | impl Default for Git { 66 | fn default() -> Self { 67 | Git { 68 | attrs: FeatureGate::Disable, // expensive 69 | ignore: FeatureGate::Auto, 70 | } 71 | } 72 | } 73 | 74 | #[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Deserialize)] 75 | #[serde(rename_all = "snake_case")] 76 | pub enum FeatureGate { 77 | /// Determinate whether turn on the feature. 78 | Auto, 79 | /// Force enable the feature. 80 | Enable, 81 | /// Force disable the feature. 82 | Disable, 83 | } 84 | 85 | impl FeatureGate { 86 | pub fn is_enable(&self) -> bool { 87 | match self { 88 | FeatureGate::Auto => false, 89 | FeatureGate::Enable => true, 90 | FeatureGate::Disable => false, 91 | } 92 | } 93 | 94 | pub fn is_disable(&self) -> bool { 95 | match self { 96 | FeatureGate::Auto => false, 97 | FeatureGate::Enable => false, 98 | FeatureGate::Disable => true, 99 | } 100 | } 101 | 102 | pub fn is_auto(&self) -> bool { 103 | match self { 104 | FeatureGate::Auto => true, 105 | FeatureGate::Enable => false, 106 | FeatureGate::Disable => false, 107 | } 108 | } 109 | } 110 | 111 | #[derive(Debug, Clone)] 112 | pub enum Mapping { 113 | Filename { 114 | pattern: String, 115 | header_type: String, 116 | }, 117 | Extension { 118 | pattern: String, 119 | header_type: String, 120 | }, 121 | } 122 | 123 | impl PartialEq for Mapping { 124 | fn eq(&self, other: &Self) -> bool { 125 | match (self, other) { 126 | (Mapping::Filename { pattern: p1, .. }, Mapping::Filename { pattern: p2, .. }) => { 127 | p1 == p2 128 | } 129 | (Mapping::Extension { pattern: p1, .. }, Mapping::Extension { pattern: p2, .. }) => { 130 | p1 == p2 131 | } 132 | _ => false, 133 | } 134 | } 135 | } 136 | 137 | impl Eq for Mapping {} 138 | 139 | impl Hash for Mapping { 140 | fn hash(&self, state: &mut H) { 141 | state.write(match self { 142 | Mapping::Filename { pattern, .. } => pattern.as_bytes(), 143 | Mapping::Extension { pattern, .. } => pattern.as_bytes(), 144 | }); 145 | } 146 | } 147 | 148 | impl Mapping { 149 | pub fn header_type(&self, filename: &str) -> Option { 150 | let filename = filename.to_lowercase(); 151 | match self { 152 | Mapping::Filename { 153 | header_type, 154 | pattern, 155 | } => { 156 | let pattern = pattern.to_lowercase(); 157 | (filename == pattern).then(|| header_type.clone()) 158 | } 159 | Mapping::Extension { 160 | header_type, 161 | pattern, 162 | } => { 163 | let pattern = format!(".{pattern}").to_lowercase(); 164 | filename.ends_with(&pattern).then(|| header_type.clone()) 165 | } 166 | } 167 | } 168 | } 169 | 170 | fn default_cwd() -> PathBuf { 171 | ".".into() 172 | } 173 | 174 | fn default_keywords() -> Vec { 175 | vec!["copyright".to_string()] 176 | } 177 | 178 | fn de_properties<'de, D>(de: D) -> Result, D::Error> 179 | where 180 | D: Deserializer<'de>, 181 | { 182 | HashMap::::deserialize(de)? 183 | .into_iter() 184 | .map(|(k, v)| { 185 | let v = match v { 186 | Value::String(v) => Ok(v), 187 | Value::Integer(v) => Ok(v.to_string()), 188 | Value::Float(v) => Ok(v.to_string()), 189 | Value::Boolean(v) => Ok(v.to_string()), 190 | Value::Datetime(v) => Ok(v.to_string()), 191 | Value::Array(_) => Err(Error::custom("array cannot be property value")), 192 | Value::Table(_) => Err(Error::custom("table cannot be property value")), 193 | }?; 194 | Ok((k, v)) 195 | }) 196 | .collect() 197 | } 198 | 199 | fn de_mapping<'de, D>(de: D) -> Result, D::Error> 200 | where 201 | D: Deserializer<'de>, 202 | { 203 | #[derive(Debug, Default, Clone, Deserialize)] 204 | #[serde(default)] 205 | struct MappingModel { 206 | extensions: Vec, 207 | filenames: Vec, 208 | } 209 | 210 | let mappings = HashMap::::deserialize(de)?; 211 | let mut set = HashSet::new(); 212 | for (header_type, model) in mappings { 213 | for pattern in model.extensions { 214 | set.insert(Mapping::Extension { 215 | pattern, 216 | header_type: header_type.clone(), 217 | }); 218 | } 219 | for pattern in model.filenames { 220 | set.insert(Mapping::Filename { 221 | pattern, 222 | header_type: header_type.clone(), 223 | }); 224 | } 225 | } 226 | Ok(set) 227 | } 228 | -------------------------------------------------------------------------------- /fmt/src/document/defaults.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [ACTIONSCRIPT] 16 | pattern = "as" 17 | headerType = "SLASHSTAR_STYLE" 18 | extension = true 19 | filename = false 20 | 21 | [ADA_BODY] 22 | pattern = "adb" 23 | headerType = "DOUBLEDASHES_STYLE" 24 | extension = true 25 | filename = false 26 | 27 | [ADA_SPEC] 28 | pattern = "ads" 29 | headerType = "DOUBLEDASHES_STYLE" 30 | extension = true 31 | filename = false 32 | 33 | [ASCII_DOC] 34 | pattern = "adoc" 35 | headerType = "ASCIIDOC_STYLE" 36 | extension = true 37 | filename = false 38 | 39 | [ASP] 40 | pattern = "asp" 41 | headerType = "ASP" 42 | extension = true 43 | filename = false 44 | 45 | [ASPECTJ] 46 | pattern = "aj" 47 | headerType = "SLASHSTAR_STYLE" 48 | extension = true 49 | filename = false 50 | 51 | [ASSEMBLER] 52 | pattern = "asm" 53 | headerType = "SEMICOLON_STYLE" 54 | extension = true 55 | filename = false 56 | 57 | [C] 58 | pattern = "c" 59 | headerType = "SLASHSTAR_STYLE" 60 | extension = true 61 | filename = false 62 | 63 | [CC] 64 | pattern = "cc" 65 | headerType = "SLASHSTAR_STYLE" 66 | extension = true 67 | filename = false 68 | 69 | [CLOJURE] 70 | pattern = "clj" 71 | headerType = "SEMICOLON_STYLE" 72 | extension = true 73 | filename = false 74 | 75 | [CLOJURESCRIPT] 76 | pattern = "cljs" 77 | headerType = "SEMICOLON_STYLE" 78 | extension = true 79 | filename = false 80 | 81 | [CMAKELISTS] 82 | pattern = "CMakeLists.txt" 83 | headerType = "SCRIPT_STYLE" 84 | extension = false 85 | filename = true 86 | 87 | [COLDFUSION_COMPONENT] 88 | pattern = "cfc" 89 | headerType = "DYNASCRIPT3_STYLE" 90 | extension = true 91 | filename = false 92 | 93 | [COLDFUSION_ML] 94 | pattern = "cfm" 95 | headerType = "DYNASCRIPT3_STYLE" 96 | extension = true 97 | filename = false 98 | 99 | [CPP] 100 | pattern = "cpp" 101 | headerType = "SLASHSTAR_STYLE" 102 | extension = true 103 | filename = false 104 | 105 | [CSHARP] 106 | pattern = "cs" 107 | headerType = "SLASHSTAR_STYLE" 108 | extension = true 109 | filename = false 110 | 111 | [CSS] 112 | pattern = "css" 113 | headerType = "SLASHSTAR_STYLE" 114 | extension = true 115 | filename = false 116 | 117 | [DELPHI] 118 | pattern = "pas" 119 | headerType = "BRACESSTAR_STYLE" 120 | extension = true 121 | filename = false 122 | 123 | [DOCKERFILE] 124 | pattern = "Dockerfile" 125 | headerType = "SCRIPT_STYLE" 126 | extension = false 127 | filename = true 128 | 129 | [DOXIA_APT] 130 | pattern = "apt" 131 | headerType = "DOUBLETILDE_STYLE" 132 | extension = true 133 | filename = false 134 | 135 | [DOXIA_FAQ] 136 | pattern = "fml" 137 | headerType = "XML_STYLE" 138 | extension = true 139 | filename = false 140 | 141 | [DTD] 142 | pattern = "dtd" 143 | headerType = "XML_STYLE" 144 | extension = true 145 | filename = false 146 | 147 | [EDITORCONFIG] 148 | pattern = ".editorconfig" 149 | headerType = "SCRIPT_STYLE" 150 | extension = false 151 | filename = true 152 | 153 | [EIFFEL] 154 | pattern = "e" 155 | headerType = "DOUBLEDASHES_STYLE" 156 | extension = true 157 | filename = false 158 | 159 | [ERLANG] 160 | pattern = "erl" 161 | headerType = "PERCENT3_STYLE" 162 | extension = true 163 | filename = false 164 | 165 | [ERLANG_HEADER] 166 | pattern = "hrl" 167 | headerType = "PERCENT3_STYLE" 168 | extension = true 169 | filename = false 170 | 171 | [FORTRAN] 172 | pattern = "f" 173 | headerType = "EXCLAMATION_STYLE" 174 | extension = true 175 | filename = false 176 | 177 | [FREEMARKER] 178 | pattern = "ftl" 179 | headerType = "FTL" 180 | extension = true 181 | filename = false 182 | 183 | [GO] 184 | pattern = "go" 185 | headerType = "SLASHSTAR_STYLE" 186 | extension = true 187 | filename = false 188 | 189 | [GO_MOD] 190 | pattern = "go.mod" 191 | headerType = "DOUBLESLASH_STYLE" 192 | extension = false 193 | filename = true 194 | 195 | [GRADLE] 196 | pattern = "gradle" 197 | headerType = "SLASHSTAR_STYLE" 198 | extension = true 199 | filename = false 200 | 201 | [GROOVY] 202 | pattern = "groovy" 203 | headerType = "SLASHSTAR_STYLE" 204 | extension = true 205 | filename = false 206 | 207 | [GSP] 208 | pattern = "GSP" 209 | headerType = "XML_STYLE" 210 | extension = true 211 | filename = false 212 | 213 | [H] 214 | pattern = "h" 215 | headerType = "SLASHSTAR_STYLE" 216 | extension = true 217 | filename = false 218 | 219 | [HH] 220 | pattern = "hh" 221 | headerType = "SLASHSTAR_STYLE" 222 | extension = true 223 | filename = false 224 | 225 | [HPP] 226 | pattern = "hpp" 227 | headerType = "SLASHSTAR_STYLE" 228 | extension = true 229 | filename = false 230 | 231 | [HAML] 232 | pattern = "haml" 233 | headerType = "HAML_STYLE" 234 | extension = true 235 | filename = false 236 | 237 | [HTM] 238 | pattern = "htm" 239 | headerType = "XML_STYLE" 240 | extension = true 241 | filename = false 242 | 243 | [HTML] 244 | pattern = "html" 245 | headerType = "XML_STYLE" 246 | extension = true 247 | filename = false 248 | 249 | [JAVA] 250 | pattern = "java" 251 | headerType = "SLASHSTAR_STYLE" 252 | extension = true 253 | filename = false 254 | 255 | [JAVAFX] 256 | pattern = "fx" 257 | headerType = "SLASHSTAR_STYLE" 258 | extension = true 259 | filename = false 260 | 261 | [JAVASCRIPT] 262 | pattern = "js" 263 | headerType = "SLASHSTAR_STYLE" 264 | extension = true 265 | filename = false 266 | 267 | [JSP] 268 | pattern = "jsp" 269 | headerType = "DYNASCRIPT_STYLE" 270 | extension = true 271 | filename = false 272 | 273 | [JSPX] 274 | pattern = "jspx" 275 | headerType = "XML_STYLE" 276 | extension = true 277 | filename = false 278 | 279 | [JSX] 280 | pattern = "jsx" 281 | headerType = "SLASHSTAR_STYLE" 282 | extension = true 283 | filename = false 284 | 285 | [KML] 286 | pattern = "kml" 287 | headerType = "XML_STYLE" 288 | extension = true 289 | filename = false 290 | 291 | [KOTLIN] 292 | pattern = "kt" 293 | headerType = "SLASHSTAR_STYLE" 294 | extension = true 295 | filename = false 296 | 297 | [KOTLIN_SCRIPT] 298 | pattern = "kts" 299 | headerType = "SLASHSTAR_STYLE" 300 | extension = true 301 | filename = false 302 | 303 | [LISP] 304 | pattern = "el" 305 | headerType = "EXCLAMATION3_STYLE" 306 | extension = true 307 | filename = false 308 | 309 | [LUA] 310 | pattern = "lua" 311 | headerType = "LUA" 312 | extension = true 313 | filename = false 314 | 315 | [MAKEFILE] 316 | pattern = "Makefile" 317 | headerType = "SCRIPT_STYLE" 318 | extension = true 319 | filename = true 320 | 321 | [MOONBIT] 322 | pattern = "mbt" 323 | headerType = "DOUBLESLASH_STYLE" 324 | extension = true 325 | filename = false 326 | 327 | [MUSTACHE] 328 | pattern = "mustache" 329 | headerType = "MUSTACHE_STYLE" 330 | extension = true 331 | filename = false 332 | 333 | [MVEL] 334 | pattern = "mv" 335 | headerType = "MVEL_STYLE" 336 | extension = true 337 | filename = false 338 | 339 | [MXML] 340 | pattern = "mxml" 341 | headerType = "XML_STYLE" 342 | extension = true 343 | filename = false 344 | 345 | [PERL] 346 | pattern = "pl" 347 | headerType = "SCRIPT_STYLE" 348 | extension = true 349 | filename = false 350 | 351 | [PERL_MODULE] 352 | pattern = "pm" 353 | headerType = "SCRIPT_STYLE" 354 | extension = true 355 | filename = false 356 | 357 | [PKL] 358 | pattern = "pkl" 359 | headerType = "LINE_BLOCK_STYLE" 360 | extension = true 361 | filename = false 362 | 363 | [PKL_PROJECT] 364 | pattern = "PklProject" 365 | headerType = "LINE_BLOCK_STYLE" 366 | extension = false 367 | filename = true 368 | 369 | [PHP] 370 | pattern = "php" 371 | headerType = "PHP" 372 | extension = true 373 | filename = false 374 | 375 | [POM] 376 | pattern = "pom" 377 | headerType = "XML_STYLE" 378 | extension = true 379 | filename = false 380 | 381 | [PROPERTIES] 382 | pattern = "properties" 383 | headerType = "SCRIPT_STYLE" 384 | extension = true 385 | filename = false 386 | 387 | [PROTO] 388 | pattern = "proto" 389 | headerType = "SLASHSTAR_STYLE" 390 | extension = true 391 | filename = false 392 | 393 | [PYTHON] 394 | pattern = "py" 395 | headerType = "SCRIPT_STYLE" 396 | extension = true 397 | filename = false 398 | 399 | [PYTHON_STUBS] 400 | pattern = "pyi" 401 | headerType = "SCRIPT_STYLE" 402 | extension = true 403 | filename = false 404 | 405 | [RUBY] 406 | pattern = "rb" 407 | headerType = "SCRIPT_STYLE" 408 | extension = true 409 | filename = false 410 | 411 | [RUST] 412 | pattern = "rs" 413 | headerType = "DOUBLESLASH_STYLE" 414 | extension = true 415 | filename = false 416 | 417 | [SCALA] 418 | pattern = "scala" 419 | headerType = "SLASHSTAR_STYLE" 420 | extension = true 421 | filename = false 422 | 423 | [SCAML] 424 | pattern = "scaml" 425 | headerType = "HAML_STYLE" 426 | extension = true 427 | filename = false 428 | 429 | [SCSS] 430 | pattern = "scss" 431 | headerType = "SLASHSTAR_STYLE" 432 | extension = true 433 | filename = false 434 | 435 | [SHELL] 436 | pattern = "sh" 437 | headerType = "SCRIPT_STYLE" 438 | extension = true 439 | filename = false 440 | 441 | [SPRING_FACTORIES] 442 | pattern = "spring.factories" 443 | headerType = "SCRIPT_STYLE" 444 | extension = false 445 | filename = false 446 | 447 | [SVELTE] 448 | pattern = "svelte" 449 | headerType = "XML_STYLE" 450 | extension = true 451 | filename = false 452 | 453 | [SQL] 454 | pattern = "sql" 455 | headerType = "DOUBLEDASHES_STYLE" 456 | extension = true 457 | filename = false 458 | 459 | [TAGX] 460 | pattern = "tagx" 461 | headerType = "XML_STYLE" 462 | extension = true 463 | filename = false 464 | 465 | [TEX_CLASS] 466 | pattern = "cls" 467 | headerType = "PERCENT_STYLE" 468 | extension = true 469 | filename = false 470 | 471 | [TEX_STYLE] 472 | pattern = "sty" 473 | headerType = "PERCENT_STYLE" 474 | extension = true 475 | filename = false 476 | 477 | [TEX] 478 | pattern = "tex" 479 | headerType = "PERCENT_STYLE" 480 | extension = true 481 | filename = false 482 | 483 | [TLD] 484 | pattern = "tld" 485 | headerType = "XML_STYLE" 486 | extension = true 487 | filename = false 488 | 489 | [TOML] 490 | pattern = "toml" 491 | headerType = "SCRIPT_STYLE" 492 | extension = true 493 | filename = false 494 | 495 | [TS] 496 | pattern = "ts" 497 | headerType = "SLASHSTAR_STYLE" 498 | extension = true 499 | filename = false 500 | 501 | [TSX] 502 | pattern = "tsx" 503 | headerType = "SLASHSTAR_STYLE" 504 | extension = true 505 | filename = false 506 | 507 | [VB] 508 | pattern = "bas" 509 | headerType = "HAML_STYLE" 510 | extension = true 511 | filename = false 512 | 513 | [VBA] 514 | pattern = "vba" 515 | headerType = "APOSTROPHE_STYLE" 516 | extension = true 517 | filename = false 518 | 519 | [VELOCITY] 520 | pattern = "vm" 521 | headerType = "SHARPSTAR_STYLE" 522 | extension = true 523 | filename = false 524 | 525 | [WINDOWS_BATCH] 526 | pattern = "bat" 527 | headerType = "BATCH" 528 | extension = true 529 | filename = false 530 | 531 | [WINDOWS_SHELL] 532 | pattern = "cmd" 533 | headerType = "BATCH" 534 | extension = true 535 | filename = false 536 | 537 | [WSDL] 538 | pattern = "wsdl" 539 | headerType = "XML_STYLE" 540 | extension = true 541 | filename = false 542 | 543 | [XHTML] 544 | pattern = "xhtml" 545 | headerType = "XML_STYLE" 546 | extension = true 547 | filename = false 548 | 549 | [XML] 550 | pattern = "xml" 551 | headerType = "XML_STYLE" 552 | extension = true 553 | filename = false 554 | 555 | [XSD] 556 | pattern = "xsd" 557 | headerType = "XML_STYLE" 558 | extension = true 559 | filename = false 560 | 561 | [XSL] 562 | pattern = "xsl" 563 | headerType = "XML_STYLE" 564 | extension = true 565 | filename = false 566 | 567 | [XSLT] 568 | pattern = "xslt" 569 | headerType = "XML_STYLE" 570 | extension = true 571 | filename = false 572 | 573 | [YAML] 574 | pattern = "yaml" 575 | headerType = "SCRIPT_STYLE" 576 | extension = true 577 | filename = false 578 | 579 | [YML] 580 | pattern = "yml" 581 | headerType = "SCRIPT_STYLE" 582 | extension = true 583 | filename = false 584 | 585 | [ZIG] 586 | pattern = "zig" 587 | headerType = "DOUBLESLASH_STYLE" 588 | extension = true 589 | filename = false 590 | -------------------------------------------------------------------------------- /fmt/src/document/factory.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::HashMap; 16 | use std::collections::HashSet; 17 | use std::path::Path; 18 | use std::path::PathBuf; 19 | 20 | use std::fs; 21 | 22 | use anyhow::Context; 23 | use gix::date::time::CustomFormat; 24 | 25 | use crate::config::Mapping; 26 | use crate::document::Attributes; 27 | use crate::document::Document; 28 | use crate::git::GitFileAttrs; 29 | use crate::header::model::HeaderDef; 30 | 31 | pub struct DocumentFactory { 32 | mapping: HashSet, 33 | definitions: HashMap, 34 | properties: HashMap, 35 | 36 | keywords: Vec, 37 | git_file_attrs: HashMap, 38 | } 39 | 40 | impl DocumentFactory { 41 | pub fn new( 42 | mapping: HashSet, 43 | definitions: HashMap, 44 | properties: HashMap, 45 | keywords: Vec, 46 | git_file_attrs: HashMap, 47 | ) -> Self { 48 | Self { 49 | mapping, 50 | definitions, 51 | properties, 52 | keywords, 53 | git_file_attrs, 54 | } 55 | } 56 | 57 | pub fn create_document(&self, filepath: &Path) -> anyhow::Result> { 58 | let lower_file_name = filepath 59 | .file_name() 60 | .map(|n| n.to_string_lossy().to_lowercase()) 61 | .unwrap_or_default(); 62 | let header_type = self 63 | .mapping 64 | .iter() 65 | .find_map(|m| m.header_type(&lower_file_name)) 66 | .unwrap_or_else(|| "unknown".to_string()) 67 | .to_lowercase(); 68 | let header_def = self 69 | .definitions 70 | .get(&header_type) 71 | .ok_or_else(|| std::io::Error::other(format!("header type {header_type} not found"))) 72 | .with_context(|| format!("cannot to create document: {}", filepath.display()))?; 73 | 74 | let props = self.properties.clone(); 75 | 76 | const YEAR_FORMAT: CustomFormat = CustomFormat::new("%Y"); 77 | let attrs = Attributes { 78 | filename: filepath 79 | .file_name() 80 | .map(|s| s.to_string_lossy().to_string()), 81 | git_file_created_year: self 82 | .git_file_attrs 83 | .get(filepath) 84 | .map(|attrs| attrs.created_time.format(YEAR_FORMAT)), 85 | git_file_modified_year: self 86 | .git_file_attrs 87 | .get(filepath) 88 | .map(|attrs| attrs.modified_time.format(YEAR_FORMAT)), 89 | git_authors: self 90 | .git_file_attrs 91 | .get(filepath) 92 | .map(|attrs| attrs.authors.clone()) 93 | .unwrap_or_default(), 94 | disk_file_creation_year: fs::metadata(filepath) 95 | .and_then(|meta| meta.created()) 96 | .ok() 97 | .map(|created_time| { 98 | let datetime = chrono::DateTime::::from(created_time); 99 | datetime.format("%Y").to_string() 100 | }), 101 | }; 102 | 103 | Document::new( 104 | filepath.to_path_buf(), 105 | header_def.clone(), 106 | &self.keywords, 107 | props, 108 | attrs, 109 | ) 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /fmt/src/document/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::BTreeSet; 16 | use std::collections::HashMap; 17 | use std::fs; 18 | use std::fs::File; 19 | use std::io::BufRead; 20 | use std::path::PathBuf; 21 | 22 | use anyhow::Context; 23 | use minijinja::context; 24 | use minijinja::Environment; 25 | use serde::Deserialize; 26 | use serde::Serialize; 27 | 28 | use crate::header::matcher::HeaderMatcher; 29 | use crate::header::model::HeaderDef; 30 | use crate::header::parser::parse_header; 31 | use crate::header::parser::FileContent; 32 | use crate::header::parser::HeaderParser; 33 | 34 | pub mod factory; 35 | pub mod model; 36 | 37 | #[derive(Debug, Clone, Serialize, Deserialize)] 38 | pub struct Attributes { 39 | pub filename: Option, 40 | pub git_file_created_year: Option, 41 | pub git_file_modified_year: Option, 42 | pub git_authors: BTreeSet, 43 | pub disk_file_creation_year: Option, 44 | } 45 | 46 | #[derive(Debug)] 47 | pub struct Document { 48 | pub filepath: PathBuf, 49 | 50 | header_def: HeaderDef, 51 | props: HashMap, 52 | attrs: Attributes, 53 | parser: HeaderParser, 54 | } 55 | 56 | impl Document { 57 | pub fn new( 58 | filepath: PathBuf, 59 | header_def: HeaderDef, 60 | keywords: &[String], 61 | props: HashMap, 62 | attrs: Attributes, 63 | ) -> anyhow::Result> { 64 | match FileContent::new(&filepath) { 65 | Ok(content) => Ok(Some(Self { 66 | parser: parse_header(content, &header_def, keywords), 67 | filepath, 68 | header_def, 69 | props, 70 | attrs, 71 | })), 72 | Err(e) => { 73 | if matches!(e.kind(), std::io::ErrorKind::InvalidData) { 74 | log::debug!("skip non-textual file: {}", filepath.display()); 75 | Ok(None) 76 | } else { 77 | Err(e).with_context(|| { 78 | format!("cannot to create document: {}", filepath.display()) 79 | }) 80 | } 81 | } 82 | } 83 | } 84 | 85 | pub fn is_unsupported(&self) -> bool { 86 | self.header_def.name.eq_ignore_ascii_case("unknown") 87 | } 88 | 89 | /// Detected but not necessarily a valid header 90 | pub fn header_detected(&self) -> bool { 91 | self.parser.end_pos.is_some() 92 | } 93 | 94 | /// Detected and valid header 95 | pub fn header_matched( 96 | &self, 97 | header: &HeaderMatcher, 98 | strict_check: bool, 99 | ) -> anyhow::Result { 100 | if strict_check { 101 | let file_header = { 102 | let mut lines = self.read_file_first_lines(header)?.join("\n"); 103 | lines.push_str("\n\n"); 104 | lines.replace(" *\r?\n", "\n") 105 | }; 106 | let expected_header = { 107 | let raw_header = header.build_for_definition(&self.header_def); 108 | let resolved_header = self.merge_properties(&raw_header)?; 109 | resolved_header.replace(" *\r?\n", "\n") 110 | }; 111 | Ok(file_header.contains(expected_header.as_str())) 112 | } else { 113 | let file_header = self.read_file_header_on_one_line(header)?; 114 | let expected_header = self.merge_properties(header.header_content_one_line())?; 115 | Ok(file_header.contains(expected_header.as_str())) 116 | } 117 | } 118 | 119 | fn read_file_first_lines(&self, header: &HeaderMatcher) -> std::io::Result> { 120 | let file = File::open(&self.filepath)?; 121 | std::io::BufReader::new(file) 122 | .lines() 123 | .take(header.header_content_lines_count() + 10) 124 | .collect::>>() 125 | } 126 | 127 | fn read_file_header_on_one_line(&self, header: &HeaderMatcher) -> std::io::Result { 128 | let first_lines = self.read_file_first_lines(header)?; 129 | let file_header = first_lines 130 | .join("") 131 | .trim() 132 | .replace(self.header_def.first_line.trim(), "") 133 | .replace(self.header_def.end_line.trim(), "") 134 | .replace(self.header_def.before_each_line.trim(), "") 135 | .replace(self.header_def.after_each_line.trim(), "") 136 | .split_whitespace() 137 | .collect(); 138 | Ok(file_header) 139 | } 140 | 141 | pub fn update_header(&mut self, header: &HeaderMatcher) -> anyhow::Result<()> { 142 | let header_str = header.build_for_definition(&self.header_def); 143 | let header_str = self.merge_properties(&header_str)?; 144 | let begin_pos = self.parser.begin_pos; 145 | self.parser 146 | .file_content 147 | .insert(begin_pos, header_str.as_str()); 148 | Ok(()) 149 | } 150 | 151 | pub fn remove_header(&mut self) { 152 | if let Some(end_pos) = self.parser.end_pos { 153 | self.parser 154 | .file_content 155 | .delete(self.parser.begin_pos, end_pos); 156 | } 157 | } 158 | 159 | pub fn save(&mut self, filepath: Option<&PathBuf>) -> anyhow::Result<()> { 160 | let filepath = filepath.unwrap_or(&self.filepath); 161 | fs::write(filepath, self.parser.file_content.content()) 162 | .context(format!("cannot save document {}", filepath.display())) 163 | } 164 | 165 | pub(crate) fn merge_properties(&self, s: &str) -> anyhow::Result { 166 | let mut env = Environment::new(); 167 | env.add_template("template", s) 168 | .context("malformed template")?; 169 | 170 | let tmpl = env.get_template("template").expect("template must exist"); 171 | let mut result = tmpl.render(context! { 172 | props => &self.props, 173 | attrs => &self.attrs, 174 | })?; 175 | result.push('\n'); 176 | Ok(result) 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /fmt/src/document/model.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::HashMap; 16 | 17 | use serde::Deserialize; 18 | use serde::Serialize; 19 | 20 | use crate::config::Mapping; 21 | 22 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] 23 | #[serde(default, rename_all = "camelCase")] 24 | pub struct DocumentType { 25 | pub pattern: String, 26 | pub header_type: String, 27 | pub extension: bool, 28 | pub filename: bool, 29 | } 30 | 31 | pub fn default_mapping() -> Vec { 32 | let defaults = include_str!("defaults.toml"); 33 | let mapping: HashMap = 34 | toml::from_str(defaults).expect("default mapping must be valid"); 35 | 36 | mapping 37 | .into_iter() 38 | .flat_map(|(_, doctype)| { 39 | let mut ms = vec![]; 40 | if doctype.extension { 41 | ms.push(Mapping::Extension { 42 | pattern: doctype.pattern.clone(), 43 | header_type: doctype.header_type.clone(), 44 | }) 45 | } 46 | if doctype.filename { 47 | ms.push(Mapping::Filename { 48 | pattern: doctype.pattern, 49 | header_type: doctype.header_type, 50 | }) 51 | } 52 | ms 53 | }) 54 | .collect() 55 | } 56 | -------------------------------------------------------------------------------- /fmt/src/git.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::hash_map::Entry; 16 | use std::collections::BTreeSet; 17 | use std::collections::HashMap; 18 | use std::path::Path; 19 | use std::path::PathBuf; 20 | 21 | use anyhow::bail; 22 | use anyhow::Context; 23 | use gix::Repository; 24 | 25 | use crate::config; 26 | use crate::config::FeatureGate; 27 | 28 | #[derive(Debug, Clone)] 29 | pub struct GitContext { 30 | pub repo: Option, 31 | pub config: config::Git, 32 | } 33 | 34 | pub fn discover(basedir: &Path, config: config::Git) -> anyhow::Result { 35 | let feature = resolve_features(&config); 36 | 37 | if feature.is_disable() { 38 | return Ok(GitContext { repo: None, config }); 39 | } 40 | 41 | match gix::discover(basedir) { 42 | Ok(repo) => match repo.worktree() { 43 | None => { 44 | let message = "bare repository detected"; 45 | if feature.is_auto() { 46 | log::info!(config:?; "git config is resolved to disabled; {message}"); 47 | Ok(GitContext { repo: None, config }) 48 | } else { 49 | bail!("invalid config: {}", message); 50 | } 51 | } 52 | Some(_) => { 53 | log::info!("git config is resolved to enabled"); 54 | Ok(GitContext { 55 | repo: Some(repo), 56 | config, 57 | }) 58 | } 59 | }, 60 | Err(err) => { 61 | if feature.is_auto() { 62 | log::info!(err:?, config:?; "git config is resolved to disabled"); 63 | Ok(GitContext { repo: None, config }) 64 | } else { 65 | Err(err).context("cannot discover git repository with gix") 66 | } 67 | } 68 | } 69 | } 70 | 71 | fn resolve_features(config: &config::Git) -> FeatureGate { 72 | let features = [config.attrs, config.ignore]; 73 | for feature in features.iter() { 74 | if feature.is_enable() { 75 | return FeatureGate::Enable; 76 | } 77 | } 78 | for feature in features.iter() { 79 | if feature.is_auto() { 80 | return FeatureGate::Auto; 81 | } 82 | } 83 | FeatureGate::Disable 84 | } 85 | 86 | #[derive(Debug)] 87 | pub struct GitFileAttrs { 88 | pub created_time: gix::date::Time, 89 | pub modified_time: gix::date::Time, 90 | pub authors: BTreeSet, 91 | } 92 | 93 | pub fn resolve_file_attrs( 94 | git_context: GitContext, 95 | ) -> anyhow::Result> { 96 | let mut attrs = HashMap::new(); 97 | 98 | if git_context.config.attrs.is_disable() { 99 | return Ok(attrs); 100 | } 101 | 102 | let repo = match git_context.repo { 103 | Some(repo) => repo, 104 | None => return Ok(attrs), 105 | }; 106 | 107 | let workdir = repo.workdir().expect("workdir cannot be absent"); 108 | let workdir = workdir.canonicalize()?; 109 | 110 | let mut do_insert_attrs = 111 | |change: gix::diff::tree_with_rewrites::Change, time: gix::date::Time, author: &str| { 112 | let filepath = gix::path::from_bstr(change.location()); 113 | let filepath = workdir.join(filepath); 114 | match attrs.entry(filepath) { 115 | Entry::Occupied(mut ent) => { 116 | let attrs: &mut GitFileAttrs = ent.get_mut(); 117 | attrs.created_time = time.min(attrs.created_time); 118 | attrs.modified_time = time.max(attrs.modified_time); 119 | attrs.authors.insert(author.to_string()); 120 | } 121 | Entry::Vacant(ent) => { 122 | ent.insert(GitFileAttrs { 123 | created_time: time, 124 | modified_time: time, 125 | authors: { 126 | let mut authors = BTreeSet::new(); 127 | authors.insert(author.to_string()); 128 | authors 129 | }, 130 | }); 131 | } 132 | } 133 | }; 134 | 135 | let option = { 136 | let mut option = gix::diff::Options::default(); 137 | option.track_path(); 138 | option 139 | }; 140 | 141 | let head = repo.head_commit()?; 142 | let mut next_commit = head.clone(); 143 | 144 | for info in head.ancestors().all()? { 145 | let info = info?; 146 | let this_commit = info.object()?; 147 | let time = next_commit.time()?; 148 | let author = next_commit.author()?.name.to_string(); 149 | 150 | let this_tree = this_commit.tree()?; 151 | let next_tree = next_commit.tree()?; 152 | 153 | let changes = repo.diff_tree_to_tree(Some(&this_tree), Some(&next_tree), Some(option))?; 154 | for change in changes { 155 | do_insert_attrs(change, time, author.as_str()); 156 | } 157 | next_commit = this_commit; 158 | } 159 | 160 | // process the root commit 161 | let time = next_commit.time()?; 162 | let author = next_commit.author()?.name.to_string(); 163 | let next_tree = next_commit.tree()?; 164 | let changes = repo.diff_tree_to_tree(None, Some(&next_tree), Some(option))?; 165 | for change in changes { 166 | do_insert_attrs(change, time, author.as_str()); 167 | } 168 | 169 | Ok(attrs) 170 | } 171 | -------------------------------------------------------------------------------- /fmt/src/header/defaults.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [SHARPSTAR_STYLE] 16 | firstLine = '#*' 17 | endLine = ' *#' 18 | beforeEachLine = ' * ' 19 | afterEachLine = '' 20 | allowBlankLines = false 21 | multipleLines = true 22 | padLines = false 23 | firstLineDetectionPattern = '(\s|\t)*#\*.*$' 24 | lastLineDetectionPattern = '.*\*#(\s|\t)*$' 25 | 26 | [PERCENT_STYLE] 27 | firstLine = '' 28 | endLine = "\n" 29 | beforeEachLine = '% ' 30 | afterEachLine = '' 31 | allowBlankLines = false 32 | multipleLines = false 33 | padLines = false 34 | firstLineDetectionPattern = '^% .*$' 35 | lastLineDetectionPattern = '^% .*$' 36 | 37 | [BRACESSTAR_STYLE] 38 | firstLine = '{*' 39 | endLine = ' *}' 40 | beforeEachLine = ' * ' 41 | afterEachLine = '' 42 | allowBlankLines = false 43 | multipleLines = true 44 | padLines = false 45 | firstLineDetectionPattern = '(\s|\t)*\{\*.*$' 46 | lastLineDetectionPattern = '.*\*\}(\s|\t)*$' 47 | 48 | [EXCLAMATION_STYLE] 49 | firstLine = '!' 50 | endLine = "!\n" 51 | beforeEachLine = '! ' 52 | afterEachLine = '' 53 | allowBlankLines = false 54 | multipleLines = false 55 | padLines = false 56 | firstLineDetectionPattern = '!.*$' 57 | lastLineDetectionPattern = '!.*$' 58 | 59 | [MVEL_STYLE] 60 | firstLine = '@comment{' 61 | endLine = '}' 62 | beforeEachLine = ' ' 63 | afterEachLine = '' 64 | allowBlankLines = true 65 | multipleLines = true 66 | padLines = false 67 | firstLineDetectionPattern = '@comment\{$' 68 | lastLineDetectionPattern = '\}$' 69 | 70 | [APOSTROPHE_STYLE] 71 | firstLine = "'" 72 | endLine = "'\n" 73 | beforeEachLine = "' " 74 | afterEachLine = '' 75 | allowBlankLines = false 76 | multipleLines = false 77 | padLines = false 78 | firstLineDetectionPattern = "'.*$" 79 | lastLineDetectionPattern = "'.*$" 80 | 81 | [TRIPLESLASH_STYLE] 82 | firstLine = '///' 83 | endLine = "///\n" 84 | beforeEachLine = '/// ' 85 | afterEachLine = '' 86 | allowBlankLines = false 87 | multipleLines = false 88 | padLines = false 89 | firstLineDetectionPattern = '///.*$' 90 | lastLineDetectionPattern = '///.*$' 91 | 92 | [PHP] 93 | firstLine = '/*' 94 | endLine = ' */' 95 | beforeEachLine = ' * ' 96 | afterEachLine = '' 97 | allowBlankLines = false 98 | multipleLines = true 99 | padLines = false 100 | skipLinePattern = '^<\?php.*$' 101 | firstLineDetectionPattern = '(\s|\t)*/\*.*$' 102 | lastLineDetectionPattern = '.*\*/(\s|\t)*$' 103 | 104 | [LUA] 105 | firstLine = "--[[\n" 106 | endLine = "\n]]" 107 | beforeEachLine = ' ' 108 | afterEachLine = '' 109 | allowBlankLines = true 110 | multipleLines = true 111 | padLines = false 112 | firstLineDetectionPattern = '--\[\[$' 113 | lastLineDetectionPattern = '\]\]$' 114 | 115 | [SCALA_STYLE] 116 | firstLine = '/**' 117 | endLine = ' */' 118 | beforeEachLine = ' * ' 119 | afterEachLine = '' 120 | allowBlankLines = false 121 | multipleLines = true 122 | padLines = false 123 | firstLineDetectionPattern = '(\s|\t)*/\*.*$' 124 | lastLineDetectionPattern = '.*\*/(\s|\t)*$' 125 | 126 | [BATCH] 127 | firstLine = '@REM' 128 | endLine = "@REM\n" 129 | beforeEachLine = '@REM ' 130 | afterEachLine = '' 131 | allowBlankLines = false 132 | multipleLines = false 133 | padLines = false 134 | firstLineDetectionPattern = '@REM.*$' 135 | lastLineDetectionPattern = '@REM.*$' 136 | 137 | [MUSTACHE_STYLE] 138 | firstLine = '{{!' 139 | endLine = '}}' 140 | beforeEachLine = ' ' 141 | afterEachLine = '' 142 | allowBlankLines = false 143 | multipleLines = true 144 | padLines = false 145 | firstLineDetectionPattern = '\{\{\!.*$' 146 | lastLineDetectionPattern = '\}\}.*$' 147 | 148 | [HAML_STYLE] 149 | firstLine = '-#' 150 | endLine = "-#\n" 151 | beforeEachLine = '-# ' 152 | afterEachLine = '' 153 | allowBlankLines = false 154 | multipleLines = false 155 | padLines = false 156 | skipLinePattern = '^-#!.*$' 157 | firstLineDetectionPattern = '-#.*$' 158 | lastLineDetectionPattern = '-#.*$' 159 | 160 | [PERCENT3_STYLE] 161 | firstLine = '%%%' 162 | endLine = "%%%\n" 163 | beforeEachLine = '%%% ' 164 | afterEachLine = '' 165 | allowBlankLines = false 166 | multipleLines = false 167 | padLines = false 168 | firstLineDetectionPattern = '%%%.*$' 169 | lastLineDetectionPattern = '%%%.*$' 170 | 171 | [EXCLAMATION3_STYLE] 172 | firstLine = '!!!' 173 | endLine = "!!!\n" 174 | beforeEachLine = '!!! ' 175 | afterEachLine = '' 176 | allowBlankLines = false 177 | multipleLines = false 178 | padLines = false 179 | firstLineDetectionPattern = '!!!.*$' 180 | lastLineDetectionPattern = '!!!.*$' 181 | 182 | [ASP] 183 | firstLine = '<%' 184 | endLine = '%>' 185 | beforeEachLine = "' " 186 | afterEachLine = '' 187 | allowBlankLines = true 188 | multipleLines = true 189 | padLines = false 190 | firstLineDetectionPattern = '(\s|\t)*<%( .*)?$' 191 | lastLineDetectionPattern = '.*%>(\s|\t)*$' 192 | 193 | [SCRIPT_STYLE] 194 | firstLine = '' 195 | endLine = "\n" 196 | beforeEachLine = '# ' 197 | afterEachLine = '' 198 | allowBlankLines = false 199 | multipleLines = false 200 | padLines = false 201 | skipLinePattern = '^#!.*$' 202 | firstLineDetectionPattern = '#.*$' 203 | lastLineDetectionPattern = '#.*$' 204 | 205 | [JAVAPKG_STYLE] 206 | firstLine = "\n/*-" 207 | endLine = ' */' 208 | beforeEachLine = ' * ' 209 | afterEachLine = '' 210 | allowBlankLines = false 211 | multipleLines = true 212 | padLines = false 213 | skipLinePattern = '^package [a-z_]+(\.[a-z_][a-z0-9_]*)*;$' 214 | firstLineDetectionPattern = '(\s|\t)*/\*.*$' 215 | lastLineDetectionPattern = '.*\*/(\s|\t)*$' 216 | 217 | [DOUBLESLASH_STYLE] 218 | firstLine = '' 219 | endLine = "\n" 220 | beforeEachLine = '// ' 221 | afterEachLine = '' 222 | allowBlankLines = false 223 | multipleLines = false 224 | padLines = false 225 | firstLineDetectionPattern = '//.*$' 226 | lastLineDetectionPattern = '//.*$' 227 | 228 | [XML_STYLE] 229 | firstLine = "" 231 | beforeEachLine = ' ' 232 | afterEachLine = '' 233 | allowBlankLines = true 234 | multipleLines = true 235 | padLines = false 236 | skipLinePattern = '^<\?xml.*>$' 237 | firstLineDetectionPattern = '(\s|\t)*(\s|\t)*$' 239 | 240 | [ASCIIDOC_STYLE] 241 | firstLine = '////' 242 | endLine = "////\n" 243 | beforeEachLine = ' // ' 244 | afterEachLine = '' 245 | allowBlankLines = false 246 | multipleLines = true 247 | padLines = false 248 | firstLineDetectionPattern = '^////$' 249 | lastLineDetectionPattern = '^////$' 250 | 251 | [SEMICOLON_STYLE] 252 | firstLine = ';' 253 | endLine = ";\n" 254 | beforeEachLine = '; ' 255 | afterEachLine = '' 256 | allowBlankLines = false 257 | multipleLines = false 258 | padLines = false 259 | firstLineDetectionPattern = ';.*$' 260 | lastLineDetectionPattern = ';.*$' 261 | 262 | [DOUBLETILDE_STYLE] 263 | firstLine = '~~' 264 | endLine = "~~\n" 265 | beforeEachLine = '~~ ' 266 | afterEachLine = '' 267 | allowBlankLines = false 268 | multipleLines = false 269 | padLines = false 270 | firstLineDetectionPattern = '~~.*$' 271 | lastLineDetectionPattern = '~~.*$' 272 | 273 | [SLASHSTAR_STYLE] 274 | firstLine = '/*' 275 | endLine = " */\n" 276 | beforeEachLine = ' * ' 277 | afterEachLine = '' 278 | allowBlankLines = false 279 | multipleLines = true 280 | padLines = false 281 | firstLineDetectionPattern = '(\s|\t)*/\*.*$' 282 | lastLineDetectionPattern = '.*\*/(\s|\t)*$' 283 | 284 | [FTL_ALT] 285 | firstLine = "[#--\n" 286 | endLine = "\n--]" 287 | beforeEachLine = ' ' 288 | afterEachLine = '' 289 | allowBlankLines = true 290 | multipleLines = true 291 | padLines = false 292 | skipLinePattern = '\[#ftl(\s.*)?\]' 293 | firstLineDetectionPattern = '(\s|\t)*\[#--.*$' 294 | lastLineDetectionPattern = '.*--\](\s|\t)*$' 295 | 296 | [DOUBLEDASHES_STYLE] 297 | firstLine = '--' 298 | endLine = "--\n" 299 | beforeEachLine = '-- ' 300 | afterEachLine = '' 301 | allowBlankLines = false 302 | multipleLines = false 303 | padLines = false 304 | firstLineDetectionPattern = '--.*$' 305 | lastLineDetectionPattern = '--.*$' 306 | 307 | [DYNASCRIPT3_STYLE] 308 | firstLine = "" 310 | beforeEachLine = ' ' 311 | afterEachLine = '' 312 | allowBlankLines = true 313 | multipleLines = true 314 | padLines = false 315 | firstLineDetectionPattern = '(\s|\t)*(\s|\t)*$' 317 | 318 | [SINGLE_LINE_DOUBLESLASH_STYLE] 319 | firstLine = '' 320 | endLine = '' 321 | beforeEachLine = '// ' 322 | afterEachLine = '' 323 | allowBlankLines = false 324 | multipleLines = false 325 | padLines = false 326 | firstLineDetectionPattern = '//.*$' 327 | lastLineDetectionPattern = '//.*$' 328 | 329 | [XML_PER_LINE] 330 | firstLine = "\n" 331 | endLine = "\n" 332 | beforeEachLine = '' 334 | allowBlankLines = false 335 | multipleLines = false 336 | padLines = true 337 | skipLinePattern = '^<\?xml.*>$' 338 | firstLineDetectionPattern = '(\s|\t)*(\s|\t)*$' 340 | 341 | [UNKNOWN] 342 | firstLine = '' 343 | endLine = '' 344 | beforeEachLine = '' 345 | afterEachLine = '' 346 | allowBlankLines = false 347 | multipleLines = false 348 | padLines = false 349 | firstLineDetectionPattern = '' 350 | lastLineDetectionPattern = '' 351 | 352 | [JAVADOC_STYLE] 353 | firstLine = '/**' 354 | endLine = ' */' 355 | beforeEachLine = ' * ' 356 | afterEachLine = '' 357 | allowBlankLines = false 358 | multipleLines = true 359 | padLines = false 360 | firstLineDetectionPattern = '(\s|\t)*/\*.*$' 361 | lastLineDetectionPattern = '.*\*/(\s|\t)*$' 362 | 363 | [DYNASCRIPT_STYLE] 364 | firstLine = "<%--\n" 365 | endLine = "\n--%>" 366 | beforeEachLine = ' ' 367 | afterEachLine = '' 368 | allowBlankLines = true 369 | multipleLines = true 370 | padLines = false 371 | firstLineDetectionPattern = '(\s|\t)*<%--.*$' 372 | lastLineDetectionPattern = '.*--%>(\s|\t)*$' 373 | 374 | [FTL] 375 | firstLine = "<#--\n" 376 | endLine = "\n-->" 377 | beforeEachLine = ' ' 378 | afterEachLine = '' 379 | allowBlankLines = true 380 | multipleLines = true 381 | padLines = false 382 | firstLineDetectionPattern = '(\s|\t)*<#--.*$' 383 | lastLineDetectionPattern = '.*-->(\s|\t)*$' 384 | 385 | [LINE_BLOCK_STYLE] 386 | firstLine = '//===----------------------------------------------------------------------===//' 387 | endLine = "//===----------------------------------------------------------------------===//\n" 388 | beforeEachLine = '// ' 389 | afterEachLine = '' 390 | allowBlankLines = false 391 | multipleLines = true 392 | padLines = false 393 | firstLineDetectionPattern = '//\s?===' 394 | lastLineDetectionPattern = '//\s?===' 395 | -------------------------------------------------------------------------------- /fmt/src/header/matcher.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::fmt::Display; 16 | use std::fmt::Formatter; 17 | 18 | use crate::header::model::HeaderDef; 19 | 20 | #[derive(Debug)] 21 | pub struct HeaderMatcher { 22 | header_content: String, 23 | header_content_one_line: String, 24 | header_content_lines: Vec, 25 | max_length: usize, 26 | } 27 | 28 | impl HeaderMatcher { 29 | pub fn new(header_content: String) -> Self { 30 | let header_content_one_line = header_content.split_whitespace().collect(); 31 | let header_content_lines = header_content 32 | .lines() 33 | .map(ToString::to_string) 34 | .collect::>(); 35 | let max_length = header_content_lines 36 | .iter() 37 | .map(|l| l.len()) 38 | .max() 39 | .unwrap_or(0); 40 | Self { 41 | header_content, 42 | header_content_one_line, 43 | header_content_lines, 44 | max_length, 45 | } 46 | } 47 | 48 | pub fn build_for_definition(&self, def: &HeaderDef) -> String { 49 | let eol = "\n"; 50 | let mut result = String::new(); 51 | 52 | if !def.first_line.is_empty() { 53 | result.push_str(&def.first_line); 54 | if def.first_line != eol { 55 | result.push_str(eol); 56 | } 57 | } 58 | 59 | for line in &self.header_content_lines { 60 | let before = &def.before_each_line; 61 | let after = &def.after_each_line; 62 | let this_line = if def.pad_lines { 63 | let max_length = self.max_length; 64 | format!("{before}{line: usize { 83 | self.header_content_lines.len() 84 | } 85 | 86 | pub fn header_content_one_line(&self) -> &str { 87 | &self.header_content_one_line 88 | } 89 | } 90 | 91 | impl Display for HeaderMatcher { 92 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 93 | f.write_str(&self.header_content) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /fmt/src/header/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | pub mod matcher; 16 | pub mod model; 17 | pub mod parser; 18 | -------------------------------------------------------------------------------- /fmt/src/header/model.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::HashMap; 16 | 17 | use anyhow::Context; 18 | use regex::Regex; 19 | use serde::Deserialize; 20 | use serde::Serialize; 21 | 22 | use crate::default_true; 23 | 24 | #[derive(Debug, Clone)] 25 | pub struct HeaderDef { 26 | pub name: String, 27 | pub first_line: String, 28 | pub end_line: String, 29 | pub before_each_line: String, 30 | pub after_each_line: String, 31 | 32 | pub allow_blank_lines: bool, 33 | pub multiple_lines: bool, 34 | pub pad_lines: bool, 35 | 36 | pub skip_line_pattern: Option, 37 | pub first_line_detection_pattern: Regex, 38 | pub last_line_detection_pattern: Regex, 39 | } 40 | 41 | impl HeaderDef { 42 | /// Tells if the given content line must be skipped according to this header definition. The 43 | /// header is outputted after any skipped line if any pattern defined on this point or on the 44 | /// first line if not pattern defined. 45 | pub fn is_skip_line(&self, line: &str) -> bool { 46 | self.skip_line_pattern 47 | .as_ref() 48 | .is_some_and(|pattern| pattern.is_match(line)) 49 | } 50 | 51 | /// Tells if the given content line is the first line of a possible header of this definition 52 | /// kind. 53 | pub fn is_first_header_line(&self, line: &str) -> bool { 54 | self.first_line_detection_pattern.is_match(line) 55 | } 56 | 57 | /// Tells if the given content line is the last line of a possible header of this definition 58 | /// kind. 59 | pub fn is_last_header_line(&self, line: &str) -> bool { 60 | self.last_line_detection_pattern.is_match(line) 61 | } 62 | } 63 | 64 | pub fn default_headers() -> HashMap { 65 | let defaults = include_str!("defaults.toml"); 66 | deserialize_header_definitions(defaults.to_string()).unwrap() 67 | } 68 | 69 | pub fn deserialize_header_definitions(value: String) -> anyhow::Result> { 70 | let header_styles: HashMap = toml::from_str(&value).map_err(Box::new)?; 71 | 72 | let headers = header_styles 73 | .into_iter() 74 | .map(|(name, style)| { 75 | let name = name.to_lowercase(); 76 | 77 | assert!( 78 | !style.allow_blank_lines || style.multiple_lines, 79 | "Header style {name} is configured to allow blank lines, so it should be set as a multi-line header style" 80 | ); 81 | 82 | let def = HeaderDef { 83 | name: name.clone(), 84 | first_line: style.first_line, 85 | end_line: style.end_line, 86 | before_each_line: style.before_each_line, 87 | after_each_line: style.after_each_line, 88 | allow_blank_lines: style.allow_blank_lines, 89 | multiple_lines: style.multiple_lines, 90 | pad_lines: style.pad_lines, 91 | skip_line_pattern: style 92 | .skip_line_pattern 93 | .map(|pattern| Regex::new(&pattern).with_context( 94 | || format!("malformed regex: {pattern}") 95 | )).transpose()?, 96 | first_line_detection_pattern: style 97 | .first_line_detection_pattern 98 | .map(|pattern| Regex::new(&pattern).with_context( 99 | || format!("malformed regex: {pattern}") 100 | )).transpose()?.context("empty regex in header")?, 101 | last_line_detection_pattern: style 102 | .last_line_detection_pattern 103 | .map(|pattern| Regex::new(&pattern).with_context( 104 | || format!("malformed regex: {pattern}") 105 | )).transpose()?.context("empty regex in header")?, 106 | }; 107 | 108 | Ok((name, def)) 109 | }) 110 | .collect::>>()?; 111 | Ok(headers) 112 | } 113 | 114 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] 115 | #[serde(default, rename_all = "camelCase")] 116 | pub struct HeaderStyle { 117 | /// The first fixed line of this header. 118 | pub first_line: String, 119 | /// The last fixed line of this header. 120 | pub end_line: String, 121 | /// The characters to prepend before each license header lines. Default to empty. 122 | pub before_each_line: String, 123 | /// The characters to append after each license header lines. Default to empty. 124 | pub after_each_line: String, 125 | /// Only for multi-line comments: specify if blank lines are allowed. 126 | /// Default to false because most of the time, a header has some characters on each line. 127 | pub allow_blank_lines: bool, 128 | /// Specify whether this is a multi-line comment style or not. 129 | /// 130 | /// A multi-line comment style is equivalent to what we have in Java, where a first line and 131 | /// line will delimit a whole multi-line comment section. 132 | /// 133 | /// A style that is not multi-line is usually repeating in each line the characters before and 134 | /// after each line to delimit a one-line comment. 135 | #[serde(default = "default_true")] 136 | pub multiple_lines: bool, 137 | /// Only for non multi-line comments: specify if some spaces should be added after the header 138 | /// line and before the {@link #afterEachLine} characters so that all the lines are aligned. 139 | /// Default to false. 140 | pub pad_lines: bool, 141 | /// A regex to define a first line in a file that should be skipped and kept untouched, like 142 | /// the XML declaration at the top of XML documents. Default to none. 143 | pub skip_line_pattern: Option, 144 | /// The regex used to detect the start of a header section or line. 145 | pub first_line_detection_pattern: Option, 146 | /// The regex used to detect the end of a header section or line. 147 | pub last_line_detection_pattern: Option, 148 | } 149 | -------------------------------------------------------------------------------- /fmt/src/header/parser.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::fmt::Display; 16 | use std::fmt::Formatter; 17 | use std::fs::File; 18 | use std::io::BufRead; 19 | use std::io::BufReader; 20 | use std::path::Path; 21 | 22 | use crate::header::model::HeaderDef; 23 | 24 | #[derive(Debug)] 25 | pub struct HeaderParser { 26 | pub begin_pos: usize, 27 | /// Some if header exists; None if header does not exist. 28 | pub end_pos: Option, 29 | pub file_content: FileContent, 30 | } 31 | 32 | pub fn parse_header( 33 | mut file_content: FileContent, 34 | header_def: &HeaderDef, 35 | keywords: &[String], 36 | ) -> HeaderParser { 37 | let mut line = file_content.next_line(); 38 | 39 | // 1. find begin position 40 | let begin_pos = find_first_position(&mut line, &mut file_content, header_def); 41 | 42 | // 2. has header 43 | let existing_header = existing_header(&mut line, &mut file_content, header_def, keywords); 44 | 45 | // 3. find end position 46 | let end_pos = if existing_header { 47 | // we check if there is a header, if the next line is the blank line of the header 48 | let mut end = file_content.pos; 49 | line = file_content.next_line(); 50 | if begin_pos == 0 { 51 | while line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(false) { 52 | end = file_content.pos; 53 | line = file_content.next_line(); 54 | } 55 | } 56 | if header_def.end_line.ends_with('\n') 57 | && line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(false) 58 | { 59 | end = file_content.pos; 60 | } 61 | Some(end) 62 | } else { 63 | None 64 | }; 65 | 66 | HeaderParser { 67 | begin_pos, 68 | end_pos, 69 | file_content, 70 | } 71 | } 72 | 73 | fn find_first_position( 74 | line: &mut Option, 75 | file_content: &mut FileContent, 76 | header_def: &HeaderDef, 77 | ) -> usize { 78 | const UTF8_BOM: [u8; 3] = [0xEF, 0xBB, 0xBF]; 79 | 80 | let mut begin_pos = 0; 81 | 82 | if let Some(l) = line.as_ref() { 83 | // skip UTF-8 BOM if exists 84 | if l.as_bytes().starts_with(&UTF8_BOM) { 85 | log::debug!("Detected UTF-8 BOM for {}; skip", file_content); 86 | begin_pos = 3; 87 | file_content.reset_to(3); 88 | } 89 | } 90 | 91 | if header_def.skip_line_pattern.is_some() { 92 | // the format expect to find lines to be skipped 93 | while line 94 | .as_ref() 95 | .map(|l| !header_def.is_skip_line(l)) 96 | .unwrap_or(false) 97 | { 98 | begin_pos = file_content.pos; 99 | *line = file_content.next_line(); 100 | } 101 | 102 | // at least we have found the line to skip, or we are the end of the file 103 | // this time we are going to skip next lines if they match the skip pattern 104 | while line 105 | .as_ref() 106 | .map(|l| header_def.is_skip_line(l)) 107 | .unwrap_or(false) 108 | { 109 | begin_pos = file_content.pos; 110 | *line = file_content.next_line(); 111 | } 112 | 113 | // After skipping everything we are at the end of the file 114 | // Header has to be at the file beginning 115 | if line.is_none() { 116 | begin_pos = 0; 117 | file_content.reset(); 118 | *line = file_content.next_line(); 119 | 120 | // recheck for UTF-8 BOM 121 | if let Some(l) = line.as_ref() { 122 | if l.as_bytes().starts_with(&UTF8_BOM) { 123 | begin_pos = 3; 124 | file_content.reset_to(3); 125 | } 126 | } 127 | } 128 | } 129 | 130 | begin_pos 131 | } 132 | 133 | fn existing_header( 134 | line: &mut Option, 135 | file_content: &mut FileContent, 136 | header_def: &HeaderDef, 137 | keywords: &[String], 138 | ) -> bool { 139 | // skip blank lines 140 | while line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(false) { 141 | *line = file_content.next_line(); 142 | } 143 | 144 | // check if there is already a header 145 | let l = match line.as_ref() { 146 | Some(l) if header_def.is_first_header_line(l) => l, 147 | _ => return false, 148 | }; 149 | 150 | let mut got_header = false; 151 | let mut in_place_header = String::new(); 152 | in_place_header.push_str(&l.to_lowercase()); 153 | 154 | *line = file_content.next_line(); 155 | 156 | // skip blank lines before header text 157 | if header_def.allow_blank_lines { 158 | while line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(false) { 159 | *line = file_content.next_line(); 160 | } 161 | } 162 | 163 | // first header detected line & potential blank lines have been detected 164 | // following lines should be header lines 165 | if let Some(l) = line.as_ref() { 166 | let before = { 167 | let mut before = header_def.before_each_line.trim_end(); 168 | if before.is_empty() && !header_def.multiple_lines { 169 | before = header_def.before_each_line.as_str(); 170 | } 171 | before 172 | }; 173 | 174 | let found_end = { 175 | let mut found_end = false; 176 | if (header_def.multiple_lines && header_def.is_last_header_line(l)) 177 | || l.trim().is_empty() 178 | { 179 | in_place_header.push_str(&l.to_lowercase()); 180 | found_end = true; 181 | } else { 182 | loop { 183 | match line.as_ref() { 184 | Some(l) if l.starts_with(before) => { 185 | in_place_header.push_str(&l.to_lowercase()); 186 | if header_def.multiple_lines && header_def.is_last_header_line(l) { 187 | found_end = true; 188 | break; 189 | } 190 | } 191 | _ => break, 192 | } 193 | *line = file_content.next_line(); 194 | } 195 | 196 | if line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(true) { 197 | found_end = true; 198 | } 199 | } 200 | found_end 201 | }; 202 | 203 | // skip blank lines after header text 204 | if header_def.multiple_lines && header_def.allow_blank_lines && !found_end { 205 | loop { 206 | if !line.as_ref().map(|l| l.trim().is_empty()).unwrap_or(false) { 207 | break; 208 | } 209 | *line = file_content.next_line(); 210 | } 211 | file_content.rewind(); 212 | } else if !header_def.multiple_lines && !found_end { 213 | file_content.rewind(); 214 | } 215 | 216 | if !header_def.multiple_lines { 217 | // keep track of the position for headers where the end line is the same as the 218 | // before each line 219 | let pos = file_content.pos; 220 | // check if the line is the end line 221 | while line 222 | .as_ref() 223 | .map(|l| { 224 | !header_def.is_last_header_line(l) 225 | && (header_def.allow_blank_lines || !l.trim().is_empty()) 226 | && l.starts_with(before) 227 | }) 228 | .unwrap_or(false) 229 | { 230 | *line = file_content.next_line(); 231 | } 232 | if line.is_none() { 233 | file_content.reset_to(pos); 234 | } 235 | } else if line.is_some() { 236 | // we could end up there if we still have some lines, but not matching "before". 237 | // This can be the last line in a multi line header 238 | let pos = file_content.pos; 239 | *line = file_content.next_line(); 240 | if line 241 | .as_ref() 242 | .map(|l| !header_def.is_last_header_line(l)) 243 | .unwrap_or(true) 244 | { 245 | file_content.reset_to(pos); 246 | } 247 | } 248 | 249 | got_header = true; 250 | for keyword in keywords { 251 | if !in_place_header.contains(keyword) { 252 | got_header = false; 253 | break; 254 | } 255 | } 256 | } 257 | // else - we detected previously a one line comment block that matches the header 258 | // detection it is not a header it is a comment 259 | got_header 260 | } 261 | 262 | #[derive(Debug)] 263 | pub struct FileContent { 264 | pos: usize, 265 | old_pos: usize, 266 | content: String, 267 | filepath: String, 268 | } 269 | 270 | impl Display for FileContent { 271 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 272 | f.write_str(&self.filepath) 273 | } 274 | } 275 | 276 | impl FileContent { 277 | pub fn new(file: &Path) -> std::io::Result { 278 | Ok(Self { 279 | pos: 0, 280 | old_pos: 0, 281 | content: { 282 | let mut content = String::new(); 283 | let mut reader = File::open(file).map(BufReader::new)?; 284 | let mut buf = String::new(); 285 | let mut n = reader.read_line(&mut buf)?; 286 | while n > 0 { 287 | if buf.ends_with('\n') { 288 | buf.pop(); 289 | if buf.ends_with('\r') { 290 | buf.pop(); 291 | } 292 | content.push_str(&buf); 293 | content.push('\n'); 294 | } else { 295 | content.push_str(&buf); 296 | } 297 | buf.clear(); 298 | n = reader.read_line(&mut buf)?; 299 | } 300 | content 301 | }, 302 | filepath: file.to_string_lossy().to_string(), 303 | }) 304 | } 305 | 306 | pub fn reset_to(&mut self, pos: usize) { 307 | self.old_pos = pos; 308 | self.pos = pos; 309 | } 310 | 311 | pub fn reset(&mut self) { 312 | self.reset_to(0); 313 | } 314 | 315 | pub fn rewind(&mut self) { 316 | self.pos = self.old_pos; 317 | } 318 | 319 | pub fn end_reached(&self) -> bool { 320 | self.pos >= self.content.len() 321 | } 322 | 323 | pub fn next_line(&mut self) -> Option { 324 | if self.end_reached() { 325 | return None; 326 | } 327 | 328 | let lf = self.content[self.pos..].find('\n').map(|i| i + self.pos); 329 | let eol = lf.unwrap_or(self.content.len()); 330 | let result = self.content[self.pos..eol].to_string(); 331 | 332 | self.old_pos = self.pos; 333 | self.pos = if let Some(lf) = lf { 334 | lf + 1 335 | } else { 336 | self.content.len() 337 | }; 338 | 339 | Some(result) 340 | } 341 | 342 | pub fn content(&self) -> String { 343 | self.content.clone() 344 | } 345 | 346 | pub fn insert(&mut self, index: usize, s: &str) { 347 | self.content.insert_str(index, s); 348 | } 349 | 350 | pub fn delete(&mut self, start: usize, end: usize) { 351 | self.content.drain(start..end); 352 | } 353 | } 354 | -------------------------------------------------------------------------------- /fmt/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | pub mod config; 16 | pub mod document; 17 | pub mod git; 18 | pub mod header; 19 | pub mod license; 20 | pub mod processor; 21 | pub mod selection; 22 | 23 | const fn default_true() -> bool { 24 | true 25 | } 26 | -------------------------------------------------------------------------------- /fmt/src/license/Apache-2.0-ASF.txt: -------------------------------------------------------------------------------- 1 | Licensed to the Apache Software Foundation (ASF) under one 2 | or more contributor license agreements. See the NOTICE file 3 | distributed with this work for additional information 4 | regarding copyright ownership. The ASF licenses this file 5 | to you under the Apache License, Version 2.0 (the 6 | "License"); you may not use this file except in compliance 7 | with the License. You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, 12 | software distributed under the License is distributed on an 13 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | KIND, either express or implied. See the License for the 15 | specific language governing permissions and limitations 16 | under the License. -------------------------------------------------------------------------------- /fmt/src/license/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Copyright {{props["inceptionYear"]}} {{props["copyrightOwner"]}} 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /fmt/src/license/Elastic-2.0.txt: -------------------------------------------------------------------------------- 1 | Copyright {{props["inceptionYear"]}} {{props["copyrightOwner"]}} 2 | 3 | Licensed under the Elastic License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | https://www.elastic.co/licensing/elastic-license 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /fmt/src/license/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use anyhow::Context; 16 | 17 | use crate::config::Config; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct HeaderSource { 21 | pub content: String, 22 | } 23 | 24 | impl HeaderSource { 25 | pub fn from_config(config: &Config) -> anyhow::Result { 26 | // 1. inline_header takes priority. 27 | if let Some(content) = config.inline_header.as_ref().cloned() { 28 | return Ok(HeaderSource { content }); 29 | } 30 | 31 | // 2. Then, header_path tries to load from base_dir. 32 | let header_path = config 33 | .header_path 34 | .as_ref() 35 | .context("no header source found (both inline_header and header_path are None)")?; 36 | let path = { 37 | let mut path = config.base_dir.clone(); 38 | path.push(header_path); 39 | path 40 | }; 41 | if let Ok(content) = std::fs::read_to_string(path) { 42 | return Ok(HeaderSource { content }); 43 | } 44 | 45 | // 3. Finally, fallback to try bundled headers. 46 | bundled_headers(header_path).with_context(|| { 47 | format!("no header source found (header_path is invalid: {header_path})") 48 | }) 49 | } 50 | } 51 | 52 | macro_rules! match_bundled_headers { 53 | ($name:expr, $($file:expr),*) => { 54 | match $name { 55 | $( 56 | $file => Some(HeaderSource { content: include_str!($file).to_string() }), 57 | )* 58 | _ => None, 59 | } 60 | } 61 | } 62 | 63 | fn bundled_headers(name: &str) -> Option { 64 | match_bundled_headers!( 65 | name, 66 | "Apache-2.0.txt", 67 | "Apache-2.0-ASF.txt", 68 | "Elastic-2.0.txt" 69 | ) 70 | } 71 | -------------------------------------------------------------------------------- /fmt/src/processor.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::hash_map::Entry; 16 | use std::collections::HashMap; 17 | use std::fs; 18 | use std::path::Path; 19 | use std::path::PathBuf; 20 | 21 | use anyhow::Context; 22 | 23 | use crate::config::Config; 24 | use crate::document::factory::DocumentFactory; 25 | use crate::document::model::default_mapping; 26 | use crate::document::Document; 27 | use crate::git; 28 | use crate::header::matcher::HeaderMatcher; 29 | use crate::header::model::default_headers; 30 | use crate::header::model::deserialize_header_definitions; 31 | use crate::license::HeaderSource; 32 | use crate::selection::Selection; 33 | 34 | /// Callback for processing the result of checking license headers. 35 | pub trait Callback { 36 | /// Called when the header is unknown. 37 | fn on_unknown(&mut self, path: &Path); 38 | 39 | /// Called when the header is matched. 40 | fn on_matched(&mut self, header: &HeaderMatcher, document: Document) -> anyhow::Result<()>; 41 | 42 | /// Called when the header is not matched. 43 | fn on_not_matched(&mut self, header: &HeaderMatcher, document: Document) -> anyhow::Result<()>; 44 | } 45 | 46 | #[allow(clippy::type_complexity)] 47 | pub fn check_license_header( 48 | run_config: PathBuf, 49 | callback: &mut C, 50 | ) -> anyhow::Result<()> { 51 | let config = { 52 | let name = run_config.display().to_string(); 53 | let config = fs::read_to_string(&run_config) 54 | .with_context(|| format!("cannot load config: {name}"))?; 55 | toml::from_str::(&config) 56 | .map_err(Box::new) 57 | .with_context(|| format!("cannot parse config file: {name}"))? 58 | }; 59 | 60 | let basedir = config.base_dir.clone(); 61 | anyhow::ensure!( 62 | basedir.is_dir(), 63 | format!( 64 | "{} does not exist or is not a directory.", 65 | basedir.display() 66 | ) 67 | ); 68 | 69 | let git_context = git::discover(&basedir, config.git)?; 70 | 71 | let selected_files = { 72 | let selection = Selection::new( 73 | basedir, 74 | config.header_path.as_ref(), 75 | &config.includes, 76 | &config.excludes, 77 | config.use_default_excludes, 78 | git_context.clone(), 79 | ); 80 | selection.select()? 81 | }; 82 | 83 | let mapping = { 84 | let mut mapping = config.mapping.clone(); 85 | if config.use_default_mapping { 86 | let default_mapping = default_mapping(); 87 | for m in default_mapping { 88 | if let Some(o) = mapping.get(&m) { 89 | log::warn!("default mapping {m:?} is override by {o:?}"); 90 | continue; 91 | } 92 | mapping.insert(m); 93 | } 94 | } 95 | mapping 96 | }; 97 | 98 | let definitions = { 99 | let mut defs = HashMap::new(); 100 | for (k, v) in default_headers() { 101 | match defs.entry(k) { 102 | Entry::Occupied(mut ent) => { 103 | log::warn!("Default header {} is override", ent.key()); 104 | ent.insert(v); 105 | } 106 | Entry::Vacant(ent) => { 107 | ent.insert(v); 108 | } 109 | } 110 | } 111 | for additional_header in &config.additional_headers { 112 | let additional_defs = fs::read_to_string(additional_header) 113 | .with_context(|| format!("cannot load header definitions: {additional_header}")) 114 | .and_then(deserialize_header_definitions)?; 115 | for (k, v) in additional_defs { 116 | match defs.entry(k) { 117 | Entry::Occupied(mut ent) => { 118 | log::warn!("Additional header {} is override", ent.key()); 119 | ent.insert(v); 120 | } 121 | Entry::Vacant(ent) => { 122 | ent.insert(v); 123 | } 124 | } 125 | } 126 | } 127 | defs 128 | }; 129 | 130 | let header_matcher = { 131 | let header_source = HeaderSource::from_config(&config)?; 132 | HeaderMatcher::new(header_source.content) 133 | }; 134 | 135 | let git_file_attrs = git::resolve_file_attrs(git_context)?; 136 | 137 | let document_factory = DocumentFactory::new( 138 | mapping, 139 | definitions, 140 | config.properties, 141 | config.keywords, 142 | git_file_attrs, 143 | ); 144 | 145 | for file in selected_files { 146 | let document = match document_factory.create_document(&file)? { 147 | Some(document) => document, 148 | None => { 149 | callback.on_unknown(&file); 150 | continue; 151 | } 152 | }; 153 | 154 | if document.is_unsupported() { 155 | callback.on_unknown(&file); 156 | } else if document 157 | .header_matched(&header_matcher, config.strict_check) 158 | .context("failed to match header")? 159 | { 160 | callback.on_matched(&header_matcher, document)?; 161 | } else { 162 | callback.on_not_matched(&header_matcher, document)?; 163 | } 164 | } 165 | 166 | Ok(()) 167 | } 168 | -------------------------------------------------------------------------------- /fmt/src/selection.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::path::Path; 16 | use std::path::PathBuf; 17 | 18 | use anyhow::Context; 19 | use ignore::overrides::OverrideBuilder; 20 | use walkdir::WalkDir; 21 | 22 | use crate::git::GitContext; 23 | 24 | pub struct Selection { 25 | basedir: PathBuf, 26 | includes: Vec, 27 | excludes: Vec, 28 | git_context: GitContext, 29 | } 30 | 31 | impl Selection { 32 | pub fn new( 33 | basedir: PathBuf, 34 | header_path: Option<&String>, 35 | includes: &[String], 36 | excludes: &[String], 37 | use_default_excludes: bool, 38 | git_context: GitContext, 39 | ) -> Selection { 40 | let includes = if includes.is_empty() { 41 | INCLUDES.iter().map(|s| s.to_string()).collect() 42 | } else { 43 | includes.to_vec() 44 | }; 45 | 46 | let input_excludes = excludes; 47 | let mut excludes = vec![]; 48 | if let Some(path) = header_path.cloned() { 49 | excludes.push(path); 50 | } 51 | if use_default_excludes { 52 | excludes.extend(EXCLUDES.iter().map(ToString::to_string)); 53 | } 54 | excludes.extend(input_excludes.to_vec()); 55 | 56 | Selection { 57 | basedir, 58 | includes, 59 | excludes, 60 | git_context, 61 | } 62 | } 63 | 64 | pub fn select(self) -> anyhow::Result> { 65 | log::debug!( 66 | "selecting files with baseDir: {}, included: {:?}, excluded: {:?}", 67 | self.basedir.display(), 68 | self.includes, 69 | self.excludes, 70 | ); 71 | 72 | let (excludes, reverse_excludes) = { 73 | let mut excludes = self.excludes; 74 | let mut reverse_excludes = vec![]; 75 | // TODO(tisonkun): can be simplified and no clone when extract_if stable 76 | excludes.retain_mut(|pat| { 77 | if pat.starts_with('!') { 78 | pat.remove(0); 79 | reverse_excludes.push(pat.clone()); 80 | false 81 | } else { 82 | true 83 | } 84 | }); 85 | (excludes, reverse_excludes) 86 | }; 87 | 88 | let includes = self.includes; 89 | anyhow::ensure!( 90 | includes.iter().all(|pat| !pat.starts_with('!')), 91 | "select files failed; reverse pattern is not allowed for includes: {includes:?}" 92 | ); 93 | 94 | let ignore = self.git_context.config.ignore.is_auto(); 95 | let result = match self.git_context.repo { 96 | None => select_files_with_ignore( 97 | &self.basedir, 98 | &includes, 99 | &excludes, 100 | &reverse_excludes, 101 | ignore, 102 | )?, 103 | Some(repo) => { 104 | select_files_with_git(&self.basedir, &includes, &excludes, &reverse_excludes, repo)? 105 | } 106 | }; 107 | 108 | log::debug!("selected files: {:?} (count: {})", result, result.len()); 109 | Ok(result) 110 | } 111 | } 112 | 113 | fn select_files_with_ignore( 114 | basedir: &PathBuf, 115 | includes: &[String], 116 | excludes: &[String], 117 | reverse_excludes: &[String], 118 | turn_on_git_ignore: bool, 119 | ) -> anyhow::Result> { 120 | log::debug!(turn_on_git_ignore; "Selecting files with ignore crate"); 121 | let mut result = vec![]; 122 | 123 | let walker = ignore::WalkBuilder::new(basedir) 124 | .ignore(false) // do not use .ignore file 125 | .hidden(false) // check hidden files 126 | .follow_links(true) // proper path name 127 | .parents(turn_on_git_ignore) 128 | .git_exclude(turn_on_git_ignore) 129 | .git_global(turn_on_git_ignore) 130 | .git_ignore(turn_on_git_ignore) 131 | .overrides({ 132 | let mut builder = OverrideBuilder::new(basedir); 133 | for pat in includes.iter() { 134 | builder.add(pat)?; 135 | } 136 | for pat in excludes.iter() { 137 | let pat = format!("!{pat}"); 138 | builder.add(pat.as_str())?; 139 | } 140 | for pat in reverse_excludes.iter() { 141 | builder.add(pat)?; 142 | } 143 | builder.build()? 144 | }) 145 | .build(); 146 | 147 | for mat in walker { 148 | let mat = mat?; 149 | if mat.file_type().map(|ft| ft.is_file()).unwrap_or(false) { 150 | result.push(mat.into_path()) 151 | } 152 | } 153 | 154 | Ok(result) 155 | } 156 | 157 | fn select_files_with_git( 158 | basedir: &Path, 159 | includes: &[String], 160 | excludes: &[String], 161 | reverse_excludes: &[String], 162 | repo: gix::Repository, 163 | ) -> anyhow::Result> { 164 | log::debug!("selecting files with git helper"); 165 | let mut result = vec![]; 166 | 167 | let matcher = { 168 | let mut builder = OverrideBuilder::new(basedir); 169 | for pat in includes.iter() { 170 | builder.add(pat)?; 171 | } 172 | for pat in excludes.iter() { 173 | let pat = format!("!{pat}"); 174 | builder.add(pat.as_str())?; 175 | } 176 | for pat in reverse_excludes.iter() { 177 | builder.add(pat)?; 178 | } 179 | builder.build()? 180 | }; 181 | 182 | let basedir = basedir 183 | .canonicalize() 184 | .with_context(|| format!("cannot resolve absolute path: {}", basedir.display()))?; 185 | let mut it = WalkDir::new(basedir.clone()) 186 | .follow_links(false) 187 | .into_iter(); 188 | 189 | let workdir = repo.workdir().expect("workdir cannot be absent"); 190 | let workdir = workdir 191 | .canonicalize() 192 | .with_context(|| format!("cannot resolve absolute path: {}", basedir.display()))?; 193 | let worktree = repo.worktree().expect("worktree cannot be absent"); 194 | let mut excludes = worktree 195 | .excludes(None) 196 | .map_err(Box::new) 197 | .context("cannot create gix exclude stack")?; 198 | 199 | while let Some(entry) = it.next() { 200 | let entry = entry.context("cannot traverse directory")?; 201 | let path = entry.path(); 202 | let file_type = entry.file_type(); 203 | if !file_type.is_file() && !file_type.is_dir() { 204 | log::debug!(file_type:?; "skip file: {path:?}"); 205 | continue; 206 | } 207 | 208 | let rela_path = path 209 | .strip_prefix(&workdir) 210 | .expect("git repository encloses iteration"); 211 | let mode = Some(if file_type.is_dir() { 212 | gix::index::entry::Mode::DIR 213 | } else { 214 | gix::index::entry::Mode::FILE 215 | }); 216 | let platform = excludes 217 | .at_path(rela_path, mode) 218 | .context("cannot check gix exclude")?; 219 | 220 | if file_type.is_dir() { 221 | if platform.is_excluded() { 222 | log::debug!(path:?, rela_path:?; "skip git ignored directory"); 223 | it.skip_current_dir(); 224 | continue; 225 | } 226 | if matcher.matched(rela_path, file_type.is_dir()).is_ignore() { 227 | log::debug!(path:?, rela_path:?; "skip glob ignored directory"); 228 | it.skip_current_dir(); 229 | continue; 230 | } 231 | } else if file_type.is_file() { 232 | if platform.is_excluded() { 233 | log::debug!(path:?, rela_path:?; "skip git ignored file"); 234 | continue; 235 | } 236 | if !matcher 237 | .matched(rela_path, file_type.is_dir()) 238 | .is_whitelist() 239 | { 240 | log::debug!(path:?, rela_path:?; "skip glob ignored file"); 241 | continue; 242 | } 243 | result.push(path.to_path_buf()); 244 | } 245 | } 246 | 247 | Ok(result) 248 | } 249 | 250 | pub const INCLUDES: [&str; 1] = ["**"]; 251 | pub const EXCLUDES: [&str; 140] = [ 252 | // Miscellaneous typical temporary files 253 | "**/*~", 254 | "**/#*#", 255 | "**/.#*", 256 | "**/%*%", 257 | "**/._*", 258 | "**/.repository/**", 259 | "**/*.lck", 260 | // CVS 261 | "**/CVS", 262 | "**/CVS/**", 263 | "**/.cvsignore", 264 | // RCS 265 | "**/RCS", 266 | "**/RCS/**", 267 | // SCCS 268 | "**/SCCS", 269 | "**/SCCS/**", 270 | // Visual SourceSafe 271 | "**/vssver.scc", 272 | // Subversion 273 | "**/.svn", 274 | "**/.svn/**", 275 | // Arch 276 | "**/.arch-ids", 277 | "**/.arch-ids/**", 278 | // Bazaar 279 | "**/.bzr", 280 | "**/.bzr/**", 281 | // SurroundSCM 282 | "**/.MySCMServerInfo", 283 | // Mac 284 | "**/.DS_Store", 285 | // Docker 286 | ".dockerignore", 287 | // Serena Dimensions Version 10 288 | "**/.metadata", 289 | "**/.metadata/**", 290 | // Mercurial 291 | "**/.hg", 292 | "**/.hg/**", 293 | "**/.hgignore", 294 | // git 295 | "**/.git", 296 | "**/.git/**", 297 | "**/.gitattributes", 298 | "**/.gitignore", 299 | "**/.gitkeep", 300 | "**/.gitmodules", 301 | // BitKeeper 302 | "**/BitKeeper", 303 | "**/BitKeeper/**", 304 | "**/ChangeSet", 305 | "**/ChangeSet/**", 306 | // darcs 307 | "**/_darcs", 308 | "**/_darcs/**", 309 | "**/.darcsrepo", 310 | "**/.darcsrepo/**", 311 | "**/-darcs-backup*", 312 | "**/.darcs-temp-mail", 313 | // maven project's temporary files 314 | "**/target/**", 315 | "**/test-output/**", 316 | "**/release.properties", 317 | "**/dependency-reduced-pom.xml", 318 | "**/release-pom.xml", 319 | "**/pom.xml.releaseBackup", 320 | "**/pom.xml.versionsBackup", 321 | // Node 322 | "**/node/**", 323 | "**/node_modules/**", 324 | // Yarn 325 | "**/.yarn/**", 326 | "**/yarn.lock", 327 | // pnpm 328 | "pnpm-lock.yaml", 329 | // Golang 330 | "**/go.sum", 331 | // Cargo 332 | "**/Cargo.lock", 333 | // code coverage tools 334 | "**/cobertura.ser", 335 | "**/.clover/**", 336 | "**/jacoco.exec", 337 | // eclipse project files 338 | "**/.classpath", 339 | "**/.project", 340 | "**/.settings/**", 341 | // IDEA projet files 342 | "**/*.iml", 343 | "**/*.ipr", 344 | "**/*.iws", 345 | "**/.idea/**", 346 | // Netbeans 347 | "**/nb-configuration.xml", 348 | // Hibernate Validator Annotation Processor 349 | "**/.factorypath", 350 | // descriptors 351 | "**/MANIFEST.MF", 352 | // License files 353 | "**/LICENSE", 354 | "**/LICENSE_HEADER", 355 | // binary files - images 356 | "**/*.jpg", 357 | "**/*.png", 358 | "**/*.gif", 359 | "**/*.ico", 360 | "**/*.bmp", 361 | "**/*.tiff", 362 | "**/*.tif", 363 | "**/*.cr2", 364 | "**/*.xcf", 365 | // binary files - programs 366 | "**/*.class", 367 | "**/*.exe", 368 | "**/*.dll", 369 | "**/*.so", 370 | // checksum files 371 | "**/*.md5", 372 | "**/*.sha1", 373 | "**/*.sha256", 374 | "**/*.sha512", 375 | // Security files 376 | "**/*.asc", 377 | "**/*.jks", 378 | "**/*.keytab", 379 | "**/*.lic", 380 | "**/*.p12", 381 | "**/*.pub", 382 | // binary files - archives 383 | "**/*.jar", 384 | "**/*.zip", 385 | "**/*.rar", 386 | "**/*.tar", 387 | "**/*.tar.gz", 388 | "**/*.tar.bz2", 389 | "**/*.gz", 390 | "**/*.7z", 391 | // ServiceLoader files 392 | "**/META-INF/services/**", 393 | // Markdown files 394 | "**/*.md", 395 | // Office documents 396 | "**/*.xls", 397 | "**/*.doc", 398 | "**/*.odt", 399 | "**/*.ods", 400 | "**/*.pdf", 401 | // Travis 402 | "**/.travis.yml", 403 | // AppVeyor 404 | "**/.appveyor.yml", 405 | "**/appveyor.yml", 406 | // CircleCI 407 | "**/.circleci", 408 | "**/.circleci/**", 409 | // SourceHut 410 | "**/.build.yml", 411 | // Maven 3.3+ configs 412 | "**/jvm.config", 413 | "**/maven.config", 414 | // Wrappers 415 | "**/gradlew", 416 | "**/gradlew.bat", 417 | "**/gradle-wrapper.properties", 418 | "**/mvnw", 419 | "**/mvnw.cmd", 420 | "**/maven-wrapper.properties", 421 | "**/MavenWrapperDownloader.java", 422 | // flash 423 | "**/*.swf", 424 | // json files 425 | "**/*.json", 426 | // fonts 427 | "**/*.svg", 428 | "**/*.eot", 429 | "**/*.otf", 430 | "**/*.ttf", 431 | "**/*.woff", 432 | "**/*.woff2", 433 | // logs 434 | "**/*.log", 435 | // office documents 436 | "**/*.xlsx", 437 | "**/*.docx", 438 | "**/*.ppt", 439 | "**/*.pptx", 440 | ]; 441 | -------------------------------------------------------------------------------- /fmt/tests/content/empty.py: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | -------------------------------------------------------------------------------- /fmt/tests/content/two_headers.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Greptime Team 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This file also contains some code from prometheus project. 16 | // Copyright 2015 The Prometheus Authors 17 | // Licensed under the Apache License, Version 2.0 (the "License"); 18 | // you may not use this file except in compliance with the License. 19 | // You may obtain a copy of the License at 20 | // 21 | // http://www.apache.org/licenses/LICENSE-2.0 22 | // 23 | // Unless required by applicable law or agreed to in writing, software 24 | // distributed under the License is distributed on an "AS IS" BASIS, 25 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 26 | // See the License for the specific language governing permissions and 27 | // limitations under the License. 28 | 29 | //! Implementations of `rate`, `increase` and `delta` functions in PromQL. 30 | 31 | use std::fmt::Display; 32 | use std::sync::Arc; 33 | -------------------------------------------------------------------------------- /fmt/tests/tests.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2024 tison 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::path::Path; 16 | 17 | use hawkeye_fmt::header::model::default_headers; 18 | use hawkeye_fmt::header::parser::parse_header; 19 | use hawkeye_fmt::header::parser::FileContent; 20 | 21 | #[test] 22 | fn test_remove_file_only_header() { 23 | let file = Path::new("tests/content/empty.py"); 24 | let defs = default_headers(); 25 | let def = defs.get("script_style").unwrap().clone(); 26 | let keywords = vec!["copyright".to_string()]; 27 | 28 | let file_content = FileContent::new(file).unwrap(); 29 | let document = parse_header(file_content, &def, &keywords); 30 | let end_pos = document.end_pos.unwrap(); 31 | let content = document.file_content.content(); 32 | assert!(content[end_pos..].trim().is_empty()); 33 | } 34 | 35 | #[test] 36 | fn test_two_headers_should_only_remove_the_first() { 37 | let file = Path::new("tests/content/two_headers.rs"); 38 | let defs = default_headers(); 39 | let def = defs.get("doubleslash_style").unwrap().clone(); 40 | let keywords = vec!["copyright".to_string()]; 41 | 42 | let file_content = FileContent::new(file).unwrap(); 43 | let document = parse_header(file_content, &def, &keywords); 44 | let end_pos = document.end_pos.unwrap(); 45 | let content = document.file_content.content(); 46 | assert!(content[end_pos..].contains("Copyright 2015 The Prometheus Authors")); 47 | } 48 | -------------------------------------------------------------------------------- /licenserc.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | headerPath = "Apache-2.0.txt" 16 | 17 | excludes = [ 18 | # Plain text files AS IS 19 | "*.txt", 20 | 21 | # Test files 22 | "fmt/tests/content/**", 23 | "tests/**", 24 | "!tests/it.py", 25 | 26 | # Generated files 27 | ".github/workflows/release.yml", 28 | ] 29 | 30 | [git] 31 | attrs = 'auto' 32 | ignore = 'auto' 33 | 34 | [properties] 35 | inceptionYear = 2024 36 | copyrightOwner = "tison " 37 | projectName = "HawkEye" 38 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [build-system] 16 | requires = ["maturin>=1.0,<2.0"] 17 | build-backend = "maturin" 18 | 19 | [tool.maturin] 20 | bindings = "bin" 21 | manifest-path = "cli/Cargo.toml" 22 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [toolchain] 16 | channel = "stable" 17 | components = ["cargo", "rustfmt", "clippy", "rust-analyzer"] 18 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 tison 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | imports_granularity = "Item" 16 | group_imports = "StdExternalCrate" 17 | comment_width = 120 18 | wrap_comments = true 19 | format_code_in_doc_comments = true 20 | -------------------------------------------------------------------------------- /tests/.gitignore: -------------------------------------------------------------------------------- 1 | *.formatted 2 | -------------------------------------------------------------------------------- /tests/attrs_and_props/license.txt: -------------------------------------------------------------------------------- 1 | props["inceptionYear"]={{props["inceptionYear"]}} 2 | props["copyrightOwner"]={{props["copyrightOwner"]}} 3 | 4 | attrs.filename={{attrs.filename}} 5 | attrs.git_file_created_year={{attrs.git_file_created_year}} 6 | attrs.git_file_modified_year={{attrs.git_file_modified_year}} 7 | -------------------------------------------------------------------------------- /tests/attrs_and_props/licenserc.toml: -------------------------------------------------------------------------------- 1 | baseDir = "." 2 | headerPath = "license.txt" 3 | 4 | excludes = ["licenserc.toml", "*.expected"] 5 | 6 | [git] 7 | ignore = 'auto' 8 | attrs = 'enable' 9 | 10 | [properties] 11 | inceptionYear = 2024 12 | copyrightOwner = "Mike Delaney " 13 | -------------------------------------------------------------------------------- /tests/attrs_and_props/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /tests/attrs_and_props/main.rs.expected: -------------------------------------------------------------------------------- 1 | // props["inceptionYear"]=2024 2 | // props["copyrightOwner"]=Mike Delaney 3 | // 4 | // attrs.filename=main.rs 5 | // attrs.git_file_created_year=2025 6 | // attrs.git_file_modified_year=2025 7 | 8 | fn main() { 9 | println!("Hello, world!"); 10 | } 11 | -------------------------------------------------------------------------------- /tests/bom_issue/headless_bom.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Some.Fake.Namespace; 4 | 5 | public class SomeFakeClass 6 | { 7 | public void SomeFakeMethod() 8 | { 9 | Console.WriteLine("Hello, World!"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/bom_issue/headless_bom.cs.expected: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------- 2 | // Static Copyright 3 | // ------------------------------------------------------- 4 | 5 | using System; 6 | 7 | namespace Some.Fake.Namespace; 8 | 9 | public class SomeFakeClass 10 | { 11 | public void SomeFakeMethod() 12 | { 13 | Console.WriteLine("Hello, World!"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/bom_issue/license.txt: -------------------------------------------------------------------------------- 1 | Static Copyright -------------------------------------------------------------------------------- /tests/bom_issue/licenserc.toml: -------------------------------------------------------------------------------- 1 | baseDir = "." 2 | headerPath = "license.txt" 3 | 4 | excludes = ["*.toml", "*.expected"] 5 | 6 | additionalHeaders = ["style.toml"] 7 | 8 | [mapping.CS_TEST_STYLE] 9 | extensions = ["cs"] 10 | -------------------------------------------------------------------------------- /tests/bom_issue/style.toml: -------------------------------------------------------------------------------- 1 | [CS_TEST_STYLE] 2 | firstLine = "// -------------------------------------------------------" 3 | endLine = "// -------------------------------------------------------\n" 4 | skipLinePattern = "^#!.*$" 5 | allowBlankLines = false 6 | multipleLines = false 7 | beforeEachLine = "// " 8 | firstLineDetectionPattern = "//\\s+\\-+" 9 | lastLineDetectionPattern = "//\\s+\\-+" 10 | -------------------------------------------------------------------------------- /tests/disk_file_creation_year/license.txt: -------------------------------------------------------------------------------- 1 | Copyright {{attrs.git_file_created_year if attrs.git_file_created_year else attrs.disk_file_creation_year }} -------------------------------------------------------------------------------- /tests/disk_file_creation_year/licenserc.toml: -------------------------------------------------------------------------------- 1 | baseDir = "." 2 | headerPath = "license.txt" 3 | 4 | excludes = ["licenserc.toml", "*.expected"] 5 | -------------------------------------------------------------------------------- /tests/disk_file_creation_year/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /tests/disk_file_creation_year/main.rs.expected: -------------------------------------------------------------------------------- 1 | // Copyright 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /tests/it.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright 2024 tison 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from pathlib import Path 17 | import difflib 18 | import subprocess 19 | import os 20 | import shutil 21 | import datetime 22 | 23 | def diff_files(file1, file2): 24 | with file1.open("r", encoding="utf8") as f1, file2.open("r", encoding="utf8") as f2: 25 | diff = difflib.unified_diff(f1.readlines(), f2.readlines(), str(file1), str(file2)) 26 | diff = list(diff) 27 | if diff: 28 | for line in diff: 29 | print(line, end="") 30 | exit(1) 31 | 32 | 33 | basedir = Path(__file__).parent.absolute() 34 | rootdir = basedir.parent 35 | 36 | subprocess.run(["cargo", "build", "--bin", "hawkeye"], cwd=rootdir, check=True) 37 | hawkeye = rootdir / "target" / "debug" / "hawkeye" 38 | 39 | def drive(name, files, create_temp_copy=False): 40 | temp_paths = [] 41 | expected_files = [] 42 | case_dir = basedir / name 43 | try: 44 | if create_temp_copy: 45 | current_year = str(datetime.datetime.now().year) 46 | for filepath in files: 47 | base, ext = os.path.splitext(filepath) 48 | temp_path = f"{base}_temp{ext}" 49 | shutil.copy2(case_dir / filepath, case_dir / temp_path) 50 | temp_paths.append(temp_path) 51 | expected_temp_path = f"{base}_temp{ext}.expected" 52 | shutil.copy2(case_dir / f"{filepath}.expected", case_dir / expected_temp_path) 53 | expected_files.append(expected_temp_path) 54 | with (case_dir / expected_temp_path).open("r", encoding="utf8") as f: 55 | content = f.read() 56 | content = content.replace("", current_year) 57 | with (case_dir / expected_temp_path).open("w", encoding="utf8") as f: 58 | f.write(content) 59 | else: 60 | temp_paths = files 61 | expected_files = [f"{file}.expected" for file in files] 62 | subprocess.run([hawkeye, "format", "--fail-if-unknown", "--fail-if-updated=false", "--dry-run"], cwd=case_dir, check=True) 63 | 64 | for file in temp_paths: 65 | diff_files(case_dir / f"{file}.expected", case_dir / f"{file}.formatted") 66 | finally: 67 | # Remove all temp files at the end 68 | if create_temp_copy: 69 | for temp_path in temp_paths: 70 | if os.path.exists(case_dir / temp_path): 71 | os.remove(case_dir / temp_path) 72 | for expected_file in expected_files: 73 | if os.path.exists(case_dir / expected_file): 74 | os.remove(case_dir / expected_file) 75 | 76 | drive("attrs_and_props", ["main.rs"]) 77 | drive("load_header_path", ["main.rs"]) 78 | drive("bom_issue", ["headless_bom.cs"]) 79 | drive("regression_blank_line", ["main.rs"]) 80 | drive("regression_no_blank_lines", ["repro.py"]) 81 | drive("disk_file_creation_year", ["main.rs"], True) 82 | -------------------------------------------------------------------------------- /tests/load_header_path/license.txt: -------------------------------------------------------------------------------- 1 | Copyright {{props["inceptionYear"]}} {{props["copyrightOwner"]}} 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 | -------------------------------------------------------------------------------- /tests/load_header_path/licenserc.toml: -------------------------------------------------------------------------------- 1 | baseDir = "." 2 | headerPath = "license.txt" 3 | 4 | excludes = ["licenserc.toml", "*.expected"] 5 | 6 | [properties] 7 | inceptionYear = 2024 8 | copyrightOwner = "Mike Delaney " 9 | -------------------------------------------------------------------------------- /tests/load_header_path/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /tests/load_header_path/main.rs.expected: -------------------------------------------------------------------------------- 1 | // Copyright 2024 Mike Delaney 2 | // 3 | // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | // 5 | // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | // 7 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | // 9 | // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | // 11 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 | 13 | fn main() { 14 | println!("Hello, world!"); 15 | } 16 | -------------------------------------------------------------------------------- /tests/regression_blank_line/licenserc.toml: -------------------------------------------------------------------------------- 1 | baseDir = "." 2 | headerPath = "Apache-2.0.txt" 3 | 4 | includes = ["*.rs"] 5 | excludes = ["*.expected"] 6 | 7 | [properties] 8 | inceptionYear = 2023 9 | copyrightOwner = "The CopyrightOwner" 10 | -------------------------------------------------------------------------------- /tests/regression_blank_line/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2023 The Authors. Licensed under Apache-2.0. 2 | 3 | //! Load balancer 4 | 5 | use macros::define_result; 6 | -------------------------------------------------------------------------------- /tests/regression_blank_line/main.rs.expected: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The CopyrightOwner 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Load balancer 16 | 17 | use macros::define_result; 18 | -------------------------------------------------------------------------------- /tests/regression_no_blank_lines/licenserc.toml: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022-2025, Example, All Rights Reserved. 2 | 3 | inlineHeader = "Copyright (c) 2022-2025, Example, All Rights Reserved." 4 | 5 | baseDir = "." 6 | includes = ["*.py"] 7 | excludes = ["*.expected"] 8 | -------------------------------------------------------------------------------- /tests/regression_no_blank_lines/repro.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022-2025, Example, All Rights Reserved. 2 | from __future__ import annotations 3 | 4 | if __name__ == "__main__": 5 | print() 6 | -------------------------------------------------------------------------------- /tests/regression_no_blank_lines/repro.py.expected: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022-2025, Example, All Rights Reserved. 2 | 3 | from __future__ import annotations 4 | 5 | if __name__ == "__main__": 6 | print() 7 | --------------------------------------------------------------------------------