Giter Site home page Giter Site logo

lucas-c / pre-commit-hooks Goto Github PK

View Code? Open in Web Editor NEW
111.0 6.0 48.0 218 KB

git pre-commit hooks

Home Page: http://pre-commit.com/hooks.html

License: MIT License

Python 94.74% Groovy 2.14% CSS 1.38% Jinja 0.93% C++ 0.60% PHP 0.20%
pre-commit git-hooks crlf tabs license

pre-commit-hooks's Introduction

build status

A few useful git hooks to integrate with pre-commit.

⚠️ ⚠️ This hook, since v1.5.2, requires pre-commit 3.2.0 or superior. If you get an error like Expected one of ... but got: 'pre-commit', check this issue: #83

⚠️ The last version of this hook to support Python 2.7 & 3.6 is v1.1.15

Hooks specific to a language, or with more dependencies have been extracted into separate repos:

Usage

- repo: https://github.com/Lucas-C/pre-commit-hooks
  rev: v1.5.5
  hooks:
    - id: forbid-crlf
    - id: remove-crlf
    - id: forbid-tabs
    - id: remove-tabs
      args: [--whitespaces-count, '2']  # defaults to: 4
    - id: chmod
      args: ['644']
      files: \.md$
    - id: insert-license
      files: \.groovy$
      args:
        - --license-filepath
        - src/license_header.txt        # defaults to: LICENSE.txt
        - --comment-style
        - //                            # defaults to:  #
        - --use-current-year
        - --no-extra-eol                # see below

insert-license

Comment styles

The following styles can be used for example:

  • For Java / Javascript / CSS/ C / C++ (multi-line comments) set /*| *| */ ;
  • For Java / Javascript / C / C++ (single line comments) set // ;
  • For HTML files: <!--| ~| --> ;
  • For Python: # ;
  • For Jinja templates: '{#||#}' .

How to specify in how many lines to search for the license header in each file

You can add --detect-license-in-X-top-lines=<X> to search for the license in top X lines (default 5).

Removing old license and replacing it with a new one

In case you want to remove the comment headers introduced by insert-license hook, e.g. because you want to change the wording of your LICENSE.txt and update the comments in your source files:

  1. Temporarily add the --remove-header arg in your .pre-commit-config.yaml ;
  2. Run the hook on all your files: pre-commit run insert-license --all-files ;
  3. Remove the --remove-header arg and update your LICENSE.txt ;
  4. Re-run the hook on all your files.

Handling years flexibly

You can add --use-current-year to change how the hook treats years in the headers:

  • When inserting a header, the current year will always be inserted regardless of the year listed in the license file.
  • When modifying a file that already has a header, the hook will ensure the current year is listed in the header by using a range. For instance, 2015 or 2015-2018 would get updated to 2015-2023 in the year 2023.
  • When removing headers, the licenses will be removed regardless of the years they contain -- as if they used the year currently present in the license file.

You can also use --allow-past-years to allow stale years to be unchanged. Using both --allow-past-years and --use-current-year issues a year range as described above.

No extra EOL

The --no-extra-eol argument prevents the insertion of an additional End-of-Line (EOL) character at the end of the license header; see issue #70.

Fuzzy license matching

In some cases your license files can contain several slightly different variants of the license - either containing slight modifications or differently broken lines of the license text.
By default the plugin does exact matching when searching for the license and in such case it will add second license on top - leaving the non-perfectly matched one in the source code.
You can prevent that and add --fuzzy-match-generates-todo flag in which case fuzzy matching is performed based on Levenshtein distance of set of tokens in expected and actual license text (partial match in two sets is used).
The license is detected if the ratio is > than --fuzzy-ratio-cut-off parameter (default 85) - ration corresponds roughly to how well the expected and actual license match (scale 0 - 100). Additionally --fuzzy-match-extra-lines-to-check lines in this case are checked for the license in case it has lines broken differently and takes more lines (default 3).

If a fuzzy match is found (and no exact match), a TODO comment is inserted at the beginning of the match found. The comment inserted can be overridden by --fuzzy-match-todo-comment=<COMMENT> flag.
By default the inserted comment is TODO: This license is not consistent with license used in the project Additionally instructions on what to do are inserted in this case.
By default instructions are:
Delete the inconsistent license and above line and rerun pre-commit to insert a good license..
You can change it via --fuzzy-match-todo-instructions argument of the hook.

When the TODO comment is committed, pre-commit will fail with appropriate message. The check will fails systematically if the --fuzzy-match-generates-todo flag is set or not.
You will need to remove the TODO comment and license so that it gets re-added in order to get rid of the error.

License insertion can be skipped altogether if the file contains the SKIP LICENSE INSERTION in the first X top lines. This can also be overridden by --skip-license-insertion-comment=<COMMENT> flag.

Multiple license files

If more than one --license-filepath argument is specified, the checks are performed as follows:

  1. First, an exact match is pursued, checking the 1st license file, then the 2nd, and so on. If a match is found, the normal behavior is followed, as if the matched license file was the only license file specified.

  2. If no exact match is found, then the software resorts to fuzzy matching. Again, as soon as a match is found, the normal behavior is followed, as if the fuzzy-matched license file was the only license file specified.

  3. Finally, if neither exact nor fuzzy matches are found, the content of the first license file is inserted.

Handy shell functions

pre_commit_all_cache_repos () {  # Requires sqlite3
    sqlite3 -header -column ~/.cache/pre-commit/db.db < <(echo -e ".width 50\nSELECT repo, ref, path FROM repos ORDER BY repo;")
}

pre_commit_local_cache_repos () {  # Requires PyYaml & sqlite3
    < $(git rev-parse --show-toplevel)/.pre-commit-config.yaml \
        python -c "from __future__ import print_function; import sys, yaml; print('\n'.join(h['repo']+' '+h['sha'] for h in yaml.load(sys.stdin) if h['repo'] != 'local'))" \
        | while read repo sha; do
            echo $repo
            sqlite3 ~/.cache/pre-commit/db.db "SELECT ref, path FROM repos WHERE repo = '$repo' AND ref = '$sha';"
            echo
        done
}

