git代码格式化上传

848 阅读7分钟

引言

遇到的问题

在项目开发过程中,代码不规范,诸如一些缩进、使用tab或空格、最大长度、及换行符等,空白在表达式和语句中的运用空格、换行等,未做任何限制也可以提交代码

许多项目都有自己的编码风格准则,多人协助,不同的人有不同的风格,导致代码可读性较差

解决思路

pylint可以查找编程错误,帮助实施编码标准,并提供简单的重构建议代码

git-pylint-commit-hook可以设置满足提交代码的limit分数值,提交代码时若未达到limit,则提交失败,按照建议规范后重新提交达到limit后方可提交成功

解决方案

Git提交代码前格式校验git-pylint-commit-hook

第一步 下载安装pylint和git-pylint-commit-hook

pip install pylint

pip install git-pylint-commit-hook

第二步

下载成功后进入项目.git/hooks路径下进行配置

1、新建文件pre-commit,并写入如下内容

cd .git/hooks

#新建文件pre-commit

vim pre-commit
#!/bin/sh

git-pylint-commit-hook --limit=9.0 --pylintrc=.pylintrc

2、新建文件.pylintrc,并写入如下内容

vim .pylintrc

ln -sf $(pwd)/.hooks/pre-commit .git/hooks/

#关联到github的commit事件,也就是执行commit指令时,自动运行pre-commit脚本。

应用示例

以test_repetition.py为例,将不规范的代码按照提示完善成可以提交的代码

#! /usr/bin/env python
#coding=utf-8
__author__ = 'zhongyaqi'
from collections import Counter #引入Counter

def deal_repetition(a):
        # a= ['4175726040','417572604','417675161','417675666','417572604','417572604','417675161','417675666','417572604','417675161','417675666','417572604','417572604']
        b = dict(Counter(a))
        print(b.items())
        print ([key for key,value in b.items()if value > 1]) #只展示重复元素
        print ({key:value for key,value in b.items()if value > 1}) #展现重复元素和重复次数
        return ({key:value for key,value in b.items()if value > 1}) #展现重复元素和重复次数

if __name__ == '__main__':
    deal_repetition()

git commit 结果

$ git commit -m "test git pylint"
Running pylint on src/testpylint/common_method.py (file 1/2)..  -11/10.00       FAILED
************* Module common_method
src\testpylint\common_method.py:7:0: C0301: Line too long (789/100) (line-too-long)
src\testpylint\common_method.py:8:0: W0311: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
src\testpylint\common_method.py:9:0: W0311: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
src\testpylint\common_method.py:10:0: W0311: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
src\testpylint\common_method.py:10:14: C0326: No space allowed before bracket
        print ([key for key,value in b.items()if value > 1]) #ֻչʾ▒ظ▒Ԫ▒▒
              ^ (bad-whitespace)
src\testpylint\common_method.py:10:27: C0326: Exactly one space required after comma
        print ([key for key,value in b.items()if value > 1]) #ֻչʾ▒ظ▒Ԫ▒▒
                           ^ (bad-whitespace)
src\testpylint\common_method.py:11:0: W0311: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
src\testpylint\common_method.py:11:14: C0326: No space allowed before bracket
        print ({key:value for key,value in b.items()if value > 1}) #չ▒▒▒ظ▒Ԫ▒غ▒▒ظ▒▒▒▒▒
              ^ (bad-whitespace)
src\testpylint\common_method.py:11:33: C0326: Exactly one space required after comma
        print ({key:value for key,value in b.items()if value > 1}) #չ▒▒▒ظ▒Ԫ▒غ▒▒ظ▒▒▒▒▒
                                 ^ (bad-whitespace)
src\testpylint\common_method.py:12:0: W0311: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
src\testpylint\common_method.py:12:34: C0326: Exactly one space required after comma
        return ({key:value for key,value in b.items()if value > 1}) #չ▒▒▒ظ▒Ԫ▒غ▒▒ظ▒▒▒▒▒
                                  ^ (bad-whitespace)
src\testpylint\common_method.py:15:0: C0304: Final newline missing (missing-final-newline)
src\testpylint\common_method.py:1:0: C0114: Missing module docstring (missing-module-docstring)
src\testpylint\common_method.py:6:0: C0103: Argument name "a" doesn't conform to snake_case naming style (invalid-name)
src\testpylint\common_method.py:6:0: C0116: Missing function or method docstring (missing-function-docstring)
src\testpylint\common_method.py:8:8: C0103: Variable name "b" doesn't conform to snake_case naming style (invalid-name)
src\testpylint\common_method.py:15:4: E1120: No value for argument 'a' in function call (no-value-for-parameter)

按照提示修改后代码如下

