Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Useful pylint fixes #1715

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .ycm_extra_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@
# For more information, please refer to <http://unlicense.org/>

from sysconfig import get_path
import platform
import os.path as p
import subprocess

DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
Expand Down Expand Up @@ -120,7 +118,7 @@ def FindCorrespondingSourceFile( filename ):
def PathToPythonUsedDuringBuild():
try:
filepath = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' )
with open( filepath ) as f:
with open( filepath, encoding = 'utf8' ) as f:
return f.read().strip()
except OSError:
return None
Expand Down
13 changes: 6 additions & 7 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def UseVsWhere( quiet, vswhere_args ):
latest_full_v = subprocess.check_output( vswhere_args ).strip().decode()
if '.' in latest_full_v:
try:
latest_v = int( latest_full_v.split( '.' )[ 0 ] )
latest_v = int( latest_full_v.split( '.', 1 )[ 0 ] )
except ValueError:
raise ValueError( f"{ latest_full_v } is not a version number." )

Expand Down Expand Up @@ -481,10 +481,10 @@ def ParseArguments():
DEFAULT_RUST_TOOLCHAIN + '" is tested/'
'supported by the maintainers of YCM/ycmd' )
parser.add_argument( '--java-completer', action = 'store_true',
help = 'Enable Java semantic completion engine.' ),
help = 'Enable Java semantic completion engine.' )
parser.add_argument( '--ts-completer', action = 'store_true',
help = 'Enable JavaScript and TypeScript semantic '
'completion engine.' ),
'completion engine.' )
parser.add_argument( '--system-libclang', action = 'store_true',
help = 'Use system libclang instead of downloading one '
'from llvm.org. NOT RECOMMENDED OR SUPPORTED!' )
Expand Down Expand Up @@ -855,7 +855,6 @@ def CleanCsCompleter( build_dir, version ):
if os.path.isfile( file_path ):
os.remove( file_path )
elif os.path.isdir( file_path ):
import shutil
shutil.rmtree( file_path )


Expand Down Expand Up @@ -974,14 +973,14 @@ def EnableGoCompleter( args ):

def WriteToolchainVersion( version ):
path = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' )
with open( path, 'w' ) as f:
with open( path, 'w', encoding = 'utf8' ) as f:
f.write( version )


def ReadToolchainVersion():
try:
filepath = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' )
with open( filepath ) as f:
with open( filepath, encoding = 'utf8' ) as f:
return f.read().strip()
except OSError:
return None
Expand Down Expand Up @@ -1255,7 +1254,7 @@ def Print( msg ):

def WritePythonUsedDuringBuild():
path = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' )
with open( path, 'w' ) as f:
with open( path, 'w', encoding = 'utf8' ) as f:
f.write( sys.executable )


Expand Down
4 changes: 2 additions & 2 deletions run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ def BuildYcmdLibs( args ):
'--core-tests'
]

for key in COMPLETERS:
for key, value in COMPLETERS.items():
if key in args.completers:
build_cmd.extend( COMPLETERS[ key ][ 'build' ] )
build_cmd.extend( value[ 'build' ] )

if args.msvc and platform.system() == 'Windows':
build_cmd.extend( [ '--msvc', str( args.msvc ) ] )
Expand Down
2 changes: 1 addition & 1 deletion update_clang_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def ExtractTar( uncompressed_data, destination ):
tar_file.extractall( destination )

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


def ExtractLZMA( compressed_data, destination ):
Expand Down
4 changes: 2 additions & 2 deletions update_unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ def GenerateNormalizationTestCases( output_file ):
JoinUnicodeToUtf8( captures[ 4 ].split() ) + '"},\n' )

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


Expand All @@ -629,7 +629,7 @@ def GenerateGraphemeBreakTestCases( output_file ):
for x in split_data ] ).rstrip( ',' ) + '}},\n' )

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


Expand Down
2 changes: 1 addition & 1 deletion ycmd/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
def SetupLogging( log_level ):
numeric_level = getattr( logging, log_level.upper(), None )
if not isinstance( numeric_level, int ):
raise ValueError( 'Invalid log level: %s' % log_level )
raise ValueError( f'Invalid log level: { log_level }' )