pre_commit_db_rm_repo () {  # Requires sqlite3
    local repo=${1?'Missing parameter'}
    local repo_path=$(sqlite3 ~/.cache/pre-commit/db.db "SELECT path FROM repos WHERE repo LIKE '%${repo}%';")
    if [ -z "$repo_path" ]; then
        echo "No repository known for repo $repo"
        return 1
    fi
    rm -rf "$repo_path"
    sqlite3 ~/.cache/pre-commit/db.db "DELETE FROM repos WHERE repo LIKE '%${repo}%';";
}

Useful local hooks

Forbid / remove some unicode characters

- repo: local
  hooks:
    - id: forbid-unicode-non-breaking-spaces
      name: Detect unicode non-breaking space character U+00A0 aka M-BM-
      language: system
      entry: perl -ne 'print if $m = /\xc2\xa0/; $t ||= $m; END{{exit $t}}'
      files: ''
    - id: remove-unicode-non-breaking-spaces
      name: Remove unicode non-breaking space character U+00A0 aka M-BM-
      language: system
      entry: perl -pi* -e 's/\xc2\xa0/ /g && ($t = 1) && print STDERR $_; END{{exit
        $t}}'
      files: ''
    - id: forbid-en-dashes
      name: Detect the EXTREMELY confusing unicode character U+2013
      language: system
      entry: perl -ne 'print if $m = /\xe2\x80\x93/; $t ||= $m; END{{exit $t}}'
      files: ''
    - id: remove-en-dashes
      name: Remove the EXTREMELY confusing unicode character U+2013
      language: system
      entry: perl -pi* -e 's/\xe2\x80\x93/-/g && ($t = 1) && print STDERR $_; END{{exit
        $t}}'
      files: ''

Bash syntax validation

- repo: local
  hooks:
  - id: check-bash-syntax
    name: Check Shell scripts syntax correctness
    language: system
    entry: bash -n
    files: \.sh$

For Groovy-like Jenkins pipelines

- repo: local
  hooks:
  - id: forbid-abstract-classes-and-traits
    name: Ensure neither abstract classes nor traits are used
    language: pygrep
    entry: "^(abstract|trait) "
    files: ^src/.*\.groovy$

Rationale: abstract classes & traits do not work in Jenkins pipelines : cf. https://issues.jenkins-ci.org/browse/JENKINS-39329 & https://issues.jenkins-ci.org/browse/JENKINS-46145 .

- repo: local
  hooks:
  - id: force-JsonSlurperClassic
    name: Ensure JsonSlurperClassic is used instead of non-serializable JsonSlurper
    language: pygrep
    entry: JsonSlurper[^C]
    files: \.groovy$

Rationale: cf. http://stackoverflow.com/a/38439681/636849

- repo: local
  hooks:
    - id: Jenkinsfile-linter
      name: Check Jenkinsfile following the scripted-pipeline syntax using Jenkins
        API
      files: Jenkinsfile
      language: system
      entry: sh -c '! curl --silent $JENKINS_URL/job/MyPipelineName/job/master/1/replay/checkScriptCompile
        --user $JENKINS_USER:$JENKINS_TOKEN --data-urlencode value@Jenkinsfile |
        grep -F "\"status\":\"fail\""'

Note: the $JENKINS_TOKEN can be retrieved from $JENKINS_URL/user/$USER_NAME/configure

Beware, in 1 case on 6 I faced this unsolved bug with explictly-loaded libraries: https://issues.jenkins-ci.org/browse/JENKINS-42730 .

Also, there is also a linter for the declarative syntax: https://jenkins.io/doc/book/pipeline/development/#linter .

Forbid some Javascript keywords for browser retrocompatibility issues

- repo: local
  hooks:
    - id: js-forbid-const
      name: The const keyword is not supported by IE10
      language: pygrep
      entry: 'const '
      files: \.js$
    - id: js-forbid-let
      name: The let keyword is not supported by IE10
      language: pygrep
      entry: 'let '
      files: \.js$

CSS

- repo: local
  hooks:
    - id: css-forbid-px
      name: In CSS files, use rem or % over px
      language: pygrep
      entry: px
      files: \.css$
    - id: ot-sanitize-fonts
      name: Calling ot-sanitise on otf/ttf/woff/woff2 font files
      language: system
      entry: sh -c 'type ot-sanitise >/dev/null
        && for font in "$@";
        do echo "$font";
        ot-sanitise "$font"; done
        || echo "WARNING Command ot-sanitise not found - skipping check"'
      files: \.(otf|ttf|woff|woff2)$

Some Angular 1.5 checks

- repo: local
  hooks:
    - id: angular-forbid-apply
      name: In AngularJS, use $digest over $apply
      language: pygrep
      entry: \$apply
      files: \.js$
    - id: angular-forbid-ngrepeat-without-trackby
      name: In AngularJS, ALWAYS use 'track by' with ng-repeat
      language: pygrep
      entry: ng-repeat(?!.*track by)
      files: \.html$
    - id: angular-forbid-ngmodel-with-no-dot
      name: In AngularJS, whenever you have ng-model there's gotta be a dot in
        there somewhere
      language: pygrep
      entry: ng-model="?[^.]+[" ]
      files: \.html$

Development

The GitHub releases form the historical ChangeLog.

Releasing a new version

  1. Bump version in README.md, setup.py & .pre-commit-config.yaml
  2. git commit -nam "New release $version" && git tag $version && git push && git push --tags
  3. Publish a GitHub release.

pre-commit-hooks's People

Contributors

antoined avatar aostrowski avatar cclauss avatar chriskuehl avatar daisylb avatar daniela-winkler avatar frazar avatar gadgetsteve avatar henryiii avatar jumanjiman avatar lucas-c avatar maxbachmann avatar mdeweerd avatar mjpieters avatar njzjz avatar oerp-odoo avatar potiuk avatar snoopj avatar vorburger avatar xaver-k avatar yiftachkarkason avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

