Repository: pre-commit/pre-commit-hooks
Pull request #185 (2017-03-17 21:39:35)

Add a no commit to specific branch hook.


Patch:
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ccfdc4b..193b00e 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,5 +1,5 @@
 -   repo: https://github.com/pre-commit/pre-commit-hooks
-    sha: v0.7.0
+    sha: 4c3cc8f3edc3c673b3a4abe2054e64f21d26772c
     hooks:
     -   id: trailing-whitespace
     -   id: end-of-file-fixer
diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml
index 0604585..bda3f76 100644
--- a/.pre-commit-hooks.yaml
+++ b/.pre-commit-hooks.yaml
@@ -129,6 +129,12 @@
     entry: name-tests-test
     language: python
     files: tests/.+\.py$
+-   id: no-commit-to-branch
+    name: "Don't commit to branch"
+    entry: no-commit-to-branch
+    language: python
+    files: .*
+    always_run: true
 -   id: pyflakes
     name: Pyflakes (DEPRECATED, use flake8)
     description: This hook runs pyflakes. (This is deprecated, use flake8).
diff --git a/README.md b/README.md
index 031edfd..723136d 100644
--- a/README.md
+++ b/README.md
@@ -56,6 +56,8 @@ Add this to your `.pre-commit-config.yaml`
 - `forbid-new-submodules` - Prevent addition of new git submodules.
 - `name-tests-test` - Assert that files in tests/ end in `_test.py`.
     - Use `args: ['--django']` to match `test*.py` instead.
+- `no-commit-to-branch` - Protect specific branches from direct checkins.
+    - Use `args: -b <branch> ` to set the branch. `master` is the default if no argument is set.
 - `pyflakes` - Run pyflakes on your python files.
 - `pretty-format-json` - Checks that all your JSON files are pretty.  "Pretty"
   here means that keys are sorted and indented.  You can configure this with
diff --git a/hooks.yaml b/hooks.yaml
index 0604585..bda3f76 100644
--- a/hooks.yaml
+++ b/hooks.yaml
@@ -129,6 +129,12 @@
     entry: name-tests-test
     language: python
     files: tests/.+\.py$
+-   id: no-commit-to-branch
+    name: "Don't commit to branch"
+    entry: no-commit-to-branch
+    language: python
+    files: .*
+    always_run: true
 -   id: pyflakes
     name: Pyflakes (DEPRECATED, use flake8)
     description: This hook runs pyflakes. (This is deprecated, use flake8).
diff --git a/pre_commit_hooks/no_commit_to_branch.py b/pre_commit_hooks/no_commit_to_branch.py
new file mode 100644
index 0000000..4aa3535
--- /dev/null
+++ b/pre_commit_hooks/no_commit_to_branch.py
@@ -0,0 +1,25 @@
+from __future__ import print_function
+
+import argparse
+import sys
+
+from pre_commit_hooks.util import cmd_output
+
+
+def is_on_branch(protected):
+    branch = cmd_output('git', 'symbolic-ref', 'HEAD')
+    chunks = branch.strip().split('/')
+    return '/'.join(chunks[2:]) == protected
+
+
+def main(argv=[]):
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        '-b', '--branch', default='master', help='branch to disallow commits to')
+    args = parser.parse_args(argv)
+
+    return int(is_on_branch(args.branch))
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv))
diff --git a/pre_commit_hooks/pretty_format_json.py b/pre_commit_hooks/pretty_format_json.py
index bf1ccb1..76b8cfb 100644
--- a/pre_commit_hooks/pretty_format_json.py
+++ b/pre_commit_hooks/pretty_format_json.py
@@ -1,13 +1,15 @@
 from __future__ import print_function
 
 import argparse
+import io
 import sys
 from collections import OrderedDict
 
 import simplejson
+import six
 
 
-def _get_pretty_format(contents, indent, sort_keys=True, top_keys=[]):
+def _get_pretty_format(contents, indent, ensure_ascii=True, sort_keys=True, top_keys=[]):
     def pairs_first(pairs):
         before = [pair for pair in pairs if pair[0] in top_keys]
         before = sorted(before, key=lambda x: top_keys.index(x[0]))
@@ -15,18 +17,19 @@ def _get_pretty_format(contents, indent, sort_keys=True, top_keys=[]):
         if sort_keys:
             after = sorted(after, key=lambda x: x[0])
         return OrderedDict(before + after)
-    return simplejson.dumps(
+    return six.text_type(simplejson.dumps(
         simplejson.loads(
             contents,
             object_pairs_hook=pairs_first,
         ),
-        indent=indent
-    ) + "\n"  # dumps don't end with a newline
+        indent=indent,
+        ensure_ascii=ensure_ascii,
+    )) + "\n"  # dumps does not end with a newline
 
 
-def _autofix(filename, new_contents):
+def _autofix(filename, new_contents, encoding=None):
     print("Fixing file {}".format(filename))
-    with open(filename, 'w') as f:
+    with io.open(filename, 'w', encoding=encoding) as f:
         f.write(new_contents)
 
 
@@ -69,6 +72,13 @@ def pretty_format_json(argv=None):
         default='  ',
         help='String used as delimiter for one indentation level',
     )
