Auto merge of #3045 - micbou:flake8-ycm, r=puremourning

[READY] Enforce YCM coding style

See PR https://github.com/Valloric/ycmd/pull/1047.

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/valloric/youcompleteme/3045)
<!-- Reviewable:end -->
This commit is contained in:
zzbot 2018-06-02 07:46:13 -07:00 committed by GitHub
commit 2dcb3e91ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 140 additions and 138 deletions

View File

@ -1,5 +1,6 @@
flake8 >= 3.0.0 flake8 >= 3.0.0
flake8-comprehensions >= 1.4.1 flake8-comprehensions >= 1.4.1
flake8-ycm >= 0.1.0
mock >= 1.0.1 mock >= 1.0.1
nose >= 1.3.7 nose >= 1.3.7
PyHamcrest >= 1.8.0 PyHamcrest >= 1.8.0

View File

@ -32,7 +32,7 @@ from ycmd.utils import ToBytes, urljoin, urlparse, GetCurrentDirectory
from ycmd.hmac_utils import CreateRequestHmac, CreateHmac, SecureBytesEqual from ycmd.hmac_utils import CreateRequestHmac, CreateHmac, SecureBytesEqual
from ycmd.responses import ServerError, UnknownExtraConf from ycmd.responses import ServerError, UnknownExtraConf
_HEADERS = {'content-type': 'application/json'} _HEADERS = { 'content-type': 'application/json' }
_CONNECT_TIMEOUT_SEC = 0.01 _CONNECT_TIMEOUT_SEC = 0.01
# Setting this to None seems to screw up the Requests/urllib3 libs. # Setting this to None seems to screw up the Requests/urllib3 libs.
_READ_TIMEOUT_SEC = 30 _READ_TIMEOUT_SEC = 30

View File

@ -94,7 +94,7 @@ def _FormatCompleterDebugInfo( completer ):
message += ' {0} process ID: {1}\n'.format( name, server[ 'pid' ] ) message += ' {0} process ID: {1}\n'.format( name, server[ 'pid' ] )
else: else:
message += ' {0} not running\n'.format( name ) message += ' {0} not running\n'.format( name )
message += ' {0} executable: {1}\n'.format( name, server[ 'executable'] ) message += ' {0} executable: {1}\n'.format( name, server[ 'executable' ] )
logfiles = server[ 'logfiles' ] logfiles = server[ 'logfiles' ]
if logfiles: if logfiles:
message += ' {0} logfiles:\n'.format( name ) message += ' {0} logfiles:\n'.format( name )

View File