pre-commit-hooks's Issues

Using pre-commit to insert a license header

Objective is to add a license to each new file staged with pre-commit.

I've created a .pre-commit-config.yaml file with the following:

repos:

  # license header
  - repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.1.12
    hooks:
      - id: insert-license
        name: "Insert license header in C++ source files"
        args: [--license-filepath=util/header.txt,
               '--comment-style=/*| *| */',
               --detect-license-in-X-top-lines=16]
        types_or: [c, c++, objective-c]

The git repo has pre-commit 'installed', created a new file, staged it, ran pre-commit and results return with:

Insert license header in C++ source files............(no files to check)Skipped

What else might I need to add for the hook script to find the files to add the license header?

Thanks

Python 3 support

Currently all hooks fail.
Fix suggestion:

non_printable_chars = ''.join(c for c in stuff if c not in string.printable)

But false CRLF & tabs positives are still detected:

CRLF end-lines remover.................................................................................................................................................................Failed
hookid: remove-crlf

CRLF end-lines have been successfully removed. Now aborting the commit.
You can check the changes made. Then simply "git add --update ." and re-commit

Failing test test_badopt

While updating PRs as per request, I now have this new error during tests.

I a checking on how to fix that, just registering this as an issue to explain why the future change is there.
This breaks commit because of more stringent pre-commit target (all tests must pass).

________________________________________ test_badopt[a/b] _________________________________________

arg = 'a/b'

    @pytest.mark.parametrize(('arg'), ('', 'a.b', 'a/b'))
    def test_badopt(arg):
        with pytest.raises(FileNotFoundError):
>           remove_crlf([arg])

tests/remove_crlf_test.py:26:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
pre_commit_hooks/remove_crlf.py:24: in main
    text_files = [f for f in args.filenames if is_textfile(f)]
pre_commit_hooks/remove_crlf.py:24: in <listcomp>
    text_files = [f for f in args.filenames if is_textfile(f)]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

filename = 'a/b', blocksize = 512

    def is_textfile(filename, blocksize=512):
        if any(filename.endswith(ext) for ext in KNOWN_BINARY_FILE_EXTS):
            return False
>       with open(filename, 'rb') as text_file:
E       NotADirectoryError: [Errno 20] Not a directory: 'a/b'

pre_commit_hooks/utils.py:8: NotADirectoryError

breaking changes in 1.5.2 and 1.5.3 - InvalidManifestError

It seem that something is not working as expected in the latest version

pre-commit version: 3.1.0
git --version: git version 2.41.0
sys.version:
    3.10.10 (main, Feb  7 2023, 12:19:31) [GCC 12.2.0]
sys.executable: /nix/store/syz2y6j53y5hpzbs7l0965zwxshi8iyl-python3-3.10.10/bin/python3.10
os.name: posix
sys.platform: linux

error information

An error has occurred: InvalidManifestError: 
==> File ~/.cache/pre-commit/repofbad9rxa/.pre-commit-hooks.yaml
==> At Hook(id='forbid-crlf')
==> At key: stages
==> At index 0
=====> Expected one of commit, commit-msg, manual, merge-commit, post-checkout, post-commit, post-merge, post-rewrite, prepare-commit-msg, push but got: 'pre-commit'
Check the log at ~/.cache/pre-commit/pre-commit.log

It seems, that version constraint check is not working as it should, but I am sure it is not related to the hook but to the framework.

make `forbid-tabs` and `replace-tabs` accept an exclusion list

I am trying to use this for a project to make sure i have consistency in tabs v spaces. However, there are certain tab-separated- value files that I would want to keep untouched. I can't find some way to exclude those files. Having an exclusion argument would be very helpful.

1.1.9 Broken

v1.1.9 is breaking on a repo I work on where it was working fine before. I was able to make the problem go away by changing the version back to v1.1.6.

I also tried out v1.1.9 on a blank repo and got (something that looked like) essentially the same error message:

$ pre-commit run --all-files
[INFO] Installing environment for https://github.com/Lucas-C/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
An unexpected error has occurred: CalledProcessError: command: ('/my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/bin/python', '-mpip', 'install', '.')
return code: 1
expected return code: 0
stdout:
    Processing /my/home/dir/.cache/pre-commit/repo3cbmr7ik
    Collecting fuzzywuzzy
      Using cached fuzzywuzzy-0.18.0-py2.py3-none-any.whl (18 kB)
    Collecting python-Levenshtein
      Using cached python-Levenshtein-0.12.0.tar.gz (48 kB)
    Requirement already satisfied: setuptools in ./py_env-python3.8/lib/python3.8/site-packages (from python-Levenshtein->pre-commit-hooks==1.1.9) (49.2.1)
    Building wheels for collected packages: pre-commit-hooks, python-Levenshtein
      Building wheel for pre-commit-hooks (setup.py): started
      Building wheel for pre-commit-hooks (setup.py): finished with status 'done'
      Created wheel for pre-commit-hooks: filename=pre_commit_hooks-1.1.9-py3-none-any.whl size=12895 sha256=38f2e6cae6e56f8fa3348d481cd95a57e48476ebb5891730e5e39541b675b176
      Stored in directory: /tmp/pip-ephem-wheel-cache-tzngl1rg/wheels/e6/7e/1e/03ca43d281b207ead0872d956fe0c6d7a93b107772a89de835
      Building wheel for python-Levenshtein (setup.py): started
      Building wheel for python-Levenshtein (setup.py): finished with status 'error'
      Running setup.py clean for python-Levenshtein
    Successfully built pre-commit-hooks
    Failed to build python-Levenshtein
    Installing collected packages: fuzzywuzzy, python-Levenshtein, pre-commit-hooks
        Running setup.py install for python-Levenshtein: started
        Running setup.py install for python-Levenshtein: finished with status 'error'
    
