Skip to content

Commit 0dda19f

Browse files
committed
Reorganize output writing
1 parent 1adfa24 commit 0dda19f

File tree

20 files changed

+202
-142
lines changed

20 files changed

+202
-142
lines changed

pre_commit/clientlib/validate_base.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
import argparse
55
import os.path
66
import re
7-
import sys
87

98
import jsonschema
109
import jsonschema.exceptions
1110
import pkg_resources
1211
import yaml
1312

13+
from pre_commit import output
1414
from pre_commit.jsonschema_extensions import apply_defaults
1515

1616

@@ -69,7 +69,6 @@ def validate(filename, load_strategy=yaml.load):
6969

7070
def get_run_function(filenames_help, validate_strategy, exception_cls):
7171
def run(argv=None):
72-
argv = argv if argv is not None else sys.argv[1:]
7372
parser = argparse.ArgumentParser()
7473
parser.add_argument('filenames', nargs='*', help=filenames_help)
7574
parser.add_argument(
@@ -87,7 +86,7 @@ def run(argv=None):
8786
try:
8887
validate_strategy(filename)
8988
except exception_cls as e:
90-
print(e.args[0])
89+
output.write_line(e.args[0])
9190
retval = 1
9291
return retval
9392
return run

pre_commit/commands/autoupdate.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
from __future__ import unicode_literals
33

44
import logging
5-
import sys
65

76
from aspy.yaml import ordered_dump
87
from aspy.yaml import ordered_load
98

109
import pre_commit.constants as C
10+
from pre_commit import output
1111
from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA
1212
from pre_commit.clientlib.validate_config import is_local_hooks
1313
from pre_commit.clientlib.validate_config import load_config
@@ -86,26 +86,23 @@ def autoupdate(runner):
8686
if is_local_hooks(repo_config):
8787
output_configs.append(repo_config)
8888
continue
89-
sys.stdout.write('Updating {}...'.format(repo_config['repo']))
90-
sys.stdout.flush()
89+
output.write('Updating {}...'.format(repo_config['repo']))
9190
try:
9291
new_repo_config = _update_repository(repo_config, runner)
9392
except RepositoryCannotBeUpdatedError as error:
94-
print(error.args[0])
93+
output.write_line(error.args[0])
9594
output_configs.append(repo_config)
9695
retv = 1
9796
continue
9897

9998
if new_repo_config['sha'] != repo_config['sha']:
10099
changed = True
101-
print(
102-
'updating {} -> {}.'.format(
103-
repo_config['sha'], new_repo_config['sha'],
104-
)
105-
)
100+
output.write_line('updating {} -> {}.'.format(
101+
repo_config['sha'], new_repo_config['sha'],
102+
))
106103
output_configs.append(new_repo_config)
107104
else:
108-
print('already up to date.')
105+
output.write_line('already up to date.')
109106
output_configs.append(repo_config)
110107

111108
if changed:

pre_commit/commands/clean.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33

44
import os.path
55

6+
from pre_commit import output
67
from pre_commit.util import rmtree
78

89

910
def clean(runner):
1011
if os.path.exists(runner.store.directory):
1112
rmtree(runner.store.directory)
12-
print('Cleaned {}.'.format(runner.store.directory))
13+
output.write_line('Cleaned {}.'.format(runner.store.directory))
1314
return 0

pre_commit/commands/install_uninstall.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os.path
88
import sys
99

10+
from pre_commit import output
1011
from pre_commit.logging_handler import LoggingHandler
1112
from pre_commit.util import make_executable
1213
from pre_commit.util import mkdirp
@@ -61,7 +62,7 @@ def install(runner, overwrite=False, hooks=False, hook_type='pre-commit'):
6162
if overwrite and os.path.exists(legacy_path):
6263
os.remove(legacy_path)
6364
elif os.path.exists(legacy_path):
64-
print(
65+
output.write_line(
6566
'Running in migration mode with existing hooks at {}\n'
6667
'Use -f to use only pre-commit.'.format(
6768
legacy_path,
@@ -83,7 +84,7 @@ def install(runner, overwrite=False, hooks=False, hook_type='pre-commit'):
8384
pre_commit_file_obj.write(contents)
8485
make_executable(hook_path)
8586

86-
print('pre-commit installed at {}'.format(hook_path))
87+
output.write_line('pre-commit installed at {}'.format(hook_path))
8788

8889
# If they requested we install all of the hooks, do so.
8990
if hooks:
@@ -110,10 +111,10 @@ def uninstall(runner, hook_type='pre-commit'):
110111
return 0
111112

112113
os.remove(hook_path)
113-
print('{} uninstalled'.format(hook_type))
114+
output.write_line('{} uninstalled'.format(hook_type))
114115

115116
if os.path.exists(legacy_path):
116117
os.rename(legacy_path, hook_path)
117-
print('Restored previous hooks to {}'.format(hook_path))
118+
output.write_line('Restored previous hooks to {}'.format(hook_path))
118119

119120
return 0

pre_commit/commands/run.py

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77

88
from pre_commit import color
99
from pre_commit import git
10+
from pre_commit import output
1011
from pre_commit.logging_handler import LoggingHandler
1112
from pre_commit.output import get_hook_message
12-
from pre_commit.output import sys_stdout_write_wrapper
1313
from pre_commit.staged_files_only import staged_files_only
1414
from pre_commit.util import cmd_output
1515
from pre_commit.util import noop_context
@@ -56,10 +56,10 @@ def get_filenames(args, include_expr, exclude_expr):
5656
NO_FILES = '(no files to check)'
5757

5858

59-
def _run_single_hook(hook, repo, args, write, skips, cols):
59+
def _run_single_hook(hook, repo, args, skips, cols):
6060
filenames = get_filenames(args, hook['files'], hook['exclude'])
6161
if hook['id'] in skips:
62-
write(get_hook_message(
62+
output.write(get_hook_message(
6363
_hook_msg_start(hook, args.verbose),
6464
end_msg=SKIPPED,
6565
end_color=color.YELLOW,
@@ -68,7 +68,7 @@ def _run_single_hook(hook, repo, args, write, skips, cols):
6868
))
6969
return 0
7070
elif not filenames and not hook['always_run']:
71-
write(get_hook_message(
71+
output.write(get_hook_message(
7272
_hook_msg_start(hook, args.verbose),
7373
postfix=NO_FILES,
7474
end_msg=SKIPPED,
@@ -80,7 +80,7 @@ def _run_single_hook(hook, repo, args, write, skips, cols):
8080

8181
# Print the hook and the dots first in case the hook takes hella long to
8282
# run.
83-
write(get_hook_message(
83+
output.write(get_hook_message(
8484
_hook_msg_start(hook, args.verbose), end_len=6, cols=cols,
8585
))
8686
sys.stdout.flush()
@@ -104,26 +104,25 @@ def _run_single_hook(hook, repo, args, write, skips, cols):
104104
print_color = color.GREEN
105105
pass_fail = 'Passed'
106106

107-
write(color.format_color(pass_fail, print_color, args.color) + '\n')
107+
output.write_line(color.format_color(pass_fail, print_color, args.color))
108108

109109
if (stdout or stderr or file_modifications) and (retcode or args.verbose):
110-
write('hookid: {}\n'.format(hook['id']))
111-
write('\n')
110+
output.write_line('hookid: {}\n'.format(hook['id']))
112111

113112
# Print a message if failing due to file modifications
114113
if file_modifications:
115-
write('Files were modified by this hook.')
114+
output.write('Files were modified by this hook.')
116115

117116
if stdout or stderr:
118-
write(' Additional output:\n')
117+
output.write_line(' Additional output:')
119118

120-
write('\n')
119+
output.write_line()
121120

122-
for output in (stdout, stderr):
123-
assert type(output) is bytes, type(output)
124-
if output.strip():
125-
write(output.strip() + b'\n')
126-
write('\n')
121+
for out in (stdout, stderr):
122+
assert type(out) is bytes, type(out)
123+
if out.strip():
124+
output.write_line(out.strip())
125+
output.write_line()
127126

128127
return retcode
129128

@@ -147,13 +146,13 @@ def _compute_cols(hooks, verbose):
147146
return max(cols, 80)
148147

149148

150-
def _run_hooks(repo_hooks, args, write, environ):
149+
def _run_hooks(repo_hooks, args, environ):
151150
"""Actually run the hooks."""
152151
skips = _get_skips(environ)
153152
cols = _compute_cols([hook for _, hook in repo_hooks], args.verbose)
154153
retval = 0
155154
for repo, hook in repo_hooks:
156-
retval |= _run_single_hook(hook, repo, args, write, skips, cols)
155+
retval |= _run_single_hook(hook, repo, args, skips, cols)
157156
return retval
158157

159158

@@ -177,10 +176,10 @@ def _has_unstaged_config(runner):
177176
return retcode == 1
178177

179178

180-
def run(runner, args, write=sys_stdout_write_wrapper, environ=os.environ):
179+
def run(runner, args, environ=os.environ):
181180
no_stash = args.no_stash or args.all_files or bool(args.files)
182181
# Set up our logging handler
183-
logger.addHandler(LoggingHandler(args.color, write=write))
182+
logger.addHandler(LoggingHandler(args.color))
184183
logger.setLevel(logging.INFO)
185184

186185
# Check if we have unresolved merge conflict files and fail fast.
@@ -220,7 +219,7 @@ def run(runner, args, write=sys_stdout_write_wrapper, environ=os.environ):
220219
if hook['id'] == args.hook
221220
]
222221
if not repo_hooks:
223-
write('No hook with id `{}`\n'.format(args.hook))
222+
output.write_line('No hook with id `{}`'.format(args.hook))
224223
return 1
225224

226225
# Filter hooks for stages
@@ -229,4 +228,4 @@ def run(runner, args, write=sys_stdout_write_wrapper, environ=os.environ):
229228
if not hook['stages'] or args.hook_stage in hook['stages']
230229
]
231230

232-
return _run_hooks(repo_hooks, args, write, environ)
231+
return _run_hooks(repo_hooks, args, environ)

pre_commit/error_handler.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
import traceback
99

1010
from pre_commit import five
11+
from pre_commit import output
1112
from pre_commit.errors import FatalError
12-
from pre_commit.output import sys_stdout_write_wrapper
1313
from pre_commit.store import Store
1414

1515

@@ -25,19 +25,19 @@ def _to_bytes(exc):
2525
return five.text(exc).encode('UTF-8')
2626

2727

28-
def _log_and_exit(msg, exc, formatted, write_fn=sys_stdout_write_wrapper):
28+
def _log_and_exit(msg, exc, formatted):
2929
error_msg = b''.join((
3030
five.to_bytes(msg), b': ',
3131
five.to_bytes(type(exc).__name__), b': ',
3232
_to_bytes(exc), b'\n',
3333
))
34-
write_fn(error_msg)
35-
write_fn('Check the log at ~/.pre-commit/pre-commit.log\n')
34+
output.write(error_msg)
35+
output.write_line('Check the log at ~/.pre-commit/pre-commit.log')
3636
store = Store()
3737
store.require_created()
3838
with io.open(os.path.join(store.directory, 'pre-commit.log'), 'wb') as log:
39-
log.write(five.to_bytes(error_msg))
40-
log.write(five.to_bytes(formatted) + b'\n')
39+
output.write(error_msg, stream=log)
40+
output.write_line(formatted, stream=log)
4141
raise PreCommitSystemExit(1)
4242

4343

pre_commit/logging_handler.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from __future__ import unicode_literals
22

33
import logging
4-
import sys
54

65
from pre_commit import color
6+
from pre_commit import output
77

88

99
LOG_LEVEL_COLORS = {
@@ -15,14 +15,13 @@
1515

1616

1717
class LoggingHandler(logging.Handler):
18-
def __init__(self, use_color, write=sys.stdout.write):
18+
def __init__(self, use_color):
1919
super(LoggingHandler, self).__init__()
2020
self.use_color = use_color
21-
self.__write = write
2221

2322
def emit(self, record):
24-
self.__write(
25-
'{}{}\n'.format(
23+
output.write_line(
24+
'{}{}'.format(
2625
color.format_color(
2726
'[{}]'.format(record.levelname),
2827
LOG_LEVEL_COLORS[record.levelname],
@@ -31,4 +30,3 @@ def emit(self, record):
3130
record.getMessage(),
3231
)
3332
)
34-
sys.stdout.flush()

pre_commit/make_archives.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import tarfile
77

88
from pre_commit import five
9+
from pre_commit import output
910
from pre_commit.util import cmd_output
1011
from pre_commit.util import cwd
1112
from pre_commit.util import rmtree
@@ -61,7 +62,9 @@ def make_archive(name, repo, ref, destdir):
6162

6263
def main():
6364
for archive_name, repo, ref in REPOS:
64-
print('Making {}.tar.gz for {}@{}'.format(archive_name, repo, ref))
65+
output.write_line('Making {}.tar.gz for {}@{}'.format(
66+
archive_name, repo, ref,
67+
))
6568
make_archive(archive_name, repo, ref, RESOURCES_DIR)
6669

6770

pre_commit/output.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,13 @@ def get_hook_message(
6666
stdout_byte_stream = getattr(sys.stdout, 'buffer', sys.stdout)
6767

6868

69-
def sys_stdout_write_wrapper(s, stream=stdout_byte_stream):
69+
def write(s, stream=stdout_byte_stream):
7070
stream.write(five.to_bytes(s))
71+
stream.flush()
72+
73+
74+
def write_line(s=None, stream=stdout_byte_stream):
75+
if s is not None:
76+
stream.write(five.to_bytes(s))
77+
stream.write(b'\n')
78+
stream.flush()
File renamed without changes.

0 commit comments

Comments
 (0)