+    parser.add_argument(
+        '--no-ensure-ascii',
+        action='store_true',
+        dest='no_ensure_ascii',
+        default=False,
+        help='Do NOT convert non-ASCII characters to Unicode escape sequences (\\uXXXX)',
+    )
     parser.add_argument(
         '--no-sort-keys',
         action='store_true',
@@ -90,20 +100,23 @@ def pretty_format_json(argv=None):
     status = 0
 
     for json_file in args.filenames:
-        with open(json_file) as f:
+        with io.open(json_file, encoding='utf-8') as f:
             contents = f.read()
 
         try:
             pretty_contents = _get_pretty_format(
-                contents, args.indent, sort_keys=not args.no_sort_keys,
-                top_keys=args.top_keys
+                contents, args.indent, ensure_ascii=not args.no_ensure_ascii,
+                sort_keys=not args.no_sort_keys, top_keys=args.top_keys,
             )
 
             if contents != pretty_contents:
                 print("File {} is not pretty-formatted".format(json_file))
 
                 if args.autofix:
-                    _autofix(json_file, pretty_contents)
+                    _autofix(
+                        json_file, pretty_contents,
+                        encoding='utf-8' if args.no_ensure_ascii else None,
+                    )
 
                 status = 1
 
diff --git a/setup.py b/setup.py
index 68a8664..9db61a4 100644
--- a/setup.py
+++ b/setup.py
@@ -52,6 +52,7 @@ setup(
             'fix-encoding-pragma = pre_commit_hooks.fix_encoding_pragma:main',
             'forbid-new-submodules = pre_commit_hooks.forbid_new_submodules:main',
             'name-tests-test = pre_commit_hooks.tests_should_end_in_test:validate_files',
+            'no-commit-to-branch = pre_commit_hooks.no_commit_to_branch:main',
             'pretty-format-json = pre_commit_hooks.pretty_format_json:pretty_format_json',
             'requirements-txt-fixer = pre_commit_hooks.requirements_txt_fixer:fix_requirements_txt',
             'trailing-whitespace-fixer = pre_commit_hooks.trailing_whitespace_fixer:fix_trailing_whitespace',


Test patch:
diff --git a/testing/resources/non_ascii_pretty_formatted_json.json b/testing/resources/non_ascii_pretty_formatted_json.json
new file mode 100644
index 0000000..05d0d00
--- /dev/null
+++ b/testing/resources/non_ascii_pretty_formatted_json.json
@@ -0,0 +1,10 @@
+{
+  "alist": [
+    2,
+    34,
+    234
+  ],
+  "blah": null,
+  "foo": "bar",
+  "non_ascii": "中文にほんご한국어"
+}
diff --git a/tests/check_no_commit_to_branch_test.py b/tests/check_no_commit_to_branch_test.py
new file mode 100644
index 0000000..99af938
--- /dev/null
+++ b/tests/check_no_commit_to_branch_test.py
@@ -0,0 +1,47 @@
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
+from pre_commit_hooks.no_commit_to_branch import is_on_branch
+from pre_commit_hooks.no_commit_to_branch import main
+from pre_commit_hooks.util import cmd_output
+
+
+def test_other_branch(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'anotherbranch')
+        assert is_on_branch('master') is False
+
+
+def test_multi_branch(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'another/branch')
+        assert is_on_branch('master') is False
+
+
+def test_multi_branch_fail(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'another/branch')
+        assert is_on_branch('another/branch') is True
+
+
+def test_master_branch(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        assert is_on_branch('master') is True
+
+
+def test_main_b_call(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'other')
+        assert main(['-b', 'other']) == 1
+
+
+def test_main_branch_call(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'other')
+        assert main(['--branch', 'other']) == 1
+
+
+def test_main_default_call(temp_git_dir):
+    with temp_git_dir.as_cwd():
+        cmd_output('git', 'checkout', '-b', 'anotherbranch')
+        assert main() == 0
diff --git a/tests/pretty_format_json_test.py b/tests/pretty_format_json_test.py
index 7bfc31f..62e37f1 100644
--- a/tests/pretty_format_json_test.py
+++ b/tests/pretty_format_json_test.py
@@ -20,6 +20,7 @@ def test_parse_indent():
 @pytest.mark.parametrize(('filename', 'expected_retval'), (
     ('not_pretty_formatted_json.json', 1),
     ('unsorted_pretty_formatted_json.json', 1),
+    ('non_ascii_pretty_formatted_json.json', 1),
     ('pretty_formatted_json.json', 0),
 ))
 def test_pretty_format_json(filename, expected_retval):
@@ -30,6 +31,7 @@ def test_pretty_format_json(filename, expected_retval):
 @pytest.mark.parametrize(('filename', 'expected_retval'), (
     ('not_pretty_formatted_json.json', 1),
     ('unsorted_pretty_formatted_json.json', 0),
+    ('non_ascii_pretty_formatted_json.json', 1),
     ('pretty_formatted_json.json', 0),
 ))
 def test_unsorted_pretty_format_json(filename, expected_retval):
@@ -40,6 +42,7 @@ def test_unsorted_pretty_format_json(filename, expected_retval):
 @pytest.mark.parametrize(('filename', 'expected_retval'), (
     ('not_pretty_formatted_json.json', 1),
     ('unsorted_pretty_formatted_json.json', 1),
+    ('non_ascii_pretty_formatted_json.json', 1),
     ('pretty_formatted_json.json', 1),
     ('tab_pretty_formatted_json.json', 0),
 ))
@@ -48,6 +51,11 @@ def test_tab_pretty_format_json(filename, expected_retval):
     assert ret == expected_retval
 
 
+def test_non_ascii_pretty_format_json():
+    ret = pretty_format_json(['--no-ensure-ascii', get_resource_path('non_ascii_pretty_formatted_json.json')])
+    assert ret == 0
+
+
 def test_autofix_pretty_format_json(tmpdir):
     srcfile = tmpdir.join('to_be_json_formatted.json')
     shutil.copyfile(