stderr:
      ERROR: Command errored out with exit status 1:
       command: /my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-nwoa_9c9
           cwd: /tmp/pip-install-r2bjrp57/python-levenshtein/
      Complete output (31 lines):
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.linux-x86_64-3.8
      creating build/lib.linux-x86_64-3.8/Levenshtein
      copying Levenshtein/__init__.py -> build/lib.linux-x86_64-3.8/Levenshtein
      copying Levenshtein/StringMatcher.py -> build/lib.linux-x86_64-3.8/Levenshtein
      running egg_info
      writing python_Levenshtein.egg-info/PKG-INFO
      writing dependency_links to python_Levenshtein.egg-info/dependency_links.txt
      writing entry points to python_Levenshtein.egg-info/entry_points.txt
      writing namespace_packages to python_Levenshtein.egg-info/namespace_packages.txt
      writing requirements to python_Levenshtein.egg-info/requires.txt
      writing top-level names to python_Levenshtein.egg-info/top_level.txt
      reading manifest file 'python_Levenshtein.egg-info/SOURCES.txt'
      reading manifest template 'MANIFEST.in'
      warning: no previously-included files matching '*pyc' found anywhere in distribution
      warning: no previously-included files matching '*so' found anywhere in distribution
      warning: no previously-included files matching '.project' found anywhere in distribution
      warning: no previously-included files matching '.pydevproject' found anywhere in distribution
      writing manifest file 'python_Levenshtein.egg-info/SOURCES.txt'
      copying Levenshtein/_levenshtein.c -> build/lib.linux-x86_64-3.8/Levenshtein
      copying Levenshtein/_levenshtein.h -> build/lib.linux-x86_64-3.8/Levenshtein
      running build_ext
      building 'Levenshtein._levenshtein' extension
      creating build/temp.linux-x86_64-3.8
      creating build/temp.linux-x86_64-3.8/Levenshtein
      x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/include -I/usr/include/python3.8 -c Levenshtein/_levenshtein.c -o build/temp.linux-x86_64-3.8/Levenshtein/_levenshtein.o
      unable to execute 'x86_64-linux-gnu-gcc': No such file or directory
      error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
      ----------------------------------------
      ERROR: Failed building wheel for python-Levenshtein
    DEPRECATION: Could not build wheels for python-Levenshtein which do not use PEP 517. pip will fall back to legacy 'setup.py install' for these. pip 21.0 will remove support for this functionality. A possible replacement is to fix the wheel build issue reported above. You can find discussion regarding this at https://github.com/pypa/pip/issues/8368.
        ERROR: Command errored out with exit status 1:
         command: /my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-rtq37kz2/install-record.txt --single-version-externally-managed --compile --install-headers /my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/include/site/python3.8/python-Levenshtein
             cwd: /tmp/pip-install-r2bjrp57/python-levenshtein/
        Complete output (31 lines):
        running install
        running build
        running build_py
        creating build
        creating build/lib.linux-x86_64-3.8
        creating build/lib.linux-x86_64-3.8/Levenshtein
        copying Levenshtein/__init__.py -> build/lib.linux-x86_64-3.8/Levenshtein
        copying Levenshtein/StringMatcher.py -> build/lib.linux-x86_64-3.8/Levenshtein
        running egg_info
        writing python_Levenshtein.egg-info/PKG-INFO
        writing dependency_links to python_Levenshtein.egg-info/dependency_links.txt
        writing entry points to python_Levenshtein.egg-info/entry_points.txt
        writing namespace_packages to python_Levenshtein.egg-info/namespace_packages.txt
        writing requirements to python_Levenshtein.egg-info/requires.txt
        writing top-level names to python_Levenshtein.egg-info/top_level.txt
        reading manifest file 'python_Levenshtein.egg-info/SOURCES.txt'
        reading manifest template 'MANIFEST.in'
        warning: no previously-included files matching '*pyc' found anywhere in distribution
        warning: no previously-included files matching '*so' found anywhere in distribution
        warning: no previously-included files matching '.project' found anywhere in distribution
        warning: no previously-included files matching '.pydevproject' found anywhere in distribution
        writing manifest file 'python_Levenshtein.egg-info/SOURCES.txt'
        copying Levenshtein/_levenshtein.c -> build/lib.linux-x86_64-3.8/Levenshtein
        copying Levenshtein/_levenshtein.h -> build/lib.linux-x86_64-3.8/Levenshtein
        running build_ext
        building 'Levenshtein._levenshtein' extension
        creating build/temp.linux-x86_64-3.8
        creating build/temp.linux-x86_64-3.8/Levenshtein
        x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/include -I/usr/include/python3.8 -c Levenshtein/_levenshtein.c -o build/temp.linux-x86_64-3.8/Levenshtein/_levenshtein.o
        unable to execute 'x86_64-linux-gnu-gcc': No such file or directory
        error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
        ----------------------------------------
    ERROR: Command errored out with exit status 1: /my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r2bjrp57/python-levenshtein/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-rtq37kz2/install-record.txt --single-version-externally-managed --compile --install-headers /my/home/dir/.cache/pre-commit/repo3cbmr7ik/py_env-python3.8/include/site/python3.8/python-Levenshtein Check the logs for full command output.
    
Check the log at /my/home/dir/.cache/pre-commit/pre-commit.log

(I replaced references to my home directory with /my/home/dir)

These were the contents of .pre-commit-config.yaml:

-   repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.1.9
    hooks:
    -   id: remove-tabs

Rename this repo?

AFAIK pre-commit hooks repo should not have "pre-commit" in the name they usually use mirrors or some other convention.

Project depends (implicitly) on both `python-Levenshtein` and `python-Levenshtein-wheels`

The changes introduced by #18 do not apply to .pre-commit-config.yaml, which still declares a dependency on python-Levenshtein. Probably the config needs to be updated to declare python-Levenshtein-wheels as well, since it is a more recent fork of the former.

This came up in the #python channel on Freenode's IRC network when a user was confused by the apparent need for gcc caused by this change. It confused a few of us for a bit and I thought I'd document the problem here.

Aside: fuzzywuzzy works perfectly well without any extension modules, and depends on this speedup as an extra. Perhaps this project could do the same? 😇