@ -42,7 +42,7 @@ SYNTAX_ARGUMENT_REGEX = re.compile(
r"^\w+=.*$" ) r"^\w+=.*$" )
SYNTAX_REGION_ARGUMENT_REGEX = re.compile( SYNTAX_REGION_ARGUMENT_REGEX = re.compile(
r"^(?:matchgroup|start)=.*$") r"^(?:matchgroup|start)=.*$" )
# See ":h syn-nextgroup". # See ":h syn-nextgroup".
SYNTAX_NEXTGROUP_ARGUMENTS = { SYNTAX_NEXTGROUP_ARGUMENTS = {
@ -106,7 +106,7 @@ def _SyntaxGroupsFromOutput( syntax_output ):
group_name_to_group[ current_group.name ] = current_group group_name_to_group[ current_group.name ] = current_group
current_group = SyntaxGroup( match.group( 'group_name' ), current_group = SyntaxGroup( match.group( 'group_name' ),
[ match.group( 'content').strip() ] ) [ match.group( 'content' ).strip() ] )
else: else:
if looking_for_group: if looking_for_group:
continue continue

View File

@ -35,7 +35,7 @@ from ycm import base
@contextlib.contextmanager @contextlib.contextmanager
def MockCurrentFiletypes( filetypes = [''] ): def MockCurrentFiletypes( filetypes = [ '' ] ):
with patch( 'ycm.vimsupport.CurrentFiletypes', return_value = filetypes ): with patch( 'ycm.vimsupport.CurrentFiletypes', return_value = filetypes ):
yield yield
@ -180,7 +180,7 @@ def LastEnteredCharIsIdentifierChar_Basic_test():
def LastEnteredCharIsIdentifierChar_FiletypeHtml_test(): def LastEnteredCharIsIdentifierChar_FiletypeHtml_test():
with MockCurrentFiletypes( ['html'] ): with MockCurrentFiletypes( [ 'html' ] ):
with MockCurrentColumnAndLineContents( 3, 'ab-' ): with MockCurrentColumnAndLineContents( 3, 'ab-' ):
ok_( base.LastEnteredCharIsIdentifierChar() ) ok_( base.LastEnteredCharIsIdentifierChar() )
@ -272,7 +272,7 @@ def CurrentIdentifierFinished_InMiddleOfLine_test():
def CurrentIdentifierFinished_Html_test(): def CurrentIdentifierFinished_Html_test():
with MockCurrentFiletypes( ['html'] ): with MockCurrentFiletypes( [ 'html' ] ):
with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ): with MockCurrentColumnAndLineContents( 4, 'bar-zoo' ):
ok_( not base.CurrentIdentifierFinished() ) ok_( not base.CurrentIdentifierFinished() )

View File

@ -98,10 +98,10 @@ def HandlePollResponse_MultipleDiagnostics_test():
assert_that( _HandlePollResponse( messages, diagnostics_handler ), assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) ) equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [ diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [
call ( 'foo', [ 'PLACEHOLDER1' ] ), call( 'foo', [ 'PLACEHOLDER1' ] ),
call ( 'bar', [ 'PLACEHOLDER2' ] ), call( 'bar', [ 'PLACEHOLDER2' ] ),
call ( 'baz', [ 'PLACEHOLDER3' ] ), call( 'baz', [ 'PLACEHOLDER3' ] ),
call ( 'foo', [ 'PLACEHOLDER4' ] ) call( 'foo', [ 'PLACEHOLDER4' ] )
] ) ] )
@ -122,10 +122,10 @@ def HandlePollResponse_MultipleMessagesAndDiagnostics_test( post_vim_message ):
assert_that( _HandlePollResponse( messages, diagnostics_handler ), assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) ) equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [ diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [
call ( 'foo', [ 'PLACEHOLDER1' ] ), call( 'foo', [ 'PLACEHOLDER1' ] ),
call ( 'bar', [ 'PLACEHOLDER2' ] ), call( 'bar', [ 'PLACEHOLDER2' ] ),
call ( 'baz', [ 'PLACEHOLDER3' ] ), call( 'baz', [ 'PLACEHOLDER3' ] ),
call ( 'foo', [ 'PLACEHOLDER4' ] ) call( 'foo', [ 'PLACEHOLDER4' ] )
] ) ] )
post_vim_message.assert_has_exact_calls( [ post_vim_message.assert_has_exact_calls( [

View File

@ -65,7 +65,7 @@ def RawResponse_ConvertedFromOmniCompleter_test():
{ "word": "WORD2", "abbr": "ABBR2", "menu": "MENU2", { "word": "WORD2", "abbr": "ABBR2", "menu": "MENU2",
"kind": "KIND2", "info": "INFO" }, "kind": "KIND2", "info": "INFO" },
{ "word": "WORD", "abbr": "ABBR", }, { "word": "WORD", "abbr": "ABBR", },
{ }, {},
] ]
expected_results = [ expected_results = [
has_entries( { "insertion_text": "WORD", "menu_text": "ABBR", has_entries( { "insertion_text": "WORD", "menu_text": "ABBR",
@ -75,7 +75,7 @@ def RawResponse_ConvertedFromOmniCompleter_test():
"extra_menu_info": "MENU2", "kind": [ "KIND2" ], "extra_menu_info": "MENU2", "kind": [ "KIND2" ],
"detailed_info": "INFO" } ), "detailed_info": "INFO" } ),
has_entries( { "insertion_text": "WORD", "menu_text": "ABBR", } ), has_entries( { "insertion_text": "WORD", "menu_text": "ABBR", } ),
has_entries( { } ), has_entries( {} ),
] ]
request = BuildOmnicompletionRequest( vim_results ) request = BuildOmnicompletionRequest( vim_results )

View File

@ -389,7 +389,7 @@ def PostCompleteFixIt_ApplyFixIt_EmptyFixIt_test( replace_chunks, *args ):
@patch( 'ycm.vimsupport.ReplaceChunks' ) @patch( 'ycm.vimsupport.ReplaceChunks' )
def PostCompleteFixIt_ApplyFixIt_NoFixIt_test( replace_chunks, *args ): def PostCompleteFixIt_ApplyFixIt_NoFixIt_test( replace_chunks, *args ):
completions = [ completions = [
BuildCompletion( ) BuildCompletion()
] ]
with _SetUpCompleteDone( completions ) as request: with _SetUpCompleteDone( completions ) as request:
request._OnCompleteDone_FixIt() request._OnCompleteDone_FixIt()

View File

@ -1114,17 +1114,17 @@ def ReplaceChunks_User_Aborts_Opening_File_test(
False, # second_file (apply) False, # second_file (apply)
True, # side_effect (check after open) True, # side_effect (check after open)
], ],
new_callable = ExtendedMock) new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.OpenFilename', @patch( 'ycm.vimsupport.OpenFilename',
new_callable = ExtendedMock) new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.PostVimMessage', @patch( 'ycm.vimsupport.PostVimMessage',
new_callable = ExtendedMock) new_callable = ExtendedMock )
@patch( 'ycm.vimsupport.Confirm', return_value = True, @patch( 'ycm.vimsupport.Confirm', return_value = True,
new_callable = ExtendedMock) new_callable = ExtendedMock )
@patch( 'vim.eval', return_value = 10, @patch( 'vim.eval', return_value = 10,
new_callable = ExtendedMock) new_callable = ExtendedMock )
@patch( 'vim.command', @patch( 'vim.command',
new_callable = ExtendedMock) new_callable = ExtendedMock )
def ReplaceChunks_MultiFile_Open_test( vim_command, def ReplaceChunks_MultiFile_Open_test( vim_command,
vim_eval, vim_eval,
confirm, confirm,
@ -1295,7 +1295,7 @@ def AddDiagnosticSyntaxMatch_UnicodeAtEndOfLine_test():
@patch( 'vim.command', new_callable=ExtendedMock ) @patch( 'vim.command', new_callable=ExtendedMock )
@patch( 'vim.current', new_callable=ExtendedMock) @patch( 'vim.current', new_callable=ExtendedMock )
def WriteToPreviewWindow_test( vim_current, vim_command ): def WriteToPreviewWindow_test( vim_current, vim_command ):
vim_current.window.options.__getitem__ = MagicMock( return_value = True ) vim_current.window.options.__getitem__ = MagicMock( return_value = True )
@ -1534,7 +1534,7 @@ def SelectFromList_FirstItem_test( vim_eval ):
@patch( 'vim.eval', side_effect = [ None, 3, None ] ) @patch( 'vim.eval', side_effect = [ None, 3, None ] )
def SelectFromList_OutOfRange_test( vim_eval ): def SelectFromList_OutOfRange_test( vim_eval ):
assert_that( calling( vimsupport.SelectFromList).with_args( 'test', assert_that( calling( vimsupport.SelectFromList ).with_args( 'test',
[ 'a', 'b' ] ), [ 'a', 'b' ] ),
raises( RuntimeError, vimsupport.NO_SELECTION_MADE_MSG ) ) raises( RuntimeError, vimsupport.NO_SELECTION_MADE_MSG ) )

View File

@ -28,30 +28,30 @@ except ImportError:
# only send network requests). The YCM workload is one of those workloads where # only send network requests). The YCM workload is one of those workloads where
# it's safe (the aforementioned network requests case). # it's safe (the aforementioned network requests case).
class _WorkItem(object): class _WorkItem( object ):
def __init__(self, future, fn, args, kwargs): def __init__( self, future, fn, args, kwargs ):
self.future = future self.future = future
self.fn = fn self.fn = fn
self.args = args self.args = args
self.kwargs = kwargs self.kwargs = kwargs
def run(self): def run( self ):
if not self.future.set_running_or_notify_cancel(): if not self.future.set_running_or_notify_cancel():
return return
try: try:
result = self.fn(*self.args, **self.kwargs) result = self.fn( *self.args, **self.kwargs )
except BaseException: except BaseException:
e = sys.exc_info()[1] e = sys.exc_info()[ 1 ]
self.future.set_exception(e) self.future.set_exception( e )
else: else:
self.future.set_result(result) self.future.set_result( result )
def _worker(executor_reference, work_queue): def _worker( executor_reference, work_queue ):
try: try:
while True: while True:
work_item = work_queue.get(block=True) work_item = work_queue.get( block=True )
if work_item is not None: if work_item is not None:
work_item.run() work_item.run()
continue continue
@ -61,15 +61,15 @@ def _worker(executor_reference, work_queue):
# - The executor that owns the worker has been shutdown. # - The executor that owns the worker has been shutdown.
if executor is None or executor._shutdown: if executor is None or executor._shutdown:
# Notice other workers # Notice other workers
work_queue.put(None) work_queue.put( None )
return return
del executor del executor
except BaseException: except BaseException:
_base.LOGGER.critical('Exception in worker', exc_info=True) _base.LOGGER.critical( 'Exception in worker', exc_info=True )
class UnsafeThreadPoolExecutor(_base.Executor): class UnsafeThreadPoolExecutor( _base.Executor ):
def __init__(self, max_workers): def __init__( self, max_workers ):
"""Initializes a new ThreadPoolExecutor instance. """Initializes a new ThreadPoolExecutor instance.
Args: Args:
@ -82,38 +82,38 @@ class UnsafeThreadPoolExecutor(_base.Executor):
self._shutdown = False self._shutdown = False
self._shutdown_lock = threading.Lock() self._shutdown_lock = threading.Lock()
def submit(self, fn, *args, **kwargs): def submit( self, fn, *args, **kwargs ):
with self._shutdown_lock: with self._shutdown_lock:
if self._shutdown: if self._shutdown:
raise RuntimeError('cannot schedule new futures after shutdown') raise RuntimeError( 'cannot schedule new futures after shutdown' )
f = _base.Future() f = _base.Future()
w = _WorkItem(f, fn, args, kwargs) w = _WorkItem( f, fn, args, kwargs )
self._work_queue.put(w) self._work_queue.put( w )
self._adjust_thread_count() self._adjust_thread_count()
return f return f
submit.__doc__ = _base.Executor.submit.__doc__ submit.__doc__ = _base.Executor.submit.__doc__
def _adjust_thread_count(self): def _adjust_thread_count( self ):
# When the executor gets lost, the weakref callback will wake up # When the executor gets lost, the weakref callback will wake up
# the worker threads. # the worker threads.
def weakref_cb(_, q=self._work_queue): def weakref_cb( _, q=self._work_queue ):
q.put(None) q.put( None )
# TODO(bquinlan): Should avoid creating new threads if there are more # TODO(bquinlan): Should avoid creating new threads if there are more
# idle threads than items in the work queue. # idle threads than items in the work queue.
if len(self._threads) < self._max_workers: if len( self._threads ) < self._max_workers:
t = threading.Thread(target=_worker, t = threading.Thread( target=_worker,
args=(weakref.ref(self, weakref_cb), args=( weakref.ref( self, weakref_cb ),
self._work_queue)) self._work_queue ) )
t.daemon = True t.daemon = True
t.start() t.start()
self._threads.add(t) self._threads.add( t )
def shutdown(self, wait=True): def shutdown( self, wait=True ):
with self._shutdown_lock: with self._shutdown_lock:
self._shutdown = True self._shutdown = True
self._work_queue.put(None) self._work_queue.put( None )
if wait: if wait:
for t in self._threads: for t in self._threads:
t.join() t.join()

View File

@ -941,7 +941,7 @@ def ReplaceChunk( start, end, replacement_text, vim_buffer ):
replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ] replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:] vim_buffer[ start_line : end_line + 1 ] = replacement_lines[ : ]
return { return {
'bufnr': vim_buffer.number, 'bufnr': vim_buffer.number,
@ -977,7 +977,8 @@ def InsertNamespace( namespace ):
def SearchInCurrentBuffer( pattern ): def SearchInCurrentBuffer( pattern ):
""" Returns the 1-indexed line on which the pattern matches """ Returns the 1-indexed line on which the pattern matches
(going UP from the current position) or 0 if not found """ (going UP from the current position) or 0 if not found """
return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern ))) return GetIntValue(
"search('{0}', 'Wcnb')".format( EscapeForVim( pattern ) ) )
def LineTextInCurrentBuffer( line_number ): def LineTextInCurrentBuffer( line_number ):
@ -1033,7 +1034,7 @@ def WriteToPreviewWindow( message ):
vim.current.buffer.options[ 'modifiable' ] = True vim.current.buffer.options[ 'modifiable' ] = True
vim.current.buffer.options[ 'readonly' ] = False vim.current.buffer.options[ 'readonly' ] = False
vim.current.buffer[:] = message.splitlines() vim.current.buffer[ : ] = message.splitlines()
vim.current.buffer.options[ 'buftype' ] = 'nofile' vim.current.buffer.options[ 'buftype' ] = 'nofile'
vim.current.buffer.options[ 'bufhidden' ] = 'wipe' vim.current.buffer.options[ 'bufhidden' ] = 'wipe'

View File

@ -53,9 +53,9 @@ from ycm.client.messages_request import MessagesPoll
def PatchNoProxy(): def PatchNoProxy():
current_value = os.environ.get('no_proxy', '') current_value = os.environ.get( 'no_proxy', '' )
additions = '127.0.0.1,localhost' additions = '127.0.0.1,localhost'
os.environ['no_proxy'] = ( additions if not current_value os.environ[ 'no_proxy' ] = ( additions if not current_value
else current_value + ',' + additions ) else current_value + ',' + additions )

View File

@ -1,4 +1,4 @@
[flake8] [flake8]
ignore = E111,E114,E121,E125,E126,E127,E128,E129,E131,E133,E201,E202,E203,E211,E221,E222,E241,E251,E261,E303,E402,W503 ignore = E111,E114,E121,E125,E126,E127,E128,E129,E131,E133,E201,E202,E203,E221,E222,E241,E251,E261,E303,E402,W503
max-complexity = 10 max-complexity = 10
max-line-length = 80 max-line-length = 80