기본 콘텐츠로 건너뛰기

[git] hook을 이용하여 코드 스타일 검사 - pep8 검증



pep을 사용해서 매번 검사를 하는건 꽤나 귀찮은 일입니다. 이러한 검사 과정을 특정 행위를 하기 이전에 먼저 수행함으로써 귀찮음을 해결 할 수 있습니다. git hook의 pre-commit을 이용하여 커밋이 되기 이전에 pep 검사를 수행 후 결과에 따라 커밋 결정 유무를 판단을 해보도록 하는 hook을 만들어 보갰습니다.

$ git status

On branch master

Your branch is ahead of 'origin/master' by 1 commit.

  (use "git push" to publish your local commits)

Changes to be committed:

  (use "git reset HEAD ..." to unstage)
 new file:   .app.py.swp
    new file:   app.py
    new file:   app2.py
커밋 대상의 파일을 보실 수 있습니다.
status를 통해 app.py, app2.py가 add되어 cache되었음을 알 수 있습니다.

어떤 코드가 cache되었는지 확인을 하기 위해서는 diff의 명령어를 사용하면 됩니다.

$ git diff --stahed 또는 git diff --cached # 같은 결과입니다.

diff --git a/.app.py.swp b/.app.py.swp
new file mode 100644
index 0000000..6cf6386
Binary files /dev/null and b/.app.py.swp differ
diff --git a/app.py b/app.py
new file mode 100644
index 0000000..aa07c85
--- /dev/null
+++ b/app.py
@@ -0,0 +1,41 @@
+'''
+2017.03.04
+'''
+import requests
+
+class a_test:
+    '''
+    해당 클래스는 어쩌구 저쩌구
+    '''
+
+    def __init__(self):
+        self.aTest = 'asd'
+
+    def test(self):
+        '''
+        self.a_test를 어쩌구 저쩌구
+        '''
+        print(self.aTest)
+
+    def _test1(self):
+        ''''
+        해당 메소드는 해당 클래스 외부로 노출이 되지 않는 메소드 입니다
+        '''
+        return self.a_test
+
+    def test2(self):
+        '''
+        something
+        '''
+        return self.a_test
+
+
+def test():
+    '''
+    test function 입니다
+    '''
+    print('test')
+
+
+if __name__ == "__main__":
+    test()
diff --git a/app2.py b/app2.py
new file mode 100644
index 0000000..5bc8d31

--- /dev/null
+++ b/app2.py
@@ -0,0 +1,3 @@
+adslkfjadfkj
+
+adsfasdf
cache된 내용을 확인 할 수 있습니다.

하지만 우리는 결과가 아닌 pep검증된 결과 입니다. 캐시 된 내용을 검증해보면 됩니다.
우리는 파이프라고 하는 |을 통해 추가적으로 작업을 연결을 시켜줄 수 있습니다.

$ git diff --staged | pep8 diff
./app.py:6:1 E302 expected 2 blank lines, found1
| pep8 diff을 통해 pep검사 결과를 출력 해 줍니다.

이제 해당 명령어를 pre-commit에 추가를 해주면 됩니다.

$ git commit -m 'asd' ./app.py:6:1: E302 expected 2 blank lines, found 1 [master d714ba1] asd Committer: 박정태 Your name and email address were configured automatically based on your username and hostname. Please check that they are accurate. You can suppress this message by setting them explicitly. Run the following command and follow the instructions in your editor to edit your configuration file: git config --global --edit After doing this, you may fix the identity used for this commit with: git commit --amend --reset-author 3 files changed, 44 insertions(+) create mode 100644 .app.py.swp create mode 100644 app.py create mode 100644 app2.py
commit을 하였습니다.

가장 첫번째 줄에 pep검사 결과가 출력이 되었습니다.
우리는 pep검사 결과에서 아무것도 뜨지 않아야 커밋을 진행을 해야 합니다.
훅을 조금 더 수정을 해보도록 하겠습니다.



$ vim .git/hooks/pre-commit #!/bin/sh # ...중략 FILES=$(git diff --cached | pep8 --diff) if [ -n "$FILES" ]; then echo $FILES exit 1 fi ...중략

훅은 .sh, python, ruby, perl로 작성이 가능 합니다. 저는 그나마 py, sh가 친숙하여 sh로 작성을 하였습니다.

git diff --cached | pep8 --diff)의 결과를 비교하여 exit의 결정 유무를 판단해주면 됩니다.
0이외의 값을 반환을 해주면 해당 커밋은 일어나지 않습니다.

$ git commit -m "hooks test' ./app.py:6:1 #302 expected 2 blank lines, found 1
정상적으로 커밋이 진행되지 않았음을 확인 할 수 있습니다.







댓글

이 블로그의 인기 게시물

[git] pull을 하여 최신코드를 내려받자

보면 먼가 로고가 다르게 뜨는것을 확인을 할 수가있다. C:\Users\mung\Desktop\etc\study\python-gene>git checkout remotes/origin/master Note: checking out 'remotes/origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:   git checkout -b HEAD is now at 29e282a... fetch test C:\Users\mung\Desktop\etc\study\python-gene>git branch * (HEAD detached at origin/master)   master   test1   test2 깃이 잘 쓰면 참 좋은놈인데 어지간히 쓰기가 까다롭다. 처음에 깃을 푸시 성공하는데만 한달정도 걸렸던걸로 기억이 난다.. ㅋㅋㅋ 여담으로  깃 프로필을 가면 아래사진 처럼 보인다. 기여도에 따라서 초록색으로 작은 박스가 채워지는데 저걸 잔디라고 표현을 한다고 합니다 ㅎ 저 사진은 제 깃 기여도 사진입니당 ㅋㅋㅋㅋ 다시 본론으로 돌아와서 ㅋㅋ pull을 하면...

[kali linux] sqlmap - post요청 injection 시도

아래 내용은 직접 테스트 서버를 구축하여 테스트 함을 알립니다.  실 서버에 사용하여 얻는 불이익에는 책임을 지지 않음을 알립니다. sqlmap을 이용하여 get요청이 아닌 post요청에 대해서 injection공격을 시도하자. 뚀한 다양한 플래그를 이용하여 DB 취약점 테스트를 진행을 해보려고 한다. 서버  OS : windows 7 64bit Web server : X Server engine : node.js Framework : expresss Use modules : mysql Address : 172.30.1.30 Open port : 6000번 공격자 OS : kali linux 64bit use tools : sqlmap Address : 172.30.1.57 우선 서버측 부터  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 var  express  =  require( 'express' ); var  app  =  express(); var  mysql  =  require( 'mysql' ); var  ccc  =  mysql.createConnection({     host: '127.0.0.1' ,     user: 'root' ,     pos...

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...