Forbid/remove tabs doesn't like .gitmodules

I believe .gitmodules should be excluded by default as well.

By the way, in the documentation, sha: is given, but that was replaced by rev: for pre-commit a long time ago (1.7+). It still works, but it would be nice to show the newer, recommended name. Ideally should be changed in the little script shown in the readme, too, I think.

Possible incorrect formatting from remove tabs

If lines contain spaces followed by tabs then replacing with a fixed number of spaces will miss-align which can be a problem for some file types, e.g. fi a file contains 2 lines such as:
"
Line 1
Line 2
"
Then visually, with tab spacing of 4, it will be:

    Line 1
    Line 2

But after tab replacement will become:

    Line 1
     Line 2

Suggest adding:

def line_tab_strip(line: bytes, whitespaces_count: int) -> bytes:
    """Remove tabs and replace with whitespaces_count spaces maintaining alignment"""
    spaces = b" " * whitespaces_count
    return spaces.join(sect.strip(b' ') for sect in line.split(b"\t"))

And changing the line:

    lines = [line.replace(b'\t', b' ' * whitespaces_count) for line in lines]

With something like:

    lines = [line_tab_strip(line, whitespaces_count) for line in lines]

This should give the expected alignment even on multi column lines such as: \tCol 1\t Col 2 \tCol 3 \n

insert_license - write file back in original encoding

In insert_license.py we can red:

    for encoding in ('utf8', 'ISO-8859-1'):  # we could use the chardet library to support more encodings

But when writeing the file back, utf8 is used, so the original file encoding could be changed.

It would be better to remember the original encoding to reuse it on writeback.

insert-license hook ignores top-level files selected by `types` or `types_or`

https://github.com/Lucas-C/pre-commit-hooks/blob/master/.pre-commit-hooks.yaml#L33 has line files: '.*/.*'. This overrides defaults and ignores top level files from project (top-level files don't have / in path when pre-commit is run).

Example when insert-license hook omits useful files (example uses language: fail just to print filenames passed by pre-commit):

repos:
  - repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.3.0
    hooks:
      - id: insert-license
        types: [makefile]
        language: fail
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.2.0
    hooks:
      - id: end-of-file-fixer
        types: [makefile]
        language: fail

The output for running pre-commit:

$ pre-commit run --all
Insert license in comments...............................................Failed
- hook id: insert-license
- exit code: 1

insert_license

doc/Makefile
src/Makefile

fix end of files.........................................................Failed
- hook id: end-of-file-fixer
- exit code: 1

end-of-file-fixer

Makefile
doc/Makefile
src/Makefile

Note fix end of files hook from https://github.com/pre-commit/pre-commit-hooks prints top-level Makefile while insert-license doesn't.

Trailing newline handling in insert-license

Currently there is a rather annoying issue in how a LICENCE.txt file with a trailing newline is handled.

Our LICENSE.txt contains, in abstract, with newlines made explicit:

line1\n
line2\n
line3\n

so the last line ends in a newline. Nothing unusual here.

But this causes the hook to want to insert license headers twice when using a three-element comment style header, like /*| *| */.

That's because the above LICENSE.txt content is then transformed to the prefixed_license list:

['/*\n',
 ' * line1\n',
 ' * line2\n',
 ' * line3\n',
 '\n */']

Note the \n character on the last line. The first time you add a licence header things go sort-of fine, and the files end up with

/*\n
 * line1\n
 * line2\n
 * line3\n
\n
 */\n

File contents start here

Note the extra, empty newline in the header. That by itself is a little irksome, we didn't need an extra newline there.

But next time such a file is modified at the commit hook runs again, you now can't detect that the header is already present, because now the find_license_header_index() function fails to account for the extra newline. There isn't an extra element in the prefixed_license for that line, it's a prefixed newline in the wrong place, the start of an entry.

That's because the source lines \n (the empty line inserted by the script), and \n #} (the line in the prefixed_license list) can never line up. The newline exists in prefixed_license, but not on its own.

The work-around is to commit a LICENSE.txt file with no trailing newline.

A proper fix would add the newline to the last line of the license lines only if there isn't one there already, rather than prefix comment_end. comment_end itself also needs a newline character though:

if not prefixed_license[-1].endswith(eol):
    prefixed_license[-1] += eol  # make sure the license text ends in a newline
if comment_start:
    prefixed_license = [comment_start + eol] + prefixed_license
if comment_end:
    prefixed_license = prefixed_license + [comment_end + eol]

pre-commit fails to install/run due to failures within python-Levenshtein-wheels

pre-commit fails to install/run due to failures within python-Levenshtein-wheels.

This is with a fresh install.

Trying to make a batch file with the following script to install in a brand new repository:
Setup.bat.txt

The pre-commit file which is running is:
pre-commit-config.yaml.txt

