Skip to content

Commit 06a41bd

Browse files
committed
Useful pylint fixes
After combing through all the stuff pylint has found, this seems to me the useful part. The only questionable thing here, I think, could be the stuff related to `open()` and explicit encoding argument. This changes behaviour! Without specifying, the encoding is platform dependent. See https://docs.python.org/3/library/functions.html#open for details. Fixes #1672
1 parent adce5d8 commit 06a41bd

29 files changed

+69
-85
lines changed

.ycm_extra_conf.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@
2929
# For more information, please refer to <http://unlicense.org/>
3030

3131
from sysconfig import get_path
32-
import platform
3332
import os.path as p
34-
import subprocess
3533

3634
DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) )
3735
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
@@ -120,7 +118,7 @@ def FindCorrespondingSourceFile( filename ):
120118
def PathToPythonUsedDuringBuild():
121119
try:
122120
filepath = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' )
123-
with open( filepath ) as f:
121+
with open( filepath, encoding = 'utf8' ) as f:
124122
return f.read().strip()
125123
except OSError:
126124
return None

build.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def FindLatestMSVC( quiet ):
130130
).strip().decode()
131131
if '.' in latest_full_v:
132132
try:
133-
latest_v = int( latest_full_v.split( '.' )[ 0 ] )
133+
latest_v = int( latest_full_v.split( '.', 1 )[ 0 ] )
134134
except ValueError:
135135
raise ValueError( f"{ latest_full_v } is not a version number." )
136136

@@ -464,10 +464,10 @@ def ParseArguments():
464464
DEFAULT_RUST_TOOLCHAIN + '" is tested/'
465465
'supported by the maintainers of YCM/ycmd' )
466466
parser.add_argument( '--java-completer', action = 'store_true',
467-
help = 'Enable Java semantic completion engine.' ),
467+
help = 'Enable Java semantic completion engine.' )
468468
parser.add_argument( '--ts-completer', action = 'store_true',
469469
help = 'Enable JavaScript and TypeScript semantic '
470-
'completion engine.' ),
470+
'completion engine.' )
471471
parser.add_argument( '--system-libclang', action = 'store_true',
472472
help = 'Use system libclang instead of downloading one '
473473
'from llvm.org. NOT RECOMMENDED OR SUPPORTED!' )
@@ -834,7 +834,6 @@ def CleanCsCompleter( build_dir, version ):
834834
if os.path.isfile( file_path ):
835835
os.remove( file_path )
836836
elif os.path.isdir( file_path ):
837-
import shutil
838837
shutil.rmtree( file_path )
839838

840839

@@ -953,14 +952,14 @@ def EnableGoCompleter( args ):
953952

954953
def WriteToolchainVersion( version ):
955954
path = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' )
956-
with open( path, 'w' ) as f:
955+
with open( path, 'w', encoding = 'utf8' ) as f:
957956
f.write( version )
958957

959958

960959
def ReadToolchainVersion():
961960
try:
962961
filepath = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' )
963-
with open( filepath ) as f:
962+
with open( filepath, encoding = 'utf8' ) as f:
964963
return f.read().strip()
965964
except OSError:
966965
return None
@@ -1234,7 +1233,7 @@ def Print( msg ):
12341233

12351234
def WritePythonUsedDuringBuild():
12361235
path = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' )
1237-
with open( path, 'w' ) as f:
1236+
with open( path, 'w', encoding = 'utf8' ) as f:
12381237
f.write( sys.executable )
12391238

12401239

run_tests.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,9 @@ def BuildYcmdLibs( args ):
195195
'--core-tests'
196196
]
197197

198-
for key in COMPLETERS:
198+
for key, value in COMPLETERS.items():
199199
if key in args.completers:
200-
build_cmd.extend( COMPLETERS[ key ][ 'build' ] )
200+
build_cmd.extend( value[ 'build' ] )
201201

202202
if args.msvc and platform.system() == 'Windows':
203203
build_cmd.extend( [ '--msvc', str( args.msvc ) ] )

update_clang_headers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def ExtractTar( uncompressed_data, destination ):
3939
tar_file.extractall( destination )
4040

4141
# Determine the directory name
42-
return os.path.join( destination, a_member.name.split( '/' )[ 0 ] )
42+
return os.path.join( destination, a_member.name.split( '/', 1 )[ 0 ] )
4343

4444

4545
def ExtractLZMA( compressed_data, destination ):