Check warning on line 136 in ycmd/__main__.py

View check run for this annotation

Codecov / codecov/patch

ycmd/__main__.py#L136

Added line #L136 was not covered by tests

# Has to be called before any call to logging.getLogger()
logging.basicConfig( format = '%(asctime)s - %(levelname)s - %(message)s',
Expand Down
4 changes: 2 additions & 2 deletions ycmd/completers/cpp/clang_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,9 +436,9 @@ def DebugInfo( self, request_data ):

database_item = responses.DebugInfoItem(
key = 'compilation database path',
value = '{0}'.format( database_directory ) )
value = f'{ database_directory }' )
flags_item = responses.DebugInfoItem(
key = 'flags', value = '{0}'.format( list( flags ) ) )
key = 'flags', value = f'{ list( flags ) }' )
filename_item = responses.DebugInfoItem(
key = 'translation unit', value = filename )

Expand Down
3 changes: 1 addition & 2 deletions ycmd/completers/cpp/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,13 +673,12 @@ def UserIncludePaths( user_flags, filename ):
it = iter( user_flags )
for user_flag in it:
user_flag_len = len( user_flag )
for flag in include_flags:
for flag, container in include_flags.items():
if user_flag.startswith( flag ):
flag_len = len( flag )
include_path = ( next( it ) if user_flag_len == flag_len else
user_flag[ flag_len: ] )
if include_path:
container = include_flags[ flag ]
container.append( ToUnicode( include_path ) )
break
except StopIteration:
Expand Down
2 changes: 1 addition & 1 deletion ycmd/completers/cs/cs_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ def _GetSolutionFile( self, filepath ):
return self._solution_for_file[ filepath ]


class CsharpSolutionCompleter( object ):
class CsharpSolutionCompleter:
def __init__( self,
solution_path,
keep_logfiles,
Expand Down
10 changes: 5 additions & 5 deletions ycmd/completers/language_server/generic_lsp_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@
cmd = utils.FindExecutable( self._command_line[ 0 ] )

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

Check warning on line 51 in ycmd/completers/language_server/generic_lsp_completer.py

View check run for this annotation

Codecov / codecov/patch

ycmd/completers/language_server/generic_lsp_completer.py#L51

Added line #L51 was not covered by tests
"Cannot use %s completer.",
self._command_line[ 0 ],
self._name )
raise RuntimeError( f"Invalid cmdline: { self._command_line }" )

Check warning on line 55 in ycmd/completers/language_server/generic_lsp_completer.py

View check run for this annotation

Codecov / codecov/patch

ycmd/completers/language_server/generic_lsp_completer.py#L55

Added line #L55 was not covered by tests

self._command_line[ 0 ] = cmd
for idx in range( len( self._command_line ) ):
Expand Down
12 changes: 6 additions & 6 deletions ycmd/completers/language_server/language_server_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,8 +565,8 @@
key, value = utils.ToUnicode( line ).split( ':', 1 )
headers[ key.strip() ] = value.strip()
except Exception:
LOGGER.exception( 'Received invalid protocol data from server: '
+ str( line ) )
LOGGER.exception(

Check warning on line 568 in ycmd/completers/language_server/language_server_completer.py

View check run for this annotation

Codecov / codecov/patch

ycmd/completers/language_server/language_server_completer.py#L568

Added line #L568 was not covered by tests
'Received invalid protocol data from server: %s', line )
raise

read_bytes += 1
Expand Down Expand Up @@ -1102,7 +1102,7 @@
self._project_directory,
lambda globs: WatchdogHandler( self, globs ),
self._port,
lambda request: self.WorkspaceConfigurationResponse( request ),
self.WorkspaceConfigurationResponse,
self.GetDefaultNotificationHandler() )
else:
self._stderr_file = utils.CreateLogfile(
Expand All @@ -1122,7 +1122,7 @@
lambda globs: WatchdogHandler( self, globs ),
self._server_handle.stdin,
self._server_handle.stdout,
lambda request: self.WorkspaceConfigurationResponse( request ),
self.WorkspaceConfigurationResponse,
self.GetDefaultNotificationHandler() )
)