[INFO] Initializing environment for https://github.com/Lucas-C/pre-commit-hooks.
[INFO] Initializing environment for https://github.com/pre-commit/mirrors-clang-format.
[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/Lucas-C/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
An unexpected error has occurred: CalledProcessError: command: ('C:\\Users\\vikram.s\\.cache\\pre-commit\\repoovyiw2ie\\py_env-python3.12\\Scripts\\python.EXE', '-mpip', 'install', '.')
return code: 1
stdout:
    Processing c:\users\vikram.s\.cache\pre-commit\repoovyiw2ie
      Installing build dependencies: started
      Installing build dependencies: finished with status 'done'
      Getting requirements to build wheel: started
      Getting requirements to build wheel: finished with status 'done'
      Preparing metadata (pyproject.toml): started
      Preparing metadata (pyproject.toml): finished with status 'done'
    Collecting fuzzywuzzy (from pre-commit-hooks==1.1.13)
      Using cached fuzzywuzzy-0.18.0-py2.py3-none-any.whl (18 kB)
    Collecting python-Levenshtein-wheels (from pre-commit-hooks==1.1.13)
      Using cached python-Levenshtein-wheels-0.13.2.tar.gz (38 kB)
      Installing build dependencies: started
      Installing build dependencies: finished with status 'done'
      Getting requirements to build wheel: started
      Getting requirements to build wheel: finished with status 'done'
      Preparing metadata (pyproject.toml): started
      Preparing metadata (pyproject.toml): finished with status 'done'
    Building wheels for collected packages: pre-commit-hooks, python-Levenshtein-wheels
      Building wheel for pre-commit-hooks (pyproject.toml): started
      Building wheel for pre-commit-hooks (pyproject.toml): finished with status 'done'
      Created wheel for pre-commit-hooks: filename=pre_commit_hooks-1.1.13-py3-none-any.whl size=13349 sha256=91ac1545b3fff0b50058b0ec874ab0b35fc363527103ba137a7c1d6d1bd16128
      Stored in directory: C:\Users\vikram.s\AppData\Local\Temp\pip-ephem-wheel-cache-i8c3zsty\wheels\9a\c8\b2\ce802d52810509a2c2e44a876b77a65e7cac1f1c8851fe3632
      Building wheel for python-Levenshtein-wheels (pyproject.toml): started
      Building wheel for python-Levenshtein-wheels (pyproject.toml): finished with status 'error'
    Successfully built pre-commit-hooks
    Failed to build python-Levenshtein-wheels

Attached the log file:
pre-commit.log

Dropped py2 in patch version?

I was just looking over v1.1.13...v1.1.14 and it looks like you dropped support for python2 in a patch version. Seems like that should've been done in a minor or major version. Just wanted to point that out. It doesn't affect me, but also doesn't conform to change standards of semver.

An error has occurred: InvalidManifestError

Hey 👋

since a few weeks, I have an error when running my pre-commit :

An error has occurred: InvalidManifestError: 
==> File /Users/alexisotton/.cache/pre-commit/repoiey05pzu/.pre-commit-hooks.yaml
==> At Hook(id='forbid-crlf')
==> At key: stages
==> At index 0
=====> Expected one of commit, commit-msg, manual, merge-commit, post-checkout, post-commit, post-merge, post-rewrite, prepare-commit-msg, push but got: 'pre-commit'

Here are my env infos :

pre-commit --version: 3.5.0
git --version: 2.24.3
python3 --version: Python 3.11.6
sys.platform: MacOS monterey 12.6.7

Here is my pre-commit-config.yaml part in error :

- repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.5.4
    hooks:
      - id: forbid-crlf
        exclude_types: [svg]
      - id: remove-crlf
        exclude_types: [svg]

I've looked at this similar issue, but my pre-commitversion look good

Thank's for your help

insert-license should not add a LF at the end of the license header file if it does not have one, to prevent an ugly empty separator line

Salut! I ❤️ LOVE insert-license - this is GREAT! I just have 1 very small gripe with... 😃 I wish it wouldn't insert a new line! Details:

  - repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.4.2
    hooks:
      - id: insert-license
        files: \.java$
        args:
          - --comment-style
          - /*| *| */
          - --license-filepath
          - LICENSE-header.txt
          - --fuzzy-match-generates-todo
          - --use-current-year

That LICENSE-header.txt file DOES NOT end with a LF (e.g. perl -p -i -e 'chomp if eof' LICENSE-header.txt; and I've double-checked with hexedit that the last byte is not a 0A (LF), but a 2E for .). The *.java files which do not contain a license header will be updated to like this by insert-license:

...

 * limitations under the License.
 */

package dev.enola.k8s;

The empty line after */ before package bothers me (yeah, I know, hair splitting; sorry!) - and seems to be added by insert-license? Would it be possible to avoid it doing that, if the given file does not end in a newline?

I'm currently working around this by removing that separator line (and that's kept and not put back), but I wish it wouldn't add it in the first place...

Thank You again for insert-license!

Tabs are replaced in this binary string

$ python -V
Python 3.10.2
# .pre-commit-config.yaml
repos:
-   repo: git://github.com/Lucas-C/pre-commit-hooks.git
    rev: v1.1.13
    hooks:
    -   id: remove-tabs
# example.py
TEST_DATA = b"AZ	SHN	999	SH	Saint Helena	410	7460	AF	.sh	AUD	Pound	290	STHL 1ZZ"

After running this, the tabs are replace with spaces.

$ pre-commit run remove-tabs --files example.py

add ignore-files argument to remove-crlf?

Generally I want to replace/remove CRLF in my repos. However, there are times where I require CRLF endings in files. It would be very beneficial to have an --ignore-files argument that would take file names or globs and ignore them.

chmod hook conflicts with shell chmod in a python virtual env

In a Python virtualenv configuration, the new chmod hook is placed in the virtualenv bin directory.

source .venv/bin/activate

add .venv/bin at the start of the $PATH env var.

Then using chmod command in shell fails :

chmod u+x
Incorrect octal permissions provided in configuration: invalid literal for int() with base 8: 'u+x'
which chmod
.venv/bin/chmod

Workaround: downgrade to version v1.4.2

Proposed solution: rename chmod hook to pre_commit_chmod ?

IndexError while removing license file in files containing just the license header

Hi, and thanks for this nice tool!

I found a bug, when trying to remove the header of a file which only contains the header (typically __init__.py), I get following error:

  File "site-packages/pre_commit_hooks/insert_license.py", line 206, in license_found
    if src_file_content[license_header_index + len(license_info.prefixed_license)].strip():
IndexError: list index out of range

if src_file_content[license_header_index + len(license_info.prefixed_license)].strip():

I added a -1 in the equation and it fixes the issue. I tried to go a bit further by fixing how license_header_index is computed, but I am afraid I don’t get everything, so I would prefer that you fix it the best way.

Thanks.

Is there a way of defining a string in the hooks args instead of --license-filepath

This:

- repo: https://github.com/Lucas-C/pre-commit-hooks
  rev: v1.5.3
  hooks:
    - id: insert-license
      files: ./*
      args:
        - --license-filepath
        - LICENSE
        - --use-current-year

does not work for me as my LICENSE 600+ lines long and I don't want to add a txt file to the repo simply for this. Is there a way of specifying a string to be inserted? Something like

- repo: https://github.com/Lucas-C/pre-commit-hooks
  rev: v1.5.3
  hooks:
    - id: insert-license
      files: ./*
      args:
        - --license-string
        - "MyName RepoName AGPL3.0 License"
        - --use-current-year

?

insert_license - Only first year range is replaced in existing license

When a license exists in a file and insert_license with --use-current-year updates the year, it only does so for the first line containing a year:

 * Copyright © 2020-2022 Steve Luamo <[email protected]>
 * Copyright © 2015-2022 Leve Stuamo <[email protected]>

becomes (note the 2022 in the second line):

 * Copyright © 2020-2023 Steve Luamo <[email protected]>
 * Copyright © 2015-2022 Leve Stuamo <[email protected]>

This seems to be intentional since the comment in try_update_year_range() says "The change will affect only the first line containing years". But I'm not sure why this limitation exists and whether it could be lifted.

pre-commit has changed from hooks.yaml -> .pre-commit-hooks.yaml

Hello pre-commit hook implementer!

In version 0.12.0 pre-commit has changed the default location for the file formerly known as hooks.yaml to make it more convincing for others to add more hooks.

As such, a migration has to (unfortunately) occur.

For maximum compatibility it is suggested to cp hooks.yaml .pre-commit-hooks.yaml (at least for the migration period). A copy is suggested over a symlink unless you do not care for windows compatibility (and I wouldn't blame you!).

Once the migration period is over (or you no longer care to support old versions of pre-commit), the hooks.yaml file is no longer necessary and may be deleted.

See pre-commit/pre-commit#470 for more details

Thanks again for contributing to the pre-commit ecosystem, we couldn't do it without you :)
Anthony

split commit hooks for less dependencies

Hi,

I believe your tab 2 space pre-commit module is very usefull. However, as this project has python-Levenshtein-wheels installing that on my Windows 10 machine resulted in many C++ compiler elements that had to be installed and many stackoverflow post to be read.

I would be a lot more convienient if the simple hooks could be installed easily and just if i want the license replacement, I actually pull in the dependecy for Levenshtein.

Thanks

[Enhancement] Update multiple licence year ends in one run.

I have two lines with the licence year in my headers:

/* Copyright (c) 2012-2023 Dummy             */
/*********************************************/
/* @copyright Copyright (c) 2012-2023 Dummy  */

On the first pre-commit execution, the first line is updated.
On the second pre-commit execution, the second line is updated.
On the third run, the commit is performed.

If one of the pre-commit runs could be avoided by changing both lines in a single run that would be great.

This is my configuration:

  - repo: https://github.com/Lucas-C/pre-commit-hooks
    rev: v1.5.1
    hooks:
      - id: insert-license
        files: ^(.*\.(php))$
        args:
          - --license-filepath
          - doc/LICENSE
          - --use-current-year
          - --comment-style
          - ''
          - --no-space-in-comment-prefix
          - --fuzzy-match-extra-lines-to-check
          - '10'
          - --insert-license-after-regex
          - ^<\?php$

Note: My licence file is already updated like this:

/* Copyright (c) 2012-2024 Dummy             */
/*********************************************/
/* @copyright Copyright (c) 2012-2024 Dummy  */

Expected string got int

Config:

  - repo: https://github.com/Lucas-C/pre-commit-hooks
    sha: v1.1.7
    hooks:
      - id: forbid-crlf
        files: \.groovy$
      - id: forbid-tabs
        files: \.groovy$
      - id: insert-license
        files: \.groovy$
      - id: remove-crlf
        files: \.groovy$
      - id: remove-tabs
        args: [--whitespaces-count, 2]  # Defaults to: 4.
        files: \.groovy$

Error on pre-commit run -a:

An error has occurred: InvalidConfigError:
==> File .pre-commit-config.yaml
==> At Config()
==> At key: repos
==> At Repository(repo='https://github.com/Lucas-C/pre-commit-hooks')
==> At key: hooks
==> At Hook(id='remove-tabs')
==> At key: args
==> At index 1
=====> Expected string got int
Check the log at ~/.cache/pre-commit/pre-commit.log

Error when using `exclude_types`, but not `exclude`

When using this hook like

- repo: https://github.com/Lucas-C/pre-commit-hooks
  rev: v1.5.4
  hooks:
    - id: forbid-tabs
      exclude: dic$

it works fine. However when I use

- repo: https://github.com/Lucas-C/pre-commit-hooks
  rev: v1.5.4
  hooks:
    - id: forbid-tabs
      exclude_types:
        - dic

I get the following error and I cannot work out why. Any ideas?

An error has occurred: InvalidConfigError:
==> File ../../.cache/pre-commit/repo0b9skro8/precommit/general/general-hooks.yml
==> At Config()
==> At key: repos
==> At Repository(repo='https://github.com/Lucas-C/pre-commit-hooks')
==> At key: hooks
==> At Hook(id='forbid-tabs')
==> At key: exclude_types
==> At index 0
=====> Type tag 'dic' is not recognized.  Try upgrading identify and pre-commit?
Check the log at /Users/paddy/.cache/pre-commit/pre-commit.log

Enhancement: fix-tabs limit by filename ending

certain languages and files are unfortunately very picky about tab characters
makefiles are a prime example, though there are some systems to somewhat fix that in newer versions.

It would be nice to be able to limit the only *.php for example

When copyright year changes, insert-license simply puts new copy of whole license file at the top.

Currently doing this:

diff --git a/foo b/foo
index daf7c00..c1b0299 100644
--- a/foo
+++ b/foo
@@ -1,3 +1,7 @@
+// Copyright (c) 2022 by Foo Inc.
+// Confidential and proprietary, see LICENSE for details.
+// SPDX-License-Identifier: LicenseRef-Foo-Internal-Only
+
 // Copyright (c) 2021 by Foo Inc.
 // Confidential and proprietary, see LICENSE for details.
 // SPDX-License-Identifier: LicenseRef-Foo-Internal-Only

Would be preferable to allow for the detection of year change and only change that part.

Based on https://reuse.software/faq/#years-copyright , This would need to detect either a single year, or a range of years.

Ignore commit amend message files in .git when running forbid-tabs & co by default

When amending to an existing commit, forbid-tabs detects tabs in the git/COMMIT_EDITMSG and fails the check. The tab is part of the message that is auto-generated by git to inform about the history of the commit, so it is not the user's fault.

Example output:

$ git commit --amend
No-tabs checker..........................................................Failed 
- hook id: forbid-tabs
- exit code: 1

Tabs detected in file: .git/COMMIT_EDITMSG 

Example git message:

title

original message

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Mon Apr 24 12:40:35 2023 +0200
#
# On branch xxxxxxxxxxxxxxx
#
# Changes to be committed:
#       modified:   ../some_file.hpp   <- This line has a tab in the terminal, but github helpfully replaces tabs with spaces....
#

The file should probably be ignored by the hook by default. However, I am not sure what the best approach for that would be here.
Options are to either ignoring the specific file (might not be enough in similar scenarios) OR a set of specific files (which ones) or everything in .git (might break some use-cases).

Feature Request (insert_license): Dynamic years in license

Hi folks,

first of all - thanks for this tool :)

