YouCompleteMe/python/ycm/completers/cs/cs_completer.py

233 lines
7.7 KiB
Python
Raw Normal View History

#!/usr/bin/env python
#
# Copyright (C) 2011, 2012 Chiel ten Brinke <ctenbrinke@gmail.com>
# Strahinja Val Markovic <val@markovic.io>
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
2013-06-21 16:26:11 -04:00
import os
from sys import platform
2013-06-21 16:26:11 -04:00
import glob
from ycm.completers.threaded_completer import ThreadedCompleter
from ycm.server import responses
from ycm import utils
import urllib2
import urllib
import urlparse
import json
2013-06-28 15:15:05 -04:00
import subprocess
import logging
SERVER_NOT_FOUND_MSG = ( 'OmniSharp server binary not found at {0}. ' +
'Did you compile it? You can do so by running ' +
'"./install.sh --omnisharp-completer".' )
class CsharpCompleter( ThreadedCompleter ):
"""
A Completer that uses the Omnisharp server as completion engine.
"""
def __init__( self, user_options ):
super( CsharpCompleter, self ).__init__( user_options )
2013-08-15 05:50:54 -04:00
self._omnisharp_port = None
self._logger = logging.getLogger( __name__ )
# if self.user_options[ 'auto_start_csharp_server' ]:
# self._StartServer()
2013-07-07 16:36:05 -04:00
2013-07-17 21:29:34 -04:00
2013-07-08 05:39:17 -04:00
def OnVimLeave( self ):
if ( self.user_options[ 'auto_start_csharp_server' ] and
2013-08-14 21:57:41 -04:00
self._ServerIsRunning() ):
2013-07-08 08:39:43 -04:00
self._StopServer()
2013-07-17 21:29:34 -04:00
def SupportedFiletypes( self ):
""" Just csharp """
2013-06-28 15:15:05 -04:00
return [ 'cs' ]
2013-07-17 21:29:34 -04:00
def ComputeCandidates( self, request_data ):
return [ responses.BuildCompletionData(
completion[ 'CompletionText' ],
completion[ 'DisplayText' ],
completion[ 'Description' ] )
for completion in self._GetCompletions( request_data ) ]
2013-07-17 21:29:34 -04:00
2013-06-13 17:34:34 -04:00
def DefinedSubcommands( self ):
2013-06-28 15:15:05 -04:00
return [ 'StartServer',
2013-07-07 16:36:05 -04:00
'StopServer',
2013-08-15 06:17:42 -04:00
'RestartServer',
'GoToDefinition',
'GoToDeclaration',
'GoToDefinitionElseDeclaration' ]
2013-06-13 17:34:34 -04:00
2013-07-17 21:29:34 -04:00
def OnUserCommand( self, arguments, request_data ):
2013-06-13 17:34:34 -04:00
if not arguments:
raise ValueError( self.UserCommandsHelpMessage() )
2013-06-13 17:34:34 -04:00
command = arguments[ 0 ]
if command == 'StartServer':
self._StartServer( request_data )
2013-06-13 17:34:34 -04:00
elif command == 'StopServer':
self._StopServer()
2013-07-07 16:36:05 -04:00
elif command == 'RestartServer':
2013-07-08 05:44:06 -04:00
if self._ServerIsRunning():
self._StopServer()
self._StartServer( request_data )
2013-08-16 05:11:32 -04:00
elif command in [ 'GoToDefinition',
'GoToDeclaration',
'GoToDefinitionElseDeclaration' ]:
return self._GoToDefinition( request_data )
2013-06-13 17:34:34 -04:00
2013-07-17 21:29:34 -04:00
2013-08-14 10:34:44 -04:00
def DebugInfo( self ):
if self._ServerIsRunning():
return 'Server running at: {}\nLogfiles:\n{}\n{}'.format(
self._PortToHost(), self._filename_stdout, self._filename_stderr )
2013-08-14 10:34:44 -04:00
else:
2013-08-14 11:02:10 -04:00
return 'Server is not running'
2013-08-14 10:34:44 -04:00
def _StartServer( self, request_data ):
2013-06-13 17:34:34 -04:00
""" Start the OmniSharp server """
2013-08-14 09:40:43 -04:00
self._omnisharp_port = self._FindFreePort()
solutionfiles, folder = _FindSolutionFiles( request_data[ 'filepath' ] )
if len( solutionfiles ) == 0:
raise RuntimeError(
'Error starting OmniSharp server: no solutionfile found' )
elif len( solutionfiles ) == 1:
solutionfile = solutionfiles[ 0 ]
else:
raise RuntimeError(
'Found multiple solution files instead of one!\n{}'.format(
solutionfiles ) )
omnisharp = os.path.join(
os.path.abspath( os.path.dirname( __file__ ) ),
'OmniSharpServer/OmniSharp/bin/Debug/OmniSharp.exe' )
if not os.path.isfile( omnisharp ):
raise RuntimeError( SERVER_NOT_FOUND_MSG.format( omnisharp ) )
2013-07-18 11:18:17 -04:00
if not platform.startswith( 'win' ):
2013-07-19 06:16:16 -04:00
omnisharp = 'mono ' + omnisharp
2013-08-14 09:40:43 -04:00
path_to_solutionfile = os.path.join( folder, solutionfile )
# command has to be provided as one string for some reason
command = [ omnisharp + ' -p ' + str( self._omnisharp_port ) + ' -s ' +
2013-08-14 09:40:43 -04:00
path_to_solutionfile ]
filename_format = os.path.join( utils.PathToTempDir(),
'omnisharp_{port}_{sln}_{std}.log' )
2013-08-14 21:57:41 -04:00
2013-08-14 10:34:44 -04:00
self._filename_stdout = filename_format.format(
2013-08-14 11:02:10 -04:00
port=self._omnisharp_port, sln=solutionfile, std='stdout' )
2013-08-14 10:34:44 -04:00
self._filename_stderr = filename_format.format(
2013-08-14 11:02:10 -04:00
port=self._omnisharp_port, sln=solutionfile, std='stderr' )
2013-06-13 17:34:34 -04:00
2013-08-14 10:34:44 -04:00
with open( self._filename_stderr, 'w' ) as fstderr:
with open( self._filename_stdout, 'w' ) as fstdout:
subprocess.Popen( command, stdout=fstdout, stderr=fstderr, shell=True )
self._logger.info( 'Starting OmniSharp server' )
2013-06-13 17:34:34 -04:00
def _StopServer( self ):
""" Stop the OmniSharp server """
2013-07-08 05:39:17 -04:00
self._GetResponse( '/stopserver' )
2013-08-15 05:50:54 -04:00
self._omnisharp_port = None
self._logger.info( 'Stopping OmniSharp server' )
2013-06-13 17:34:34 -04:00
def _GetCompletions( self, request_data ):
2013-08-15 06:17:42 -04:00
""" Ask server for completions """
completions = self._GetResponse( '/autocomplete',
self._DefaultParameters( request_data ) )
2013-08-15 06:17:42 -04:00
return completions if completions != None else []
def _GoToDefinition( self, request_data ):
2013-08-16 15:00:26 -04:00
""" Jump to definition of identifier under cursor """
definition = self._GetResponse( '/gotodefinition',
self._DefaultParameters( request_data ) )
2013-08-16 15:00:26 -04:00
if definition[ 'FileName' ] != None:
return responses.BuildGoToResponse( definition[ 'FileName' ],
definition[ 'Line' ],
definition[ 'Column' ] )
2013-08-16 15:00:26 -04:00
else:
raise RuntimeError( 'Can\'t jump to definition' )
2013-08-16 15:00:26 -04:00
2013-08-15 06:17:42 -04:00
def _DefaultParameters( self, request_data ):
2013-08-16 15:00:26 -04:00
""" Some very common request parameters """
2013-08-15 06:17:42 -04:00
parameters = {}
parameters[ 'line' ] = request_data[ 'line_num' ] + 1
parameters[ 'column' ] = request_data[ 'column_num' ] + 1
filepath = request_data[ 'filepath' ]
parameters[ 'buffer' ] = request_data[ 'file_data' ][ filepath ][
'contents' ]
parameters[ 'filename' ] = filepath
2013-08-16 15:00:26 -04:00
return parameters
2013-08-15 06:17:42 -04:00
2013-08-15 05:50:54 -04:00
def _ServerIsRunning( self ):
""" Check if our OmniSharp server is running """
return ( self._omnisharp_port != None and
self._GetResponse( '/checkalivestatus', silent=True ) != None )
2013-06-13 17:34:34 -04:00
2013-07-19 06:16:16 -04:00
def _FindFreePort( self ):
2013-08-15 05:50:54 -04:00
""" Find port without an OmniSharp server running on it """
port = self.user_options[ 'csharp_server_port' ]
2013-08-15 05:50:54 -04:00
while self._GetResponse( '/checkalivestatus',
silent=True,
port=port ) != None:
2013-08-14 09:40:43 -04:00
port += 1
return port
2013-08-14 09:40:43 -04:00
def _PortToHost( self, port=None ):
if port == None:
port = self._omnisharp_port
return 'http://localhost:' + str( port )
2013-07-16 06:33:07 -04:00
2013-08-14 11:02:10 -04:00
def _GetResponse( self, endPoint, parameters={}, silent=False, port=None ):
2013-06-13 17:34:34 -04:00
""" Handle communication with server """
# TODO: Replace usage of urllib with Requests
2013-08-14 11:02:10 -04:00
target = urlparse.urljoin( self._PortToHost( port ), endPoint )
parameters = urllib.urlencode( parameters )
response = urllib2.urlopen( target, parameters )
return json.loads( response.read() )
2013-07-17 21:29:34 -04:00
def _FindSolutionFiles( filepath ):
2013-08-16 15:00:26 -04:00
""" Find solution files by searching upwards in the file tree """
folder = os.path.dirname( filepath )
2013-07-17 21:29:34 -04:00
solutionfiles = glob.glob1( folder, '*.sln' )
while not solutionfiles:
lastfolder = folder
folder = os.path.dirname( folder )
if folder == lastfolder:
break
solutionfiles = glob.glob1( folder, '*.sln' )
return solutionfiles, folder