update_unicode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ def GenerateNormalizationTestCases( output_file ):
580580
JoinUnicodeToUtf8( captures[ 4 ].split() ) + '"},\n' )
581581

582582
res[ -1 ] = res[ -1 ].rstrip( ',\n' )
583-
with open( output_file, 'w' ) as f:
583+
with open( output_file, 'w', encoding = 'utf8' ) as f:
584584
f.writelines( res )
585585

586586

@@ -602,7 +602,7 @@ def GenerateGraphemeBreakTestCases( output_file ):
602602
for x in split_data ] ).rstrip( ',' ) + '}},\n' )
603603

604604
res[ -1 ] = res[ -1 ].rstrip( ',\n' )
605-
with open( output_file, 'w' ) as f:
605+
with open( output_file, 'w', encoding = 'utf8' ) as f:
606606
f.writelines( res )
607607

608608

ycmd/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def ParseArguments():
142142
def SetupLogging( log_level ):
143143
numeric_level = getattr( logging, log_level.upper(), None )
144144
if not isinstance( numeric_level, int ):
145-
raise ValueError( 'Invalid log level: %s' % log_level )
145+
raise ValueError( f'Invalid log level: { log_level }' )
146146

147147
# Has to be called before any call to logging.getLogger()
148148
logging.basicConfig( format = '%(asctime)s - %(levelname)s - %(message)s',

ycmd/completers/cpp/clang_completer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,9 +436,9 @@ def DebugInfo( self, request_data ):
436436

437437
database_item = responses.DebugInfoItem(
438438
key = 'compilation database path',
439-
value = '{0}'.format( database_directory ) )
439+
value = f'{ database_directory }' )
440440
flags_item = responses.DebugInfoItem(
441-
key = 'flags', value = '{0}'.format( list( flags ) ) )
441+
key = 'flags', value = f'{ list( flags ) }' )
442442
filename_item = responses.DebugInfoItem(
443443
key = 'translation unit', value = filename )
444444

ycmd/completers/cpp/flags.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -673,13 +673,12 @@ def UserIncludePaths( user_flags, filename ):
673673
it = iter( user_flags )
674674
for user_flag in it:
675675
user_flag_len = len( user_flag )
676-
for flag in include_flags:
676+
for flag, container in include_flags.items():
677677
if user_flag.startswith( flag ):
678678
flag_len = len( flag )
679679
include_path = ( next( it ) if user_flag_len == flag_len else
680680
user_flag[ flag_len: ] )
681681
if include_path:
682-
container = include_flags[ flag ]
683682
container.append( ToUnicode( include_path ) )
684683
break
685684
except StopIteration:

ycmd/completers/cs/cs_completer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ def _GetSolutionFile( self, filepath ):
387387
return self._solution_for_file[ filepath ]
388388

389389

390-
class CsharpSolutionCompleter( object ):
390+
class CsharpSolutionCompleter:
391391
def __init__( self,
392392
solution_path,
393393
keep_logfiles,

ycmd/completers/language_server/generic_lsp_completer.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,17 @@ def __init__( self, user_options, server_settings ):
4848
cmd = utils.FindExecutable( self._command_line[ 0 ] )
4949

5050
if cmd is None:
51-
utils.LOGGER.warn( "Unable to find any executable with the path %s. "
52-
"Cannot use %s completer.",
53-
self._command_line[ 0 ],
54-
self._name )
55-
raise RuntimeError( f"Invalid cmdline: { str( self._command_line ) }" )
51+
utils.LOGGER.warning( "Unable to find any executable with the path %s. "
52+
"Cannot use %s completer.",
53+
self._command_line[ 0 ],
54+
self._name )
55+
raise RuntimeError( f"Invalid cmdline: { self._command_line }" )
5656

5757
self._command_line[ 0 ] = cmd
58-
for idx in range( len( self._command_line ) ):
59-
self._command_line[ idx ] = string.Template(
60-
self._command_line[ idx ] ).safe_substitute( {
61-
'port': self._port
62-
} )
58+
for arg in self._command_line:
59+
arg = string.Template( arg ).safe_substitute( {
60+
'port': self._port
61+
} )
6362

6463
super().__init__( user_options, connection_type )
6564

ycmd/completers/language_server/language_server_completer.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -564,8 +564,8 @@ def _ReadHeaders( self, data ):
564564
key, value = utils.ToUnicode( line ).split( ':', 1 )
565565
headers[ key.strip() ] = value.strip()
566566
except Exception:
567-
LOGGER.exception( 'Received invalid protocol data from server: '
568-
+ str( line ) )
567+
LOGGER.exception( 'Received invalid protocol data from server: ',
568+
line )
569569
raise
570570

571571
read_bytes += 1
@@ -1096,7 +1096,7 @@ def _StartServerNoLock( self, request_data ):
10961096
self._project_directory,
10971097
lambda globs: WatchdogHandler( self, globs ),
10981098
self._port,
1099-
lambda request: self.WorkspaceConfigurationResponse( request ),
1099+
self.WorkspaceConfigurationResponse,
11001100
self.GetDefaultNotificationHandler() )
11011101
else:
11021102
self._stderr_file = utils.CreateLogfile(
@@ -1116,7 +1116,7 @@ def _StartServerNoLock( self, request_data ):
11161116
lambda globs: WatchdogHandler( self, globs ),
11171117
self._server_handle.stdin,
11181118
self._server_handle.stdout,
1119-
lambda request: self.WorkspaceConfigurationResponse( request ),
1119+
self.WorkspaceConfigurationResponse,
11201120
self.GetDefaultNotificationHandler() )
11211121
)
11221122