I propose a new flag --dynamic-years which determines the start year of the copyright time range automatically - based on when the file was first tracked with GIT. If a start year is already present, it is not touched. The end year is automatically set to the current year (--use-current-year is activated automatically when --dynamic-years is present).

The syntax in the License.txt could be as follows:

Copyright (C) {year_start}-{year_end}, PearCorp, Inc.
SPDX-License-Identifier: LicenseRef-PearCorp

To be discussed: I also considered a flag to determine just the start year dynamically. This, however, would lead to some inconsistencies regarding the logic to update year ranges. This is due to the fact that update_year_range only works when --use-current-year is supplied (update_year_range=args.use_current_year). My proposal, therefore, features a flag to determine both years automatically.

To be discussed: Whether the {year_start} / {year_end} syntax should be used. Currently, this syntax isn't used in this repository but I think that it suits this case well as it clearly communicates in the LICENSE file that the start and end year is not set there, but determined automatically. However, I'm open to suggestions.

Use cases: When introducing license headers to a new repository, all year ranges per file are adjusted automatically.
Simply run pre-commit run insert-license --all-files.

If you agree that this feature is useful, I'm happy to contribute by creating a PR.

Edit: Introduce {year_end} directly in the proposal.

Add LICENSE after "file header" for php

When adding the lines to PHP files starting with <?php, the license should be added after that line.