Expand Down Expand Up @@ -3071,7 +3071,7 @@
if response is not None:
return response

if len( edits ):
if edits:
fixits = [ WorkspaceEditToFixIt(
request_data,
e[ 'edit' ],
Expand Down Expand Up @@ -3427,7 +3427,7 @@
lsp_location = symbol
lsp_location[ 'uri' ] = lsp.FilePathToUri( request_data[ 'filepath' ] )

location, line_value = _LspLocationToLocationAndDescription(
location, _ = _LspLocationToLocationAndDescription(
request_data,
lsp_location )

Expand Down
9 changes: 0 additions & 9 deletions ycmd/completers/python/python_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,12 +650,3 @@ def _OffsetToPosition( start_end, filename, text, newlines ):
if len( loc ) == 2:
break
return loc

# Invalid position - it's outside of the text. Just return the last
# position in the text. This is an internal error.
LOGGER.error( "Invalid offset %s in file %s with text %s and newlines %s",
offset,
filename,
text,
newlines )
raise RuntimeError( "Invalid file offset in diff" )
7 changes: 3 additions & 4 deletions ycmd/completers/typescript/typescript_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@
LOGGER.info( 'Received %s event from TSServer', eventname )
continue
if msgtype != 'response':
LOGGER.error( 'Unsupported message type', msgtype )
LOGGER.error( 'Unsupported message type: %s', msgtype )

Check warning on line 268 in ycmd/completers/typescript/typescript_completer.py

View check run for this annotation

Codecov / codecov/patch

ycmd/completers/typescript/typescript_completer.py#L268

Added line #L268 was not covered by tests
continue

seq = message[ 'request_seq' ]
Expand Down Expand Up @@ -373,9 +373,8 @@

filename = request_data[ 'filepath' ]
contents = request_data[ 'file_data' ][ filename ][ 'contents' ]
tmpfile = NamedTemporaryFile( delete = False )
tmpfile.write( utils.ToBytes( contents ) )
tmpfile.close()
with NamedTemporaryFile( delete = False ) as tmpfile:
tmpfile.write( utils.ToBytes( contents ) )
self._SendRequest( 'reload', {
'file': filename,
'tmpfile': tmpfile.name
Expand Down
2 changes: 1 addition & 1 deletion ycmd/tests/clang/flags_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def Settings( **kwargs ):
assert_that( filename, equal_to( '/foo' ) )


def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( *args ):
def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( self, *args ):
flags_object = flags.Flags()

def Settings( **kwargs ):
Expand Down
4 changes: 2 additions & 2 deletions ycmd/tests/clang/include_cache_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def test_IncludeCache_Cached_NewMtime( self ):
include_cache = IncludeCache()
assert_that( include_cache._cache, equal_to( {} ) )
foo_path = os.path.join( tmp_dir, 'foo' )
with open( foo_path, 'w' ) as foo_file:
with open( foo_path, 'w', encoding = 'utf8' ) as foo_file:
foo_file.write( 'foo' )

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

bar_path = os.path.join( tmp_dir, 'bar' )
with open( bar_path, 'w' ) as bar_file:
with open( bar_path, 'w', encoding = 'utf8' ) as bar_file:
bar_file.write( 'bar' )

new_includes = include_cache.GetIncludes( tmp_dir )
Expand Down
2 changes: 1 addition & 1 deletion ycmd/tests/clangd/debug_info_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def test_DebugInfo_ExtraConf_UseLocalOverDatabase( self, app ):

with TemporaryClangProject( tmp_dir, database ):
extra_conf = os.path.join( tmp_dir, '.ycm_extra_conf.py' )
with open( extra_conf, 'w' ) as f:
with open( extra_conf, 'w', encoding = 'utf8' ) as f:
f.write( '''
def Settings( **kwargs ):
return { 'flags': [ '-x', 'c++', '-I', 'ycm' ] }
Expand Down
12 changes: 6 additions & 6 deletions ycmd/tests/clangd/diagnostics_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,19 +520,19 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
source_contents = """#include "header.h"
int main() {return S::h();}
"""
with open( source_file, 'w' ) as sf:
with open( source_file, 'w', encoding = 'utf8' ) as sf:
sf.write( source_contents )

header_file = os.path.join( tmp_dir, 'header.h' )
old_header_content = """#pragma once
struct S{static int h();};
"""
with open( header_file, 'w' ) as hf:
with open( header_file, 'w', encoding = 'utf8' ) as hf:
hf.write( old_header_content )

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

messages_request = { 'contents': source_contents,
Expand All @@ -548,7 +548,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
new_header_content = """#pragma once
static int h();
"""
with open( header_file, 'w' ) as f:
with open( header_file, 'w', encoding = 'utf8' ) as f:
f.write( new_header_content )

# Send BufferSaved notification for the header
Expand Down Expand Up @@ -594,7 +594,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
break

# Restore original content
with open( header_file, 'w' ) as f:
with open( header_file, 'w', encoding = 'utf8' ) as f:
f.write( old_header_content )

# Send BufferSaved notification for the header
Expand All @@ -617,5 +617,5 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ):
break

# Assert no dirty files
with open( header_file, 'r' ) as f:
with open( header_file, 'r', encoding = 'utf8' ) as f:
assert_that( f.read(), equal_to( old_header_content ) )
2 changes: 1 addition & 1 deletion ycmd/tests/clangd/utilities_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def test_ClangdCompleter_GetClangdCommand_CustomBinary( self ):
( 13, 0, 0 ),
( 13, 10, 10 ),
( 100, 100, 100 ) ] )
def test_ClangdCompleter_CheckClangdVersion( *args ):
def test_ClangdCompleter_CheckClangdVersion( self, *args ):
assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
equal_to( True ) )
assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
Expand Down
2 changes: 1 addition & 1 deletion ycmd/tests/cs/debug_info_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def test_GetCompleter_RoslynFound( self ):

@patch( 'ycmd.completers.cs.cs_completer.PATH_TO_OMNISHARP_ROSLYN_BINARY',
None )
def test_GetCompleter_RoslynNotFound( *args ):
def test_GetCompleter_RoslynNotFound( self, *args ):
assert_that( not GetCompleter( user_options_store.GetAll() ) )


Expand Down
8 changes: 4 additions & 4 deletions ycmd/tests/identifier_completer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def test_GetCursorIdentifier_IgnoreIdentifierFromCommentsAndStrings( self ):
4 ) ) ) )
assert_that( '', equal_to(
ic._GetCursorIdentifier( False,
BuildRequestWrap( '/*\n' ' * foobar\n' ' */',
BuildRequestWrap( '/*\n * foobar\n */',
5,
2 ) ) ) )

Expand All @@ -133,7 +133,7 @@ def test_GetCursorIdentifier_CollectIdentifierFromCommentsAndStrings( self ):
4 ) ) ) )
assert_that( 'foobar', equal_to(
ic._GetCursorIdentifier( True,
BuildRequestWrap( '/*\n' ' * foobar\n' ' */',
BuildRequestWrap( '/*\n * foobar\n */',
5,
2 ) ) ) )

Expand Down Expand Up @@ -254,7 +254,7 @@ def test_PreviousIdentifier_IgnoreIdentifierFromCommentsAndStrings( self ):
assert_that( '', equal_to(
ic._PreviousIdentifier( 2,
False,
BuildRequestWrap( '/*\n' ' * foo\n' ' */',
BuildRequestWrap( '/*\n * foo\n */',
column_num = 2,
line_num = 3 ) ) ) )

Expand All @@ -269,7 +269,7 @@ def test_PreviousIdentifier_CollectIdentifierFromCommentsAndStrings( self ):
assert_that( 'foo', equal_to(
ic._PreviousIdentifier( 2,
True,
BuildRequestWrap( '/*\n' ' * foo\n' ' */',
BuildRequestWrap( '/*\n * foo\n */',
column_num = 2,
line_num = 3 ) ) ) )

Expand Down
Loading
Loading