@@ -2865,7 +2865,7 @@ def ExecuteCommand( self, request_data, args ):
28652865
if response is not None:
28662866
return response
28672867

2868-
if len( edits ):
2868+
if edits:
28692869
fixits = [ WorkspaceEditToFixIt(
28702870
request_data,
28712871
e[ 'edit' ],
@@ -3190,7 +3190,7 @@ def _SymbolInfoListToGoTo( request_data, symbols ):
31903190
"""Convert a list of LSP SymbolInformation into a YCM GoTo response"""
31913191

31923192
def BuildGoToLocationFromSymbol( symbol ):
3193-
location, line_value = _LspLocationToLocationAndDescription(
3193+
location, _ = _LspLocationToLocationAndDescription(
31943194
request_data,
31953195
symbol[ 'location' ] )
31963196

ycmd/completers/python/python_completer.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -650,12 +650,3 @@ def _OffsetToPosition( start_end, filename, text, newlines ):
650650
if len( loc ) == 2:
651651
break
652652
return loc
653-
654-
# Invalid position - it's outside of the text. Just return the last
655-
# position in the text. This is an internal error.
656-
LOGGER.error( "Invalid offset %s in file %s with text %s and newlines %s",
657-
offset,
658-
filename,
659-
text,
660-
newlines )
661-
raise RuntimeError( "Invalid file offset in diff" )

ycmd/completers/typescript/typescript_completer.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -373,9 +373,8 @@ def _Reload( self, request_data ):
373373

374374
filename = request_data[ 'filepath' ]
375375
contents = request_data[ 'file_data' ][ filename ][ 'contents' ]
376-
tmpfile = NamedTemporaryFile( delete = False )
377-
tmpfile.write( utils.ToBytes( contents ) )
378-
tmpfile.close()
376+
with NamedTemporaryFile( delete = False ) as tmpfile:
377+
tmpfile.write( utils.ToBytes( contents ) )
379378
self._SendRequest( 'reload', {
380379
'file': filename,
381380
'tmpfile': tmpfile.name

ycmd/tests/clang/flags_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def Settings( **kwargs ):
9999
assert_that( filename, equal_to( '/foo' ) )
100100

101101

102-
def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( *args ):
102+
def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( self, *args ):
103103
flags_object = flags.Flags()
104104

105105
def Settings( **kwargs ):

ycmd/tests/clang/include_cache_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def test_IncludeCache_Cached_NewMtime( self ):
102102
include_cache = IncludeCache()
103103
assert_that( include_cache._cache, equal_to( {} ) )
104104
foo_path = os.path.join( tmp_dir, 'foo' )
105-
with open( foo_path, 'w' ) as foo_file:
105+
with open( foo_path, 'w', encoding = 'utf8' ) as foo_file:
106106
foo_file.write( 'foo' )
107107

108108
old_includes = include_cache.GetIncludes( tmp_dir )
@@ -124,7 +124,7 @@ def test_IncludeCache_Cached_NewMtime( self ):
124124
sleep( 2 )
125125

126126
bar_path = os.path.join( tmp_dir, 'bar' )
127-
with open( bar_path, 'w' ) as bar_file:
127+
with open( bar_path, 'w', encoding = 'utf8' ) as bar_file:
128128
bar_file.write( 'bar' )
129129

130130
new_includes = include_cache.GetIncludes( tmp_dir )

ycmd/tests/clangd/debug_info_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ def test_DebugInfo_ExtraConf_UseLocalOverDatabase( self, app ):
336336

337337
with TemporaryClangProject( tmp_dir, database ):
338338
extra_conf = os.path.join( tmp_dir, '.ycm_extra_conf.py' )
339-
with open( extra_conf, 'w' ) as f:
339+
with open( extra_conf, 'w', encoding = 'utf8' ) as f:
340340
f.write( '''
341341
def Settings( **kwargs ):
342342
return { 'flags': [ '-x', 'c++', '-I', 'ycm' ] }

ycmd/tests/clangd/diagnostics_test.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -474,19 +474,19 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
474474
source_contents = """#include "header.h"
475475
int main() {return S::h();}
476476
"""
477-
with open( source_file, 'w' ) as sf:
477+
with open( source_file, 'w', encoding = 'utf8' ) as sf:
478478
sf.write( source_contents )
479479

480480
header_file = os.path.join( tmp_dir, 'header.h' )
481481
old_header_content = """#pragma once
482482
struct S{static int h();};
483483
"""
484-
with open( header_file, 'w' ) as hf:
484+
with open( header_file, 'w', encoding = 'utf8' ) as hf:
485485
hf.write( old_header_content )
486486

487487
flags_file = os.path.join( tmp_dir, 'compile_flags.txt' )
488488
flags_content = """-xc++"""
489-
with open( flags_file, 'w' ) as ff:
489+
with open( flags_file, 'w', encoding = 'utf8' ) as ff:
490490
ff.write( flags_content )
491491

492492
messages_request = { 'contents': source_contents,
@@ -502,7 +502,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
502502
new_header_content = """#pragma once
503503
static int h();
504504
"""
505-
with open( header_file, 'w' ) as f:
505+
with open( header_file, 'w', encoding = 'utf8' ) as f:
506506
f.write( new_header_content )
507507

508508
# Send BufferSaved notification for the header
@@ -548,7 +548,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
548548
break
549549

550550
# Restore original content
551-
with open( header_file, 'w' ) as f:
551+
with open( header_file, 'w', encoding = 'utf8' ) as f:
552552
f.write( old_header_content )
553553

554554
# Send BufferSaved notification for the header
@@ -571,5 +571,5 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
571571
break
572572

573573
# Assert no dirty files
574-
with open( header_file, 'r' ) as f:
574+
with open( header_file, 'r', encoding = 'utf8' ) as f:
575575
assert_that( f.read(), equal_to( old_header_content ) )

ycmd/tests/clangd/utilities_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def test_ClangdCompleter_GetClangdCommand_CustomBinary( self ):
104104
( 13, 0, 0 ),
105105
( 13, 10, 10 ),
106106
( 100, 100, 100 ) ] )
107-
def test_ClangdCompleter_CheckClangdVersion( *args ):
107+
def test_ClangdCompleter_CheckClangdVersion( self, *args ):
108108
assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
109109
equal_to( True ) )
110110
assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),

ycmd/tests/cs/debug_info_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,14 +193,14 @@ def test_GetCompleter_RoslynFound( self ):
193193

194194
@patch( 'ycmd.completers.cs.cs_completer.PATH_TO_OMNISHARP_ROSLYN_BINARY',
195195
None )
196-
def test_GetCompleter_RoslynNotFound( *args ):
196+
def test_GetCompleter_RoslynNotFound( self, *args ):
197197
assert_that( not GetCompleter( user_options_store.GetAll() ) )
198198

199199

200200
@patch( 'ycmd.completers.cs.cs_completer.FindExecutableWithFallback',
201201
wraps = lambda x, fb: x if x == 'roslyn' else fb )
202202
@patch( 'os.path.isfile', return_value = True )
203-
def test_GetCompleter_RoslynFromUserOption( *args ):
203+
def test_GetCompleter_RoslynFromUserOption( self, *args ):
204204
user_options = user_options_store.GetAll().copy(
205205
roslyn_binary_path = 'roslyn' )
206206
assert_that( GetCompleter( user_options )._roslyn_path,

0 commit comments

Comments
 (0)