Currently the license is inserted at the top of the PHP file.

I did not see an option to specify this case.

Matching multiple license headers?

Hi folks,

Firstly, thanks for building and maintaining this useful tool -- it's great! 😄 One question I have, is there support for matching multiple license files? i.e., check if the license in a file is one of several options? We have use cases where different files require slightly different licenses.

I see that there's support for fuzzy matching (https://github.com/Lucas-C/pre-commit-hooks#fuzzy-license-matching), but it would be great to see if we could support exact matching with multiple potential licenses? Does this already exist, or is it something that would require changes? (Apologies if I've missed it!)

Thanks for your help!

Avoid space insertion when inserting licence

I like my licence header to have "/**********************" or "#################" to emphasize it.

However a space is systematically added either resulting in "/* ****" or "# #####". I also tried using --comment-style '' but then I get a space before the imported lines, so I get " /*****" or " ######" .

Can this be avoided (or an option be added to avoid that)?

Thanks.

Newline is forced between license comment and code

Even if I force remove newline on my license_header.txt file (in other words to not have newline as ending), it still adds newline between code. There should be an option to ignore newline. So it would be possible to get this:

############
# My LICENSE
############
import blabla

instead of:

############
# My LICENSE
############

import blabla

insert_license - Inserting new license with --use-current-year replaces start years in ranges

When a file has no license and one gets inserted with --use-current-year enabled, all years are replaced with the current year. This destroys year ranges.

Input LICENSE.txt:

 Copyright © 2020-2022 Steve Luamo <[email protected]>
 Copyright © 2015-2022 Leve Stuamo <[email protected]>

Inserted license comment, if none exists:

 /*
  * Copyright © 2023-2023 Steve Luamo <[email protected]>
  * Copyright © 2023-2023 Leve Stuamo <[email protected]>
  */

Consider changing the output of `insert-license` to only mention what the script did, instead of instructing the user or mentioning what pre-commit will do

This would more closely match how various other pre-commit hooks and linters operate, such as https://github.com/psf/black, https://github.com/PyCQA/isort, https://github.com/asottile/blacken-docs and https://github.com/pre-commit/mirrors-prettier.

It avoids making assumptions about the user's workflow (eg: I don't use the CLI, but instead a GUI for inspecting files before committing them). It also does not make the assumption that pre-commit is being run as a git hook, since it can be run as a CLI tool as well (eg: pre-commit run --all-files, like we do in pip's CI).

The current output of insert-license on one of my projects is:

Some sources were modified by the hook ['docs/conf.py', 'src/lutra/errors.py', 'src/lutra/_demo_module.py', 'src/lutra/navigation.py'] 
Now aborting the commit.
You should check the changes made. Then simply "git add --update ." and re-commit


Some sources were modified by the hook ['src/lutra/__init__.py', 'src/lutra/_sphinxext.py', 'src/lutra/styles.py'] 
Now aborting the commit.
You should check the changes made. Then simply "git add --update ." and re-commit

IMO, it would be much nicer if the output were:

Modified files:
  docs/conf.py
  src/lutra/__init__.py
  src/lutra/_demo_module.py
  src/lutra/_sphinxext.py
  src/lutra/errors.py
  src/lutra/navigation.py
  src/lutra/styles.py
You should check the changes made.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.