#! /usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'zhongyaqi'
from collections import Counter #引入Counter
def deal_repetition(idlist):
    ''' This method checks for duplicate id
    '''
    # IDLIST = ['4175726040','417572604','417675161','417675666','417572604','417572604',
    # '417675161','417675666','417572604','417675161','417675666','417572604','417572604']
    id_dict = dict(Counter(idlist))
    print(id_dict.items())
    print([key for key, value in id_dict.items()if value > 1]) #只展示重复元素
    print({key:value for key, value in id_dict.items()if value > 1}) #展现重复元素和重复次数
    return ({key:value for key, value in id_dict.items()if value > 1}) #展现重复元素和重复次数

if __name__ == '__main__':
    IDLIST = ['4175726040', '417572604', '417675161', '4175726040',
              '417572604', '417675161', '4175726040', '417572604', '417675161']
    deal_repetition(IDLIST)


执行git commit后结果如下

zhongyaqi@010A1612190049 MINGW64 /e/PythonProject/gitTest/gittest (dev-login)
$ git commit -m "test git pylint"
Running pylint on src/testpylint/common_method.py (file 1/1)..  9.1/10.00       PASSED
[dev-login 4b56be4] test git pylint
 2 files changed, 135 insertions(+), 35 deletions(-)
 rewrite src/testpylint/common_method.py (94%)

那问题来了到底什么是pylint,什么又是PEP8,什么又是git-pylint-commit-hook,接下来参考官网大致介绍下~

什么是pylint

Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8,具体信息,请参阅参考资料)和有潜在问题的代码。

官网上是这么介绍的

Pylint is a Python static code analysis tool which looks for programming errors, helps enforcing a coding standard, sniffs for code smells and offers simple refactoring suggestions.

Pylint是Python静态代码分析工具,它可以查找编程错误,帮助实施编码标准,嗅探代码并提供简单的重构建议

It’s highly configurable, having special pragmas to control its errors and warnings from within your code, as well as from an extensive configuration file. It is also possible to write your own plugins for adding your own checks or for extending pylint in one way or another.

它是高度可配置的,具有特殊的编译指示,可以从您的代码以及广泛的配置文件中控制其错误和警告。 也可以编写自己的插件以添加自己的检查或以一种或另一种方式扩展pylint。

什么是PEP8

PEP8给出了Python代码的编码约定,该Python代码包含主Python发行版中的标准库。 请参阅随附的信息性PEP,它描述了Python [1]的C实现中C代码的样式准则。

该样式指南会随着时间的流逝而发展,因为会确定其他约定,而过去的约定会因语言本身的更改而过时。

如下约定了代码布局,包含缩进、使用tab或空格、最大长度、及换行符等,空白在表达式和语句中的运用,等具体可参考文章底部附的官网地址

  • Code Lay-out
    • Indentation
    • Tabs or Spaces?
    • Maximum Line Length
    • Should a Line Break Before or After a Binary Operator?
    • Blank Lines
    • Source File Encoding
    • Imports
    • Module Level Dunder Names
  • String Quotes
  • Whitespace in Expressions and Statements
    • Pet Peeves
    • Other Recommendations
  • When to Use Trailing Commas

什么是git-pylint-commit-hook

git-pylint-commit-hook will automatically find your pylint configuration files, according to the pylint configuration file default read order. Any configuration found for the project will be used in the git-pylint-commit-hook.

将根据pylint配置文件的默认读取顺序自动找到您的pylint配置文件。 为项目找到的任何配置都将在git-pylint-commit-hook中使用。

使用--pylintrc命令行选项定义自定义pylint配置文件

pylint configuration Settings are loaded by default from the .pylintrc file in the root of your repo.

[pre-commit-hook]
command=custom_pylint
params=--rcfile=/path/to/another/pylint.rc
limit=8.0
command is for the actual command, for instance if pylint is not installed globally, but is in a virtualenv inside the project itself.

params lets you pass custom parameters to pylint

limit is the lowest value which you want to allow for a pylint score. Any lower than this, and the script will fail and won’t commit.

git-pylint-commit-hook命令行选项

--limit LIMIT         Score limit, files with a lower score will stop the
                      commit. Default: 8.0
--pylint PYLINT       Path to pylint executable. Default: pylint
--pylintrc PYLINTRC   Path to pylintrc file. Options in the pylintrc will
                      override the command line parameters. Default:
                      pylintsearch order
--pylint-params PYLINT_PARAMS
                      Custom pylint parameters to add to the pylint command
--suppress-report     Suppress report output if pylint fails
--always-show-violations
                      Show violations in case of pass as well
--version             Print current version number
--ignore IGNORED_FILES
                      Add regex to blacklist files or directories, allowing
                      to avoid running pylint those files.
--stash               Stash any unstaged changes while linting (changes are
                      unstashed automatically unless the process is forcibly
                      killed)

参考文档

pypi.org/project/pyl…

git-pylint-commit-hook.readthedocs.io/en/latest/u…

www.python.org/dev/peps/pe…


猜你喜欢