Compare commits

...

1605 commits

Author SHA1 Message Date
anthony sottile
8416413a0e
Merge pull request #3599 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-12-22 16:55:46 -05:00
pre-commit-ci[bot]
37a879e65e
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v3.1.0 → v3.2.0](https://github.com/asottile/setup-cfg-fmt/compare/v3.1.0...v3.2.0)
2025-12-22 20:26:26 +00:00
Anthony Sottile
8a0630ca1a v4.5.1
Some checks failed
main / main-linux (push) Has been cancelled
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
2025-12-16 16:13:56 -05:00
anthony sottile
fcbc745744
Merge pull request #3597 from pre-commit/empty-setup-py
fix python local template when artifact dirs are present
2025-12-16 14:56:40 -06:00
Anthony Sottile
51592eecec fix python local template when artifact dirs are present 2025-12-16 15:45:01 -05:00
anthony sottile
67e8faf80b
Merge pull request #3596 from pre-commit/pre-commit-ci-update-config
Some checks are pending
languages / language (push) Blocked by required conditions
languages / collector (push) Blocked by required conditions
languages / vars (push) Waiting to run
main / main-windows (push) Waiting to run
main / main-linux (push) Waiting to run
[pre-commit.ci] pre-commit autoupdate
2025-12-15 16:04:01 -06:00
pre-commit-ci[bot]
c251e6b6d0
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.19.0 → v1.19.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.19.0...v1.19.1)
2025-12-15 20:48:45 +00:00
anthony sottile
98ccafa3ce
Merge pull request #3593 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-12-01 16:13:49 -05:00
pre-commit-ci[bot]
48953556d0
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.18.2 → v1.19.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.18.2...v1.19.0)
2025-12-01 21:05:15 +00:00
anthony sottile
2cedd58e69
Merge pull request #3588 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-11-25 10:52:12 -05:00
pre-commit-ci[bot]
465192d7de
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.21.1 → v3.21.2](https://github.com/asottile/pyupgrade/compare/v3.21.1...v3.21.2)
2025-11-24 20:53:38 +00:00
anthony sottile
fd42f96874
Merge pull request #3586 from pre-commit/zipapp-sha256-file-not-needed
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
remove sha256 file from zipapp script
2025-11-22 16:15:39 -05:00
anthony sottile
8ea2b790d8 remove sha256 file from zipapp script
github displays the checksum for us now!
2025-11-22 16:06:27 -05:00
anthony sottile
1af6c8fa95 v4.5.0 2025-11-22 16:02:16 -05:00
anthony sottile
3358a3b540
Merge pull request #3585 from pre-commit/hazmat
add pre-commit hazmat
2025-11-22 14:03:09 -05:00
anthony sottile
bdf68790b7 add pre-commit hazmat 2025-11-22 13:53:53 -05:00
anthony sottile
e436690f14
Merge pull request #3584 from pre-commit/exitstack
Some checks are pending
languages / vars (push) Waiting to run
languages / language (push) Blocked by required conditions
languages / collector (push) Blocked by required conditions
main / main-windows (push) Waiting to run
main / main-linux (push) Waiting to run
use ExitStack instead of start + stop
2025-11-21 15:19:53 -05:00
anthony sottile
8d34f95308 use ExitStack instead of start + stop 2025-11-21 15:09:41 -05:00
anthony sottile
9c7ea88ab9
Merge pull request #3583 from pre-commit/forward-compat-map-manifest
Some checks failed
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
languages / collector (push) Has been cancelled
add forward-compat error message
2025-11-19 15:10:28 -05:00
Anthony Sottile
844dacc168 add forward-compat error message 2025-11-19 14:57:01 -05:00
anthony sottile
6a1d543e52
Merge pull request #3582 from pre-commit/move-gc-back
move logic for gc back to commands.gc
2025-11-19 14:44:46 -05:00
Anthony Sottile
66278a9a0b move logic for gc back to commands.gc 2025-11-19 14:32:09 -05:00
anthony sottile
1b32c50bc7
Merge pull request #3579 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-11-10 16:53:56 -05:00
pre-commit-ci[bot]
063229aee7
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.21.0 → v3.21.1](https://github.com/asottile/pyupgrade/compare/v3.21.0...v3.21.1)
2025-11-10 20:59:54 +00:00
anthony sottile
49e28eea48
Merge pull request #3578 from pre-commit/store-gc-refactor
Some checks are pending
languages / vars (push) Waiting to run
languages / language (push) Blocked by required conditions
languages / collector (push) Blocked by required conditions
main / main-windows (push) Waiting to run
main / main-linux (push) Waiting to run
refactor gc into store
2025-11-09 17:16:27 -05:00
Anthony Sottile
d5c273a2ba refactor gc into store
this will make refactoring this easier later and limits the api surface of Store
2025-11-09 17:03:43 -05:00
anthony sottile
17cf886473 v4.4.0
Some checks are pending
languages / vars (push) Waiting to run
languages / language (push) Blocked by required conditions
languages / collector (push) Blocked by required conditions
main / main-windows (push) Waiting to run
main / main-linux (push) Waiting to run
2025-11-08 16:11:43 -05:00
anthony sottile
cb63a5cb9a
Merge pull request #3535 from br-rhrbacek/fix-cgroups
Fix docker-in-docker detection for cgroups v2
2025-11-08 15:45:53 -05:00
Radek Hrbacek
f80801d75a Fix docker-in-docker detection for cgroups v2 2025-11-08 15:37:32 -05:00
anthony sottile
9143fc3545
Merge pull request #3577 from pre-commit/language-unsupported
rename system and script languages to unsupported / unsupported_script
2025-11-08 15:21:50 -05:00
anthony sottile
725acc969a rename system and script languages to unsupported / unsupported_script 2025-11-08 15:09:16 -05:00
anthony sottile
3815e2e6d8
Merge pull request #3576 from pre-commit/fix-stages-config-error
fix missing context in error for stages
2025-11-08 14:44:32 -05:00
anthony sottile
aa2961c122 fix missing context in error for stages 2025-11-08 14:31:15 -05:00
anthony sottile
46297f7cd6
Merge pull request #3575 from pre-commit/rm-python3-hooks-repo
Some checks are pending
languages / vars (push) Waiting to run
languages / language (push) Blocked by required conditions
languages / collector (push) Blocked by required conditions
main / main-windows (push) Waiting to run
main / main-linux (push) Waiting to run
rm python3_hooks_repo
2025-11-08 13:45:42 -05:00
anthony sottile
95eec75004 rm python3_hooks_repo 2025-11-08 13:34:44 -05:00
anthony sottile
5e4b3546f3
Merge pull request #3574 from pre-commit/rm-hook-with-spaces-test
remove redundant system spaces test
2025-11-08 13:24:42 -05:00
anthony sottile
8bbfcf1f82 remove redundant system spaces test
`test_args_with_spaces_and_quotes` also covers this behaviour
2025-11-08 13:16:38 -05:00
anthony sottile
65175f3cf3
Merge pull request #3566 from pre-commit/upgrade-rbenv
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
upgrade rbenv / ruby-build
2025-10-24 12:34:53 -07:00
anthony sottile
fc33a62f3c upgrade rbenv / ruby-build 2025-10-24 15:18:07 -04:00
anthony sottile
2db924eb98
Merge pull request #3561 from pre-commit/warn-to-warning
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
fix deprecated call
2025-10-16 10:34:47 -04:00
Anthony Sottile
ddfcf4034b fix deprecated call 2025-10-16 10:23:30 -04:00
anthony sottile
1b424ccfa2
Merge pull request #3558 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-10-13 16:54:01 -04:00
pre-commit-ci[bot]
221637b0cb
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.8.0 → v3.1.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.8.0...v3.1.0)
- [github.com/asottile/reorder-python-imports: v3.15.0 → v3.16.0](https://github.com/asottile/reorder-python-imports/compare/v3.15.0...v3.16.0)
- [github.com/asottile/add-trailing-comma: v3.2.0 → v4.0.0](https://github.com/asottile/add-trailing-comma/compare/v3.2.0...v4.0.0)
- [github.com/asottile/pyupgrade: v3.20.0 → v3.21.0](https://github.com/asottile/pyupgrade/compare/v3.20.0...v3.21.0)
2025-10-13 20:38:45 +00:00
anthony sottile
7ad23528d0
Merge pull request #3554 from pre-commit/all-repos_autofix_all-repos-manual
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
py310+
2025-10-10 12:08:36 -04:00
anthony sottile
f415f6c4d7 py310+
Committed via https://github.com/asottile/all-repos
2025-10-09 17:44:05 -04:00
Anthony Sottile
99fa9ba5ef
Merge pull request #3544 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-09-23 09:36:35 -04:00
pre-commit-ci[bot]
ad0d4cd427
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.17.1 → v1.18.2](https://github.com/pre-commit/mirrors-mypy/compare/v1.17.1...v1.18.2)
2025-09-22 20:44:04 +00:00
Anthony Sottile
924680e974
Merge pull request #3537 from pre-commit/security-options-null
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
handle `SecurityOptions: null` in docker response
2025-09-06 14:47:53 -04:00
anthony sottile
2930ea0fcd handle SecurityOptions: null in docker response 2025-09-06 14:40:20 -04:00
Anthony Sottile
b96127c485
Merge pull request #3536 from pre-commit/store-true-default
store_true does not need default=...
2025-09-06 14:28:02 -04:00
Anthony Sottile
954cc3b3b3
Merge pull request #3528 from JulianMaurin/feat/fail-fast
Add fail-fast argument for run command
2025-09-06 14:22:57 -04:00
anthony sottile
e671830402 store_true does not need default=... 2025-09-06 14:20:01 -04:00
JulianMaurin
c78f248c60 Add fail-fast argument for run command 2025-09-06 14:14:23 -04:00
Anthony Sottile
e70b313c80
Merge pull request #3510 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-08-13 10:21:38 -04:00
pre-commit-ci[bot]
87a681f866
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v5.0.0 → v6.0.0](https://github.com/pre-commit/pre-commit-hooks/compare/v5.0.0...v6.0.0)
2025-08-11 20:46:13 +00:00
anthony sottile
b74a22d96c v4.3.0
Some checks failed
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / vars (push) Has been cancelled
languages / collector (push) Has been cancelled
languages / language (push) Has been cancelled
2025-08-09 14:54:49 -04:00
Anthony Sottile
cc899de192
Merge pull request #3507 from bc-lee/dart-fix
Make Dart pre-commit hook compatible with the latest Dart SDKs
2025-08-09 14:03:07 -04:00
Byoungchan Lee
2a0bcea757 Downgrade Dart SDK version installed in the CI 2025-08-08 17:40:30 +09:00
Byoungchan Lee
f1cc7a445f Make Dart pre-commit hook compatible with the latest Dart SDKs
Dart introduced sound null safety in version 2.12.0, and as of Dart 3,
null safety is mandatory. Older Dart SDKs allowed both pre-null safety
and null-safe packages, but modern Dart SDKs, where most source code is
null-safe, now reject pre-null safety packages.

The current `pubspec.yaml` template with `sdk: '>=2.10.0'` is
incompatible with recent Dart SDKs, leading to the following error:

An unexpected error has occurred: CalledProcessError: command: ('/path/to/dart-sdk/bin/dart', 'pub', 'get')
return code: 65
stdout:
    Resolving dependencies...
stderr:
    The lower bound of "sdk: '>=2.10.0'" must be 2.12.0'
    or higher to enable null safety.

    The current Dart SDK (3.8.3) only supports null safety.

    For details, see https://dart.dev/null-safety

To ensure compatibility with the modern Dart ecosystem, this commit
updates the minimum Dart SDK version to 2.12.0 or higher,
which implicitly supports null safety.
Additionally, `testing/get-dart.sh` has been updated to verify that
the pre-commit hook functions correctly with the latest Dart versions.
2025-08-08 17:14:59 +09:00
Anthony Sottile
72a3b71f0e
Merge pull request #3504 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-08-04 18:09:19 -04:00
pre-commit-ci[bot]
c8925a457a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.17.0 → v1.17.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.17.0...v1.17.1)
2025-08-04 20:31:31 +00:00
Anthony Sottile
a5fe6c500c
Merge pull request #3496 from ericphanson/eph/jl-startup
Some checks failed
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
Julia language: skip startup.jl file
2025-08-02 14:43:29 -04:00
Eric Hanson
6f1f433a9c Julia language: skip startup.jl file 2025-08-02 14:35:27 -04:00
Anthony Sottile
c6817210b1
Merge pull request #3499 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-07-24 11:21:39 +02:00
pre-commit-ci[bot]
4fd4537bc6
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.16.1 → v1.17.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.16.1...v1.17.0)
2025-07-21 20:02:20 +00:00
Anthony Sottile
a1d7bed86f
Merge pull request #3485 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-06-24 15:37:11 -04:00
pre-commit-ci[bot]
d1d5b3d564
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 7.2.0 → 7.3.0](https://github.com/PyCQA/flake8/compare/7.2.0...7.3.0)
- [github.com/pre-commit/mirrors-mypy: v1.16.0 → v1.16.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.16.0...v1.16.1)
2025-06-23 19:55:22 +00:00
Anthony Sottile
9c228a0bd8
Merge pull request #3477 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-06-02 17:29:56 -07:00
pre-commit-ci[bot]
d4f0c6e8a7
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.15.0 → v1.16.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.15.0...v1.16.0)
2025-06-02 19:57:10 +00:00
Anthony Sottile
5f0c773e74
Merge pull request #3470 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-05-27 21:36:14 -07:00
pre-commit-ci[bot]
43b426a501
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder-python-imports: v3.14.0 → v3.15.0](https://github.com/asottile/reorder-python-imports/compare/v3.14.0...v3.15.0)
- [github.com/asottile/add-trailing-comma: v3.1.0 → v3.2.0](https://github.com/asottile/add-trailing-comma/compare/v3.1.0...v3.2.0)
- [github.com/asottile/pyupgrade: v3.19.1 → v3.20.0](https://github.com/asottile/pyupgrade/compare/v3.19.1...v3.20.0)
2025-05-26 19:45:48 +00:00
Anthony Sottile
8a4af027a1
Merge pull request #3446 from matthewhughes934/fix-docker-rootless-permission-mounts
Some checks failed
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
Fix permission errors for mounts in rootless docker
2025-05-23 17:11:14 -04:00
Matthew Hughes
466f6c4a39 Fix permission errors for mounts in rootless docker
By running containers in a rootless docker context as root. This is
because user and group IDs are remapped in the user namespaces uses by
rootless docker, and it's unlikely that the current user ID will map to
the same ID under this remap (see docs[1] for some more details).
Specifically, it means ownership of mounted volumes will not be for the
current user and trying to write can result in permission errors.

This change borrows heavily from an existing PR[2].

The output format of `docker system info` I don't think is
documented/guaranteed anywhere, but it should corresponding to the
format of a `/info` API request to Docker[3]

The added test _hopes_ to avoid regressions in this behaviour, but since
tests aren't run in a rootless docker context on the PR checks (and I
couldn't find an easy way to make it the case) there's still a risk of
regressions sneaking in.

Link: https://docs.docker.com/engine/security/rootless/ [1]
Link: https://github.com/pre-commit/pre-commit/pull/1484/ [2]
Link: https://docs.docker.com/reference/api/engine/version/v1.48/#tag/System/operation/SystemAuth [3]
Co-authored-by: Kurt von Laven <Kurt-von-Laven@users.noreply.github.com>
Co-authored-by: Fabrice Flore-Thébault <ffloreth@redhat.com>
2025-05-23 17:01:10 -04:00
Anthony Sottile
d2b61d0ef2
Merge pull request #3439 from pre-commit/pre-commit-ci-update-config
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
[pre-commit.ci] pre-commit autoupdate
2025-03-31 15:55:15 -04:00
pre-commit-ci[bot]
43592c2a29 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2025-03-31 19:44:12 +00:00
pre-commit-ci[bot]
6d47b8d52b
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.7.0 → v2.8.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.7.0...v2.8.0)
- [github.com/PyCQA/flake8: 7.1.2 → 7.2.0](https://github.com/PyCQA/flake8/compare/7.1.2...7.2.0)
2025-03-31 19:43:51 +00:00
Anthony Sottile
aa48766b88 v4.2.0
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
2025-03-18 17:34:49 -04:00
Anthony Sottile
bf6f11dc6c
Merge pull request #3430 from pre-commit/preferential-sys-impl
adjust python default_language_version to prefer versioned exe
2025-03-18 17:26:41 -04:00
Anthony Sottile
3e8d0f5e1c adjust python default_language_version to prefer versioned exe 2025-03-18 14:55:24 -04:00
Anthony Sottile
ff7256cedf
Merge pull request #3425 from tusharsadhwani/ambiguous-ref
Some checks failed
languages / vars (push) Has been cancelled
languages / language (push) Has been cancelled
languages / collector (push) Has been cancelled
main / main-windows (push) Has been cancelled
main / main-linux (push) Has been cancelled
fix: crash on ambiguous ref 'HEAD'
2025-03-15 15:29:29 -04:00
Tushar Sadhwani
b7eb412c79 fix: crash on ambiguous ref 'HEAD' 2025-03-15 15:23:15 -04:00
Anthony Sottile
7b88c63ae6
Merge pull request #3404 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2025-02-17 16:20:33 -05:00
pre-commit-ci[bot]
94b97e28f7
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 7.1.1 → 7.1.2](https://github.com/PyCQA/flake8/compare/7.1.1...7.1.2)
2025-02-17 21:07:26 +00:00
Anthony Sottile
2f93b80484
Merge pull request #3401 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2025-02-12 09:34:15 -05:00
pre-commit-ci[bot]
4f90a1e88a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.14.1 → v1.15.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.14.1...v1.15.0)
2025-02-10 22:44:01 +00:00
Anthony Sottile
aba1ce04e7
Merge pull request #3396 from pre-commit/all-repos_autofix_all-repos-sed
upgrade asottile/workflows
2025-01-30 15:05:49 -05:00
Anthony Sottile
e2210c97e2 upgrade asottile/workflows
Committed via https://github.com/asottile/all-repos
2025-01-30 14:58:50 -05:00
Anthony Sottile
804c853d8f
Merge pull request #3390 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2025-01-20 20:43:00 -05:00
pre-commit-ci[bot]
edd0002e43
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/hhatto/autopep8: v2.3.1 → v2.3.2](https://github.com/hhatto/autopep8/compare/v2.3.1...v2.3.2)
2025-01-20 22:30:07 +00:00
Anthony Sottile
b152e922ef v4.1.0 2025-01-20 13:35:33 -05:00
Anthony Sottile
c3125a4d36
Merge pull request #3389 from lorenzwalthert/dev-always-unset-renv
Fix language:r hook installation when initiated in RStudio
2025-01-20 13:18:20 -05:00
Lorenz Walthert
c2c061cf63 fix: ensure env patch is applied for vanilla emulation
otherwise, installing the hooks when RENV_USER env variable is set (e.g. in RStudio with renv project) will result in executing the installation script in the wrong renv
2025-01-20 13:13:36 -05:00
Anthony Sottile
cd429db5e2
Merge pull request #3382 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2025-01-07 20:21:38 -05:00
pre-commit-ci[bot]
9b9f8e254d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.14.0 → v1.14.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.14.0...v1.14.1)
2025-01-06 23:30:19 +00:00
Anthony Sottile
86300a4a7e
Merge pull request #3376 from pre-commit/r-gone
install r on ubuntu runners
2024-12-28 16:16:53 -05:00
Anthony Sottile
77edad8455 install r on ubuntu runners
this was removed in ubuntu-24.04 github actions runner
2024-12-28 16:06:00 -05:00
Anthony Sottile
18b393905e
Merge pull request #3375 from pre-commit/dotnet-tests-ubuntu-latest
update .net tests to use .net 8
2024-12-28 16:03:04 -05:00
Anthony Sottile
31cb945ffb
Merge pull request #3374 from pre-commit/docker-image-tests-ubuntu-22-not-present
fix docker_image test when ubuntu:22.04 image is not pre-pulled
2024-12-28 15:52:16 -05:00
Anthony Sottile
28c3d81bd2 update .net tests to use .net 8
.net 6 and 7 were removed from github actions runners
2024-12-28 15:50:58 -05:00
Anthony Sottile
aa85be9340 fix docker_image test when ubuntu:22.04 image is not pre-pulled 2024-12-28 15:45:05 -05:00
Anthony Sottile
1027596280
Merge pull request #3373 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-12-23 21:10:03 -05:00
pre-commit-ci[bot]
db85eeed2d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.19.0 → v3.19.1](https://github.com/asottile/pyupgrade/compare/v3.19.0...v3.19.1)
- [github.com/pre-commit/mirrors-mypy: v1.13.0 → v1.14.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.13.0...v1.14.0)
2024-12-23 22:45:24 +00:00
Anthony Sottile
cb14bc2d9c
Merge pull request #3304 from AleksaC/go-toolchain
disable automatic toolchain switching for golang hooks
2024-11-25 18:54:37 -05:00
AleksaC
109628c505 disable automatic toolchain switching for golang hooks 2024-11-25 18:47:18 -05:00
Anthony Sottile
74233a125a
Merge pull request #3348 from fredrikekre/fe/julia
Add support for julia hooks
2024-11-25 18:38:49 -05:00
Fredrik Ekre
85783bdc0b Add support for julia hooks
This patch adds 2nd class support for hooks using julia as the language.
pre-commit will install any dependencies defined in the hooks repo
`Project.toml` file, with support for `additional_dependencies` as well.
Julia doesn't (yet) have a way to install binaries/scripts so for julia
hooks the `entry` value is a (relative) path to a julia script within
the hooks repository. When executing a julia hook the (globally
installed) julia interpreter is prepended to the entry.

Example `.pre-commit-hooks.yaml`:

```yaml
- id: foo
  name: ...
  language: julia
  entry: bin/foo.jl --arg1
```

Example hooks repo: https://github.com/fredrikekre/runic-pre-commit/tree/fe/julia
Accompanying pre-commit.com PR: https://github.com/pre-commit/pre-commit.com/pull/998

Fixes #2689.
2024-11-25 18:31:25 -05:00
Anthony Sottile
9da45a686a
Merge pull request #3345 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-10-28 21:23:33 -04:00
pre-commit-ci[bot]
708ca3b581
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.18.0 → v3.19.0](https://github.com/asottile/pyupgrade/compare/v3.18.0...v3.19.0)
- [github.com/pre-commit/mirrors-mypy: v1.12.1 → v1.13.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.12.1...v1.13.0)
2024-10-28 22:56:52 +00:00
Anthony Sottile
611195a088
Merge pull request #3333 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-10-21 20:42:52 -04:00
Anthony Sottile
0de4c8028a remove unused type ignore 2024-10-21 20:35:56 -04:00
pre-commit-ci[bot]
46de4da34e
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.5.0 → v2.7.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.5.0...v2.7.0)
- [github.com/asottile/reorder-python-imports: v3.13.0 → v3.14.0](https://github.com/asottile/reorder-python-imports/compare/v3.13.0...v3.14.0)
- [github.com/asottile/pyupgrade: v3.17.0 → v3.18.0](https://github.com/asottile/pyupgrade/compare/v3.17.0...v3.18.0)
- [github.com/pre-commit/mirrors-mypy: v1.11.2 → v1.12.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.11.2...v1.12.1)
2024-10-21 22:30:38 +00:00
Anthony Sottile
cc4a522415 v4.0.1 2024-10-08 12:08:49 -04:00
Anthony Sottile
772d7d45d3
Merge pull request #3324 from pre-commit/migrate-config-purelib
fix migrate-config for purelib yaml
2024-10-08 12:01:05 -04:00
Anthony Sottile
222c62bc5d fix migrate-config for purelib yaml 2024-10-08 11:46:48 -04:00
Anthony Sottile
3d5548b487
Merge pull request #3323 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-10-08 06:48:13 -04:00
pre-commit-ci[bot]
4235a877f3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.6.0 → v5.0.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.6.0...v5.0.0)
2024-10-08 00:02:26 +00:00
Anthony Sottile
dbccd57db0 v4.0.0 2024-10-05 14:58:22 -04:00
Anthony Sottile
d07e52901c
Merge pull request #3320 from pre-commit/remove-python-venv
remove deprecated python_venv alias
2024-10-05 13:58:57 -04:00
Anthony Sottile
801b956304 remove deprecated python_venv alias 2024-10-05 13:30:25 -04:00
Anthony Sottile
a2f7b80e89
Merge pull request #3315 from pre-commit/warn-deprecated-stage-names-on-init
add warning for deprecates stages for remote repos on init
2024-09-30 20:48:47 -04:00
Anthony Sottile
d31722386e add warning for deprecates stages for remote repos on init 2024-09-30 20:41:50 -04:00
Anthony Sottile
7555e11098
Merge pull request #3314 from pre-commit/remove-log-info-mock
replace log_info_mock with pytest's caplog
2024-09-30 20:07:00 -04:00
Anthony Sottile
05e365fe08
Merge pull request #3313 from pre-commit/default-stages-warning
add warning for deprecated stages values in `default_stages`
2024-09-30 20:02:15 -04:00
Anthony Sottile
1d2f1c0cce replace log_info_mock with pytest's caplog 2024-09-30 19:58:16 -04:00
Anthony Sottile
33e020f315 add warning for deprecated stages values in default_stages 2024-09-30 19:22:14 -04:00
Anthony Sottile
e7cfc0d2cb
Merge pull request #3312 from pre-commit/warning-for-old-stage-names
add warning for deprecated stages names
2024-09-30 18:48:39 -04:00
Anthony Sottile
7441a62eb1 add warning for deprecated stages names 2024-09-30 18:41:13 -04:00
Anthony Sottile
eec11bd124
Merge pull request #3311 from pre-commit/sensible-regex-for-meta
also apply sensible regex warning for `repo: meta`
2024-09-30 18:16:05 -04:00
Anthony Sottile
fa08d1d637 also apply sensible regex warning for repo: meta 2024-09-30 18:09:04 -04:00
Anthony Sottile
6c068a78d6
Merge pull request #3199 from ThisGuyCodes/thisguycodes/upgrade-ruby-build
Upgrade to ruby-build v20240501
2024-09-28 13:16:09 -04:00
Anthony Sottile
c9454e2ec3 regenerate ruby-build archive 2024-09-28 13:07:55 -04:00
Anthony Sottile
e687548842 regenerate archives with python3.12 2024-09-28 13:07:38 -04:00
Travis Johnson
a4e4cef335 Upgrade to ruby-build v20240917 2024-09-28 13:07:38 -04:00
Anthony Sottile
de8590064e
Merge pull request #3302 from pre-commit/migrate-config-stages
migrate-config rewrites deprecated stages
2024-09-16 20:45:21 -04:00
Anthony Sottile
5679399d90 migrate-config rewrites deprecated stages 2024-09-16 20:36:33 -04:00
Anthony Sottile
a7b671a758
Merge pull request #3301 from pre-commit/yaml-rewrite
change migrate-config to use yaml parse tree instead
2024-09-16 20:24:35 -04:00
Anthony Sottile
364e6d77f0 change migrate-config to use yaml parse tree instead 2024-09-16 20:16:16 -04:00
Anthony Sottile
504149d2ca
Merge pull request #3286 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-08-26 19:03:22 -04:00
pre-commit-ci[bot]
c2c68d985c
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.11.1 → v1.11.2](https://github.com/pre-commit/mirrors-mypy/compare/v1.11.1...v1.11.2)
2024-08-26 22:18:35 +00:00
Anthony Sottile
0f8f383d53
Merge pull request #3275 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-08-05 18:46:27 -04:00
pre-commit-ci[bot]
d5c21926ab
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 7.1.0 → 7.1.1](https://github.com/PyCQA/flake8/compare/7.1.0...7.1.1)
- [github.com/pre-commit/mirrors-mypy: v1.11.0 → v1.11.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.11.0...v1.11.1)
2024-08-05 22:39:33 +00:00
Anthony Sottile
8a3ee454a2
Merge pull request #3270 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-07-29 21:36:13 -04:00
pre-commit-ci[bot]
917e2102be [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2024-07-29 21:59:19 +00:00
pre-commit-ci[bot]
9d4ab670d1
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.16.0 → v3.17.0](https://github.com/asottile/pyupgrade/compare/v3.16.0...v3.17.0)
2024-07-29 21:59:01 +00:00
Anthony Sottile
d46423ffe1 v3.8.0 2024-07-28 15:58:29 -04:00
Anthony Sottile
8133abd730
Merge pull request #3265 from lorenzwalthert/issue-3206
Support health check for `language: r`
2024-07-28 15:54:27 -04:00
Lorenz Walthert
da0c1d0cfa implement health check for language:r 2024-07-28 15:44:07 -04:00
Anthony Sottile
f641f6a157
Merge pull request #3264 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-07-28 15:07:33 -04:00
Anthony Sottile
a68a19d217 fixes for mypy 1.11 2024-07-28 14:57:13 -04:00
pre-commit-ci[bot]
88317ddb34
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.10.1 → v1.11.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.10.1...v1.11.0)
2024-07-22 22:04:19 +00:00
Anthony Sottile
faa6f8c70c
Merge pull request #3244 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-07-05 18:34:07 -04:00
pre-commit-ci[bot]
f632459bc6
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.10.0 → v1.10.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.10.0...v1.10.1)
2024-07-01 23:34:14 +00:00
Anthony Sottile
0252908c27
Merge pull request #3240 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-06-25 14:16:25 -04:00
pre-commit-ci[bot]
69b5dce12a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/hhatto/autopep8: v2.3.0 → v2.3.1](https://github.com/hhatto/autopep8/compare/v2.3.0...v2.3.1)
2024-06-24 21:49:02 +00:00
Anthony Sottile
d56502acab
Merge pull request #3237 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-06-18 20:14:03 -04:00
pre-commit-ci[bot]
49a9664cd0
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/hhatto/autopep8: v2.2.0 → v2.3.0](https://github.com/hhatto/autopep8/compare/v2.2.0...v2.3.0)
- [github.com/PyCQA/flake8: 7.0.0 → 7.1.0](https://github.com/PyCQA/flake8/compare/7.0.0...7.1.0)
2024-06-17 21:57:20 +00:00
Anthony Sottile
60db5d78d1
Merge pull request #3227 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-06-13 10:28:30 -04:00
pre-commit-ci[bot]
9dd247898c
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.15.2 → v3.16.0](https://github.com/asottile/pyupgrade/compare/v3.15.2...v3.16.0)
2024-06-10 21:56:51 +00:00
Anthony Sottile
15d9f7f61e
Merge pull request #3217 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-06-03 21:46:10 -04:00
pre-commit-ci[bot]
1f128556e4
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder-python-imports: v3.12.0 → v3.13.0](https://github.com/asottile/reorder-python-imports/compare/v3.12.0...v3.13.0)
- [github.com/hhatto/autopep8: v2.1.1 → v2.2.0](https://github.com/hhatto/autopep8/compare/v2.1.1...v2.2.0)
2024-06-03 21:47:18 +00:00
Anthony Sottile
dd144c95f6
Merge pull request #3207 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-05-27 17:46:19 -04:00
pre-commit-ci[bot]
5526bb2137
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/hhatto/autopep8: v2.1.0 → v2.1.1](https://github.com/hhatto/autopep8/compare/v2.1.0...v2.1.1)
2024-05-27 21:34:15 +00:00
Anthony Sottile
9ee0768353 v3.7.1 2024-05-10 21:24:51 -04:00
Anthony Sottile
eeac061b31
Merge pull request #3201 from pre-commit/rust-default-language-version
determine rust default language version independent of rust-toolchain.toml
2024-05-10 21:21:22 -04:00
Anthony Sottile
296f59266e determine rust default language version independent of rust-toolchain.toml 2024-05-10 17:06:29 -04:00
Anthony Sottile
16023286d2
Merge pull request #3193 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-04-29 21:45:54 -04:00
pre-commit-ci[bot]
0142f45322 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.9.0 → v1.10.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.9.0...v1.10.0)
2024-04-29 21:38:52 -04:00
Anthony Sottile
d7e21cd29c
Merge pull request #3194 from pre-commit/handle-readonly-3-12
adjust _handle_readonly for typeshed updates
2024-04-29 21:36:47 -04:00
Anthony Sottile
5c3d006443
use a simpler gem for testing additional_dependencies
tins required building bigdecimal, whereas jmespath is self-contained
2024-04-29 21:28:16 -04:00
Anthony Sottile
0d4c6da36e adjust _handle_readonly for typeshed updates 2024-04-29 21:05:41 -04:00
Anthony Sottile
85fe18253f
Merge pull request #3176 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-04-10 11:20:08 -04:00
pre-commit-ci[bot]
74d05b444d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.5.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.5.0...v4.6.0)
2024-04-08 22:08:29 +00:00
Anthony Sottile
a9f19f4cc0
Merge pull request #3169 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-03-27 17:20:38 -04:00
pre-commit-ci[bot]
4e121ef25c
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.15.1 → v3.15.2](https://github.com/asottile/pyupgrade/compare/v3.15.1...v3.15.2)
2024-03-25 21:31:39 +00:00
Anthony Sottile
7b4667e9e6 v3.7.0 2024-03-24 13:37:19 -04:00
Anthony Sottile
d46c8fc051
Merge pull request #3168 from pre-commit/fix-fail-fast
fix per-hook fail_fast to not fail on previous failures
2024-03-24 13:28:36 -04:00
Anthony Sottile
fc622159a6 fix per-hook fail_fast to not fail on previous failures 2024-03-24 13:17:00 -04:00
Anthony Sottile
716da1e49c
Merge pull request #3155 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-03-20 09:29:19 -04:00
pre-commit-ci[bot]
0939c11b4f
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/hhatto/autopep8: v2.0.4 → v2.1.0](https://github.com/hhatto/autopep8/compare/v2.0.4...v2.1.0)
2024-03-18 21:47:27 +00:00
Anthony Sottile
3bdf9fb91b
Merge pull request #3150 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-03-13 10:01:23 -04:00
pre-commit-ci[bot]
75b3e52e57
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0)
2024-03-13 00:16:12 +00:00
Anthony Sottile
5e11c266ae
Merge pull request #3122 from glehmann/docker-tty
give docker a tty output when expecting color
2024-03-02 11:57:30 -05:00
Gaëtan Lehmann
e58009684c give docker a tty output when expecting color
this makes the behavior more consistent with the system language
and would help the executable run in a docker container to
produce a colored output.
2024-03-02 11:51:34 -05:00
Anthony Sottile
7b868c3508
Merge pull request #3132 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-02-20 10:21:58 -05:00
pre-commit-ci[bot]
a768c038e3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.15.0 → v3.15.1](https://github.com/asottile/pyupgrade/compare/v3.15.0...v3.15.1)
2024-02-20 00:02:29 +00:00
Anthony Sottile
e525726855 v3.6.2 2024-02-18 13:19:11 -05:00
Anthony Sottile
3187538d2b
Merge pull request #3130 from pre-commit/golang-build-during-commit-a
fix building golang hooks during `commit --all`
2024-02-18 13:14:37 -05:00
Anthony Sottile
61d9c95cc1 fix building golang hooks during commit --all 2024-02-18 13:03:44 -05:00
Anthony Sottile
15bd0c7993 v3.6.1 2024-02-10 14:45:43 -05:00
Anthony Sottile
92678c3fa2
Merge pull request #3126 from pre-commit/crlf-only-diff
staged_files_only can handle a crlf-only diff
2024-02-10 14:10:29 -05:00
Anthony Sottile
032d8e2704 staged_files_only can handle a crlf-only diff 2024-02-10 14:01:49 -05:00
Anthony Sottile
73848383f2
Merge pull request #3110 from untitaker/pythonexecutable
Pop PYTHONEXECUTABLE
2024-01-12 11:39:51 -05:00
pre-commit-ci[bot]
96e0712f43 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2024-01-12 16:32:44 +00:00
Markus Unterwaditzer
3388e2dbdf Pop PYTHONEXECUTABLE 2024-01-12 17:30:01 +01:00
Anthony Sottile
10f8853631
Merge pull request #3107 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-01-08 17:41:12 -05:00
pre-commit-ci[bot]
9682f93e31
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 6.1.0 → 7.0.0](https://github.com/PyCQA/flake8/compare/6.1.0...7.0.0)
2024-01-08 20:21:06 +00:00
Anthony Sottile
5f8ebaefa9
Merge pull request #3102 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-12-26 13:50:45 -05:00
pre-commit-ci[bot]
9cce283422
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.7.1 → v1.8.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.7.1...v1.8.0)
2023-12-25 20:20:03 +00:00
Anthony Sottile
9c9983dba0 v3.6.0 2023-12-09 16:24:52 -05:00
Anthony Sottile
7dc0a59ee5
Merge pull request #3093 from pre-commit/removeprefix
python 3.9+: use removeprefix
2023-12-09 16:13:25 -05:00
Anthony Sottile
d3fa7f415c
Merge pull request #3092 from pre-commit/minimum-version-first
attempt minimum_pre_commit_version first when parsing configs
2023-12-09 16:04:44 -05:00
Anthony Sottile
08478ec176 python 3.9+: use removeprefix 2023-12-09 16:04:25 -05:00
Anthony Sottile
047439abff attempt minimum_pre_commit_version first when parsing configs 2023-12-09 15:34:16 -05:00
Anthony Sottile
23a2b7360e
Merge pull request #3079 from edgarrmondragon/deprecation-rmtree-onerror
Address deprecation warning in `shutil.rmtree(onerror=...)`
2023-12-09 14:59:09 -05:00
Edgar Ramírez Mondragón
cffabe54be Address deprecation warning in shutil.rmtree(onerror=...) 2023-12-09 14:51:01 -05:00
Anthony Sottile
51df34e5fb
Merge pull request #3078 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-11-27 17:55:04 -05:00
pre-commit-ci[bot]
e36cefc8bd
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.7.0 → v1.7.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.7.0...v1.7.1)
2023-11-27 20:01:19 +00:00
Anthony Sottile
2280645d0e
Merge pull request #3064 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-11-13 21:41:08 -05:00
pre-commit-ci[bot]
1d474994e0
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.6.1 → v1.7.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.6.1...v1.7.0)
2023-11-13 20:35:35 +00:00
Anthony Sottile
14169eb31d
Merge pull request #3043 from pre-commit/jaraco
3.13 removed the simpler importlib.resources api
2023-10-28 14:50:43 -04:00
Anthony Sottile
75f2710bd4 3.13 removed the simpler importlib.resources api 2023-10-28 14:39:49 -04:00
Anthony Sottile
762e68173b
Merge pull request #3042 from pre-commit/py39
python3.9+
2023-10-28 14:35:26 -04:00
Anthony Sottile
7f15dc75ee python3.9+ 2023-10-28 14:20:37 -04:00
Anthony Sottile
5f4ed54cfe
Merge pull request #3038 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-10-23 16:57:56 -04:00
pre-commit-ci[bot]
c69e32e925
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.6.0 → v1.6.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.6.0...v1.6.1)
2023-10-23 20:28:04 +00:00
Anthony Sottile
48f0dc9615
Merge pull request #3033 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-10-16 22:08:24 -04:00
pre-commit-ci[bot]
44b625ebd3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.5.1 → v1.6.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.5.1...v1.6.0)
2023-10-16 20:03:36 +00:00
Anthony Sottile
61cc55a59c v3.5.0 2023-10-13 11:57:20 -04:00
Anthony Sottile
c9945b9aa3
Merge pull request #3029 from adamchainz/improve_duration_timing
Improve hook duration timing
2023-10-13 11:49:53 -04:00
Adam Johnson
d988767b41 Improve hook duration timing 2023-10-13 16:40:30 +01:00
Anthony Sottile
0d8b2451ca
Merge pull request #3023 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-10-09 17:08:44 -04:00
pre-commit-ci[bot]
155c521348 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.5.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.5.0)
- [github.com/asottile/pyupgrade: v3.14.0 → v3.15.0](https://github.com/asottile/pyupgrade/compare/v3.14.0...v3.15.0)
2023-10-09 16:58:51 -04:00
Anthony Sottile
676e51aa5e
Merge pull request #3024 from pre-commit/pick-shebang-path-without-spaces
use sys.executable instead of echo.exe in parse_shebang
2023-10-09 16:58:43 -04:00
Anthony Sottile
997ea0ad52 use sys.executable instead of echo.exe in parse_shebang
the GHA runners now have echo.exe in a path with spaces
2023-10-09 16:49:30 -04:00
Anthony Sottile
19aa121db0
Merge pull request #3016 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-10-03 12:57:10 -04:00
pre-commit-ci[bot]
a4ab977cc3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.4.0 → v2.5.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.4.0...v2.5.0)
- [github.com/asottile/reorder-python-imports: v3.11.0 → v3.12.0](https://github.com/asottile/reorder-python-imports/compare/v3.11.0...v3.12.0)
- [github.com/asottile/pyupgrade: v3.13.0 → v3.14.0](https://github.com/asottile/pyupgrade/compare/v3.13.0...v3.14.0)
2023-10-03 08:58:04 +00:00
Anthony Sottile
3f3760b86c
Merge pull request #3011 from hack3ric/bump-node-and-go-version
Bump Node.js version to 18.14.0 and Go to 1.21.1
2023-09-26 14:16:57 -04:00
Anthony Sottile
051f4e2550
Merge pull request #3012 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-09-26 09:04:10 -04:00
pre-commit-ci[bot]
c68c6b944a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.11.0 → v3.13.0](https://github.com/asottile/pyupgrade/compare/v3.11.0...v3.13.0)
2023-09-26 07:23:52 +00:00
Eric Long
5e05b01215
Bump Node.js version to 18.14.0 and Go to 1.21.1
On riscv64, nodeenv will pull binary from unofficial-builds [1], and
unfortunately 18.13.0 seems to be the only version above 18 that is
missing riscv64 builds. Shifting the version slightly to make test work.

Go's binary now ships with linux/riscv64 binary since 1.21.
2023-09-25 17:02:13 +08:00
Anthony Sottile
84f91646bb
Merge pull request #3006 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-09-19 09:06:27 -04:00
pre-commit-ci[bot]
d33801e781
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder-python-imports: v3.10.0 → v3.11.0](https://github.com/asottile/reorder-python-imports/compare/v3.10.0...v3.11.0)
- [github.com/asottile/pyupgrade: v3.10.1 → v3.11.0](https://github.com/asottile/pyupgrade/compare/v3.10.1...v3.11.0)
2023-09-19 07:06:08 +00:00
Anthony Sottile
f56b75dd77
Merge pull request #2998 from pre-commit/short-circuit
Short-circuit `check-hooks-apply` and `check-useless-excludes` hooks
2023-09-11 19:52:51 -04:00
Max R
5d692d7e06 Short-circuit hooks 2023-09-11 19:41:40 -04:00
Anthony Sottile
0845e4e816
Merge pull request #2996 from RoelAdriaans/feature/fix-1983-npm
Use the --include command, hides warning messages
2023-09-11 19:12:06 -04:00
Anthony Sottile
5f4b828999
Merge pull request #3000 from pre-commit/refactor-tests
Refactor `target_concurrency` tests
2023-09-10 10:45:14 -04:00
Max R
9ac229dad8 Refactor target_concurrency tests 2023-09-10 08:39:19 -04:00
Roel Adriaans
493c20ce91 Use the --include command, hides warning messages
Fixes #1983
2023-09-08 15:12:54 +02:00
Anthony Sottile
e2c6a822c7
Merge pull request #2991 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-09-05 09:07:18 -04:00
pre-commit-ci[bot]
818240e425
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v3.0.1 → v3.1.0](https://github.com/asottile/add-trailing-comma/compare/v3.0.1...v3.1.0)
- https://github.com/pre-commit/mirrors-autopep8https://github.com/hhatto/autopep8
2023-09-05 06:46:49 +00:00
Anthony Sottile
fe9ba6b53f v3.4.0 2023-09-02 13:09:13 -04:00
Anthony Sottile
ac42dc586a
Merge pull request #2979 from jdb8/cpu-sched-getaffinity
Use os.sched_getaffinity for cpu counts when available
2023-08-30 13:57:54 -04:00
Joe Bateson
ea8244b229 Use os.sched_getaffinity for cpu counts when available 2023-08-30 13:39:20 -04:00
Anthony Sottile
9ebda91889
Merge pull request #2980 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-08-29 11:15:54 -04:00
pre-commit-ci[bot]
3dd1875df8
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v2.0.2 → v2.0.4](https://github.com/pre-commit/mirrors-autopep8/compare/v2.0.2...v2.0.4)
2023-08-29 05:38:11 +00:00
Anthony Sottile
bde292b510
Merge pull request #2972 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-08-22 09:09:16 -04:00
pre-commit-ci[bot]
a4ae868633
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.5.0 → v1.5.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.5.0...v1.5.1)
2023-08-22 06:16:21 +00:00
Anthony Sottile
0c3d605fa0
Merge pull request #2971 from chriskuehl/fix-signal-death
Fix exit code for commands terminated by signals
2023-08-21 21:30:11 -04:00
Chris Kuehl
5a4b5b1f8e Fix exit code for commands terminated by signals
Fixes https://github.com/pre-commit/pre-commit/issues/2970
2023-08-21 20:02:27 -05:00
Anthony Sottile
a1f1d19156
Merge pull request #2961 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-08-15 10:19:29 -04:00
pre-commit-ci[bot]
93b1a14402
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.4.1 → v1.5.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.4.1...v1.5.0)
2023-08-15 06:03:09 +00:00
Anthony Sottile
23df082edc
Merge pull request #2958 from fangfufu/typo-fix
fix typo in CONTRIBUTING.md
2023-08-14 18:01:42 -04:00
Fufu Fang
1803db979f
fix typo in CONTRIBUTING.md 2023-08-14 11:00:17 +01:00
Anthony Sottile
b2ff5e401b
Merge pull request #2949 from pre-commit/asottile-patch-1
update hello world go test
2023-08-01 12:17:31 -04:00
Anthony Sottile
8c75a26f2d
update hello world go test 2023-08-01 12:08:52 -04:00
Anthony Sottile
13b673ce3c
Merge pull request #2946 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-08-01 11:56:47 -04:00
pre-commit-ci[bot]
3557077bbc
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v3.0.0 → v3.0.1](https://github.com/asottile/add-trailing-comma/compare/v3.0.0...v3.0.1)
- [github.com/asottile/pyupgrade: v3.9.0 → v3.10.1](https://github.com/asottile/pyupgrade/compare/v3.9.0...v3.10.1)
- [github.com/PyCQA/flake8: 6.0.0 → 6.1.0](https://github.com/PyCQA/flake8/compare/6.0.0...6.1.0)
2023-08-01 07:08:53 +00:00
Anthony Sottile
2bffc0ad85
Merge pull request #2932 from alunduil/haskell-language
Add haskell language support to pre-commit.
2023-07-22 16:39:17 -04:00
Alex Brandt
60273ca81e Add haskell language support to pre-commit. 2023-07-22 16:28:48 -04:00
Anthony Sottile
f8488e36c8
Merge pull request #2929 from pre-commit/s#helper#lang_base#g
`s/helpers/lang_base/g` in docs
2023-07-17 13:47:20 -04:00
Max R
d537c09032 s/helpers/lang_base/g 2023-07-17 09:36:47 -04:00
Anthony Sottile
9660d3b451
Merge pull request #2927 from pre-commit/mxr-patch-1
Fix link to `language` API
2023-07-16 16:51:06 -04:00
Max R
5e4af63e85
Fix link to language API 2023-07-16 15:00:55 -04:00
Anthony Sottile
4f73b8a2af
Merge pull request #2924 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-07-11 06:28:48 -04:00
pre-commit-ci[bot]
9bf6856db3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.8.0 → v3.9.0](https://github.com/asottile/pyupgrade/compare/v3.8.0...v3.9.0)
2023-07-11 05:21:22 +00:00
Anthony Sottile
8bf22bd3c1
Merge pull request #2917 from pre-commit/py38-shelx-join
shlex.join is always available in 3.8+
2023-07-01 17:33:28 -04:00
Anthony Sottile
1c439b5a79 shlex.join is always available in 3.8+ 2023-07-01 17:22:42 -04:00
Anthony Sottile
3126802bf4
Merge pull request #2916 from pre-commit/all-repos_autofix_add-trailing-comma-3
updates for add-trailing-comma 3.x
2023-07-01 16:57:16 -04:00
Anthony Sottile
e72699b9ef updates for add-trailing-comma 3.x
Committed via https://github.com/asottile/all-repos
2023-07-01 16:47:06 -04:00
Anthony Sottile
8891089cf5
Merge pull request #2914 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-06-27 00:12:59 -04:00
pre-commit-ci[bot]
854f698531
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.3.0 → v1.4.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.3.0...v1.4.1)
2023-06-27 03:51:58 +00:00
Anthony Sottile
c25ea47cf7
Merge pull request #2908 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-06-20 19:13:54 -07:00
pre-commit-ci[bot]
f94744a699
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder-python-imports: v3.9.0 → v3.10.0](https://github.com/asottile/reorder-python-imports/compare/v3.9.0...v3.10.0)
- [github.com/asottile/pyupgrade: v3.6.0 → v3.7.0](https://github.com/asottile/pyupgrade/compare/v3.6.0...v3.7.0)
2023-06-20 04:33:31 +00:00
Anthony Sottile
5da4258b17 v3.3.3 2023-06-13 19:11:02 -04:00
Anthony Sottile
e891f8606e
Merge pull request #2905 from jaysoffian/fix-gem-install
Force gem installation into envdir
2023-06-13 19:09:34 -04:00
pre-commit-ci[bot]
50b1511a5b [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-06-13 22:04:03 +00:00
Jay Soffian
9a7ed8be09 Force gem installation into envdir
RubyGems allows OS packagers to specify defaults for `--install-dir`
and `--bindir` and these take precedence over `GEM_HOME`. The only way
to override the defaults is to explicitly specify the options ourselves
when running `gem install`.

Examples of OSes where this is the case are RedHat 9.2 and Gentoo.

Fixes #2799.
2023-06-13 18:03:52 -04:00
Anthony Sottile
f073f8e13c
Merge pull request #2904 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-06-13 04:49:13 -04:00
pre-commit-ci[bot]
1fc28903ab
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v2.4.0 → v2.5.1](https://github.com/asottile/add-trailing-comma/compare/v2.4.0...v2.5.1)
- [github.com/asottile/pyupgrade: v3.4.0 → v3.6.0](https://github.com/asottile/pyupgrade/compare/v3.4.0...v3.6.0)
2023-06-13 03:58:21 +00:00
Anthony Sottile
c7f472d176
Merge pull request #2903 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-06-06 00:00:19 -04:00
pre-commit-ci[bot]
5d273951e0 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-06-06 03:14:27 +00:00
pre-commit-ci[bot]
f88cc61256
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.2.0 → v2.3.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.2.0...v2.3.0)
2023-06-06 03:14:12 +00:00
Anthony Sottile
c716de12f7
Merge pull request #2901 from pre-commit/all-repos_autofix_all-repos-sed
fix tags trigger for github actions
2023-06-01 19:29:26 -04:00
Anthony Sottile
f4a2d52bb4 fix tags trigger for github actions
the old syntax worked for azure pipelines but not GHA

Committed via https://github.com/asottile/all-repos
2023-06-01 19:12:46 -04:00
Anthony Sottile
8034430539
Merge pull request #2889 from pre-commit/zipapp-make-standalone
use distlib inside the zipapp docker image
2023-05-17 16:15:56 -07:00
Anthony Sottile
18348f5d0d use distlib inside the zipapp docker image 2023-05-17 18:58:11 -04:00
Anthony Sottile
a0a734750e v3.3.2 2023-05-17 18:36:52 -04:00
Anthony Sottile
bcd8274e1c
Merge pull request #2885 from lorenzwalthert/avoid-quote-write-to-tempfile
More robust R hooks for Windows
2023-05-17 15:20:36 -07:00
Lorenz Walthert
cd09c3525e avoid quoting and escaping while installing R hooks by writing code to tempfile instead of execute R code inline 2023-05-17 18:00:00 -04:00
Anthony Sottile
c389ac0ba8
Merge pull request #2886 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-05-16 07:51:08 -07:00
pre-commit-ci[bot]
64985bd63d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.2.0 → v1.3.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.2.0...v1.3.0)
2023-05-16 03:20:34 +00:00
Anthony Sottile
f5a98eb152
Merge pull request #2883 from pre-commit/install-swift-not-needed
swift is included in github actions
2023-05-13 17:50:47 -07:00
Anthony Sottile
08b670ff9e swift is included in github actions 2023-05-13 16:37:02 -07:00
Anthony Sottile
72b7b53ae3
Merge pull request #2884 from pre-commit/typo
fix typo in testing/languages
2023-05-13 13:39:56 -07:00
Anthony Sottile
9c2a01186b fix typo in testing/languages 2023-05-13 16:27:14 -04:00
Anthony Sottile
ee49d4289f
Merge pull request #2882 from pre-commit/languages-always-run
make some files trigger all languages
2023-05-13 13:19:21 -07:00
Anthony Sottile
926071b6a7 make some files trigger all languages 2023-05-13 16:03:14 -04:00
Anthony Sottile
0deb445a73
Merge pull request #2881 from pre-commit/r-does-not-support-language-version
r does not support language_version currently
2023-05-13 12:54:10 -07:00
Anthony Sottile
8923fa368a r does not support language_version currently 2023-05-13 15:46:34 -04:00
Anthony Sottile
cf3e826070
Merge pull request #2879 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-05-09 08:40:54 -04:00
pre-commit-ci[bot]
1dd85c904e
[pre-commit.ci] pre-commit autoupdate
updates:
- https://github.com/asottile/reorder_python_importshttps://github.com/asottile/reorder-python-imports
- [github.com/asottile/pyupgrade: v3.3.2 → v3.4.0](https://github.com/asottile/pyupgrade/compare/v3.3.2...v3.4.0)
2023-05-09 04:04:18 +00:00
Anthony Sottile
51104fa94a v3.3.1 2023-05-02 10:07:25 -04:00
Anthony Sottile
0fd2501503
Merge pull request #2866 from pre-commit/autoupdate-hack-windows
add partial clone hack to fix autoupdate for windows
2023-05-02 10:05:33 -04:00
Anthony Sottile
420a15f87e add partial clone hack to fix autoupdate for windows 2023-05-02 09:54:25 -04:00
Anthony Sottile
4c0623963f v3.3.0 2023-05-01 18:23:50 -04:00
Anthony Sottile
5df9eb9d66
Merge pull request #2863 from pre-commit/parallel-autoupdate
add --jobs option to autoupdate
2023-04-29 15:57:36 -04:00
Anthony Sottile
ddbee32ad0 add --jobs option to autoupdate 2023-04-29 15:42:01 -04:00
Anthony Sottile
bab5f70a38
Merge pull request #2861 from pre-commit/autoupdate-without-store
perform autoupdate without Store contention
2023-04-29 15:41:45 -04:00
Anthony Sottile
4f045cbc21 perform autoupdate without Store contention 2023-04-29 15:32:20 -04:00
Anthony Sottile
27d77fc8bc
Merge pull request #2860 from pre-commit/autoupdate-dash-C
use -C for git commands in autoupdate
2023-04-29 15:24:41 -04:00
Anthony Sottile
e885f2e76e use -C for git commands in autoupdate 2023-04-29 15:12:51 -04:00
Anthony Sottile
148df0d718
Merge pull request #2859 from pre-commit/blobless-clone
use blobless clone for faster autoupdate
2023-04-29 13:37:20 -04:00
Anthony Sottile
4727922b93 use blobless clone for faster autoupdate 2023-04-29 13:29:00 -04:00
Anthony Sottile
5cd99d81ad
Merge pull request #2846 from jalessio/upgrade-to-ruby-build-v20230330
Upgrade to ruby-build v20230330
2023-04-29 13:03:19 -04:00
Anthony Sottile
8656797c78
Merge pull request #2854 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-04-25 00:53:45 -04:00
pre-commit-ci[bot]
6f941298a4
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.3.1 → v3.3.2](https://github.com/asottile/pyupgrade/compare/v3.3.1...v3.3.2)
2023-04-25 03:20:55 +00:00
Jamie Alessio
cfcb88364e Upgrade to ruby-build v20230330 2023-04-18 10:58:57 -07:00
Anthony Sottile
6896025288
Merge pull request #2843 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-04-12 16:07:39 -04:00
pre-commit-ci[bot]
f5a716f1b1
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.1.1 → v1.2.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.1.1...v1.2.0)
2023-04-11 02:57:43 +00:00
Anthony Sottile
5027592625 v3.2.2 2023-04-03 16:31:09 -04:00
Anthony Sottile
597bf7caf8
Merge pull request #2836 from edelabar/main
Change deprecated `swift build` `-C` command line option to replacement `--package-path`
2023-04-03 16:25:11 -04:00
Eric DeLabar
84f040f58a
fix #2235 2023-04-03 15:50:55 -04:00
Anthony Sottile
bb49560dc9 v3.2.1 2023-03-25 14:02:57 -04:00
Anthony Sottile
0477abd3ce
Merge pull request #2827 from pre-commit/cargo-home-during-rustup
set CARGO_HOME while executing rustup
2023-03-25 14:00:25 -04:00
Anthony Sottile
ee71a9345c set CARGO_HOME while executing rustup 2023-03-25 13:06:22 -04:00
Anthony Sottile
df2cada973 v3.2.0 2023-03-17 14:26:34 -04:00
Anthony Sottile
fdb9ede460
Merge pull request #2820 from pre-commit/clear-rust-registry-cache
don't set CARGO_HOME in rust
2023-03-17 13:08:37 -04:00
Anthony Sottile
a412e5492d don't set CARGO_HOME in rust
this adds a 270 MB registry cache in the output
2023-03-17 12:55:34 -04:00
Anthony Sottile
d5f919e72f
Merge pull request #2815 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-03-14 00:57:29 -04:00
pre-commit-ci[bot]
7a7772fcda
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.0.1 → v1.1.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.0.1...v1.1.1)
2023-03-14 03:19:10 +00:00
Anthony Sottile
4caea677c6
Merge pull request #2809 from m-rsha/move-slow-repository-tests
move slowest python-specific tests out of repository_test
2023-03-12 11:11:04 -04:00
marsha
d3c0a66d23 move slowest python-specific tests out of repository_test 2023-03-12 08:24:38 -05:00
Anthony Sottile
950451e1ef
Merge pull request #2725 from mgaligniana/issue-2582
Add pre-rebase hook support
2023-03-11 15:26:52 -05:00
Marcelo Galigniana
f39154f69f Add pre-rebase hook support 2023-03-11 15:17:42 -05:00
Anthony Sottile
f2661bfc31
Merge pull request #2808 from pre-commit/hook-stage-and-type-match
make --hook-type and stages match
2023-03-11 14:51:16 -05:00
Anthony Sottile
e3e17a1617 make --hook-type and stages match 2023-03-11 14:26:14 -05:00
Anthony Sottile
02e9680a46
Merge pull request #2805 from pre-commit/durations
show 20 slowest durations in CI
2023-03-09 11:12:00 -05:00
Anthony Sottile
8ab9747b33 show 20 slowest durations in CI 2023-03-09 11:00:31 -05:00
Anthony Sottile
321a90e0a1
Merge pull request #2798 from m-rsha/spargs-test
rewrite `args with spaces` test to not require python
2023-03-09 09:48:17 -05:00
marsha
63a180a935 rewrite args with spaces test to not require python 2023-03-09 00:41:27 -06:00
Anthony Sottile
fe73f519c7
Merge pull request #2801 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-03-06 22:01:43 -05:00
pre-commit-ci[bot]
0616c0abf7
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v2.0.1 → v2.0.2](https://github.com/pre-commit/mirrors-autopep8/compare/v2.0.1...v2.0.2)
2023-03-07 02:52:32 +00:00
Anthony Sottile
321685ee0e
Merge pull request #2796 from m-rsha/os-name
prefer `sys.platform` over `os.name` when checking for windows OS
2023-03-04 01:20:22 -05:00
marsha
5ce4a549d3 prefer sys.platform over os.name when checking for windows OS 2023-03-03 22:13:07 -06:00
Anthony Sottile
2822de9aa6 v3.1.1 2023-02-27 21:07:23 -05:00
Anthony Sottile
7f386a752e
Merge pull request #2788 from pre-commit/rustup-home-temporary
set RUSTUP_HOME when using a non-system rust
2023-02-27 21:02:12 -05:00
Anthony Sottile
2700a7d622 set RUSTUP_HOME when using a non-system rust 2023-02-27 20:49:22 -05:00
Anthony Sottile
294590fd12 v3.1.0 2023-02-22 20:53:02 -05:00
Anthony Sottile
7bfa7e15c6
Merge pull request #2776 from pre-commit/unsorted-additional-deps
remove sorting for repo key for additional_deps
2023-02-22 20:42:44 -05:00
Anthony Sottile
a631abdabf remove sorting for repo key for additional_deps
in other languages this order can matter (such as ruby)
2023-02-22 20:31:14 -05:00
Anthony Sottile
cdd360645a
Merge pull request #2775 from pre-commit/called-process-error-trailing-whitespace
fix trailing whitespace in CalledProcessError output
2023-02-21 13:02:50 -05:00
Anthony Sottile
4ded56efac fix trailing whitespace in CalledProcessError output 2023-02-21 12:42:09 -05:00
Anthony Sottile
192be6079b
Merge pull request #2774 from pre-commit/diff-must-succeed
only treat exit code 1 as a successful diff
2023-02-21 12:30:33 -05:00
Anthony Sottile
cddc9cff0f only treat exit code 1 as a successful diff 2023-02-21 12:20:25 -05:00
Anthony Sottile
8ba9bc6d89
Merge pull request #2768 from pre-commit/per-language-tests
test languages only when they are changed
2023-02-21 11:31:14 -05:00
Anthony Sottile
08fa5ffc43 make a change to trigger the language tests 2023-02-21 11:11:44 -05:00
Anthony Sottile
9655158d93 test languages only when they are changed 2023-02-21 11:11:44 -05:00
Anthony Sottile
1054afd978
Merge pull request #2772 from pre-commit/run-language-for-repository-test
use run_language for repository_test
2023-02-20 22:49:55 -05:00
Anthony Sottile
d23990cc8b use run_language for repository_test 2023-02-20 22:21:31 -05:00
Anthony Sottile
51b14c2b37
Merge pull request #2771 from pre-commit/ruby-is-the-only-bytesio
resources_bytesio is only used by ruby
2023-02-20 22:17:20 -05:00
Anthony Sottile
4666b6956f
Merge pull request #2770 from pre-commit/lang_base_unit_tests
improve unit test coverage of lang_base
2023-02-20 21:59:10 -05:00
Anthony Sottile
8d84a7a270 resources_bytesio is only used by ruby 2023-02-20 21:47:01 -05:00
Anthony Sottile
ccbf15150f
Merge pull request #2769 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-02-20 21:39:08 -05:00
Anthony Sottile
25b8ad7528 improve unit test coverage of lang_base 2023-02-20 21:32:32 -05:00
pre-commit-ci[bot]
0cc2856883
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v1.0.0 → v1.0.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.0.0...v1.0.1)
2023-02-21 02:06:17 +00:00
Anthony Sottile
4f6ba18cad
Merge pull request #2767 from pre-commit/test-more-directly
test things more directly to improve coverage
2023-02-20 18:52:11 -05:00
Anthony Sottile
c3402e6648
Merge pull request #2766 from pre-commit/move-language-helpers
move languages.all and languages.helpers out of languages
2023-02-20 18:34:59 -05:00
Anthony Sottile
c3613b954a test things more directly to improve coverage 2023-02-20 18:18:08 -05:00
Anthony Sottile
d3883ce7f7 move languages.all and languages.helpers out of languages 2023-02-20 18:03:45 -05:00
Anthony Sottile
5bc56889e9
Merge pull request #2761 from m-rsha/test-pygrep
test pygrep inline
2023-02-18 18:20:42 -05:00
marsha
a2373d0a81 test pygrep inline 2023-02-18 17:54:44 -05:00
Anthony Sottile
f5ec578647
Merge pull request #2763 from m-rsha/dotnet-output
future-proof dotnet build command
2023-02-18 16:39:39 -05:00
marsha
8db5aaf4f3 future-proof dotnet build command
see https://github.com/dotnet/sdk/issues/30624#issuecomment-1435457318
2023-02-17 21:34:24 -06:00
Anthony Sottile
8afe5958e6
Merge pull request #2760 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-02-13 22:57:43 -05:00
pre-commit-ci[bot]
ea2569027b
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.991 → v1.0.0](https://github.com/pre-commit/mirrors-mypy/compare/v0.991...v1.0.0)
2023-02-14 02:25:01 +00:00
Anthony Sottile
8f2dfce5d1
Merge pull request #2756 from m-rsha/test-fail
test fail language inline
2023-02-13 18:30:00 -05:00
marsha
4fdfb25a52 test fail language inline 2023-02-13 17:03:59 -06:00
Anthony Sottile
4bd1677cda do template links need about? 2023-02-08 11:23:43 -05:00
Anthony Sottile
16869444ca git mv .github/ISSUE_TEMPLATE/config.{yaml,yml} 2023-02-08 11:21:50 -05:00
Anthony Sottile
5635079373 force the issue template more 2023-02-08 11:20:30 -05:00
Anthony Sottile
c5fc8627be
Merge pull request #2752 from adamchainz/document_go_first_class
List golang as first-class language
2023-02-08 08:20:07 -05:00
Adam Johnson
abbfb2e9b9 List golang as first-class language 2023-02-08 06:43:04 +00:00
Anthony Sottile
4d970de329
Merge pull request #2751 from m-rsha/test-dotnet
test dotnet directly
2023-02-07 23:17:00 -05:00
marsha
915b930a5d test dotnet directly 2023-02-07 21:47:26 -06:00
Anthony Sottile
97c7870f89
Merge pull request #2713 from m-rsha/test-go
test golang directly
2023-02-06 18:40:14 -05:00
marsha
6804100701 test golang directly 2023-02-06 17:02:20 -06:00
Anthony Sottile
f7df13f3d8
Merge pull request #2747 from pre-commit/docker-tests
test docker and docker_image directly
2023-02-04 17:51:28 -05:00
Anthony Sottile
0afb95ccca test docker and docker_image directly 2023-02-04 17:22:06 -05:00
Anthony Sottile
b609368ca5
Merge pull request #2746 from pre-commit/deprecate-python-venv
deprecate python_venv language
2023-02-04 14:58:35 -05:00
Anthony Sottile
0c1267b214 deprecate python_venv language 2023-02-04 14:26:09 -05:00
Anthony Sottile
0359fae2da v3.0.4 2023-02-03 12:07:23 -05:00
Anthony Sottile
cc7bf965eb
Merge pull request #2743 from adamchainz/issue_2742
Add `--no-textconv` to `git diff` calls
2023-02-03 12:05:56 -05:00
Adam Johnson
7783a3e63a Add --no-textconv to git diff calls 2023-02-03 15:56:11 +00:00
Anthony Sottile
e846829992 v3.0.3 2023-02-01 18:21:18 -05:00
Anthony Sottile
bfe1a72734
Merge pull request #2740 from pre-commit/gem-file-bleh
Revert "also ignore Gemfile in project"
2023-02-01 18:19:39 -05:00
Anthony Sottile
1129e7d222 fixup Gemfile in ruby tests 2023-02-01 18:17:24 -05:00
Anthony Sottile
7260d24d0f Revert "also ignore Gemfile in project"
This reverts commit f4bd44996c.
2023-02-01 18:17:24 -05:00
Anthony Sottile
9868b1a347
Merge pull request #2741 from pre-commit/golang-1-20
fix golang version regex in test
2023-02-01 18:16:54 -05:00
Anthony Sottile
d216cdd5c1 fix golang version regex in test 2023-02-01 18:16:09 -05:00
Anthony Sottile
c2e432cdf6
Merge pull request #2736 from pre-commit/node-tests
test node directly
2023-01-31 21:40:03 -05:00
Anthony Sottile
909dd0e8a1 test node directly 2023-01-31 21:13:11 -05:00
Anthony Sottile
3c2ca11332
Merge pull request #2737 from pre-commit/health-check-after-create
ensure languages are healthy after creation
2023-01-31 21:12:56 -05:00
Anthony Sottile
2530913fad ensure languages are healthy after creation 2023-01-31 20:40:19 -05:00
Anthony Sottile
650afe4ffa
Merge pull request #2735 from pre-commit/fast-checkout
upgrade asottile/workflows to get fast-checkout
2023-01-30 23:35:09 -05:00
Anthony Sottile
f54386203e upgrade asottile/workflows to get fast-checkout 2023-01-30 23:04:25 -05:00
Anthony Sottile
50cf02764c
Merge pull request #2733 from pre-commit/test-ruby
test ruby directly
2023-01-30 22:12:15 -05:00
Anthony Sottile
5b50acbd2c test ruby directly 2023-01-30 21:36:13 -05:00
Anthony Sottile
77b4ea38ca
Merge pull request #2729 from pre-commit/rust-tests
test rust directly
2023-01-29 19:00:09 -05:00
Anthony Sottile
6abb05a60c v3.0.2 2023-01-29 18:36:45 -05:00
Anthony Sottile
2adca78c6f test rust directly 2023-01-29 18:27:10 -05:00
Anthony Sottile
2e1cfa8f05
Merge pull request #2728 from pre-commit/fix-r-local-hooks
fix r local hooks
2023-01-29 18:26:01 -05:00
Anthony Sottile
420902f67c fix r local hooks
`language: r` acts more like `language: script` so we have to *not* append
the prefix when run with `repo: local`
2023-01-29 17:27:42 -05:00
Anthony Sottile
6eacdd440e
Merge pull request #2726 from pre-commit/pick-better-ruby-version
speed up ruby tests by picking a prebuilt in 22.04
2023-01-28 19:06:42 -05:00
Anthony Sottile
6e8051b9e6 speed up ruby tests by picking a prebuilt in 22.04 2023-01-28 18:36:35 -05:00
Anthony Sottile
840cf532a9
Merge pull request #2727 from pre-commit/ignore-gemfile
also ignore Gemfile in project
2023-01-28 17:15:48 -05:00
Anthony Sottile
f4bd44996c also ignore Gemfile in project
this starts failing with ruby 3.2.0
2023-01-28 16:44:44 -05:00
Anthony Sottile
dd8e717ed6 v3.0.1 2023-01-26 11:09:17 -05:00
Anthony Sottile
6d3a7eeef5
Merge pull request #2723 from pre-commit/coursier-cache
ensure coursier hooks are available offline after install
2023-01-25 17:23:13 -05:00
Anthony Sottile
83e05e607e ensure coursier hooks are available offline after install 2023-01-25 14:03:39 -05:00
Anthony Sottile
6b88fe577c v3.0.0 2023-01-23 20:40:13 -05:00
Anthony Sottile
ea88b377d5
Merge pull request #2720 from pre-commit/install-state-v2
introduce install state v2 to replace v1
2023-01-23 20:33:49 -05:00
Anthony Sottile
bff5e0e738 introduce install state v2 to replace v1
the v1 state is unnecessary since new repos are created for new additional_dependencies
2023-01-23 19:58:48 -05:00
Anthony Sottile
2c39545d24
Merge pull request #2718 from jalessio/jamie/upgrade-to-ruby-build-v20221225
Upgrade to ruby-build v20221225
2023-01-23 17:57:14 -05:00
Jamie Alessio
14c38d18fc Upgrade to ruby-build v20221225 2023-01-21 11:05:13 -08:00
Anthony Sottile
50848aaca2
Merge pull request #2709 from pre-commit/test-lua
test lua directly
2023-01-18 00:12:28 -05:00
Anthony Sottile
a0fc6022d7
Merge pull request #2708 from pre-commit/r-tests
test r language directly
2023-01-17 23:57:44 -05:00
Anthony Sottile
f042540311 test lua directly 2023-01-17 23:43:31 -05:00
Anthony Sottile
7512e3b7e1 test r language directly 2023-01-17 23:25:00 -05:00
Anthony Sottile
6014ebd2e7
Merge pull request #2707 from pre-commit/dart-tests
test dart directly
2023-01-17 19:16:25 -05:00
Anthony Sottile
043565d28a test dart directly 2023-01-17 18:44:14 -05:00
Anthony Sottile
2bd853e96f
Merge pull request #2706 from pre-commit/perl-tests
test perl language directly
2023-01-17 18:01:31 -05:00
Anthony Sottile
d24055cb40 test perl language directly 2023-01-17 17:34:04 -05:00
Anthony Sottile
9a56f8dca0
Merge pull request #2705 from pre-commit/speed-up-r-tests
speed up R unit tests
2023-01-17 14:51:00 -05:00
Anthony Sottile
f5a365c2c8
Merge pull request #2704 from pre-commit/swift-language-tests
test swift language directly
2023-01-17 14:25:47 -05:00
Anthony Sottile
966c67a832 speed up R unit tests 2023-01-17 14:16:13 -05:00
Anthony Sottile
c36f03cd2e test swift language directly 2023-01-17 13:51:06 -05:00
Anthony Sottile
a26b631aae
Merge pull request #2703 from pre-commit/conda-language-tests
test conda language directly
2023-01-17 13:35:46 -05:00
Anthony Sottile
f1b5f66374 test conda language directly 2023-01-17 13:05:49 -05:00
Anthony Sottile
0316676fdc
Merge pull request #2702 from pre-commit/coursier-additional-deps
coursier: additional_dependencies support
2023-01-17 10:31:22 -05:00
Anthony Sottile
70bfd76ced coursier: additional_dependencies support 2023-01-17 09:59:04 -05:00
Anthony Sottile
59ed51a309
Merge pull request #2701 from pre-commit/run-hook-no-Hook
adjust the run_hook api to no longer take Hook
2023-01-16 17:11:10 -05:00
Anthony Sottile
628c876b2d adjust the run_hook api to no longer take Hook 2023-01-16 16:34:01 -05:00
Anthony Sottile
48ae18a2cb
Merge pull request #2700 from pre-commit/in-env-api
make in_env part of the language api
2023-01-16 16:18:18 -05:00
Anthony Sottile
ae34a962d7 make in_env part of the language api 2023-01-16 15:36:29 -05:00
Anthony Sottile
bcf0230772
Merge pull request #2699 from pre-commit/local-no-git
the local repo no longer needs to be a git repo
2023-01-15 10:30:28 -05:00
Anthony Sottile
37685a7f42 the local repo no longer needs to be a git repo 2023-01-15 09:56:30 -05:00
Anthony Sottile
87ab767175
Merge pull request #2651 from taoufik07/golang_playground
Make Golang a first class language
2023-01-13 13:14:41 -05:00
taoufik07
9afd63948e Make Go a first class language 2023-01-13 12:42:57 -05:00
Anthony Sottile
ceb429b253
Merge pull request #2686 from pre-commit/migrate-config-invalid-yaml
eagerly catch invalid yaml in migrate-config
2023-01-09 13:05:51 -05:00
Anthony Sottile
619f2bf5a9 eagerly catch invalid yaml in migrate-config 2023-01-09 12:31:05 -05:00
Anthony Sottile
dc667ab9fb
Merge pull request #2677 from taoufik07/fix_cmd_norm_env
Fix command normalization when a custom env is passed
2023-01-06 10:03:08 -05:00
taoufik07
bf1a1fa5fd Fix command normalization when a custom env is passed 2023-01-06 09:27:49 -05:00
Anthony Sottile
0dbc154380
Merge pull request #2672 from taoufik07/remove_gopath_special_build
Remove `GOPATH` special build
2023-01-02 19:32:08 -05:00
Anthony Sottile
83e64e2071
Merge pull request #2673 from pre-commit/split-util
add pre_commit.yaml module
2023-01-02 19:15:57 -05:00
Anthony Sottile
e1567b6148
Merge pull request #2674 from pre-commit/revert-2671-simplify-state
Revert "simplify install state"
2023-01-02 19:09:16 -05:00
taoufik07
60a42e9419 Remove GOPATH special build 2023-01-02 18:53:14 -05:00
Anthony Sottile
8529a0c1d3 add pre_commit.yaml module 2023-01-02 18:42:34 -05:00
Anthony Sottile
990643c1e0
Revert "simplify install state" 2023-01-02 18:39:42 -05:00
Anthony Sottile
978e26c544
Merge pull request #2671 from pre-commit/simplify-state
simplify install state
2023-01-02 17:30:43 -05:00
Anthony Sottile
0920cb33ee simplify install state
the additional bookkeeping has been unnecessary since b827694520

unfortunately this will cause a rebuild of all hooks in order to be
forward/backward compatible -- shrugs
2023-01-02 16:00:27 -05:00
Anthony Sottile
c787efd558
Merge pull request #2669 from pre-commit/env_dir
simplify environment_dir
2023-01-01 21:43:32 -05:00
Anthony Sottile
05c8911363 simplify environment_dir 2023-01-01 21:11:56 -05:00
Anthony Sottile
10f835c501
Merge pull request #2668 from pre-commit/clean-on-failure
move clean_path_on_failure out of each hook install
2023-01-01 20:31:02 -05:00
Anthony Sottile
d05b7888ab move clean_path_on_failure out of each hook install 2023-01-01 20:04:58 -05:00
Anthony Sottile
0224be8194
Merge pull request #2667 from pre-commit/env-dir-always-non-null
remove None overload for environment_dir
2023-01-01 19:52:48 -05:00
Anthony Sottile
3d09b66c6b
Merge pull request #2666 from pre-commit/r-dont-use-src
avoid using hook.src in R language
2023-01-01 19:34:22 -05:00
Anthony Sottile
f0baffb01f remove None overload for environment_dir 2023-01-01 19:20:40 -05:00
Anthony Sottile
8e57e8075d avoid using hook.src in R language
this wasn't meant to be read -- hook.prefix works fine for local too
2023-01-01 19:02:20 -05:00
Anthony Sottile
017fa5c0b8
Merge pull request #2665 from pre-commit/move-parse-version
move parse_version to pre_commit.clientlib
2023-01-01 17:51:11 -05:00
Anthony Sottile
0cec5bd6f0
Merge pull request #2664 from pre-commit/special-rmtree-no-longer-needed
special rmtree is not needed for TemporaryDirectory in 3.8+
2023-01-01 17:51:05 -05:00
Anthony Sottile
5425c754a0 move parse_version to pre_commit.clientlib 2023-01-01 17:17:00 -05:00
Anthony Sottile
0a0754e44a special rmtree is not needed for TemporaryDirectory in 3.8+ 2023-01-01 17:12:28 -05:00
Anthony Sottile
092e9a50ae
Merge pull request #2662 from pre-commit/r-default-gha
r is installed by default on GHA
2022-12-30 01:10:13 -05:00
Anthony Sottile
cddaa0dddc r is installed by default on GHA 2022-12-29 23:48:34 -05:00
Anthony Sottile
21407882fe
Merge pull request #2661 from pre-commit/gha
azure pipelines -> github actions
2022-12-29 22:48:25 -05:00
Anthony Sottile
887c5e1142 azure pipelines -> github actions 2022-12-29 22:18:31 -05:00
Anthony Sottile
848a73ed40
Merge pull request #2658 from pre-commit/remove-pre-commit-validate
remove pre-commit-validate-config and pre-commit-validate-manifest
2022-12-27 13:53:10 -05:00
Anthony Sottile
4a50859936 remove pre-commit-validate-config and pre-commit-validate-manifest 2022-12-27 13:05:30 -05:00
Anthony Sottile
d33df92add
Merge pull request #2602 from pre-commit/mypy-modules-as-protocols
use modules as protocols
2022-12-27 13:04:48 -05:00
Anthony Sottile
def3fa3929
Merge pull request #2657 from pre-commit/remove-sha-support
remove support for sha to specify rev
2022-12-27 12:13:26 -05:00
Anthony Sottile
12a979ea75
Merge pull request #2656 from pre-commit/remove-list-format
remove support for top-level list format
2022-12-27 12:09:42 -05:00
Anthony Sottile
40e69ce8e3 use modules as protocols 2022-12-27 11:46:11 -05:00
Anthony Sottile
7daceb083b
Merge pull request #2655 from pre-commit/drop-py37
drop python<3.8
2022-12-27 11:46:01 -05:00
Anthony Sottile
ff3150d58a remove support for sha to specify rev 2022-12-27 11:29:00 -05:00
Anthony Sottile
0024484f5b remove support for top-level list format 2022-12-27 11:15:45 -05:00
Anthony Sottile
524a236072 drop python<3.8 2022-12-27 11:10:31 -05:00
Anthony Sottile
40c5bdad65 v2.21.0 2022-12-25 17:52:05 -05:00
Anthony Sottile
bb27ea32cd
Merge pull request #2642 from rkm/fix/dotnet-nuget-config
dotnet: ignore nuget source during tool install
2022-12-21 15:04:41 -05:00
Ruairidh MacLeod
c38e0c7ba8 dotnet: ignore nuget source during tool install 2022-12-21 14:26:13 -05:00
Anthony Sottile
bce513fac6
Merge pull request #2641 from rkm/fix/dotnet-tool-prefix
fix for dotnet hooks with prefixes
2022-12-21 14:13:14 -05:00
Ruairidh MacLeod
e904628830 fix dotnet hooks with prefixes 2022-12-21 13:35:19 -05:00
Anthony Sottile
d7b8b123e6
Merge pull request #2646 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-12-19 20:49:15 -05:00
pre-commit-ci[bot]
94b6178906
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v2.0.0 → v2.0.1](https://github.com/pre-commit/mirrors-autopep8/compare/v2.0.0...v2.0.1)
2022-12-20 00:30:07 +00:00
Anthony Sottile
b474a83463
Merge pull request #2643 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-12-12 21:22:38 -05:00
pre-commit-ci[bot]
a179808bfe
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v2.3.0 → v2.4.0](https://github.com/asottile/add-trailing-comma/compare/v2.3.0...v2.4.0)
- [github.com/asottile/pyupgrade: v3.3.0 → v3.3.1](https://github.com/asottile/pyupgrade/compare/v3.3.0...v3.3.1)
2022-12-13 00:40:31 +00:00
Anthony Sottile
3aa6206e4f
Merge pull request #2605 from lorenzwalthert/r/fix-exe
Adapt extension of R executable depending on os
2022-12-12 14:28:54 -05:00
Anthony Sottile
04225fec72
Merge pull request #2628 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-12-12 13:45:07 -05:00
Lorenz Walthert
52948f610c When R executable is an explicit path, we need to appene .exe on Windows 2022-12-12 13:21:55 -05:00
pre-commit-ci[bot]
6ab7fc25d5 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.2.2 → v3.3.0](https://github.com/asottile/pyupgrade/compare/v3.2.2...v3.3.0)
2022-12-12 13:21:08 -05:00
Anthony Sottile
f9b28cc2b0
Merge pull request #2634 from pre-commit/fix-ci
fix CI
2022-12-12 13:02:24 -05:00
Anthony Sottile
b00c31cf9e use a newer version of ruby which builds cleanly 2022-12-12 12:22:39 -05:00
Anthony Sottile
8cc3a6d8aa passenv is stupid anyway 2022-12-10 23:45:04 -05:00
Anthony Sottile
b92fe01755 force the -p branch to run for language: python under test 2022-12-10 23:33:20 -05:00
Anthony Sottile
92c70766fd fix rust coverage on windows
it's a complete mystery why this isn't needed on other platforms, the branch is legitimately uncovered there
2022-12-06 17:36:57 -05:00
Anthony Sottile
0b45ecc8a4 remove python 2.x cross version tests 2022-12-06 17:36:57 -05:00
Anthony Sottile
46c64efd9d update .net framework target 2022-12-06 15:00:06 -05:00
Anthony Sottile
6c524f7a55 fix rust platform detection on windows 2022-12-06 13:10:12 -05:00
Anthony Sottile
5becd50974 update swift for jammy 2022-12-06 13:06:23 -05:00
Anthony Sottile
cb0bcfd67f
Merge pull request #2618 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-11-28 18:43:03 -08:00
pre-commit-ci[bot]
df7bcf78c3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.3.0 → v4.4.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.3.0...v4.4.0)
- [github.com/PyCQA/flake8: 5.0.4 → 6.0.0](https://github.com/PyCQA/flake8/compare/5.0.4...6.0.0)
2022-11-29 01:09:52 +00:00
Anthony Sottile
50c217964b
remove obsolete comment 2022-11-27 16:30:58 -05:00
Anthony Sottile
46f7117753
Merge pull request #2601 from pre-commit/all-repos_autofix_no-implicit-optional
remove no_implicit_optional
2022-11-22 08:41:28 -05:00
Anthony Sottile
5698781c78
Merge pull request #2608 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-11-21 19:57:42 -05:00
pre-commit-ci[bot]
391d05e2f3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.990 → v0.991](https://github.com/pre-commit/mirrors-mypy/compare/v0.990...v0.991)
2022-11-21 23:11:57 +00:00
Anthony Sottile
318296d8c5 remove no_implicit_optional
this is the default in mypy 0.990

Committed via https://github.com/asottile/all-repos
2022-11-16 19:19:49 -05:00
Anthony Sottile
6a661f8453
Merge pull request #2595 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-11-16 19:07:27 -05:00
pre-commit-ci[bot]
371b4fc1fd
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v3.2.0 → v3.2.2](https://github.com/asottile/pyupgrade/compare/v3.2.0...v3.2.2)
- [github.com/pre-commit/mirrors-mypy: v0.982 → v0.990](https://github.com/pre-commit/mirrors-mypy/compare/v0.982...v0.990)
2022-11-14 23:36:47 +00:00
Anthony Sottile
1f59f4cba8
Merge pull request #2590 from m-rsha/add-no-ext-diff
Add `--no-ext-diff` to `git diff` call
2022-11-10 21:55:56 -05:00
marsha
4399c2dbc6 Add --no-ext-diff to git diff call 2022-11-10 20:09:56 -06:00
Anthony Sottile
5009f57279
Merge pull request #2576 from mishaschwartz/update-ruby-build-binary
Update ruby-build to 20220710 to ensure that the correct openssl version is used
2022-11-07 20:20:11 -05:00
mishaschwartz
97ad4f89ec ruby: update ruby-build to 20220710 to ensure that the correct openssl version is used 2022-11-07 18:39:24 -05:00
Anthony Sottile
3ca9ea7b98
Merge pull request #2580 from m-rsha/diff-filter
Change `intent_to_add_files` from using `git status` to `git diff`
2022-11-02 20:30:01 -04:00
marsha
4bca29ee2c Change intent_to_add_files from using git status to git diff 2022-11-02 18:59:36 -05:00
Anthony Sottile
5840635baa
Merge pull request #2573 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-10-31 16:32:48 -07:00
pre-commit-ci[bot]
3b3cf8c1f1
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.1.0 → v2.2.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.1.0...v2.2.0)
- [github.com/asottile/reorder_python_imports: v3.8.5 → v3.9.0](https://github.com/asottile/reorder_python_imports/compare/v3.8.5...v3.9.0)
- [github.com/asottile/pyupgrade: v3.1.0 → v3.2.0](https://github.com/asottile/pyupgrade/compare/v3.1.0...v3.2.0)
- [github.com/pre-commit/mirrors-autopep8: v1.7.0 → v2.0.0](https://github.com/pre-commit/mirrors-autopep8/compare/v1.7.0...v2.0.0)
2022-10-31 23:27:34 +00:00
Anthony Sottile
0827de1864
Merge pull request #2569 from m-rsha/cmd-retcode-to-check
Change `cmd_output_b`s `retcode` arg to a boolean `check`
2022-10-30 14:24:10 -07:00
marsha
42102a1bfd Remove expected_returncode from CalledProcessError 2022-10-30 15:31:45 -05:00
marsha
84b38f7b89 Change cmd_output_bs retcode arg to a boolean check 2022-10-30 14:49:42 -05:00
Anthony Sottile
71925c47ea
Merge pull request #2568 from m-rsha/cargler-bargler
Change Rust to install environment with `cargo add` over `toml`
2022-10-28 23:13:36 -04:00
marsha
e703982de4 Change Rust to install environment with cargo add over toml 2022-10-28 21:32:52 -05:00
Anthony Sottile
5c9e844104
Merge pull request #2564 from mattp-/main
allow GIT_ASKPASS as a pass through env var
2022-10-27 16:39:14 -04:00
Matt Phillips
8ebb7ae2f5 add GIT_ASKPASS as a passthrough env var
documented via man gitcredentials,  it is used to provide a script/input
for git to fetch creds in a no-tty usecase.
used among other things by jenkins to pass credentials down to git for
authentication.

1e3488a730/README.adoc (git-bindings)
9429e7d05d/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java (L130)
2022-10-27 15:55:31 -04:00
Anthony Sottile
7ac2dbeee0
Merge pull request #2555 from pre-commit/fix-tests
fix tests for submodules for CVE-2022-39253
2022-10-22 15:06:31 -07:00
Anthony Sottile
0fe7a0baa6
Merge pull request #2460 from lorenzwalthert/binary-additional-deps
Enforce binary installs also for dependencies in R
2022-10-22 11:28:13 -07:00
Anthony Sottile
bc96b0bcf6 fix tests for submodules for CVE-2022-39253 2022-10-22 09:34:43 -07:00
Anthony Sottile
0239b27f4f
Merge pull request #2552 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-10-17 19:32:11 -04:00
pre-commit-ci[bot]
f9532fb59a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v2.0.0 → v2.1.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.0.0...v2.1.0)
- [github.com/asottile/reorder_python_imports: v3.8.4 → v3.8.5](https://github.com/asottile/reorder_python_imports/compare/v3.8.4...v3.8.5)
2022-10-17 23:10:12 +00:00
Anthony Sottile
529b1a60e9
Merge pull request #2534 from Holzhaus/rust-as-1st-class-language
Rust as 1st class language
2022-10-10 17:35:21 -07:00
Jan Holthuis
eb469c756d Rust as 1st class language 2022-10-10 20:05:36 -04:00
Anthony Sottile
cd38fa3507
Merge pull request #2547 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-10-10 17:03:25 -07:00
pre-commit-ci[bot]
3d4f6db2a0
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v3.8.3 → v3.8.4](https://github.com/asottile/reorder_python_imports/compare/v3.8.3...v3.8.4)
- [github.com/asottile/pyupgrade: v2.38.2 → v3.1.0](https://github.com/asottile/pyupgrade/compare/v2.38.2...v3.1.0)
- [github.com/pre-commit/mirrors-mypy: v0.981 → v0.982](https://github.com/pre-commit/mirrors-mypy/compare/v0.981...v0.982)
2022-10-10 23:49:52 +00:00
Anthony Sottile
028efcbd87
Merge pull request #2539 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-10-03 19:13:54 -04:00
pre-commit-ci[bot]
68be295b75
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.971 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.971...v0.981)
2022-10-03 22:51:41 +00:00
Anthony Sottile
495b5991cf
"yes" is not a valid search 2022-09-29 16:51:19 -04:00
Anthony Sottile
653d15504e
Merge pull request #2528 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-09-26 19:21:58 -04:00
Anthony Sottile
3610087fab
Merge pull request #2527 from chrisRedwine/remove-extraneous-raw-string-literal
remove extraneous raw string literal in test
2022-09-26 18:59:37 -04:00
pre-commit-ci[bot]
404f2dccd5
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v3.8.2 → v3.8.3](https://github.com/asottile/reorder_python_imports/compare/v3.8.2...v3.8.3)
- [github.com/asottile/add-trailing-comma: v2.2.3 → v2.3.0](https://github.com/asottile/add-trailing-comma/compare/v2.2.3...v2.3.0)
- [github.com/asottile/pyupgrade: v2.38.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.38.0...v2.38.2)
2022-09-26 22:58:40 +00:00
chrisRedwine
6d5de9feaf remove extraneous raw string literal in test 2022-09-26 17:53:14 -05:00
Anthony Sottile
102fbb21ce
Merge pull request #2524 from chrisRedwine/fix-local-regex-warnings
extend warning if globs are used instead of regex to local hooks
2022-09-26 12:52:13 -04:00
chrisRedwine
a95f488e71 extend warning if globs are used instead of regex to local hooks 2022-09-25 11:56:04 -05:00
Anthony Sottile
b1de3338ef
Merge pull request #2519 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-09-19 18:35:13 -05:00
pre-commit-ci[bot]
fb608ee1b4
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.37.3 → v2.38.0](https://github.com/asottile/pyupgrade/compare/v2.37.3...v2.38.0)
2022-09-19 22:48:22 +00:00
Anthony Sottile
3fe38dff05
Merge pull request #2485 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-08-15 17:23:45 -04:00
Anthony Sottile
51e6d655b8
Merge pull request #2484 from pre-commit/allow-files-when-unmerged
allow `pre-commit run --files ...` against unmerged files
2022-08-15 17:23:40 -04:00
pre-commit-ci[bot]
7a62bf7be2
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v1.6.0 → v1.7.0](https://github.com/pre-commit/mirrors-autopep8/compare/v1.6.0...v1.7.0)
2022-08-15 21:15:11 +00:00
Anthony Sottile
2405caa352 allow pre-commit run --files ... against unmerged files 2022-08-15 13:46:17 -04:00
Anthony Sottile
6740a1795c
Merge pull request #2480 from imc-trading/fix-skip-alias
respect aliases in SKIP when installing environments
2022-08-11 16:50:15 -04:00
Mark Korondi
587c6b97e7
respect aliases in SKIP when installing environments 2022-08-11 09:30:39 +02:00
Anthony Sottile
49f95b9ef3
Merge pull request #2475 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-08-08 18:52:59 -04:00
pre-commit-ci[bot]
317c9e037a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 5.0.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/5.0.2...5.0.4)
2022-08-08 22:24:53 +00:00
Anthony Sottile
9c55cc3954
Merge pull request #2474 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-08-01 20:06:48 -04:00
pre-commit-ci[bot]
d4b73c9e88 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2022-08-01 22:41:21 +00:00
pre-commit-ci[bot]
3e920b5ba7
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v1.20.2 → v2.0.0](https://github.com/asottile/setup-cfg-fmt/compare/v1.20.2...v2.0.0)
- [github.com/asottile/pyupgrade: v2.37.2 → v2.37.3](https://github.com/asottile/pyupgrade/compare/v2.37.2...v2.37.3)
- [github.com/PyCQA/flake8: 4.0.1 → 5.0.2](https://github.com/PyCQA/flake8/compare/4.0.1...5.0.2)
2022-08-01 22:40:58 +00:00
Anthony Sottile
77d9b4651f
Merge pull request #2466 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-07-25 19:57:05 -04:00
Anthony Sottile
9ee8c51edc
Merge pull request #2467 from pre-commit/asottile-patch-1
require a version of virtualenv which is less broken in 3.10+
2022-07-25 19:56:57 -04:00
Anthony Sottile
f4e658fc6e
require a version of virtualenv which is less broken in 3.10+ 2022-07-25 19:29:09 -04:00
pre-commit-ci[bot]
a8bfaab091
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v1.20.1 → v1.20.2](https://github.com/asottile/setup-cfg-fmt/compare/v1.20.1...v1.20.2)
- [github.com/asottile/reorder_python_imports: v3.8.1 → v3.8.2](https://github.com/asottile/reorder_python_imports/compare/v3.8.1...v3.8.2)
- [github.com/asottile/pyupgrade: v2.37.1 → v2.37.2](https://github.com/asottile/pyupgrade/compare/v2.37.1...v2.37.2)
- [github.com/pre-commit/mirrors-mypy: v0.961 → v0.971](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.971)
2022-07-25 21:46:05 +00:00
Anthony Sottile
c1e0836d6b
Merge pull request #2459 from pre-commit/relative-commit-msg-filename
adjust relative --commit-msg-filename if in subdir
2022-07-23 16:49:07 -04:00
Lorenz Walthert
a568f3c818 enforce binary installs also for dependencies of R packages
Similar problem seems to be found in https://github.com/r-lib/devtools/issues/1724
2022-07-12 22:47:19 +01:00
Lorenz Walthert
7c14405f8b just bump failing CI 2022-07-12 22:44:31 +01:00
Anthony Sottile
db51d3009f adjust relative --commit-msg-filename if in subdir 2022-07-12 14:08:57 -04:00
Anthony Sottile
bdc08d8285
Merge pull request #2455 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-07-11 18:01:24 -04:00
pre-commit-ci[bot]
0cef48edbf
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v3.3.0 → v3.8.1](https://github.com/asottile/reorder_python_imports/compare/v3.3.0...v3.8.1)
- [github.com/asottile/pyupgrade: v2.34.0 → v2.37.1](https://github.com/asottile/pyupgrade/compare/v2.34.0...v2.37.1)
2022-07-11 21:25:15 +00:00
Anthony Sottile
78a2d867fe v2.20.0 2022-07-10 20:55:02 -04:00
Anthony Sottile
e3dc5b7baf
Merge pull request #2454 from pre-commit/asottile-patch-1
remove warnings checks
2022-07-10 14:49:44 -04:00
Anthony Sottile
ebce88c13d
remove warnings checks
this wasn't all that useful -- and most of it was for checking python 2 things
2022-07-10 14:20:14 -04:00
Anthony Sottile
d6cc8a1419
Merge pull request #2453 from hroncok/python3.11
Tests: Adjust traceback regexes to allow Python 3.11+ ^^^^^^^
2022-07-09 20:30:59 -04:00
Miro Hrončok
901e831313 Tests: Adjust traceback regexes to allow Python 3.11+ ^^^^^^^
Fixes https://github.com/pre-commit/pre-commit/issues/2451
2022-07-10 02:03:56 +02:00
Anthony Sottile
98bb7e6630
Merge pull request #2440 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-07-04 18:33:56 -04:00
Anthony Sottile
706d1e9929
Merge pull request #2439 from pre-commit/all-repos_autofix_type-checking
remove imports from TYPE_CHECKING (py37+)
2022-07-04 18:33:51 -04:00
pre-commit-ci[bot]
3ebd101eb5
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v3.1.0 → v3.3.0](https://github.com/asottile/reorder_python_imports/compare/v3.1.0...v3.3.0)
2022-07-04 21:58:49 +00:00
Anthony Sottile
d8b59300ce remove imports from TYPE_CHECKING (py37+)
Committed via https://github.com/asottile/all-repos
2022-07-04 17:57:38 -04:00
Anthony Sottile
170335cbb6
Merge pull request #2429 from pre-commit/remove-config-option-when-unused
remove unused --config options from commands which don't use it
2022-06-22 23:24:27 -04:00
Anthony Sottile
53643def07 remove unused --config options from commands which don't use it 2022-06-22 16:06:15 -07:00
Anthony Sottile
c69ae26c1f
Merge pull request #2421 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-06-13 18:47:43 -04:00
pre-commit-ci[bot]
efc1d059fa
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.2.0 → v4.3.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.2.0...v4.3.0)
- [github.com/asottile/pyupgrade: v2.32.1 → v2.34.0](https://github.com/asottile/pyupgrade/compare/v2.32.1...v2.34.0)
- [github.com/pre-commit/mirrors-mypy: v0.960 → v0.961](https://github.com/pre-commit/mirrors-mypy/compare/v0.960...v0.961)
2022-06-13 21:57:06 +00:00
Anthony Sottile
4738d06e71
Merge pull request #2407 from M-Whitaker/main
Expose prepare-commit-msg arguments as environment vars
2022-06-11 14:56:13 -04:00
Matt Whitaker
702ebf402c Expose prepare-commit-msg arguments as environment vars 2022-06-11 14:25:55 -04:00
Anthony Sottile
44cb80f74a
Merge pull request #2410 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-05-30 17:09:06 -04:00
pre-commit-ci[bot]
50589386af
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.950 → v0.960](https://github.com/pre-commit/mirrors-mypy/compare/v0.950...v0.960)
2022-05-30 20:32:51 +00:00
Anthony Sottile
fb0ccf3546
correct one slight inaccuracy in language docs 2022-05-26 09:43:30 -04:00
Anthony Sottile
e93c1c6f27
Merge pull request #2393 from gaige/set-default-branch-for-tests-2391
force default branch name for tests
2022-05-14 22:21:07 -04:00
Gaige B. Paulsen
34e97023f4 force default branch name for tests 2022-05-14 18:40:37 -07:00
Anthony Sottile
9eccd9c35b
Merge pull request #2390 from gaige/main
Switch pty use to fix solaris
2022-05-14 09:38:52 -04:00
Gaige B. Paulsen
a84136d070 Switch pty use to fix solaris
Use the child instead of parent fd when manipulating pty for color.
2022-05-14 09:15:03 +00:00
Anthony Sottile
3cdc6c9d81
Merge pull request #2387 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-05-09 14:10:50 -07:00
pre-commit-ci[bot]
323fd0d188
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.32.0 → v2.32.1](https://github.com/asottile/pyupgrade/compare/v2.32.0...v2.32.1)
2022-05-09 20:28:33 +00:00
Anthony Sottile
fd78116f5c
Merge pull request #2384 from narpfel/gem-no-user-install
Force gem installation into `GEM_HOME`
2022-05-07 14:28:31 -07:00
Paul Gey
a54391e96f Force gem installation into GEM_HOME
When `--user-install` is set in the gemrc config file, `gem` ignores
`GEM_HOME`. `--no-user-install` prevents this behaviour.
2022-05-07 20:44:02 +02:00
Anthony Sottile
cc9d950601 v2.19.0 2022-05-05 06:54:43 -07:00
Anthony Sottile
96bf685380
fix non-unique id 2022-05-04 21:22:24 -04:00
Anthony Sottile
1b8665571e
Merge pull request #2375 from pre-commit/search-the-tracker
add search term required input to issue template
2022-05-04 18:21:39 -07:00
Anthony Sottile
af467017c2 add search term required input to issue template 2022-05-04 17:58:31 -07:00
Anthony Sottile
bec1728133
Merge pull request #2370 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-05-02 16:22:55 -04:00
pre-commit-ci[bot]
81129cefa5
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v3.0.1 → v3.1.0](https://github.com/asottile/reorder_python_imports/compare/v3.0.1...v3.1.0)
- [github.com/pre-commit/mirrors-mypy: v0.942 → v0.950](https://github.com/pre-commit/mirrors-mypy/compare/v0.942...v0.950)
2022-05-02 20:18:58 +00:00
Anthony Sottile
7f189260e6
Merge pull request #2362 from pre-commit/deprecate-separate-entry-points
deprecate pre-commit-validate-{config,manifest}
2022-04-24 20:03:35 -04:00
Anthony Sottile
3929fe4a63 upgrade CI to ubuntu-latest / windows-latest 2022-04-24 19:10:09 -04:00
Anthony Sottile
777ffdd692 deprecate pre-commit-validate-{config,manifest} 2022-04-24 19:08:47 -04:00
Anthony Sottile
e1ce4c0bf3
Merge pull request #2349 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-04-18 16:24:09 -04:00
pre-commit-ci[bot]
18f1cdf470
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v2.2.2 → v2.2.3](https://github.com/asottile/add-trailing-comma/compare/v2.2.2...v2.2.3)
2022-04-18 19:50:30 +00:00
Anthony Sottile
f7940112a2
Merge pull request #2342 from jalessio/upgrade-to-ruby-build-20220412
Update ruby-build to v20220412
2022-04-17 10:44:37 -04:00
Jamie Alessio
392bc33466 Update ruby-build to v20220412 2022-04-17 07:12:48 -07:00
Anthony Sottile
89a50ed64d
Merge pull request #2348 from pre-commit/healthy-info
add additional info to healthy-after-install check
2022-04-16 17:16:19 -04:00
Anthony Sottile
07554e9525 add additional info to healthy-after-install check 2022-04-16 16:46:28 -04:00
Anthony Sottile
2562c7f796
Merge pull request #2345 from wwade/main
pre-push: fix stdin line splitting when <local ref> has whitespace
2022-04-14 18:17:56 -04:00
Wade Carpenter
feb0d34213
pre-push: fix stdin line splitting when <local ref> has whitespace
From the `pre-push.sample` file:

> Information about the commits which are being pushed is supplied as
> lines to the standard input in the form:
>
>   <local ref> <local sha1> <remote ref> <remote sha1>

When `<local ref>` is not simply a branch name, but a more general
ref (see git-rev-parse(1)), it could contain whitespace, and that
breaks the split() call that expected only 3 spaces in the line.

Changed to use `rsplit(maxsplit=3)` since only the <local ref> is
likely to have embedded whitespace.

Added a new test case for the same.
2022-04-14 14:27:46 -07:00
Anthony Sottile
f9473e756d
Merge pull request #2343 from pre-commit/golang-1-18
fix tests for golang 1.18
2022-04-13 18:25:13 -04:00
Anthony Sottile
b952c99898 fix tests for golang 1.18 2022-04-13 17:52:55 -04:00
Anthony Sottile
7189f340a9
Merge pull request #2339 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-04-11 20:01:17 -04:00
pre-commit-ci[bot]
e3ae0664bb
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.1.0 → v4.2.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.1.0...v4.2.0)
- [github.com/asottile/pyupgrade: v2.31.1 → v2.32.0](https://github.com/asottile/pyupgrade/compare/v2.31.1...v2.32.0)
2022-04-11 20:54:45 +00:00
Anthony Sottile
ecd7363676
Merge pull request #2332 from WallucePinkham/main
Handling multiple outputs from dotnet pack
2022-04-07 14:13:54 -04:00
Walluce Pinkham
9b3df4b90e Handling multiple outputs from dotnet pack 2022-04-07 13:16:56 -04:00
Anthony Sottile
26a3e6f9ff
Merge pull request #2329 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-04-04 16:03:56 -04:00
pre-commit-ci[bot]
c8ce94b40e
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v1.20.0 → v1.20.1](https://github.com/asottile/setup-cfg-fmt/compare/v1.20.0...v1.20.1)
- [github.com/asottile/add-trailing-comma: v2.2.1 → v2.2.2](https://github.com/asottile/add-trailing-comma/compare/v2.2.1...v2.2.2)
2022-04-04 20:00:42 +00:00
Anthony Sottile
0276e25f71 v2.18.1 2022-04-02 21:32:54 -04:00
Anthony Sottile
f5af0a9ff4
Merge pull request #2324 from pre-commit/local-hooks-py27
fix python 2.7 `repo: local` hooks
2022-04-02 21:31:34 -04:00
Anthony Sottile
1722448c3b fix python 2.7 repo: local hooks 2022-04-02 21:19:13 -04:00
Anthony Sottile
c5a39ae77e v2.18.0 2022-04-02 19:36:45 -04:00
Anthony Sottile
3aa2ce89e8
Merge pull request #2323 from pre-commit/move-try-slightly
move patch discarding inside `try` for staged_files_only
2022-04-02 19:23:04 -04:00
Anthony Sottile
a138c85e64 move patch discarding inside try for staged_files_only
there's a rare race outlined in #2287
2022-04-02 16:24:57 -04:00
Anthony Sottile
7602abc3cf
Merge pull request #2322 from pre-commit/default-install-hook-types
implement default_install_hook_types
2022-04-02 15:36:59 -04:00
Anthony Sottile
e11163d010
Merge pull request #2301 from jeff-m-sullivan/rscript-path
use Rscript path relative to $R_HOME/bin/...
2022-04-02 15:30:52 -04:00
Anthony Sottile
d65016042b
Merge pull request #2252 from daschuer/worktree_fix
Use the correct .git path in case of worktrees.
2022-04-02 15:30:45 -04:00
Anthony Sottile
fd0177ae3a implement default_install_hook_types
this implements a configurable fallback for the default value of `pre-commit install`
2022-04-02 15:11:31 -04:00
Daniel Schürmann
ba132f0200 Split get_git_dir() into get_git_dir() and get_git_common_dir()
This fixes the conflicted state check when using work trees. #1972
2022-04-02 15:07:22 -04:00
Jeff Sullivan
764a0db68e use Rscript path relative to $R_HOME/bin/...
Co-authored-by: Lorenz Walthert <lorenz.walthert@icloud.com>
2022-04-02 14:22:29 -04:00
Anthony Sottile
934afb85a4
Merge pull request #2319 from jalessio/jamie/upgrade-rbenv-and-ruby-build
Update ruby-build to latest available (v20220324)
2022-03-31 14:35:15 -04:00
Jamie Alessio
9021fa15dd Update ruby-build to latest available 2022-03-31 14:05:30 -04:00
Anthony Sottile
b97bb1809f
Merge pull request #2312 from mblayman/multiple-tags
Pick a tag if multiple tags exist on a SHA.
2022-03-31 11:13:45 -04:00
Matt Layman
e8b46c1b16 Pick a tag if multiple tags exist on a SHA.
Fixes #2311
2022-03-31 10:37:51 -04:00
Anthony Sottile
a522507020
Merge pull request #2315 from pre-commit/error-messages
include the configured value in the language_version / additional_dependencies error
2022-03-30 12:54:37 -04:00
Anthony Sottile
2188c0fd2c include the configured value in the language_version / additional_dependencies error 2022-03-30 11:14:00 -04:00
Anthony Sottile
db44ad3022
Merge pull request #2304 from pre-commit/all-repos_autofix_reorder-pre-commit-config
reorder pre-commit config
2022-03-25 15:01:02 -04:00
Anthony Sottile
3b98040623 fix pre-commit issues 2022-03-25 14:31:33 -04:00
Anthony Sottile
97419b34de reorder pre-commit config
Committed via https://github.com/asottile/all-repos
2022-03-25 14:12:02 -04:00
Anthony Sottile
98b9b70aa4
Merge pull request #2302 from pre-commit/master-to-main
update master to main
2022-03-24 13:56:33 -04:00
Anthony Sottile
525191f34b update master to main 2022-03-24 13:52:25 -04:00
Anthony Sottile
354b900f15
Merge pull request #2297 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-03-21 19:03:59 -04:00
pre-commit-ci[bot]
28a5a28b39
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.940 → v0.941](https://github.com/pre-commit/mirrors-mypy/compare/v0.940...v0.941)
2022-03-21 22:31:22 +00:00
Anthony Sottile
4421cb9424
Merge pull request #2293 from Holzhaus/coursier-executable-names
coursier: Add support for both `cs` and `coursier` executable names
2022-03-17 19:05:17 -04:00
Jan Holthuis
678ef6b9fd coursier: Add support for both cs and coursier executable names
On some systems, the executable might be named `coursier` instead of
`cs`. For example, this is the case on Arch Linux when using the AUR
package, or when following the official instructions when installing the
JAR-based launcher:

  https://get-coursier.io/docs/cli-installation#jar-based-launcher
2022-03-17 22:25:22 +01:00
Anthony Sottile
da55e97df8
Merge pull request #2288 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-03-15 11:49:36 -04:00
Anthony Sottile
a8225a250b convince mypy that these are the same 2022-03-14 18:37:07 -04:00
pre-commit-ci[bot]
9516ed41aa
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.31.0 → v2.31.1](https://github.com/asottile/pyupgrade/compare/v2.31.0...v2.31.1)
- [github.com/asottile/reorder_python_imports: v2.7.1 → v3.0.1](https://github.com/asottile/reorder_python_imports/compare/v2.7.1...v3.0.1)
- [github.com/pre-commit/mirrors-mypy: v0.931 → v0.940](https://github.com/pre-commit/mirrors-mypy/compare/v0.931...v0.940)
2022-03-14 22:18:01 +00:00
Anthony Sottile
f5116bc88d
Merge pull request #2285 from pre-commit/all-repos_autofix_gitignore-cleanup
remove unneeded gitignore lines
2022-03-13 20:20:38 -04:00
Anthony Sottile
a85df8027b remove unneeded gitignore lines
- coverage-html: coverage>=6.2 writes a .gitignore file
- mypy_cache: mypy>=0.770 writes a .gitignore file
- pytest_cache: pytest>=3.8.1 writes a .gitignore file
- venv: virtualenv>=20.0.21 writes a .gitignore file

Committed via https://github.com/asottile/all-repos
2022-03-13 19:55:30 -04:00
Anthony Sottile
d525928665
Merge pull request #2272 from VincentBerthier/master
GIT_HTTP_PROXY_AUTHMETHOD kept in env variables
2022-03-05 18:26:51 -05:00
Anthony Sottile
2ed0eaa121
Merge pull request #2277 from lorenzwalthert/always-binary
Avoid build-time dependencies by prioritising binary over source dependencies for R
2022-03-05 18:26:34 -05:00
Lorenz Walthert
65755af7e3 inline options() to always install binaries 2022-03-05 21:04:01 +01:00
VincentBerthier
07f441584b
GIT_HTTP_PROXY_AUTHMETHOD kept in env variables 2022-03-04 20:18:27 +01:00
Anthony Sottile
e0e536b54e
Merge pull request #2266 from leetrout/patch-1
Fix typo in help docs for to-ref and from-ref
2022-03-02 18:09:02 -05:00
Lee Trout
e58bcb51fc
Fix typo in help docs for to-ref and from-ref 2022-03-02 17:33:11 -05:00
Anthony Sottile
7858ad066f
Merge pull request #2227 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-01-31 16:25:02 -05:00
pre-commit-ci[bot]
8e9202acb4
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/reorder_python_imports: v2.6.0 → v2.7.1](https://github.com/asottile/reorder_python_imports/compare/v2.6.0...v2.7.1)
2022-01-31 21:02:21 +00:00
Anthony Sottile
f1d2e6c289
Merge pull request #2216 from pre-commit/all-repos_autofix_flake8-typing-imports
upgrade flake8-typing-imports
2022-01-23 21:56:48 -05:00
Anthony Sottile
1112c9f5ce upgrade flake8-typing-imports
Committed via https://github.com/asottile/all-repos
2022-01-23 21:20:59 -05:00
Anthony Sottile
84372e0edc
Merge pull request #2215 from pre-commit/drop-py36
drop python 3.6 support
2022-01-18 19:29:54 -05:00
Anthony Sottile
04de6a2e57 drop python 3.6 support
python 3.6 reached end of life on 2021-12-23
2022-01-18 18:44:20 -05:00
Anthony Sottile
d3bdf1403d v2.17.0 2022-01-18 12:59:39 -05:00
Anthony Sottile
b22b313e4b
Merge pull request #2158 from mblayman/lua
Add Lua language support
2022-01-17 16:20:03 -05:00
Anthony Sottile
54331dca6f get lua version from luarocks itself 2022-01-17 15:46:36 -05:00
Matt Layman
3f8be7400d Add naive and untested version of Lua language support. 2022-01-17 13:43:38 -05:00
Anthony Sottile
7a305e5d9a
Merge pull request #2210 from pre-commit/git-version
add git version to error output
2022-01-16 12:42:43 -05:00
Anthony Sottile
c05f58b776 add git version to error output 2022-01-16 07:20:12 -08:00
Anthony Sottile
12b482345b
Merge pull request #2207 from xhochy/mamba
Add mamba support to `language: conda`
2022-01-15 17:57:13 -05:00
Uwe L. Korn
83aa65c429 Add mamba support to language: conda 2022-01-15 16:28:44 -05:00
Anthony Sottile
657e76ba77
Merge pull request #2205 from jalessio/jamie/upgrade-rbenv
Update rbenv / ruby-build versions
2022-01-15 16:19:59 -05:00
Jamie Alessio
428dc6e46e Update rbenv / ruby-build versions 2022-01-15 16:19:28 -05:00
Anthony Sottile
b944395d66
Merge pull request #2198 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-01-10 16:17:42 -05:00
Anthony Sottile
bba6cf4296 Revert "work around python/mypy#11852"
This reverts commit 83675fe768.
2022-01-10 15:35:33 -05:00
pre-commit-ci[bot]
a33773182e
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.930 → v0.931](https://github.com/pre-commit/mirrors-mypy/compare/v0.930...v0.931)
2022-01-10 20:21:20 +00:00
Anthony Sottile
445a2ef498
Merge pull request #2187 from pre-commit/always-sh-on-windows
always use #!/bin/sh on windows
2022-01-06 09:05:46 -05:00
Anthony Sottile
e3dc3f7934 always use #!/bin/sh on windows 2022-01-05 13:22:49 -05:00
Anthony Sottile
cccbc9d280
Merge pull request #2183 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2022-01-03 15:44:21 -05:00
pre-commit-ci[bot]
8be0a10e91
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v1.5.7 → v1.6.0](https://github.com/pre-commit/mirrors-autopep8/compare/v1.5.7...v1.6.0)
- [github.com/asottile/pyupgrade: v2.29.1 → v2.31.0](https://github.com/asottile/pyupgrade/compare/v2.29.1...v2.31.0)
2022-01-03 20:02:48 +00:00
Anthony Sottile
e97140e4d0
Merge pull request #2181 from pre-commit/forbid-meta-override-entry
forbid overriding `entry` for meta hooks
2021-12-31 21:00:44 -05:00
Anthony Sottile
d3b4f737b9 forbid overriding entry for meta hooks 2021-12-31 17:31:12 -08:00
Anthony Sottile
16f68254a8
Merge pull request #2177 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-12-27 19:08:23 -05:00
Anthony Sottile
83675fe768 work around python/mypy#11852 2021-12-27 18:32:56 -05:00
pre-commit-ci[bot]
d7ac975454
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.0.1 → v4.1.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.0.1...v4.1.0)
- [github.com/pre-commit/mirrors-mypy: v0.920 → v0.930](https://github.com/pre-commit/mirrors-mypy/compare/v0.920...v0.930)
2021-12-27 20:06:12 +00:00
Anthony Sottile
0248dd4a0b
Merge pull request #2170 from lorenzwalthert/fix-renv-in-wd
Make `language: r` work when there is already a renv in the working directory and `RENV_PROJECT` is set
2021-12-24 16:52:06 -05:00
Lorenz Walthert
1617692f12 no docs 2021-12-24 14:52:46 +01:00
Lorenz Walthert
b7331b653a unset renv project 2021-12-24 14:36:43 +01:00
Lorenz Walthert
ba496b8369 better r path detection 2021-12-24 14:01:18 +01:00
Anthony Sottile
44687a3cda
Merge pull request #2167 from pre-commit/dead
run dead, remove dead code
2021-12-22 16:34:39 -05:00
Anthony Sottile
42b0a263a6 run dead, remove dead code
via https://github.com/asottile/dead
2021-12-22 11:30:55 -08:00
Anthony Sottile
de177e8850
Merge pull request #2164 from pre-commit/py2-cleanup
minor py2 cleanup for sys.stderr.buffer
2021-12-20 22:03:16 -05:00
Anthony Sottile
3512e441f4 replace echo image with focal 2021-12-20 17:38:59 -05:00
Anthony Sottile
f637ac8603 minor py2 cleanup for sys.stderr.buffer 2021-12-20 17:01:51 -05:00
Anthony Sottile
bd787a9fcd
Merge pull request #2163 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-12-20 15:45:55 -05:00
pre-commit-ci[bot]
a781bfb063
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.910-1 → v0.920](https://github.com/pre-commit/mirrors-mypy/compare/v0.910-1...v0.920)
2021-12-20 19:42:45 +00:00
Anthony Sottile
c0d3b8e7d0
Merge pull request #2161 from schmir/use-go-install
Use 'go install' instead of 'go get'
2021-12-15 12:15:08 -05:00
Ralf Schmitt
379db4cb88 Use 'go install' instead of 'go get'
`go install` is the recommended way to install modules starting from go 1.16.
In go 1.18 `go get` cannot be used anymore to install packages [1]. go 1.18 is
not released yet.

[1] https://tip.golang.org/doc/go1.18#go-command
2021-12-15 10:05:59 +01:00
Anthony Sottile
097f2c8917
Merge pull request #2154 from kuviokelluja/master
fix: Add missing warning for regular expression with [\\/]
2021-12-05 14:44:48 -05:00
Tony Rintala
b5088ceca6 fix: regex lists to regex tuples 2021-12-05 01:35:43 +02:00
Tony Rintala
d4ffa5befb fix: Add missing warning for regular expression with [\\/]
test: Test case parameters for said regular expression

refactor: For-loop for regex warnings instead of multiple if statements

resolves #2151
2021-12-04 22:51:04 +02:00
Anthony Sottile
a737d5fe2f add setuptools to the zipapp. resolves #2122 2021-11-30 18:19:36 -05:00
Anthony Sottile
d91a4c47f3 v2.16.0 2021-11-30 18:16:47 -05:00
Anthony Sottile
3efc436d71
Merge pull request #2145 from pre-commit/all-repos_autofix_covdefaults-2-1
improve coverage pragmas with covdefaults 2.1
2021-11-29 21:09:33 -05:00
Anthony Sottile
270b539e8f improve coverage pragmas with covdefaults 2.1
Committed via https://github.com/asottile/all-repos
2021-11-29 20:45:40 -05:00
Anthony Sottile
f6547ac54e
Merge pull request #2138 from pre-commit/all-repos_autofix_gh-funding-default
Use org-default .github/FUNDING.yml
2021-11-25 11:12:04 -05:00
Anthony Sottile
c45b84bd39 Use org-default .github/FUNDING.yml
Committed via https://github.com/asottile/all-repos
2021-11-23 11:24:26 -05:00
Anthony Sottile
36e9514e03
Merge pull request #2136 from emzeat/fix/git_config_env
support gitconfig from env
2021-11-22 20:17:34 -05:00
Anthony Sottile
fbf964864d
Merge pull request #2134 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-11-22 20:17:26 -05:00
Marius Zwicker
4eb91cdd8e support gitconfig from env
Add exceptions to the git env so externally configured gitconfig
values set via GIT_CONFIG_KEY_<n>, GIT_CONFIG_VALUE_<n> and
GIT_CONFIG_COUNT get passed through.
2021-11-22 19:40:30 -05:00
pre-commit-ci[bot]
a064f248d7 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.29.0 → v2.29.1](https://github.com/asottile/pyupgrade/compare/v2.29.0...v2.29.1)
- [github.com/asottile/add-trailing-comma: v2.2.0 → v2.2.1](https://github.com/asottile/add-trailing-comma/compare/v2.2.0...v2.2.1)
- [github.com/asottile/setup-cfg-fmt: v1.19.0 → v1.20.0](https://github.com/asottile/setup-cfg-fmt/compare/v1.19.0...v1.20.0)
2021-11-22 19:36:24 -05:00
Anthony Sottile
b300116adc
Merge pull request #2137 from pre-commit/upgrade-perl-tidy
bump perltidy version
2021-11-22 19:35:58 -05:00
Anthony Sottile
b2a35414aa bump perltidy version 2021-11-22 18:43:47 -05:00
Anthony Sottile
cb40e9682e
Merge pull request #2115 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-11-01 16:05:53 -04:00
pre-commit-ci[bot]
141e18319a
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/setup-cfg-fmt: v1.18.0 → v1.19.0](https://github.com/asottile/setup-cfg-fmt/compare/v1.18.0...v1.19.0)
2021-11-01 19:35:28 +00:00
Anthony Sottile
58ae1140c3
Merge pull request #2114 from pre-commit/fix-indent
fix indent in hook-tmpl
2021-10-30 13:40:44 -04:00
Anthony Sottile
087541cb2d fix indent in hook-tmpl 2021-10-30 12:11:52 -04:00
Anthony Sottile
d300bcfb80
Merge pull request #2111 from pre-commit/silence
silence the output of `command -v`
2021-10-29 11:14:51 -04:00
Anthony Sottile
0b87867729 silence the output of command -v 2021-10-28 21:21:59 -07:00
Anthony Sottile
9b18686168
Merge pull request #2106 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-10-25 12:30:19 -07:00
pre-commit-ci[bot]
2b30fbcfd5
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/add-trailing-comma: v2.1.0 → v2.2.0](https://github.com/asottile/add-trailing-comma/compare/v2.1.0...v2.2.0)
2021-10-25 18:59:17 +00:00
Anthony Sottile
c6a1bc144a
Merge pull request #2104 from pre-commit/all-repos_autofix_exit-main-2
exit(main()) -> raise SystemExit(main()) pt2
2021-10-24 08:11:48 -07:00
Anthony Sottile
28cafc2273 exit(main()) -> raise SystemExit(main()) pt2
Committed via https://github.com/asottile/all-repos
2021-10-24 07:19:57 -07:00
Anthony Sottile
26a05b547e
Merge pull request #2103 from pre-commit/all-repos_autofix_systemexit-main
replace exit(main()) with raise SystemExit(main())
2021-10-23 11:29:35 -07:00
Anthony Sottile
c8cf74dc71 replace exit(main()) with raise SystemExit(main())
Committed via https://github.com/asottile/all-repos
2021-10-23 13:23:48 -04:00
Anthony Sottile
663a766a0c
Merge pull request #2097 from colens3/master
Support fail_fast on check level
2021-10-22 16:19:24 -07:00
Stojan Nedic
63ae399db0 Add fail_fast support per-hook 2021-10-22 19:16:30 -04:00
Anthony Sottile
ae53a8eb65
Merge pull request #2098 from pre-commit/asottile-patch-1
ban broken importlib-resources versions
2021-10-19 19:14:13 -07:00
Anthony Sottile
d0c9e589ca
ban broken importlib-resources versions 2021-10-19 19:02:36 -07:00
Anthony Sottile
2ac26e221c
Merge pull request #2086 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-10-11 17:55:17 -07:00
Anthony Sottile
8c844c794d work around conda bug installing python3.1/site-packages
https://github.com/conda/conda/issues/10969
2021-10-11 20:21:34 -04:00
pre-commit-ci[bot]
69a4dbda68 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2021-10-11 18:53:57 +00:00
pre-commit-ci[bot]
247d892e69
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 3.9.2 → 4.0.1](https://github.com/PyCQA/flake8/compare/3.9.2...4.0.1)
- [github.com/asottile/setup-cfg-fmt: v1.17.0 → v1.18.0](https://github.com/asottile/setup-cfg-fmt/compare/v1.17.0...v1.18.0)
- [github.com/pre-commit/mirrors-mypy: v0.910 → v0.910-1](https://github.com/pre-commit/mirrors-mypy/compare/v0.910...v0.910-1)
2021-10-11 18:53:36 +00:00
Anthony Sottile
6872289f1a
Merge pull request #2078 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-10-04 12:58:20 -07:00
pre-commit-ci[bot]
0acf2e99c4
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.25.0 → v2.29.0](https://github.com/asottile/pyupgrade/compare/v2.25.0...v2.29.0)
2021-10-04 18:54:25 +00:00
Anthony Sottile
d021bbfabd
Merge pull request #2071 from pre-commit/submodule-recurse-bug
make sure to not discard changes even if submodule.recurse=1
2021-10-01 16:47:50 -07:00
Anthony Sottile
e9ed248a15 make sure to not discard changes even if submodule.recurse=1 2021-10-01 18:45:36 -04:00
Anthony Sottile
e0e3fabfdb
Merge pull request #2066 from pre-commit/unxfail-node-windows
un-xfail node on windows
2021-09-27 17:44:37 -07:00
Anthony Sottile
2fc00f73b6 un-xfail node on windows
these have been reasonably stable for a while
2021-09-27 20:00:18 -04:00
Anthony Sottile
b3c0d84dd3
Merge pull request #2065 from pre-commit/hook-template-bash
port hook template to bash
2021-09-27 16:59:10 -07:00
Anthony Sottile
e622f793c3 port hook template to bash
this avoids some version-specific code in python

this also makes the bootstrap script slightly more portable
2021-09-27 19:34:04 -04:00
Anthony Sottile
ef7b126ee3
Merge pull request #2053 from radek-sprta/master
Add warning for regular expression with [\/] (#2043)
2021-09-22 16:56:21 -07:00
Radek SPRTA
cef9c4af03 Add warning for regular expression with [\/] (#2043) 2021-09-22 19:07:38 -04:00
Anthony Sottile
530dbe69ce
Merge pull request #2047 from pre-commit/windows-as-usual
fix pre-commit autoupdate for core.useBuiltinFSMonitor=true on windows
2021-09-14 14:15:34 -07:00
Anthony Sottile
ab94dd69f8 fix pre-commit autoupdate for core.useBuiltinFSMonitor=true on windows 2021-09-13 20:01:25 -04:00
Anthony Sottile
2ef29b7f95
Merge pull request #2039 from pre-commit/issue-form
add a bug report issue form
2021-09-06 15:52:04 -04:00
Anthony Sottile
09ffe421a9 add a bug report issue form 2021-09-06 15:01:42 -04:00
Anthony Sottile
36b8ad63d2 v2.15.0 2021-09-02 20:33:19 -04:00
Anthony Sottile
c64c36b120
Merge pull request #2036 from uSpike/add-post-rewrite-hook
Add: post-rewrite hook support
2021-09-02 14:08:23 -04:00
Jordan Speicher
4cd8b364dd Add: post-rewrite hook support 2021-09-01 14:50:59 -05:00
Anthony Sottile
3bab1514c3
Merge pull request #2030 from pre-commit/duplicate-messages-autoupdate
remove duplicate warnings while running autoupdate
2021-08-30 21:49:04 -04:00
Anthony Sottile
25a1988859
Merge pull request #2029 from pre-commit/broken-symlink-check-useless-excludes
fix check-useless-excludes for exclude of broken symlink
2021-08-30 21:48:56 -04:00
Anthony Sottile
726f2ad0a3 remove duplicate warnings while running autoupdate 2021-08-30 20:56:24 -04:00
Anthony Sottile
35d3ed40cd fix check-useless-excludes for exclude of broken symlink 2021-08-30 20:56:14 -04:00
Anthony Sottile
a96bb23caf
Merge pull request #2031 from pre-commit/wtf-is-ort
update tests for latest git
2021-08-30 20:55:57 -04:00
Anthony Sottile
54a481c04b update tests for latest git 2021-08-30 20:48:41 -04:00
Anthony Sottile
66c51a3d56
Merge pull request #2027 from pre-commit/dart
add support for dart as a hook language
2021-08-30 19:30:51 -04:00
Anthony Sottile
2d03991195
Merge pull request #2028 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-08-30 15:10:08 -04:00
pre-commit-ci[bot]
46c18d9370
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.24.0 → v2.25.0](https://github.com/asottile/pyupgrade/compare/v2.24.0...v2.25.0)
2021-08-30 18:35:12 +00:00
Anthony Sottile
f8e21cb78b add support for dart as a hook language 2021-08-29 08:57:56 -07:00
Anthony Sottile
0f08ba77c8 v2.14.1 2021-08-28 14:15:40 -04:00
Anthony Sottile
12f62d2191
Merge pull request #2026 from pre-commit/incorrect-regular-expressions
make `repo: meta` only apply to top level configuration
2021-08-28 14:07:53 -04:00
Anthony Sottile
f963bf6f9a make repo: meta only apply to top level configuration 2021-08-28 13:39:55 -04:00
Anthony Sottile
40e21bb8ba
Merge pull request #2020 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-08-23 14:44:45 -04:00
pre-commit-ci[bot]
b829bc2dba
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.23.3 → v2.24.0](https://github.com/asottile/pyupgrade/compare/v2.23.3...v2.24.0)
2021-08-23 18:12:36 +00:00
Anthony Sottile
509e4e20e8
Merge pull request #2005 from pre-commit/disparate-histories
fall back to full diff on disparate histories
2021-08-10 08:55:03 -04:00
Anthony Sottile
0fe959df60 fall back to full diff on disparate histories 2021-08-09 20:13:15 -04:00
Anthony Sottile
abc1c5d9ba
Merge pull request #2004 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-08-09 11:52:02 -07:00
pre-commit-ci[bot]
d6f5504311
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.23.1 → v2.23.3](https://github.com/asottile/pyupgrade/compare/v2.23.1...v2.23.3)
2021-08-09 18:05:46 +00:00
Anthony Sottile
ab15d7d22d v2.14.0 2021-08-06 11:32:11 -07:00
Anthony Sottile
6cfdabb69a
Merge pull request #1997 from pre-commit/true-dind
ignore self-container when in docker-in-docker
2021-08-03 16:41:21 -04:00
Anthony Sottile
5d1cac64c1 ignore self-container when in docker-in-docker 2021-08-03 13:08:07 -07:00
Anthony Sottile
a4444f1996
Merge pull request #1996 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-08-02 15:30:08 -04:00
pre-commit-ci[bot]
5bd2077872
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.23.0 → v2.23.1](https://github.com/asottile/pyupgrade/compare/v2.23.0...v2.23.1)
2021-08-02 18:01:06 +00:00
Anthony Sottile
a02859ad6b
Merge pull request #1989 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-07-26 14:34:48 -04:00
pre-commit-ci[bot]
6cd4e2af48
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.21.2 → v2.23.0](https://github.com/asottile/pyupgrade/compare/v2.21.2...v2.23.0)
- [github.com/asottile/reorder_python_imports: v2.5.0 → v2.6.0](https://github.com/asottile/reorder_python_imports/compare/v2.5.0...v2.6.0)
2021-07-26 17:51:54 +00:00
Anthony Sottile
621146bd80
Merge pull request #1984 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-07-19 18:24:20 -04:00
pre-commit-ci[bot]
0065a71e3d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.21.0 → v2.21.2](https://github.com/asottile/pyupgrade/compare/v2.21.0...v2.21.2)
2021-07-19 21:58:13 +00:00
Anthony Sottile
fe436f1eb0
Merge pull request #1974 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-07-12 20:18:26 -04:00
pre-commit-ci[bot]
81c0413c38
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.20.0 → v2.21.0](https://github.com/asottile/pyupgrade/compare/v2.20.0...v2.21.0)
2021-07-12 23:20:49 +00:00
Anthony Sottile
835f9c65e9
Merge pull request #1968 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-07-05 18:30:48 -04:00
pre-commit-ci[bot]
d4c14fb6fd
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.19.4 → v2.20.0](https://github.com/asottile/pyupgrade/compare/v2.19.4...v2.20.0)
2021-07-05 22:01:40 +00:00
Anthony Sottile
edcbf8fb4b
Merge pull request #1919 from adarnimrod/fix-container-id
A more reliable way to get the container id.
2021-07-03 14:44:01 -04:00
Anthony Sottile
8067f013d2 fix casing in .pre-commit-hooks.yaml 2021-07-03 11:14:05 -07:00
Adar Nimrod
3e1020945e A more reliable way to get the container id.
The hostname is not always the container id. Get the container id from
/proc/1/cgroup. Fixes #1918.
2021-07-03 10:43:11 -07:00
Anthony Sottile
68294256a1
Merge pull request #1956 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-06-28 18:14:39 -07:00
pre-commit-ci[bot]
af429b951d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-mypy: v0.902 → v0.910](https://github.com/pre-commit/mirrors-mypy/compare/v0.902...v0.910)
2021-06-28 17:37:10 +00:00
Anthony Sottile
2d4de2ef35
Merge pull request #1949 from pre-commit/all-repos_autofix_mypy-settings
stricter mypy settings
2021-06-21 19:52:48 -07:00
Anthony Sottile
1dca1f3c19 stricter mypy settings
Committed via https://github.com/asottile/all-repos
2021-06-21 19:15:37 -07:00
Anthony Sottile
ba5e6eb42d
Merge pull request #1947 from FlorentClarret/pre_push_local_branch
Expose local branch ref as an environment variable
2021-06-19 11:46:17 -07:00
Florent Clarret
584fd585ec Expose local branch ref as an environment variable 2021-06-19 18:18:14 +02:00
Anthony Sottile
8037b45cb1
Merge pull request #1943 from pre-commit/binary_legacy
read legacy hooks in an encoding-agnostic way
2021-06-15 10:23:11 -07:00
Anthony Sottile
0ed646ed09 read legacy hooks in an encoding-agnostic way 2021-06-15 08:32:44 -07:00
Anthony Sottile
b77194644e
Merge pull request #1941 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-06-14 12:26:01 -07:00
Anthony Sottile
19da6479a8
Add mypy dependency on types-all 2021-06-14 11:58:41 -07:00
pre-commit-ci[bot]
65dc06c989
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.19.1 → v2.19.4](https://github.com/asottile/pyupgrade/compare/v2.19.1...v2.19.4)
- [github.com/pre-commit/mirrors-mypy: v0.812 → v0.902](https://github.com/pre-commit/mirrors-mypy/compare/v0.812...v0.902)
2021-06-14 17:34:33 +00:00
Anthony Sottile
4e3ec8ef24
Merge pull request #1933 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-06-07 19:16:04 -07:00
pre-commit-ci[bot]
c4e4f2d9fa
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.19.0 → v2.19.1](https://github.com/asottile/pyupgrade/compare/v2.19.0...v2.19.1)
2021-06-08 01:47:05 +00:00
Anthony Sottile
f0fc9f8846
Merge pull request #1928 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-05-31 10:56:52 -07:00
pre-commit-ci[bot]
b517f9cc7f
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.18.2 → v2.19.0](https://github.com/asottile/pyupgrade/compare/v2.18.2...v2.19.0)
2021-05-31 17:26:07 +00:00
Anthony Sottile
488b1999f3
Merge pull request #1922 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-05-24 11:19:27 -07:00
pre-commit-ci[bot]
d3c5cd6ee2 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2021-05-24 17:20:17 +00:00
pre-commit-ci[bot]
1d2cde763c
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.16.0 → v2.18.2](https://github.com/asottile/pyupgrade/compare/v2.16.0...v2.18.2)
2021-05-24 17:19:56 +00:00
Anthony Sottile
229a4e03e3 v2.13.0 2021-05-21 14:04:43 -07:00
Anthony Sottile
a1f2d69552
Merge pull request #1913 from jalessio/jamie/upgrade-ruby
Update rbenv / ruby-build
2021-05-18 08:11:20 -07:00
Jamie Alessio
14afbc7ad6 Update rbenv / ruby-build 2021-05-18 08:08:07 -07:00
Anthony Sottile
9f2f405c3f
Merge pull request #1915 from pre-commit/reproducible-tar
make tarfile creation reproducible
2021-05-18 07:59:54 -07:00
Anthony Sottile
c2108d6d43 make tarfile creation reproducible 2021-05-17 20:15:00 -07:00
Anthony Sottile
7266936138
Merge pull request #1914 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-05-17 11:54:41 -07:00
pre-commit-ci[bot]
7f65d2745d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/pre-commit-hooks: v3.4.0 → v4.0.1](https://github.com/pre-commit/pre-commit-hooks/compare/v3.4.0...v4.0.1)
- [github.com/asottile/pyupgrade: v2.15.0 → v2.16.0](https://github.com/asottile/pyupgrade/compare/v2.15.0...v2.16.0)
2021-05-17 17:22:52 +00:00
Anthony Sottile
147b047487
Merge pull request #1911 from pre-commit/all-repos_autofix_more-inclusive-language
Use more inclusive language
2021-05-14 19:53:14 -07:00
Anthony Sottile
3922263f8c Use more inclusive language
Committed via https://github.com/asottile/all-repos
2021-05-14 19:11:05 -07:00
Anthony Sottile
2c28197c2a
Merge pull request #1906 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-05-10 14:09:01 -07:00
pre-commit-ci[bot]
b9c2c477cc
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 3.9.1 → 3.9.2](https://github.com/PyCQA/flake8/compare/3.9.1...3.9.2)
- [github.com/asottile/pyupgrade: v2.14.0 → v2.15.0](https://github.com/asottile/pyupgrade/compare/v2.14.0...v2.15.0)
2021-05-10 20:19:33 +00:00
Anthony Sottile
45c721a2ca
Merge pull request #1878 from lorenzwalthert/local-r-hooks
R local hooks should not prefix hook path
2021-05-05 19:04:14 -07:00
Lorenz
788aec156f local r hooks should not get prefix for path 2021-05-05 18:15:56 -07:00
Anthony Sottile
c082292bb8
Merge pull request #1841 from lorenzwalthert/renv-activate2
Avoid warnings with R hooks when renv version don't match
2021-05-04 19:27:44 -07:00
Anthony Sottile
0107df0a2b
Merge pull request #1898 from lorenzwalthert/idenfity-package-over-package-field
Use more common package definition for R
2021-05-04 18:59:23 -07:00
Lorenz
b8fff8c508 Avoid warnings with R hooks when renv version don't match 2021-05-04 18:56:43 -07:00
Anthony Sottile
c753eeb6ec
Merge pull request #1899 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-05-03 10:54:56 -07:00
pre-commit-ci[bot]
6485dd45a3
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/pre-commit/mirrors-autopep8: v1.5.6 → v1.5.7](https://github.com/pre-commit/mirrors-autopep8/compare/v1.5.6...v1.5.7)
- [github.com/asottile/pyupgrade: v2.13.0 → v2.14.0](https://github.com/asottile/pyupgrade/compare/v2.13.0...v2.14.0)
2021-05-03 17:18:16 +00:00
Lorenz
a19a59652f Use more common package definition 2021-05-03 18:08:22 +02:00
Anthony Sottile
7f13fa5d5f
Merge pull request #1888 from okainov/docker-fix-2
fix: fix path mounting when running in Docker
2021-04-28 19:51:27 -07:00
Oleg Kainov
6d5d386c9f fix: fix path mounting when running in Docker
Currently pre-commit mounts the current directory to /src and uses
current directory name as mount base.
However this does not work when pre-commit is run inside the container
on some mounted path already, because mount points are relative to the
host, not to the container.

Fixes #1387
2021-04-28 19:21:34 -07:00
Anthony Sottile
52e1dd6099
Merge pull request #1890 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-04-26 11:05:21 -07:00
pre-commit-ci[bot]
60bf370a7d
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/asottile/pyupgrade: v2.12.0 → v2.13.0](https://github.com/asottile/pyupgrade/compare/v2.12.0...v2.13.0)
- [github.com/asottile/reorder_python_imports: v2.4.0 → v2.5.0](https://github.com/asottile/reorder_python_imports/compare/v2.4.0...v2.5.0)
2021-04-26 17:18:40 +00:00
Anthony Sottile
24d9dc7469
Merge pull request #1875 from pre-commit/skip-installation-for-skip
skip installation for SKIP'd hooks
2021-04-19 19:40:51 -07:00
Anthony Sottile
9b4e7691f4
Merge pull request #1883 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-04-19 11:42:55 -07:00
pre-commit-ci[bot]
de2b7b6dcc
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/PyCQA/flake8: 3.9.0 → 3.9.1](https://github.com/PyCQA/flake8/compare/3.9.0...3.9.1)
2021-04-19 17:08:45 +00:00
Anthony Sottile
8fc66027f7 v2.12.1 2021-04-16 14:14:17 -07:00
Anthony Sottile
52ada7c614
Merge pull request #1881 from adamchainz/issue_1880_patch_naming
Include PID in patch filename
2021-04-16 14:12:38 -07:00
Adam Johnson
4f2069ee9a Include PID in patch filename
Fixes #1880.
2021-04-16 21:35:49 +01:00
Anthony Sottile
559d8a78d1
Merge pull request #1877 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-04-12 10:40:04 -07:00
pre-commit-ci[bot]
30649e7fee
[pre-commit.ci] pre-commit autoupdate 2021-04-12 17:09:59 +00:00
Anthony Sottile
12a7075fda skip installation for SKIP'd hooks 2021-04-10 00:37:59 -07:00
Anthony Sottile
8dede082d5
Merge pull request #1873 from pre-commit/all-repos_autofix_azure-pipelines-autoupdate
Update azure-pipelines template repositories
2021-04-08 20:08:57 -07:00
Anthony Sottile
5deeb82e0e Update azure-pipelines template repositories
Committed via https://github.com/asottile/all-repos
2021-04-08 19:22:17 -07:00
Anthony Sottile
a1b462c94a v2.12.0 2021-04-06 08:18:14 -07:00
Anthony Sottile
baadc2dc93
Merge pull request #1868 from pre-commit/fix_archive_permissions
fix archive permissions for ruby tar.gz roots
2021-04-06 08:14:11 -07:00
Anthony Sottile
d5eda977ce fix archive permissions for ruby tar.gz roots 2021-04-06 07:55:32 -07:00
Anthony Sottile
bd1658baae
Merge pull request #1866 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-04-05 11:30:44 -07:00
pre-commit-ci[bot]
5827a93c2f
[pre-commit.ci] pre-commit autoupdate 2021-04-05 17:08:42 +00:00
Anthony Sottile
008717fcc9
Merge pull request #1864 from pre-commit/batch_additional_headroom
give xargs batch file execution additional headroom
2021-04-04 10:32:11 -07:00
Anthony Sottile
fb590d41ff give xargs batch file execution additional headroom 2021-04-04 10:00:55 -07:00
Anthony Sottile
e431b2b898
Merge pull request #1854 from pre-commit/upgrade_ruby_build
upgrade ruby-build
2021-03-23 07:39:23 -07:00
Anthony Sottile
3bada745ea upgrade ruby-build 2021-03-22 19:41:30 -07:00
Anthony Sottile
060b719d44
Merge pull request #1851 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-03-22 12:10:59 -07:00
pre-commit-ci[bot]
e8cb09f70f
[pre-commit.ci] pre-commit autoupdate 2021-03-22 17:03:06 +00:00
Anthony Sottile
d6ec6cf719
Merge pull request #1839 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-03-15 12:15:56 -07:00
pre-commit-ci[bot]
4a440f67c8 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2021-03-15 17:00:34 +00:00
pre-commit-ci[bot]
74bbc72d28
[pre-commit.ci] pre-commit autoupdate 2021-03-15 17:00:05 +00:00
Anthony Sottile
8aec369df7 v2.11.1 2021-03-09 16:57:10 -08:00
Anthony Sottile
478efe55c6
Merge pull request #1831 from lorenzwalthert/renv-fix
Fix r hooks when hook repo is a package
2021-03-09 16:55:52 -08:00
Lorenz
cf57e35e37 install package from prefix_dir, not env_dir (which yields empty pkg) 2021-03-09 16:44:36 -08:00
Anthony Sottile
54c49abbcb v2.11.0 2021-03-07 14:58:42 -08:00
Anthony Sottile
b3750cac62
Merge pull request #1828 from pre-commit/worktree_in_git
add test for worktree inside of .git dir
2021-03-07 14:52:44 -08:00
Anthony Sottile
14d3af25eb add test for worktree inside of .git dir 2021-03-07 14:43:32 -08:00
Anthony Sottile
19bffaa2fd
Merge pull request #1799 from lorenzwalthert/renv
Support for R / renv as a language
2021-03-07 14:28:33 -08:00
Lorenz
f1502119a2 add support for R via renv 2021-03-07 13:58:14 -08:00
Anthony Sottile
b193d9e67b
Merge pull request #1800 from psacawa/post-merge-pr
Add support for post-merge hooks
2021-02-27 09:19:40 -08:00
Anthony Sottile
a38f8d059e
Merge pull request #1818 from rafikdraoui/go1.16-support
Add support for Go 1.16
2021-02-26 18:38:45 -08:00
Rafik Draoui
fe1f56c08f Add support for Go 1.16
Go 1.16 changes the way modules are handled. It now expects Go projects
to have non-empty `go.mod` files.

This change is compatible with Go 1.15.

Fixes #1815
2021-02-25 19:25:39 -04:00
Anthony Sottile
f3de91c2bb
Merge pull request #1814 from pre-commit/subst
Fix pre-commit install on subst drives
2021-02-23 19:20:33 -08:00
Paweł Sacawa
6b73138c73 Add: post-merge hook support 2021-02-23 19:00:02 -08:00
Anthony Sottile
f2dffc5237
Merge pull request #1809 from JamMarHer/patch-1
Instruct users how to prevent a warning.
2021-02-23 18:54:23 -08:00
Anthony Sottile
616249e680
Merge pull request #1813 from pre-commit/fix_without_us_test
fix _path_without_us under test when path segment ends in slash
2021-02-23 18:54:13 -08:00
Anthony Sottile
f9fbe18abf Fix pre-commit install on subst drives 2021-02-23 18:52:24 -08:00
Anthony Sottile
87dccbb8dc fix _path_without_us under test when path segment ends in slash 2021-02-23 18:22:12 -08:00
Jam M. Hernandez Quiceno
3d31858ee3 Instruct users how to prevent a mutable rev in repo warning. 2021-02-23 17:59:50 -08:00
Anthony Sottile
d7b189ce56
Merge pull request #1811 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-02-22 09:35:09 -08:00
pre-commit-ci[bot]
c024147ede
[pre-commit.ci] pre-commit autoupdate 2021-02-22 17:03:19 +00:00
Anthony Sottile
d827e9aa72
Merge pull request #1792 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-02-08 09:20:08 -08:00
pre-commit-ci[bot]
0cd8cbc83d
[pre-commit.ci] pre-commit autoupdate 2021-02-08 16:48:57 +00:00
Anthony Sottile
0047fa35dd v2.10.1 2021-02-06 13:21:12 -08:00
Anthony Sottile
2dac92cc8c
Merge pull request #1789 from paulhfischer/recursive_golang
added recursive repository support for golang
2021-02-06 13:18:37 -08:00
Anthony Sottile
833bbf7186 add test for recursive submodules for golang 2021-02-06 12:52:42 -08:00
Paul Fischer
34e0ff3497 added recursive repository support for golang 2021-02-06 12:52:41 -08:00
Anthony Sottile
e6caddba19
Merge pull request #1781 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-02-01 12:46:22 -08:00
pre-commit-ci[bot]
5e7c6eb31e
[pre-commit.ci] pre-commit autoupdate 2021-02-01 16:48:53 +00:00
Anthony Sottile
c67ba85311 v2.10.0 2021-01-27 12:47:08 -08:00
Anthony Sottile
588b6ed3fc
Merge pull request #1778 from pre-commit/bare_worktree
fix execution in worktrees in subdirectories of bare repositories
2021-01-27 12:30:59 -08:00
Anthony Sottile
f75fc6b2a8 fix execution in worktrees in subdirectories of bare repositories 2021-01-27 10:08:48 -08:00
Anthony Sottile
7727f8777a
Merge pull request #1773 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-01-25 13:24:57 -08:00
Anthony Sottile
d258650ad4 use comparison with sys.platform so mypy understands it 2021-01-25 12:47:07 -08:00
pre-commit-ci[bot]
74183d91cb
[pre-commit.ci] pre-commit autoupdate 2021-01-25 16:40:14 +00:00
Anthony Sottile
dbd69af90d
Merge pull request #1772 from pre-commit/caplog_moar
replace fake_log_handler with caplog
2021-01-22 14:34:42 -08:00
Anthony Sottile
da369be096
Merge pull request #1771 from pre-commit/no_install_language_options
produce a more useful error message when non-installable things use language_version or additional_dependencies
2021-01-22 14:34:35 -08:00
Anthony Sottile
c7cbb1e6ad replace fake_log_handler with caplog 2021-01-22 14:02:45 -08:00
Anthony Sottile
4f39946ea3 produce a more useful error message when non-installable things use language_version or additional_dependencies 2021-01-22 13:56:06 -08:00
Anthony Sottile
ffed7beab6
Merge pull request #1770 from pre-commit/remote_branch_ref
Expose remote branch ref as an environment variable
2021-01-22 13:48:30 -08:00
surafelabebe
cb5ed6276d Expose remote branch ref as an environment variable 2021-01-22 13:18:25 -08:00
Anthony Sottile
bb50e00447
Merge pull request #1769 from pre-commit/fix_golang_hello_example
fix reference to github.com/golang/example
2021-01-22 13:15:55 -08:00
Anthony Sottile
d57207510d fix reference to github.com/golang/example 2021-01-22 12:26:22 -08:00
Anthony Sottile
ebd83171df
Merge pull request #1751 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2021-01-04 09:19:50 -08:00
pre-commit-ci[bot]
42cc56c0f6
[pre-commit.ci] pre-commit autoupdate 2021-01-04 16:43:53 +00:00
Anthony Sottile
b2c0fab3b9
Merge pull request #1750 from paulhfischer/warn_on_globs_instead_of_regex
extended warning if globs are used instead of regex to top level
2021-01-01 16:45:30 -08:00
Paul Fischer
b1a9209f9f
extended warning if globs are used instead of regex to top level 2021-01-01 23:57:24 +01:00
Anthony Sottile
7432acc215
Merge pull request #1741 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2020-12-21 09:37:54 -08:00
pre-commit-ci[bot]
75aa6a0840
[pre-commit.ci] pre-commit autoupdate 2020-12-21 16:43:31 +00:00
Anthony Sottile
0ed7930976
Merge pull request #1715 from paulhfischer/warn_if_mutable_rev_is_used
added warning if mutable rev is used
2020-12-18 12:59:31 -08:00
Paul Fischer
1e4de986a8 added warning if mutable rev is used 2020-12-18 12:20:21 -08:00
Anthony Sottile
8670d0b3bc
Merge pull request #1735 from pre-commit/allow_ci_key
allow configuration for pre-commit.ci
2020-12-18 12:06:15 -08:00
Anthony Sottile
38a4a0aa3b allow configuration for pre-commit.ci 2020-12-16 20:21:33 -08:00
Anthony Sottile
2d54ea112a fix typo in CHANGELOG 2020-12-07 15:09:02 -08:00
Anthony Sottile
a062cbd439 v2.9.3 2020-12-07 15:06:39 -08:00
Anthony Sottile
eacf4c886e
Merge pull request #1727 from mrogaski/1610_git_toplevel_relpath
git: changed rev-parse option for Git 2.25 changes to --show-toplevel
2020-12-07 14:50:54 -08:00
Mark Rogaski
29d15de38e git: changed rev-parse option for Git 2.25 changes to --show-toplevel
Git 2.25 introduced a change to "rev-parse --show-toplevel" that exposed underlying volumes for Windows drives mapped with SUBST.  We use "rev-parse --show-cdup" to get the appropriate path, but must perform an extra check to see if we are in the .git directory.
2020-12-07 13:54:05 -08:00
Anthony Sottile
cf604f6b93
Merge pull request #1725 from fsouza/fix-rmtree
util: also run chmod on EPERM
2020-12-06 10:27:15 -08:00
francisco souza
c598785b6f
util: use set instead of tuple in errno check
Co-authored-by: Paul Fischer <70564747+paulhfischer@users.noreply.github.com>
2020-12-06 07:45:31 -08:00
francisco souza
bb0d9573a9
util: also run chmod on EPERM
Writing a test for this one is tricky, because I was seeing the issue
only when the directory being removed is a docker volume, so instead of
getting EACCES we get EPERM.

This is easy to reproduce though. The existing test fails when the
directory being used for the files is a docker volume:

```
% docker run \
	-v $(mktemp -d):/tmp \
	-v ${PWD}:/src \
	-w /src \
	python:3 \
	bash -c 'pip install -e . && pip install -r requirements-dev.txt && python -m pytest tests/util_test.py'
```
2020-12-05 22:26:38 -05:00
Anthony Sottile
92ce2dcbc3
Merge pull request #1721 from pre-commit/dont_crash_on_cygwin_check
don't crash on cygwin mismatch check
2020-11-28 15:48:30 -08:00
Anthony Sottile
8cfe8e590d don't crash on cygwin mismatch check 2020-11-28 15:20:14 -08:00
Anthony Sottile
6c6294571a
Add link to issue by CodeBleu 2020-11-27 17:00:17 -08:00
Anthony Sottile
a82a79bf3f
Merge pull request #1717 from pre-commit/fix_test
fix symlink test for windows
2020-11-26 11:34:22 -08:00
Anthony Sottile
e6c9b04386 fix symlink test for windows 2020-11-26 09:42:27 -08:00
Anthony Sottile
f15cfbb208 v2.9.2 2020-11-25 18:39:54 -08:00
Anthony Sottile
bf85379619
Merge pull request #1716 from pre-commit/types_or_default
fix the default value for types_or
2020-11-25 18:37:50 -08:00
Anthony Sottile
89ab609732 fix the default value for types_or 2020-11-25 18:21:37 -08:00
Anthony Sottile
b5baf5c807
Merge pull request #1714 from pre-commit/sha256sum_pyz
also produce sha256sum of pyz on creation
2020-11-25 14:09:42 -08:00
Anthony Sottile
0bd6dfc1a2 also produce sha256sum of pyz on creation 2020-11-25 13:45:22 -08:00
Anthony Sottile
c4f2c6d24d v2.9.1 2020-11-25 13:40:28 -08:00
Anthony Sottile
a9ed1de5f7
Merge pull request #1713 from pre-commit/pyvenv_utf8_windows
fix for base executable with non-ascii characters on windows
2020-11-25 13:26:19 -08:00
Anthony Sottile
7486dee082 fix for base executable with non-ascii characters on windows 2020-11-25 12:44:48 -08:00
Anthony Sottile
029f9cca97
Merge pull request #1707 from paulhfischer/warn_on_globs_instead_of_regex
added warning if globs are used instead of regex
2020-11-23 11:52:05 -08:00
Paul Fischer
610716d3d1 added warning if globs are used instead of regex 2020-11-22 18:53:48 -08:00
Anthony Sottile
6e37f197b0
Merge pull request #1709 from paulhfischer/fix_missing_hooks_autoupdate_message
fixed message if repo couldn't be updated due to missing hook(s)
2020-11-22 14:03:04 -08:00
Paul Fischer
53109a0127 fixed message if repo couldn't be updated due to missing hook(s) 2020-11-22 13:34:10 -08:00
Anthony Sottile
099213f365 v2.9.0 2020-11-21 13:33:20 -08:00
Anthony Sottile
b368fbd1a0
Merge pull request #1704 from Vynce/ignore-submodules
Improve performance by ignoring submodules
2020-11-19 22:27:13 -08:00
Michael Vincent
120d60223a Improve performance by ignoring submodules
When git status runs in a repo with submodules, it'll recursively run
git status in every submodule as well by default (sequentially).
git status is substantially slower on Windows than on Linux. git diff
behaves similarly to git status in terms of running recursively within
all submodules. In repos with hundreds of submodules, this quickly adds
up when git status/diff are called multiple times. Pre-commit runs
git status once at the beginning of an operation and then runs git diff
before and after each hook. These calls quickly add up and make
pre-commit unusable in large repos with lots of submodules.

This commit drastically improves performance in repos with lots of
submodules and fixes #1701 by telling git status and git diff to ignore
submodules. This change is not expected to have any negative effect on
existing hooks because each submodule should manage its own hooks
instead of relying on superproject hooks to manipulate their contents.
2020-11-19 23:26:05 -06:00
Anthony Sottile
84195868fc
Merge pull request #1700 from pre-commit/rbenv_default_more
fix for rbenv used outside of pre-commit and language_version: default
2020-11-19 17:45:44 -08:00
Anthony Sottile
e5a5ae8f24
Merge pull request #1703 from pre-commit/all-repos_autofix_gh-sponsors
Add link to GitHub Sponsors + Open Collective
2020-11-19 17:45:33 -08:00
Anthony Sottile
184e1908c8 Add link to GitHub Sponsors + Open Collective
at the time of writing I am currently unemployed.  I'd love to make open
source a full time career.  if you or your company is deriving value from
this free software, please consider [sponsoring] or [supporting].

[sponsoring]: https://github.com/sponsors/asottile
[supporting]: https://opencollective.com/pre-commit

Committed via https://github.com/asottile/all-repos
2020-11-19 17:13:02 -08:00
Anthony Sottile
a3e3b3d8aa fix for rbenv used outside of pre-commit and language_version: default 2020-11-17 11:58:46 -08:00
Anthony Sottile
59acc7e48a
Merge pull request #1698 from pre-commit/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2020-11-16 09:48:49 -08:00
pre-commit-ci[bot]
6dbd53b387 [pre-commit.ci] pre-commit autoupdate 2020-11-16 17:04:58 +00:00
Anthony Sottile
8d28c9ab40
Merge pull request #1691 from pre-commit/slightly_simpler_enum
use slightly simpler enum syntax
2020-11-09 13:24:05 -08:00
Anthony Sottile
55cdfc6fd2 use slightly simpler enum syntax 2020-11-09 12:29:57 -08:00
Anthony Sottile
e836e55489
Merge pull request #1688 from pre-commit/simplify_new_rev
add test to guard against yaml_dump
2020-11-06 22:39:59 -08:00
Anthony Sottile
13242f55c5 add test to guard against yaml_dump 2020-11-06 17:07:37 -08:00
Anthony Sottile
1494faee1f
Merge pull request #1687 from pre-commit/simple_rev_line_re
remove DOTALL on REV_LINE_RE
2020-11-06 16:32:46 -08:00
Anthony Sottile
64d57ba466 remove DOTALL on REV_LINE_RE 2020-11-06 14:36:43 -08:00
Anthony Sottile
10b0c113a4
Merge pull request #1686 from pre-commit/cmd_is_the_worst
improve xargs when running windows batch files
2020-11-06 14:09:11 -08:00
Anthony Sottile
14f984fbcf improve xargs when running windows batch files 2020-11-06 13:09:01 -08:00
Anthony Sottile
c972205214
Merge pull request #1684 from pre-commit/migrate_config_less_work
only perform migrate_config parsing if it is a list
2020-11-05 16:27:23 -08:00
Anthony Sottile
1975c056bc
Merge pull request #1683 from pre-commit/textwrap_indent
use textwrap.indent instead of _indent
2020-11-05 16:22:17 -08:00
Anthony Sottile
b4ab84df58 only perform migrate_config parsing if it is a list 2020-11-05 16:05:41 -08:00
Anthony Sottile
64876697b5 use textwrap.indent instead of _indent 2020-11-05 15:59:46 -08:00
Anthony Sottile
392a1fe16d
Merge pull request #1678 from rkm/dotnet-fix-cleanup
fix dotnet build cleanup
2020-11-03 10:33:15 -08:00
Ruairidh MacLeod
aa8023407e fix dotnet build cleanup 2020-11-03 08:53:17 -08:00
Anthony Sottile
3fa9d3d758
Merge pull request #1677 from MarcoGorelli/types_or
Add types_or
2020-11-02 16:01:04 -08:00
Marco Gorelli
62f668fc3f add types_or 2020-11-02 17:25:10 +00:00
Anthony Sottile
3112e08088 v2.8.2 2020-10-30 13:36:35 -07:00
Anthony Sottile
4aa249c8a5
Merge pull request #1672 from pre-commit/ruby_default
don't call rbenv install for language_version = default
2020-10-30 13:22:06 -07:00
Anthony Sottile
e05ac1e91f don't call ruby install for language_version = default 2020-10-29 19:45:06 -07:00
Anthony Sottile
b2207e5b04 v2.8.1 2020-10-28 23:04:31 -07:00
Anthony Sottile
8fb7365a61
Merge pull request #1669 from pre-commit/not_a_shim_when_home_is_slash
allow default language_version of system when homedir is /
2020-10-28 23:03:34 -07:00
Anthony Sottile
62b8d0ed82 allow default language_version of system when homedir is / 2020-10-28 22:56:10 -07:00
Anthony Sottile
711248f678 show features first 2020-10-28 22:01:15 -07:00
Anthony Sottile
a3c9721d8f v2.8.0 2020-10-28 21:59:03 -07:00
Anthony Sottile
763dbc0ac6
Merge pull request #1668 from pre-commit/avoid_shims
don't use system for ruby/node if it is a shim exe
2020-10-28 17:22:27 -07:00
Anthony Sottile
7f9f66e542 don't use system for ruby/node if it is a shim exe 2020-10-28 16:52:55 -07:00
Anthony Sottile
0c339e0647
Merge pull request #1667 from pre-commit/improve_node_install
improve node install by using npm pack
2020-10-28 16:03:52 -07:00
Anthony Sottile
29f3e67655 improve node install by using npm pack 2020-10-28 15:13:53 -07:00
Anthony Sottile
2779bde2a2
Merge pull request #1666 from pre-commit/mutable_mapping
Replace EnvironT with MutableMapping[str, str]
2020-10-28 14:03:14 -07:00
Anthony Sottile
24dfeed89c Replace EnvironT with MutableMapping[str, str] 2020-10-28 13:00:25 -07:00
Anthony Sottile
a0c0870b87
Merge pull request #1601 from int3l/distinct_exit_codes
Distinct exit codes for the various error cases
2020-10-28 11:59:22 -07:00
int3l
47e758d8f1 Distinct error handling exit codes
https://tldp.org/LDP/abs/html/exitcodes.html - exit codes convention
2020-10-28 11:13:04 -07:00
Anthony Sottile
9d0ab3b97b
Merge pull request #1633 from JosephMoniz/add-jvm-coursier-support
add coursier (jvm) as a language
2020-10-27 10:13:03 -07:00
Joseph Moniz
70ab1c3b6f add coursier (jvm) as a language 2020-10-27 09:21:54 -07:00
Anthony Sottile
eee891c8cb
Merge pull request #1662 from pre-commit/pci
Add pre-commit.ci
2020-10-26 16:38:49 -07:00
Anthony Sottile
653cdd286b Add pre-commit.ci 2020-10-26 16:11:27 -07:00
Anthony Sottile
9e4754fb4a
Merge pull request #1616 from pre-commit/zipapp
add zipapp support
2020-10-17 11:15:03 -07:00
Anthony Sottile
01f1a0090e
Merge pull request #1643 from MarcoGorelli/negate-pygrep
ENH add --negate flag to pygrep
2020-10-17 11:14:19 -07:00
Marco Gorelli
a0658c06bf add --negate flag to pygrep 2020-10-17 18:50:40 +01:00
Anthony Sottile
6ba50f3aa7
Merge pull request #1644 from MarcoGorelli/clean-pygrep-test
Remove unnecessary fixtures in signatures from pygrep tests
2020-10-16 14:27:56 -07:00
Marco Gorelli
2fc676709d Remove unnecessary fixtures in signatures from pygrep tests 2020-10-16 13:11:18 -07:00
Anthony Sottile
ee1fcfbeca
Merge pull request #1634 from pre-commit/simplify
simplify docker run
2020-10-10 18:38:29 -07:00
Anthony Sottile
3584b99caa simplify docker run 2020-10-10 18:09:51 -07:00
Anthony Sottile
11568caf97
Merge pull request #1637 from pre-commit/conda_test
use implementation-agnostic conda package for test
2020-10-10 18:09:09 -07:00
Anthony Sottile
32a286d530 use implementation-agnostic conda package for test 2020-10-10 17:44:56 -07:00
Anthony Sottile
fbd529204b make an exe stub for windows 2020-09-28 18:37:10 -07:00
Anthony Sottile
bc198b89ca add zipapp support 2020-09-28 16:57:59 -07:00
Anthony Sottile
202f0bbbc9
Merge pull request #1598 from rkm/feature/dotnet
add initial dotnet support
2020-09-27 15:25:56 -07:00
Anthony Sottile
949ea163cd
Merge pull request #1611 from mcsitter/patch-1
Update pre-commit version in sample config
2020-09-27 15:16:50 -07:00
Ruairidh MacLeod
003e4c21e0 add initial dotnet support 2020-09-27 15:04:35 -07:00
Maximilian Cosmo Sitter
3de3c6a5fc Update pre-commit version in sample config 2020-09-27 14:54:42 -07:00
Anthony Sottile
a85b9f798d
Merge pull request #1617 from pre-commit/no_p_default_exe
don't pass through -p if using the default version
2020-09-23 18:24:43 -07:00
Anthony Sottile
58a190fd69 don't pass through -p if using the default version 2020-09-23 17:44:18 -07:00
Anthony Sottile
7162a3defe
Merge pull request #1614 from pre-commit/update_rbenv
update rbenv / ruby-build
2020-09-23 11:22:17 -07:00
Thomas Romera
36653586a0 update rbenv / ruby-build 2020-09-22 23:03:01 -07:00
Anthony Sottile
1b3d14237a
Merge pull request #1608 from pre-commit/spelling
fix a few spelling errors
2020-09-20 19:42:27 -07:00
Anthony Sottile
365f896c36 fix a few spelling errors
found via `pre-commit  try-repo https://github.com/codespell-project/codespell --all-files`
2020-09-20 19:21:24 -07:00
Anthony Sottile
f13dcac9ef
Merge pull request #1606 from pre-commit/move_cygwin_mismatch
check cygwin mismatch earlier
2020-09-20 11:14:51 -07:00
Anthony Sottile
91530f1005 check cygwin mismatch earlier 2020-09-20 10:42:11 -07:00
Anthony Sottile
3e2b9dc91a
Merge pull request #1603 from pre-commit/no_format_executable
Fix ruby hooks when --format-executable is in gemrc
2020-09-18 09:37:41 -07:00
Anthony Sottile
13eed4ac5b Fix ruby hooks when --format-executable is in gemrc
I used this gemrc to break things (default on opensuse):

```yaml
---
:benchmark: false
:install: --format-executable --no-user-install
install: --format-executable --no-user-install
:backtrace: true
:update_sources: true
:format_executable: true
:verbose: true
:update: --format-executable --no-user-install
update: --format-executable --no-user-install
:bulk_threshold: 1000
:sources:
- https://rubygems.org
```
2020-09-18 09:13:19 -07:00
Anthony Sottile
801a31302d
Merge pull request #1599 from pre-commit/remove_hardcoded_c_python
remove hardcoded python location
2020-09-15 12:44:52 -07:00
Anthony Sottile
4888644990 remove hardcoded python location 2020-09-15 12:04:25 -07:00
Anthony Sottile
8f32c5b929
Merge pull request #1595 from Celeborn2BeAlive/1583-wrong-shebang-line-win10-pyenvwin
Drop python.exe extension on windows in shebang line to fix pyenv-win setup
2020-09-09 13:19:39 -07:00
Celeborn2BeAlive
273326b89b drop python.exe extension on windows on shebang 2020-09-09 12:42:48 -07:00
Anthony Sottile
8e9f927e3d
Merge pull request #1592 from pre-commit/ws_traceback
fix excess whitespace in traceback in error
2020-09-07 15:23:16 -07:00
Anthony Sottile
3a0406847b fix excess whitespace in traceback in error 2020-09-07 15:01:50 -07:00
Anthony Sottile
918821b7e0
Merge pull request #1590 from pre-commit/nodeenv_system_healthy_fix
fix for node healthy() when system executable moves
2020-09-07 14:24:11 -07:00
Anthony Sottile
b149c7a344 fix for node healthy() when system executable moves 2020-09-07 13:23:02 -07:00
Anthony Sottile
f511afe40e v2.7.1 2020-08-23 10:53:21 -07:00
Anthony Sottile
7c804cabe6
Merge pull request #1577 from pre-commit/os_replace
fix atomic file replace on windows
2020-08-23 10:49:14 -07:00
Anthony Sottile
fe70c72691
Merge pull request #1576 from pre-commit/immediately_unhealthy_cache
fix cache of invalidated unhealthy environment version info
2020-08-23 10:49:07 -07:00
Anthony Sottile
79b098c409 fix atomic file replace on windows 2020-08-23 10:18:59 -07:00
Anthony Sottile
b63b37ac36 fix cache of invalidated unhealthy environment version info 2020-08-23 10:17:24 -07:00
Anthony Sottile
2e0ee5f5b2
Merge pull request #1572 from rkm/issues/1569-docker-perf
remove docker_is_running check from source
2020-08-22 18:03:50 -07:00
Ruairidh MacLeod
eb8b48aeb4 remove docker_is_running check from source
Moved to testing.util so it can be used for the skipif_cant_run_docker
test hooks.
2020-08-22 17:33:32 -07:00
Anthony Sottile
f1de792877 v2.7.0 2020-08-22 13:31:12 -07:00
Anthony Sottile
a438dbfcf6
Merge pull request #1570 from pre-commit/readonly
allow pre-commit to succeed on a readonly store directory
2020-08-22 11:19:11 -07:00
Anthony Sottile
bf33f4c91c allow pre-commit to succeed on a readonly store directory 2020-08-22 10:51:57 -07:00
Anthony Sottile
9a5461db24
Merge pull request #1566 from thetradedesk/master
Save diff between hook executions
2020-08-21 21:02:09 -07:00
Johan Henkens
4063730925 Save diff between hook executions 2020-08-21 20:41:06 -07:00
Anthony Sottile
4f5cb99ff5
Merge pull request #1544 from pre-commit/wip_warning_on_old_config_style
warn on old list-style configuration
2020-07-25 14:27:08 -07:00
Anthony Sottile
e384c182bc
Merge pull request #1546 from pre-commit/error_logging_read_only_filesystem
better error handling when Store is readonly
2020-07-25 13:10:39 -07:00
Anthony Sottile
68510596d3 warn on old list-style configuration 2020-07-25 13:04:54 -07:00
Anthony Sottile
cee834bb5e better error handling when Store is readonly 2020-07-25 12:32:54 -07:00
Anthony Sottile
c0f750d9b3
Merge pull request #1539 from singergr/feat/no-allow-missing-config
Add --no-allow-missing-config option to init-templatedir
2020-07-20 19:21:11 -07:00
Greg Singer
1b435f1f1f add init-templatedir --no-allow-missing-config
Add a `--no-allow-missing-config` option to the `init-templatedir`
command. Enable configuration of a Git template that requires newly
cloned repos to have a `pre-commit` config.
2020-07-20 19:02:35 -07:00
Anthony Sottile
0e851bdf75
Merge pull request #1535 from pre-commit/require_healthy_after_install
require healthy() after installation
2020-07-17 11:50:09 -07:00
Anthony Sottile
7da72563dd require healthy() after installation 2020-07-15 21:07:21 -07:00
Anthony Sottile
2f1d4d10e0
Merge pull request #1531 from pre-commit/upgrade_mypy
upgrade mypy to get typeshed fixes
2020-07-08 14:22:23 -07:00
Anthony Sottile
c9ad2e1451 upgrade mypy to get typeshed fixes 2020-07-08 13:55:28 -07:00
Anthony Sottile
6fe1702ee1 v2.6.0 2020-07-01 12:39:34 -07:00
Anthony Sottile
e2fe94cbe7
Merge pull request #1521 from pre-commit/npm_config_userconfig
fix node hooks when NPM_CONFIG_USERCONFIG is set
2020-06-19 14:15:32 -07:00
Anthony Sottile
6ec47ea736 fix node hooks when NPM_CONFIG_USERCONFIG is set 2020-06-19 13:58:14 -07:00
Anthony Sottile
7d46852aa9
Merge pull request #1518 from pre-commit/xfail_node_windows
xfail a flaky node test on windows
2020-06-17 22:42:18 -07:00
Anthony Sottile
1392471854 xfail a flaky node test on windows 2020-06-17 12:55:30 -07:00
Anthony Sottile
a336a6b0b5
Merge pull request #1506 from Pierre-Sassoulas/master
Add three missing required dependencies in CONTRIBUTING.md
2020-06-15 14:19:03 -07:00
Anthony Sottile
ecaf70128a
Merge pull request #1509 from pre-commit/system_language_version_ruby
skip rbenv if ruby and gem are installed with default language_version
2020-06-15 14:13:44 -07:00
Anthony Sottile
e1e6a32c51 skip rbenv if ruby and gem are installed with default language_version 2020-06-15 13:50:47 -07:00
Pierre Sassoulas
fd53cdea17 Add foor missing required dependencies in CONTRIBUTING.md
There could still be missing dependencies, I'm not using a fresh environement
to test that. Also added the specific required git version see
https://github.com/git/git/blob/master/Documentation/RelNotes/2.24.0.txt
2020-06-12 18:38:44 +02:00
Anthony Sottile
0e5eb19929 v2.5.1 2020-06-09 14:18:42 -07:00
Anthony Sottile
8ffcd386ae
Merge pull request #1497 from pre-commit/no_recurse_clone
prevent infinite recursion of post-checkout on clone
2020-06-09 14:15:35 -07:00
Anthony Sottile
6ee9e13b26 prevent infinite recursion of post-checkout on clone 2020-06-09 10:18:22 -07:00
Anthony Sottile
2f25085d60 v2.5.0 2020-06-08 15:17:13 -07:00
Anthony Sottile
e69e3e04a1
Merge pull request #1494 from pre-commit/normalize_slashes_more
normalize slashes even earlier on windows for filenames
2020-06-08 15:08:24 -07:00
Anthony Sottile
5fb721f7a7 normalize slashes even earlier on windows for filenames 2020-06-08 14:53:27 -07:00
Anthony Sottile
79359ed4e2
Merge pull request #1480 from pre-commit/random_meth
use the shuffle method of Random instead
2020-05-31 12:59:41 -07:00
Anthony Sottile
e120828042 use the shuffle method of Random instead 2020-05-31 12:42:17 -07:00
Anthony Sottile
d71699d7cd
Merge pull request #1474 from pre-commit/unicode_error_py_launcher
avoid a UnicodeError on windows with non-charmap characters
2020-05-27 15:02:41 -07:00
Anthony Sottile
0781dac78f avoid a UnicodeError on windows with non-charmap characters 2020-05-27 13:14:29 -07:00
Anthony Sottile
42562a12ed
Merge pull request #1471 from pre-commit/all-repos_autofix_faster-tests
slightly speed up tests by avoiding pre-commit install
2020-05-26 22:26:20 -07:00
Anthony Sottile
254c42864b slightly speed up tests by avoiding pre-commit install
Committed via https://github.com/asottile/all-repos
2020-05-26 21:53:16 -07:00
Anthony Sottile
ab63f9393f
Merge pull request #1467 from tech-chad/env_variable_pre-commit
Expose an env variable that indicates if pre-commit is running
2020-05-23 19:01:40 -07:00
Chad Larson
9e0b4a9d4d pre-commit env var exposed 2020-05-23 17:20:26 -05:00
Anthony Sottile
f32bc648f0
Merge pull request #1450 from pre-commit/all-repos_autofix_pre-commit-autoupdate
Run pre-commit autoupdate
2020-05-11 15:32:04 -07:00
Anthony Sottile
6f2e869213 Run pre-commit autoupdate
Committed via https://github.com/asottile/all-repos
2020-05-11 14:15:20 -07:00
Anthony Sottile
9641434163 v2.4.0 2020-05-11 12:31:10 -07:00
Anthony Sottile
b3c0eab7dc
Merge pull request #1448 from pre-commit/refuse_migrating_invalid_config
refuse to migrate an invalid configuration
2020-05-10 19:48:06 -07:00
Anthony Sottile
9b8e3d082d refuse to migrate an invalid configuration 2020-05-10 18:02:37 -07:00
Anthony Sottile
46f5cc9609
Merge pull request #1442 from tdeo/tdeo/ruby_gem_path
Unset GEM_PATH for ruby hooks
2020-05-10 12:42:54 -07:00
Thierry Deo
b44461da33 Unset GEM_PATH for ruby hooks 2020-05-10 12:12:15 -07:00
Anthony Sottile
d89486b0f0 oh right, needs a no-cover for xfail 2020-05-10 12:06:27 -07:00
Anthony Sottile
2e47f2dc72 xfail this one too 2020-05-10 11:30:37 -07:00
Anthony Sottile
8db02bd550 xfail these tests on windows (access violation in npm) 2020-05-08 15:55:10 -07:00
Anthony Sottile
182658c88c
Merge pull request #1443 from pre-commit/realpath_cache_dir
Use the real path of the cache root
2020-05-08 15:48:00 -07:00
Anthony Sottile
4c154c3019 Use the real path of the cache root 2020-05-08 14:22:57 -07:00
Anthony Sottile
450d617dec
Merge pull request #1435 from marcjay/maintain-scalar-quotes-rev-autoupdate
Maintain scalar quoting style when autoupdate re-writes rev
2020-05-04 19:41:50 -07:00
Marc Jay
98d8a3d60f Maintain scalar quoting style when autoupdate re-writes rev
If rev is wrapped in single or double quotes (e.g. due to a yamllint quoted-strings rule), when
re-writing the rev to update it, honour the existing quotation style
2020-05-04 19:29:03 -07:00
Anthony Sottile
f455312944
Merge pull request #1431 from pre-commit/better_healthy
Improve python healthy() and eliminate python_venv
2020-05-04 10:52:59 -07:00
Anthony Sottile
e65ea5ede0
Merge pull request #1432 from skmatz/patch-1
Fix some typos
2020-05-03 22:25:23 -07:00
Shunta Komatsu
c2375f2fa8 Fix typo 2020-05-04 14:16:53 +09:00
Anthony Sottile
3d50b3736a Improve python healthy() and eliminate python_venv
- the `healthy()` check now requires virtualenv 20.x's metadata
- `python_venv` is obsolete now that `virtualenv` generates the same structure
  and `virtualenv` is more portable
2020-05-03 21:55:48 -07:00
Anthony Sottile
0c481ea51d
Merge pull request #1429 from pre-commit/minor
yay french strings
2020-05-02 19:22:16 -07:00
Anthony Sottile
df01824d10
Merge pull request #1422 from domodwyer/bugfix/stash-with-post-checkout-hook
fix hooks firing during staged_files_only
2020-05-02 14:47:38 -07:00
Dom
928938a6a1 fix hooks firing during staged_files_only 2020-05-02 14:00:21 -07:00
Anthony Sottile
5ed3f5649b
Merge pull request #1428 from scop/golang-empty-dummy-module
Add dummy go.mod for local "empty" installs
2020-05-02 13:23:29 -07:00
Anthony Sottile
3b728fdb76 yay french strings 2020-05-02 11:37:31 -07:00
Ville Skyttä
e2ed73209a Add dummy go.mod for local "empty" installs 2020-05-02 21:02:36 +03:00
Anthony Sottile
0670e0b287
Merge pull request #1421 from pre-commit/quiet_you_pip
disable pip version check in python hooks
2020-04-29 21:26:16 -07:00
Anthony Sottile
e492a5578c disable pip version check in python hooks 2020-04-29 12:11:34 -07:00
Anthony Sottile
ec6ba99715
Merge pull request #1415 from ModischFabrications/post_commit
Implement post-commit
2020-04-28 11:16:08 -07:00
ModischFabrications
26adf1d560 add support for post-commit 2020-04-27 10:55:22 -07:00
Anthony Sottile
3b3b33ea29
Merge pull request #1413 from ModischFabrications/patch-1
Update CONTRIBUTING.md
2020-04-26 18:46:25 -07:00
Robin Modisch
3ff133c166 add instructions to activate virtualenvs on windows 2020-04-26 18:06:39 -07:00
Anthony Sottile
bcff73c9cc v2.3.0 2020-04-22 14:16:23 -07:00
Anthony Sottile
54fdd6ae5f
Merge pull request #1402 from utek/preserve_line_endings
Preserve line ending when running autoupdate
2020-04-19 09:50:59 -07:00
Lukasz Boldys
13d528c569 Preserve line ending when running autoupdate 2020-04-19 09:12:02 -07:00
Anthony Sottile
2960549682
Merge pull request #1399 from pre-commit/upgrade_pip_on_windows
Allow pip to be upgradable on windows
2020-04-17 08:21:46 -07:00
Anthony Sottile
522e82b7b7 Allow pip to be upgradable on windows 2020-04-17 07:41:11 -07:00
Anthony Sottile
171fd18ba5
Merge pull request #1395 from pre-commit/argument_length
validate argument length as part of hook-impl
2020-04-15 13:46:13 -07:00
Anthony Sottile
80a59db094 validate argument length as part of hook-impl 2020-04-15 12:30:44 -07:00
Anthony Sottile
282527ef16
Merge pull request #1388 from pre-commit/node_default_system
Default to `language_version: system` if node and npm are installed
2020-04-09 16:48:18 -07:00
Anthony Sottile
0f528544b5 Default to language_version: system if node and npm are installed 2020-04-07 20:31:42 -07:00
Anthony Sottile
30a36a8a00
Merge pull request #1382 from pre-commit/better_windows_color
support colors on windows during git better
2020-04-02 07:48:17 -07:00
Anthony Sottile
9fc5a9316e support colors on windows during git better 2020-04-02 00:10:37 -07:00
Anthony Sottile
34e9d11786
Merge pull request #1378 from sophgn/master
fix CJK characters width in output
2020-03-28 08:20:56 -07:00
zjeuhpiung liu
605b39f617 fix CJK characters width in output 2020-03-28 08:06:49 -07:00
Anthony Sottile
528c7afd18
Merge pull request #1371 from killuazhu/windows-no-user
Don't use --user when running docker on windows
2020-03-20 08:27:07 -07:00
KYLE ZHU
23d5b78fdb Don't use --user when running docker on windows 2020-03-19 21:55:16 -07:00
Anthony Sottile
bb6f1efe63 Fix issue link 2020-03-13 23:26:51 -07:00
Anthony Sottile
30d3bb2990 v2.2.0 2020-03-12 12:37:15 -07:00
Anthony Sottile
1e0db9c2c8 Fix help description for --from-ref and --to-ref 2020-03-12 12:27:54 -07:00
Anthony Sottile
74c582fb04
Merge pull request #1364 from pre-commit/exec_error_no_shebang
Don't crash out on OSErrors in subprocess calls
2020-03-12 11:15:40 -07:00
Anthony Sottile
03617b2f98 Don't crash out on OSErrors in subprocess calls 2020-03-12 10:52:10 -07:00
Anthony Sottile
58a16bcf57
Merge pull request #1363 from pre-commit/broken_symlinks_healthy
mark a python environment as unhealthy if python goes missing
2020-03-12 10:07:47 -07:00
Anthony Sottile
7a49309035 mark a python environment as unhealthy if python goes missing 2020-03-12 09:40:56 -07:00
Anthony Sottile
1c10340943
Merge pull request #1359 from pre-commit/bytesable_exceptions
Don't crash on un-stringable exceptions
2020-03-10 09:45:32 -07:00
Anthony Sottile
01be1713cf Don't crash on un-stringable exceptions 2020-03-10 09:02:51 -07:00
Anthony Sottile
0a8ba31b9b
Merge pull request #1349 from pre-commit/covdefaults
Use covdefaults to handle coveragerc
2020-02-29 15:10:32 -08:00
Anthony Sottile
67c1beb322 Use covdefaults to handle coveragerc 2020-02-29 14:25:19 -08:00
Anthony Sottile
4a3b10f0ed
Merge pull request #1346 from pre-commit/3_6_1_plus
Drop python 3.6.0 support (broken NamedTuple)
2020-02-24 09:52:59 -08:00
Anthony Sottile
b2b5676698 Drop python 3.6.0 support (broken NamedTuple) 2020-02-24 09:34:55 -08:00
Anthony Sottile
db6124482d Merge tag 'v2.1.1' 2020-02-24 09:07:39 -08:00
Anthony Sottile
ccf84fb698 v2.1.1 2020-02-24 09:04:36 -08:00
Anthony Sottile
081f3028ee Temporarily restore python 3.6.0 support 2020-02-24 09:02:19 -08:00
Anthony Sottile
5e21e0bec6
Merge pull request #1345 from pre-commit/fix_coverage
Fix test coverage
2020-02-23 15:07:52 -08:00
Anthony Sottile
1b93e26b58 Fix test coverage 2020-02-23 14:53:03 -08:00
Anthony Sottile
92f433c3cf
Merge pull request #1344 from pre-commit/post_checkout_no_files
Ensure files aren't passed to post-checkout hooks
2020-02-23 12:49:23 -08:00
Anthony Sottile
53052fe019 Ensure files aren't passed to post-checkout hooks 2020-02-23 11:38:16 -08:00
Anthony Sottile
2d2ea15246
Merge pull request #1343 from pre-commit/from_ref_to_ref
Make more readable --from-ref / --to-ref aliases for --source / --origin
2020-02-23 11:21:21 -08:00
Anthony Sottile
d35b00352f Make more readable --from-ref / --to-ref aliases for --source / --origin 2020-02-23 11:07:57 -08:00
Anthony Sottile
566f1afcd4
Merge pull request #1339 from andrewhare/andrewhare/post-checkout
Add post-checkout
2020-02-23 10:39:28 -08:00
Anthony Sottile
05f486ef49
Merge pull request #1341 from particledecay/catch_commit-msg_missing_arg
Detect missing arg for prepare-commit-msg and commit-msg
2020-02-23 10:30:44 -08:00
Andrew Hare
18fa004254 Add post-checkout 2020-02-23 10:22:18 -08:00
Joey Espinosa
5258dce73b fix: catch missing arg if using {prepare-}commit-msg stage
If using the prepare-commit-msg and commit-msg stages specifically (such
    as with the try-repo command), the `--commit-msg-filename` arg must be
provided.

[fixes #1336]

chore: improve error message for hook stage check
2020-02-23 10:15:59 -08:00
Anthony Sottile
1c641b1c28 v2.1.0 2020-02-18 10:53:53 -08:00
Anthony Sottile
dbdb8f7606
Merge pull request #1334 from ddelange/badge
Add pre-commit badge
2020-02-14 11:12:12 -08:00
david
5f64b1a255 Add pre-commit badge 2020-02-14 10:49:03 -08:00
Anthony Sottile
524bdaeb33
Merge pull request #1319 from pre-commit/better_shebang_detection
Improve git hook shebang creation
2020-02-07 09:27:13 -08:00
Anthony Sottile
cc45b5e57b Improve git hook shebang creation 2020-02-07 09:09:17 -08:00
Anthony Sottile
659086f22f
Merge pull request #1318 from pre-commit/unnecessary_quoted_annotation
Remove unnecessary forward annotations
2020-02-07 08:54:40 -08:00
Anthony Sottile
fa8d022813 Remove unnecessary forward annotations 2020-02-07 08:32:39 -08:00
Anthony Sottile
78f406af8a
Merge pull request #1311 from pre-commit/unused_latest_git_sh
delete unused testing/latest-git.sh
2020-02-03 14:23:55 -08:00
Anthony Sottile
8d2af32e4d delete unused testing/latest-git.sh 2020-02-03 14:06:51 -08:00
Anthony Sottile
60f30cd827
Merge pull request #1303 from scop/perl
Perl hook support
2020-02-03 12:59:52 -08:00
Anthony Sottile
977bbd7643 put strawberry perl on the beginning of the PATH for windows 2020-02-03 12:42:10 -08:00
Anthony Sottile
44f5753bd8 shlex-quote install path to fix windows 2020-02-03 10:39:08 -08:00
Ville Skyttä
04471f7d97 Add perl additional dependencies test 2020-02-01 16:13:01 +02:00
Ville Skyttä
1295364986 Add basic perl repo test 2020-02-01 15:41:14 +02:00
Ville Skyttä
aee7843bec Add perl to gen-languages-all 2020-02-01 15:20:25 +02:00
Anthony Sottile
11c55fd4c2
Merge pull request #1306 from pre-commit/sort_keys_False
Replace aspy.yaml with sort_keys=False
2020-01-31 17:36:49 -08:00
Anthony Sottile
a64fa6d478 Replace aspy.yaml with sort_keys=False 2020-01-31 17:18:59 -08:00
Ville Skyttä
bb29630d57 First cut at Perl hook support 2020-01-30 09:19:58 +02:00
Anthony Sottile
f0ee93c5a7 v2.0.1 2020-01-29 17:57:05 -08:00
Anthony Sottile
eee3c759b6
Merge pull request #1302 from pre-commit/3_6_0
Fix pre-commit in python 3.6.0-3.6.1
2020-01-29 17:56:15 -08:00
Anthony Sottile
9e4dc7f349 Fix pre-commit in python 3.6.0-3.6.1 2020-01-29 17:40:16 -08:00
Anthony Sottile
0cc199d351 v2.0.0 2020-01-28 18:38:55 -08:00
Anthony Sottile
6c2a14839e
Merge pull request #1299 from pre-commit/hookspath_init_templatedir
allow init-templatedir to succeed when core.hooksPath is set
2020-01-28 13:11:16 -08:00
Anthony Sottile
d56fdca618 allow init-templatedir to succeed when core.hooksPath is set 2020-01-28 12:43:18 -08:00
Anthony Sottile
f74e3031bd
Merge pull request #1292 from pre-commit/hook_impl
Move most of the actual hook script into `pre-commit hook-impl`
2020-01-22 09:01:06 -08:00
Anthony Sottile
95b8d71bd9 Move most of the actual hook script into pre-commit hook-impl 2020-01-21 16:41:22 -08:00
Anthony Sottile
627c9eb0bf
Merge pull request #1293 from schiermike/master
exclude GIT_SSL_NO_VERIFY env variable from getting stripped
2020-01-21 15:40:31 -08:00
Michael Schier
d9800ad95a exclude GIT_SSL_NO_VERIFY env variable from getting stripped 2020-01-21 15:17:03 -08:00
Anthony Sottile
93152218a7
Merge pull request #1295 from pre-commit/ap_bash_broken
work around broken bash in azure pipelines
2020-01-21 15:15:52 -08:00
Anthony Sottile
32d32e3743 work around broken bash in azure pipelines 2020-01-21 14:58:03 -08:00
Anthony Sottile
dde988bd38
Merge pull request #1288 from dmbarreiro/push_remote
Push remote env var details
2020-01-16 13:39:06 -08:00
Anthony Sottile
0bb8a8fabe Move test to install_uninstall test so environment variables apply 2020-01-16 13:02:20 -08:00
David Martinez Barreiro
57cc814b8b Push remote env var details 2020-01-16 12:35:04 -08:00
Anthony Sottile
b66d28964b
Merge pull request #1289 from pre-commit/only_versioned_python
Use a more specific hook shebang now that it can't be python 2
2020-01-16 10:42:06 -08:00
Anthony Sottile
2f51b9da1c Use a more specific hook shebang now that it can't be python 2 2020-01-16 09:57:41 -08:00
Anthony Sottile
31c4c37156
Merge pull request #1287 from pre-commit/move_hook
move Hook data type to a separate file
2020-01-15 14:37:30 -08:00
Anthony Sottile
755b8000f6 move Hook data type to a separate file 2020-01-15 14:20:51 -08:00
Anthony Sottile
5a62501307
Merge pull request #1282 from pre-commit/cleanup
More miscellaneous cleanup
2020-01-13 12:47:28 -08:00
Anthony Sottile
df40e862f4 More miscellaneous cleanup 2020-01-13 11:47:34 -08:00
Anthony Sottile
489d9f9926
Merge pull request #1281 from pre-commit/py2_cleanup_more
Some manual python 2 cleanup
2020-01-12 15:46:34 -08:00
Anthony Sottile
251721b890 os.symlink is always an attribute in py3 2020-01-12 13:39:53 -08:00
Anthony Sottile
5706b9149c deep listdir works in python3 on windows 2020-01-12 13:39:53 -08:00
Anthony Sottile
5779f93ec6 keyword only arguments in some places 2020-01-12 13:39:53 -08:00
Anthony Sottile
34c3a1580a unrelated cleanup 2020-01-12 13:39:53 -08:00
Anthony Sottile
49cf490697 Remove noop_context 2020-01-12 13:39:53 -08:00
Anthony Sottile
2a9893d0f0 mkdirp -> os.makedirs(..., exist_ok=True) 2020-01-12 13:39:53 -08:00
Anthony Sottile
67c2dcd90d Remove pre_commit.five 2020-01-12 13:39:53 -08:00
Anthony Sottile
f33716cc17 Remove usage of OrderedDict 2020-01-12 13:39:53 -08:00
Anthony Sottile
5e52a657df Remove unused ruby activate script 2020-01-12 13:39:53 -08:00
Anthony Sottile
5d767bbc49 Replace match.group(n) with match[n] 2020-01-12 13:39:53 -08:00
Anthony Sottile
9000e9dd41 Some manual .format() -> f-strings 2020-01-12 13:39:53 -08:00
Anthony Sottile
aefbe71765 Clean up calls to .encode() / .decode() 2020-01-12 10:46:33 -08:00
Anthony Sottile
b2faf339ce
Merge pull request #1277 from pre-commit/pyupgrade
Drop python 2 / python3.5 support in pre-commit
2020-01-12 10:41:30 -08:00
Anthony Sottile
76a184eb07 Update get-swift for bionic 2020-01-12 10:15:02 -08:00
Anthony Sottile
4eea90c26c leverage mypy to check language implementations 2020-01-12 10:15:02 -08:00
Anthony Sottile
327ed924a3 Add types to pre-commit 2020-01-12 10:15:01 -08:00
Anthony Sottile
fa536a8693 mypy passes with check_untyped_defs 2020-01-12 09:27:04 -08:00
Anthony Sottile
ab19b94811 some manual py2 cleanups 2020-01-12 09:27:04 -08:00
Anthony Sottile
30c1e8289f upgrade hooks, pyupgrade pre-commit 2020-01-12 09:27:04 -08:00
Anthony Sottile
764c765d29
Merge pull request #1276 from orcutt989/issue-#1273
fix prog arg to return correct version
2020-01-10 16:07:59 -08:00
orcutt989
c7d938c2c4 corrected styling 2020-01-10 18:49:21 -05:00
orcutt989
2cf127f2d3 fix prog arg to return correct version 2020-01-10 18:43:13 -05:00
Anthony Sottile
75043079d0
Merge pull request #1275 from flaudisio/fix-release-date-in-changelog
Fix the v1.21.0 release date in Changelog
2020-01-09 12:36:20 -08:00
Flaudísio Tolentino
8f109890c2 Fix the v1.21.0 release date in Changelog
Signed-off-by: Flaudísio Tolentino <flaudisio@gmail.com>
2020-01-09 17:21:18 -03:00
Anthony Sottile
ef583d2fde
Merge pull request #1269 from pre-commit/remove_tags_only
Remove autoupdate --tags-only option
2020-01-08 20:04:01 -08:00
Anthony Sottile
300eb6b902
Merge pull request #1268 from pre-commit/remove_prce
Remove deprecated `pcre` language
2020-01-08 20:03:52 -08:00
Anthony Sottile
ae97bb5068 Remove autoupdate --tags-only option 2020-01-05 14:04:41 -08:00
Anthony Sottile
97e3371046 Remove deprecated pcre language 2020-01-05 13:58:44 -08:00
Anthony Sottile
3fadbefab9 Fix git version number in changelog 2020-01-02 13:05:57 -08:00
Anthony Sottile
db46dc79bb Fix one of the issue links 2020-01-02 10:28:45 -08:00
Anthony Sottile
23762d39ba v1.21.0 2020-01-02 09:46:01 -08:00
Anthony Sottile
f5e7337db6
Merge pull request #1263 from pre-commit/clear_frozen
clear 'frozen: ...' comment if autoupdate unfreezes
2020-01-01 23:58:10 -05:00
Anthony Sottile
35caf115f8 clear 'frozen: ...' comment if autoupdate unfreezes 2020-01-01 20:21:42 -08:00
Anthony Sottile
cd57ba90f5
Merge pull request #1262 from yhoiseth/patch-1
Make URL clickable
2020-01-01 11:09:46 -05:00
Yngve Høiseth
d8b54ddf4a
Make URL clickable
I added a space after as well in order to make it look more balanced.
2020-01-01 15:27:27 +01:00
Anthony Sottile
2500767f1b
Merge pull request #1259 from pre-commit/try_repo_bare
Allow try-repo to work on bare repositories
2019-12-30 14:30:05 -05:00
Anthony Sottile
968b2fdaf1 Allow try-repo to work on bare repositories 2019-12-30 11:00:45 -08:00
Anthony Sottile
3a72fb39cb
Merge pull request #1257 from pre-commit/duration
Add duration to verbose run
2019-12-28 21:48:54 -05:00
Anthony Sottile
0c0427bfbd Add duration to verbose run 2019-12-28 18:20:10 -08:00
Anthony Sottile
1074b39988
Merge pull request #1256 from pre-commit/freeze
Implement `pre-commit autoupdate --freeze`
2019-12-28 16:26:58 -05:00
Anthony Sottile
8a3c740f9e Implement pre-commit autoupdate --freeze 2019-12-28 13:07:39 -08:00
Anthony Sottile
32ce682238
Merge pull request #1210 from pre-commit/pre_merge_commit
support pre-merge-commit
2019-12-27 00:46:38 -05:00
Anthony Sottile
c699e255a1 support pre-merge-commit 2019-12-26 21:21:00 -08:00
Anthony Sottile
bf68512e7d
Merge pull request #1254 from igankevich/master
Add GIT_SSL_CAINFO environment variable to whitelist.
2019-12-26 13:22:19 -05:00
Ivan Gankevich
8c93896c48 Add GIT_SSL_CAINFO environment variable to whitelist.
This commit fixes #1253.
2019-12-26 12:43:55 +03:00
Anthony Sottile
40e0b2c57f
Merge pull request #1252 from pre-commit/normalize_crlf
Normalize crlf in tests
2019-12-23 22:33:35 -05:00
Anthony Sottile
4941ed58d5 Normalize crlf in tests 2019-12-23 18:27:30 -08:00
Anthony Sottile
517c3145f4
Merge pull request #1251 from pre-commit/calledprocesserror_cleanups
A few cleanups for CalledProcessError to hopefully make it more readable
2019-12-23 21:05:43 -05:00
Anthony Sottile
b90412742e A few cleanups for CalledProcessError to hopefully make it more readable 2019-12-23 17:46:48 -08:00
Anthony Sottile
83f0802578
Merge pull request #1249 from pre-commit/simpler_verbose
Make verbose output less special
2019-12-23 19:09:31 -05:00
Anthony Sottile
01a628d96d Make verbose output less special 2019-12-23 15:51:58 -08:00
Anthony Sottile
74fd04c67e
Merge pull request #1248 from pre-commit/top_level_files
Add top-level `files` key for inclusion
2019-12-23 15:23:12 -05:00
Anthony Sottile
6af0e33eed Add top-level files key for inclusion 2019-12-23 12:04:05 -08:00
Anthony Sottile
0ecd50b80d
Merge pull request #1232 from xhochy/conda-language
Support for conda as a language
2019-12-20 19:06:21 -08:00
Uwe L. Korn
4ff23b4eab Support for conda as a language 2019-12-20 18:43:59 -08:00
Anthony Sottile
6850c27dd6
Merge pull request #1237 from pre-commit/actual_environment_python_test
Create an actual environment for python healthy() types test
2019-12-06 15:05:02 -08:00
Anthony Sottile
2cff185c00 Revert "Fix step template breakage"
This reverts commit dc612f0219.
2019-12-06 13:35:28 -08:00
Anthony Sottile
f6b0c135ce Create an actual environment for python healthy() types test 2019-12-06 13:31:08 -08:00
Anthony Sottile
fe10811e29
Merge pull request #1236 from pre-commit/future_proof_parse_shebang_test
Use echo instead of python in parse_shebang_test
2019-12-06 13:08:31 -08:00
Anthony Sottile
9fada617b9 Use echo instead of python in parse_shebang_test 2019-12-06 11:54:53 -08:00
Anthony Sottile
cb36410c91
Merge pull request #1234 from pre-commit/step_template_breakage
Fix step template breakage
2019-12-06 09:51:28 -08:00
Anthony Sottile
2bdbd9e7a0 Fix for newest git 2019-12-06 09:27:19 -08:00
Anthony Sottile
dc612f0219 Fix step template breakage 2019-12-06 09:08:26 -08:00
Anthony Sottile
023b337ff0
Merge pull request #1224 from pre-commit/better_error_inside_dotgit
Show better error message when running inside `.git`
2019-11-18 15:15:23 -08:00
Anthony Sottile
0760bec3ff Show better error message when running inside .git 2019-11-18 14:57:41 -08:00
Anthony Sottile
0fd4a2ea38
Merge pull request #1201 from ryanrhee/rhee/grammar
grammar
2019-11-01 08:34:35 -07:00
Ryan Rhee
addc7045ba grammar 2019-11-01 11:33:04 -04:00
Anthony Sottile
6d4487e4b4
Merge pull request #1200 from ryanrhee/rhee/color
[xargs] Update docblock comment
2019-11-01 07:21:33 -07:00
Ryan Rhee
8dd05c9fce [xargs] Update docblock 2019-11-01 10:03:07 -04:00
Anthony Sottile
0bc40bc4ea v1.20.0 2019-10-28 16:29:59 -07:00
Anthony Sottile
d09930469c
Merge pull request #1197 from pre-commit/bump_sample_config
Bump the version of pre-commit-hooks in sample-config
2019-10-28 16:20:46 -07:00
Anthony Sottile
54359fff39 Bump the version of pre-commit-hooks in sample-config 2019-10-28 15:21:28 -07:00
Anthony Sottile
7d5f98b6a0
Merge pull request #1196 from pre-commit/mkdirp
Fix rare first-run race with creation of pre-commit directory
2019-10-28 15:14:21 -07:00
Anthony Sottile
8ff880faa6 Fix rare first-run race with creation of pre-commit directory 2019-10-28 14:56:03 -07:00
Anthony Sottile
6970827a84
Merge pull request #1195 from choffee/master
Update ruby-build to latest version
2019-10-28 13:25:12 -07:00
John Cooper
1bd745eccf Added new versions of rbenv and ruby-build 2019-10-28 19:54:14 +00:00
Anthony Sottile
f1b6a7842a v1.19.0 2019-10-26 12:45:55 -07:00
Anthony Sottile
7728162d7a
Merge pull request #1185 from pre-commit/healthy_types
Fix python.healthy() check with stdlib module clashes
2019-10-22 13:58:24 -07:00
Anthony Sottile
bfcee8ec9f Fix python.healthy() check with stdlib module clashes 2019-10-22 13:23:57 -07:00
Anthony Sottile
1509dc497e
Merge pull request #1179 from pre-commit/normalize_paths_to_forward_slashes
Normalize paths on windows to forward slashes
2019-10-19 15:08:56 -07:00
Anthony Sottile
707407dd49 Normalize paths on windows to forward slashes 2019-10-19 14:45:23 -07:00
Anthony Sottile
4bd6529c05
Merge pull request #1176 from pre-commit/importlib_metadata_py38
Use importlib.metadata directly in python3.8+
2019-10-17 11:36:01 -07:00
Anthony Sottile
f8f81db36d Use importlib.metadata directly in python3.8+ 2019-10-17 10:52:44 -07:00
Anthony Sottile
b3582dfd31
Merge pull request #1169 from pre-commit/color
show color in hook outputs when attached to a tty
2019-10-14 14:12:48 -07:00
Anthony Sottile
7c3404ef1f show color in hook outputs when attached to a tty 2019-10-12 23:17:36 -07:00
Anthony Sottile
c8620f35e1
Merge pull request #1170 from pre-commit/fail_fix
Fix fail type signature
2019-10-12 21:53:37 -07:00
Anthony Sottile
38766816ac Fix fail type signature 2019-10-12 21:29:15 -07:00
Anthony Sottile
2048fed110
Merge pull request #1168 from pre-commit/fix_stdout_stderr_splicing
Fix ordering of mixed stdout / stderr printing
2019-10-12 13:54:11 -07:00
Anthony Sottile
2633d38a63 Fix ordering of mixed stdout / stderr printing 2019-10-12 13:35:04 -07:00
Anthony Sottile
183c8cbb3a
Merge pull request #1161 from WillKoehrsen/not-executable-fix
Handle case when executable is not executable
2019-10-07 13:10:10 -07:00
WillKoehrsen
95dbf1190a Handle case when executable is not executable
- Changed error message if executable is not executable

Closes:[1159](https://github.com/pre-commit/pre-commit/issues/1159)
2019-10-07 15:47:30 -04:00
Anthony Sottile
bb108bf00e
Merge pull request #1160 from pre-commit/cmd_output_b
Split out cmd_output_b
2019-10-06 17:19:46 -07:00
Anthony Sottile
f612aeb22b Split out cmd_output_b 2019-10-06 15:16:47 -07:00
Anthony Sottile
ab063977ad
Merge pull request #1153 from pre-commit/init_templatedir_hook_types
Fix hook_types when calling init-templatedir
2019-09-30 11:11:07 -07:00
Anthony Sottile
36609ee305 Fix hook_types when calling init-templatedir 2019-09-30 10:29:53 -07:00
Anthony Sottile
2d0927d0b3
Merge pull request #1148 from pre-commit/newline_fixup
Fix up some newlines in output
2019-09-24 20:55:07 +02:00
Anthony Sottile
795506a486 Fix up some newlines in output 2019-09-24 10:22:44 -07:00
Anthony Sottile
cfc4910068
Merge pull request #1142 from marqueewinq/master
Add version information to error logs
2019-09-24 17:54:20 +02:00
marqueewinq
cb164ef629 replaced str concat with .write_line(); replaced \t with spaces; removed trailing space in logs 2019-09-24 16:25:27 +03:00
marqueewinq
e0155fbd66 removed meta from stdout; replaced = with : ; handled sys.version newlines; stylized errorlog to md 2019-09-24 15:50:07 +03:00
marqueewinq
de63b6a850 updated import style; put the version info on top of error message; fixed tests 2019-09-24 13:34:46 +03:00
Anthony Sottile
f735f47448
Merge pull request #1145 from pre-commit/multiple_hooks_install
Allow --hook-type to be specified multiple times
2019-09-23 20:40:49 +02:00
Anthony Sottile
a18646deb2 Allow --hook-type to be specified multiple times 2019-09-23 11:14:36 -07:00
marqueewinq
247d45af05 fixed #1141 2019-09-20 15:05:51 +03:00
Anthony Sottile
96c35185f0
Merge pull request #1124 from pre-commit/all-repos_autofix_rm-reqs
Remove redundant flake8 dependency
2019-08-28 11:58:30 -07:00
Anthony Sottile
d3474dfff3 make the tests not depend on flake8 being installed 2019-08-28 11:41:03 -07:00
Anthony Sottile
c1580be7d3 Remove redundant flake8 dependency
Committed via https://github.com/asottile/all-repos
2019-08-27 21:28:06 -07:00
Anthony Sottile
0245a67831 v1.18.3 2019-08-27 10:38:53 -07:00
Anthony Sottile
8537e7c94e Simplify if statement slightly 2019-08-27 10:35:40 -07:00
Anthony Sottile
47fb42cf1f
Merge pull request #1122 from henryykt/bugfix/windows_node_path
Fix NODE_PATH on win32
2019-08-27 10:33:18 -07:00
Henry Tang
b0c7ae4d29 Fix NODE_PATH on win32 2019-08-28 00:03:04 +08:00
Anthony Sottile
7f900395ec v1.18.2 2019-08-15 10:07:24 -07:00
Anthony Sottile
7c376cb4d6
Merge pull request #1117 from scop/py3-default-version
Stabilize python default version lookup
2019-08-15 09:51:40 -07:00
Ville Skyttä
f84b19748d Patch the correct find_executable 2019-08-15 19:28:07 +03:00
Ville Skyttä
562276098c Address more @asottile's review comments 2019-08-15 18:54:08 +03:00
Ville Skyttä
38da98d2d6 Address @asottile's review comments 2019-08-15 18:43:31 +03:00
Ville Skyttä
c377830898 Mock find_executable for find_by_sys_executable test 2019-08-15 18:34:25 +03:00
Anthony Sottile
66a78ce819
Merge pull request #1116 from scop/spelling
Spelling fixes
2019-08-15 06:11:44 -07:00
Ville Skyttä
fa2e154b41 Stabilize python default version lookup
For example, for sys.executable:
    /usr/bin/python3 -> python3.7
...the default lookup may return either python3 or python3.7. Make the
order deterministic by iterating over tuple, not set, of candidates.
2019-08-15 10:06:31 +03:00
Ville Skyttä
dd46fde384 Spelling fixes 2019-08-15 08:26:01 +03:00
Anthony Sottile
7c69730ad2 v1.18.1 2019-08-11 14:07:20 -07:00
Anthony Sottile
9297befe5c
Merge pull request #1113 from zimbatm/rust-language-fix
rust language: use the new cargo install command
2019-08-11 14:05:11 -07:00
zimbatm
cbbfcd20b4 rust language: use the new cargo install command
cargo install now requires an additional `--path <TARGET>` argument.
2019-08-11 13:36:13 -07:00
Anthony Sottile
07f66417dd v1.18.0 2019-08-03 15:21:26 -07:00
Anthony Sottile
e6d63d70be
Merge pull request #1107 from pre-commit/init_templatedir_fixes
Several fixes for init-templatedir
2019-08-03 13:55:01 -07:00
Anthony Sottile
f48c0abcbe Use expanduser in init-templatedir like git does 2019-08-03 13:30:13 -07:00
Anthony Sottile
cab8036db3 Don't treat unset init.templateDir as the current directory 2019-08-03 11:55:53 -07:00
Anthony Sottile
da80cc6479 Allow init-templatedir to be called outside of git 2019-08-03 11:41:54 -07:00
Anthony Sottile
7f1e9c1907
Merge pull request #1103 from pre-commit/dumb_term
Disable color if TERM=dumb is detected
2019-07-27 19:49:20 -07:00
Anthony Sottile
120cae9d41 Disable color if TERM=dumb is detected 2019-07-27 13:46:30 -07:00
Anthony Sottile
376d283ba3
Merge pull request #1094 from geieredgar/windows-docker-fix
Fix docker based hooks failing on Windows
2019-07-25 06:19:21 -07:00
Edgar Geier
d4a9ff4d1f Simplify docker user fallback implementation and test 2019-07-25 11:22:59 +02:00
Anthony Sottile
332b98bd86
Merge pull request #1098 from geieredgar/switch-to-pre-commit-color-env
Switch from NO_COLOR to PRE_COMMIT_COLOR environment variable
2019-07-23 09:07:54 -07:00
Edgar Geier
aaa249bda9 Overwrite default value of --color argument with PRE_COMMIT_COLOR env var 2019-07-23 17:42:28 +02:00
Edgar Geier
c75d8939f8 Revert "Don't use color if NO_COLOR environment variable is set"
This reverts commit 1bf9ff7493.
2019-07-23 17:40:08 +02:00
Edgar Geier
df919e6ab5 Revert "Require NO_COLOR environment variable to be non-empty to disable colors"
This reverts commit 01d3a72a0e.
2019-07-23 17:39:34 +02:00
Edgar Geier
e82c1e7259 Revert "Add tests for NO_COLOR support"
This reverts commit 8520455042.
2019-07-23 17:38:50 +02:00
Edgar Geier
69b2cb5ea6 Revert "Simplify NO_COLOR check"
This reverts commit e9ff1be96c.
2019-07-23 17:38:29 +02:00
Edgar Geier
07797f3fff Revert "Change test to remove missed branch"
This reverts commit 84dcb91119.
2019-07-23 17:37:44 +02:00
Edgar Geier
a21a4f46c7 Fix missing create=True attribute in docker tests 2019-07-23 15:35:19 +02:00
Edgar Geier
b43b6a61ab Add docker uid and gid fallback tests 2019-07-23 15:14:06 +02:00
Edgar Geier
b7ce5db782 Use fallback uid and gid if os.getuid() and os.getgid() are unavailable 2019-07-23 12:38:09 +02:00
Anthony Sottile
1874cea63e
Merge pull request #1092 from geieredgar/respect-no-color-environment-variable
Don't use color if NO_COLOR environment variable is set
2019-07-22 15:06:23 -07:00
Edgar Geier
84dcb91119 Change test to remove missed branch 2019-07-22 20:23:59 +02:00
Edgar Geier
e9ff1be96c Simplify NO_COLOR check 2019-07-22 20:09:32 +02:00
Edgar Geier
8520455042 Add tests for NO_COLOR support 2019-07-22 20:07:16 +02:00
Edgar Geier
01d3a72a0e Require NO_COLOR environment variable to be non-empty to disable colors 2019-07-22 19:35:39 +02:00
Edgar Geier
1bf9ff7493 Don't use color if NO_COLOR environment variable is set 2019-07-22 19:18:36 +02:00
Anthony Sottile
1bd9bfefeb
Merge pull request #1090 from pre-commit/template_dir
Implement `pre-commit init-templatedir`
2019-07-20 20:56:02 -07:00
Anthony Sottile
9a52eefc99 Implement pre-commit init-templatedir 2019-07-20 20:33:42 -07:00
Anthony Sottile
83fbbaea9a
Merge pull request #1089 from pre-commit/autoupdate_non_master_default_branch
Make autoupdate work for non-master default branches
2019-07-20 17:41:19 -07:00
Anthony Sottile
3def940574 reorder pre-commit sub commands 2019-07-20 16:28:35 -07:00
Anthony Sottile
8be0f857e8 Make autoupdate work for non-master default branches 2019-07-20 15:30:30 -07:00
Anthony Sottile
7769915a0b
Merge pull request #1088 from pre-commit/autoupdate_shallow_fix
Fix autoupdate to always use non-shallow clone
2019-07-20 15:21:27 -07:00
Anthony Sottile
73250ff4e3 Fix autoupdate to always use non-shallow clone 2019-07-20 14:59:49 -07:00
Anthony Sottile
95afd642f5
Merge pull request #1079 from madkinsz/run-stage-prompt-1078
Added hook-stage print to output for missing hook id
2019-07-09 12:10:43 -07:00
Michael Adkins
02d95c033c Fixed code style 2019-07-09 13:48:06 -05:00
Michael Adkins
c148845a98 Added hook-stage print to output for missing hook id 2019-07-09 13:06:18 -05:00
Anthony Sottile
927b2ab3f8
Merge pull request #1077 from pre-commit/shallow_fetch_fetch_head
Fix shallow fetch by checking out FETCH_HEAD
2019-07-08 08:22:21 -07:00
Anthony Sottile
01653b8077 Fix shallow fetch by checking out FETCH_HEAD 2019-07-07 22:10:32 -07:00
Anthony Sottile
24d4bc82d7
Merge pull request #1075 from pre-commit/manifest_unnecessary
MANIFEST.in is unnecessary with `license_file`
2019-07-07 13:01:27 -04:00
Anthony Sottile
b12e4e82aa MANIFEST.in is unnecessary with license_file 2019-07-07 09:41:28 -07:00
Anthony Sottile
0cf2638b3b
Merge pull request #1067 from pre-commit/devenv
Suggest tox --devenv instead of tox -e venv
2019-06-26 07:43:06 -07:00
Anthony Sottile
f4b3add8ab Suggest tox --devenv instead of tox -e venv 2019-06-25 22:46:24 -07:00
Anthony Sottile
702f1401d4
Merge pull request #1062 from pre-commit/sys_executable_matches
Use sys.executable if it matches on posix as well
2019-06-17 13:12:25 -07:00
Anthony Sottile
9bdce088c8 Use sys.executable if it matches on posix as well 2019-06-17 07:54:38 -07:00
Anthony Sottile
fdf476a5a1
Merge pull request #1056 from pre-commit/document_new_language
Document adding a supported language
2019-06-09 08:51:07 -07:00
Anthony Sottile
9d1342aeb6 Document adding a supported language 2019-06-09 08:42:09 -07:00
Anthony Sottile
e0c7db1021
Merge pull request #1054 from pre-commit/rust_ap_linux
Fixes for rust tests on azure pipelines linux
2019-06-06 09:18:40 -07:00
Anthony Sottile
90128c5a9d Fixes for rust tests on azure pipelines linux 2019-06-06 08:50:01 -07:00
Anthony Sottile
016eda9f3c v1.17.0 2019-06-06 08:30:11 -07:00
Anthony Sottile
a75fe69984
Merge pull request #1051 from mandarvaze/master
Pass color option to git diff (on failure)
2019-06-01 08:11:45 -07:00
Mandar Vaze
3d7b374bef Pass correct value to git color based on args.color 2019-06-01 17:33:27 +05:30
Mandar Vaze
64f0178b75 Pass color option to git diff unconditionally 2019-06-01 07:40:20 +05:30
Anthony Sottile
fff3ad518c
Merge pull request #1052 from pre-commit/rust_ap
azure pipelines now has rust by default on windows
2019-05-31 13:35:49 -07:00
Anthony Sottile
071cc422c7 xfail default language version check for azure pipelines 2019-05-31 13:17:54 -07:00
Anthony Sottile
e08d373be3 azure pipelines now has rust by default on windows 2019-05-31 09:51:08 -07:00
Mandar Vaze
4f4767c9e0 Pass color option to git diff (on failure)
Fixes #1007
2019-05-31 16:42:16 +05:30
Anthony Sottile
0b6a39768a
Merge pull request #1048 from pre-commit/cfgv_2
fixes for cfgv>=2
2019-05-27 13:59:24 -07:00
Anthony Sottile
625750eeef fixes for cfgv>=2 2019-05-27 13:37:49 -07:00
Anthony Sottile
099f521b7e
Merge pull request #1045 from pre-commit/fix_test_pre_commit_on_path
Fix test_environment_not_sourced when pre-commit is installed globally
2019-05-26 19:11:57 -07:00
Anthony Sottile
e868add5a3 Fix test_environment_not_sourced when pre-commit is installed globally 2019-05-26 17:03:15 -07:00
Anthony Sottile
28664d6bf1
Merge pull request #1043 from pre-commit/rmtree_readonly_dirs
Fix rmtree for readonly directories
2019-05-22 12:32:54 -07:00
Anthony Sottile
da44d4267e Fix rmtree for readonly directories 2019-05-22 11:04:35 -07:00
Anthony Sottile
77947f212e
Merge pull request #1033 from yoavcaspi/fix_tox_venv
restore testenv:venv section
2019-05-13 15:19:15 -07:00
Yoav Caspi
bb78de09d1 move testenv:venv section to be in lexicographic order 2019-05-14 00:08:54 +03:00
Anthony Sottile
bd212393ae
Merge pull request #1027 from pre-commit/keyboard_interrupt_fix
Fix handling of SIGINT in hook script
2019-05-13 13:17:48 -07:00
Yoav Caspi
471fe7d58f restore testenv:venv section. to be able to set the dev environment as described in the CONTRIBUTING.md 2019-05-13 23:14:41 +03:00
Anthony Sottile
fb15fa65f2 Fix handling of SIGINT in hook script 2019-05-13 12:33:51 -07:00
Anthony Sottile
e10b81858a
Merge pull request #1028 from yoavcaspi/warn_unknown_keys
Add warning to additional keys in config
2019-05-12 15:04:41 -07:00
Yoav Caspi
7a998a091e improve function name 2019-05-12 23:29:42 +03:00
Yoav Caspi
ba7760b705 Add a test to validate that cfgv.WarnAdditionalKeys working as expected in the relevant config schemas 2019-05-12 15:09:15 +03:00
Anthony Sottile
a889f0bfd5
Merge pull request #1030 from pre-commit/improved_interrupt_output
Improve output when interrupted (^C)
2019-05-11 20:18:06 -07:00
Yoav Caspi
217d31ec1c Add a check and test to the real top level and improve the warning message 2019-05-11 22:57:52 +03:00
Anthony Sottile
f21316ebe8 Improve output when interrupted (^C) 2019-05-11 12:19:00 -07:00
Anthony Sottile
1c7ac67fba
Merge pull request #1029 from yoavcaspi/typo_fix
typo fix
2019-05-11 12:09:29 -07:00
Yoav Caspi
59c282b184 typo fix 2019-05-11 21:47:26 +03:00
Yoav Caspi
fd9d9d276b Add warning to additional keys in config 2019-05-11 20:59:34 +03:00
Anthony Sottile
b3bfecde39 Fix markdown typo 2019-05-08 08:27:53 -07:00
Anthony Sottile
168ede2be0 v1.16.1 2019-05-08 08:26:15 -07:00
Anthony Sottile
c2980217a8
Merge pull request #1022 from pre-commit/1021
Don't attempt to decode the healthy response
2019-05-07 16:23:14 -07:00
Anthony Sottile
d74ee6d743 Don't attempt to decode the healthy response 2019-05-07 09:38:17 -07:00
Anthony Sottile
8df6b22f4f
Merge pull request #1018 from pre-commit/dates_in_changelog
Add dates to changelog entries
2019-05-04 14:27:39 -04:00
Anthony Sottile
f72a82359c Add dates to changelog entries
Automated with this script:

```bash
git tag -l | sed 's/^v//g' |
    xargs --replace bash -c 'sed -r -i "s/^({})$/\1 - $(git show --format=%ad --date=short --no-patch v{})/g" CHANGELOG.md'
sed -r -i 's/^(=+)$/\1=============/g' CHANGELOG.md
                     # - 2019-01-01
```

Thanks @hynek for the suggestion
2019-05-04 08:43:11 -07:00
Anthony Sottile
c65dd3ea3a Manually fix up 0.1 tag log 2019-05-04 08:40:51 -07:00
Anthony Sottile
75651dc8b0 v1.16.0 2019-05-04 08:26:42 -07:00
Anthony Sottile
72f98d26e6
Merge pull request #1015 from Myrheimb/patch-1
Could this fix #1013?
2019-04-29 13:44:52 -07:00
Bjørnar Myrheim
00e048995c
Yet another try to fix #1013
One again changed the string and file referenced to handle single quotes properly inside pcre greps.
2019-04-29 21:45:56 +02:00
Bjørnar Myrheim
5977b1125b
Another try to fix #1013
Properly changed the string and file referenced to handle single quotes properly inside pcre greps.
2019-04-29 21:33:58 +02:00
Bjørnar Myrheim
5590fc7a53
New try to fix #1013
Changed the string and file referenced to handle single quotes properly inside pcre greps.
2019-04-29 21:20:22 +02:00
Bjørnar Myrheim
e9e665d042
Could this fix #1013?
I'm still a beginner, but a single single quote looked a bit off to me.
Could adding another single quote after pre fix this issue?
2019-04-29 20:22:18 +02:00
Anthony Sottile
c97dfb2281
Merge pull request #1014 from mxr/patch-1
Whitespace nit
2019-04-28 22:53:24 -07:00
Max R
64a65351b9
Whitespace nit 2019-04-29 01:40:12 -04:00
Anthony Sottile
ee80f6218a Fix badge url 2019-04-28 22:08:21 -07:00
Anthony Sottile
fee8ddd54b
Merge pull request #1012 from pre-commit/azure_pipelines
azure pipelines [skip travis] [skip appveyor]
2019-04-28 22:00:31 -07:00
Anthony Sottile
9c6edab726 azure pipelines [skip travis] [skip appveyor] 2019-04-28 21:39:06 -07:00
Anthony Sottile
09e64e8ff6
Merge pull request #1011 from pre-commit/multi_install_windows
Fix double legacy install on windows
2019-04-27 16:01:32 -07:00
Anthony Sottile
af2c6de9ae Fix double legacy install on windows 2019-04-27 15:10:01 -07:00
Anthony Sottile
b8300268bf
Merge pull request #1004 from marcjay/add_prepare-commit-msg_stage
Add support for prepare-commit-msg hooks
2019-04-21 15:56:16 -07:00
Anthony Sottile
81a94b8048
Merge pull request #1005 from asottile/gocache_appveyor
passenv %LocalAppData% so go functions on windows
2019-04-21 15:54:32 -07:00
Anthony Sottile
efeef97f5e passenv %LocalAppData% so go functions on windows 2019-04-21 15:32:27 -07:00
Marc Jay
82969e4ba3 Use set rather than list for commit message related stages, remove
default file open modes, tidy up bash call for failing hook test
2019-04-21 21:58:01 +01:00
Marc Jay
64467f6ab9 Fix broken test_manifest_hooks test 2019-04-21 21:54:23 +01:00
Marc Jay
e60f541559 Adds support for prepare-commit-msg hooks
Adds a prepare-commit-msg hook stage which allows for hooks which add
dynamic suggested/placeholder text to commit messages that an author can
use as a starting point for writing a commit message
2019-04-21 21:07:13 +01:00
Anthony Sottile
809b7482df v1.15.2 2019-04-16 11:33:16 -07:00
Anthony Sottile
2d4ea61c93
Merge pull request #998 from pre-commit/full_clone_non_mainline_tag
Fix full clone + non-mainline tag
2019-04-16 11:30:57 -07:00
Anthony Sottile
eab24f3e48 Fix full clone + non-mainline tag 2019-04-16 10:30:05 -07:00
Anthony Sottile
b33f2c40d8 v1.15.1 2019-04-01 09:44:09 -07:00
Anthony Sottile
6302dec938
Merge pull request #987 from asottile/no_sc_arg_max
Bound maxsize by 4096 when SC_ARG_MAX is not present
2019-04-01 09:42:44 -07:00
Anthony Sottile
681d78b6cf Bound maxsize by 4096 when SC_ARG_MAX is not present 2019-04-01 09:25:20 -07:00
Anthony Sottile
5169f455c9 v1.15.0 2019-03-30 16:13:03 -07:00
Anthony Sottile
a009dd6caf
Merge pull request #982 from bnorquist/master
add helpful CI message
2019-03-30 15:53:28 -07:00
Anthony Sottile
668e6415c0 Adjust messaging slightly 2019-03-30 14:05:24 -07:00
Ben Norquist
71a740d65d add helpful message and test 2019-03-30 14:00:03 -07:00
Anthony Sottile
03ac3b0840
Merge pull request #981 from tristan0x/fix/infinite-process-recursion
Do not run legacy script again when this is the one being executed
2019-03-30 13:54:42 -07:00
Anthony Sottile
bbc3130af2 Produce slightly more helpful message 2019-03-30 13:40:37 -07:00
Anthony Sottile
2fbe359846
Merge pull request #986 from tim77/master
Specify env python explicitly.
2019-03-30 11:35:50 -07:00
Artem Polishchuk
9f0cfed600 Specify env python explicitly. 2019-03-30 19:56:52 +02:00
Tristan Carel
ec72cb7260
assert that the pre-commit script being executed is not the legacy 2019-03-29 13:55:04 +01:00
Tristan Carel
cd61269389
Do not run legacy script again when this is the one being executed 2019-03-27 06:24:47 +01:00
Anthony Sottile
da00fa98f9
Merge pull request #978 from pre-commit/all-repos_autofix_pre-commit-autoupdate
Run pre-commit autoupdate
2019-03-21 22:50:41 -07:00
Anthony Sottile
dc28922ccb Run pre-commit autoupdate
Committed via https://github.com/asottile/all-repos
2019-03-21 21:09:33 -07:00
Anthony Sottile
06d01c8c9d
Merge pull request #977 from asottile/minimum_pre_commit_version
Add top level minimum_pre_commit_version
2019-03-21 18:51:19 -07:00
Anthony Sottile
c78b6967cd Add top level minimum_pre_commit_version 2019-03-21 18:29:17 -07:00
Anthony Sottile
264161c182
Merge pull request #973 from DanielChabrowski/try-repo-fix
Fix try-repo for staged untracked changes
2019-03-19 13:09:28 -07:00
DanielChabrowski
c7b369a7be Add test for xargs propagating kwargs to cmd_output 2019-03-19 20:36:21 +01:00
DanielChabrowski
7023caba94 Execute with xargs in try_repo 2019-03-19 20:35:52 +01:00
DanielChabrowski
24a2c3d8db Add support for passing cwd and env to xargs 2019-03-19 20:35:21 +01:00
Anthony Sottile
a18b683d12
Add review suggestion
Co-Authored-By: DanielChabrowski <dantezstudio@gmail.com>
2019-03-18 02:31:47 +01:00
DanielChabrowski
888787fb2d Fix try-repo for staged untracked changes 2019-03-18 02:04:50 +01:00
Anthony Sottile
71c238d4ec
Merge pull request #972 from javabrett/test-no-git-env
Added test for git.no_git_env()
2019-03-17 17:48:27 -07:00
Brett Randall
7d7c9c0fde
Additional fixes prompted by double-quote-string-fixer.
Signed-off-by: Brett Randall <javabrett@gmail.com>
2019-03-18 10:24:46 +11:00
Brett Randall
f5af95cc9d Added test for git.no_git_env().
Signed-off-by: Brett Randall <javabrett@gmail.com>
2019-03-18 10:23:54 +11:00
Brett Randall
f673f8bb55 Added double-quote-string-fixer pre-commit hook.
Signed-off-by: Brett Randall <javabrett@gmail.com>
2019-03-18 09:47:31 +11:00
Anthony Sottile
185a288645
Merge pull request #958 from DanielChabrowski/shallow-clone
Allow shallow cloning
2019-03-15 20:45:51 -07:00
DanielChabrowski
ab1df03418 Ignore shallow clone coverage on appveyor
Appveyor uses old version of git so shallow clone
always fails and lines 150-151 are not executed.
2019-03-16 00:16:42 +01:00
DanielChabrowski
a170e60daa Remove protocol.version 1 shallow cloning 2019-03-15 23:46:35 +01:00
DanielChabrowski
e748da2abe Remove clone depth check 2019-03-15 23:25:04 +01:00
Anthony Sottile
ec2e15f086 pre-commit run --all-files 2019-03-14 18:32:27 -07:00
Anthony Sottile
d71a75fea2 Run npm install before npm install -g 2019-03-14 18:31:57 -07:00
Anthony Sottile
3cb35e8679 Revert "Merge pull request #949 from asottile/npm_install_git"
This reverts commit a4c1a701bc, reversing
changes made to 889124b5ca.
2019-03-14 18:20:30 -07:00
Anthony Sottile
3e76af4912
Merge pull request #966 from pre-commit/command_length_better
Compute the maximum command length more accurately
2019-03-11 10:19:11 -07:00
Anthony Sottile
545bc0d21c
Merge pull request #967 from asottile/improve_testsuite_speed_windows
Improve testsuite speed on windows by ~23 seconds
2019-03-10 12:48:48 -07:00
Anthony Sottile
7a763a9851 Improve testsuite speed on windows by ~23 seconds 2019-03-10 11:27:25 -07:00
Anthony Sottile
985f09ff88 Compute the maximum command length more accurately 2019-03-10 11:14:22 -07:00
DanielChabrowski
960bcc9614 Fix relative path repos 2019-03-09 23:56:37 +01:00
DanielChabrowski
b920f3cc6b Reuse the directory for cloning 2019-03-09 22:59:56 +01:00
Anthony Sottile
cac1a3f34e
Merge pull request #959 from asottile/non_cd
Don't require git for clean, gc, sample-config
2019-03-04 08:46:54 -08:00
Anthony Sottile
917586a0e0 Don't require git for clean, gc, sample-config 2019-03-02 19:01:05 -08:00
DanielChabrowski
e74253d2de Allow shallow cloning 2019-03-03 01:35:53 +01:00
Anthony Sottile
518a72d7e7
Merge pull request #956 from pre-commit/all-repos_autofix_setup-py-upgrade
Migrate setup.py to setup.cfg declarative metadata
2019-02-27 22:55:37 -08:00
Anthony Sottile
f9cfaef5aa Migrate setup.py to setup.cfg declarative metadata
Committed via https://github.com/asottile/all-repos
2019-02-27 22:12:03 -08:00
Anthony Sottile
aa4bc9d241 v1.14.4 2019-02-18 09:13:54 -08:00
Anthony Sottile
35dd1907b6
Merge pull request #944 from minrk/respect-git-exec-path
don't unset GIT_EXEC_PATH
2019-02-18 08:14:34 -08:00
Anthony Sottile
a4c1a701bc
Merge pull request #949 from asottile/npm_install_git
Use npm install git+file:// instead of npm install .
2019-02-17 15:51:53 -05:00
Anthony Sottile
6088b1f995 3 slashes works around an npm bug
https://npm.community/t/npm-install-g-git-file-c-path-to-repository-does-not-work-on-windows/5453
2019-02-17 12:17:46 -08:00
Anthony Sottile
136834038d Use npm install git+file:// instead of npm install . 2019-02-17 10:14:21 -08:00
Min RK
9cde231665 respect GIT_EXEC_PATH env
This env may be required for git to work,
unsetting it can cause clone to fail

occurs with bundled git, e.g. Fork git client
2019-02-16 09:14:11 +01:00
Anthony Sottile
889124b5ca
Merge pull request #948 from firba1/bariteau/add_git_ssh_command_support
pass GIT_SSH_COMMAND to git commands
2019-02-15 18:30:03 -05:00
Benjamin Bariteau
db04d612e0 pass GIT_SSH_COMMAND to git commands, refs #947 2019-02-15 14:37:53 -08:00
Anthony Sottile
2fa0fabb05 v1.14.3 2019-02-04 08:43:31 -08:00
Anthony Sottile
f3b4565e8c
Merge pull request #936 from asottile/require_new_virtualenv
Require new virtualenv
2019-02-03 14:29:34 -08:00
Anthony Sottile
728349bc4b Require new virtualenv
I'd like to start using metadata-based setup (`setup.cfg`) and this is the
minimum virtualenv version needed to build those.
2019-02-03 14:01:28 -08:00
Anthony Sottile
7e2ad215c2
Merge pull request #933 from jessebona/patch-1
Fix crash on `pre-commit migrate-config` when configuration is empty
2019-02-01 17:31:38 -08:00
Anthony Sottile
1a3d296d87
Trailing whitespace too
Github editor is a fickle beast
2019-02-01 16:47:08 -08:00
Jesse Bona
e2ee95d9b2
Update migrate_config_test.py
Added second blank line between test_migrate_config_sha_to_rev and test_empty_configuration_file_user_error
2019-02-02 11:32:09 +11:00
Jesse Bona
8a7142d763
Added test for blank configuration file 2019-02-02 10:38:04 +11:00
Jesse Bona
f2be2ead35
Update migrate_config.py
Corrected loop condition to not run if configuration file only contains new lines.
2019-02-02 10:34:53 +11:00
Jesse Bona
7b491c7110
Update migrate_config.py
Added if statement to prevent looping through header lines if configuration file is empty
2019-02-01 19:15:59 +11:00
Anthony Sottile
35a78c06d0
Merge pull request #928 from pre-commit/all-repos_autofix_pre-commit-flake8-migrate
Migrate to official pycqa/flake8 hooks repo
2019-01-30 00:55:15 -08:00
Anthony Sottile
29460606b2 Migrate to official pycqa/flake8 hooks repo
Committed via https://github.com/asottile/all-repos
2019-01-30 00:39:01 -08:00
Anthony Sottile
b268b37482
Merge pull request #927 from pre-commit/all-repos_autofix_all-repos-sed
Add W504 to ignored autopep8 rules
2019-01-29 22:20:22 -08:00
Anthony Sottile
1f3c6ce035 Add W504 to ignored autopep8 rules
Committed via https://github.com/asottile/all-repos
2019-01-29 22:09:47 -08:00
Anthony Sottile
160238220f
Merge pull request #924 from ashanbrown/unset-gobin
Ensure that GOBIN is unset when installing a golang hook
2019-01-27 18:18:06 -08:00
Andrew S. Brown
1eed1b51b8 Address PR feedback 2019-01-27 17:55:11 -08:00
Andrew S. Brown
950bc2c7fb Shorten line 2019-01-27 14:02:53 -08:00
Andrew S. Brown
fe5390c068 Ensure that GOBIN is not set when installing a golang hook
If GOBIN is set, it will be used as the install path instead of the first item
from GOPATH followed by "/bin".  If it is used, commands will not be isolated
between different repos.
2019-01-27 13:34:47 -08:00
Anthony Sottile
6bc7b91dd1
Merge pull request #921 from pre-commit/speed_up_filenames_filtering
Speed up filename filtering.
2019-01-24 08:00:18 -08:00
Anthony Sottile
b1389603e0 Speed up filename filtering.
Before there was a `getcwd` syscall for every filename which was filtered.

Instead this is now cached per-run.

- When all files are identified by filename only: ~45% improvement
- When no files are identified by filename only: ~55% improvement

This makes little difference to overall execution, the bigger win is
eliminating the `memoize_by_cwd` hack.  Just removing the memoization would
have *increased* the runtime by 300-500%.
2019-01-23 20:48:41 -08:00
Anthony Sottile
38308dc02d
Merge pull request #919 from asottile/node_fixed
Revert "Merge pull request #888 from pre-commit/887_xfail_windows_node_again"
2019-01-20 23:00:29 -08:00
Anthony Sottile
ea58596a56 Revert "Merge pull request #888 from pre-commit/887_xfail_windows_node_again"
This reverts commit 45a34d6b75, reversing
changes made to d0c62aae7a.
2019-01-20 22:22:39 -08:00
Anthony Sottile
570d629a14
Merge pull request #916 from pre-commit/asottile-patch-1
Fix non-parallel option changelog entry
2019-01-11 08:20:01 -08:00
Anthony Sottile
9898b490df
Fix non-parallel option changelog entry 2019-01-11 07:39:51 -08:00
Anthony Sottile
90cfe677bc v1.14.2 2019-01-10 16:04:07 -08:00
Anthony Sottile
4621859936
Merge pull request #915 from pre-commit/defpath
Be more timid about choosing a shebang
2019-01-10 15:21:38 -08:00
Anthony Sottile
4f8a9580aa Be more timid about choosing a shebang 2019-01-10 14:26:55 -08:00
Anthony Sottile
cc1af1da06 v1.14.1 2019-01-10 10:21:36 -08:00
Anthony Sottile
f1f299c4b8
Merge pull request #914 from pre-commit/self_exe_python
Use sys.executable if it matches the requested version
2019-01-10 09:44:47 -08:00
Anthony Sottile
32d65236bf Use sys.executable if it matches the requested version 2019-01-10 06:48:49 -08:00
Anthony Sottile
1cf4b54cba v1.14.0 2019-01-08 10:57:44 -08:00
Anthony Sottile
84c398d6f4
Merge pull request #912 from asottile/intent_to_add
Fix staged-files-only for `git add --intent-to-add` files
2019-01-08 10:36:00 -08:00
Anthony Sottile
e60579d9f3 Fix staged-files-only for git add --intent-to-add files 2019-01-08 09:28:57 -08:00
Anthony Sottile
2941a1142b
Merge pull request #911 from asottile/bump_cfgv
bump cfgv, forgot in last PR
2019-01-07 08:15:42 -08:00
Anthony Sottile
8432d9b692 bump cfgv, forgot in last PR 2019-01-07 07:38:16 -08:00
Anthony Sottile
a2b536030a
Merge pull request #910 from asottile/cleanup_tests
small cleanups in tests
2019-01-06 12:59:13 -08:00
Anthony Sottile
bea33af310 small cleanups in tests 2019-01-06 12:08:52 -08:00
Anthony Sottile
782244a7b8
Merge pull request #909 from asottile/default_stages
Implement default_stages
2019-01-06 11:29:41 -08:00
Anthony Sottile
bd65d8947f Implement default_stages 2019-01-06 10:32:58 -08:00
Anthony Sottile
9c6a1d80d6
Merge pull request #908 from asottile/default_language_version
Implement default_language_version
2019-01-05 13:47:18 -08:00
Anthony Sottile
d3b5a41830 Implement default_language_version 2019-01-05 13:15:23 -08:00
Anthony Sottile
579b05e424
Merge pull request #907 from asottile/schema_default
Default local / meta through cfgv
2019-01-05 09:06:18 -08:00
Anthony Sottile
fc84567923 Default local / meta through cfgv 2019-01-05 08:31:03 -08:00
Anthony Sottile
46ae88c1f0
Merge pull request #906 from asottile/gc
pre-commit gc
2019-01-02 19:46:38 -08:00
Anthony Sottile
9e34e6e316 pre-commit gc 2019-01-02 19:07:23 -08:00
Anthony Sottile
d7f5c6f979
Merge pull request #904 from asottile/clone_uncommitted
Teach pre-commit try-repo to clone uncommitted changes
2019-01-01 15:56:02 -08:00
Anthony Sottile
e4f0b4c1b7 Only configure logging inside the context 2019-01-01 15:01:37 -08:00
Anthony Sottile
bdc58cc33f Teach pre-commit try-repo to clone uncommitted changes 2019-01-01 15:01:36 -08:00
Anthony Sottile
e04505a669
Merge pull request #903 from pre-commit/relative_chdir_try_repo
Fix try-repo relpath while in a sub-directory
2019-01-01 12:35:00 -08:00
Anthony Sottile
4da461d90a Fix try-repo relpath while in a sub-directory 2019-01-01 11:57:06 -08:00
Anthony Sottile
b31cb22d8b
Merge pull request #902 from pre-commit/windows_100
Add more 'no cover windows' comments
2018-12-31 14:35:09 -08:00
Anthony Sottile
4f9d0397b5 Add more 'no cover windows' comments 2018-12-31 14:06:10 -08:00
Anthony Sottile
177164b5a2
Merge pull request #901 from pre-commit/no_asdict
Use Hook api in languages
2018-12-31 13:27:32 -08:00
Anthony Sottile
b59d7197ff Use Hook api in languages 2018-12-31 13:16:48 -08:00
Anthony Sottile
5f9a667470
Merge pull request #900 from pre-commit/simplify_dict
just use normal dicts in tests
2018-12-31 11:43:36 -08:00
Anthony Sottile
e4cf5f321b just use normal dicts in tests 2018-12-31 11:15:22 -08:00
Anthony Sottile
2125a4cf47
Merge pull request #899 from pre-commit/repository_refactor
Refactor pre_commit.repository and factor out cached-property
2018-12-30 21:47:36 -08:00
Anthony Sottile
c577ed92e7 Refactor pre_commit.repository and factor out cached-property 2018-12-30 20:56:49 -08:00
Anthony Sottile
7448e588ff
Merge pull request #898 from pre-commit/identity
Add identity meta hook
2018-12-29 13:34:30 -08:00
Anthony Sottile
a49a34ef3d Add identity meta hook 2018-12-29 13:13:31 -08:00
Anthony Sottile
d2b92e8170
Merge pull request #894 from s0undt3ch/hotfix/no-gpg-sign
Don't fail if GPG signing is configured by default. All references.
2018-12-28 16:20:51 -08:00
Anthony Sottile
160a11a0a7 Improve git_commit helper 2018-12-28 15:32:25 -08:00
Pedro Algarvio
28c97a95cd
Don't fail if GPG signing is configured by default. All references. 2018-12-28 20:11:37 +00:00
Anthony Sottile
7afb2944b2
Merge pull request #896 from pre-commit/cleanup
misc cleanup
2018-12-27 19:26:16 -08:00
Anthony Sottile
d46bbc486f Use in_git_dir in more places 2018-12-27 18:25:54 -08:00
Anthony Sottile
2af0b0b4f3 better no-cover for windows 2018-12-27 18:25:52 -08:00
Anthony Sottile
8c550d0157
Merge pull request #886 from s0undt3ch/features/repo-alias
Allow aliasing a hook and calling it by it's alias
2018-12-27 12:17:29 -08:00
Anthony Sottile
6d40b2a38b
Simplify the skip test to only test skipping 2018-12-27 09:24:41 -08:00
Pedro Algarvio
8ffd1f69d7
Address review comments 2018-12-27 17:18:11 +00:00
Pedro Algarvio
79c8b1fceb
Allow hook alias to be used in SKIP. Includes test. 2018-12-27 12:03:27 +00:00
Pedro Algarvio
5840f880a9
Address review comments and test failures 2018-12-27 12:03:27 +00:00
Pedro Algarvio
afbc57f2ad
Go back to optional. Requires less changes to existing code. 2018-12-27 12:03:27 +00:00
Pedro Algarvio
b096c0b8f2
Allow aliasing a hook and calling it by it's alias 2018-12-27 12:03:27 +00:00
Anthony Sottile
c5c0a0699b
Merge pull request #895 from pre-commit/rip_runner
Remove stateful Runner
2018-12-26 23:11:38 -08:00
Anthony Sottile
2b8291d18f add a no-cover for py3 [ci skip] 2018-12-26 22:45:13 -08:00
Anthony Sottile
fe409f1a43 Remove stateful Runner 2018-12-26 22:33:21 -08:00
Anthony Sottile
1d40cc2104
Merge pull request #893 from pre-commit/shebang
Pick a better python shebang for hook executable
2018-12-25 21:05:21 -08:00
Anthony Sottile
de942894ff Pick a better python shebang for hook executable 2018-12-25 12:11:02 -08:00
Anthony Sottile
748c2ad273 v1.13.0 2018-12-20 12:05:22 -08:00
Anthony Sottile
45a34d6b75
Merge pull request #888 from pre-commit/887_xfail_windows_node_again
xfail windows node until #887 is resolved
2018-12-19 17:04:21 -08:00
Anthony Sottile
91782bb6c8 xfail windows node until #887 is resolved 2018-12-19 17:03:52 -08:00
Anthony Sottile
d0c62aae7a
Merge pull request #889 from pre-commit/no_document
Switch from deprecated docs-off args to --no-document
2018-12-19 14:40:22 -08:00
Anthony Sottile
435d9945a3 Switch from deprecated docs-off args to --no-document 2018-12-19 14:22:09 -08:00
Anthony Sottile
c292ba892b
Merge pull request #885 from s0undt3ch/hotfix/no-gpg-sign
Don't fail if GPG signing is configured by default
2018-12-14 16:25:50 -05:00
Anthony Sottile
15b1f118b5
Update fixtures.py 2018-12-14 13:14:13 -08:00
Pedro Algarvio
afeac2f099
Don't fail if GPG signing is configured by default 2018-12-14 11:45:01 +00:00
Anthony Sottile
51659ee606
Merge pull request #874 from chriskuehl/shuffle-args
Shuffle arguments before running hooks
2018-11-19 23:00:36 -08:00
Chris Kuehl
45e3dab00d Shuffle arguments before running hooks 2018-11-19 17:53:19 -08:00
Anthony Sottile
6b6ebe7e30
Merge pull request #870 from pre-commit/bump_sample
Upgrade the sample config
2018-11-15 16:19:22 -08:00
Anthony Sottile
e15d7cde86 Upgrade the sample config 2018-11-15 14:17:10 -08:00
Anthony Sottile
dc84f21dd4
Merge pull request #857 from runz0rd/master
Reraises InvalidManifestError as RepositoryCannotBeUpdatedError
2018-11-14 17:29:43 -08:00
Anthony Sottile
aaa3976a29 Use text_type instead of str() 2018-11-13 17:23:32 -08:00
Milos Pejanovic
e339de22d7 Added requested changes 2018-11-14 01:59:18 +01:00
Milos Pejanovic
bf8c8521cd Added a test and small change for error output 2018-11-14 00:43:04 +01:00
Anthony Sottile
76e0f11916
Merge pull request #851 from chriskuehl/concurrent-execution
Implement concurrent execution of individual hooks
2018-11-01 18:46:13 -07:00
Anthony Sottile
6bac405d40 Minor cleanups 2018-11-01 18:05:36 -07:00
Milos Pejanovic
1c97d3f5fd Added a try except block which reraises InvalidManifestError as RepositoryCannotBeUpdatedError 2018-10-31 17:39:47 +01:00
Chris Kuehl
9125439c3a Force serial hook runs during tests 2018-10-24 16:33:06 -07:00
Chris Kuehl
aa50a8cde0 Switch to using concurrent.futures 2018-10-24 16:33:06 -07:00
Chris Kuehl
231f6013bb Allow more time on the concurrency test
Spawning processes is apparently really slow on Windows, and the test is
occasionally taking slightly more than a second on AppVeyor. I think we
can allow up to the full 2.5 seconds without losing the valuable bits of
the test.
2018-10-24 16:33:06 -07:00
Chris Kuehl
b6926e8e2e Attempt to partition files to use all possible cores 2018-10-24 16:33:06 -07:00
Chris Kuehl
ec0ed8aef5 Handle CPU detection errors and running on Travis 2018-10-24 16:16:13 -07:00
Chris Kuehl
ba5e27e4ec Implement concurrent execution of individual hooks 2018-10-24 16:16:10 -07:00
Anthony Sottile
1f1cd2bc39
Merge pull request #839 from georgeyk/refactor-xargs-partition
Update xargs.partition with platform information
2018-10-23 22:55:30 -07:00
Anthony Sottile
ead906aed0 Compute win32 python2 length according to encoded size 2018-10-23 22:02:48 -07:00
Anthony Sottile
eecf3472ff v1.12.0 2018-10-23 10:55:09 -07:00
Anthony Sottile
0c9a53bf1b Correct resources declaration 2018-10-23 10:50:35 -07:00
Anthony Sottile
47e4f39436
Merge pull request #852 from pre-commit/install_only_once
Install multi-hook repositories only once
2018-10-23 10:47:22 -07:00
Anthony Sottile
6cde287a1e Install multi-hook repositories only once 2018-10-23 10:28:37 -07:00
Anthony Sottile
fcdd638134
Merge pull request #847 from pre-commit/improve_coverage
Improve coverage of check_hooks_apply
2018-10-14 16:28:32 -07:00
Anthony Sottile
f19bf57afc
Merge pull request #846 from pre-commit/performance
Improve performance by factoring out pkg_resources
2018-10-14 15:32:18 -07:00
Anthony Sottile
8e8b962266 Improve coverage of check_hooks_apply 2018-10-14 15:00:57 -07:00
Anthony Sottile
62493d1115 Exclude coverage in the template file 2018-10-14 14:37:36 -07:00
Anthony Sottile
9f60561d6f Replace resources with importlib_resources 2018-10-14 14:37:35 -07:00
Anthony Sottile
ebe5132576 Replace pkg_resources.get_distribution with importlib-metadata 2018-10-14 12:24:59 -07:00
Anthony Sottile
14df93ef3e
Merge pull request #845 from pre-commit/all-repos_autofix_pre-commit-autopep8-migrate
Migrate from autopep8-wrapper to mirrors-autopep8
2018-10-12 21:49:22 -07:00
Anthony Sottile
3dbb61d9af Migrate from autopep8-wrapper to mirrors-autopep8
Committed via https://github.com/asottile/all-repos
2018-10-12 20:08:47 -07:00
Anthony Sottile
9c37473256 v1.11.2 2018-10-10 20:43:57 -07:00
Anthony Sottile
9bcfe176d4
Merge pull request #844 from pre-commit/pre_push_ancestor_identification
fix pushing to new branch not identifying all commits
2018-10-10 20:41:46 -07:00
Anthony Sottile
3181b461aa fix pushing to new branch not identifying all commits 2018-10-10 20:08:16 -07:00
George Y. Kussumoto
3d573d8736 Fix xargs.partion: win32 test 2018-10-09 23:32:46 -03:00
George Y. Kussumoto
c9e297ddb6 Fix xargs.partition: win32 new string length computation 2018-10-09 22:54:41 -03:00
George Y. Kussumoto
2560280d21 Fix xargs.partition tests: explicity set unicode chars 2018-10-08 19:42:59 -03:00
George Y. Kussumoto
333ea75e45 Refactor xargs.partition: _command_length usage 2018-10-06 20:04:17 -03:00
George Y. Kussumoto
bb6b1c33ae Remove pytest-mock 2018-10-06 19:57:30 -03:00
George Y. Kussumoto
2ad69e12ce Fix xargs.partition: use sys.getfilesystemencoding
The previous `sys.getdefaultencoding` almost always fallsback to
`ascii` while `sys.getfilesystemencoding` is utf-8 once in utf-8 mode.
2018-10-05 16:39:49 -03:00
George Y. Kussumoto
df5d171cd7 Fix xargs.partition tests in python2.7 (pytest-mock) 2018-10-05 14:33:32 -03:00
George Y. Kussumoto
fa4c03da65 Update xargs.partition with platform information
Change how xargs.partition computes the command length (including
arguments) depending on the plataform.
More specifically, 'win32' uses the amount of characters while posix
system uses the byte count.
2018-10-05 11:54:31 -03:00
Anthony Sottile
c0b1f2ff25
Merge pull request #837 from georgeyk/check-useless-excludes-type-filter
Fix `check-useless-exclude` to consider types filter
2018-10-02 11:43:01 -07:00
George Y. Kussumoto
1b496c5fc3 Fix check-useless-exclude to consider types filter 2018-10-02 12:17:46 -03:00
Anthony Sottile
08319101f4 v1.11.1 2018-09-22 12:02:33 -07:00
Anthony Sottile
3e11c2d05d
Merge pull request #832 from pre-commit/rev_parse_error_mode
Fix rev-parse for older git versions
2018-09-22 11:59:56 -07:00
Anthony Sottile
18b6f4b519 Fix rev-parse for older git versions 2018-09-22 11:12:27 -07:00
Anthony Sottile
4b0a22a8ba v1.11.0 2018-09-02 19:57:09 -07:00
Anthony Sottile
a2bd0097c5
Merge pull request #821 from pre-commit/allow_language_fail_check_useless_excludes
Exempt `language: fail` hooks from check-hooks-apply
2018-09-02 19:49:01 -07:00
Anthony Sottile
ce25b652b9 Exempt language: fail hooks from check-hooks-apply 2018-09-02 18:54:34 -07:00
Anthony Sottile
21c2c9df33 No need for OrderedDict 2018-09-02 18:51:55 -07:00
Anthony Sottile
9d48766c02 git mv tests/meta_hooks/{,check_}useless_excludes_test.py 2018-09-02 18:39:11 -07:00
Anthony Sottile
cd116977cc
Merge pull request #819 from jeffreyrack/fix-windows-reporting
Don't print bogus characters on windows terminals that don't support colors
2018-08-30 20:10:02 -07:00
Jeffrey Rackauckas
710eef317a Fixing tests to account for the new terminal_supports_color variable 2018-08-30 19:39:37 -07:00
Jeffrey Rackauckas
3d777bb386 Move logic to handle terminal not supporting colors to use_color 2018-08-30 19:15:46 -07:00
Jeffrey Rackauckas
a970d3b69b Removing useless pass statement. 2018-08-30 18:45:29 -07:00
Jeffrey Rackauckas
1bd6fce7dc Don't print bogus characters on windows terminals that don't support colors. 2018-08-29 18:54:55 -07:00
Anthony Sottile
f042e302d8
Merge pull request #815 from pre-commit/update_config
Update config
2018-08-16 07:44:27 -07:00
Anthony Sottile
72d10903d5 Update config 2018-08-15 17:55:06 -07:00
Anthony Sottile
a5ccc89748
Merge pull request #812 from pre-commit/language_fail
Add language: fail
2018-08-11 08:13:35 -07:00
Anthony Sottile
a6e2e1d4bb Add language: fail 2018-08-10 18:11:28 -07:00
Anthony Sottile
cf691e85c8 that's what I get for not waiting for CI 2018-08-10 12:39:40 -07:00
Anthony Sottile
67bc05eb35
Merge pull request #811 from BoboTiG/fix-resources-warnings
Fix several ResourceWarning: unclosed file
2018-08-10 12:34:05 -07:00
Anthony Sottile
174d3bf057
Minor style adjustment 2018-08-10 12:33:21 -07:00
Anthony Sottile
a8640c759d
Add # pragma: no cover for the py3-only branch 2018-08-10 11:11:50 -07:00
Mickaël Schoentgen
d68a778e3b Fix the use of deprecated inspect.getargspec() on Python 3 2018-08-10 18:30:22 +02:00
Mickaël Schoentgen
67d6fcb0f6 Fix several ResourceWarning: unclosed file 2018-08-10 18:30:22 +02:00
Mickaël Schoentgen
abee146199 Get rid of @pytest.mark.integration 2018-08-10 18:29:30 +02:00
Anthony Sottile
ff73f6f741 v1.10.5 2018-08-06 14:03:01 -07:00
Anthony Sottile
2f0fefeb74
Merge pull request #809 from pre-commit/worktree
Support `pre-commit install` inside a worktree
2018-08-06 10:11:51 -07:00
Anthony Sottile
3f78487769 Support pre-commit install inside a worktree 2018-08-06 09:26:42 -07:00
Anthony Sottile
ab556f4dff
Merge pull request #805 from pre-commit/workaround_brew
Work around sys.executable issue using brew python on macos
2018-07-24 18:28:34 -07:00
Anthony Sottile
7e69d117c6 Work around sys.executable issue using brew python on macos
https://github.com/Homebrew/homebrew-core/issues/30445
2018-07-24 16:05:26 -07:00
Anthony Sottile
a3847d830c A few changelog entries didn't get commited 2018-07-22 09:25:34 -07:00
243 changed files with 16936 additions and 5881 deletions

View file

@ -1,33 +0,0 @@
[run]
branch = True
source = .
omit =
.tox/*
/usr/*
setup.py
# Don't complain if non-runnable code isn't run
*/__main__.py
pre_commit/color_windows.py
[report]
show_missing = True
skip_covered = True
exclude_lines =
# Have to re-enable the standard pragma
\#\s*pragma: no cover
# We optionally substitute this
${COVERAGE_IGNORE_WINDOWS}
# Don't complain if tests don't hit defensive assertion code:
^\s*raise AssertionError\b
^\s*raise NotImplementedError\b
^\s*return NotImplemented\b
^\s*raise$
# Don't complain if non-runnable code isn't run:
^if __name__ == ['"]__main__['"]:$
[html]
directory = coverage-html
# vim:ft=dosini

54
.github/ISSUE_TEMPLATE/00_bug.yaml vendored Normal file
View file

@ -0,0 +1,54 @@
name: bug report
description: something went wrong
body:
- type: markdown
attributes:
value: |
this is for issues for `pre-commit` (the framework).
if you are reporting an issue for [pre-commit.ci] please report it at [pre-commit-ci/issues]
[pre-commit.ci]: https://pre-commit.ci
[pre-commit-ci/issues]: https://github.com/pre-commit-ci/issues
- type: input
id: search
attributes:
label: search you tried in the issue tracker
placeholder: ...
validations:
required: true
- type: markdown
attributes:
value: |
95% of issues created are duplicates.
please try extra hard to find them first.
it's very unlikely your problem is unique.
- type: textarea
id: freeform
attributes:
label: describe your issue
placeholder: 'I was doing ... I ran ... I expected ... I got ...'
validations:
required: true
- type: input
id: version
attributes:
label: pre-commit --version
placeholder: pre-commit x.x.x
validations:
required: true
- type: textarea
id: configuration
attributes:
label: .pre-commit-config.yaml
description: (auto-rendered as yaml, no need for backticks)
placeholder: 'repos: ...'
render: yaml
validations:
required: true
- type: textarea
id: error-log
attributes:
label: '~/.cache/pre-commit/pre-commit.log (if present)'
placeholder: "### version information\n..."
validations:
required: false

38
.github/ISSUE_TEMPLATE/01_feature.yaml vendored Normal file
View file

@ -0,0 +1,38 @@
name: feature request
description: something new
body:
- type: markdown
attributes:
value: |
this is for issues for `pre-commit` (the framework).
if you are reporting an issue for [pre-commit.ci] please report it at [pre-commit-ci/issues]
[pre-commit.ci]: https://pre-commit.ci
[pre-commit-ci/issues]: https://github.com/pre-commit-ci/issues
- type: input
id: search
attributes:
label: search you tried in the issue tracker
placeholder: ...
validations:
required: true
- type: markdown
attributes:
value: |
95% of issues created are duplicates.
please try extra hard to find them first.
it's very unlikely your feature idea is a new one.
- type: textarea
id: freeform
attributes:
label: describe your actual problem
placeholder: 'I want to do ... I tried ... It does not work because ...'
validations:
required: true
- type: input
id: version
attributes:
label: pre-commit --version
placeholder: pre-commit x.x.x
validations:
required: true

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View file

@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: documentation
url: https://pre-commit.com
about: please check the docs first
- name: pre-commit.ci issues
url: https://github.com/pre-commit-ci/issues
about: please report issues about pre-commit.ci here

9
.github/actions/pre-test/action.yml vendored Normal file
View file

@ -0,0 +1,9 @@
inputs:
env:
default: ${{ matrix.env }}
runs:
using: composite
steps:
- uses: asottile/workflows/.github/actions/latest-git@v1.4.0
if: inputs.env == 'py39' && runner.os == 'Linux'

84
.github/workflows/languages.yaml vendored Normal file
View file

@ -0,0 +1,84 @@
name: languages
on:
push:
branches: [main, test-me-*]
tags: '*'
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
vars:
runs-on: ubuntu-latest
outputs:
languages: ${{ steps.vars.outputs.languages }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: install deps
run: python -mpip install -e . -r requirements-dev.txt
- name: vars
run: testing/languages ${{ github.event_name == 'push' && '--all' || '' }}
id: vars
language:
needs: [vars]
runs-on: ${{ matrix.os }}
if: needs.vars.outputs.languages != '[]'
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON(needs.vars.outputs.languages) }}
steps:
- uses: asottile/workflows/.github/actions/fast-checkout@v1.8.1
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- run: echo "$CONDA\Scripts" >> "$GITHUB_PATH"
shell: bash
if: matrix.os == 'windows-latest' && matrix.language == 'conda'
- run: testing/get-coursier.sh
shell: bash
if: matrix.language == 'coursier'
- run: testing/get-dart.sh
shell: bash
if: matrix.language == 'dart'
- run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
lua5.3 \
liblua5.3-dev \
luarocks
if: matrix.os == 'ubuntu-latest' && matrix.language == 'lua'
- run: |
echo 'C:\Strawberry\perl\bin' >> "$GITHUB_PATH"
echo 'C:\Strawberry\perl\site\bin' >> "$GITHUB_PATH"
echo 'C:\Strawberry\c\bin' >> "$GITHUB_PATH"
shell: bash
if: matrix.os == 'windows-latest' && matrix.language == 'perl'
- uses: haskell/actions/setup@v2
if: matrix.language == 'haskell'
- uses: r-lib/actions/setup-r@v2
if: matrix.os == 'ubuntu-latest' && matrix.language == 'r'
- name: install deps
run: python -mpip install -e . -r requirements-dev.txt
- name: run tests
run: coverage run -m pytest tests/languages/${{ matrix.language }}_test.py
- name: check coverage
run: coverage report --include pre_commit/languages/${{ matrix.language }}.py,tests/languages/${{ matrix.language }}_test.py
collector:
needs: [language]
if: always()
runs-on: ubuntu-latest
steps:
- name: check for failures
if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
run: echo job failed && exit 1

23
.github/workflows/main.yml vendored Normal file
View file

@ -0,0 +1,23 @@
name: main
on:
push:
branches: [main, test-me-*]
tags: '*'
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
main-windows:
uses: asottile/workflows/.github/workflows/tox.yml@v1.8.1
with:
env: '["py310"]'
os: windows-latest
main-linux:
uses: asottile/workflows/.github/workflows/tox.yml@v1.8.1
with:
env: '["py310", "py311", "py312", "py313"]'
os: ubuntu-latest

16
.gitignore vendored
View file

@ -1,14 +1,6 @@
*.egg-info
*.iml
*.py[co]
.*.sw[a-z]
.coverage
.idea
.project
.pydevproject
.tox
.venv.touch
/venv*
coverage-html
dist
.pytest_cache
/.coverage
/.tox
/dist
.vscode/

View file

@ -1,31 +1,44 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.2.3
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: autopep8-wrapper
- id: check-docstring-first
- id: check-json
- id: check-yaml
- id: debug-statements
- id: double-quote-string-fixer
- id: name-tests-test
- id: requirements-txt-fixer
- id: flake8
- repo: https://github.com/pre-commit/pre-commit
rev: v1.7.0
- repo: https://github.com/asottile/setup-cfg-fmt
rev: v3.2.0
hooks:
- id: validate_manifest
- repo: https://github.com/asottile/reorder_python_imports
rev: v1.0.1
- id: setup-cfg-fmt
- repo: https://github.com/asottile/reorder-python-imports
rev: v3.16.0
hooks:
- id: reorder-python-imports
language_version: python2.7
exclude: ^pre_commit/resources/
args: [--py310-plus, --add-import, 'from __future__ import annotations']
- repo: https://github.com/asottile/add-trailing-comma
rev: v0.6.4
rev: v4.0.0
hooks:
- id: add-trailing-comma
- repo: meta
- repo: https://github.com/asottile/pyupgrade
rev: v3.21.2
hooks:
- id: check-hooks-apply
- id: check-useless-excludes
- id: pyupgrade
args: [--py310-plus]
- repo: https://github.com/hhatto/autopep8
rev: v2.3.2
hooks:
- id: autopep8
- repo: https://github.com/PyCQA/flake8
rev: 7.3.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.19.1
hooks:
- id: mypy
additional_dependencies: [types-pyyaml]
exclude: ^testing/resources/

View file

@ -1,6 +1,6 @@
- id: validate_manifest
name: Validate Pre-Commit Manifest
name: validate pre-commit manifest
description: This validator validates a pre-commit hooks manifest file
entry: pre-commit-validate-manifest
entry: pre-commit validate-manifest
language: python
files: ^(\.pre-commit-hooks\.yaml|hooks\.yaml)$
files: ^\.pre-commit-hooks\.yaml$

View file

@ -1,37 +0,0 @@
language: python
dist: trusty
sudo: required
services:
- docker
matrix:
include:
- env: TOXENV=py27
- env: TOXENV=py27 LATEST_GIT=1
- env: TOXENV=py36
python: 3.6
- env: TOXENV=pypy
python: pypy2.7-5.10.0
- env: TOXENV=py37
python: 3.7
sudo: required
dist: xenial
install: pip install coveralls tox
script: tox
before_install:
- git --version
- |
if [ "$LATEST_GIT" = "1" ]; then
testing/latest-git.sh
export PATH="/tmp/git/bin:$PATH"
fi
- git --version
- 'testing/get-swift.sh && export PATH="/tmp/swift/usr/bin:$PATH"'
- 'curl -sSf https://sh.rustup.rs | bash -s -- -y'
- export PATH="$HOME/.cargo/bin:$PATH"
after_success: coveralls
cache:
directories:
- $HOME/.cache/pip
- $HOME/.cache/pre-commit
- $HOME/.rustup
- $HOME/.swift

File diff suppressed because it is too large Load diff

View file

@ -2,22 +2,26 @@
## Local development
- The complete test suite depends on having at least the following installed (possibly not
a complete list)
- git (A sufficiently newer version is required to run pre-push tests)
- python2 (Required by a test which checks different python versions)
- The complete test suite depends on having at least the following installed
(possibly not a complete list)
- git (Version 2.24.0 or above is required to run pre-merge-commit tests)
- python3 (Required by a test which checks different python versions)
- tox (or virtualenv)
- ruby + gem
- docker
- conda
- cargo (required by tests for rust dependencies)
- go (required by tests for go dependencies)
- swift
### Setting up an environemnt
### Setting up an environment
This is useful for running specific tests. The easiest way to set this up
is to run:
1. `tox -e venv`
2. `. venv-pre_commit/bin/activate`
1. `tox --devenv venv` (note: requires tox>=3.13)
2. `. venv/bin/activate` (or follow the [activation instructions] for your
platform)
This will create and put you into a virtualenv which has an editable
installation of pre-commit. Hack away! Running `pre-commit` will reflect
@ -30,7 +34,7 @@ Running a specific test with the environment activated is as easy as:
### Running all the tests
Running all the tests can be done by running `tox -e py27` (or your
Running all the tests can be done by running `tox -e py37` (or your
interpreter version of choice). These often take a long time and consume
significant cpu while running the slower node / ruby integration tests.
@ -49,5 +53,101 @@ Documentation is hosted at https://pre-commit.com
This website is controlled through
https://github.com/pre-commit/pre-commit.github.io
When adding a feature, please make a pull request to add yourself to the
contributors list and add documentation to the website if applicable.
## Adding support for a new hook language
pre-commit already supports many [programming languages](https://pre-commit.com/#supported-languages)
to write hook executables with.
When adding support for a language, you must first decide what level of support
to implement. The current implemented languages are at varying levels:
- 0th class - pre-commit does not require any dependencies for these languages
as they're not actually languages (current examples: fail, pygrep)
- 1st class - pre-commit will bootstrap a full interpreter requiring nothing to
be installed globally (current examples: go, node, ruby, rust)
- 2nd class - pre-commit requires the user to install the language globally but
will install tools in an isolated fashion (current examples: python, swift,
docker).
- 3rd class - pre-commit requires the user to install both the tool and the
language globally (current examples: script, system)
"second class" is usually the easiest to implement first and is perfectly
acceptable.
Ideally the language works on the supported platforms for pre-commit (linux,
windows, macos) but it's ok to skip one or more platforms (for example, swift
doesn't run on windows).
When writing your new language, it's often useful to look at other examples in
the `pre_commit/languages` directory.
It might also be useful to look at a recent pull request which added a
language, for example:
- [rust](https://github.com/pre-commit/pre-commit/pull/751)
- [fail](https://github.com/pre-commit/pre-commit/pull/812)
- [swift](https://github.com/pre-commit/pre-commit/pull/467)
### `language` api
here are the apis that should be implemented for a language
Note that these are also documented in [`pre_commit/lang_base.py`](https://github.com/pre-commit/pre-commit/blob/main/pre_commit/lang_base.py)
#### `ENVIRONMENT_DIR`
a short string which will be used for the prefix of where packages will be
installed. For example, python uses `py_env` and installs a `virtualenv` at
that location.
this will be `None` for 0th / 3rd class languages as they don't have an install
step.
#### `get_default_version`
This is used to retrieve the default `language_version` for a language. If
one cannot be determined, return `'default'`.
You generally don't need to implement this on a first pass and can just use:
```python
get_default_version = lang_base.basic_default_version
```
`python` is currently the only language which implements this api
#### `health_check`
This is used to check whether the installed environment is considered healthy.
This function should return a detailed message if unhealthy or `None` if
healthy.
You generally don't need to implement this on a first pass and can just use:
```python
health_check = lang_base.basic_health_check
```
`python` is currently the only language which implements this api, for python
it is checking whether some common dlls are still available.
#### `install_environment`
this is the trickiest one to implement and where all the smart parts happen.
this api should do the following things
- (0th / 3rd class): `install_environment = lang_base.no_install`
- (1st class): install a language runtime into the hook's directory
- (2nd class): install the package at `.` into the `ENVIRONMENT_DIR`
- (2nd class, optional): install packages listed in `additional_dependencies`
into `ENVIRONMENT_DIR` (not a required feature for a first pass)
#### `run_hook`
This is usually the easiest to implement, most of them look the same as the
`node` hook implementation:
https://github.com/pre-commit/pre-commit/blob/160238220f022035c8ef869c9a8642f622c02118/pre_commit/languages/node.py#L72-L74
[activation instructions]: https://virtualenv.pypa.io/en/latest/user_guide.html#activators

View file

@ -1 +0,0 @@
include LICENSE

View file

@ -1,6 +1,5 @@
[![Build Status](https://travis-ci.org/pre-commit/pre-commit.svg?branch=master)](https://travis-ci.org/pre-commit/pre-commit)
[![Coverage Status](https://coveralls.io/repos/github/pre-commit/pre-commit/badge.svg?branch=master)](https://coveralls.io/github/pre-commit/pre-commit?branch=master)
[![Build status](https://ci.appveyor.com/api/projects/status/mmcwdlfgba4esaii/branch/master?svg=true)](https://ci.appveyor.com/project/asottile/pre-commit/branch/master)
[![build status](https://github.com/pre-commit/pre-commit/actions/workflows/main.yml/badge.svg)](https://github.com/pre-commit/pre-commit/actions/workflows/main.yml)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/pre-commit/pre-commit/main.svg)](https://results.pre-commit.ci/latest/github/pre-commit/pre-commit/main)
## pre-commit

View file

@ -1,29 +0,0 @@
environment:
global:
COVERAGE_IGNORE_WINDOWS: '# pragma: windows no cover'
TOX_TESTENV_PASSENV: COVERAGE_IGNORE_WINDOWS
matrix:
- TOXENV: py27
- TOXENV: py37
install:
- "SET PATH=C:\\Python37;C:\\Python37\\Scripts;%PATH%"
- pip install tox virtualenv --upgrade
- "mkdir -p C:\\Temp"
- "SET TMPDIR=C:\\Temp"
- "curl -sSf https://sh.rustup.rs | bash -s -- -y"
- "SET PATH=%USERPROFILE%\\.cargo\\bin;%PATH%"
# Not a C# project
build: false
before_test:
# Shut up CRLF messages
- git config --global core.autocrlf false
- git config --global core.safecrlf false
test_script: tox
cache:
- '%LOCALAPPDATA%\pip\cache'
- '%USERPROFILE%\.cache\pre-commit'

View file

@ -1,7 +1,7 @@
from __future__ import absolute_import
from __future__ import annotations
from pre_commit.main import main
if __name__ == '__main__':
exit(main())
raise SystemExit(main())

View file

@ -0,0 +1,50 @@
from __future__ import annotations
from pre_commit.lang_base import Language
from pre_commit.languages import conda
from pre_commit.languages import coursier
from pre_commit.languages import dart
from pre_commit.languages import docker
from pre_commit.languages import docker_image
from pre_commit.languages import dotnet
from pre_commit.languages import fail
from pre_commit.languages import golang
from pre_commit.languages import haskell
from pre_commit.languages import julia
from pre_commit.languages import lua
from pre_commit.languages import node
from pre_commit.languages import perl
from pre_commit.languages import pygrep
from pre_commit.languages import python
from pre_commit.languages import r
from pre_commit.languages import ruby
from pre_commit.languages import rust
from pre_commit.languages import swift
from pre_commit.languages import unsupported
from pre_commit.languages import unsupported_script
languages: dict[str, Language] = {
'conda': conda,
'coursier': coursier,
'dart': dart,
'docker': docker,
'docker_image': docker_image,
'dotnet': dotnet,
'fail': fail,
'golang': golang,
'haskell': haskell,
'julia': julia,
'lua': lua,
'node': node,
'perl': perl,
'pygrep': pygrep,
'python': python,
'r': r,
'ruby': ruby,
'rust': rust,
'swift': swift,
'unsupported': unsupported,
'unsupported_script': unsupported_script,
}
language_names = sorted(languages)

View file

@ -1,49 +1,252 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import argparse
import collections
import functools
import logging
import os.path
import re
import shlex
import sys
from collections.abc import Callable
from collections.abc import Sequence
from typing import Any
from typing import NamedTuple
import cfgv
from aspy.yaml import ordered_load
from identify.identify import ALL_TAGS
import pre_commit.constants as C
from pre_commit.error_handler import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.all_languages import language_names
from pre_commit.errors import FatalError
from pre_commit.yaml import yaml_load
logger = logging.getLogger('pre_commit')
check_string_regex = cfgv.check_and(cfgv.check_string, cfgv.check_regex)
HOOK_TYPES = (
'commit-msg',
'post-checkout',
'post-commit',
'post-merge',
'post-rewrite',
'pre-commit',
'pre-merge-commit',
'pre-push',
'pre-rebase',
'prepare-commit-msg',
)
# `manual` is not invoked by any installed git hook. See #719
STAGES = (*HOOK_TYPES, 'manual')
def check_type_tag(tag):
def check_type_tag(tag: str) -> None:
if tag not in ALL_TAGS:
raise cfgv.ValidationError(
'Type tag {!r} is not recognized. '
'Try upgrading identify and pre-commit?'.format(tag),
f'Type tag {tag!r} is not recognized. '
f'Try upgrading identify and pre-commit?',
)
def _make_argparser(filenames_help):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help=filenames_help)
parser.add_argument('-V', '--version', action='version', version=C.VERSION)
return parser
def parse_version(s: str) -> tuple[int, ...]:
"""poor man's version comparison"""
return tuple(int(p) for p in s.split('.'))
def check_min_version(version: str) -> None:
if parse_version(version) > parse_version(C.VERSION):
raise cfgv.ValidationError(
f'pre-commit version {version} is required but version '
f'{C.VERSION} is installed. '
f'Perhaps run `pip install --upgrade pre-commit`.',
)
_STAGES = {
'commit': 'pre-commit',
'merge-commit': 'pre-merge-commit',
'push': 'pre-push',
}
def transform_stage(stage: str) -> str:
return _STAGES.get(stage, stage)
MINIMAL_MANIFEST_SCHEMA = cfgv.Array(
cfgv.Map(
'Hook', 'id',
cfgv.Required('id', cfgv.check_string),
cfgv.Optional('stages', cfgv.check_array(cfgv.check_string), []),
),
)
def warn_for_stages_on_repo_init(repo: str, directory: str) -> None:
try:
manifest = cfgv.load_from_filename(
os.path.join(directory, C.MANIFEST_FILE),
schema=MINIMAL_MANIFEST_SCHEMA,
load_strategy=yaml_load,
exc_tp=InvalidManifestError,
)
except InvalidManifestError:
return # they'll get a better error message when it actually loads!
legacy_stages = {} # sorted set
for hook in manifest:
for stage in hook.get('stages', ()):
if stage in _STAGES:
legacy_stages[stage] = True
if legacy_stages:
logger.warning(
f'repo `{repo}` uses deprecated stage names '
f'({", ".join(legacy_stages)}) which will be removed in a '
f'future version. '
f'Hint: often `pre-commit autoupdate --repo {shlex.quote(repo)}` '
f'will fix this. '
f'if it does not -- consider reporting an issue to that repo.',
)
class StagesMigrationNoDefault(NamedTuple):
key: str
default: Sequence[str]
def check(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
with cfgv.validate_context(f'At key: {self.key}'):
val = dct[self.key]
cfgv.check_array(cfgv.check_any)(val)
val = [transform_stage(v) for v in val]
cfgv.check_array(cfgv.check_one_of(STAGES))(val)
def apply_default(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
dct[self.key] = [transform_stage(v) for v in dct[self.key]]
def remove_default(self, dct: dict[str, Any]) -> None:
raise NotImplementedError
class StagesMigration(StagesMigrationNoDefault):
def apply_default(self, dct: dict[str, Any]) -> None:
dct.setdefault(self.key, self.default)
super().apply_default(dct)
class DeprecatedStagesWarning(NamedTuple):
key: str
def check(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
val = dct[self.key]
cfgv.check_array(cfgv.check_any)(val)
legacy_stages = [stage for stage in val if stage in _STAGES]
if legacy_stages:
logger.warning(
f'hook id `{dct["id"]}` uses deprecated stage names '
f'({", ".join(legacy_stages)}) which will be removed in a '
f'future version. '
f'run: `pre-commit migrate-config` to automatically fix this.',
)
def apply_default(self, dct: dict[str, Any]) -> None:
pass
def remove_default(self, dct: dict[str, Any]) -> None:
raise NotImplementedError
class DeprecatedDefaultStagesWarning(NamedTuple):
key: str
def check(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
val = dct[self.key]
cfgv.check_array(cfgv.check_any)(val)
legacy_stages = [stage for stage in val if stage in _STAGES]
if legacy_stages:
logger.warning(
f'top-level `default_stages` uses deprecated stage names '
f'({", ".join(legacy_stages)}) which will be removed in a '
f'future version. '
f'run: `pre-commit migrate-config` to automatically fix this.',
)
def apply_default(self, dct: dict[str, Any]) -> None:
pass
def remove_default(self, dct: dict[str, Any]) -> None:
raise NotImplementedError
def _translate_language(name: str) -> str:
return {
'system': 'unsupported',
'script': 'unsupported_script',
}.get(name, name)
class LanguageMigration(NamedTuple): # remove
key: str
check_fn: Callable[[object], None]
def check(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
with cfgv.validate_context(f'At key: {self.key}'):
self.check_fn(_translate_language(dct[self.key]))
def apply_default(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
return
dct[self.key] = _translate_language(dct[self.key])
def remove_default(self, dct: dict[str, Any]) -> None:
raise NotImplementedError
class LanguageMigrationRequired(LanguageMigration): # replace with Required
def check(self, dct: dict[str, Any]) -> None:
if self.key not in dct:
raise cfgv.ValidationError(f'Missing required key: {self.key}')
super().check(dct)
MANIFEST_HOOK_DICT = cfgv.Map(
'Hook', 'id',
# check first in case it uses some newer, incompatible feature
cfgv.Optional(
'minimum_pre_commit_version',
cfgv.check_and(cfgv.check_string, check_min_version),
'0',
),
cfgv.Required('id', cfgv.check_string),
cfgv.Required('name', cfgv.check_string),
cfgv.Required('entry', cfgv.check_string),
cfgv.Required('language', cfgv.check_one_of(all_languages)),
LanguageMigrationRequired('language', cfgv.check_one_of(language_names)),
cfgv.Optional('alias', cfgv.check_string, ''),
cfgv.Optional(
'files', cfgv.check_and(cfgv.check_string, cfgv.check_regex), '',
),
cfgv.Optional(
'exclude', cfgv.check_and(cfgv.check_string, cfgv.check_regex), '^$',
),
cfgv.Optional('files', check_string_regex, ''),
cfgv.Optional('exclude', check_string_regex, '^$'),
cfgv.Optional('types', cfgv.check_array(check_type_tag), ['file']),
cfgv.Optional('types_or', cfgv.check_array(check_type_tag), []),
cfgv.Optional('exclude_types', cfgv.check_array(check_type_tag), []),
cfgv.Optional(
@ -51,12 +254,13 @@ MANIFEST_HOOK_DICT = cfgv.Map(
),
cfgv.Optional('args', cfgv.check_array(cfgv.check_string), []),
cfgv.Optional('always_run', cfgv.check_bool, False),
cfgv.Optional('fail_fast', cfgv.check_bool, False),
cfgv.Optional('pass_filenames', cfgv.check_bool, True),
cfgv.Optional('description', cfgv.check_string, ''),
cfgv.Optional('language_version', cfgv.check_string, 'default'),
cfgv.Optional('language_version', cfgv.check_string, C.DEFAULT),
cfgv.Optional('log_file', cfgv.check_string, ''),
cfgv.Optional('minimum_pre_commit_version', cfgv.check_string, '0'),
cfgv.Optional('stages', cfgv.check_array(cfgv.check_one_of(C.STAGES)), []),
cfgv.Optional('require_serial', cfgv.check_bool, False),
StagesMigration('stages', []),
cfgv.Optional('verbose', cfgv.check_bool, False),
)
MANIFEST_SCHEMA = cfgv.Array(MANIFEST_HOOK_DICT)
@ -66,60 +270,172 @@ class InvalidManifestError(FatalError):
pass
def _load_manifest_forward_compat(contents: str) -> object:
obj = yaml_load(contents)
if isinstance(obj, dict):
check_min_version('5')
raise AssertionError('unreachable')
else:
return obj
load_manifest = functools.partial(
cfgv.load_from_filename,
schema=MANIFEST_SCHEMA,
load_strategy=ordered_load,
load_strategy=_load_manifest_forward_compat,
exc_tp=InvalidManifestError,
)
def validate_manifest_main(argv=None):
parser = _make_argparser('Manifest filenames.')
args = parser.parse_args(argv)
ret = 0
for filename in args.filenames:
try:
load_manifest(filename)
except InvalidManifestError as e:
print(e)
ret = 1
return ret
LOCAL = 'local'
META = 'meta'
_LOCAL_SENTINEL = 'local'
_META_SENTINEL = 'meta'
class WarnMutableRev(cfgv.Conditional):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if self.key in dct:
rev = dct[self.key]
if '.' not in rev and not re.match(r'^[a-fA-F0-9]+$', rev):
logger.warning(
f'The {self.key!r} field of repo {dct["repo"]!r} '
f'appears to be a mutable reference '
f'(moving tag / branch). Mutable references are never '
f'updated after first install and are not supported. '
f'See https://pre-commit.com/#using-the-latest-version-for-a-repository ' # noqa: E501
f'for more details. '
f'Hint: `pre-commit autoupdate` often fixes this.',
)
class MigrateShaToRev(object):
@staticmethod
def _cond(key):
return cfgv.Conditional(
key, cfgv.check_string,
condition_key='repo',
condition_value=cfgv.NotIn(_LOCAL_SENTINEL, _META_SENTINEL),
ensure_absent=True,
)
class OptionalSensibleRegexAtHook(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
def check(self, dct):
if dct.get('repo') in {_LOCAL_SENTINEL, _META_SENTINEL}:
self._cond('rev').check(dct)
self._cond('sha').check(dct)
elif 'sha' in dct and 'rev' in dct:
raise cfgv.ValidationError('Cannot specify both sha and rev')
elif 'sha' in dct:
self._cond('sha').check(dct)
else:
self._cond('rev').check(dct)
def apply_default(self, dct):
if 'sha' in dct:
dct['rev'] = dct.pop('sha')
def remove_default(self, dct):
pass
if '/*' in dct.get(self.key, ''):
logger.warning(
f'The {self.key!r} field in hook {dct.get("id")!r} is a '
f"regex, not a glob -- matching '/*' probably isn't what you "
f'want here',
)
for fwd_slash_re in (r'[\\/]', r'[\/]', r'[/\\]'):
if fwd_slash_re in dct.get(self.key, ''):
logger.warning(
fr'pre-commit normalizes slashes in the {self.key!r} '
fr'field in hook {dct.get("id")!r} to forward slashes, '
fr'so you can use / instead of {fwd_slash_re}',
)
class OptionalSensibleRegexAtTop(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if '/*' in dct.get(self.key, ''):
logger.warning(
f'The top-level {self.key!r} field is a regex, not a glob -- '
f"matching '/*' probably isn't what you want here",
)
for fwd_slash_re in (r'[\\/]', r'[\/]', r'[/\\]'):
if fwd_slash_re in dct.get(self.key, ''):
logger.warning(
fr'pre-commit normalizes the slashes in the top-level '
fr'{self.key!r} field to forward slashes, so you '
fr'can use / instead of {fwd_slash_re}',
)
def _entry(modname: str) -> str:
"""the hook `entry` is passed through `shlex.split()` by the command
runner, so to prevent issues with spaces and backslashes (on Windows)
it must be quoted here.
"""
return f'{shlex.quote(sys.executable)} -m pre_commit.meta_hooks.{modname}'
def warn_unknown_keys_root(
extra: Sequence[str],
orig_keys: Sequence[str],
dct: dict[str, str],
) -> None:
logger.warning(f'Unexpected key(s) present at root: {", ".join(extra)}')
def warn_unknown_keys_repo(
extra: Sequence[str],
orig_keys: Sequence[str],
dct: dict[str, str],
) -> None:
logger.warning(
f'Unexpected key(s) present on {dct["repo"]}: {", ".join(extra)}',
)
_meta = (
(
'check-hooks-apply', (
('name', 'Check hooks apply to the repository'),
('files', f'^{re.escape(C.CONFIG_FILE)}$'),
('entry', _entry('check_hooks_apply')),
),
),
(
'check-useless-excludes', (
('name', 'Check for useless excludes'),
('files', f'^{re.escape(C.CONFIG_FILE)}$'),
('entry', _entry('check_useless_excludes')),
),
),
(
'identity', (
('name', 'identity'),
('verbose', True),
('entry', _entry('identity')),
),
),
)
class NotAllowed(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
if self.key in dct:
raise cfgv.ValidationError(f'{self.key!r} cannot be overridden')
_COMMON_HOOK_WARNINGS = (
OptionalSensibleRegexAtHook('files', cfgv.check_string),
OptionalSensibleRegexAtHook('exclude', cfgv.check_string),
DeprecatedStagesWarning('stages'),
)
META_HOOK_DICT = cfgv.Map(
'Hook', 'id',
cfgv.Required('id', cfgv.check_string),
cfgv.Required('id', cfgv.check_one_of(tuple(k for k, _ in _meta))),
# language must be `unsupported`
cfgv.Optional(
'language', cfgv.check_one_of({'unsupported'}), 'unsupported',
),
# entry cannot be overridden
NotAllowed('entry', cfgv.check_any),
*(
# default to the hook definition for the meta hooks
cfgv.ConditionalOptional(key, cfgv.check_any, value, 'id', hook_id)
for hook_id, values in _meta
for key, value in values
),
*(
# default to the "manifest" parsing
cfgv.OptionalNoDefault(item.key, item.check_fn)
# these will always be defaulted above
if item.key in {'name', 'language', 'entry'} else
item
for item in MANIFEST_HOOK_DICT.items
),
*_COMMON_HOOK_WARNINGS,
)
CONFIG_HOOK_DICT = cfgv.Map(
'Hook', 'id',
@ -129,66 +445,107 @@ CONFIG_HOOK_DICT = cfgv.Map(
# are optional.
# No defaults are provided here as the config is merged on top of the
# manifest.
*[
*(
cfgv.OptionalNoDefault(item.key, item.check_fn)
for item in MANIFEST_HOOK_DICT.items
if item.key != 'id'
]
if item.key != 'stages'
if item.key != 'language' # remove
),
StagesMigrationNoDefault('stages', []),
LanguageMigration('language', cfgv.check_one_of(language_names)), # remove
*_COMMON_HOOK_WARNINGS,
)
LOCAL_HOOK_DICT = cfgv.Map(
'Hook', 'id',
*MANIFEST_HOOK_DICT.items,
*_COMMON_HOOK_WARNINGS,
)
CONFIG_REPO_DICT = cfgv.Map(
'Repository', 'repo',
cfgv.Required('repo', cfgv.check_string),
cfgv.RequiredRecurse('hooks', cfgv.Array(CONFIG_HOOK_DICT)),
MigrateShaToRev(),
cfgv.ConditionalRecurse(
'hooks', cfgv.Array(CONFIG_HOOK_DICT),
'repo', cfgv.NotIn(LOCAL, META),
),
cfgv.ConditionalRecurse(
'hooks', cfgv.Array(LOCAL_HOOK_DICT),
'repo', LOCAL,
),
cfgv.ConditionalRecurse(
'hooks', cfgv.Array(META_HOOK_DICT),
'repo', META,
),
WarnMutableRev(
'rev', cfgv.check_string,
condition_key='repo',
condition_value=cfgv.NotIn(LOCAL, META),
ensure_absent=True,
),
cfgv.WarnAdditionalKeys(('repo', 'rev', 'hooks'), warn_unknown_keys_repo),
)
DEFAULT_LANGUAGE_VERSION = cfgv.Map(
'DefaultLanguageVersion', None,
cfgv.NoAdditionalKeys(language_names),
*(cfgv.Optional(x, cfgv.check_string, C.DEFAULT) for x in language_names),
)
CONFIG_SCHEMA = cfgv.Map(
'Config', None,
# check first in case it uses some newer, incompatible feature
cfgv.Optional(
'minimum_pre_commit_version',
cfgv.check_and(cfgv.check_string, check_min_version),
'0',
),
cfgv.RequiredRecurse('repos', cfgv.Array(CONFIG_REPO_DICT)),
cfgv.Optional('exclude', cfgv.check_regex, '^$'),
cfgv.Optional(
'default_install_hook_types',
cfgv.check_array(cfgv.check_one_of(HOOK_TYPES)),
['pre-commit'],
),
cfgv.OptionalRecurse(
'default_language_version', DEFAULT_LANGUAGE_VERSION, {},
),
StagesMigration('default_stages', STAGES),
DeprecatedDefaultStagesWarning('default_stages'),
cfgv.Optional('files', check_string_regex, ''),
cfgv.Optional('exclude', check_string_regex, '^$'),
cfgv.Optional('fail_fast', cfgv.check_bool, False),
cfgv.WarnAdditionalKeys(
(
'repos',
'default_install_hook_types',
'default_language_version',
'default_stages',
'files',
'exclude',
'fail_fast',
'minimum_pre_commit_version',
'ci',
),
warn_unknown_keys_root,
),
OptionalSensibleRegexAtTop('files', cfgv.check_string),
OptionalSensibleRegexAtTop('exclude', cfgv.check_string),
# do not warn about configuration for pre-commit.ci
cfgv.OptionalNoDefault('ci', cfgv.check_type(dict)),
)
def is_local_repo(repo_entry):
return repo_entry['repo'] == _LOCAL_SENTINEL
def is_meta_repo(repo_entry):
return repo_entry['repo'] == _META_SENTINEL
class InvalidConfigError(FatalError):
pass
def ordered_load_normalize_legacy_config(contents):
data = ordered_load(contents)
if isinstance(data, list):
# TODO: Once happy, issue a deprecation warning and instructions
return collections.OrderedDict([('repos', data)])
else:
return data
load_config = functools.partial(
cfgv.load_from_filename,
schema=CONFIG_SCHEMA,
load_strategy=ordered_load_normalize_legacy_config,
load_strategy=yaml_load,
exc_tp=InvalidConfigError,
)
def validate_config_main(argv=None):
parser = _make_argparser('Config filenames.')
args = parser.parse_args(argv)
ret = 0
for filename in args.filenames:
try:
load_config(filename)
except InvalidConfigError as e:
print(e)
ret = 1
return ret

View file

@ -1,27 +1,70 @@
from __future__ import unicode_literals
from __future__ import annotations
import argparse
import os
import sys
if os.name == 'nt': # pragma: no cover (windows)
from pre_commit.color_windows import enable_virtual_terminal_processing
if sys.platform == 'win32': # pragma: no cover (windows)
def _enable() -> None:
from ctypes import POINTER
from ctypes import windll
from ctypes import WinError
from ctypes import WINFUNCTYPE
from ctypes.wintypes import BOOL
from ctypes.wintypes import DWORD
from ctypes.wintypes import HANDLE
STD_ERROR_HANDLE = -12
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
def bool_errcheck(result, func, args):
if not result:
raise WinError()
return args
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
('GetStdHandle', windll.kernel32), ((1, 'nStdHandle'),),
)
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
('GetConsoleMode', windll.kernel32),
((1, 'hConsoleHandle'), (2, 'lpMode')),
)
GetConsoleMode.errcheck = bool_errcheck
SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
('SetConsoleMode', windll.kernel32),
((1, 'hConsoleHandle'), (1, 'dwMode')),
)
SetConsoleMode.errcheck = bool_errcheck
# As of Windows 10, the Windows console supports (some) ANSI escape
# sequences, but it needs to be enabled using `SetConsoleMode` first.
#
# More info on the escape sequences supported:
# https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
stderr = GetStdHandle(STD_ERROR_HANDLE)
flags = GetConsoleMode(stderr)
SetConsoleMode(stderr, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
try:
enable_virtual_terminal_processing()
except WindowsError:
pass
_enable()
except OSError:
terminal_supports_color = False
else:
terminal_supports_color = True
else: # pragma: win32 no cover
terminal_supports_color = True
RED = '\033[41m'
GREEN = '\033[42m'
YELLOW = '\033[43;30m'
TURQUOISE = '\033[46;30m'
NORMAL = '\033[0m'
SUBTLE = '\033[2m'
NORMAL = '\033[m'
class InvalidColorSetting(ValueError):
pass
def format_color(text, color, use_color_setting):
def format_color(text: str, color: str, use_color_setting: bool) -> str:
"""Format text with color.
Args:
@ -29,22 +72,38 @@ def format_color(text, color, use_color_setting):
color - The color start string
use_color_setting - Whether or not to color
"""
if not use_color_setting:
return text
if use_color_setting:
return f'{color}{text}{NORMAL}'
else:
return '{}{}{}'.format(color, text, NORMAL)
return text
COLOR_CHOICES = ('auto', 'always', 'never')
def use_color(setting):
def use_color(setting: str) -> bool:
"""Choose whether to use color based on the command argument.
Args:
setting - Either `auto`, `always`, or `never`
"""
if setting not in COLOR_CHOICES:
raise InvalidColorSetting(setting)
raise ValueError(setting)
return setting == 'always' or (setting == 'auto' and sys.stdout.isatty())
return (
setting == 'always' or (
setting == 'auto' and
sys.stderr.isatty() and
terminal_supports_color and
os.getenv('TERM') != 'dumb'
)
)
def add_color_option(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
type=use_color,
metavar='{' + ','.join(COLOR_CHOICES) + '}',
help='Whether to use color in output. Defaults to `%(default)s`.',
)

View file

@ -1,48 +0,0 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from ctypes import POINTER
from ctypes import windll
from ctypes import WinError
from ctypes import WINFUNCTYPE
from ctypes.wintypes import BOOL
from ctypes.wintypes import DWORD
from ctypes.wintypes import HANDLE
STD_OUTPUT_HANDLE = -11
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
def bool_errcheck(result, func, args):
if not result:
raise WinError()
return args
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
("GetStdHandle", windll.kernel32), ((1, "nStdHandle"),),
)
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
("GetConsoleMode", windll.kernel32),
((1, "hConsoleHandle"), (2, "lpMode")),
)
GetConsoleMode.errcheck = bool_errcheck
SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
("SetConsoleMode", windll.kernel32),
((1, "hConsoleHandle"), (1, "dwMode")),
)
SetConsoleMode.errcheck = bool_errcheck
def enable_virtual_terminal_processing():
"""As of Windows 10, the Windows console supports (some) ANSI escape
sequences, but it needs to be enabled using `SetConsoleMode` first.
More info on the escape sequences supported:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
"""
stdout = GetStdHandle(STD_OUTPUT_HANDLE)
flags = GetConsoleMode(stdout)
SetConsoleMode(stdout, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)

View file

@ -1,150 +1,215 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
import concurrent.futures
import os.path
import re
from collections import OrderedDict
from aspy.yaml import ordered_dump
from aspy.yaml import ordered_load
from cfgv import remove_defaults
import tempfile
from collections.abc import Sequence
from typing import Any
from typing import NamedTuple
import pre_commit.constants as C
from pre_commit import git
from pre_commit import output
from pre_commit.clientlib import CONFIG_SCHEMA
from pre_commit.clientlib import is_local_repo
from pre_commit.clientlib import is_meta_repo
from pre_commit import xargs
from pre_commit.clientlib import InvalidManifestError
from pre_commit.clientlib import load_config
from pre_commit.clientlib import load_manifest
from pre_commit.clientlib import LOCAL
from pre_commit.clientlib import META
from pre_commit.commands.migrate_config import migrate_config
from pre_commit.repository import Repository
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from pre_commit.yaml import yaml_dump
from pre_commit.yaml import yaml_load
class RevInfo(NamedTuple):
repo: str
rev: str
frozen: str | None = None
hook_ids: frozenset[str] = frozenset()
@classmethod
def from_config(cls, config: dict[str, Any]) -> RevInfo:
return cls(config['repo'], config['rev'])
def update(self, tags_only: bool, freeze: bool) -> RevInfo:
with tempfile.TemporaryDirectory() as tmp:
_git = ('git', *git.NO_FS_MONITOR, '-C', tmp)
if tags_only:
tag_opt = '--abbrev=0'
else:
tag_opt = '--exact'
tag_cmd = (*_git, 'describe', 'FETCH_HEAD', '--tags', tag_opt)
git.init_repo(tmp, self.repo)
cmd_output_b(*_git, 'config', 'extensions.partialClone', 'true')
cmd_output_b(
*_git, 'fetch', 'origin', 'HEAD',
'--quiet', '--filter=blob:none', '--tags',
)
try:
rev = cmd_output(*tag_cmd)[1].strip()
except CalledProcessError:
rev = cmd_output(*_git, 'rev-parse', 'FETCH_HEAD')[1].strip()
else:
if tags_only:
rev = git.get_best_candidate_tag(rev, tmp)
frozen = None
if freeze:
exact = cmd_output(*_git, 'rev-parse', rev)[1].strip()
if exact != rev:
rev, frozen = exact, rev
try:
# workaround for windows -- see #2865
cmd_output_b(*_git, 'show', f'{rev}:{C.MANIFEST_FILE}')
cmd_output(*_git, 'checkout', rev, '--', C.MANIFEST_FILE)
except CalledProcessError:
pass # this will be caught by manifest validating code
try:
manifest = load_manifest(os.path.join(tmp, C.MANIFEST_FILE))
except InvalidManifestError as e:
raise RepositoryCannotBeUpdatedError(f'[{self.repo}] {e}')
else:
hook_ids = frozenset(hook['id'] for hook in manifest)
return self._replace(rev=rev, frozen=frozen, hook_ids=hook_ids)
class RepositoryCannotBeUpdatedError(RuntimeError):
pass
def _update_repo(repo_config, store, tags_only):
"""Updates a repository to the tip of `master`. If the repository cannot
be updated because a hook that is configured does not exist in `master`,
this raises a RepositoryCannotBeUpdatedError
Args:
repo_config - A config for a repository
"""
repo_path = store.clone(repo_config['repo'], repo_config['rev'])
cmd_output('git', 'fetch', cwd=repo_path)
tag_cmd = ('git', 'describe', 'origin/master', '--tags')
if tags_only:
tag_cmd += ('--abbrev=0',)
else:
tag_cmd += ('--exact',)
try:
rev = cmd_output(*tag_cmd, cwd=repo_path)[1].strip()
except CalledProcessError:
tag_cmd = ('git', 'rev-parse', 'origin/master')
rev = cmd_output(*tag_cmd, cwd=repo_path)[1].strip()
# Don't bother trying to update if our rev is the same
if rev == repo_config['rev']:
return repo_config
# Construct a new config with the head rev
new_config = OrderedDict(repo_config)
new_config['rev'] = rev
new_repo = Repository.create(new_config, store)
def _check_hooks_still_exist_at_rev(
repo_config: dict[str, Any],
info: RevInfo,
) -> None:
# See if any of our hooks were deleted with the new commits
hooks = {hook['id'] for hook in repo_config['hooks']}
hooks_missing = hooks - (hooks & set(new_repo.manifest_hooks))
hooks_missing = hooks - info.hook_ids
if hooks_missing:
raise RepositoryCannotBeUpdatedError(
'Cannot update because the tip of master is missing these hooks:\n'
'{}'.format(', '.join(sorted(hooks_missing))),
f'[{info.repo}] Cannot update because the update target is '
f'missing these hooks: {", ".join(sorted(hooks_missing))}',
)
return new_config
def _update_one(
i: int,
repo: dict[str, Any],
*,
tags_only: bool,
freeze: bool,
) -> tuple[int, RevInfo, RevInfo]:
old = RevInfo.from_config(repo)
new = old.update(tags_only=tags_only, freeze=freeze)
_check_hooks_still_exist_at_rev(repo, new)
return i, old, new
REV_LINE_RE = re.compile(r'^(\s+)rev:(\s*)([^\s#]+)(.*)$', re.DOTALL)
REV_LINE_FMT = '{}rev:{}{}{}'
REV_LINE_RE = re.compile(r'^(\s+)rev:(\s*)([\'"]?)([^\s#]+)(.*)(\r?\n)$')
def _write_new_config_file(path, output):
original_contents = open(path).read()
output = remove_defaults(output, CONFIG_SCHEMA)
new_contents = ordered_dump(output, **C.YAML_DUMP_KWARGS)
def _original_lines(
path: str,
rev_infos: list[RevInfo | None],
retry: bool = False,
) -> tuple[list[str], list[int]]:
"""detect `rev:` lines or reformat the file"""
with open(path, newline='') as f:
original = f.read()
lines = original_contents.splitlines(True)
rev_line_indices_reversed = list(reversed([
i for i, line in enumerate(lines) if REV_LINE_RE.match(line)
]))
for line in new_contents.splitlines(True):
if REV_LINE_RE.match(line):
# It's possible we didn't identify the rev lines in the original
if not rev_line_indices_reversed:
break
line_index = rev_line_indices_reversed.pop()
original_line = lines[line_index]
orig_match = REV_LINE_RE.match(original_line)
new_match = REV_LINE_RE.match(line)
lines[line_index] = REV_LINE_FMT.format(
orig_match.group(1), orig_match.group(2),
new_match.group(3), orig_match.group(4),
)
# If we failed to intelligently rewrite the rev lines, fall back to the
# pretty-formatted yaml output
to_write = ''.join(lines)
if remove_defaults(ordered_load(to_write), CONFIG_SCHEMA) != output:
to_write = new_contents
with open(path, 'w') as f:
f.write(to_write)
lines = original.splitlines(True)
idxs = [i for i, line in enumerate(lines) if REV_LINE_RE.match(line)]
if len(idxs) == len(rev_infos):
return lines, idxs
elif retry:
raise AssertionError('could not find rev lines')
else:
with open(path, 'w') as f:
f.write(yaml_dump(yaml_load(original)))
return _original_lines(path, rev_infos, retry=True)
def autoupdate(runner, store, tags_only, repos=()):
"""Auto-update the pre-commit config to the latest versions of repos."""
migrate_config(runner, quiet=True)
retv = 0
output_repos = []
changed = False
def _write_new_config(path: str, rev_infos: list[RevInfo | None]) -> None:
lines, idxs = _original_lines(path, rev_infos)
input_config = load_config(runner.config_file_path)
for repo_config in input_config['repos']:
if (
is_local_repo(repo_config) or
is_meta_repo(repo_config) or
# Skip updating any repo_configs that aren't for the specified repo
repos and repo_config['repo'] not in repos
):
output_repos.append(repo_config)
for idx, rev_info in zip(idxs, rev_infos):
if rev_info is None:
continue
output.write('Updating {}...'.format(repo_config['repo']))
try:
new_repo_config = _update_repo(repo_config, store, tags_only)
except RepositoryCannotBeUpdatedError as error:
output.write_line(error.args[0])
output_repos.append(repo_config)
retv = 1
continue
if new_repo_config['rev'] != repo_config['rev']:
changed = True
output.write_line('updating {} -> {}.'.format(
repo_config['rev'], new_repo_config['rev'],
))
output_repos.append(new_repo_config)
match = REV_LINE_RE.match(lines[idx])
assert match is not None
new_rev_s = yaml_dump({'rev': rev_info.rev}, default_style=match[3])
new_rev = new_rev_s.split(':', 1)[1].strip()
if rev_info.frozen is not None:
comment = f' # frozen: {rev_info.frozen}'
elif match[5].strip().startswith('# frozen:'):
comment = ''
else:
output.write_line('already up to date.')
output_repos.append(repo_config)
comment = match[5]
lines[idx] = f'{match[1]}rev:{match[2]}{new_rev}{comment}{match[6]}'
with open(path, 'w', newline='') as f:
f.write(''.join(lines))
def autoupdate(
config_file: str,
tags_only: bool,
freeze: bool,
repos: Sequence[str] = (),
jobs: int = 1,
) -> int:
"""Auto-update the pre-commit config to the latest versions of repos."""
migrate_config(config_file, quiet=True)
changed = False
retv = 0
config_repos = [
repo for repo in load_config(config_file)['repos']
if repo['repo'] not in {LOCAL, META}
]
rev_infos: list[RevInfo | None] = [None] * len(config_repos)
jobs = jobs or xargs.cpu_count() # 0 => number of cpus
jobs = min(jobs, len(repos) or len(config_repos)) # max 1-per-thread
jobs = max(jobs, 1) # at least one thread
with concurrent.futures.ThreadPoolExecutor(jobs) as exe:
futures = [
exe.submit(
_update_one,
i, repo, tags_only=tags_only, freeze=freeze,
)
for i, repo in enumerate(config_repos)
if not repos or repo['repo'] in repos
]
for future in concurrent.futures.as_completed(futures):
try:
i, old, new = future.result()
except RepositoryCannotBeUpdatedError as e:
output.write_line(str(e))
retv = 1
else:
if new.rev != old.rev:
changed = True
if new.frozen:
new_s = f'{new.frozen} (frozen)'
else:
new_s = new.rev
msg = f'updating {old.rev} -> {new_s}'
rev_infos[i] = new
else:
msg = 'already up to date!'
output.write_line(f'[{old.repo}] {msg}')
if changed:
output_config = input_config.copy()
output_config['repos'] = output_repos
_write_new_config_file(runner.config_file_path, output_config)
_write_new_config(config_file, rev_infos)
return retv

View file

@ -1,16 +1,16 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
import os.path
from pre_commit import output
from pre_commit.store import Store
from pre_commit.util import rmtree
def clean(store):
def clean(store: Store) -> int:
legacy_path = os.path.expanduser('~/.pre-commit')
for directory in (store.directory, legacy_path):
if os.path.exists(directory):
rmtree(directory)
output.write_line('Cleaned {}.'.format(directory))
output.write_line(f'Cleaned {directory}.')
return 0

98
pre_commit/commands/gc.py Normal file
View file

@ -0,0 +1,98 @@
from __future__ import annotations
import os.path
from typing import Any
import pre_commit.constants as C
from pre_commit import output
from pre_commit.clientlib import InvalidConfigError
from pre_commit.clientlib import InvalidManifestError
from pre_commit.clientlib import load_config
from pre_commit.clientlib import load_manifest
from pre_commit.clientlib import LOCAL
from pre_commit.clientlib import META
from pre_commit.store import Store
from pre_commit.util import rmtree
def _mark_used_repos(
store: Store,
all_repos: dict[tuple[str, str], str],
unused_repos: set[tuple[str, str]],
repo: dict[str, Any],
) -> None:
if repo['repo'] == META:
return
elif repo['repo'] == LOCAL:
for hook in repo['hooks']:
deps = hook.get('additional_dependencies')
unused_repos.discard((
store.db_repo_name(repo['repo'], deps),
C.LOCAL_REPO_VERSION,
))
else:
key = (repo['repo'], repo['rev'])
path = all_repos.get(key)
# can't inspect manifest if it isn't cloned
if path is None:
return
try:
manifest = load_manifest(os.path.join(path, C.MANIFEST_FILE))
except InvalidManifestError:
return
else:
unused_repos.discard(key)
by_id = {hook['id']: hook for hook in manifest}
for hook in repo['hooks']:
if hook['id'] not in by_id:
continue
deps = hook.get(
'additional_dependencies',
by_id[hook['id']]['additional_dependencies'],
)
unused_repos.discard((
store.db_repo_name(repo['repo'], deps), repo['rev'],
))
def _gc(store: Store) -> int:
with store.exclusive_lock(), store.connect() as db:
store._create_configs_table(db)
repos = db.execute('SELECT repo, ref, path FROM repos').fetchall()
all_repos = {(repo, ref): path for repo, ref, path in repos}
unused_repos = set(all_repos)
configs_rows = db.execute('SELECT path FROM configs').fetchall()
configs = [path for path, in configs_rows]
dead_configs = []
for config_path in configs:
try:
config = load_config(config_path)
except InvalidConfigError:
dead_configs.append(config_path)
continue
else:
for repo in config['repos']:
_mark_used_repos(store, all_repos, unused_repos, repo)
paths = [(path,) for path in dead_configs]
db.executemany('DELETE FROM configs WHERE path = ?', paths)
db.executemany(
'DELETE FROM repos WHERE repo = ? and ref = ?',
sorted(unused_repos),
)
for k in unused_repos:
rmtree(all_repos[k])
return len(unused_repos)
def gc(store: Store) -> int:
output.write_line(f'{_gc(store)} repo(s) removed.')
return 0

View file

@ -0,0 +1,95 @@
from __future__ import annotations
import argparse
import subprocess
from collections.abc import Sequence
from pre_commit.parse_shebang import normalize_cmd
def add_parsers(parser: argparse.ArgumentParser) -> None:
subparsers = parser.add_subparsers(dest='tool')
cd_parser = subparsers.add_parser(
'cd', help='cd to a subdir and run the command',
)
cd_parser.add_argument('subdir')
cd_parser.add_argument('cmd', nargs=argparse.REMAINDER)
ignore_exit_code_parser = subparsers.add_parser(
'ignore-exit-code', help='run the command but ignore the exit code',
)
ignore_exit_code_parser.add_argument('cmd', nargs=argparse.REMAINDER)
n1_parser = subparsers.add_parser(
'n1', help='run the command once per filename',
)
n1_parser.add_argument('cmd', nargs=argparse.REMAINDER)
def _cmd_filenames(cmd: tuple[str, ...]) -> tuple[
tuple[str, ...],
tuple[str, ...],
]:
for idx, val in enumerate(reversed(cmd)):
if val == '--':
split = len(cmd) - idx
break
else:
raise SystemExit('hazmat entry must end with `--`')
return cmd[:split - 1], cmd[split:]
def cd(subdir: str, cmd: tuple[str, ...]) -> int:
cmd, filenames = _cmd_filenames(cmd)
prefix = f'{subdir}/'
new_filenames = []
for filename in filenames:
if not filename.startswith(prefix):
raise SystemExit(f'unexpected file without {prefix=}: {filename}')
else:
new_filenames.append(filename.removeprefix(prefix))
cmd = normalize_cmd(cmd)
return subprocess.call((*cmd, *new_filenames), cwd=subdir)
def ignore_exit_code(cmd: tuple[str, ...]) -> int:
cmd = normalize_cmd(cmd)
subprocess.call(cmd)
return 0
def n1(cmd: tuple[str, ...]) -> int:
cmd, filenames = _cmd_filenames(cmd)
cmd = normalize_cmd(cmd)
ret = 0
for filename in filenames:
ret |= subprocess.call((*cmd, filename))
return ret
def impl(args: argparse.Namespace) -> int:
args.cmd = tuple(args.cmd)
if args.tool == 'cd':
return cd(args.subdir, args.cmd)
elif args.tool == 'ignore-exit-code':
return ignore_exit_code(args.cmd)
elif args.tool == 'n1':
return n1(args.cmd)
else:
raise NotImplementedError(f'unexpected tool: {args.tool}')
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
add_parsers(parser)
args = parser.parse_args(argv)
return impl(args)
if __name__ == '__main__':
raise SystemExit(main())

View file

@ -0,0 +1,272 @@
from __future__ import annotations
import argparse
import os.path
import subprocess
import sys
from collections.abc import Sequence
from pre_commit.commands.run import run
from pre_commit.envcontext import envcontext
from pre_commit.parse_shebang import normalize_cmd
from pre_commit.store import Store
Z40 = '0' * 40
def _run_legacy(
hook_type: str,
hook_dir: str,
args: Sequence[str],
) -> tuple[int, bytes]:
if os.environ.get('PRE_COMMIT_RUNNING_LEGACY'):
raise SystemExit(
f"bug: pre-commit's script is installed in migration mode\n"
f'run `pre-commit install -f --hook-type {hook_type}` to fix '
f'this\n\n'
f'Please report this bug at '
f'https://github.com/pre-commit/pre-commit/issues',
)
if hook_type == 'pre-push':
stdin = sys.stdin.buffer.read()
else:
stdin = b''
# not running in legacy mode
legacy_hook = os.path.join(hook_dir, f'{hook_type}.legacy')
if not os.access(legacy_hook, os.X_OK):
return 0, stdin
with envcontext((('PRE_COMMIT_RUNNING_LEGACY', '1'),)):
cmd = normalize_cmd((legacy_hook, *args))
return subprocess.run(cmd, input=stdin).returncode, stdin
def _validate_config(
retv: int,
config: str,
skip_on_missing_config: bool,
) -> None:
if not os.path.isfile(config):
if skip_on_missing_config or os.getenv('PRE_COMMIT_ALLOW_NO_CONFIG'):
print(f'`{config}` config file not found. Skipping `pre-commit`.')
raise SystemExit(retv)
else:
print(
f'No {config} file was found\n'
f'- To temporarily silence this, run '
f'`PRE_COMMIT_ALLOW_NO_CONFIG=1 git ...`\n'
f'- To permanently silence this, install pre-commit with the '
f'--allow-missing-config option\n'
f'- To uninstall pre-commit run `pre-commit uninstall`',
)
raise SystemExit(1)
def _ns(
hook_type: str,
color: bool,
*,
all_files: bool = False,
remote_branch: str | None = None,
local_branch: str | None = None,
from_ref: str | None = None,
to_ref: str | None = None,
pre_rebase_upstream: str | None = None,
pre_rebase_branch: str | None = None,
remote_name: str | None = None,
remote_url: str | None = None,
commit_msg_filename: str | None = None,
prepare_commit_message_source: str | None = None,
commit_object_name: str | None = None,
checkout_type: str | None = None,
is_squash_merge: str | None = None,
rewrite_command: str | None = None,
) -> argparse.Namespace:
return argparse.Namespace(
color=color,
hook_stage=hook_type,
remote_branch=remote_branch,
local_branch=local_branch,
from_ref=from_ref,
to_ref=to_ref,
pre_rebase_upstream=pre_rebase_upstream,
pre_rebase_branch=pre_rebase_branch,
remote_name=remote_name,
remote_url=remote_url,
commit_msg_filename=commit_msg_filename,
prepare_commit_message_source=prepare_commit_message_source,
commit_object_name=commit_object_name,
all_files=all_files,
checkout_type=checkout_type,
is_squash_merge=is_squash_merge,
rewrite_command=rewrite_command,
files=(),
hook=None,
verbose=False,
show_diff_on_failure=False,
fail_fast=False,
)
def _rev_exists(rev: str) -> bool:
return not subprocess.call(('git', 'rev-list', '--quiet', rev))
def _pre_push_ns(
color: bool,
args: Sequence[str],
stdin: bytes,
) -> argparse.Namespace | None:
remote_name = args[0]
remote_url = args[1]
for line in stdin.decode().splitlines():
parts = line.rsplit(maxsplit=3)
local_branch, local_sha, remote_branch, remote_sha = parts
if local_sha == Z40:
continue
elif remote_sha != Z40 and _rev_exists(remote_sha):
return _ns(
'pre-push', color,
from_ref=remote_sha, to_ref=local_sha,
remote_branch=remote_branch,
local_branch=local_branch,
remote_name=remote_name, remote_url=remote_url,
)
else:
# ancestors not found in remote
ancestors = subprocess.check_output((
'git', 'rev-list', local_sha, '--topo-order', '--reverse',
'--not', f'--remotes={remote_name}',
)).decode().strip()
if not ancestors:
continue
else:
first_ancestor = ancestors.splitlines()[0]
cmd = ('git', 'rev-list', '--max-parents=0', local_sha)
roots = set(subprocess.check_output(cmd).decode().splitlines())
if first_ancestor in roots:
# pushing the whole tree including root commit
return _ns(
'pre-push', color,
all_files=True,
remote_name=remote_name, remote_url=remote_url,
remote_branch=remote_branch,
local_branch=local_branch,
)
else:
rev_cmd = ('git', 'rev-parse', f'{first_ancestor}^')
source = subprocess.check_output(rev_cmd).decode().strip()
return _ns(
'pre-push', color,
from_ref=source, to_ref=local_sha,
remote_name=remote_name, remote_url=remote_url,
remote_branch=remote_branch,
local_branch=local_branch,
)
# nothing to push
return None
_EXPECTED_ARG_LENGTH_BY_HOOK = {
'commit-msg': 1,
'post-checkout': 3,
'post-commit': 0,
'pre-commit': 0,
'pre-merge-commit': 0,
'post-merge': 1,
'post-rewrite': 1,
'pre-push': 2,
}
def _check_args_length(hook_type: str, args: Sequence[str]) -> None:
if hook_type == 'prepare-commit-msg':
if len(args) < 1 or len(args) > 3:
raise SystemExit(
f'hook-impl for {hook_type} expected 1, 2, or 3 arguments '
f'but got {len(args)}: {args}',
)
elif hook_type == 'pre-rebase':
if len(args) < 1 or len(args) > 2:
raise SystemExit(
f'hook-impl for {hook_type} expected 1 or 2 arguments '
f'but got {len(args)}: {args}',
)
elif hook_type in _EXPECTED_ARG_LENGTH_BY_HOOK:
expected = _EXPECTED_ARG_LENGTH_BY_HOOK[hook_type]
if len(args) != expected:
arguments_s = 'argument' if expected == 1 else 'arguments'
raise SystemExit(
f'hook-impl for {hook_type} expected {expected} {arguments_s} '
f'but got {len(args)}: {args}',
)
else:
raise AssertionError(f'unexpected hook type: {hook_type}')
def _run_ns(
hook_type: str,
color: bool,
args: Sequence[str],
stdin: bytes,
) -> argparse.Namespace | None:
_check_args_length(hook_type, args)
if hook_type == 'pre-push':
return _pre_push_ns(color, args, stdin)
elif hook_type in 'commit-msg':
return _ns(hook_type, color, commit_msg_filename=args[0])
elif hook_type == 'prepare-commit-msg' and len(args) == 1:
return _ns(hook_type, color, commit_msg_filename=args[0])
elif hook_type == 'prepare-commit-msg' and len(args) == 2:
return _ns(
hook_type, color, commit_msg_filename=args[0],
prepare_commit_message_source=args[1],
)
elif hook_type == 'prepare-commit-msg' and len(args) == 3:
return _ns(
hook_type, color, commit_msg_filename=args[0],
prepare_commit_message_source=args[1], commit_object_name=args[2],
)
elif hook_type in {'post-commit', 'pre-merge-commit', 'pre-commit'}:
return _ns(hook_type, color)
elif hook_type == 'post-checkout':
return _ns(
hook_type, color,
from_ref=args[0], to_ref=args[1], checkout_type=args[2],
)
elif hook_type == 'post-merge':
return _ns(hook_type, color, is_squash_merge=args[0])
elif hook_type == 'post-rewrite':
return _ns(hook_type, color, rewrite_command=args[0])
elif hook_type == 'pre-rebase' and len(args) == 1:
return _ns(hook_type, color, pre_rebase_upstream=args[0])
elif hook_type == 'pre-rebase' and len(args) == 2:
return _ns(
hook_type, color, pre_rebase_upstream=args[0],
pre_rebase_branch=args[1],
)
else:
raise AssertionError(f'unexpected hook type: {hook_type}')
def hook_impl(
store: Store,
*,
config: str,
color: bool,
hook_type: str,
hook_dir: str,
skip_on_missing_config: bool,
args: Sequence[str],
) -> int:
retv, stdin = _run_legacy(hook_type, hook_dir, args)
_validate_config(retv, config, skip_on_missing_config)
ns = _run_ns(hook_type, color, args, stdin)
if ns is None:
return retv
else:
return retv | run(config, store, ns)

View file

@ -0,0 +1,39 @@
from __future__ import annotations
import logging
import os.path
from pre_commit.commands.install_uninstall import install
from pre_commit.store import Store
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
logger = logging.getLogger('pre_commit')
def init_templatedir(
config_file: str,
store: Store,
directory: str,
hook_types: list[str] | None,
skip_on_missing_config: bool = True,
) -> int:
install(
config_file,
store,
hook_types=hook_types,
overwrite=True,
skip_on_missing_config=skip_on_missing_config,
git_dir=directory,
)
try:
_, out, _ = cmd_output('git', 'config', 'init.templateDir')
except CalledProcessError:
configured_path = None
else:
configured_path = os.path.realpath(os.path.expanduser(out.strip()))
dest = os.path.realpath(directory)
if configured_path != dest:
logger.warning('`init.templateDir` not set to the target directory')
logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
return 0

View file

@ -1,123 +1,167 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
import io
import logging
import os.path
import shlex
import shutil
import sys
from pre_commit import git
from pre_commit import output
from pre_commit.repository import repositories
from pre_commit.util import cmd_output
from pre_commit.clientlib import InvalidConfigError
from pre_commit.clientlib import load_config
from pre_commit.repository import all_hooks
from pre_commit.repository import install_hook_envs
from pre_commit.store import Store
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
from pre_commit.util import resource_text
logger = logging.getLogger(__name__)
# This is used to identify the hook file we install
PRIOR_HASHES = (
'4d9958c90bc262f47553e2c073f14cfe',
'd8ee923c46731b42cd95cc869add4062',
'49fd668cb42069aa1b6048464be5d395',
'79f09a650522a87b0da915d0d983b2de',
'e358c9dae00eac5d06b38dfdb1e33a8c',
b'4d9958c90bc262f47553e2c073f14cfe',
b'd8ee923c46731b42cd95cc869add4062',
b'49fd668cb42069aa1b6048464be5d395',
b'79f09a650522a87b0da915d0d983b2de',
b'e358c9dae00eac5d06b38dfdb1e33a8c',
)
CURRENT_HASH = '138fd403232d2ddd5efb44317e38bf03'
CURRENT_HASH = b'138fd403232d2ddd5efb44317e38bf03'
TEMPLATE_START = '# start templated\n'
TEMPLATE_END = '# end templated\n'
def _hook_paths(git_root, hook_type):
pth = os.path.join(git.get_git_dir(git_root), 'hooks', hook_type)
return pth, '{}.legacy'.format(pth)
def _hook_types(cfg_filename: str, hook_types: list[str] | None) -> list[str]:
if hook_types is not None:
return hook_types
else:
try:
cfg = load_config(cfg_filename)
except InvalidConfigError:
return ['pre-commit']
else:
return cfg['default_install_hook_types']
def is_our_script(filename):
if not os.path.exists(filename):
def _hook_paths(
hook_type: str,
git_dir: str | None = None,
) -> tuple[str, str]:
git_dir = git_dir if git_dir is not None else git.get_git_common_dir()
pth = os.path.join(git_dir, 'hooks', hook_type)
return pth, f'{pth}.legacy'
def is_our_script(filename: str) -> bool:
if not os.path.exists(filename): # pragma: win32 no cover (symlink)
return False
contents = io.open(filename).read()
with open(filename, 'rb') as f:
contents = f.read()
return any(h in contents for h in (CURRENT_HASH,) + PRIOR_HASHES)
def install(
runner, store, overwrite=False, hooks=False, hook_type='pre-commit',
skip_on_missing_conf=False,
):
"""Install the pre-commit hooks."""
if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip():
logger.error(
'Cowardly refusing to install hooks with `core.hooksPath` set.\n'
'hint: `git config --unset-all core.hooksPath`',
)
return 1
def _install_hook_script(
config_file: str,
hook_type: str,
overwrite: bool = False,
skip_on_missing_config: bool = False,
git_dir: str | None = None,
) -> None:
hook_path, legacy_path = _hook_paths(hook_type, git_dir=git_dir)
hook_path, legacy_path = _hook_paths(runner.git_root, hook_type)
mkdirp(os.path.dirname(hook_path))
os.makedirs(os.path.dirname(hook_path), exist_ok=True)
# If we have an existing hook, move it to pre-commit.legacy
if os.path.lexists(hook_path) and not is_our_script(hook_path):
os.rename(hook_path, legacy_path)
shutil.move(hook_path, legacy_path)
# If we specify overwrite, we simply delete the legacy file
if overwrite and os.path.exists(legacy_path):
os.remove(legacy_path)
elif os.path.exists(legacy_path):
output.write_line(
'Running in migration mode with existing hooks at {}\n'
'Use -f to use only pre-commit.'.format(legacy_path),
f'Running in migration mode with existing hooks at {legacy_path}\n'
f'Use -f to use only pre-commit.',
)
params = {
'CONFIG': runner.config_file,
'HOOK_TYPE': hook_type,
'INSTALL_PYTHON': sys.executable,
'SKIP_ON_MISSING_CONFIG': skip_on_missing_conf,
}
args = ['hook-impl', f'--config={config_file}', f'--hook-type={hook_type}']
if skip_on_missing_config:
args.append('--skip-on-missing-config')
with io.open(hook_path, 'w') as hook_file:
with io.open(resource_filename('hook-tmpl')) as f:
contents = f.read()
with open(hook_path, 'w') as hook_file:
contents = resource_text('hook-tmpl')
before, rest = contents.split(TEMPLATE_START)
to_template, after = rest.split(TEMPLATE_END)
_, after = rest.split(TEMPLATE_END)
# on windows always use `/bin/sh` since `bash` might not be on PATH
# though we use bash-specific features `sh` on windows is actually
# bash in "POSIXLY_CORRECT" mode which still supports the features we
# use: subshells / arrays
if sys.platform == 'win32': # pragma: win32 cover
hook_file.write('#!/bin/sh\n')
hook_file.write(before + TEMPLATE_START)
for line in to_template.splitlines():
var = line.split()[0]
hook_file.write('{} = {!r}\n'.format(var, params[var]))
hook_file.write(f'INSTALL_PYTHON={shlex.quote(sys.executable)}\n')
args_s = shlex.join(args)
hook_file.write(f'ARGS=({args_s})\n')
hook_file.write(TEMPLATE_END + after)
make_executable(hook_path)
output.write_line('pre-commit installed at {}'.format(hook_path))
output.write_line(f'pre-commit installed at {hook_path}')
def install(
config_file: str,
store: Store,
hook_types: list[str] | None,
overwrite: bool = False,
hooks: bool = False,
skip_on_missing_config: bool = False,
git_dir: str | None = None,
) -> int:
if git_dir is None and git.has_core_hookpaths_set():
logger.error(
'Cowardly refusing to install hooks with `core.hooksPath` set.\n'
'hint: `git config --unset-all core.hooksPath`',
)
return 1
for hook_type in _hook_types(config_file, hook_types):
_install_hook_script(
config_file, hook_type,
overwrite=overwrite,
skip_on_missing_config=skip_on_missing_config,
git_dir=git_dir,
)
# If they requested we install all of the hooks, do so.
if hooks:
install_hooks(runner, store)
install_hooks(config_file, store)
return 0
def install_hooks(runner, store):
for repository in repositories(runner.config, store):
repository.require_installed()
def install_hooks(config_file: str, store: Store) -> int:
install_hook_envs(all_hooks(load_config(config_file), store), store)
return 0
def uninstall(runner, hook_type='pre-commit'):
"""Uninstall the pre-commit hooks."""
hook_path, legacy_path = _hook_paths(runner.git_root, hook_type)
def _uninstall_hook_script(hook_type: str) -> None:
hook_path, legacy_path = _hook_paths(hook_type)
# If our file doesn't exist or it isn't ours, gtfo.
if not os.path.exists(hook_path) or not is_our_script(hook_path):
return 0
return
os.remove(hook_path)
output.write_line('{} uninstalled'.format(hook_type))
output.write_line(f'{hook_type} uninstalled')
if os.path.exists(legacy_path):
os.rename(legacy_path, hook_path)
output.write_line('Restored previous hooks to {}'.format(hook_path))
os.replace(legacy_path, hook_path)
output.write_line(f'Restored previous hooks to {hook_path}')
def uninstall(config_file: str, hook_types: list[str] | None) -> int:
for hook_type in _hook_types(config_file, hook_types):
_uninstall_hook_script(hook_type)
return 0

View file

@ -1,61 +1,135 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
import io
import re
import functools
import itertools
import textwrap
from collections.abc import Callable
import cfgv
import yaml
from aspy.yaml import ordered_load
from yaml.nodes import ScalarNode
from pre_commit.clientlib import InvalidConfigError
from pre_commit.yaml import yaml_compose
from pre_commit.yaml import yaml_load
from pre_commit.yaml_rewrite import MappingKey
from pre_commit.yaml_rewrite import MappingValue
from pre_commit.yaml_rewrite import match
from pre_commit.yaml_rewrite import SequenceItem
def _indent(s):
lines = s.splitlines(True)
return ''.join(' ' * 4 + line if line.strip() else line for line in lines)
def _is_header_line(line: str) -> bool:
return line.startswith(('#', '---')) or not line.strip()
def _is_header_line(line):
return (line.startswith(('#', '---')) or not line.strip())
def _migrate_map(contents: str) -> str:
if isinstance(yaml_load(contents), list):
# Find the first non-header line
lines = contents.splitlines(True)
i = 0
# Only loop on non empty configuration file
while i < len(lines) and _is_header_line(lines[i]):
i += 1
header = ''.join(lines[:i])
rest = ''.join(lines[i:])
def _migrate_map(contents):
# Find the first non-header line
lines = contents.splitlines(True)
i = 0
while _is_header_line(lines[i]):
i += 1
header = ''.join(lines[:i])
rest = ''.join(lines[i:])
if isinstance(ordered_load(contents), list):
# If they are using the "default" flow style of yaml, this operation
# will yield a valid configuration
try:
trial_contents = header + 'repos:\n' + rest
ordered_load(trial_contents)
trial_contents = f'{header}repos:\n{rest}'
yaml_load(trial_contents)
contents = trial_contents
except yaml.YAMLError:
contents = header + 'repos:\n' + _indent(rest)
contents = f'{header}repos:\n{textwrap.indent(rest, " " * 4)}'
return contents
def _migrate_sha_to_rev(contents):
reg = re.compile(r'(\n\s+)sha:')
return reg.sub(r'\1rev:', contents)
def _preserve_style(n: ScalarNode, *, s: str) -> str:
style = n.style or ''
return f'{style}{s}{style}'
def migrate_config(runner, quiet=False):
with io.open(runner.config_file_path) as f:
def _fix_stage(n: ScalarNode) -> str:
return _preserve_style(n, s=f'pre-{n.value}')
def _migrate_composed(contents: str) -> str:
tree = yaml_compose(contents)
rewrites: list[tuple[ScalarNode, Callable[[ScalarNode], str]]] = []
# sha -> rev
sha_to_rev_replace = functools.partial(_preserve_style, s='rev')
sha_to_rev_matcher = (
MappingValue('repos'),
SequenceItem(),
MappingKey('sha'),
)
for node in match(tree, sha_to_rev_matcher):
rewrites.append((node, sha_to_rev_replace))
# python_venv -> python
language_matcher = (
MappingValue('repos'),
SequenceItem(),
MappingValue('hooks'),
SequenceItem(),
MappingValue('language'),
)
python_venv_replace = functools.partial(_preserve_style, s='python')
for node in match(tree, language_matcher):
if node.value == 'python_venv':
rewrites.append((node, python_venv_replace))
# stages rewrites
default_stages_matcher = (MappingValue('default_stages'), SequenceItem())
default_stages_match = match(tree, default_stages_matcher)
hook_stages_matcher = (
MappingValue('repos'),
SequenceItem(),
MappingValue('hooks'),
SequenceItem(),
MappingValue('stages'),
SequenceItem(),
)
hook_stages_match = match(tree, hook_stages_matcher)
for node in itertools.chain(default_stages_match, hook_stages_match):
if node.value in {'commit', 'push', 'merge-commit'}:
rewrites.append((node, _fix_stage))
rewrites.sort(reverse=True, key=lambda nf: nf[0].start_mark.index)
src_parts = []
end: int | None = None
for node, func in rewrites:
src_parts.append(contents[node.end_mark.index:end])
src_parts.append(func(node))
end = node.start_mark.index
src_parts.append(contents[:end])
src_parts.reverse()
return ''.join(src_parts)
def migrate_config(config_file: str, quiet: bool = False) -> int:
with open(config_file) as f:
orig_contents = contents = f.read()
with cfgv.reraise_as(InvalidConfigError):
with cfgv.validate_context(f'File {config_file}'):
try:
yaml_load(orig_contents)
except Exception as e:
raise cfgv.ValidationError(str(e))
contents = _migrate_map(contents)
contents = _migrate_sha_to_rev(contents)
contents = _migrate_composed(contents)
if contents != orig_contents:
with io.open(runner.config_file_path, 'w') as f:
with open(config_file, 'w') as f:
f.write(contents)
print('Configuration has been migrated.')
elif not quiet:
print('Configuration is already migrated.')
return 0

View file

@ -1,171 +1,248 @@
from __future__ import unicode_literals
from __future__ import annotations
import argparse
import contextlib
import functools
import logging
import os
import re
import subprocess
import sys
import time
import unicodedata
from collections.abc import Generator
from collections.abc import Iterable
from collections.abc import MutableMapping
from collections.abc import Sequence
from typing import Any
from identify.identify import tags_from_path
from pre_commit import color
from pre_commit import git
from pre_commit import output
from pre_commit.output import get_hook_message
from pre_commit.repository import repositories
from pre_commit.all_languages import languages
from pre_commit.clientlib import load_config
from pre_commit.hook import Hook
from pre_commit.repository import all_hooks
from pre_commit.repository import install_hook_envs
from pre_commit.staged_files_only import staged_files_only
from pre_commit.util import cmd_output
from pre_commit.util import memoize_by_cwd
from pre_commit.util import noop_context
from pre_commit.store import Store
from pre_commit.util import cmd_output_b
logger = logging.getLogger('pre_commit')
tags_from_path = memoize_by_cwd(tags_from_path)
def _len_cjk(msg: str) -> int:
widths = {'A': 1, 'F': 2, 'H': 1, 'N': 1, 'Na': 1, 'W': 2}
return sum(widths[unicodedata.east_asian_width(c)] for c in msg)
def _get_skips(environ):
skips = environ.get('SKIP', '')
return {skip.strip() for skip in skips.split(',') if skip.strip()}
def _start_msg(*, start: str, cols: int, end_len: int) -> str:
dots = '.' * (cols - _len_cjk(start) - end_len - 1)
return f'{start}{dots}'
def _hook_msg_start(hook, verbose):
return '{}{}'.format(
'[{}] '.format(hook['id']) if verbose else '', hook['name'],
def _full_msg(
*,
start: str,
cols: int,
end_msg: str,
end_color: str,
use_color: bool,
postfix: str = '',
) -> str:
dots = '.' * (cols - _len_cjk(start) - len(postfix) - len(end_msg) - 1)
end = color.format_color(end_msg, end_color, use_color)
return f'{start}{dots}{postfix}{end}\n'
def filter_by_include_exclude(
names: Iterable[str],
include: str,
exclude: str,
) -> Generator[str]:
include_re, exclude_re = re.compile(include), re.compile(exclude)
return (
filename for filename in names
if include_re.search(filename)
if not exclude_re.search(filename)
)
def _filter_by_include_exclude(filenames, include, exclude):
include_re, exclude_re = re.compile(include), re.compile(exclude)
return [
filename for filename in filenames
if (
include_re.search(filename) and
not exclude_re.search(filename) and
os.path.lexists(filename)
class Classifier:
def __init__(self, filenames: Iterable[str]) -> None:
self.filenames = [f for f in filenames if os.path.lexists(f)]
@functools.cache
def _types_for_file(self, filename: str) -> set[str]:
return tags_from_path(filename)
def by_types(
self,
names: Iterable[str],
types: Iterable[str],
types_or: Iterable[str],
exclude_types: Iterable[str],
) -> Generator[str]:
types = frozenset(types)
types_or = frozenset(types_or)
exclude_types = frozenset(exclude_types)
for filename in names:
tags = self._types_for_file(filename)
if (
tags >= types and
(not types_or or tags & types_or) and
not tags & exclude_types
):
yield filename
def filenames_for_hook(self, hook: Hook) -> Generator[str]:
return self.by_types(
filter_by_include_exclude(
self.filenames,
hook.files,
hook.exclude,
),
hook.types,
hook.types_or,
hook.exclude_types,
)
]
@classmethod
def from_config(
cls,
filenames: Iterable[str],
include: str,
exclude: str,
) -> Classifier:
# on windows we normalize all filenames to use forward slashes
# this makes it easier to filter using the `files:` regex
# this also makes improperly quoted shell-based hooks work better
# see #1173
if os.altsep == '/' and os.sep == '\\':
filenames = (f.replace(os.sep, os.altsep) for f in filenames)
filenames = filter_by_include_exclude(filenames, include, exclude)
return Classifier(filenames)
def _filter_by_types(filenames, types, exclude_types):
types, exclude_types = frozenset(types), frozenset(exclude_types)
ret = []
for filename in filenames:
tags = tags_from_path(filename)
if tags >= types and not tags & exclude_types:
ret.append(filename)
return tuple(ret)
def _get_skips(environ: MutableMapping[str, str]) -> set[str]:
skips = environ.get('SKIP', '')
return {skip.strip() for skip in skips.split(',') if skip.strip()}
SKIPPED = 'Skipped'
NO_FILES = '(no files to check)'
def _run_single_hook(filenames, hook, repo, args, skips, cols):
include, exclude = hook['files'], hook['exclude']
filenames = _filter_by_include_exclude(filenames, include, exclude)
types, exclude_types = hook['types'], hook['exclude_types']
filenames = _filter_by_types(filenames, types, exclude_types)
def _subtle_line(s: str, use_color: bool) -> None:
output.write_line(color.format_color(s, color.SUBTLE, use_color))
if hook['language'] == 'pcre':
logger.warning(
'`{}` (from {}) uses the deprecated pcre language.\n'
'The pcre language is scheduled for removal in pre-commit 2.x.\n'
'The pygrep language is a more portable (and usually drop-in) '
'replacement.'.format(hook['id'], repo.repo_config['repo']),
def _run_single_hook(
classifier: Classifier,
hook: Hook,
skips: set[str],
cols: int,
diff_before: bytes,
verbose: bool,
use_color: bool,
) -> tuple[bool, bytes]:
filenames = tuple(classifier.filenames_for_hook(hook))
if hook.id in skips or hook.alias in skips:
output.write(
_full_msg(
start=hook.name,
end_msg=SKIPPED,
end_color=color.YELLOW,
use_color=use_color,
cols=cols,
),
)
if hook['id'] in skips:
output.write(get_hook_message(
_hook_msg_start(hook, args.verbose),
end_msg=SKIPPED,
end_color=color.YELLOW,
use_color=args.color,
cols=cols,
))
return 0
elif not filenames and not hook['always_run']:
output.write(get_hook_message(
_hook_msg_start(hook, args.verbose),
postfix=NO_FILES,
end_msg=SKIPPED,
end_color=color.TURQUOISE,
use_color=args.color,
cols=cols,
))
return 0
# Print the hook and the dots first in case the hook takes hella long to
# run.
output.write(get_hook_message(
_hook_msg_start(hook, args.verbose), end_len=6, cols=cols,
))
sys.stdout.flush()
diff_before = cmd_output(
'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
)
retcode, stdout, stderr = repo.run_hook(
hook, tuple(filenames) if hook['pass_filenames'] else (),
)
diff_after = cmd_output(
'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
)
file_modifications = diff_before != diff_after
# If the hook makes changes, fail the commit
if file_modifications:
retcode = 1
if retcode:
retcode = 1
print_color = color.RED
pass_fail = 'Failed'
else:
duration = None
retcode = 0
print_color = color.GREEN
pass_fail = 'Passed'
diff_after = diff_before
files_modified = False
out = b''
elif not filenames and not hook.always_run:
output.write(
_full_msg(
start=hook.name,
postfix=NO_FILES,
end_msg=SKIPPED,
end_color=color.TURQUOISE,
use_color=use_color,
cols=cols,
),
)
duration = None
retcode = 0
diff_after = diff_before
files_modified = False
out = b''
else:
# print hook and dots first in case the hook takes a while to run
output.write(_start_msg(start=hook.name, end_len=6, cols=cols))
output.write_line(color.format_color(pass_fail, print_color, args.color))
if not hook.pass_filenames:
filenames = ()
time_before = time.monotonic()
language = languages[hook.language]
with language.in_env(hook.prefix, hook.language_version):
retcode, out = language.run_hook(
hook.prefix,
hook.entry,
hook.args,
filenames,
is_local=hook.src == 'local',
require_serial=hook.require_serial,
color=use_color,
)
duration = round(time.monotonic() - time_before, 2) or 0
diff_after = _get_diff()
if (
(stdout or stderr or file_modifications) and
(retcode or args.verbose or hook['verbose'])
):
output.write_line('hookid: {}\n'.format(hook['id']))
# if the hook makes changes, fail the commit
files_modified = diff_before != diff_after
if retcode or files_modified:
print_color = color.RED
status = 'Failed'
else:
print_color = color.GREEN
status = 'Passed'
output.write_line(color.format_color(status, print_color, use_color))
if verbose or hook.verbose or retcode or files_modified:
_subtle_line(f'- hook id: {hook.id}', use_color)
if (verbose or hook.verbose) and duration is not None:
_subtle_line(f'- duration: {duration}s', use_color)
if retcode:
_subtle_line(f'- exit code: {retcode}', use_color)
# Print a message if failing due to file modifications
if file_modifications:
output.write('Files were modified by this hook.')
if stdout or stderr:
output.write_line(' Additional output:')
if files_modified:
_subtle_line('- files were modified by this hook', use_color)
if out.strip():
output.write_line()
output.write_line_b(out.strip(), logfile_name=hook.log_file)
output.write_line()
for out in (stdout, stderr):
assert type(out) is bytes, type(out)
if out.strip():
output.write_line(out.strip(), logfile_name=hook['log_file'])
output.write_line()
return retcode
return files_modified or bool(retcode), diff_after
def _compute_cols(hooks, verbose):
def _compute_cols(hooks: Sequence[Hook]) -> int:
"""Compute the number of columns to display hook messages. The widest
that will be displayed is in the no files skipped case:
Hook name...(no files to check) Skipped
or in the verbose case
Hook name [hookid]...(no files to check) Skipped
"""
if hooks:
name_len = max(len(_hook_msg_start(hook, verbose)) for hook in hooks)
name_len = max(_len_cjk(hook.name) for hook in hooks)
else:
name_len = 0
@ -173,11 +250,17 @@ def _compute_cols(hooks, verbose):
return max(cols, 80)
def _all_filenames(args):
if args.origin and args.source:
return git.get_changed_files(args.origin, args.source)
elif args.hook_stage == 'commit-msg':
def _all_filenames(args: argparse.Namespace) -> Iterable[str]:
# these hooks do not operate on files
if args.hook_stage in {
'post-checkout', 'post-commit', 'post-merge', 'post-rewrite',
'pre-rebase',
}:
return ()
elif args.hook_stage in {'prepare-commit-msg', 'commit-msg'}:
return (args.commit_msg_filename,)
elif args.from_ref and args.to_ref:
return git.get_changed_files(args.from_ref, args.to_ref)
elif args.files:
return args.files
elif args.all_files:
@ -188,83 +271,178 @@ def _all_filenames(args):
return git.get_staged_files()
def _run_hooks(config, repo_hooks, args, environ):
def _get_diff() -> bytes:
_, out, _ = cmd_output_b(
'git', 'diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules',
check=False,
)
return out
def _run_hooks(
config: dict[str, Any],
hooks: Sequence[Hook],
skips: set[str],
args: argparse.Namespace,
) -> int:
"""Actually run the hooks."""
skips = _get_skips(environ)
cols = _compute_cols([hook for _, hook in repo_hooks], args.verbose)
filenames = _all_filenames(args)
filenames = _filter_by_include_exclude(filenames, '', config['exclude'])
cols = _compute_cols(hooks)
classifier = Classifier.from_config(
_all_filenames(args), config['files'], config['exclude'],
)
retval = 0
for repo, hook in repo_hooks:
retval |= _run_single_hook(filenames, hook, repo, args, skips, cols)
if retval and config['fail_fast']:
prior_diff = _get_diff()
for hook in hooks:
current_retval, prior_diff = _run_single_hook(
classifier, hook, skips, cols, prior_diff,
verbose=args.verbose, use_color=args.color,
)
retval |= current_retval
fail_fast = (config['fail_fast'] or hook.fail_fast or args.fail_fast)
if current_retval and fail_fast:
break
if (
retval and
args.show_diff_on_failure and
subprocess.call(('git', 'diff', '--quiet', '--no-ext-diff')) != 0
):
if retval and args.show_diff_on_failure and prior_diff:
if args.all_files:
output.write_line(
'pre-commit hook(s) made changes.\n'
'If you are seeing this message in CI, '
'reproduce locally with: `pre-commit run --all-files`.\n'
'To run `pre-commit` as part of git workflow, use '
'`pre-commit install`.',
)
output.write_line('All changes made by hooks:')
subprocess.call(('git', '--no-pager', 'diff', '--no-ext-diff'))
# args.color is a boolean.
# See user_color function in color.py
git_color_opt = 'always' if args.color else 'never'
subprocess.call((
'git', '--no-pager', 'diff', '--no-ext-diff',
f'--color={git_color_opt}',
))
return retval
def _has_unmerged_paths():
_, stdout, _ = cmd_output('git', 'ls-files', '--unmerged')
def _has_unmerged_paths() -> bool:
_, stdout, _ = cmd_output_b('git', 'ls-files', '--unmerged')
return bool(stdout.strip())
def _has_unstaged_config(runner):
retcode, _, _ = cmd_output(
'git', 'diff', '--no-ext-diff', '--exit-code', runner.config_file_path,
retcode=None,
def _has_unstaged_config(config_file: str) -> bool:
retcode, _, _ = cmd_output_b(
'git', 'diff', '--quiet', '--no-ext-diff', config_file, check=False,
)
# be explicit, other git errors don't mean it has an unstaged config.
return retcode == 1
def run(runner, store, args, environ=os.environ):
no_stash = args.all_files or bool(args.files)
def run(
config_file: str,
store: Store,
args: argparse.Namespace,
environ: MutableMapping[str, str] = os.environ,
) -> int:
stash = not args.all_files and not args.files
# Check if we have unresolved merge conflict files and fail fast.
if _has_unmerged_paths():
if stash and _has_unmerged_paths():
logger.error('Unmerged files. Resolve before committing.')
return 1
if bool(args.source) != bool(args.origin):
logger.error('Specify both --origin and --source.')
if bool(args.from_ref) != bool(args.to_ref):
logger.error('Specify both --from-ref and --to-ref.')
return 1
if _has_unstaged_config(runner) and not no_stash:
if stash and _has_unstaged_config(config_file):
logger.error(
'Your pre-commit configuration is unstaged.\n'
'`git add {}` to fix this.'.format(runner.config_file),
f'Your pre-commit configuration is unstaged.\n'
f'`git add {config_file}` to fix this.',
)
return 1
if (
args.hook_stage in {'prepare-commit-msg', 'commit-msg'} and
not args.commit_msg_filename
):
logger.error(
f'`--commit-msg-filename` is required for '
f'`--hook-stage {args.hook_stage}`',
)
return 1
# prevent recursive post-checkout hooks (#1418)
if (
args.hook_stage == 'post-checkout' and
environ.get('_PRE_COMMIT_SKIP_POST_CHECKOUT')
):
return 0
# Expose origin / source as environment variables for hooks to consume
if args.origin and args.source:
environ['PRE_COMMIT_ORIGIN'] = args.origin
environ['PRE_COMMIT_SOURCE'] = args.source
# Expose prepare_commit_message_source / commit_object_name
# as environment variables for the hooks
if args.prepare_commit_message_source:
environ['PRE_COMMIT_COMMIT_MSG_SOURCE'] = (
args.prepare_commit_message_source
)
if no_stash:
ctx = noop_context()
else:
ctx = staged_files_only(store.directory)
if args.commit_object_name:
environ['PRE_COMMIT_COMMIT_OBJECT_NAME'] = args.commit_object_name
with ctx:
repo_hooks = []
for repo in repositories(runner.config, store):
for _, hook in repo.hooks:
if (
(not args.hook or hook['id'] == args.hook) and
(not hook['stages'] or args.hook_stage in hook['stages'])
):
repo_hooks.append((repo, hook))
# Expose from-ref / to-ref as environment variables for hooks to consume
if args.from_ref and args.to_ref:
# legacy names
environ['PRE_COMMIT_ORIGIN'] = args.from_ref
environ['PRE_COMMIT_SOURCE'] = args.to_ref
# new names
environ['PRE_COMMIT_FROM_REF'] = args.from_ref
environ['PRE_COMMIT_TO_REF'] = args.to_ref
if args.hook and not repo_hooks:
output.write_line('No hook with id `{}`'.format(args.hook))
if args.pre_rebase_upstream and args.pre_rebase_branch:
environ['PRE_COMMIT_PRE_REBASE_UPSTREAM'] = args.pre_rebase_upstream
environ['PRE_COMMIT_PRE_REBASE_BRANCH'] = args.pre_rebase_branch
if (
args.remote_name and args.remote_url and
args.remote_branch and args.local_branch
):
environ['PRE_COMMIT_LOCAL_BRANCH'] = args.local_branch
environ['PRE_COMMIT_REMOTE_BRANCH'] = args.remote_branch
environ['PRE_COMMIT_REMOTE_NAME'] = args.remote_name
environ['PRE_COMMIT_REMOTE_URL'] = args.remote_url
if args.checkout_type:
environ['PRE_COMMIT_CHECKOUT_TYPE'] = args.checkout_type
if args.is_squash_merge:
environ['PRE_COMMIT_IS_SQUASH_MERGE'] = args.is_squash_merge
if args.rewrite_command:
environ['PRE_COMMIT_REWRITE_COMMAND'] = args.rewrite_command
# Set pre_commit flag
environ['PRE_COMMIT'] = '1'
with contextlib.ExitStack() as exit_stack:
if stash:
exit_stack.enter_context(staged_files_only(store.directory))
config = load_config(config_file)
hooks = [
hook
for hook in all_hooks(config, store)
if not args.hook or hook.id == args.hook or hook.alias == args.hook
if args.hook_stage in hook.stages
]
if args.hook and not hooks:
output.write_line(
f'No hook with id `{args.hook}` in stage `{args.hook_stage}`',
)
return 1
for repo in {repo for repo, _ in repo_hooks}:
repo.require_installed()
skips = _get_skips(environ)
to_install = [
hook
for hook in hooks
if hook.id not in skips and hook.alias not in skips
]
install_hook_envs(to_install, store)
return _run_hooks(runner.config, repo_hooks, args, environ)
return _run_hooks(config, hooks, skips, args)
# https://github.com/python/mypy/issues/7726
raise AssertionError('unreachable')

View file

@ -1,18 +1,10 @@
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
# TODO: maybe `git ls-remote git://github.com/pre-commit/pre-commit-hooks` to
# determine the latest revision? This adds ~200ms from my tests (and is
# significantly faster than https:// or http://). For now, periodically
# manually updating the revision is fine.
from __future__ import annotations
SAMPLE_CONFIG = '''\
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.2.1-1
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@ -21,6 +13,6 @@ repos:
'''
def sample_config():
def sample_config() -> int:
print(SAMPLE_CONFIG, end='')
return 0

View file

@ -1,37 +1,68 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import collections
import argparse
import logging
import os.path
from aspy.yaml import ordered_dump
import tempfile
import pre_commit.constants as C
from pre_commit import git
from pre_commit import output
from pre_commit.clientlib import load_manifest
from pre_commit.commands.run import run
from pre_commit.runner import Runner
from pre_commit.store import Store
from pre_commit.util import tmpdir
from pre_commit.util import cmd_output_b
from pre_commit.xargs import xargs
from pre_commit.yaml import yaml_dump
logger = logging.getLogger(__name__)
def try_repo(args):
ref = args.ref or git.head_rev(args.repo)
def _repo_ref(tmpdir: str, repo: str, ref: str | None) -> tuple[str, str]:
# if `ref` is explicitly passed, use it
if ref is not None:
return repo, ref
ref = git.head_rev(repo)
# if it exists on disk, we'll try and clone it with the local changes
if os.path.exists(repo) and git.has_diff('HEAD', repo=repo):
logger.warning('Creating temporary repo with uncommitted changes...')
shadow = os.path.join(tmpdir, 'shadow-repo')
cmd_output_b('git', 'clone', repo, shadow)
cmd_output_b('git', 'checkout', ref, '-b', '_pc_tmp', cwd=shadow)
idx = git.git_path('index', repo=shadow)
objs = git.git_path('objects', repo=shadow)
env = dict(os.environ, GIT_INDEX_FILE=idx, GIT_OBJECT_DIRECTORY=objs)
staged_files = git.get_staged_files(cwd=repo)
if staged_files:
xargs(('git', 'add', '--'), staged_files, cwd=repo, env=env)
cmd_output_b('git', 'add', '-u', cwd=repo, env=env)
git.commit(repo=shadow)
return shadow, git.head_rev(shadow)
else:
return repo, ref
def try_repo(args: argparse.Namespace) -> int:
with tempfile.TemporaryDirectory() as tempdir:
repo, ref = _repo_ref(tempdir, args.repo, args.ref)
with tmpdir() as tempdir:
store = Store(tempdir)
if args.hook:
hooks = [{'id': args.hook}]
else:
repo_path = store.clone(args.repo, ref)
repo_path = store.clone(repo, ref)
manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE))
manifest = sorted(manifest, key=lambda hook: hook['id'])
hooks = [{'id': hook['id']} for hook in manifest]
items = (('repo', args.repo), ('rev', ref), ('hooks', hooks))
config = {'repos': [collections.OrderedDict(items)]}
config_s = ordered_dump(config, **C.YAML_DUMP_KWARGS)
config = {'repos': [{'repo': repo, 'rev': ref, 'hooks': hooks}]}
config_s = yaml_dump(config)
config_filename = os.path.join(tempdir, C.CONFIG_FILE)
with open(config_filename, 'w') as cfg:
@ -43,4 +74,4 @@ def try_repo(args):
output.write(config_s)
output.write_line('=' * 79)
return run(Runner('.', config_filename), store, args)
return run(config_filename, store, args)

View file

@ -0,0 +1,18 @@
from __future__ import annotations
from collections.abc import Sequence
from pre_commit import clientlib
def validate_config(filenames: Sequence[str]) -> int:
ret = 0
for filename in filenames:
try:
clientlib.load_config(filename)
except clientlib.InvalidConfigError as e:
print(e)
ret = 1
return ret

View file

@ -0,0 +1,18 @@
from __future__ import annotations
from collections.abc import Sequence
from pre_commit import clientlib
def validate_manifest(filenames: Sequence[str]) -> int:
ret = 0
for filename in filenames:
try:
clientlib.load_manifest(filename)
except clientlib.InvalidManifestError as e:
print(e)
ret = 1
return ret

View file

@ -1,25 +1,13 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import pkg_resources
import importlib.metadata
CONFIG_FILE = '.pre-commit-config.yaml'
MANIFEST_FILE = '.pre-commit-hooks.yaml'
YAML_DUMP_KWARGS = {
'default_flow_style': False,
# Use unicode
'encoding': None,
'indent': 4,
}
# Bump when installation changes in a backwards / forwards incompatible way
INSTALLED_STATE_VERSION = '1'
# Bump when modifying `empty_template`
LOCAL_REPO_VERSION = '1'
VERSION = pkg_resources.get_distribution('pre-commit').version
VERSION_PARSED = pkg_resources.parse_version(VERSION)
VERSION = importlib.metadata.version('pre_commit')
# `manual` is not invoked by any installed git hook. See #719
STAGES = ('commit', 'commit-msg', 'manual', 'push')
DEFAULT = 'default'

View file

@ -1,19 +1,28 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import collections
import contextlib
import enum
import os
from collections.abc import Generator
from collections.abc import MutableMapping
from typing import NamedTuple
from typing import Union
_Unset = enum.Enum('_Unset', 'UNSET')
UNSET = _Unset.UNSET
UNSET = collections.namedtuple('UNSET', ())()
class Var(NamedTuple):
name: str
default: str = ''
Var = collections.namedtuple('Var', ('name', 'default'))
Var.__new__.__defaults__ = ('',)
SubstitutionT = tuple[Union[str, Var], ...]
ValueT = Union[str, _Unset, SubstitutionT]
PatchesT = tuple[tuple[str, ValueT], ...]
def format_env(parts, env):
def format_env(parts: SubstitutionT, env: MutableMapping[str, str]) -> str:
return ''.join(
env.get(part.name, part.default) if isinstance(part, Var) else part
for part in parts
@ -21,7 +30,10 @@ def format_env(parts, env):
@contextlib.contextmanager
def envcontext(patch, _env=None):
def envcontext(
patch: PatchesT,
_env: MutableMapping[str, str] | None = None,
) -> Generator[None]:
"""In this context, `os.environ` is modified according to `patch`.
`patch` is an iterable of 2-tuples (key, value):
@ -33,7 +45,7 @@ def envcontext(patch, _env=None):
replaced with the previous environment
"""
env = os.environ if _env is None else _env
before = env.copy()
before = dict(env)
for k, v in patch:
if v is UNSET:

View file

@ -1,53 +1,81 @@
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import os.path
import sys
import traceback
from collections.abc import Generator
from typing import IO
import six
from pre_commit import five
import pre_commit.constants as C
from pre_commit import output
from pre_commit.errors import FatalError
from pre_commit.store import Store
from pre_commit.util import cmd_output_b
from pre_commit.util import force_bytes
class FatalError(RuntimeError):
pass
def _log_and_exit(
msg: str,
ret_code: int,
exc: BaseException,
formatted: str,
) -> None:
error_msg = f'{msg}: {type(exc).__name__}: '.encode() + force_bytes(exc)
output.write_line_b(error_msg)
_, git_version_b, _ = cmd_output_b('git', '--version', check=False)
git_version = git_version_b.decode(errors='backslashreplace').rstrip()
def _to_bytes(exc):
try:
return bytes(exc)
except Exception:
return six.text_type(exc).encode('UTF-8')
storedir = Store().directory
log_path = os.path.join(storedir, 'pre-commit.log')
with contextlib.ExitStack() as ctx:
if os.access(storedir, os.W_OK):
output.write_line(f'Check the log at {log_path}')
log: IO[bytes] = ctx.enter_context(open(log_path, 'wb'))
else: # pragma: win32 no cover
output.write_line(f'Failed to write to log at {log_path}')
log = sys.stdout.buffer
_log_line = functools.partial(output.write_line, stream=log)
_log_line_b = functools.partial(output.write_line_b, stream=log)
def _log_and_exit(msg, exc, formatted):
error_msg = b''.join((
five.to_bytes(msg), b': ',
five.to_bytes(type(exc).__name__), b': ',
_to_bytes(exc), b'\n',
))
output.write(error_msg)
store = Store()
store.require_created()
log_path = os.path.join(store.directory, 'pre-commit.log')
output.write_line('Check the log at {}'.format(log_path))
with open(log_path, 'wb') as log:
output.write(error_msg, stream=log)
output.write_line(formatted, stream=log)
raise SystemExit(1)
_log_line('### version information')
_log_line()
_log_line('```')
_log_line(f'pre-commit version: {C.VERSION}')
_log_line(f'git --version: {git_version}')
_log_line('sys.version:')
for line in sys.version.splitlines():
_log_line(f' {line}')
_log_line(f'sys.executable: {sys.executable}')
_log_line(f'os.name: {os.name}')
_log_line(f'sys.platform: {sys.platform}')
_log_line('```')
_log_line()
_log_line('### error information')
_log_line()
_log_line('```')
_log_line_b(error_msg)
_log_line('```')
_log_line()
_log_line('```')
_log_line(formatted.rstrip())
_log_line('```')
raise SystemExit(ret_code)
@contextlib.contextmanager
def error_handler():
def error_handler() -> Generator[None]:
try:
yield
except FatalError as e:
_log_and_exit('An error has occurred', e, traceback.format_exc())
except Exception as e:
_log_and_exit(
'An unexpected error has occurred', e, traceback.format_exc(),
)
except (Exception, KeyboardInterrupt) as e:
if isinstance(e, FatalError):
msg, ret_code = 'An error has occurred', 1
elif isinstance(e, KeyboardInterrupt):
msg, ret_code = 'Interrupted (^C)', 130
else:
msg, ret_code = 'An unexpected error has occurred', 3
_log_and_exit(msg, ret_code, e, traceback.format_exc())

5
pre_commit/errors.py Normal file
View file

@ -0,0 +1,5 @@
from __future__ import annotations
class FatalError(RuntimeError):
pass

View file

@ -1,11 +1,13 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import errno
import sys
from collections.abc import Callable
from collections.abc import Generator
try: # pragma: no cover (windows)
if sys.platform == 'win32': # pragma: no cover (windows)
import msvcrt
# https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/locking
@ -15,15 +17,18 @@ try: # pragma: no cover (windows)
_region = 0xffff
@contextlib.contextmanager
def _locked(fileno, blocked_cb):
def _locked(
fileno: int,
blocked_cb: Callable[[], None],
) -> Generator[None]:
try:
msvcrt.locking(fileno, msvcrt.LK_NBLCK, _region)
except IOError:
except OSError:
blocked_cb()
while True:
try:
msvcrt.locking(fileno, msvcrt.LK_LOCK, _region)
except IOError as e:
except OSError as e:
# Locking violation. Returned when the _LK_LOCK or _LK_RLCK
# flag is specified and the file cannot be locked after 10
# attempts.
@ -41,14 +46,17 @@ try: # pragma: no cover (windows)
# "Regions should be locked only briefly and should be unlocked
# before closing a file or exiting the program."
msvcrt.locking(fileno, msvcrt.LK_UNLCK, _region)
except ImportError: # pragma: no cover (posix)
else: # pragma: win32 no cover
import fcntl
@contextlib.contextmanager
def _locked(fileno, blocked_cb):
def _locked(
fileno: int,
blocked_cb: Callable[[], None],
) -> Generator[None]:
try:
fcntl.flock(fileno, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
except OSError: # pragma: no cover (tests are single-threaded)
blocked_cb()
fcntl.flock(fileno, fcntl.LOCK_EX)
try:
@ -58,7 +66,10 @@ except ImportError: # pragma: no cover (posix)
@contextlib.contextmanager
def lock(path, blocked_cb):
def lock(
path: str,
blocked_cb: Callable[[], None],
) -> Generator[None]:
with open(path, 'a+') as f:
with _locked(f.fileno(), blocked_cb):
yield

View file

@ -1,15 +0,0 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import six
def to_text(s):
return s if isinstance(s, six.text_type) else s.decode('UTF-8')
def to_bytes(s):
return s if isinstance(s, bytes) else s.encode('UTF-8')
n = to_bytes if six.PY2 else to_text

View file

@ -1,18 +1,22 @@
from __future__ import unicode_literals
from __future__ import annotations
import logging
import os.path
import sys
from collections.abc import Mapping
from pre_commit.error_handler import FatalError
from pre_commit.errors import FatalError
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
logger = logging.getLogger(__name__)
# see #2046
NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false')
logger = logging.getLogger('pre_commit')
def zsplit(s):
def zsplit(s: str) -> list[str]:
s = s.strip('\0')
if s:
return s.split('\0')
@ -20,29 +24,76 @@ def zsplit(s):
return []
def get_root():
def no_git_env(_env: Mapping[str, str] | None = None) -> dict[str, str]:
# Too many bugs dealing with environment variables and GIT:
# https://github.com/pre-commit/pre-commit/issues/300
# In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
# pre-commit hooks
# In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
# while running pre-commit hooks in submodules.
# GIT_DIR: Causes git clone to clone wrong thing
# GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
_env = _env if _env is not None else os.environ
return {
k: v for k, v in _env.items()
if not k.startswith('GIT_') or
k.startswith(('GIT_CONFIG_KEY_', 'GIT_CONFIG_VALUE_')) or
k in {
'GIT_EXEC_PATH', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_SSL_CAINFO',
'GIT_SSL_NO_VERIFY', 'GIT_CONFIG_COUNT',
'GIT_HTTP_PROXY_AUTHMETHOD',
'GIT_ALLOW_PROTOCOL',
'GIT_ASKPASS',
}
}
def get_root() -> str:
# Git 2.25 introduced a change to "rev-parse --show-toplevel" that exposed
# underlying volumes for Windows drives mapped with SUBST. We use
# "rev-parse --show-cdup" to get the appropriate path, but must perform
# an extra check to see if we are in the .git directory.
try:
return cmd_output('git', 'rev-parse', '--show-toplevel')[1].strip()
root = os.path.abspath(
cmd_output('git', 'rev-parse', '--show-cdup')[1].strip(),
)
inside_git_dir = cmd_output(
'git', 'rev-parse', '--is-inside-git-dir',
)[1].strip()
except CalledProcessError:
raise FatalError(
'git failed. Is it installed, and are you in a Git repository '
'directory?',
)
if inside_git_dir != 'false':
raise FatalError(
'git toplevel unexpectedly empty! make sure you are not '
'inside the `.git` directory of your repository.',
)
return root
def get_git_dir(git_root):
return os.path.normpath(os.path.join(
git_root,
cmd_output('git', 'rev-parse', '--git-dir', cwd=git_root)[1].strip(),
))
def get_git_dir(git_root: str = '.') -> str:
opt = '--git-dir'
_, out, _ = cmd_output('git', 'rev-parse', opt, cwd=git_root)
git_dir = out.strip()
if git_dir != opt:
return os.path.normpath(os.path.join(git_root, git_dir))
else:
raise AssertionError('unreachable: no git dir')
def get_remote_url(git_root):
ret = cmd_output('git', 'config', 'remote.origin.url', cwd=git_root)[1]
return ret.strip()
def get_git_common_dir(git_root: str = '.') -> str:
opt = '--git-common-dir'
_, out, _ = cmd_output('git', 'rev-parse', opt, cwd=git_root)
git_common_dir = out.strip()
if git_common_dir != opt:
return os.path.normpath(os.path.join(git_root, git_common_dir))
else: # pragma: no cover (git < 2.5)
return get_git_dir(git_root)
def is_in_merge_conflict():
def is_in_merge_conflict() -> bool:
git_dir = get_git_dir('.')
return (
os.path.exists(os.path.join(git_dir, 'MERGE_MSG')) and
@ -50,75 +101,145 @@ def is_in_merge_conflict():
)
def parse_merge_msg_for_conflicts(merge_msg):
def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]:
# Conflicted files start with tabs
return [
line.lstrip(b'#').strip().decode('UTF-8')
line.lstrip(b'#').strip().decode()
for line in merge_msg.splitlines()
# '#\t' for git 2.4.1
if line.startswith((b'\t', b'#\t'))
]
def get_conflicted_files():
def get_conflicted_files() -> set[str]:
logger.info('Checking merge-conflict files only.')
# Need to get the conflicted files from the MERGE_MSG because they could
# have resolved the conflict by choosing one side or the other
merge_msg = open(os.path.join(get_git_dir('.'), 'MERGE_MSG'), 'rb').read()
with open(os.path.join(get_git_dir('.'), 'MERGE_MSG'), 'rb') as f:
merge_msg = f.read()
merge_conflict_filenames = parse_merge_msg_for_conflicts(merge_msg)
# This will get the rest of the changes made after the merge.
# If they resolved the merge conflict by choosing a mesh of both sides
# this will also include the conflicted files
tree_hash = cmd_output('git', 'write-tree')[1].strip()
merge_diff_filenames = zsplit(cmd_output(
'git', 'diff', '--name-only', '--no-ext-diff', '-z',
'-m', tree_hash, 'HEAD', 'MERGE_HEAD',
)[1])
merge_diff_filenames = zsplit(
cmd_output(
'git', 'diff', '--name-only', '--no-ext-diff', '-z',
'-m', tree_hash, 'HEAD', 'MERGE_HEAD', '--',
)[1],
)
return set(merge_conflict_filenames) | set(merge_diff_filenames)
def get_staged_files():
return zsplit(cmd_output(
'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
)[1])
def get_staged_files(cwd: str | None = None) -> list[str]:
return zsplit(
cmd_output(
'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
cwd=cwd,
)[1],
)
def get_all_files():
def intent_to_add_files() -> list[str]:
_, stdout, _ = cmd_output(
'git', 'diff', '--no-ext-diff', '--ignore-submodules',
'--diff-filter=A', '--name-only', '-z',
)
return zsplit(stdout)
def get_all_files() -> list[str]:
return zsplit(cmd_output('git', 'ls-files', '-z')[1])
def get_changed_files(new, old):
return zsplit(cmd_output(
'git', 'diff', '--name-only', '--no-ext-diff', '-z',
'{}...{}'.format(old, new),
)[1])
def get_changed_files(old: str, new: str) -> list[str]:
diff_cmd = ('git', 'diff', '--name-only', '--no-ext-diff', '-z')
try:
_, out, _ = cmd_output(*diff_cmd, f'{old}...{new}')
except CalledProcessError: # pragma: no cover (new git)
# on newer git where old and new do not have a merge base git fails
# so we try a full diff (this is what old git did for us!)
_, out, _ = cmd_output(*diff_cmd, f'{old}..{new}')
return zsplit(out)
def head_rev(remote):
def head_rev(remote: str) -> str:
_, out, _ = cmd_output('git', 'ls-remote', '--exit-code', remote, 'HEAD')
return out.split()[0]
def check_for_cygwin_mismatch():
def has_diff(*args: str, repo: str = '.') -> bool:
cmd = ('git', 'diff', '--quiet', '--no-ext-diff', *args)
return cmd_output_b(*cmd, cwd=repo, check=False)[0] == 1
def has_core_hookpaths_set() -> bool:
_, out, _ = cmd_output_b('git', 'config', 'core.hooksPath', check=False)
return bool(out.strip())
def init_repo(path: str, remote: str) -> None:
if os.path.isdir(remote):
remote = os.path.abspath(remote)
git = ('git', *NO_FS_MONITOR)
env = no_git_env()
# avoid the user's template so that hooks do not recurse
cmd_output_b(*git, 'init', '--template=', path, env=env)
cmd_output_b(*git, 'remote', 'add', 'origin', remote, cwd=path, env=env)
def commit(repo: str = '.') -> None:
env = no_git_env()
name, email = 'pre-commit', 'asottile+pre-commit@umich.edu'
env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = name
env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = email
cmd = ('git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
cmd_output_b(*cmd, cwd=repo, env=env)
def git_path(name: str, repo: str = '.') -> str:
_, out, _ = cmd_output('git', 'rev-parse', '--git-path', name, cwd=repo)
return os.path.join(repo, out.strip())
def check_for_cygwin_mismatch() -> None:
"""See https://github.com/pre-commit/pre-commit/issues/354"""
if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows)
is_cygwin_python = sys.platform == 'cygwin'
toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1]
try:
toplevel = get_root()
except FatalError: # skip the check if we're not in a git repo
return
is_cygwin_git = toplevel.startswith('/')
if is_cygwin_python ^ is_cygwin_git:
exe_type = {True: '(cygwin)', False: '(windows)'}
logger.warn(
'pre-commit has detected a mix of cygwin python / git\n'
'This combination is not supported, it is likely you will '
'receive an error later in the program.\n'
'Make sure to use cygwin git+python while using cygwin\n'
'These can be installed through the cygwin installer.\n'
' - python {}\n'
' - git {}\n'.format(
exe_type[is_cygwin_python], exe_type[is_cygwin_git],
),
logger.warning(
f'pre-commit has detected a mix of cygwin python / git\n'
f'This combination is not supported, it is likely you will '
f'receive an error later in the program.\n'
f'Make sure to use cygwin git+python while using cygwin\n'
f'These can be installed through the cygwin installer.\n'
f' - python {exe_type[is_cygwin_python]}\n'
f' - git {exe_type[is_cygwin_git]}\n',
)
def get_best_candidate_tag(rev: str, git_repo: str) -> str:
"""Get the best tag candidate.
Multiple tags can exist on a SHA. Sometimes a moving tag is attached
to a version tag. Try to pick the tag that looks like a version.
"""
tags = cmd_output(
'git', *NO_FS_MONITOR, 'tag', '--points-at', rev, cwd=git_repo,
)[1].splitlines()
for tag in tags:
if '.' in tag:
return tag
return rev

60
pre_commit/hook.py Normal file
View file

@ -0,0 +1,60 @@
from __future__ import annotations
import logging
from collections.abc import Sequence
from typing import Any
from typing import NamedTuple
from pre_commit.prefix import Prefix
logger = logging.getLogger('pre_commit')
class Hook(NamedTuple):
src: str
prefix: Prefix
id: str
name: str
entry: str
language: str
alias: str
files: str
exclude: str
types: Sequence[str]
types_or: Sequence[str]
exclude_types: Sequence[str]
additional_dependencies: Sequence[str]
args: Sequence[str]
always_run: bool
fail_fast: bool
pass_filenames: bool
description: str
language_version: str
log_file: str
minimum_pre_commit_version: str
require_serial: bool
stages: Sequence[str]
verbose: bool
@property
def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
return (
self.prefix,
self.language,
self.language_version,
tuple(self.additional_dependencies),
)
@classmethod
def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# TODO: have cfgv do this (?)
extra_keys = set(dct) - _KEYS
if extra_keys:
logger.warning(
f'Unexpected key(s) present on {src} => {dct["id"]}: '
f'{", ".join(sorted(extra_keys))}',
)
return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
_KEYS = frozenset(set(Hook._fields) - {'src', 'prefix'})

196
pre_commit/lang_base.py Normal file
View file

@ -0,0 +1,196 @@
from __future__ import annotations
import contextlib
import os
import random
import re
import shlex
import sys
from collections.abc import Generator
from collections.abc import Sequence
from typing import Any
from typing import ContextManager
from typing import NoReturn
from typing import Protocol
import pre_commit.constants as C
from pre_commit import parse_shebang
from pre_commit import xargs
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output_b
FIXED_RANDOM_SEED = 1542676187
SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
class Language(Protocol):
# Use `None` for no installation / environment
@property
def ENVIRONMENT_DIR(self) -> str | None: ...
# return a value to replace `'default` for `language_version`
def get_default_version(self) -> str: ...
# return whether the environment is healthy (or should be rebuilt)
def health_check(self, prefix: Prefix, version: str) -> str | None: ...
# install a repository for the given language and language_version
def install_environment(
self,
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
...
# modify the environment for hook execution
def in_env(self, prefix: Prefix, version: str) -> ContextManager[None]: ...
# execute a hook and return the exit code and output
def run_hook(
self,
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
...
def exe_exists(exe: str) -> bool:
found = parse_shebang.find_executable(exe)
if found is None: # exe exists
return False
homedir = os.path.expanduser('~')
try:
common: str | None = os.path.commonpath((found, homedir))
except ValueError: # on windows, different drives raises ValueError
common = None
return (
# it is not in a /shims/ directory
not SHIMS_RE.search(found) and
(
# the homedir is / (docker, service user, etc.)
os.path.dirname(homedir) == homedir or
# the exe is not contained in the home directory
common != homedir
)
)
def setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs)
def environment_dir(prefix: Prefix, d: str, language_version: str) -> str:
return prefix.path(f'{d}-{language_version}')
def assert_version_default(binary: str, version: str) -> None:
if version != C.DEFAULT:
raise AssertionError(
f'for now, pre-commit requires system-installed {binary} -- '
f'you selected `language_version: {version}`',
)
def assert_no_additional_deps(
lang: str,
additional_deps: Sequence[str],
) -> None:
if additional_deps:
raise AssertionError(
f'for now, pre-commit does not support '
f'additional_dependencies for {lang} -- '
f'you selected `additional_dependencies: {additional_deps}`',
)
def basic_get_default_version() -> str:
return C.DEFAULT
def basic_health_check(prefix: Prefix, language_version: str) -> str | None:
return None
def no_install(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> NoReturn:
raise AssertionError('This language is not installable')
@contextlib.contextmanager
def no_env(prefix: Prefix, version: str) -> Generator[None]:
yield
def target_concurrency() -> int:
if 'PRE_COMMIT_NO_CONCURRENCY' in os.environ:
return 1
else:
# Travis appears to have a bunch of CPUs, but we can't use them all.
if 'TRAVIS' in os.environ:
return 2
else:
return xargs.cpu_count()
def _shuffled(seq: Sequence[str]) -> list[str]:
"""Deterministically shuffle"""
fixed_random = random.Random()
fixed_random.seed(FIXED_RANDOM_SEED, version=1)
seq = list(seq)
fixed_random.shuffle(seq)
return seq
def run_xargs(
cmd: tuple[str, ...],
file_args: Sequence[str],
*,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
if require_serial:
jobs = 1
else:
# Shuffle the files so that they more evenly fill out the xargs
# partitions, but do it deterministically in case a hook cares about
# ordering.
file_args = _shuffled(file_args)
jobs = target_concurrency()
return xargs.xargs(cmd, file_args, target_concurrency=jobs, color=color)
def hook_cmd(entry: str, args: Sequence[str]) -> tuple[str, ...]:
cmd = shlex.split(entry)
if cmd[:2] == ['pre-commit', 'hazmat']:
cmd = [sys.executable, '-m', 'pre_commit.commands.hazmat', *cmd[2:]]
return (*cmd, *args)
def basic_run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
return run_xargs(
hook_cmd(entry, args),
file_args,
require_serial=require_serial,
color=color,
)

View file

@ -1,69 +0,0 @@
from __future__ import unicode_literals
from pre_commit.languages import docker
from pre_commit.languages import docker_image
from pre_commit.languages import golang
from pre_commit.languages import node
from pre_commit.languages import pcre
from pre_commit.languages import pygrep
from pre_commit.languages import python
from pre_commit.languages import python_venv
from pre_commit.languages import ruby
from pre_commit.languages import rust
from pre_commit.languages import script
from pre_commit.languages import swift
from pre_commit.languages import system
# A language implements the following constant and functions in its module:
#
# # Use None for no environment
# ENVIRONMENT_DIR = 'foo_env'
#
# def get_default_version():
# """Return a value to replace the 'default' value for language_version.
#
# return 'default' if there is no better option.
# """
#
# def healthy(prefix, language_version):
# """Return whether or not the environment is considered functional."""
#
# def install_environment(prefix, version, additional_dependencies):
# """Installs a repository in the given repository. Note that the current
# working directory will already be inside the repository.
#
# Args:
# prefix - `Prefix` bound to the repository.
# version - A version specified in the hook configuration or
# 'default'.
# """
#
# def run_hook(prefix, hook, file_args):
# """Runs a hook and returns the returncode and output of running that
# hook.
#
# Args:
# prefix - `Prefix` bound to the repository.
# hook - Hook dictionary
# file_args - The files to be run
#
# Returns:
# (returncode, stdout, stderr)
# """
languages = {
'docker': docker,
'docker_image': docker_image,
'golang': golang,
'node': node,
'pcre': pcre,
'pygrep': pygrep,
'python': python,
'python_venv': python_venv,
'ruby': ruby,
'rust': rust,
'script': script,
'swift': swift,
'system': system,
}
all_languages = sorted(languages)

View file

@ -0,0 +1,77 @@
from __future__ import annotations
import contextlib
import os
import sys
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import SubstitutionT
from pre_commit.envcontext import UNSET
from pre_commit.envcontext import Var
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output_b
ENVIRONMENT_DIR = 'conda'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(env: str) -> PatchesT:
# On non-windows systems executable live in $CONDA_PREFIX/bin, on Windows
# they can be in $CONDA_PREFIX/bin, $CONDA_PREFIX/Library/bin,
# $CONDA_PREFIX/Scripts and $CONDA_PREFIX. Whereas the latter only
# seems to be used for python.exe.
path: SubstitutionT = (os.path.join(env, 'bin'), os.pathsep, Var('PATH'))
if sys.platform == 'win32': # pragma: win32 cover
path = (env, os.pathsep, *path)
path = (os.path.join(env, 'Scripts'), os.pathsep, *path)
path = (os.path.join(env, 'Library', 'bin'), os.pathsep, *path)
return (
('PYTHONHOME', UNSET),
('VIRTUAL_ENV', UNSET),
('CONDA_PREFIX', env),
('PATH', path),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def _conda_exe() -> str:
if os.environ.get('PRE_COMMIT_USE_MICROMAMBA'):
return 'micromamba'
elif os.environ.get('PRE_COMMIT_USE_MAMBA'):
return 'mamba'
else:
return 'conda'
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('conda', version)
conda_exe = _conda_exe()
env_dir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
cmd_output_b(
conda_exe, 'env', 'create', '-p', env_dir, '--file',
'environment.yml', cwd=prefix.prefix_dir,
)
if additional_dependencies:
cmd_output_b(
conda_exe, 'install', '-p', env_dir, *additional_dependencies,
cwd=prefix.prefix_dir,
)

View file

@ -0,0 +1,76 @@
from __future__ import annotations
import contextlib
import os.path
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.errors import FatalError
from pre_commit.parse_shebang import find_executable
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = 'coursier'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('coursier', version)
# Support both possible executable names (either "cs" or "coursier")
cs = find_executable('cs') or find_executable('coursier')
if cs is None:
raise AssertionError(
'pre-commit requires system-installed "cs" or "coursier" '
'executables in the application search path',
)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
def _install(*opts: str) -> None:
assert cs is not None
lang_base.setup_cmd(prefix, (cs, 'fetch', *opts))
lang_base.setup_cmd(prefix, (cs, 'install', '--dir', envdir, *opts))
with in_env(prefix, version):
channel = prefix.path('.pre-commit-channel')
if os.path.isdir(channel):
for app_descriptor in os.listdir(channel):
_, app_file = os.path.split(app_descriptor)
app, _ = os.path.splitext(app_file)
_install(
'--default-channels=false',
'--channel', channel,
app,
)
elif not additional_dependencies:
raise FatalError(
'expected .pre-commit-channel dir or additional_dependencies',
)
if additional_dependencies:
_install(*additional_dependencies)
def get_env_patch(target_dir: str) -> PatchesT:
return (
('PATH', (target_dir, os.pathsep, Var('PATH'))),
('COURSIER_CACHE', os.path.join(target_dir, '.cs-cache')),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield

View file

@ -0,0 +1,97 @@
from __future__ import annotations
import contextlib
import os.path
import shutil
import tempfile
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.prefix import Prefix
from pre_commit.util import win_exe
from pre_commit.yaml import yaml_load
ENVIRONMENT_DIR = 'dartenv'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(venv: str) -> PatchesT:
return (
('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('dart', version)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
bin_dir = os.path.join(envdir, 'bin')
def _install_dir(prefix_p: Prefix, pub_cache: str) -> None:
dart_env = {**os.environ, 'PUB_CACHE': pub_cache}
with open(prefix_p.path('pubspec.yaml')) as f:
pubspec_contents = yaml_load(f)
lang_base.setup_cmd(prefix_p, ('dart', 'pub', 'get'), env=dart_env)
for executable in pubspec_contents['executables']:
lang_base.setup_cmd(
prefix_p,
(
'dart', 'compile', 'exe',
'--output', os.path.join(bin_dir, win_exe(executable)),
prefix_p.path('bin', f'{executable}.dart'),
),
env=dart_env,
)
os.makedirs(bin_dir)
with tempfile.TemporaryDirectory() as tmp:
_install_dir(prefix, tmp)
for dep_s in additional_dependencies:
with tempfile.TemporaryDirectory() as dep_tmp:
dep, _, version = dep_s.partition(':')
if version:
dep_cmd: tuple[str, ...] = (dep, '--version', version)
else:
dep_cmd = (dep,)
lang_base.setup_cmd(
prefix,
('dart', 'pub', 'cache', 'add', *dep_cmd),
env={**os.environ, 'PUB_CACHE': dep_tmp},
)
# try and find the 'pubspec.yaml' that just got added
for root, _, filenames in os.walk(dep_tmp):
if 'pubspec.yaml' in filenames:
with tempfile.TemporaryDirectory() as copied:
pkg = os.path.join(copied, 'pkg')
shutil.copytree(root, pkg)
_install_dir(Prefix(pkg), dep_tmp)
break
else:
raise AssertionError(
f'could not find pubspec.yaml for {dep_s}',
)

View file

@ -1,49 +1,86 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import hashlib
import json
import os
import re
from collections.abc import Sequence
from pre_commit import five
from pre_commit.languages import helpers
from pre_commit import lang_base
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from pre_commit.util import clean_path_on_failure
from pre_commit.util import cmd_output
from pre_commit.xargs import xargs
from pre_commit.util import cmd_output_b
ENVIRONMENT_DIR = 'docker'
PRE_COMMIT_LABEL = 'PRE_COMMIT'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
in_env = lang_base.no_env # no special environment for docker
_HOSTNAME_MOUNT_RE = re.compile(
rb"""
/containers
(?:/overlay-containers)?
/([a-z0-9]{64})
(?:/userdata)?
/hostname
""",
re.VERBOSE,
)
def md5(s): # pragma: windows no cover
return hashlib.md5(five.to_bytes(s)).hexdigest()
def _get_container_id() -> str | None:
with contextlib.suppress(FileNotFoundError):
with open('/proc/1/mountinfo', 'rb') as f:
for line in f:
m = _HOSTNAME_MOUNT_RE.search(line)
if m:
return m[1].decode()
return None
def docker_tag(prefix): # pragma: windows no cover
md5sum = md5(os.path.basename(prefix.prefix_dir)).lower()
return 'pre-commit-{}'.format(md5sum)
def _get_docker_path(path: str) -> str:
container_id = _get_container_id()
if container_id is None:
return path
def docker_is_running(): # pragma: windows no cover
try:
return cmd_output('docker', 'ps')[0] == 0
_, out, _ = cmd_output_b('docker', 'inspect', container_id)
except CalledProcessError:
return False
# self-container was not visible from here (perhaps docker-in-docker)
return path
container, = json.loads(out)
for mount in container['Mounts']:
src_path = mount['Source']
to_path = mount['Destination']
if os.path.commonpath((path, to_path)) == to_path:
# So there is something in common,
# and we can proceed remapping it
return path.replace(to_path, src_path)
# we're in Docker, but the path is not mounted, cannot really do anything,
# so fall back to original path
return path
def assert_docker_available(): # pragma: windows no cover
assert docker_is_running(), (
'Docker is either not running or not configured in this environment'
)
def md5(s: str) -> str: # pragma: win32 no cover
return hashlib.md5(s.encode()).hexdigest()
def build_docker_image(prefix, **kwargs): # pragma: windows no cover
pull = kwargs.pop('pull')
assert not kwargs, kwargs
cmd = (
def docker_tag(prefix: Prefix) -> str: # pragma: win32 no cover
md5sum = md5(os.path.basename(prefix.prefix_dir)).lower()
return f'pre-commit-{md5sum}'
def build_docker_image(
prefix: Prefix,
*,
pull: bool,
) -> None: # pragma: win32 no cover
cmd: tuple[str, ...] = (
'docker', 'build',
'--tag', docker_tag(prefix),
'--label', PRE_COMMIT_LABEL,
@ -52,49 +89,93 @@ def build_docker_image(prefix, **kwargs): # pragma: windows no cover
cmd += ('--pull',)
# This must come last for old versions of docker. See #477
cmd += ('.',)
helpers.run_setup_cmd(prefix, cmd)
lang_base.setup_cmd(prefix, cmd)
def install_environment(
prefix, version, additional_dependencies,
): # pragma: windows no cover
helpers.assert_version_default('docker', version)
helpers.assert_no_additional_deps('docker', additional_dependencies)
assert_docker_available()
prefix: Prefix, version: str, additional_dependencies: Sequence[str],
) -> None: # pragma: win32 no cover
lang_base.assert_version_default('docker', version)
lang_base.assert_no_additional_deps('docker', additional_dependencies)
directory = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
directory = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
# Docker doesn't really have relevant disk environment, but pre-commit
# still needs to cleanup it's state files on failure
with clean_path_on_failure(directory):
build_docker_image(prefix, pull=True)
os.mkdir(directory)
# still needs to cleanup its state files on failure
build_docker_image(prefix, pull=True)
os.mkdir(directory)
def docker_cmd():
@functools.lru_cache(maxsize=1)
def _is_rootless() -> bool: # pragma: win32 no cover
retcode, out, _ = cmd_output_b(
'docker', 'system', 'info', '--format', '{{ json . }}',
)
if retcode != 0:
return False
info = json.loads(out)
try:
return (
# docker:
# https://docs.docker.com/reference/api/engine/version/v1.48/#tag/System/operation/SystemInfo
'name=rootless' in (info.get('SecurityOptions') or ()) or
# podman:
# https://docs.podman.io/en/latest/_static/api.html?version=v5.4#tag/system/operation/SystemInfoLibpod
info['host']['security']['rootless']
)
except KeyError:
return False
def get_docker_user() -> tuple[str, ...]: # pragma: win32 no cover
if _is_rootless():
return ()
try:
return ('-u', f'{os.getuid()}:{os.getgid()}')
except AttributeError:
return ()
def get_docker_tty(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover # noqa: E501
return (('--tty',) if color else ())
def docker_cmd(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover
return (
'docker', 'run',
'--rm',
'-u', '{}:{}'.format(os.getuid(), os.getgid()),
*get_docker_tty(color=color),
*get_docker_user(),
# https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
# The `Z` option tells Docker to label the content with a private
# unshared label. Only the current container can use a private volume.
'-v', '{}:/src:rw,Z'.format(os.getcwd()),
'-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',
'--workdir', '/src',
)
def run_hook(prefix, hook, file_args): # pragma: windows no cover
assert_docker_available()
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]: # pragma: win32 no cover
# Rebuild the docker image in case it has gone missing, as many people do
# automated cleanup of docker images.
build_docker_image(prefix, pull=False)
hook_cmd = helpers.to_cmd(hook)
entry_exe, cmd_rest = hook_cmd[0], hook_cmd[1:]
entry_exe, *cmd_rest = lang_base.hook_cmd(entry, args)
entry_tag = ('--entrypoint', entry_exe, docker_tag(prefix))
cmd = docker_cmd() + entry_tag + cmd_rest
return xargs(cmd, file_args)
return lang_base.run_xargs(
(*docker_cmd(color=color), *entry_tag, *cmd_rest),
file_args,
require_serial=require_serial,
color=color,
)

View file

@ -1,19 +1,32 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
from pre_commit.languages import helpers
from pre_commit.languages.docker import assert_docker_available
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.languages.docker import docker_cmd
from pre_commit.xargs import xargs
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
install_environment = lang_base.no_install
in_env = lang_base.no_env
def run_hook(prefix, hook, file_args): # pragma: windows no cover
assert_docker_available()
cmd = docker_cmd() + helpers.to_cmd(hook)
return xargs(cmd, file_args)
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]: # pragma: win32 no cover
cmd = docker_cmd(color=color) + lang_base.hook_cmd(entry, args)
return lang_base.run_xargs(
cmd,
file_args,
require_serial=require_serial,
color=color,
)

View file

@ -0,0 +1,111 @@
from __future__ import annotations
import contextlib
import os.path
import re
import tempfile
import xml.etree.ElementTree
import zipfile
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = 'dotnetenv'
BIN_DIR = 'bin'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(venv: str) -> PatchesT:
return (
('PATH', (os.path.join(venv, BIN_DIR), os.pathsep, Var('PATH'))),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
@contextlib.contextmanager
def _nuget_config_no_sources() -> Generator[str]:
with tempfile.TemporaryDirectory() as tmpdir:
nuget_config = os.path.join(tmpdir, 'nuget.config')
with open(nuget_config, 'w') as f:
f.write(
'<?xml version="1.0" encoding="utf-8"?>'
'<configuration>'
' <packageSources>'
' <clear />'
' </packageSources>'
'</configuration>',
)
yield nuget_config
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('dotnet', version)
lang_base.assert_no_additional_deps('dotnet', additional_dependencies)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
build_dir = prefix.path('pre-commit-build')
# Build & pack nupkg file
lang_base.setup_cmd(
prefix,
(
'dotnet', 'pack',
'--configuration', 'Release',
'--property', f'PackageOutputPath={build_dir}',
),
)
nupkg_dir = prefix.path(build_dir)
nupkgs = [x for x in os.listdir(nupkg_dir) if x.endswith('.nupkg')]
if not nupkgs:
raise AssertionError('could not find any build outputs to install')
for nupkg in nupkgs:
with zipfile.ZipFile(os.path.join(nupkg_dir, nupkg)) as f:
nuspec, = (x for x in f.namelist() if x.endswith('.nuspec'))
with f.open(nuspec) as spec:
tree = xml.etree.ElementTree.parse(spec)
namespace = re.match(r'{.*}', tree.getroot().tag)
if not namespace:
raise AssertionError('could not parse namespace from nuspec')
tool_id_element = tree.find(f'.//{namespace[0]}id')
if tool_id_element is None:
raise AssertionError('expected to find an "id" element')
tool_id = tool_id_element.text
if not tool_id:
raise AssertionError('"id" element missing tool name')
# Install to bin dir
with _nuget_config_no_sources() as nuget_config:
lang_base.setup_cmd(
prefix,
(
'dotnet', 'tool', 'install',
'--configfile', nuget_config,
'--tool-path', os.path.join(envdir, BIN_DIR),
'--add-source', build_dir,
tool_id,
),
)

View file

@ -0,0 +1,27 @@
from __future__ import annotations
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = None
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
install_environment = lang_base.no_install
in_env = lang_base.no_env
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
out = f'{entry}\n\n'.encode()
out += b'\n'.join(f.encode() for f in file_args) + b'\n'
return 1, out

View file

@ -1,84 +1,161 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import json
import os.path
import platform
import shutil
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
import zipfile
from collections.abc import Generator
from collections.abc import Sequence
from typing import ContextManager
from typing import IO
from typing import Protocol
from pre_commit import git
import pre_commit.constants as C
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.util import clean_path_on_failure
from pre_commit.git import no_git_env
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
from pre_commit.util import rmtree
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = 'golangenv'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
_ARCH_ALIASES = {
'x86_64': 'amd64',
'i386': '386',
'aarch64': 'arm64',
'armv8': 'arm64',
'armv7l': 'armv6l',
}
_ARCH = platform.machine().lower()
_ARCH = _ARCH_ALIASES.get(_ARCH, _ARCH)
def get_env_patch(venv):
class ExtractAll(Protocol):
def extractall(self, path: str) -> None: ...
if sys.platform == 'win32': # pragma: win32 cover
_EXT = 'zip'
def _open_archive(bio: IO[bytes]) -> ContextManager[ExtractAll]:
return zipfile.ZipFile(bio)
else: # pragma: win32 no cover
_EXT = 'tar.gz'
def _open_archive(bio: IO[bytes]) -> ContextManager[ExtractAll]:
return tarfile.open(fileobj=bio)
@functools.lru_cache(maxsize=1)
def get_default_version() -> str:
if lang_base.exe_exists('go'):
return 'system'
else:
return C.DEFAULT
def get_env_patch(venv: str, version: str) -> PatchesT:
if version == 'system':
return (
('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))),
)
return (
('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))),
('GOROOT', os.path.join(venv, '.go')),
('GOTOOLCHAIN', 'local'),
(
'PATH', (
os.path.join(venv, 'bin'), os.pathsep,
os.path.join(venv, '.go', 'bin'), os.pathsep, Var('PATH'),
),
),
)
@functools.lru_cache
def _infer_go_version(version: str) -> str:
if version != C.DEFAULT:
return version
resp = urllib.request.urlopen('https://go.dev/dl/?mode=json')
return json.load(resp)[0]['version'].removeprefix('go')
def _get_url(version: str) -> str:
os_name = platform.system().lower()
version = _infer_go_version(version)
return f'https://dl.google.com/go/go{version}.{os_name}-{_ARCH}.{_EXT}'
def _install_go(version: str, dest: str) -> None:
try:
resp = urllib.request.urlopen(_get_url(version))
except urllib.error.HTTPError as e: # pragma: no cover
if e.code == 404:
raise ValueError(
f'Could not find a version matching your system requirements '
f'(os={platform.system().lower()}; arch={_ARCH})',
) from e
else:
raise
else:
with tempfile.TemporaryFile() as f:
shutil.copyfileobj(resp, f)
f.seek(0)
with _open_archive(f) as archive:
archive.extractall(dest)
shutil.move(os.path.join(dest, 'go'), os.path.join(dest, '.go'))
@contextlib.contextmanager
def in_env(prefix):
envdir = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
with envcontext(get_env_patch(envdir)):
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir, version)):
yield
def guess_go_dir(remote_url):
if remote_url.endswith('.git'):
remote_url = remote_url[:-1 * len('.git')]
looks_like_url = (
not remote_url.startswith('file://') and
('//' in remote_url or '@' in remote_url)
)
remote_url = remote_url.replace(':', '/')
if looks_like_url:
_, _, remote_url = remote_url.rpartition('//')
_, _, remote_url = remote_url.rpartition('@')
return remote_url
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
env_dir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
if version != 'system':
_install_go(version, env_dir)
if sys.platform == 'cygwin': # pragma: no cover
gopath = cmd_output('cygpath', '-w', env_dir)[1].strip()
else:
return 'unknown_src_dir'
gopath = env_dir
env = no_git_env(dict(os.environ, GOPATH=gopath))
env.pop('GOBIN', None)
if version != 'system':
env['GOTOOLCHAIN'] = 'local'
env['GOROOT'] = os.path.join(env_dir, '.go')
env['PATH'] = os.pathsep.join((
os.path.join(env_dir, '.go', 'bin'), os.environ['PATH'],
))
def install_environment(prefix, version, additional_dependencies):
helpers.assert_version_default('golang', version)
directory = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
lang_base.setup_cmd(prefix, ('go', 'install', './...'), env=env)
for dependency in additional_dependencies:
lang_base.setup_cmd(prefix, ('go', 'install', dependency), env=env)
with clean_path_on_failure(directory):
remote = git.get_remote_url(prefix.prefix_dir)
repo_src_dir = os.path.join(directory, 'src', guess_go_dir(remote))
# Clone into the goenv we'll create
helpers.run_setup_cmd(prefix, ('git', 'clone', '.', repo_src_dir))
if sys.platform == 'cygwin': # pragma: no cover
_, gopath, _ = cmd_output('cygpath', '-w', directory)
gopath = gopath.strip()
else:
gopath = directory
env = dict(os.environ, GOPATH=gopath)
cmd_output('go', 'get', './...', cwd=repo_src_dir, env=env)
for dependency in additional_dependencies:
cmd_output('go', 'get', dependency, cwd=repo_src_dir, env=env)
# Same some disk space, we don't need these after installation
rmtree(prefix.path(directory, 'src'))
pkgdir = prefix.path(directory, 'pkg')
if os.path.exists(pkgdir): # pragma: no cover (go<1.10)
rmtree(pkgdir)
def run_hook(prefix, hook, file_args):
with in_env(prefix):
return xargs(helpers.to_cmd(hook), file_args)
# save some disk space -- we don't need this after installation
pkgdir = os.path.join(env_dir, 'pkg')
if os.path.exists(pkgdir): # pragma: no branch (always true on windows?)
rmtree(pkgdir)

View file

@ -0,0 +1,56 @@
from __future__ import annotations
import contextlib
import os.path
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.errors import FatalError
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = 'hs_env'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(target_dir: str) -> PatchesT:
bin_path = os.path.join(target_dir, 'bin')
return (('PATH', (bin_path, os.pathsep, Var('PATH'))),)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('haskell', version)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
pkgs = [*prefix.star('.cabal'), *additional_dependencies]
if not pkgs:
raise FatalError('Expected .cabal files or additional_dependencies')
bindir = os.path.join(envdir, 'bin')
os.makedirs(bindir, exist_ok=True)
lang_base.setup_cmd(prefix, ('cabal', 'update'))
lang_base.setup_cmd(
prefix,
(
'cabal', 'install',
'--install-method', 'copy',
'--installdir', bindir,
*pkgs,
),
)

View file

@ -1,47 +0,0 @@
from __future__ import unicode_literals
import shlex
from pre_commit.util import cmd_output
def run_setup_cmd(prefix, cmd):
cmd_output(*cmd, cwd=prefix.prefix_dir, encoding=None)
def environment_dir(ENVIRONMENT_DIR, language_version):
if ENVIRONMENT_DIR is None:
return None
else:
return '{}-{}'.format(ENVIRONMENT_DIR, language_version)
def to_cmd(hook):
return tuple(shlex.split(hook['entry'])) + tuple(hook['args'])
def assert_version_default(binary, version):
if version != 'default':
raise AssertionError(
'For now, pre-commit requires system-installed {}'.format(binary),
)
def assert_no_additional_deps(lang, additional_deps):
if additional_deps:
raise AssertionError(
'For now, pre-commit does not support '
'additional_dependencies for {}'.format(lang),
)
def basic_get_default_version():
return 'default'
def basic_healthy(prefix, language_version):
return True
def no_install(prefix, version, additional_dependencies):
raise AssertionError('This type is not installable')

View file

@ -0,0 +1,133 @@
from __future__ import annotations
import contextlib
import os
import shutil
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import UNSET
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output_b
ENVIRONMENT_DIR = 'juliaenv'
health_check = lang_base.basic_health_check
get_default_version = lang_base.basic_get_default_version
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
# `entry` is a (hook-repo relative) file followed by (optional) args, e.g.
# `bin/id.jl` or `bin/hook.jl --arg1 --arg2` so we
# 1) shell parse it and join with args with hook_cmd
# 2) prepend the hooks prefix path to the first argument (the file), unless
# it is a local script
# 3) prepend `julia` as the interpreter
cmd = lang_base.hook_cmd(entry, args)
script = cmd[0] if is_local else prefix.path(cmd[0])
cmd = ('julia', '--startup-file=no', script, *cmd[1:])
return lang_base.run_xargs(
cmd,
file_args,
require_serial=require_serial,
color=color,
)
def get_env_patch(target_dir: str, version: str) -> PatchesT:
return (
('JULIA_LOAD_PATH', target_dir),
# May be set, remove it to not interfer with LOAD_PATH
('JULIA_PROJECT', UNSET),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir, version)):
yield
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with in_env(prefix, version):
# TODO: Support language_version with juliaup similar to rust via
# rustup
# if version != 'system':
# ...
# Copy Project.toml to hook env if it exist
os.makedirs(envdir, exist_ok=True)
project_names = ('JuliaProject.toml', 'Project.toml')
project_found = False
for project_name in project_names:
project_file = prefix.path(project_name)
if not os.path.isfile(project_file):
continue
shutil.copy(project_file, envdir)
project_found = True
break
# If no project file was found we create an empty one so that the
# package manager doesn't error
if not project_found:
open(os.path.join(envdir, 'Project.toml'), 'a').close()
# Copy Manifest.toml to hook env if it exists
manifest_names = ('JuliaManifest.toml', 'Manifest.toml')
for manifest_name in manifest_names:
manifest_file = prefix.path(manifest_name)
if not os.path.isfile(manifest_file):
continue
shutil.copy(manifest_file, envdir)
break
# Julia code to instantiate the hook environment
julia_code = """
@assert length(ARGS) > 0
hook_env = ARGS[1]
deps = join(ARGS[2:end], " ")
# We prepend @stdlib here so that we can load the package manager even
# though `get_env_patch` limits `JULIA_LOAD_PATH` to just the hook env.
pushfirst!(LOAD_PATH, "@stdlib")
using Pkg
popfirst!(LOAD_PATH)
# Instantiate the environment shipped with the hook repo. If we have
# additional dependencies we disable precompilation in this step to
# avoid double work.
precompile = isempty(deps) ? "1" : "0"
withenv("JULIA_PKG_PRECOMPILE_AUTO" => precompile) do
Pkg.instantiate()
end
# Add additional dependencies (with precompilation)
if !isempty(deps)
withenv("JULIA_PKG_PRECOMPILE_AUTO" => "1") do
Pkg.REPLMode.pkgstr("add " * deps)
end
end
"""
cmd_output_b(
'julia', '--startup-file=no', '-e', julia_code, '--', envdir,
*additional_dependencies,
cwd=prefix.prefix_dir,
)

View file

@ -0,0 +1,75 @@
from __future__ import annotations
import contextlib
import os
import sys
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
ENVIRONMENT_DIR = 'lua_env'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def _get_lua_version() -> str: # pragma: win32 no cover
"""Get the Lua version used in file paths."""
_, stdout, _ = cmd_output('luarocks', 'config', '--lua-ver')
return stdout.strip()
def get_env_patch(d: str) -> PatchesT: # pragma: win32 no cover
version = _get_lua_version()
so_ext = 'dll' if sys.platform == 'win32' else 'so'
return (
('PATH', (os.path.join(d, 'bin'), os.pathsep, Var('PATH'))),
(
'LUA_PATH', (
os.path.join(d, 'share', 'lua', version, '?.lua;'),
os.path.join(d, 'share', 'lua', version, '?', 'init.lua;;'),
),
),
(
'LUA_CPATH',
(os.path.join(d, 'lib', 'lua', version, f'?.{so_ext};;'),),
),
)
@contextlib.contextmanager # pragma: win32 no cover
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None: # pragma: win32 no cover
lang_base.assert_version_default('lua', version)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with in_env(prefix, version):
# luarocks doesn't bootstrap a tree prior to installing
# so ensure the directory exists.
os.makedirs(envdir, exist_ok=True)
# Older luarocks (e.g., 2.4.2) expect the rockspec as an arg
for rockspec in prefix.star('.rockspec'):
make_cmd = ('luarocks', '--tree', envdir, 'make', rockspec)
lang_base.setup_cmd(prefix, make_cmd)
# luarocks can't install multiple packages at once
# so install them individually.
for dependency in additional_dependencies:
cmd = ('luarocks', '--tree', envdir, 'install', dependency)
lang_base.setup_cmd(prefix, cmd)

View file

@ -1,74 +1,110 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import os
import sys
from collections.abc import Generator
from collections.abc import Sequence
import pre_commit.constants as C
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import UNSET
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.languages.python import bin_dir
from pre_commit.util import clean_path_on_failure
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
from pre_commit.xargs import xargs
from pre_commit.util import cmd_output_b
from pre_commit.util import rmtree
ENVIRONMENT_DIR = 'node_env'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
run_hook = lang_base.basic_run_hook
def _envdir(prefix, version):
directory = helpers.environment_dir(ENVIRONMENT_DIR, version)
return prefix.path(directory)
@functools.lru_cache(maxsize=1)
def get_default_version() -> str:
# nodeenv does not yet support `-n system` on windows
if sys.platform == 'win32':
return C.DEFAULT
# if node is already installed, we can save a bunch of setup time by
# using the installed version
elif all(lang_base.exe_exists(exe) for exe in ('node', 'npm')):
return 'system'
else:
return C.DEFAULT
def get_env_patch(venv):
def get_env_patch(venv: str) -> PatchesT:
if sys.platform == 'cygwin': # pragma: no cover
_, win_venv, _ = cmd_output('cygpath', '-w', venv)
install_prefix = r'{}\bin'.format(win_venv.strip())
install_prefix = fr'{win_venv.strip()}\bin'
lib_dir = 'lib'
elif sys.platform == 'win32': # pragma: no cover
install_prefix = bin_dir(venv)
else:
lib_dir = 'Scripts'
else: # pragma: win32 no cover
install_prefix = venv
lib_dir = 'lib'
return (
('NODE_VIRTUAL_ENV', venv),
('NPM_CONFIG_PREFIX', install_prefix),
('npm_config_prefix', install_prefix),
('NODE_PATH', os.path.join(venv, 'lib', 'node_modules')),
('NPM_CONFIG_USERCONFIG', UNSET),
('npm_config_userconfig', UNSET),
('NODE_PATH', os.path.join(venv, lib_dir, 'node_modules')),
('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))),
)
@contextlib.contextmanager
def in_env(prefix, language_version):
with envcontext(get_env_patch(_envdir(prefix, language_version))):
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(prefix, version, additional_dependencies):
additional_dependencies = tuple(additional_dependencies)
def health_check(prefix: Prefix, version: str) -> str | None:
with in_env(prefix, version):
retcode, _, _ = cmd_output_b('node', '--version', check=False)
if retcode != 0: # pragma: win32 no cover
return f'`node --version` returned {retcode}'
else:
return None
def install_environment(
prefix: Prefix, version: str, additional_dependencies: Sequence[str],
) -> None:
assert prefix.exists('package.json')
envdir = _envdir(prefix, version)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx?f=255&MSPPError=-2147217396#maxpath
if sys.platform == 'win32': # pragma: no cover
envdir = '\\\\?\\' + os.path.normpath(envdir)
with clean_path_on_failure(envdir):
cmd = [
sys.executable, '-mnodeenv', '--prebuilt', '--clean-src', envdir,
]
if version != 'default':
cmd.extend(['-n', version])
cmd_output(*cmd)
envdir = fr'\\?\{os.path.normpath(envdir)}'
cmd = [sys.executable, '-mnodeenv', '--prebuilt', '--clean-src', envdir]
if version != C.DEFAULT:
cmd.extend(['-n', version])
cmd_output_b(*cmd)
with in_env(prefix, version):
helpers.run_setup_cmd(
prefix,
('npm', 'install', '-g', '.') + additional_dependencies,
)
with in_env(prefix, version):
# https://npm.community/t/npm-install-g-git-vs-git-clone-cd-npm-install-g/5449
# install as if we installed from git
local_install_cmd = (
'npm', 'install', '--include=dev', '--include=prod',
'--ignore-prepublish', '--no-progress', '--no-save',
)
lang_base.setup_cmd(prefix, local_install_cmd)
def run_hook(prefix, hook, file_args):
with in_env(prefix, hook['language_version']):
return xargs(helpers.to_cmd(hook), file_args)
_, pkg, _ = cmd_output('npm', 'pack', cwd=prefix.prefix_dir)
pkg = prefix.path(pkg.strip())
install = ('npm', 'install', '-g', pkg, *additional_dependencies)
lang_base.setup_cmd(prefix, install)
# clean these up after installation
if prefix.exists('node_modules'): # pragma: win32 no cover
rmtree(prefix.path('node_modules'))
os.remove(pkg)

View file

@ -1,22 +0,0 @@
from __future__ import unicode_literals
import sys
from pre_commit.languages import helpers
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
GREP = 'ggrep' if sys.platform == 'darwin' else 'grep'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(prefix, hook, file_args):
# For PCRE the entry is the regular expression to match
cmd = (GREP, '-H', '-n', '-P') + tuple(hook['args']) + (hook['entry'],)
# Grep usually returns 0 for matches, and nonzero for non-matches so we
# negate it here.
return xargs(cmd, file_args, negate=True)

View file

@ -0,0 +1,50 @@
from __future__ import annotations
import contextlib
import os
import shlex
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = 'perl_env'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(venv: str) -> PatchesT:
return (
('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))),
('PERL5LIB', os.path.join(venv, 'lib', 'perl5')),
('PERL_MB_OPT', f'--install_base {shlex.quote(venv)}'),
(
'PERL_MM_OPT', (
f'INSTALL_BASE={shlex.quote(venv)} '
f'INSTALLSITEMAN1DIR=none INSTALLSITEMAN3DIR=none'
),
),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(
prefix: Prefix, version: str, additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('perl', version)
with in_env(prefix, version):
lang_base.setup_cmd(
prefix, ('cpan', '-T', '.', *additional_dependencies),
)

View file

@ -1,33 +1,36 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import argparse
import re
import sys
from collections.abc import Sequence
from re import Pattern
from typing import NamedTuple
from pre_commit import lang_base
from pre_commit import output
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
install_environment = lang_base.no_install
in_env = lang_base.no_env
def _process_filename_by_line(pattern, filename):
def _process_filename_by_line(pattern: Pattern[bytes], filename: str) -> int:
retv = 0
with open(filename, 'rb') as f:
for line_no, line in enumerate(f, start=1):
if pattern.search(line):
retv = 1
output.write('{}:{}:'.format(filename, line_no))
output.write_line(line.rstrip(b'\r\n'))
output.write(f'{filename}:{line_no}:')
output.write_line_b(line.rstrip(b'\r\n'))
return retv
def _process_filename_at_once(pattern, filename):
def _process_filename_at_once(pattern: Pattern[bytes], filename: str) -> int:
retv = 0
with open(filename, 'rb') as f:
contents = f.read()
@ -35,22 +38,70 @@ def _process_filename_at_once(pattern, filename):
if match:
retv = 1
line_no = contents[:match.start()].count(b'\n')
output.write('{}:{}:'.format(filename, line_no + 1))
output.write(f'{filename}:{line_no + 1}:')
matched_lines = match.group().split(b'\n')
matched_lines = match[0].split(b'\n')
matched_lines[0] = contents.split(b'\n')[line_no]
output.write_line(b'\n'.join(matched_lines))
output.write_line_b(b'\n'.join(matched_lines))
return retv
def run_hook(prefix, hook, file_args):
exe = (sys.executable, '-m', __name__)
exe += tuple(hook['args']) + (hook['entry'],)
return xargs(exe, file_args)
def _process_filename_by_line_negated(
pattern: Pattern[bytes],
filename: str,
) -> int:
with open(filename, 'rb') as f:
for line in f:
if pattern.search(line):
return 0
else:
output.write_line(filename)
return 1
def main(argv=None):
def _process_filename_at_once_negated(
pattern: Pattern[bytes],
filename: str,
) -> int:
with open(filename, 'rb') as f:
contents = f.read()
match = pattern.search(contents)
if match:
return 0
else:
output.write_line(filename)
return 1
class Choice(NamedTuple):
multiline: bool
negate: bool
FNS = {
Choice(multiline=True, negate=True): _process_filename_at_once_negated,
Choice(multiline=True, negate=False): _process_filename_at_once,
Choice(multiline=False, negate=True): _process_filename_by_line_negated,
Choice(multiline=False, negate=False): _process_filename_by_line,
}
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
cmd = (sys.executable, '-m', __name__, *args, entry)
return xargs(cmd, file_args, color=color)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=(
'grep-like finder using python regexes. Unlike grep, this tool '
@ -60,6 +111,7 @@ def main(argv=None):
)
parser.add_argument('-i', '--ignore-case', action='store_true')
parser.add_argument('--multiline', action='store_true')
parser.add_argument('--negate', action='store_true')
parser.add_argument('pattern', help='python regex pattern.')
parser.add_argument('filenames', nargs='*')
args = parser.parse_args(argv)
@ -71,13 +123,11 @@ def main(argv=None):
pattern = re.compile(args.pattern.encode(), flags)
retv = 0
process_fn = FNS[Choice(multiline=args.multiline, negate=args.negate)]
for filename in args.filenames:
if args.multiline:
retv |= _process_filename_at_once(pattern, filename)
else:
retv |= _process_filename_by_line(pattern, filename)
retv |= process_fn(pattern, filename)
return retv
if __name__ == '__main__':
exit(main())
raise SystemExit(main())

View file

@ -1,56 +1,95 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import os
import sys
from collections.abc import Generator
from collections.abc import Sequence
import pre_commit.constants as C
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import UNSET
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.parse_shebang import find_executable
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from pre_commit.util import clean_path_on_failure
from pre_commit.util import cmd_output
from pre_commit.xargs import xargs
from pre_commit.util import cmd_output_b
from pre_commit.util import win_exe
ENVIRONMENT_DIR = 'py_env'
run_hook = lang_base.basic_run_hook
def bin_dir(venv):
@functools.cache
def _version_info(exe: str) -> str:
prog = 'import sys;print(".".join(str(p) for p in sys.version_info))'
try:
return cmd_output(exe, '-S', '-c', prog)[1].strip()
except CalledProcessError:
return f'<<error retrieving version from {exe}>>'
def _read_pyvenv_cfg(filename: str) -> dict[str, str]:
ret = {}
with open(filename, encoding='UTF-8') as f:
for line in f:
try:
k, v = line.split('=')
except ValueError: # blank line / comment / etc.
continue
else:
ret[k.strip()] = v.strip()
return ret
def bin_dir(venv: str) -> str:
"""On windows there's a different directory for the virtualenv"""
bin_part = 'Scripts' if os.name == 'nt' else 'bin'
bin_part = 'Scripts' if sys.platform == 'win32' else 'bin'
return os.path.join(venv, bin_part)
def get_env_patch(venv):
def get_env_patch(venv: str) -> PatchesT:
return (
('PIP_DISABLE_PIP_VERSION_CHECK', '1'),
('PYTHONHOME', UNSET),
('VIRTUAL_ENV', venv),
('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))),
)
def _find_by_py_launcher(version): # pragma: no cover (windows only)
def _find_by_py_launcher(
version: str,
) -> str | None: # pragma: no cover (windows only)
if version.startswith('python'):
num = version.removeprefix('python')
cmd = ('py', f'-{num}', '-c', 'import sys; print(sys.executable)')
env = dict(os.environ, PYTHONIOENCODING='UTF-8')
try:
return cmd_output(
'py', '-{}'.format(version[len('python'):]),
'-c', 'import sys; print(sys.executable)',
)[1].strip()
return cmd_output(*cmd, env=env)[1].strip()
except CalledProcessError:
pass
return None
def _get_default_version(): # pragma: no cover (platform dependent)
def _norm(path):
def _impl_exe_name() -> str:
if sys.implementation.name == 'cpython': # pragma: cpython cover
return 'python'
else: # pragma: cpython no cover
return sys.implementation.name # pypy mostly
def _find_by_sys_executable() -> str | None:
def _norm(path: str) -> str | None:
_, exe = os.path.split(path.lower())
exe, _, _ = exe.partition('.exe')
if find_executable(exe) and exe not in {'python', 'pythonw'}:
if exe not in {'python', 'pythonw'} and find_executable(exe):
return exe
return None
# First attempt from `sys.executable` (or the realpath)
# On linux, I see these common sys.executables:
#
# system `python`: /usr/bin/python -> python2.7
@ -59,100 +98,131 @@ def _get_default_version(): # pragma: no cover (platform dependent)
# virtualenv v -ppython2: v/bin/python -> python2
# virtualenv v -ppython2.7: v/bin/python -> python2.7
# virtualenv v -ppypy: v/bin/python -> v/bin/pypy
for path in {sys.executable, os.path.realpath(sys.executable)}:
for path in (sys.executable, os.path.realpath(sys.executable)):
exe = _norm(path)
if exe:
return exe
return None
# Next try the `pythonX.X` executable
exe = 'python{}.{}'.format(*sys.version_info)
if find_executable(exe):
return exe
if _find_by_py_launcher(exe):
return exe
@functools.lru_cache(maxsize=1)
def get_default_version() -> str: # pragma: no cover (platform dependent)
v_major = f'{sys.version_info[0]}'
v_minor = f'{sys.version_info[0]}.{sys.version_info[1]}'
# Give a best-effort try for windows
if os.path.exists(r'C:\{}\python.exe'.format(exe.replace('.', ''))):
return exe
# attempt the likely implementation exe
for potential in (v_minor, v_major):
exe = f'{_impl_exe_name()}{potential}'
if find_executable(exe):
return exe
# next try `sys.executable` (or the realpath)
maybe_exe = _find_by_sys_executable()
if maybe_exe:
return maybe_exe
# maybe on windows we can find it via py launcher?
if sys.platform == 'win32': # pragma: win32 cover
exe = f'python{v_minor}'
if _find_by_py_launcher(exe):
return exe
# We tried!
return 'default'
return C.DEFAULT
def get_default_version():
# TODO: when dropping python2, use `functools.lru_cache(maxsize=1)`
def _sys_executable_matches(version: str) -> bool:
if version == 'python':
return True
elif not version.startswith('python'):
return False
try:
return get_default_version.cached_version
except AttributeError:
get_default_version.cached_version = _get_default_version()
return get_default_version()
info = tuple(int(p) for p in version.removeprefix('python').split('.'))
except ValueError:
return False
return sys.version_info[:len(info)] == info
def norm_version(version):
if os.name == 'nt': # pragma: no cover (windows)
def norm_version(version: str) -> str | None:
if version == C.DEFAULT: # use virtualenv's default
return None
elif _sys_executable_matches(version): # virtualenv defaults to our exe
return None
if sys.platform == 'win32': # pragma: no cover (windows)
version_exec = _find_by_py_launcher(version)
if version_exec:
return version_exec
# Try looking up by name
version_exec = find_executable(version)
if version_exec and version_exec != version:
return version_exec
version_exec = _find_by_py_launcher(version)
if version_exec:
return version_exec
# If it is in the form pythonx.x search in the default
# place on windows
if version.startswith('python'):
return r'C:\{}\python.exe'.format(version.replace('.', ''))
# Otherwise assume it is a path
return os.path.expanduser(version)
def py_interface(_dir, _make_venv):
@contextlib.contextmanager
def in_env(prefix, language_version):
envdir = prefix.path(helpers.environment_dir(_dir, language_version))
with envcontext(get_env_patch(envdir)):
yield
def healthy(prefix, language_version):
with in_env(prefix, language_version):
retcode, _, _ = cmd_output(
'python', '-c',
'import ctypes, datetime, io, os, ssl, weakref',
retcode=None,
)
return retcode == 0
def run_hook(prefix, hook, file_args):
with in_env(prefix, hook['language_version']):
return xargs(helpers.to_cmd(hook), file_args)
def install_environment(prefix, version, additional_dependencies):
additional_dependencies = tuple(additional_dependencies)
directory = helpers.environment_dir(_dir, version)
env_dir = prefix.path(directory)
with clean_path_on_failure(env_dir):
if version != 'default':
python = norm_version(version)
else:
python = os.path.realpath(sys.executable)
_make_venv(env_dir, python)
with in_env(prefix, version):
helpers.run_setup_cmd(
prefix, ('pip', 'install', '.') + additional_dependencies,
)
return in_env, healthy, run_hook, install_environment
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def make_venv(envdir, python):
env = dict(os.environ, VIRTUALENV_NO_DOWNLOAD='1')
cmd = (sys.executable, '-mvirtualenv', envdir, '-p', python)
cmd_output(*cmd, env=env, cwd='/')
def health_check(prefix: Prefix, version: str) -> str | None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
pyvenv_cfg = os.path.join(envdir, 'pyvenv.cfg')
# created with "old" virtualenv
if not os.path.exists(pyvenv_cfg):
return 'pyvenv.cfg does not exist (old virtualenv?)'
exe_name = win_exe('python')
py_exe = prefix.path(bin_dir(envdir), exe_name)
cfg = _read_pyvenv_cfg(pyvenv_cfg)
if 'version_info' not in cfg:
return "created virtualenv's pyvenv.cfg is missing `version_info`"
# always use uncached lookup here in case we replaced an unhealthy env
virtualenv_version = _version_info.__wrapped__(py_exe)
if virtualenv_version != cfg['version_info']:
return (
f'virtualenv python version did not match created version:\n'
f'- actual version: {virtualenv_version}\n'
f'- expected version: {cfg["version_info"]}\n'
)
# made with an older version of virtualenv? skip `base-executable` check
if 'base-executable' not in cfg:
return None
base_exe_version = _version_info(cfg['base-executable'])
if base_exe_version != cfg['version_info']:
return (
f'base executable python version does not match created version:\n'
f'- base-executable version: {base_exe_version}\n'
f'- expected version: {cfg["version_info"]}\n'
)
else:
return None
_interface = py_interface(ENVIRONMENT_DIR, make_venv)
in_env, healthy, run_hook, install_environment = _interface
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
venv_cmd = [sys.executable, '-mvirtualenv', envdir]
python = norm_version(version)
if python is not None:
venv_cmd.extend(('-p', python))
install_cmd = ('python', '-mpip', 'install', '.', *additional_dependencies)
cmd_output_b(*venv_cmd, cwd='/')
with in_env(prefix, version):
lang_base.setup_cmd(prefix, install_cmd)

View file

@ -1,55 +0,0 @@
from __future__ import unicode_literals
import os.path
import sys
from pre_commit.languages import python
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
ENVIRONMENT_DIR = 'py_venv'
def get_default_version(): # pragma: no cover (version specific)
if sys.version_info < (3,):
return 'python3'
else:
return python.get_default_version()
def orig_py_exe(exe): # pragma: no cover (platform specific)
"""A -mvenv virtualenv made from a -mvirtualenv virtualenv installs
packages to the incorrect location. Attempt to find the _original_ exe
and invoke `-mvenv` from there.
See:
- https://github.com/pre-commit/pre-commit/issues/755
- https://github.com/pypa/virtualenv/issues/1095
- https://bugs.python.org/issue30811
"""
try:
prefix_script = 'import sys; print(sys.real_prefix)'
_, prefix, _ = cmd_output(exe, '-c', prefix_script)
prefix = prefix.strip()
except CalledProcessError:
# not created from -mvirtualenv
return exe
if os.name == 'nt':
expected = os.path.join(prefix, 'python.exe')
else:
expected = os.path.join(prefix, 'bin', os.path.basename(exe))
if os.path.exists(expected):
return expected
else:
return exe
def make_venv(envdir, python):
cmd_output(orig_py_exe(python), '-mvenv', envdir, cwd='/')
_interface = python.py_interface(ENVIRONMENT_DIR, make_venv)
in_env, healthy, run_hook, install_environment = _interface

278
pre_commit/languages/r.py Normal file
View file

@ -0,0 +1,278 @@
from __future__ import annotations
import contextlib
import os
import shlex
import shutil
import tempfile
import textwrap
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import UNSET
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
from pre_commit.util import win_exe
ENVIRONMENT_DIR = 'renv'
get_default_version = lang_base.basic_get_default_version
_RENV_ACTIVATED_OPTS = (
'--no-save', '--no-restore', '--no-site-file', '--no-environ',
)
def _execute_r(
code: str, *,
prefix: Prefix, version: str, args: Sequence[str] = (), cwd: str,
cli_opts: Sequence[str],
) -> str:
with in_env(prefix, version), _r_code_in_tempfile(code) as f:
_, out, _ = cmd_output(
_rscript_exec(), *cli_opts, f, *args, cwd=cwd,
)
return out.rstrip('\n')
def _execute_r_in_renv(
code: str, *,
prefix: Prefix, version: str, args: Sequence[str] = (), cwd: str,
) -> str:
return _execute_r(
code=code, prefix=prefix, version=version, args=args, cwd=cwd,
cli_opts=_RENV_ACTIVATED_OPTS,
)
def _execute_vanilla_r(
code: str, *,
prefix: Prefix, version: str, args: Sequence[str] = (), cwd: str,
) -> str:
return _execute_r(
code=code, prefix=prefix, version=version, args=args, cwd=cwd,
cli_opts=('--vanilla',),
)
def _read_installed_version(envdir: str, prefix: Prefix, version: str) -> str:
return _execute_r_in_renv(
'cat(renv::settings$r.version())',
prefix=prefix, version=version,
cwd=envdir,
)
def _read_executable_version(envdir: str, prefix: Prefix, version: str) -> str:
return _execute_r_in_renv(
'cat(as.character(getRversion()))',
prefix=prefix, version=version,
cwd=envdir,
)
def _write_current_r_version(
envdir: str, prefix: Prefix, version: str,
) -> None:
_execute_r_in_renv(
'renv::settings$r.version(as.character(getRversion()))',
prefix=prefix, version=version,
cwd=envdir,
)
def health_check(prefix: Prefix, version: str) -> str | None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
r_version_installation = _read_installed_version(
envdir=envdir, prefix=prefix, version=version,
)
r_version_current_executable = _read_executable_version(
envdir=envdir, prefix=prefix, version=version,
)
if r_version_installation in {'NULL', ''}:
return (
f'Hooks were installed with an unknown R version. R version for '
f'hook repo now set to {r_version_current_executable}'
)
elif r_version_installation != r_version_current_executable:
return (
f'Hooks were installed for R version {r_version_installation}, '
f'but current R executable has version '
f'{r_version_current_executable}'
)
return None
@contextlib.contextmanager
def _r_code_in_tempfile(code: str) -> Generator[str]:
"""
To avoid quoting and escaping issues, avoid `Rscript [options] -e {expr}`
but use `Rscript [options] path/to/file_with_expr.R`
"""
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, 'script.R')
with open(fname, 'w') as f:
f.write(_inline_r_setup(textwrap.dedent(code)))
yield fname
def get_env_patch(venv: str) -> PatchesT:
return (
('R_PROFILE_USER', os.path.join(venv, 'activate.R')),
('RENV_PROJECT', UNSET),
)
@contextlib.contextmanager
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def _prefix_if_file_entry(
entry: list[str],
prefix: Prefix,
*,
is_local: bool,
) -> Sequence[str]:
if entry[1] == '-e' or is_local:
return entry[1:]
else:
return (prefix.path(entry[1]),)
def _rscript_exec() -> str:
r_home = os.environ.get('R_HOME')
if r_home is None:
return 'Rscript'
else:
return os.path.join(r_home, 'bin', win_exe('Rscript'))
def _entry_validate(entry: list[str]) -> None:
"""
Allowed entries:
# Rscript -e expr
# Rscript path/to/file
"""
if entry[0] != 'Rscript':
raise ValueError('entry must start with `Rscript`.')
if entry[1] == '-e':
if len(entry) > 3:
raise ValueError('You can supply at most one expression.')
elif len(entry) > 2:
raise ValueError(
'The only valid syntax is `Rscript -e {expr}`'
'or `Rscript path/to/hook/script`',
)
def _cmd_from_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
*,
is_local: bool,
) -> tuple[str, ...]:
cmd = shlex.split(entry)
_entry_validate(cmd)
cmd_part = _prefix_if_file_entry(cmd, prefix, is_local=is_local)
return (cmd[0], *_RENV_ACTIVATED_OPTS, *cmd_part, *args)
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
lang_base.assert_version_default('r', version)
env_dir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
os.makedirs(env_dir, exist_ok=True)
shutil.copy(prefix.path('renv.lock'), env_dir)
shutil.copytree(prefix.path('renv'), os.path.join(env_dir, 'renv'))
r_code_inst_environment = f"""\
prefix_dir <- {prefix.prefix_dir!r}
options(
repos = c(CRAN = "https://cran.rstudio.com"),
renv.consent = TRUE
)
source("renv/activate.R")
renv::restore()
activate_statement <- paste0(
'suppressWarnings({{',
'old <- setwd("', getwd(), '"); ',
'source("renv/activate.R"); ',
'setwd(old); ',
'renv::load("', getwd(), '");}})'
)
writeLines(activate_statement, 'activate.R')
is_package <- tryCatch(
{{
path_desc <- file.path(prefix_dir, 'DESCRIPTION')
suppressWarnings(desc <- read.dcf(path_desc))
"Package" %in% colnames(desc)
}},
error = function(...) FALSE
)
if (is_package) {{
renv::install(prefix_dir)
}}
"""
_execute_vanilla_r(
r_code_inst_environment,
prefix=prefix, version=version, cwd=env_dir,
)
_write_current_r_version(envdir=env_dir, prefix=prefix, version=version)
if additional_dependencies:
r_code_inst_add = 'renv::install(commandArgs(trailingOnly = TRUE))'
_execute_r_in_renv(
code=r_code_inst_add, prefix=prefix, version=version,
args=additional_dependencies,
cwd=env_dir,
)
def _inline_r_setup(code: str) -> str:
"""
Some behaviour of R cannot be configured via env variables, but can
only be configured via R options once R has started. These are set here.
"""
with_option = [
textwrap.dedent("""\
options(
install.packages.compile.from.source = "never",
pkgType = "binary"
)
"""),
code,
]
return '\n'.join(with_option)
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
cmd = _cmd_from_hook(prefix, entry, args, is_local=is_local)
return lang_base.run_xargs(
cmd,
file_args,
require_serial=require_serial,
color=color,
)

View file

@ -1,128 +1,145 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import io
import functools
import importlib.resources
import os.path
import shutil
import tarfile
from collections.abc import Generator
from collections.abc import Sequence
from typing import IO
import pre_commit.constants as C
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import UNSET
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from pre_commit.util import clean_path_on_failure
from pre_commit.util import resource_filename
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = 'rbenv'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(venv, language_version): # pragma: windows no cover
patches = (
def _resource_bytesio(filename: str) -> IO[bytes]:
files = importlib.resources.files('pre_commit.resources')
return files.joinpath(filename).open('rb')
@functools.lru_cache(maxsize=1)
def get_default_version() -> str:
if all(lang_base.exe_exists(exe) for exe in ('ruby', 'gem')):
return 'system'
else:
return C.DEFAULT
def get_env_patch(
venv: str,
language_version: str,
) -> PatchesT:
patches: PatchesT = (
('GEM_HOME', os.path.join(venv, 'gems')),
('RBENV_ROOT', venv),
('GEM_PATH', UNSET),
('BUNDLE_IGNORE_CONFIG', '1'),
(
'PATH', (
os.path.join(venv, 'gems', 'bin'), os.pathsep,
os.path.join(venv, 'shims'), os.pathsep,
os.path.join(venv, 'bin'), os.pathsep, Var('PATH'),
),
),
)
if language_version != 'default':
if language_version == 'system':
patches += (
(
'PATH', (
os.path.join(venv, 'gems', 'bin'), os.pathsep,
Var('PATH'),
),
),
)
else: # pragma: win32 no cover
patches += (
('RBENV_ROOT', venv),
(
'PATH', (
os.path.join(venv, 'gems', 'bin'), os.pathsep,
os.path.join(venv, 'shims'), os.pathsep,
os.path.join(venv, 'bin'), os.pathsep, Var('PATH'),
),
),
)
if language_version not in {'system', 'default'}: # pragma: win32 no cover
patches += (('RBENV_VERSION', language_version),)
return patches
@contextlib.contextmanager
def in_env(prefix, language_version): # pragma: windows no cover
envdir = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, language_version),
)
with envcontext(get_env_patch(envdir, language_version)):
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir, version)):
yield
def _install_rbenv(prefix, version='default'): # pragma: windows no cover
directory = helpers.environment_dir(ENVIRONMENT_DIR, version)
def _extract_resource(filename: str, dest: str) -> None:
with _resource_bytesio(filename) as bio:
with tarfile.open(fileobj=bio) as tf:
tf.extractall(dest)
with tarfile.open(resource_filename('rbenv.tar.gz')) as tf:
tf.extractall(prefix.path('.'))
shutil.move(prefix.path('rbenv'), prefix.path(directory))
def _install_rbenv(
prefix: Prefix,
version: str,
) -> None: # pragma: win32 no cover
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
_extract_resource('rbenv.tar.gz', prefix.path('.'))
shutil.move(prefix.path('rbenv'), envdir)
# Only install ruby-build if the version is specified
if version != 'default':
# ruby-download
with tarfile.open(resource_filename('ruby-download.tar.gz')) as tf:
tf.extractall(prefix.path(directory, 'plugins'))
# ruby-build
with tarfile.open(resource_filename('ruby-build.tar.gz')) as tf:
tf.extractall(prefix.path(directory, 'plugins'))
activate_path = prefix.path(directory, 'bin', 'activate')
with io.open(activate_path, 'w') as activate_file:
# This is similar to how you would install rbenv to your home directory
# However we do a couple things to make the executables exposed and
# configure it to work in our directory.
# We also modify the PS1 variable for manual debugging sake.
activate_file.write(
'#!/usr/bin/env bash\n'
"export RBENV_ROOT='{directory}'\n"
'export PATH="$RBENV_ROOT/bin:$PATH"\n'
'eval "$(rbenv init -)"\n'
'export PS1="(rbenv)$PS1"\n'
# This lets us install gems in an isolated and repeatable
# directory
"export GEM_HOME='{directory}/gems'\n"
'export PATH="$GEM_HOME/bin:$PATH"\n'
'\n'.format(directory=prefix.path(directory)),
)
# If we aren't using the system ruby, add a version here
if version != 'default':
activate_file.write('export RBENV_VERSION="{}"\n'.format(version))
if version != C.DEFAULT:
plugins_dir = os.path.join(envdir, 'plugins')
_extract_resource('ruby-download.tar.gz', plugins_dir)
_extract_resource('ruby-build.tar.gz', plugins_dir)
def _install_ruby(runner, version): # pragma: windows no cover
def _install_ruby(
prefix: Prefix,
version: str,
) -> None: # pragma: win32 no cover
try:
helpers.run_setup_cmd(runner, ('rbenv', 'download', version))
lang_base.setup_cmd(prefix, ('rbenv', 'download', version))
except CalledProcessError: # pragma: no cover (usually find with download)
# Failed to download from mirror for some reason, build it instead
helpers.run_setup_cmd(runner, ('rbenv', 'install', version))
lang_base.setup_cmd(prefix, ('rbenv', 'install', version))
def install_environment(
prefix, version, additional_dependencies,
): # pragma: windows no cover
additional_dependencies = tuple(additional_dependencies)
directory = helpers.environment_dir(ENVIRONMENT_DIR, version)
with clean_path_on_failure(prefix.path(directory)):
# TODO: this currently will fail if there's no version specified and
# there's no system ruby installed. Is this ok?
_install_rbenv(prefix, version=version)
prefix: Prefix, version: str, additional_dependencies: Sequence[str],
) -> None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
if version != 'system': # pragma: win32 no cover
_install_rbenv(prefix, version)
with in_env(prefix, version):
# Need to call this before installing so rbenv's directories are
# set up
helpers.run_setup_cmd(prefix, ('rbenv', 'init', '-'))
if version != 'default':
# Need to call this before installing so rbenv's directories
# are set up
lang_base.setup_cmd(prefix, ('rbenv', 'init', '-'))
if version != C.DEFAULT:
_install_ruby(prefix, version)
# Need to call this after installing to set up the shims
helpers.run_setup_cmd(prefix, ('rbenv', 'rehash'))
helpers.run_setup_cmd(
prefix, ('gem', 'build') + prefix.star('.gemspec'),
)
helpers.run_setup_cmd(
prefix,
('gem', 'install', '--no-ri', '--no-rdoc') +
prefix.star('.gem') + additional_dependencies,
)
lang_base.setup_cmd(prefix, ('rbenv', 'rehash'))
def run_hook(prefix, hook, file_args): # pragma: windows no cover
with in_env(prefix, hook['language_version']):
return xargs(helpers.to_cmd(hook), file_args)
with in_env(prefix, version):
lang_base.setup_cmd(
prefix, ('gem', 'build', *prefix.star('.gemspec')),
)
lang_base.setup_cmd(
prefix,
(
'gem', 'install',
'--no-document', '--no-format-executable',
'--no-user-install',
'--install-dir', os.path.join(envdir, 'gems'),
'--bindir', os.path.join(envdir, 'gems', 'bin'),
*prefix.star('.gem'), *additional_dependencies,
),
)

View file

@ -1,58 +1,121 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import functools
import os.path
import shutil
import sys
import tempfile
import urllib.request
from collections.abc import Generator
from collections.abc import Sequence
import toml
import pre_commit.constants as C
from pre_commit import lang_base
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.util import clean_path_on_failure
from pre_commit.util import cmd_output
from pre_commit.xargs import xargs
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output_b
from pre_commit.util import make_executable
from pre_commit.util import win_exe
ENVIRONMENT_DIR = 'rustenv'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(target_dir):
@functools.lru_cache(maxsize=1)
def get_default_version() -> str:
# If rust is already installed, we can save a bunch of setup time by
# using the installed version.
#
# Just detecting the executable does not suffice, because if rustup is
# installed but no toolchain is available, then `cargo` exists but
# cannot be used without installing a toolchain first.
if cmd_output_b('cargo', '--version', check=False, cwd='/')[0] == 0:
return 'system'
else:
return C.DEFAULT
def _rust_toolchain(language_version: str) -> str:
"""Transform the language version into a rust toolchain version."""
if language_version == C.DEFAULT:
return 'stable'
else:
return language_version
def get_env_patch(target_dir: str, version: str) -> PatchesT:
return (
(
'PATH',
(os.path.join(target_dir, 'bin'), os.pathsep, Var('PATH')),
('PATH', (os.path.join(target_dir, 'bin'), os.pathsep, Var('PATH'))),
# Only set RUSTUP_TOOLCHAIN if we don't want use the system's default
# toolchain
*(
(('RUSTUP_TOOLCHAIN', _rust_toolchain(version)),)
if version != 'system' else ()
),
)
@contextlib.contextmanager
def in_env(prefix):
target_dir = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
with envcontext(get_env_patch(target_dir)):
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir, version)):
yield
def _add_dependencies(cargo_toml_path, additional_dependencies):
with open(cargo_toml_path, 'r+') as f:
cargo_toml = toml.load(f)
cargo_toml.setdefault('dependencies', {})
for dep in additional_dependencies:
name, _, spec = dep.partition(':')
cargo_toml['dependencies'][name] = spec or '*'
f.seek(0)
toml.dump(cargo_toml, f)
f.truncate()
def _add_dependencies(
prefix: Prefix,
additional_dependencies: set[str],
) -> None:
crates = []
for dep in additional_dependencies:
name, _, spec = dep.partition(':')
crate = f'{name}@{spec or "*"}'
crates.append(crate)
lang_base.setup_cmd(prefix, ('cargo', 'add', *crates))
def install_environment(prefix, version, additional_dependencies):
helpers.assert_version_default('rust', version)
directory = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
def install_rust_with_toolchain(toolchain: str, envdir: str) -> None:
with tempfile.TemporaryDirectory() as rustup_dir:
with envcontext((('CARGO_HOME', envdir), ('RUSTUP_HOME', rustup_dir))):
# acquire `rustup` if not present
if parse_shebang.find_executable('rustup') is None:
# We did not detect rustup and need to download it first.
if sys.platform == 'win32': # pragma: win32 cover
url = 'https://win.rustup.rs/x86_64'
else: # pragma: win32 no cover
url = 'https://sh.rustup.rs'
resp = urllib.request.urlopen(url)
rustup_init = os.path.join(rustup_dir, win_exe('rustup-init'))
with open(rustup_init, 'wb') as f:
shutil.copyfileobj(resp, f)
make_executable(rustup_init)
# install rustup into `$CARGO_HOME/bin`
cmd_output_b(
rustup_init, '-y', '--quiet', '--no-modify-path',
'--default-toolchain', 'none',
)
cmd_output_b(
'rustup', 'toolchain', 'install', '--no-self-update',
toolchain,
)
def install_environment(
prefix: Prefix,
version: str,
additional_dependencies: Sequence[str],
) -> None:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
# There are two cases where we might want to specify more dependencies:
# as dependencies for the library being built, and as binary packages
@ -69,26 +132,29 @@ def install_environment(prefix, version, additional_dependencies):
}
lib_deps = set(additional_dependencies) - cli_deps
if len(lib_deps) > 0:
_add_dependencies(prefix.path('Cargo.toml'), lib_deps)
packages_to_install: set[tuple[str, ...]] = {('--path', '.')}
for cli_dep in cli_deps:
cli_dep = cli_dep.removeprefix('cli:')
package, _, crate_version = cli_dep.partition(':')
if crate_version != '':
packages_to_install.add((package, '--version', crate_version))
else:
packages_to_install.add((package,))
with clean_path_on_failure(directory):
packages_to_install = {()}
for cli_dep in cli_deps:
cli_dep = cli_dep[len('cli:'):]
package, _, version = cli_dep.partition(':')
if version != '':
packages_to_install.add((package, '--version', version))
else:
packages_to_install.add((package,))
with contextlib.ExitStack() as ctx:
ctx.enter_context(in_env(prefix, version))
for package in packages_to_install:
cmd_output(
'cargo', 'install', '--bins', '--root', directory, *package,
cwd=prefix.prefix_dir
if version != 'system':
install_rust_with_toolchain(_rust_toolchain(version), envdir)
tmpdir = ctx.enter_context(tempfile.TemporaryDirectory())
ctx.enter_context(envcontext((('RUSTUP_HOME', tmpdir),)))
if len(lib_deps) > 0:
_add_dependencies(prefix, lib_deps)
for args in packages_to_install:
cmd_output_b(
'cargo', 'install', '--bins', '--root', envdir, *args,
cwd=prefix.prefix_dir,
)
def run_hook(prefix, hook, file_args):
with in_env(prefix):
return xargs(helpers.to_cmd(hook), file_args)

View file

@ -1,16 +0,0 @@
from __future__ import unicode_literals
from pre_commit.languages import helpers
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(prefix, hook, file_args):
cmd = helpers.to_cmd(hook)
cmd = (prefix.path(cmd[0]),) + cmd[1:]
return xargs(cmd, file_args)

View file

@ -1,56 +1,50 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import os
from collections.abc import Generator
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.languages import helpers
from pre_commit.util import clean_path_on_failure
from pre_commit.util import cmd_output
from pre_commit.xargs import xargs
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output_b
ENVIRONMENT_DIR = 'swift_env'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
BUILD_DIR = '.build'
BUILD_CONFIG = 'release'
ENVIRONMENT_DIR = 'swift_env'
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
run_hook = lang_base.basic_run_hook
def get_env_patch(venv): # pragma: windows no cover
def get_env_patch(venv: str) -> PatchesT: # pragma: win32 no cover
bin_path = os.path.join(venv, BUILD_DIR, BUILD_CONFIG)
return (('PATH', (bin_path, os.pathsep, Var('PATH'))),)
@contextlib.contextmanager
def in_env(prefix): # pragma: windows no cover
envdir = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
@contextlib.contextmanager # pragma: win32 no cover
def in_env(prefix: Prefix, version: str) -> Generator[None]:
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
with envcontext(get_env_patch(envdir)):
yield
def install_environment(
prefix, version, additional_dependencies,
): # pragma: windows no cover
helpers.assert_version_default('swift', version)
helpers.assert_no_additional_deps('swift', additional_dependencies)
directory = prefix.path(
helpers.environment_dir(ENVIRONMENT_DIR, 'default'),
)
prefix: Prefix, version: str, additional_dependencies: Sequence[str],
) -> None: # pragma: win32 no cover
lang_base.assert_version_default('swift', version)
lang_base.assert_no_additional_deps('swift', additional_dependencies)
envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version)
# Build the swift package
with clean_path_on_failure(directory):
os.mkdir(directory)
cmd_output(
'swift', 'build',
'-C', prefix.prefix_dir,
'-c', BUILD_CONFIG,
'--build-path', os.path.join(directory, BUILD_DIR),
)
def run_hook(prefix, hook, file_args): # pragma: windows no cover
with in_env(prefix):
return xargs(helpers.to_cmd(hook), file_args)
os.mkdir(envdir)
cmd_output_b(
'swift', 'build',
'--package-path', prefix.prefix_dir,
'-c', BUILD_CONFIG,
'--build-path', os.path.join(envdir, BUILD_DIR),
)

View file

@ -1,14 +0,0 @@
from __future__ import unicode_literals
from pre_commit.languages import helpers
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(prefix, hook, file_args):
return xargs(helpers.to_cmd(hook), file_args)

View file

@ -0,0 +1,10 @@
from __future__ import annotations
from pre_commit import lang_base
ENVIRONMENT_DIR = None
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
install_environment = lang_base.no_install
in_env = lang_base.no_env
run_hook = lang_base.basic_run_hook

View file

@ -0,0 +1,32 @@
from __future__ import annotations
from collections.abc import Sequence
from pre_commit import lang_base
from pre_commit.prefix import Prefix
ENVIRONMENT_DIR = None
get_default_version = lang_base.basic_get_default_version
health_check = lang_base.basic_health_check
install_environment = lang_base.no_install
in_env = lang_base.no_env
def run_hook(
prefix: Prefix,
entry: str,
args: Sequence[str],
file_args: Sequence[str],
*,
is_local: bool,
require_serial: bool,
color: bool,
) -> tuple[int, bytes]:
cmd = lang_base.hook_cmd(entry, args)
cmd = (prefix.path(cmd[0]), *cmd[1:])
return lang_base.run_xargs(
cmd,
file_args,
require_serial=require_serial,
color=color,
)

View file

@ -1,11 +1,12 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import logging
from collections.abc import Generator
from pre_commit import color
from pre_commit import output
logger = logging.getLogger('pre_commit')
LOG_LEVEL_COLORS = {
@ -17,23 +18,25 @@ LOG_LEVEL_COLORS = {
class LoggingHandler(logging.Handler):
def __init__(self, use_color):
super(LoggingHandler, self).__init__()
def __init__(self, use_color: bool) -> None:
super().__init__()
self.use_color = use_color
def emit(self, record):
output.write_line(
'{} {}'.format(
color.format_color(
'[{}]'.format(record.levelname),
LOG_LEVEL_COLORS[record.levelname],
self.use_color,
),
record.getMessage(),
),
def emit(self, record: logging.LogRecord) -> None:
level_msg = color.format_color(
f'[{record.levelname}]',
LOG_LEVEL_COLORS[record.levelname],
self.use_color,
)
output.write_line(f'{level_msg} {record.getMessage()}')
def add_logging_handler(*args, **kwargs):
logger.addHandler(LoggingHandler(*args, **kwargs))
@contextlib.contextmanager
def logging_handler(use_color: bool) -> Generator[None]:
handler = LoggingHandler(use_color)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
try:
yield
finally:
logger.removeHandler(handler)

View file

@ -1,16 +1,21 @@
from __future__ import unicode_literals
from __future__ import annotations
import argparse
import logging
import os
import sys
from collections.abc import Sequence
import pre_commit.constants as C
from pre_commit import color
from pre_commit import five
from pre_commit import clientlib
from pre_commit import git
from pre_commit.color import add_color_option
from pre_commit.commands import hazmat
from pre_commit.commands.autoupdate import autoupdate
from pre_commit.commands.clean import clean
from pre_commit.commands.gc import gc
from pre_commit.commands.hook_impl import hook_impl
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.commands.install_uninstall import install
from pre_commit.commands.install_uninstall import install_hooks
from pre_commit.commands.install_uninstall import uninstall
@ -18,9 +23,10 @@ from pre_commit.commands.migrate_config import migrate_config
from pre_commit.commands.run import run
from pre_commit.commands.sample_config import sample_config
from pre_commit.commands.try_repo import try_repo
from pre_commit.commands.validate_config import validate_config
from pre_commit.commands.validate_manifest import validate_manifest
from pre_commit.error_handler import error_handler
from pre_commit.logging_handler import add_logging_handler
from pre_commit.runner import Runner
from pre_commit.logging_handler import logging_handler
from pre_commit.store import Store
@ -32,81 +38,239 @@ logger = logging.getLogger('pre_commit')
# pyvenv
os.environ.pop('__PYVENV_LAUNCHER__', None)
# https://github.com/getsentry/snuba/pull/5388
os.environ.pop('PYTHONEXECUTABLE', None)
def _add_color_option(parser):
parser.add_argument(
'--color', default='auto', type=color.use_color,
metavar='{' + ','.join(color.COLOR_CHOICES) + '}',
help='Whether to use color in output. Defaults to `%(default)s`.',
)
COMMANDS_NO_GIT = {
'clean', 'gc', 'hazmat', 'init-templatedir', 'sample-config',
'validate-config', 'validate-manifest',
}
def _add_config_option(parser):
def _add_config_option(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'-c', '--config', default=C.CONFIG_FILE,
help='Path to alternate config file',
)
def _add_hook_type_option(parser):
def _add_hook_type_option(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'-t', '--hook-type', choices=('pre-commit', 'pre-push', 'commit-msg'),
default='pre-commit',
'-t', '--hook-type',
choices=clientlib.HOOK_TYPES, action='append', dest='hook_types',
)
def _add_run_options(parser):
def _add_run_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument('hook', nargs='?', help='A single hook-id to run')
parser.add_argument('--verbose', '-v', action='store_true', default=False)
parser.add_argument(
'--origin', '-o',
help="The origin branch's commit_id when using `git push`.",
)
parser.add_argument(
'--source', '-s',
help="The remote branch's commit_id when using `git push`.",
)
parser.add_argument(
'--commit-msg-filename',
help='Filename to check when running during `commit-msg`',
)
parser.add_argument(
'--hook-stage', choices=C.STAGES, default='commit',
help='The stage during which the hook is fired. One of %(choices)s',
)
parser.add_argument(
'--show-diff-on-failure', action='store_true',
help='When hooks fail, run `git diff` directly afterward.',
)
parser.add_argument('--verbose', '-v', action='store_true')
mutex_group = parser.add_mutually_exclusive_group(required=False)
mutex_group.add_argument(
'--all-files', '-a', action='store_true', default=False,
'--all-files', '-a', action='store_true',
help='Run on all the files in the repo.',
)
mutex_group.add_argument(
'--files', nargs='*', default=[],
help='Specific filenames to run hooks on.',
)
parser.add_argument(
'--show-diff-on-failure', action='store_true',
help='When hooks fail, run `git diff` directly afterward.',
)
parser.add_argument(
'--fail-fast', action='store_true',
help='Stop after the first failing hook.',
)
parser.add_argument(
'--hook-stage',
choices=clientlib.STAGES,
type=clientlib.transform_stage,
default='pre-commit',
help='The stage during which the hook is fired. One of %(choices)s',
)
parser.add_argument(
'--remote-branch', help='Remote branch ref used by `git push`.',
)
parser.add_argument(
'--local-branch', help='Local branch ref used by `git push`.',
)
parser.add_argument(
'--from-ref', '--source', '-s',
help=(
'(for usage with `--to-ref`) -- this option represents the '
'original ref in a `from_ref...to_ref` diff expression. '
'For `pre-push` hooks, this represents the branch you are pushing '
'to. '
'For `post-checkout` hooks, this represents the branch that was '
'previously checked out.'
),
)
parser.add_argument(
'--to-ref', '--origin', '-o',
help=(
'(for usage with `--from-ref`) -- this option represents the '
'destination ref in a `from_ref...to_ref` diff expression. '
'For `pre-push` hooks, this represents the branch being pushed. '
'For `post-checkout` hooks, this represents the branch that is '
'now checked out.'
),
)
parser.add_argument(
'--pre-rebase-upstream', help=(
'The upstream from which the series was forked.'
),
)
parser.add_argument(
'--pre-rebase-branch', help=(
'The branch being rebased, and is not set when '
'rebasing the current branch.'
),
)
parser.add_argument(
'--commit-msg-filename',
help='Filename to check when running during `commit-msg`',
)
parser.add_argument(
'--prepare-commit-message-source',
help=(
'Source of the commit message '
'(typically the second argument to .git/hooks/prepare-commit-msg)'
),
)
parser.add_argument(
'--commit-object-name',
help=(
'Commit object name '
'(typically the third argument to .git/hooks/prepare-commit-msg)'
),
)
parser.add_argument(
'--remote-name', help='Remote name used by `git push`.',
)
parser.add_argument('--remote-url', help='Remote url used by `git push`.')
parser.add_argument(
'--checkout-type',
help=(
'Indicates whether the checkout was a branch checkout '
'(changing branches, flag=1) or a file checkout (retrieving a '
'file from the index, flag=0).'
),
)
parser.add_argument(
'--is-squash-merge',
help=(
'During a post-merge hook, indicates whether the merge was a '
'squash merge'
),
)
parser.add_argument(
'--rewrite-command',
help=(
'During a post-rewrite hook, specifies the command that invoked '
'the rewrite'
),
)
def main(argv=None):
def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
# `--config` was specified relative to the non-root working directory
if os.path.exists(args.config):
args.config = os.path.abspath(args.config)
if args.command in {'run', 'try-repo'}:
args.files = [os.path.abspath(filename) for filename in args.files]
if args.commit_msg_filename is not None:
args.commit_msg_filename = os.path.abspath(
args.commit_msg_filename,
)
if args.command == 'try-repo' and os.path.exists(args.repo):
args.repo = os.path.abspath(args.repo)
toplevel = git.get_root()
os.chdir(toplevel)
args.config = os.path.relpath(args.config)
if args.command in {'run', 'try-repo'}:
args.files = [os.path.relpath(filename) for filename in args.files]
if args.commit_msg_filename is not None:
args.commit_msg_filename = os.path.relpath(
args.commit_msg_filename,
)
if args.command == 'try-repo' and os.path.exists(args.repo):
args.repo = os.path.relpath(args.repo)
def main(argv: Sequence[str] | None = None) -> int:
argv = argv if argv is not None else sys.argv[1:]
argv = [five.to_text(arg) for arg in argv]
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(prog='pre-commit')
# https://stackoverflow.com/a/8521644/812183
parser.add_argument(
'-V', '--version',
action='version',
version='%(prog)s {}'.format(C.VERSION),
version=f'%(prog)s {C.VERSION}',
)
subparsers = parser.add_subparsers(dest='command')
install_parser = subparsers.add_parser(
'install', help='Install the pre-commit script.',
def _add_cmd(name: str, *, help: str) -> argparse.ArgumentParser:
parser = subparsers.add_parser(name, help=help)
add_color_option(parser)
return parser
autoupdate_parser = _add_cmd(
'autoupdate',
help="Auto-update pre-commit config to the latest repos' versions.",
)
_add_color_option(install_parser)
_add_config_option(autoupdate_parser)
autoupdate_parser.add_argument(
'--bleeding-edge', action='store_true',
help=(
'Update to the bleeding edge of `HEAD` instead of the latest '
'tagged version (the default behavior).'
),
)
autoupdate_parser.add_argument(
'--freeze', action='store_true',
help='Store "frozen" hashes in `rev` instead of tag names',
)
autoupdate_parser.add_argument(
'--repo', dest='repos', action='append', metavar='REPO', default=[],
help='Only update this repository -- may be specified multiple times.',
)
autoupdate_parser.add_argument(
'-j', '--jobs', type=int, default=1,
help='Number of threads to use. (default %(default)s).',
)
_add_cmd('clean', help='Clean out pre-commit files.')
_add_cmd('gc', help='Clean unused cached repos.')
hazmat_parser = _add_cmd(
'hazmat', help='Composable tools for rare use in hook `entry`.',
)
hazmat.add_parsers(hazmat_parser)
init_templatedir_parser = _add_cmd(
'init-templatedir',
help=(
'Install hook script in a directory intended for use with '
'`git config init.templateDir`.'
),
)
_add_config_option(init_templatedir_parser)
init_templatedir_parser.add_argument(
'directory', help='The directory in which to write the hook script.',
)
init_templatedir_parser.add_argument(
'--no-allow-missing-config',
action='store_false',
dest='allow_missing_config',
help='Assume cloned repos should have a `pre-commit` config.',
)
_add_hook_type_option(init_templatedir_parser)
install_parser = _add_cmd('install', help='Install the pre-commit script.')
_add_config_option(install_parser)
install_parser.add_argument(
'-f', '--overwrite', action='store_true',
@ -121,14 +285,14 @@ def main(argv=None):
)
_add_hook_type_option(install_parser)
install_parser.add_argument(
'--allow-missing-config', action='store_true', default=False,
'--allow-missing-config', action='store_true',
help=(
'Whether to allow a missing `pre-commit` configuration file '
'or exit with a failure code.'
),
)
install_hooks_parser = subparsers.add_parser(
install_hooks_parser = _add_cmd(
'install-hooks',
help=(
'Install hook environments for all environments in the config '
@ -136,65 +300,24 @@ def main(argv=None):
'useful.'
),
)
_add_color_option(install_hooks_parser)
_add_config_option(install_hooks_parser)
uninstall_parser = subparsers.add_parser(
'uninstall', help='Uninstall the pre-commit script.',
)
_add_color_option(uninstall_parser)
_add_config_option(uninstall_parser)
_add_hook_type_option(uninstall_parser)
clean_parser = subparsers.add_parser(
'clean', help='Clean out pre-commit files.',
)
_add_color_option(clean_parser)
_add_config_option(clean_parser)
autoupdate_parser = subparsers.add_parser(
'autoupdate',
help="Auto-update pre-commit config to the latest repos' versions.",
)
_add_color_option(autoupdate_parser)
_add_config_option(autoupdate_parser)
autoupdate_parser.add_argument(
'--tags-only', action='store_true', help='LEGACY: for compatibility',
)
autoupdate_parser.add_argument(
'--bleeding-edge', action='store_true',
help=(
'Update to the bleeding edge of `master` instead of the latest '
'tagged version (the default behavior).'
),
)
autoupdate_parser.add_argument(
'--repo', dest='repos', action='append', metavar='REPO',
help='Only update this repository -- may be specified multiple times.',
)
migrate_config_parser = subparsers.add_parser(
migrate_config_parser = _add_cmd(
'migrate-config',
help='Migrate list configuration to new map configuration.',
)
_add_color_option(migrate_config_parser)
_add_config_option(migrate_config_parser)
run_parser = subparsers.add_parser('run', help='Run hooks.')
_add_color_option(run_parser)
run_parser = _add_cmd('run', help='Run hooks.')
_add_config_option(run_parser)
_add_run_options(run_parser)
sample_config_parser = subparsers.add_parser(
'sample-config', help='Produce a sample {} file'.format(C.CONFIG_FILE),
)
_add_color_option(sample_config_parser)
_add_config_option(sample_config_parser)
_add_cmd('sample-config', help=f'Produce a sample {C.CONFIG_FILE} file')
try_repo_parser = subparsers.add_parser(
try_repo_parser = _add_cmd(
'try-repo',
help='Try the hooks in a repository, useful for developing new hooks.',
)
_add_color_option(try_repo_parser)
_add_config_option(try_repo_parser)
try_repo_parser.add_argument(
'repo', help='Repository to source hooks from.',
@ -208,11 +331,39 @@ def main(argv=None):
)
_add_run_options(try_repo_parser)
uninstall_parser = _add_cmd(
'uninstall', help='Uninstall the pre-commit script.',
)
_add_config_option(uninstall_parser)
_add_hook_type_option(uninstall_parser)
validate_config_parser = _add_cmd(
'validate-config', help='Validate .pre-commit-config.yaml files',
)
validate_config_parser.add_argument('filenames', nargs='*')
validate_manifest_parser = _add_cmd(
'validate-manifest', help='Validate .pre-commit-hooks.yaml files',
)
validate_manifest_parser.add_argument('filenames', nargs='*')
# does not use `_add_cmd` because it doesn't use `--color`
help = subparsers.add_parser(
'help', help='Show help for a specific command.',
)
help.add_argument('help_cmd', nargs='?', help='Command to show help for.')
# not intended for users to call this directly
hook_impl_parser = subparsers.add_parser('hook-impl')
add_color_option(hook_impl_parser)
_add_config_option(hook_impl_parser)
hook_impl_parser.add_argument('--hook-type')
hook_impl_parser.add_argument('--hook-dir')
hook_impl_parser.add_argument(
'--skip-on-missing-config', action='store_true',
)
hook_impl_parser.add_argument(dest='rest', nargs=argparse.REMAINDER)
# argparse doesn't really provide a way to use a `default` subparser
if len(argv) == 0:
argv = ['run']
@ -222,56 +373,82 @@ def main(argv=None):
parser.parse_args([args.help_cmd, '--help'])
elif args.command == 'help':
parser.parse_args(['--help'])
elif args.command in {'run', 'try-repo'}:
args.files = [
os.path.relpath(os.path.abspath(filename), git.get_root())
for filename in args.files
]
with error_handler():
add_logging_handler(args.color)
runner = Runner.create(args.config)
store = Store()
with error_handler(), logging_handler(args.color):
git.check_for_cygwin_mismatch()
if args.command == 'install':
return install(
runner, store,
overwrite=args.overwrite, hooks=args.install_hooks,
hook_type=args.hook_type,
skip_on_missing_conf=args.allow_missing_config,
store = Store()
if args.command not in COMMANDS_NO_GIT:
_adjust_args_and_chdir(args)
store.mark_config_used(args.config)
if args.command == 'autoupdate':
return autoupdate(
args.config,
tags_only=not args.bleeding_edge,
freeze=args.freeze,
repos=args.repos,
jobs=args.jobs,
)
elif args.command == 'install-hooks':
return install_hooks(runner, store)
elif args.command == 'uninstall':
return uninstall(runner, hook_type=args.hook_type)
elif args.command == 'clean':
return clean(store)
elif args.command == 'autoupdate':
if args.tags_only:
logger.warning('--tags-only is the default')
return autoupdate(
runner, store,
tags_only=not args.bleeding_edge,
repos=args.repos,
elif args.command == 'gc':
return gc(store)
elif args.command == 'hazmat':
return hazmat.impl(args)
elif args.command == 'hook-impl':
return hook_impl(
store,
config=args.config,
color=args.color,
hook_type=args.hook_type,
hook_dir=args.hook_dir,
skip_on_missing_config=args.skip_on_missing_config,
args=args.rest[1:],
)
elif args.command == 'install':
return install(
args.config, store,
hook_types=args.hook_types,
overwrite=args.overwrite,
hooks=args.install_hooks,
skip_on_missing_config=args.allow_missing_config,
)
elif args.command == 'init-templatedir':
return init_templatedir(
args.config, store, args.directory,
hook_types=args.hook_types,
skip_on_missing_config=args.allow_missing_config,
)
elif args.command == 'install-hooks':
return install_hooks(args.config, store)
elif args.command == 'migrate-config':
return migrate_config(runner)
return migrate_config(args.config)
elif args.command == 'run':
return run(runner, store, args)
return run(args.config, store, args)
elif args.command == 'sample-config':
return sample_config()
elif args.command == 'try-repo':
return try_repo(args)
elif args.command == 'uninstall':
return uninstall(
config_file=args.config,
hook_types=args.hook_types,
)
elif args.command == 'validate-config':
return validate_config(args.filenames)
elif args.command == 'validate-manifest':
return validate_manifest(args.filenames)
else:
raise NotImplementedError(
'Command {} not implemented.'.format(args.command),
f'Command {args.command} not implemented.',
)
raise AssertionError(
'Command {} failed to exit with a returncode'.format(args.command),
f'Command {args.command} failed to exit with a returncode',
)
if __name__ == '__main__':
exit(main())
raise SystemExit(main())

View file

@ -1,69 +0,0 @@
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os.path
import tarfile
from pre_commit import output
from pre_commit.util import cmd_output
from pre_commit.util import resource_filename
from pre_commit.util import rmtree
from pre_commit.util import tmpdir
# This is a script for generating the tarred resources for git repo
# dependencies. Currently it's just for "vendoring" ruby support packages.
REPOS = (
('rbenv', 'git://github.com/rbenv/rbenv', 'e60ad4a'),
('ruby-build', 'git://github.com/rbenv/ruby-build', '9bc9971'),
(
'ruby-download',
'git://github.com/garnieretienne/rvm-download',
'09bd7c6',
),
)
def make_archive(name, repo, ref, destdir):
"""Makes an archive of a repository in the given destdir.
:param text name: Name to give the archive. For instance foo. The file
that is created will be called foo.tar.gz.
:param text repo: Repository to clone.
:param text ref: Tag/SHA/branch to check out.
:param text destdir: Directory to place archives in.
"""
output_path = os.path.join(destdir, name + '.tar.gz')
with tmpdir() as tempdir:
# Clone the repository to the temporary directory
cmd_output('git', 'clone', repo, tempdir)
cmd_output('git', 'checkout', ref, cwd=tempdir)
# We don't want the '.git' directory
# It adds a bunch of size to the archive and we don't use it at
# runtime
rmtree(os.path.join(tempdir, '.git'))
with tarfile.open(output_path, 'w|gz') as tf:
tf.add(tempdir, name)
return output_path
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--dest', default=resource_filename())
args = parser.parse_args(argv)
for archive_name, repo, ref in REPOS:
output.write_line('Making {}.tar.gz for {}@{}'.format(
archive_name, repo, ref,
))
make_archive(archive_name, repo, ref, args.dest)
if __name__ == '__main__':
exit(main())

View file

@ -1,34 +1,34 @@
from __future__ import annotations
import argparse
from collections.abc import Sequence
import pre_commit.constants as C
from pre_commit import git
from pre_commit.clientlib import load_config
from pre_commit.commands.run import _filter_by_include_exclude
from pre_commit.commands.run import _filter_by_types
from pre_commit.repository import repositories
from pre_commit.commands.run import Classifier
from pre_commit.repository import all_hooks
from pre_commit.store import Store
def check_all_hooks_match_files(config_file):
files = git.get_all_files()
def check_all_hooks_match_files(config_file: str) -> int:
config = load_config(config_file)
classifier = Classifier.from_config(
git.get_all_files(), config['files'], config['exclude'],
)
retv = 0
for repo in repositories(load_config(config_file), Store()):
for hook_id, hook in repo.hooks:
if hook['always_run']:
continue
include, exclude = hook['files'], hook['exclude']
filtered = _filter_by_include_exclude(files, include, exclude)
types, exclude_types = hook['types'], hook['exclude_types']
filtered = _filter_by_types(filtered, types, exclude_types)
if not filtered:
print('{} does not apply to this repository'.format(hook_id))
retv = 1
for hook in all_hooks(config, Store()):
if hook.always_run or hook.language == 'fail':
continue
elif not any(classifier.filenames_for_hook(hook)):
print(f'{hook.id} does not apply to this repository')
retv = 1
return retv
def main(argv=None):
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', default=[C.CONFIG_FILE])
args = parser.parse_args(argv)
@ -40,4 +40,4 @@ def main(argv=None):
if __name__ == '__main__':
exit(main())
raise SystemExit(main())

View file

@ -1,7 +1,9 @@
from __future__ import print_function
from __future__ import annotations
import argparse
import re
from collections.abc import Iterable
from collections.abc import Sequence
from cfgv import apply_defaults
@ -9,9 +11,14 @@ import pre_commit.constants as C
from pre_commit import git
from pre_commit.clientlib import load_config
from pre_commit.clientlib import MANIFEST_HOOK_DICT
from pre_commit.commands.run import Classifier
def exclude_matches_any(filenames, include, exclude):
def exclude_matches_any(
filenames: Iterable[str],
include: str,
exclude: str,
) -> bool:
if exclude == '^$':
return True
include_re, exclude_re = re.compile(include), re.compile(exclude)
@ -21,36 +28,47 @@ def exclude_matches_any(filenames, include, exclude):
return False
def check_useless_excludes(config_file):
def check_useless_excludes(config_file: str) -> int:
config = load_config(config_file)
files = git.get_all_files()
filenames = git.get_all_files()
classifier = Classifier.from_config(
filenames, config['files'], config['exclude'],
)
retv = 0
exclude = config['exclude']
if not exclude_matches_any(files, '', exclude):
if not exclude_matches_any(filenames, '', exclude):
print(
'The global exclude pattern {!r} does not match any files'
.format(exclude),
f'The global exclude pattern {exclude!r} does not match any files',
)
retv = 1
for repo in config['repos']:
for hook in repo['hooks']:
# the default of manifest hooks is `types: [file]` but we may
# be configuring a symlink hook while there's a broken symlink
hook.setdefault('types', [])
# Not actually a manifest dict, but this more accurately reflects
# the defaults applied during runtime
hook = apply_defaults(hook, MANIFEST_HOOK_DICT)
names = classifier.by_types(
classifier.filenames,
hook['types'],
hook['types_or'],
hook['exclude_types'],
)
include, exclude = hook['files'], hook['exclude']
if not exclude_matches_any(files, include, exclude):
if not exclude_matches_any(names, include, exclude):
print(
'The exclude pattern {!r} for {} does not match any files'
.format(exclude, hook['id']),
f'The exclude pattern {exclude!r} for {hook["id"]} does '
f'not match any files',
)
retv = 1
return retv
def main(argv=None):
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', default=[C.CONFIG_FILE])
args = parser.parse_args(argv)
@ -62,4 +80,4 @@ def main(argv=None):
if __name__ == '__main__':
exit(main())
raise SystemExit(main())

View file

@ -0,0 +1,17 @@
from __future__ import annotations
import sys
from collections.abc import Sequence
from pre_commit import output
def main(argv: Sequence[str] | None = None) -> int:
argv = argv if argv is not None else sys.argv[1:]
for arg in argv:
output.write_line(arg)
return 0
if __name__ == '__main__':
raise SystemExit(main())

View file

@ -1,88 +1,33 @@
from __future__ import unicode_literals
from __future__ import annotations
import contextlib
import sys
from pre_commit import color
from pre_commit import five
from pre_commit.util import noop_context
from typing import Any
from typing import IO
def get_hook_message(
start,
postfix='',
end_msg=None,
end_len=0,
end_color=None,
use_color=None,
cols=80,
):
"""Prints a message for running a hook.
This currently supports three approaches:
# Print `start` followed by dots, leaving 6 characters at the end
>>> print_hook_message('start', end_len=6)
start...............................................................
# Print `start` followed by dots with the end message colored if coloring
# is specified and a newline afterwards
>>> print_hook_message(
'start',
end_msg='end',
end_color=color.RED,
use_color=True,
)
start...................................................................end
# Print `start` followed by dots, followed by the `postfix` message
# uncolored, followed by the `end_msg` colored if specified and a newline
# afterwards
>>> print_hook_message(
'start',
postfix='postfix ',
end_msg='end',
end_color=color.RED,
use_color=True,
)
start...........................................................postfix end
"""
if bool(end_msg) == bool(end_len):
raise ValueError('Expected one of (`end_msg`, `end_len`)')
if end_msg is not None and (end_color is None or use_color is None):
raise ValueError(
'`end_color` and `use_color` are required with `end_msg`',
)
if end_len:
return start + '.' * (cols - len(start) - end_len - 1)
else:
return '{}{}{}{}\n'.format(
start,
'.' * (cols - len(start) - len(postfix) - len(end_msg) - 1),
postfix,
color.format_color(end_msg, end_color, use_color),
)
stdout_byte_stream = getattr(sys.stdout, 'buffer', sys.stdout)
def write(s, stream=stdout_byte_stream):
stream.write(five.to_bytes(s))
def write(s: str, stream: IO[bytes] = sys.stdout.buffer) -> None:
stream.write(s.encode())
stream.flush()
def write_line(s=None, stream=stdout_byte_stream, logfile_name=None):
output_streams = [stream]
if logfile_name:
ctx = open(logfile_name, 'ab')
output_streams.append(ctx)
else:
ctx = noop_context()
def write_line_b(
s: bytes | None = None,
stream: IO[bytes] = sys.stdout.buffer,
logfile_name: str | None = None,
) -> None:
with contextlib.ExitStack() as exit_stack:
output_streams = [stream]
if logfile_name:
stream = exit_stack.enter_context(open(logfile_name, 'ab'))
output_streams.append(stream)
with ctx:
for output_stream in output_streams:
if s is not None:
output_stream.write(five.to_bytes(s))
output_stream.write(s)
output_stream.write(b'\n')
output_stream.flush()
def write_line(s: str | None = None, **kwargs: Any) -> None:
write_line_b(s.encode() if s is not None else s, **kwargs)

View file

@ -1,35 +1,36 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import annotations
import os.path
from collections.abc import Mapping
from typing import NoReturn
from identify.identify import parse_shebang_from_file
class ExecutableNotFoundError(OSError):
def to_output(self):
return (1, self.args[0].encode('UTF-8'), b'')
def to_output(self) -> tuple[int, bytes, None]:
return (1, self.args[0].encode(), None)
def parse_filename(filename):
def parse_filename(filename: str) -> tuple[str, ...]:
if not os.path.exists(filename):
return ()
else:
return parse_shebang_from_file(filename)
def find_executable(exe, _environ=None):
def find_executable(
exe: str, *, env: Mapping[str, str] | None = None,
) -> str | None:
exe = os.path.normpath(exe)
if os.sep in exe:
return exe
environ = _environ if _environ is not None else os.environ
environ = env if env is not None else os.environ
if 'PATHEXT' in environ:
possible_exe_names = tuple(
exe + ext.lower() for ext in environ['PATHEXT'].split(os.pathsep)
) + (exe,)
exts = environ['PATHEXT'].split(os.pathsep)
possible_exe_names = tuple(f'{exe}{ext}' for ext in exts) + (exe,)
else:
possible_exe_names = (exe,)
@ -42,24 +43,30 @@ def find_executable(exe, _environ=None):
return None
def normexe(orig):
def _error(msg):
raise ExecutableNotFoundError('Executable `{}` {}'.format(orig, msg))
def normexe(orig: str, *, env: Mapping[str, str] | None = None) -> str:
def _error(msg: str) -> NoReturn:
raise ExecutableNotFoundError(f'Executable `{orig}` {msg}')
if os.sep not in orig and (not os.altsep or os.altsep not in orig):
exe = find_executable(orig)
exe = find_executable(orig, env=env)
if exe is None:
_error('not found')
return exe
elif not os.access(orig, os.X_OK):
_error('not found')
elif os.path.isdir(orig):
_error('is a directory')
elif not os.path.isfile(orig):
_error('not found')
elif not os.access(orig, os.X_OK): # pragma: win32 no cover
_error('is not executable')
else:
return orig
def normalize_cmd(cmd):
def normalize_cmd(
cmd: tuple[str, ...],
*,
env: Mapping[str, str] | None = None,
) -> tuple[str, ...]:
"""Fixes for the following issues on windows
- https://bugs.python.org/issue8557
- windows does not parse shebangs
@ -67,12 +74,12 @@ def normalize_cmd(cmd):
This function also makes deep-path shebangs work just fine
"""
# Use PATH to determine the executable
exe = normexe(cmd[0])
exe = normexe(cmd[0], env=env)
# Figure out the shebang from the resulting command
cmd = parse_filename(exe) + (exe,) + cmd[1:]
# This could have given us back another bare executable
exe = normexe(cmd[0])
exe = normexe(cmd[0], env=env)
return (exe,) + cmd[1:]

View file

@ -1,18 +1,18 @@
from __future__ import unicode_literals
from __future__ import annotations
import os.path
from typing import NamedTuple
class Prefix(object):
def __init__(self, prefix_dir):
self.prefix_dir = prefix_dir
class Prefix(NamedTuple):
prefix_dir: str
def path(self, *parts):
def path(self, *parts: str) -> str:
return os.path.normpath(os.path.join(self.prefix_dir, *parts))
def exists(self, *parts):
def exists(self, *parts: str) -> bool:
return os.path.exists(self.path(*parts))
def star(self, end):
def star(self, end: str) -> tuple[str, ...]:
paths = os.listdir(self.prefix_dir)
return tuple(path for path in paths if path.endswith(end))

View file

@ -1,288 +1,237 @@
from __future__ import unicode_literals
from __future__ import annotations
import io
import json
import logging
import os
import pipes
import shutil
import sys
import pkg_resources
from cached_property import cached_property
from cfgv import apply_defaults
from cfgv import validate
from collections.abc import Sequence
from typing import Any
import pre_commit.constants as C
from pre_commit import five
from pre_commit import git
from pre_commit.clientlib import is_local_repo
from pre_commit.clientlib import is_meta_repo
from pre_commit.all_languages import languages
from pre_commit.clientlib import load_manifest
from pre_commit.clientlib import MANIFEST_HOOK_DICT
from pre_commit.languages.all import languages
from pre_commit.languages.helpers import environment_dir
from pre_commit.clientlib import LOCAL
from pre_commit.clientlib import META
from pre_commit.hook import Hook
from pre_commit.lang_base import environment_dir
from pre_commit.prefix import Prefix
from pre_commit.store import Store
from pre_commit.util import clean_path_on_failure
from pre_commit.util import rmtree
logger = logging.getLogger('pre_commit')
def _state(additional_deps):
return {'additional_dependencies': sorted(additional_deps)}
def _state_filename_v1(venv: str) -> str:
return os.path.join(venv, '.install_state_v1')
def _state_filename(prefix, venv):
return prefix.path(
venv, '.install_state_v' + C.INSTALLED_STATE_VERSION,
)
def _state_filename_v2(venv: str) -> str:
return os.path.join(venv, '.install_state_v2')
def _read_state(prefix, venv):
filename = _state_filename(prefix, venv)
def _state(additional_deps: Sequence[str]) -> object:
return {'additional_dependencies': additional_deps}
def _read_state(venv: str) -> object | None:
filename = _state_filename_v1(venv)
if not os.path.exists(filename):
return None
else:
return json.loads(io.open(filename).read())
with open(filename) as f:
return json.load(f)
def _write_state(prefix, venv, state):
state_filename = _state_filename(prefix, venv)
staging = state_filename + 'staging'
with io.open(staging, 'w') as state_file:
state_file.write(five.to_text(json.dumps(state)))
# Move the file into place atomically to indicate we've installed
os.rename(staging, state_filename)
def _hook_installed(hook: Hook) -> bool:
lang = languages[hook.language]
if lang.ENVIRONMENT_DIR is None:
return True
def _installed(prefix, language_name, language_version, additional_deps):
language = languages[language_name]
venv = environment_dir(language.ENVIRONMENT_DIR, language_version)
venv = environment_dir(
hook.prefix,
lang.ENVIRONMENT_DIR,
hook.language_version,
)
return (
venv is None or (
_read_state(prefix, venv) == _state(additional_deps) and
language.healthy(prefix, language_version)
)
(
os.path.exists(_state_filename_v2(venv)) or
_read_state(venv) == _state(hook.additional_dependencies)
) and
not lang.health_check(hook.prefix, hook.language_version)
)
def _install_all(venvs, repo_url, store):
"""Tuple of (prefix, language, version, deps)"""
def _need_installed():
return tuple(
(prefix, language_name, version, deps)
for prefix, language_name, version, deps in venvs
if not _installed(prefix, language_name, version, deps)
def _hook_install(hook: Hook) -> None:
logger.info(f'Installing environment for {hook.src}.')
logger.info('Once installed this environment will be reused.')
logger.info('This may take a few minutes...')
lang = languages[hook.language]
assert lang.ENVIRONMENT_DIR is not None
venv = environment_dir(
hook.prefix,
lang.ENVIRONMENT_DIR,
hook.language_version,
)
# There's potentially incomplete cleanup from previous runs
# Clean it up!
if os.path.exists(venv):
rmtree(venv)
with clean_path_on_failure(venv):
lang.install_environment(
hook.prefix, hook.language_version, hook.additional_dependencies,
)
health_error = lang.health_check(hook.prefix, hook.language_version)
if health_error:
raise AssertionError(
f'BUG: expected environment for {hook.language} to be healthy '
f'immediately after install, please open an issue describing '
f'your environment\n\n'
f'more info:\n\n{health_error}',
)
# TODO: remove v1 state writing, no longer needed after pre-commit 3.0
# Write our state to indicate we're installed
state_filename = _state_filename_v1(venv)
staging = f'{state_filename}staging'
with open(staging, 'w') as state_file:
state_file.write(json.dumps(_state(hook.additional_dependencies)))
# Move the file into place atomically to indicate we've installed
os.replace(staging, state_filename)
open(_state_filename_v2(venv), 'a+').close()
def _hook(
*hook_dicts: dict[str, Any],
root_config: dict[str, Any],
) -> dict[str, Any]:
ret, rest = dict(hook_dicts[0]), hook_dicts[1:]
for dct in rest:
ret.update(dct)
lang = ret['language']
if ret['language_version'] == C.DEFAULT:
ret['language_version'] = root_config['default_language_version'][lang]
if ret['language_version'] == C.DEFAULT:
ret['language_version'] = languages[lang].get_default_version()
if not ret['stages']:
ret['stages'] = root_config['default_stages']
if languages[lang].ENVIRONMENT_DIR is None:
if ret['language_version'] != C.DEFAULT:
logger.error(
f'The hook `{ret["id"]}` specifies `language_version` but is '
f'using language `{lang}` which does not install an '
f'environment. '
f'Perhaps you meant to use a specific language?',
)
exit(1)
if ret['additional_dependencies']:
logger.error(
f'The hook `{ret["id"]}` specifies `additional_dependencies` '
f'but is using language `{lang}` which does not install an '
f'environment. '
f'Perhaps you meant to use a specific language?',
)
exit(1)
return ret
def _non_cloned_repository_hooks(
repo_config: dict[str, Any],
store: Store,
root_config: dict[str, Any],
) -> tuple[Hook, ...]:
def _prefix(language_name: str, deps: Sequence[str]) -> Prefix:
language = languages[language_name]
# pygrep / script / system / docker_image do not have
# environments so they work out of the current directory
if language.ENVIRONMENT_DIR is None:
return Prefix(os.getcwd())
else:
return Prefix(store.make_local(deps))
return tuple(
Hook.create(
repo_config['repo'],
_prefix(hook['language'], hook['additional_dependencies']),
_hook(hook, root_config=root_config),
)
for hook in repo_config['hooks']
)
def _cloned_repository_hooks(
repo_config: dict[str, Any],
store: Store,
root_config: dict[str, Any],
) -> tuple[Hook, ...]:
repo, rev = repo_config['repo'], repo_config['rev']
manifest_path = os.path.join(store.clone(repo, rev), C.MANIFEST_FILE)
by_id = {hook['id']: hook for hook in load_manifest(manifest_path)}
for hook in repo_config['hooks']:
if hook['id'] not in by_id:
logger.error(
f'`{hook["id"]}` is not present in repository {repo}. '
f'Typo? Perhaps it is introduced in a newer version? '
f'Often `pre-commit autoupdate` fixes this.',
)
exit(1)
hook_dcts = [
_hook(by_id[hook['id']], hook, root_config=root_config)
for hook in repo_config['hooks']
]
return tuple(
Hook.create(
repo_config['repo'],
Prefix(store.clone(repo, rev, hook['additional_dependencies'])),
hook,
)
for hook in hook_dcts
)
def _repository_hooks(
repo_config: dict[str, Any],
store: Store,
root_config: dict[str, Any],
) -> tuple[Hook, ...]:
if repo_config['repo'] in {LOCAL, META}:
return _non_cloned_repository_hooks(repo_config, store, root_config)
else:
return _cloned_repository_hooks(repo_config, store, root_config)
def install_hook_envs(hooks: Sequence[Hook], store: Store) -> None:
def _need_installed() -> list[Hook]:
seen: set[tuple[Prefix, str, str, tuple[str, ...]]] = set()
ret = []
for hook in hooks:
if hook.install_key not in seen and not _hook_installed(hook):
ret.append(hook)
seen.add(hook.install_key)
return ret
if not _need_installed():
return
with store.exclusive_lock():
# Another process may have already completed this work
need_installed = _need_installed()
if not need_installed: # pragma: no cover (race)
return
logger.info(
'Installing environment for {}.'.format(repo_url),
)
logger.info('Once installed this environment will be reused.')
logger.info('This may take a few minutes...')
for prefix, language_name, version, deps in need_installed:
language = languages[language_name]
venv = environment_dir(language.ENVIRONMENT_DIR, version)
# There's potentially incomplete cleanup from previous runs
# Clean it up!
if prefix.exists(venv):
shutil.rmtree(prefix.path(venv))
language.install_environment(prefix, version, deps)
# Write our state to indicate we're installed
state = _state(deps)
_write_state(prefix, venv, state)
for hook in _need_installed():
_hook_install(hook)
def _hook(*hook_dicts):
ret, rest = dict(hook_dicts[0]), hook_dicts[1:]
for dct in rest:
ret.update(dct)
version = pkg_resources.parse_version(ret['minimum_pre_commit_version'])
if version > C.VERSION_PARSED:
logger.error(
'The hook `{}` requires pre-commit version {} but version {} '
'is installed. '
'Perhaps run `pip install --upgrade pre-commit`.'.format(
ret['id'], version, C.VERSION_PARSED,
),
)
exit(1)
if ret['language_version'] == 'default':
language = languages[ret['language']]
ret['language_version'] = language.get_default_version()
return ret
def _hook_from_manifest_dct(dct):
dct = validate(apply_defaults(dct, MANIFEST_HOOK_DICT), MANIFEST_HOOK_DICT)
dct = _hook(dct)
return dct
class Repository(object):
def __init__(self, repo_config, store):
self.repo_config = repo_config
self.store = store
self.__installed = False
@classmethod
def create(cls, config, store):
if is_local_repo(config):
return LocalRepository(config, store)
elif is_meta_repo(config):
return MetaRepository(config, store)
else:
return cls(config, store)
@cached_property
def manifest_hooks(self):
repo, rev = self.repo_config['repo'], self.repo_config['rev']
repo_path = self.store.clone(repo, rev)
manifest_path = os.path.join(repo_path, C.MANIFEST_FILE)
return {hook['id']: hook for hook in load_manifest(manifest_path)}
@cached_property
def hooks(self):
for hook in self.repo_config['hooks']:
if hook['id'] not in self.manifest_hooks:
logger.error(
'`{}` is not present in repository {}. '
'Typo? Perhaps it is introduced in a newer version? '
'Often `pre-commit autoupdate` fixes this.'.format(
hook['id'], self.repo_config['repo'],
),
)
exit(1)
return tuple(
(hook['id'], _hook(self.manifest_hooks[hook['id']], hook))
for hook in self.repo_config['hooks']
)
def _prefix_from_deps(self, language_name, deps):
repo, rev = self.repo_config['repo'], self.repo_config['rev']
return Prefix(self.store.clone(repo, rev, deps))
def _venvs(self):
ret = []
for _, hook in self.hooks:
language = hook['language']
version = hook['language_version']
deps = hook['additional_dependencies']
ret.append((
self._prefix_from_deps(language, deps),
language, version, deps,
))
return tuple(ret)
def require_installed(self):
if not self.__installed:
_install_all(self._venvs(), self.repo_config['repo'], self.store)
self.__installed = True
def run_hook(self, hook, file_args):
"""Run a hook.
:param dict hook:
:param tuple file_args: all the files to run the hook on
"""
self.require_installed()
language_name = hook['language']
deps = hook['additional_dependencies']
prefix = self._prefix_from_deps(language_name, deps)
return languages[language_name].run_hook(prefix, hook, file_args)
class LocalRepository(Repository):
def _prefix_from_deps(self, language_name, deps):
"""local repositories have a prefix per hook"""
language = languages[language_name]
# pcre / pygrep / script / system / docker_image do not have
# environments so they work out of the current directory
if language.ENVIRONMENT_DIR is None:
return Prefix(git.get_root())
else:
return Prefix(self.store.make_local(deps))
@property
def manifest(self):
raise NotImplementedError
@cached_property
def hooks(self):
return tuple(
(hook['id'], _hook_from_manifest_dct(hook))
for hook in self.repo_config['hooks']
)
class MetaRepository(LocalRepository):
@cached_property
def manifest_hooks(self):
# The hooks are imported here to prevent circular imports.
from pre_commit.meta_hooks import check_hooks_apply
from pre_commit.meta_hooks import check_useless_excludes
def _make_entry(mod):
"""the hook `entry` is passed through `shlex.split()` by the
command runner, so to prevent issues with spaces and backslashes
(on Windows) it must be quoted here.
"""
return '{} -m {}'.format(pipes.quote(sys.executable), mod.__name__)
meta_hooks = [
{
'id': 'check-hooks-apply',
'name': 'Check hooks apply to the repository',
'files': C.CONFIG_FILE,
'language': 'system',
'entry': _make_entry(check_hooks_apply),
},
{
'id': 'check-useless-excludes',
'name': 'Check for useless excludes',
'files': C.CONFIG_FILE,
'language': 'system',
'entry': _make_entry(check_useless_excludes),
},
]
return {
hook['id']: _hook_from_manifest_dct(hook)
for hook in meta_hooks
}
@cached_property
def hooks(self):
for hook in self.repo_config['hooks']:
if hook['id'] not in self.manifest_hooks:
logger.error(
'`{}` is not a valid meta hook. '
'Typo? Perhaps it is introduced in a newer version? '
'Often `pip install --upgrade pre-commit` fixes this.'
.format(hook['id']),
)
exit(1)
return tuple(
(hook['id'], _hook(self.manifest_hooks[hook['id']], hook))
for hook in self.repo_config['hooks']
)
def repositories(config, store):
return tuple(Repository.create(x, store) for x in config['repos'])
def all_hooks(root_config: dict[str, Any], store: Store) -> tuple[Hook, ...]:
return tuple(
hook
for repo in root_config['repos']
for hook in _repository_hooks(repo, store, root_config)
)

View file

@ -1,4 +0,0 @@
{
"name": "pre_commit_dummy_package",
"version": "0.0.0"
}

View file

@ -1,6 +0,0 @@
Gem::Specification.new do |s|
s.name = 'pre_commit_dummy_package'
s.version = '0.0.0'
s.summary = 'dummy gem for pre-commit hooks'
s.authors = ['Anthony Sottile']
end

View file

@ -1,4 +0,0 @@
from setuptools import setup
setup(name='pre-commit-dummy-package', version='0.0.0')

View file

@ -0,0 +1,7 @@
Copyright 2021 RStudio, PBC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,6 @@
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => "PreCommitPlaceholder",
VERSION => "0.0.1",
);

View file

@ -0,0 +1,440 @@
local({
# the requested version of renv
version <- "0.12.5"
# the project directory
project <- getwd()
# avoid recursion
if (!is.na(Sys.getenv("RENV_R_INITIALIZING", unset = NA)))
return(invisible(TRUE))
# signal that we're loading renv during R startup
Sys.setenv("RENV_R_INITIALIZING" = "true")
on.exit(Sys.unsetenv("RENV_R_INITIALIZING"), add = TRUE)
# signal that we've consented to use renv
options(renv.consent = TRUE)
# load the 'utils' package eagerly -- this ensures that renv shims, which
# mask 'utils' packages, will come first on the search path
library(utils, lib.loc = .Library)
# check to see if renv has already been loaded
if ("renv" %in% loadedNamespaces()) {
# if renv has already been loaded, and it's the requested version of renv,
# nothing to do
spec <- .getNamespaceInfo(.getNamespace("renv"), "spec")
if (identical(spec[["version"]], version))
return(invisible(TRUE))
# otherwise, unload and attempt to load the correct version of renv
unloadNamespace("renv")
}
# load bootstrap tools
bootstrap <- function(version, library) {
# attempt to download renv
tarball <- tryCatch(renv_bootstrap_download(version), error = identity)
if (inherits(tarball, "error"))
stop("failed to download renv ", version)
# now attempt to install
status <- tryCatch(renv_bootstrap_install(version, tarball, library), error = identity)
if (inherits(status, "error"))
stop("failed to install renv ", version)
}
renv_bootstrap_tests_running <- function() {
getOption("renv.tests.running", default = FALSE)
}
renv_bootstrap_repos <- function() {
# check for repos override
repos <- Sys.getenv("RENV_CONFIG_REPOS_OVERRIDE", unset = NA)
if (!is.na(repos))
return(repos)
# if we're testing, re-use the test repositories
if (renv_bootstrap_tests_running())
return(getOption("renv.tests.repos"))
# retrieve current repos
repos <- getOption("repos")
# ensure @CRAN@ entries are resolved
repos[repos == "@CRAN@"] <- "https://cloud.r-project.org"
# add in renv.bootstrap.repos if set
default <- c(CRAN = "https://cloud.r-project.org")
extra <- getOption("renv.bootstrap.repos", default = default)
repos <- c(repos, extra)
# remove duplicates that might've snuck in
dupes <- duplicated(repos) | duplicated(names(repos))
repos[!dupes]
}
renv_bootstrap_download <- function(version) {
# if the renv version number has 4 components, assume it must
# be retrieved via github
nv <- numeric_version(version)
components <- unclass(nv)[[1]]
methods <- if (length(components) == 4L) {
list(
renv_bootstrap_download_github
)
} else {
list(
renv_bootstrap_download_cran_latest,
renv_bootstrap_download_cran_archive
)
}
for (method in methods) {
path <- tryCatch(method(version), error = identity)
if (is.character(path) && file.exists(path))
return(path)
}
stop("failed to download renv ", version)
}
renv_bootstrap_download_impl <- function(url, destfile) {
mode <- "wb"
# https://bugs.r-project.org/bugzilla/show_bug.cgi?id=17715
fixup <-
Sys.info()[["sysname"]] == "Windows" &&
substring(url, 1L, 5L) == "file:"
if (fixup)
mode <- "w+b"
utils::download.file(
url = url,
destfile = destfile,
mode = mode,
quiet = TRUE
)
}
renv_bootstrap_download_cran_latest <- function(version) {
repos <- renv_bootstrap_download_cran_latest_find(version)
message("* Downloading renv ", version, " from CRAN ... ", appendLF = FALSE)
info <- tryCatch(
utils::download.packages(
pkgs = "renv",
repos = repos,
destdir = tempdir(),
quiet = TRUE
),
condition = identity
)
if (inherits(info, "condition")) {
message("FAILED")
return(FALSE)
}
message("OK")
info[1, 2]
}
renv_bootstrap_download_cran_latest_find <- function(version) {
all <- renv_bootstrap_repos()
for (repos in all) {
db <- tryCatch(
as.data.frame(
x = utils::available.packages(repos = repos),
stringsAsFactors = FALSE
),
error = identity
)
if (inherits(db, "error"))
next
entry <- db[db$Package %in% "renv" & db$Version %in% version, ]
if (nrow(entry) == 0)
next
return(repos)
}
fmt <- "renv %s is not available from your declared package repositories"
stop(sprintf(fmt, version))
}
renv_bootstrap_download_cran_archive <- function(version) {
name <- sprintf("renv_%s.tar.gz", version)
repos <- renv_bootstrap_repos()
urls <- file.path(repos, "src/contrib/Archive/renv", name)
destfile <- file.path(tempdir(), name)
message("* Downloading renv ", version, " from CRAN archive ... ", appendLF = FALSE)
for (url in urls) {
status <- tryCatch(
renv_bootstrap_download_impl(url, destfile),
condition = identity
)
if (identical(status, 0L)) {
message("OK")
return(destfile)
}
}
message("FAILED")
return(FALSE)
}
renv_bootstrap_download_github <- function(version) {
enabled <- Sys.getenv("RENV_BOOTSTRAP_FROM_GITHUB", unset = "TRUE")
if (!identical(enabled, "TRUE"))
return(FALSE)
# prepare download options
pat <- Sys.getenv("GITHUB_PAT")
if (nzchar(Sys.which("curl")) && nzchar(pat)) {
fmt <- "--location --fail --header \"Authorization: token %s\""
extra <- sprintf(fmt, pat)
saved <- options("download.file.method", "download.file.extra")
options(download.file.method = "curl", download.file.extra = extra)
on.exit(do.call(base::options, saved), add = TRUE)
} else if (nzchar(Sys.which("wget")) && nzchar(pat)) {
fmt <- "--header=\"Authorization: token %s\""
extra <- sprintf(fmt, pat)
saved <- options("download.file.method", "download.file.extra")
options(download.file.method = "wget", download.file.extra = extra)
on.exit(do.call(base::options, saved), add = TRUE)
}
message("* Downloading renv ", version, " from GitHub ... ", appendLF = FALSE)
url <- file.path("https://api.github.com/repos/rstudio/renv/tarball", version)
name <- sprintf("renv_%s.tar.gz", version)
destfile <- file.path(tempdir(), name)
status <- tryCatch(
renv_bootstrap_download_impl(url, destfile),
condition = identity
)
if (!identical(status, 0L)) {
message("FAILED")
return(FALSE)
}
message("OK")
return(destfile)
}
renv_bootstrap_install <- function(version, tarball, library) {
# attempt to install it into project library
message("* Installing renv ", version, " ... ", appendLF = FALSE)
dir.create(library, showWarnings = FALSE, recursive = TRUE)
# invoke using system2 so we can capture and report output
bin <- R.home("bin")
exe <- if (Sys.info()[["sysname"]] == "Windows") "R.exe" else "R"
r <- file.path(bin, exe)
args <- c("--vanilla", "CMD", "INSTALL", "-l", shQuote(library), shQuote(tarball))
output <- system2(r, args, stdout = TRUE, stderr = TRUE)
message("Done!")
# check for successful install
status <- attr(output, "status")
if (is.numeric(status) && !identical(status, 0L)) {
header <- "Error installing renv:"
lines <- paste(rep.int("=", nchar(header)), collapse = "")
text <- c(header, lines, output)
writeLines(text, con = stderr())
}
status
}
renv_bootstrap_prefix <- function() {
# construct version prefix
version <- paste(R.version$major, R.version$minor, sep = ".")
prefix <- paste("R", numeric_version(version)[1, 1:2], sep = "-")
# include SVN revision for development versions of R
# (to avoid sharing platform-specific artefacts with released versions of R)
devel <-
identical(R.version[["status"]], "Under development (unstable)") ||
identical(R.version[["nickname"]], "Unsuffered Consequences")
if (devel)
prefix <- paste(prefix, R.version[["svn rev"]], sep = "-r")
# build list of path components
components <- c(prefix, R.version$platform)
# include prefix if provided by user
prefix <- Sys.getenv("RENV_PATHS_PREFIX")
if (nzchar(prefix))
components <- c(prefix, components)
# build prefix
paste(components, collapse = "/")
}
renv_bootstrap_library_root_name <- function(project) {
# use project name as-is if requested
asis <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT_ASIS", unset = "FALSE")
if (asis)
return(basename(project))
# otherwise, disambiguate based on project's path
id <- substring(renv_bootstrap_hash_text(project), 1L, 8L)
paste(basename(project), id, sep = "-")
}
renv_bootstrap_library_root <- function(project) {
path <- Sys.getenv("RENV_PATHS_LIBRARY", unset = NA)
if (!is.na(path))
return(path)
path <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT", unset = NA)
if (!is.na(path)) {
name <- renv_bootstrap_library_root_name(project)
return(file.path(path, name))
}
file.path(project, "renv/library")
}
renv_bootstrap_validate_version <- function(version) {
loadedversion <- utils::packageDescription("renv", fields = "Version")
if (version == loadedversion)
return(TRUE)
# assume four-component versions are from GitHub; three-component
# versions are from CRAN
components <- strsplit(loadedversion, "[.-]")[[1]]
remote <- if (length(components) == 4L)
paste("rstudio/renv", loadedversion, sep = "@")
else
paste("renv", loadedversion, sep = "@")
fmt <- paste(
"renv %1$s was loaded from project library, but this project is configured to use renv %2$s.",
"Use `renv::record(\"%3$s\")` to record renv %1$s in the lockfile.",
"Use `renv::restore(packages = \"renv\")` to install renv %2$s into the project library.",
sep = "\n"
)
msg <- sprintf(fmt, loadedversion, version, remote)
warning(msg, call. = FALSE)
FALSE
}
renv_bootstrap_hash_text <- function(text) {
hashfile <- tempfile("renv-hash-")
on.exit(unlink(hashfile), add = TRUE)
writeLines(text, con = hashfile)
tools::md5sum(hashfile)
}
renv_bootstrap_load <- function(project, libpath, version) {
# try to load renv from the project library
if (!requireNamespace("renv", lib.loc = libpath, quietly = TRUE))
return(FALSE)
# warn if the version of renv loaded does not match
renv_bootstrap_validate_version(version)
# load the project
renv::load(project)
TRUE
}
# construct path to library root
root <- renv_bootstrap_library_root(project)
# construct library prefix for platform
prefix <- renv_bootstrap_prefix()
# construct full libpath
libpath <- file.path(root, prefix)
# attempt to load
if (renv_bootstrap_load(project, libpath, version))
return(TRUE)
# load failed; inform user we're about to bootstrap
prefix <- paste("# Bootstrapping renv", version)
postfix <- paste(rep.int("-", 77L - nchar(prefix)), collapse = "")
header <- paste(prefix, postfix)
message(header)
# perform bootstrap
bootstrap(version, libpath)
# exit early if we're just testing bootstrap
if (!is.na(Sys.getenv("RENV_BOOTSTRAP_INSTALL_ONLY", unset = NA)))
return(TRUE)
# try again to load
if (requireNamespace("renv", lib.loc = libpath, quietly = TRUE)) {
message("* Successfully installed and loaded renv ", version, ".")
return(renv::load())
}
# failed to download or load renv; warn the user
msg <- c(
"Failed to find an renv installation: the project will not be loaded.",
"Use `renv::activate()` to re-initialize the project."
)
warning(paste(msg, collapse = "\n"), call. = FALSE)
})

View file

@ -0,0 +1,9 @@
channels:
- conda-forge
- defaults
dependencies:
# This cannot be empty as otherwise no environment will be created.
# We're using openssl here as it is available on all system and will
# most likely be always installed anyways.
# See https://github.com/conda/conda/issues/9487
- openssl

View file

@ -0,0 +1 @@
module pre-commit-placeholder-empty-module

View file

@ -0,0 +1,4 @@
{
"name": "pre_commit_placeholder_package",
"version": "0.0.0"
}

View file

@ -0,0 +1,12 @@
package = "pre-commit-package"
version = "dev-1"
source = {
url = "git+ssh://git@github.com/pre-commit/pre-commit.git"
}
description = {}
dependencies = {}
build = {
type = "builtin",
modules = {},
}

View file

@ -0,0 +1,6 @@
Gem::Specification.new do |s|
s.name = 'pre_commit_placeholder_package'
s.version = '0.0.0'
s.summary = 'placeholder gem for pre-commit hooks'
s.authors = ['Anthony Sottile']
end

View file

@ -0,0 +1,4 @@
name: pre_commit_empty_pubspec
environment:
sdk: '>=2.12.0'
executables: {}

View file

@ -0,0 +1,20 @@
{
"R": {
"Version": "4.0.3",
"Repositories": [
{
"Name": "CRAN",
"URL": "https://cran.rstudio.com"
}
]
},
"Packages": {
"renv": {
"Package": "renv",
"Version": "0.12.5",
"Source": "Repository",
"Repository": "CRAN",
"Hash": "5c0cdb37f063c58cdab3c7e9fbb8bd2c"
}
}
}

View file

@ -0,0 +1,4 @@
from setuptools import setup
setup(name='pre-commit-placeholder-package', version='0.0.0', py_modules=[])

View file

@ -1,171 +1,20 @@
#!/usr/bin/env python
"""File generated by pre-commit: https://pre-commit.com"""
from __future__ import print_function
#!/usr/bin/env bash
# File generated by pre-commit: https://pre-commit.com
# ID: 138fd403232d2ddd5efb44317e38bf03
import distutils.spawn
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
Z40 = '0' * 40
ID_HASH = '138fd403232d2ddd5efb44317e38bf03'
# start templated
CONFIG = None
HOOK_TYPE = None
INSTALL_PYTHON = None
SKIP_ON_MISSING_CONFIG = None
INSTALL_PYTHON=''
ARGS=(hook-impl)
# end templated
HERE="$(cd "$(dirname "$0")" && pwd)"
ARGS+=(--hook-dir "$HERE" -- "$@")
class EarlyExit(RuntimeError):
pass
class FatalError(RuntimeError):
pass
def _norm_exe(exe):
"""Necessary for shebang support on windows.
roughly lifted from `identify.identify.parse_shebang`
"""
with open(exe, 'rb') as f:
if f.read(2) != b'#!':
return ()
try:
first_line = f.readline().decode('UTF-8')
except UnicodeDecodeError:
return ()
cmd = first_line.split()
if cmd[0] == '/usr/bin/env':
del cmd[0]
return tuple(cmd)
def _run_legacy():
if HOOK_TYPE == 'pre-push':
stdin = getattr(sys.stdin, 'buffer', sys.stdin).read()
else:
stdin = None
legacy_hook = os.path.join(HERE, '{}.legacy'.format(HOOK_TYPE))
if os.access(legacy_hook, os.X_OK):
cmd = _norm_exe(legacy_hook) + (legacy_hook,) + tuple(sys.argv[1:])
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE if stdin else None)
proc.communicate(stdin)
return proc.returncode, stdin
else:
return 0, stdin
def _validate_config():
cmd = ('git', 'rev-parse', '--show-toplevel')
top_level = subprocess.check_output(cmd).decode('UTF-8').strip()
cfg = os.path.join(top_level, CONFIG)
if os.path.isfile(cfg):
pass
elif SKIP_ON_MISSING_CONFIG or os.getenv('PRE_COMMIT_ALLOW_NO_CONFIG'):
print(
'`{}` config file not found. '
'Skipping `pre-commit`.'.format(CONFIG),
)
raise EarlyExit()
else:
raise FatalError(
'No {} file was found\n'
'- To temporarily silence this, run '
'`PRE_COMMIT_ALLOW_NO_CONFIG=1 git ...`\n'
'- To permanently silence this, install pre-commit with the '
'--allow-missing-config option\n'
'- To uninstall pre-commit run '
'`pre-commit uninstall`'.format(CONFIG),
)
def _exe():
with open(os.devnull, 'wb') as devnull:
for exe in (INSTALL_PYTHON, sys.executable):
try:
if not subprocess.call(
(exe, '-c', 'import pre_commit.main'),
stdout=devnull, stderr=devnull,
):
return (exe, '-m', 'pre_commit.main', 'run')
except OSError:
pass
if distutils.spawn.find_executable('pre-commit'):
return ('pre-commit', 'run')
raise FatalError(
'`pre-commit` not found. Did you forget to activate your virtualenv?',
)
def _rev_exists(rev):
return not subprocess.call(('git', 'rev-list', '--quiet', rev))
def _pre_push(stdin):
remote = sys.argv[1]
opts = ()
for line in stdin.decode('UTF-8').splitlines():
_, local_sha, _, remote_sha = line.split()
if local_sha == Z40:
continue
elif remote_sha != Z40 and _rev_exists(remote_sha):
opts = ('--origin', local_sha, '--source', remote_sha)
else:
# First ancestor not found in remote
first_ancestor = subprocess.check_output((
'git', 'rev-list', '--max-count=1', '--topo-order',
'--reverse', local_sha, '--not', '--remotes={}'.format(remote),
)).decode().strip()
if not first_ancestor:
continue
else:
cmd = ('git', 'rev-list', '--max-parents=0', local_sha)
roots = set(subprocess.check_output(cmd).decode().splitlines())
if first_ancestor in roots:
# pushing the whole tree including root commit
opts = ('--all-files',)
else:
cmd = ('git', 'rev-parse', '{}^'.format(first_ancestor))
source = subprocess.check_output(cmd).decode().strip()
opts = ('--origin', local_sha, '--source', source)
if opts:
return opts
else:
# An attempt to push an empty changeset
raise EarlyExit()
def _opts(stdin):
fns = {
'commit-msg': lambda _: ('--commit-msg-filename', sys.argv[1]),
'pre-commit': lambda _: (),
'pre-push': _pre_push,
}
stage = HOOK_TYPE.replace('pre-', '')
return ('--config', CONFIG, '--hook-stage', stage) + fns[HOOK_TYPE](stdin)
def main():
retv, stdin = _run_legacy()
try:
_validate_config()
return retv | subprocess.call(_exe() + _opts(stdin))
except EarlyExit:
return retv
except FatalError as e:
print(e.args[0])
return 1
if __name__ == '__main__':
exit(main())
if [ -x "$INSTALL_PYTHON" ]; then
exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}"
elif command -v pre-commit > /dev/null; then
exec pre-commit "${ARGS[@]}"
else
echo '`pre-commit` not found. Did you forget to activate your virtualenv?' 1>&2
exit 1
fi

Some files were not shown because too many files have changed in this diff Show more