Пример #1
0
    def _StartServer(self):
        """Start the Gocode server."""
        with self._gocode_lock:
            _logger.info('Starting Gocode server')

            self._gocode_port = utils.GetUnusedLocalhostPort()
            self._gocode_address = '127.0.0.1:{0}'.format(self._gocode_port)

            command = [
                self._gocode_binary_path, '-s', '-sock', 'tcp', '-addr',
                self._gocode_address
            ]

            if _logger.isEnabledFor(logging.DEBUG):
                command.append('-debug')

            self._gocode_stdout = LOG_FILENAME_FORMAT.format(
                port=self._gocode_port, std='stdout')
            self._gocode_stderr = LOG_FILENAME_FORMAT.format(
                port=self._gocode_port, std='stderr')

            with open(self._gocode_stdout, 'w') as stdout:
                with open(self._gocode_stderr, 'w') as stderr:
                    self._gocode_handle = utils.SafePopen(command,
                                                          stdout=stdout,
                                                          stderr=stderr)
Пример #2
0
  def __init__( self, user_options ):
    super( TypeScriptCompleter, self ).__init__( user_options )

    # Used to prevent threads from concurrently reading and writing to
    # the tsserver process' stdout and stdin
    self._lock = Lock()

    binarypath = utils.PathToFirstExistingExecutable( [ 'tsserver' ] )
    if not binarypath:
      _logger.error( BINARY_NOT_FOUND_MESSAGE )
      raise RuntimeError( BINARY_NOT_FOUND_MESSAGE )

    # Each request sent to tsserver must have a sequence id.
    # Responses contain the id sent in the corresponding request.
    self._sequenceid = 0

    # TSServer ignores the fact that newlines are two characters on Windows
    # (\r\n) instead of one on other platforms (\n), so we use the
    # universal_newlines option to convert those newlines to \n. See the issue
    # https://github.com/Microsoft/TypeScript/issues/3403
    # TODO: remove this option when the issue is fixed.
    # We also need to redirect the error stream to the output one on Windows.
    self._tsserver_handle = utils.SafePopen( binarypath,
                                             stdout = subprocess.PIPE,
                                             stdin = subprocess.PIPE,
                                             stderr = subprocess.STDOUT,
                                             universal_newlines = True )

    _logger.info( 'Enabling typescript completion' )
Пример #3
0
def SafePopen_ReplaceStdinWindowsPIPEOnWindows_test(*args):
    utils.SafePopen(['foo'], stdin_windows=subprocess.PIPE)
    eq_(
        subprocess.Popen.call_args,
        call(['foo'],
             stdin=subprocess.PIPE,
             creationflags=utils.CREATE_NO_WINDOW))
Пример #4
0
    def StartServer(self, request_data):
        with self._server_state_mutex:
            if self.ServerIsHealthy():
                return

            # Ensure we cleanup all states.
            self._Reset()

            LOGGER.info('Starting clangd: %s', self._clangd_command)
            self._stderr_file = utils.CreateLogfile('clangd_stderr')
            with utils.OpenForStdHandle(self._stderr_file) as stderr:
                self._server_handle = utils.SafePopen(self._clangd_command,
                                                      stdin=subprocess.PIPE,
                                                      stdout=subprocess.PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                LOGGER.error('clangd failed to start, or did not connect '
                             'successfully')
                self.Shutdown()
                return

        LOGGER.info('clangd started')

        self.SendInitialize(request_data)
Пример #5
0
  def _StartServerNoLock( self ):
    if self._ServerIsRunning():
      return

    self._logfile = utils.CreateLogfile( LOGFILE_FORMAT )
    tsserver_log = f'-file { self._logfile } -level {_LogLevel()}'
    # TSServer gets the configuration for the log file through the
    # environment variable 'TSS_LOG'. This seems to be undocumented but
    # looking at the source code it seems like this is the way:
    # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136
    environ = os.environ.copy()
    environ[ 'TSS_LOG' ] = tsserver_log

    LOGGER.info( 'TSServer log file: %s', self._logfile )

    # We need to redirect the error stream to the output one on Windows.
    self._tsserver_handle = utils.SafePopen( self._tsserver_executable,
                                             stdin = subprocess.PIPE,
                                             stdout = subprocess.PIPE,
                                             stderr = subprocess.STDOUT,
                                             env = environ )

    LOGGER.info( "TSServer started with PID %s", self._tsserver_handle.pid )
    self._tsserver_is_running.set()

    utils.StartThread( self._SetServerVersion )
Пример #6
0
  def _SetUpServer( self ):
    self._available_completers = {}
    self._user_notified_about_crash = False
    self._filetypes_with_keywords_loaded = set()
    self._server_is_ready_with_cache = False
    self._message_poll_request = None

    self._user_options = base.GetUserOptions()
    self._omnicomp = OmniCompleter( self._user_options )
    self._buffers = BufferDict( self._user_options )

    self._SetLogLevel()

    hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
    options_dict = dict( self._user_options )
    options_dict[ 'hmac_secret' ] = utils.ToUnicode(
      base64.b64encode( hmac_secret ) )
    options_dict[ 'server_keep_logfiles' ] = self._user_options[
      'keep_logfiles' ]

    # The temp options file is deleted by ycmd during startup.
    with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
      json.dump( options_dict, options_file )

    server_port = utils.GetUnusedLocalhostPort()

    BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
    BaseRequest.hmac_secret = hmac_secret

    try:
      python_interpreter = paths.PathToPythonInterpreter()
    except RuntimeError as error:
      error_message = (
        "Unable to start the ycmd server. {0}. "
        "Correct the error then restart the server "
        "with ':YcmRestartServer'.".format( str( error ).rstrip( '.' ) ) )
      self._logger.exception( error_message )
      vimsupport.PostVimMessage( error_message )
      return

    args = [ python_interpreter,
             paths.PathToServerScript(),
             '--port={0}'.format( server_port ),
             '--options_file={0}'.format( options_file.name ),
             '--log={0}'.format( self._user_options[ 'log_level' ] ),
             '--idle_suicide_seconds={0}'.format(
                SERVER_IDLE_SUICIDE_SECONDS ) ]

    self._server_stdout = utils.CreateLogfile(
        SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
    self._server_stderr = utils.CreateLogfile(
        SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
    args.append( '--stdout={0}'.format( self._server_stdout ) )
    args.append( '--stderr={0}'.format( self._server_stderr ) )

    if self._user_options[ 'keep_logfiles' ]:
      args.append( '--keep_logfiles' )

    self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
                                          stdout = PIPE, stderr = PIPE )
Пример #7
0
    def _StartServer(self):
        with self._server_lock:
            if self._ServerIsRunning():
                return

            self._logfile = _LogFileName()
            tsserver_log = '-file {path} -level {level}'.format(
                path=self._logfile, level=_LogLevel())
            # TSServer gets the configuration for the log file through the
            # environment variable 'TSS_LOG'. This seems to be undocumented but
            # looking at the source code it seems like this is the way:
            # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136
            environ = os.environ.copy()
            utils.SetEnviron(environ, 'TSS_LOG', tsserver_log)

            _logger.info('TSServer log file: {0}'.format(self._logfile))

            # We need to redirect the error stream to the output one on Windows.
            self._tsserver_handle = utils.SafePopen(PATH_TO_TSSERVER,
                                                    stdin=subprocess.PIPE,
                                                    stdout=subprocess.PIPE,
                                                    stderr=subprocess.STDOUT,
                                                    env=environ)

            self._tsserver_is_running.set()
Пример #8
0
    def _StartServer(self):
        with self._server_lock:
            self._logger.info('Starting JediHTTP server')
            self._jedihttp_port = utils.GetUnusedLocalhostPort()
            self._jedihttp_host = ToBytes('http://127.0.0.1:{0}'.format(
                self._jedihttp_port))
            self._logger.info('using port {0}'.format(self._jedihttp_port))
            self._hmac_secret = self._GenerateHmacSecret()

            # JediHTTP will delete the secret_file after it's done reading it
            with NamedTemporaryFile(delete=False, mode='w+') as hmac_file:
                json.dump(
                    {'hmac_secret': ToUnicode(b64encode(self._hmac_secret))},
                    hmac_file)
                command = [
                    self._python_binary_path, PATH_TO_JEDIHTTP, '--port',
                    str(self._jedihttp_port), '--log',
                    self._GetLoggingLevel(), '--hmac-file-secret',
                    hmac_file.name
                ]

            self._logfile_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._jedihttp_port, std='stdout'))
            self._logfile_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._jedihttp_port, std='stderr'))

            with utils.OpenForStdHandle(self._logfile_stdout) as logout:
                with utils.OpenForStdHandle(self._logfile_stderr) as logerr:
                    self._jedihttp_phandle = utils.SafePopen(command,
                                                             stdout=logout,
                                                             stderr=logerr)
Пример #9
0
    def _StartServer(self):
        with self._server_lock:
            self._logger.info('Starting SSVIM server')
            self._http_port = utils.GetUnusedLocalhostPort()
            self._http_host = ToBytes('http://{0}:{1}'.format(
                SSVIM_IP, self._http_port))
            self._logger.info('using port {0}'.format(self._http_port))
            self._hmac_secret = self._GenerateHmacSecret()

            # The server will delete the secret_file after it's done reading it
            with NamedTemporaryFile(delete=False, mode='w+') as hmac_file:
                json.dump(
                    {'hmac_secret': ToUnicode(b64encode(self._hmac_secret))},
                    hmac_file)
                command = [
                    PATH_TO_SSVIMHTTP, '--ip', SSVIM_IP, '--port',
                    str(self._http_port), '--log',
                    self._GetLoggingLevel(), '--hmac-file-secret',
                    hmac_file.name
                ]

                self._logfile_stdout = utils.CreateLogfile(
                    LOGFILE_FORMAT.format(port=self._http_port, std='stdout'))
                self._logfile_stderr = utils.CreateLogfile(
                    LOGFILE_FORMAT.format(port=self._http_port, std='stderr'))

                with utils.OpenForStdHandle(self._logfile_stdout) as logout:
                    with utils.OpenForStdHandle(
                            self._logfile_stderr) as logerr:
                        self._http_phandle = utils.SafePopen(command,
                                                             stdout=logout,
                                                             stderr=logerr)

            self._WaitForInitialSwiftySwiftVimBoot()
            self._logger.info('Started SSVIM server')
Пример #10
0
    def StartServer(self, request_data):
        with self._server_state_mutex:
            LOGGER.info('Starting %s: %s', self.GetServerName(),
                        self.GetCommandLine())

            self._stderr_file = utils.CreateLogfile('{}_stderr'.format(
                utils.MakeSafeFileNameString(self.GetServerName())))

            with utils.OpenForStdHandle(self._stderr_file) as stderr:
                self._server_handle = utils.SafePopen(self.GetCommandLine(),
                                                      stdin=subprocess.PIPE,
                                                      stdout=subprocess.PIPE,
                                                      stderr=stderr)

            self._connection = (lsc.StandardIOLanguageServerConnection(
                self._server_handle.stdin, self._server_handle.stdout,
                self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except lsc.LanguageServerConnectionTimeout:
                LOGGER.error(
                    '%s failed to start, or did not connect successfully',
                    self.GetServerName())
                self.Shutdown()
                return False

        LOGGER.info('%s started', self.GetServerName())

        return True
Пример #11
0
    def _StartServer(self):
        """Start the Gocode server."""
        with self._gocode_lock:
            _logger.info('Starting Gocode server')

            self._gocode_port = utils.GetUnusedLocalhostPort()
            self._gocode_host = '127.0.0.1:{0}'.format(self._gocode_port)

            command = [
                self._gocode_binary_path, '-s', '-sock', 'tcp', '-source',
                '-addr', self._gocode_host
            ]

            if _logger.isEnabledFor(logging.DEBUG):
                command.append('-debug')

            self._gocode_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._gocode_port, std='stdout'))
            self._gocode_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._gocode_port, std='stderr'))

            with utils.OpenForStdHandle(self._gocode_stdout) as stdout:
                with utils.OpenForStdHandle(self._gocode_stderr) as stderr:
                    self._gocode_handle = utils.SafePopen(command,
                                                          stdout=stdout,
                                                          stderr=stderr)
Пример #12
0
  def _StartServer( self ):
    with self._server_state_mutex:
      if self._ServerIsRunning():
        return

      _logger.info( 'Starting Tern server...' )

      self._server_port = utils.GetUnusedLocalhostPort()

      if _logger.isEnabledFor( logging.DEBUG ):
        extra_args = [ '--verbose' ]
      else:
        extra_args = []

      command = [ PATH_TO_NODE,
                  PATH_TO_TERN_BINARY,
                  '--port',
                  str( self._server_port ),
                  '--host',
                  SERVER_HOST,
                  '--persistent',
                  '--no-port-file' ] + extra_args

      _logger.debug( 'Starting tern with the following command: '
                    + ' '.join( command ) )

      try:
        self._server_stdout = utils.CreateLogfile(
            LOGFILE_FORMAT.format( port = self._server_port, std = 'stdout' ) )

        self._server_stderr = utils.CreateLogfile(
            LOGFILE_FORMAT.format( port = self._server_port, std = 'stderr' ) )

        # We need to open a pipe to stdin or the Tern server is killed.
        # See https://github.com/ternjs/tern/issues/740#issuecomment-203979749
        # For unknown reasons, this is only needed on Windows and for Python
        # 3.4+ on other platforms.
        with utils.OpenForStdHandle( self._server_stdout ) as stdout:
          with utils.OpenForStdHandle( self._server_stderr ) as stderr:
            self._server_handle = utils.SafePopen( command,
                                                  stdin = PIPE,
                                                  stdout = stdout,
                                                  stderr = stderr )
      except Exception:
        _logger.exception( 'Unable to start Tern server' )
        self._CleanUp()

      if self._server_port and self._ServerIsRunning():
        _logger.info( 'Tern Server started with pid: ' +
                      str( self._server_handle.pid ) +
                      ' listening on port ' +
                      str( self._server_port ) )
        _logger.info( 'Tern Server log files are: ' +
                      self._server_stdout +
                      ' and ' +
                      self._server_stderr )

        self._do_tern_project_check = True
      else:
        _logger.warning( 'Tern server did not start successfully' )
Пример #13
0
    def _StartServerNoLock(self):
        """Start the server, under the lock.

    Callers must hold self._server_state_mutex"""

        if self._ServerIsRunning():
            return

        _logger.info('Starting Tern.js server...')

        self._server_port = utils.GetUnusedLocalhostPort()

        if _logger.isEnabledFor(logging.DEBUG):
            extra_args = ['--verbose']
        else:
            extra_args = []

        command = [
            PATH_TO_NODE, PATH_TO_TERNJS_BINARY, '--port',
            str(self._server_port), '--host', SERVER_HOST, '--persistent',
            '--no-port-file'
        ] + extra_args

        _logger.debug('Starting tern with the following command: ' +
                      ' '.join(command))

        try:
            logfile_format = os.path.join(utils.PathToCreatedTempDir(),
                                          u'tern_{port}_{std}.log')

            self._server_stdout = logfile_format.format(port=self._server_port,
                                                        std='stdout')

            self._server_stderr = logfile_format.format(port=self._server_port,
                                                        std='stderr')

            # On Windows, we need to open a pipe to stdin to prevent Tern crashing
            # with following error: "Implement me. Unknown stdin file type!"
            with utils.OpenForStdHandle(self._server_stdout) as stdout:
                with utils.OpenForStdHandle(self._server_stderr) as stderr:
                    self._server_handle = utils.SafePopen(command,
                                                          stdin_windows=PIPE,
                                                          stdout=stdout,
                                                          stderr=stderr)
        except Exception:
            _logger.warning('Unable to start Tern.js server: ' +
                            traceback.format_exc())
            self._Reset()

        if self._server_port > 0 and self._ServerIsRunning():
            _logger.info('Tern.js Server started with pid: ' +
                         str(self._server_handle.pid) + ' listening on port ' +
                         str(self._server_port))
            _logger.info('Tern.js Server log files are: ' +
                         self._server_stdout + ' and ' + self._server_stderr)

            self._do_tern_project_check = True
        else:
            _logger.warning('Tern.js server did not start successfully')
Пример #14
0
def _GetRustSysroot( rustc_exec ):
  return ToUnicode( utils.SafePopen( [ rustc_exec,
                                        '--print',
                                        'sysroot' ],
                                      stdin_windows = subprocess.PIPE,
                                      stdout = subprocess.PIPE,
                                      stderr = subprocess.PIPE )
                              .communicate()[ 0 ].rstrip() )
Пример #15
0
 def test_SafePopen_ReplaceStdinWindowsPIPEOnWindows(self, *args):
     utils.SafePopen(['foo'], stdin_windows=subprocess.PIPE)
     assert_that(
         subprocess.Popen.call_args,
         equal_to(
             call(['foo'],
                  stdin=subprocess.PIPE,
                  creationflags=utils.CREATE_NO_WINDOW)))
Пример #16
0
    def _StartServer(self, request_data):
        with self._server_state_mutex:
            if self._server_started:
                return

            self._server_started = True

            _logger.info('Starting jdt.ls Language Server...')

            self._project_dir = _FindProjectDir(
                os.path.dirname(request_data['filepath']))
            self._workspace_path = _WorkspaceDirForProject(
                self._project_dir, self._use_clean_workspace)

            command = [
                PATH_TO_JAVA,
                '-Dfile.encoding=UTF-8',
                '-Declipse.application=org.eclipse.jdt.ls.core.id1',
                '-Dosgi.bundles.defaultStartLevel=4',
                '-Declipse.product=org.eclipse.jdt.ls.core.product',
                '-Dlog.level=ALL',
                '-jar',
                self._launcher_path,
                '-configuration',
                self._launcher_config,
                '-data',
                self._workspace_path,
            ]

            _logger.debug('Starting java-server with the following command: '
                          '{0}'.format(' '.join(command)))

            self._server_stderr = utils.CreateLogfile('jdt.ls_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                _logger.error('jdt.ls failed to start, or did not connect '
                              'successfully')
                self._StopServer()
                return

        _logger.info('jdt.ls Language Server started')

        self.SendInitialize(request_data)
Пример #17
0
    def __init__(self, user_options):
        super(TypeScriptCompleter, self).__init__(user_options)

        # Used to prevent threads from concurrently writing to
        # the tsserver process' stdin
        self._writelock = Lock()

        binarypath = utils.PathToFirstExistingExecutable(['tsserver'])
        if not binarypath:
            _logger.error(BINARY_NOT_FOUND_MESSAGE)
            raise RuntimeError(BINARY_NOT_FOUND_MESSAGE)

        self._logfile = _LogFileName()
        tsserver_log = '-file {path} -level {level}'.format(path=self._logfile,
                                                            level=_LogLevel())
        # TSServer get the configuration for the log file through the environment
        # variable 'TSS_LOG'. This seems to be undocumented but looking at the
        # source code it seems like this is the way:
        # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136
        self._environ = os.environ.copy()
        utils.SetEnviron(self._environ, 'TSS_LOG', tsserver_log)

        # Each request sent to tsserver must have a sequence id.
        # Responses contain the id sent in the corresponding request.
        self._sequenceid = itertools.count()

        # Used to prevent threads from concurrently accessing the sequence counter
        self._sequenceid_lock = Lock()

        # TSServer ignores the fact that newlines are two characters on Windows
        # (\r\n) instead of one on other platforms (\n), so we use the
        # universal_newlines option to convert those newlines to \n. See the issue
        # https://github.com/Microsoft/TypeScript/issues/3403
        # TODO: remove this option when the issue is fixed.
        # We also need to redirect the error stream to the output one on Windows.
        self._tsserver_handle = utils.SafePopen(binarypath,
                                                stdout=subprocess.PIPE,
                                                stdin=subprocess.PIPE,
                                                stderr=subprocess.STDOUT,
                                                env=self._environ,
                                                universal_newlines=True)

        # Used to map sequence id's to their corresponding DeferredResponse
        # objects. The reader loop uses this to hand out responses.
        self._pending = {}

        # Used to prevent threads from concurrently reading and writing to
        # the pending response dictionary
        self._pendinglock = Lock()

        # Start a thread to read response from TSServer.
        self._thread = Thread(target=self._ReaderLoop, args=())
        self._thread.daemon = True
        self._thread.start()

        _logger.info('Enabling typescript completion')
Пример #18
0
  def _StartServer( self, request_data ):
    with self._server_state_mutex:
      if self._server_started:
        return

      self._server_started = True

      LOGGER.info( 'Starting Tern server...' )

      self._SetServerProjectFileAndWorkingDirectory( request_data )

      self._server_port = utils.GetUnusedLocalhostPort()

      command = [ PATH_TO_NODE,
                  PATH_TO_TERN_BINARY,
                  '--port',
                  str( self._server_port ),
                  '--host',
                  SERVER_HOST,
                  '--persistent',
                  '--no-port-file' ]

      if LOGGER.isEnabledFor( logging.DEBUG ):
        command.append( '--verbose' )

      LOGGER.debug( 'Starting tern with the following command: %s', command )

      self._server_stdout = utils.CreateLogfile(
          LOGFILE_FORMAT.format( port = self._server_port, std = 'stdout' ) )

      self._server_stderr = utils.CreateLogfile(
          LOGFILE_FORMAT.format( port = self._server_port, std = 'stderr' ) )

      # We need to open a pipe to stdin or the Tern server is killed.
      # See https://github.com/ternjs/tern/issues/740#issuecomment-203979749
      # For unknown reasons, this is only needed on Windows and for Python
      # 3.4+ on other platforms.
      with utils.OpenForStdHandle( self._server_stdout ) as stdout:
        with utils.OpenForStdHandle( self._server_stderr ) as stderr:
          self._server_handle = utils.SafePopen(
            command,
            stdin = PIPE,
            stdout = stdout,
            stderr = stderr,
            cwd = self._server_working_dir )

      if self._ServerIsRunning():
        LOGGER.info( 'Tern Server started with pid %d listening on port %d',
                     self._server_handle.pid, self._server_port )
        LOGGER.info( 'Tern Server log files are %s and %s',
                     self._server_stdout, self._server_stderr )

        self._do_tern_project_check = True
      else:
        LOGGER.warning( 'Tern server did not start successfully' )
Пример #19
0
def SafePopen_WindowsPath_test( *args ):
  tempfile = PathToTestFile( 'safe-popen-file' )
  open( tempfile, 'a' ).close()

  try:
    utils.SafePopen( [ 'foo', tempfile ], stdin_windows = subprocess.PIPE )
    eq_( subprocess.Popen.call_args,
         call( [ 'foo', tempfile ],
               stdin = subprocess.PIPE,
               creationflags = utils.CREATE_NO_WINDOW ) )
  finally:
    os.remove( tempfile )
Пример #20
0
def IsPythonVersionCorrect(path):
    """Check if given path is the Python interpreter version 2.6 or 2.7."""
    if not EndsWithPython(path):
        return False

    command = [
        path, '-c', "import sys;"
        "major, minor = sys.version_info[ :2 ];"
        "sys.exit( major != 2 or minor < 6)"
    ]

    return utils.SafePopen(command).wait() == 0
Пример #21
0
    def _StartServer(self, request_data):
        """ Start the OmniSharp server """
        self._logger.info('startup')

        # NOTE: detection could throw an exception if an extra_conf_store needs to
        # be confirmed
        path_to_solutionfile = solutiondetection.FindSolutionPath(
            request_data['filepath'])

        if not path_to_solutionfile:
            raise RuntimeError('Autodetection of solution file failed.\n')
        self._logger.info(
            u'Loading solution file {0}'.format(path_to_solutionfile))

        self._ChooseOmnisharpPort()

        # we need to pass the command to Popen as a string since we're passing
        # shell=True (as recommended by Python's doc)
        command = ' '.join([
            PATH_TO_OMNISHARP_BINARY, '-p',
            str(self._omnisharp_port), '-s',
            u'"{0}"'.format(path_to_solutionfile)
        ])

        if not utils.OnWindows() and not utils.OnCygwin():
            command = u'mono ' + command

        if utils.OnCygwin():
            command = command + ' --client-path-mode Cygwin'

        filename_format = os.path.join(utils.PathToTempDir(),
                                       u'omnisharp_{port}_{sln}_{std}.log')

        solutionfile = os.path.basename(path_to_solutionfile)
        self._filename_stdout = filename_format.format(
            port=self._omnisharp_port, sln=solutionfile, std='stdout')
        self._filename_stderr = filename_format.format(
            port=self._omnisharp_port, sln=solutionfile, std='stderr')

        with open(self._filename_stderr, 'w') as fstderr:
            with open(self._filename_stdout, 'w') as fstdout:
                # shell=True is needed for Windows so OmniSharp does not spawn
                # in a new visible window
                self._omnisharp_phandle = utils.SafePopen(command,
                                                          stdout=fstdout,
                                                          stderr=fstderr,
                                                          shell=True)

        self._solution_path = path_to_solutionfile

        self._logger.info('Starting OmniSharp server')
Пример #22
0
    def test_SafePopen_WindowsPath(self, *args):
        tempfile = PathToTestFile('safe-popen-file')
        open(tempfile, 'a').close()

        try:
            utils.SafePopen(['foo', tempfile], stdin_windows=subprocess.PIPE)
            assert_that(
                subprocess.Popen.call_args,
                equal_to(
                    call(['foo', tempfile],
                         stdin=subprocess.PIPE,
                         creationflags=utils.CREATE_NO_WINDOW)))
        finally:
            os.remove(tempfile)
Пример #23
0
    def _StartServer(self, request_data, project_directory=None):
        with self._server_state_mutex:
            if self._server_started:
                return

            self._server_started = True

            _logger.info('Starting dart Language Server...')

            if project_directory:
                self._project_dir = project_directory
            else:
                self._project_dir = _FindProjectDir(
                    os.path.dirname(request_data['filepath']))

            self._workspace_path = self._project_dir

            command = [
                PATH_TO_DART,
                '--force_trace_level=verbose',
            ]

            _logger.debug('Starting dart-server with the following command: '
                          '{0}'.format(' '.join(command)))

            self._server_stderr = utils.CreateLogfile('dart_stderr_')
            with utils.OpenForStdHandle(self._server_stderr) as stderr:
                self._server_handle = utils.SafePopen(command,
                                                      stdin=PIPE,
                                                      stdout=PIPE,
                                                      stderr=stderr)

            self._connection = (
                language_server_completer.StandardIOLanguageServerConnection(
                    self._server_handle.stdin, self._server_handle.stdout,
                    self.GetDefaultNotificationHandler()))

            self._connection.Start()

            try:
                self._connection.AwaitServerConnection()
            except language_server_completer.LanguageServerConnectionTimeout:
                _logger.error('dart failed to start, or did not connect '
                              'successfully')
                self._StopServer()
                return

        _logger.info('dart Language Server started')

        self.SendInitialize(request_data)
Пример #24
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self._ServerIsRunning():
                return

            LOGGER.info('Starting OmniSharp server')
            LOGGER.info('Loading solution file %s', self._solution_path)

            self._ChooseOmnisharpPort()

            # Roslyn fails unless you open it in shell in Window on Python 2
            # Shell isn't preferred, but I don't see any other way to resolve
            shell_required = PY2 and utils.OnWindows()

            command = [
                PATH_TO_ROSLYN_OMNISHARP_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                str(self._solution_path)
            ]

            if (not utils.OnWindows()
                    and PATH_TO_ROSLYN_OMNISHARP_BINARY.endswith('.exe')):
                command.insert(0, 'mono')

            LOGGER.info('Starting OmniSharp server with: %s', command)

            solutionfile = os.path.basename(self._solution_path)
            self._filename_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stdout'))
            self._filename_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stderr'))

            with utils.OpenForStdHandle(self._filename_stderr) as fstderr:
                with utils.OpenForStdHandle(self._filename_stdout) as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(
                        command,
                        stdout=fstdout,
                        stderr=fstderr,
                        shell=shell_required)

            LOGGER.info('Started OmniSharp server')
Пример #25
0
    def _SetupServer(self):
        self._available_completers = {}
        self._user_notified_about_crash = False
        self._filetypes_with_keywords_loaded = set()
        self._server_is_ready_with_cache = False

        server_port = utils.GetUnusedLocalhostPort()
        # The temp options file is deleted by ycmd during startup
        with NamedTemporaryFile(delete=False, mode='w+') as options_file:
            hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
            options_dict = dict(self._user_options)
            options_dict['hmac_secret'] = utils.ToUnicode(
                base64.b64encode(hmac_secret))
            options_dict['server_keep_logfiles'] = self._user_options[
                'keep_logfiles']
            json.dump(options_dict, options_file)
            options_file.flush()

            args = [
                paths.PathToPythonInterpreter(),
                paths.PathToServerScript(), '--port={0}'.format(server_port),
                '--options_file={0}'.format(options_file.name),
                '--log={0}'.format(self._user_options['log_level']),
                '--idle_suicide_seconds={0}'.format(
                    SERVER_IDLE_SUICIDE_SECONDS)
            ]

            self._server_stdout = utils.CreateLogfile(
                SERVER_LOGFILE_FORMAT.format(port=server_port, std='stdout'))
            self._server_stderr = utils.CreateLogfile(
                SERVER_LOGFILE_FORMAT.format(port=server_port, std='stderr'))
            args.append('--stdout={0}'.format(self._server_stdout))
            args.append('--stderr={0}'.format(self._server_stderr))

            if self._user_options['keep_logfiles']:
                args.append('--keep_logfiles')

            self._server_popen = utils.SafePopen(args,
                                                 stdin_windows=PIPE,
                                                 stdout=PIPE,
                                                 stderr=PIPE)
            BaseRequest.server_location = 'http://127.0.0.1:' + str(
                server_port)
            BaseRequest.hmac_secret = hmac_secret

        self._NotifyUserIfServerCrashed()
Пример #26
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self.ServerIsRunning():
                return

            self._logger.info('Starting OmniSharp server')

            path_to_solutionfile = self._solution_path
            self._logger.info(
                u'Loading solution file {0}'.format(path_to_solutionfile))

            self._ChooseOmnisharpPort()

            command = [
                PATH_TO_OMNISHARP_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                u'{0}'.format(path_to_solutionfile)
            ]

            if not utils.OnWindows() and not utils.OnCygwin():
                command.insert(0, 'mono')

            if utils.OnCygwin():
                command.extend(['--client-path-mode', 'Cygwin'])

            filename_format = os.path.join(
                utils.PathToCreatedTempDir(),
                u'omnisharp_{port}_{sln}_{std}.log')

            solutionfile = os.path.basename(path_to_solutionfile)
            self._filename_stdout = filename_format.format(
                port=self._omnisharp_port, sln=solutionfile, std='stdout')
            self._filename_stderr = filename_format.format(
                port=self._omnisharp_port, sln=solutionfile, std='stderr')

            with open(self._filename_stderr, 'w') as fstderr:
                with open(self._filename_stdout, 'w') as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(command,
                                                              stdout=fstdout,
                                                              stderr=fstderr)
                    self._external_omnisharp = False

            self._solution_path = path_to_solutionfile
Пример #27
0
def SetUpYCM():
    from ycm import base, paths
    from ycmd import user_options_store, utils
    from ycm.youcompleteme import YouCompleteMe

    base.LoadJsonDefaultsIntoVim()

    user_options_store.SetAll(base.BuildServerConf())

    popen_args = [
        paths.PathToPythonInterpreter(),
        paths.PathToCheckCoreVersion()
    ]

    if utils.SafePopen(popen_args).wait() == 2:
        raise RuntimeError('YCM support libs too old, PLEASE RECOMPILE.')

    return YouCompleteMe(user_options_store.GetAll())
Пример #28
0
    def _StartServer(self):
        """ Start the OmniSharp server if not already running. Use a lock to avoid
    starting the server multiple times for the same solution. """
        with self._server_state_lock:
            if self._ServerIsRunning():
                return

            self._logger.info('Starting OmniSharp server')

            path_to_solutionfile = self._solution_path
            self._logger.info(
                u'Loading solution file {0}'.format(path_to_solutionfile))

            self._ChooseOmnisharpPort()

            command = [
                PATH_TO_OMNISHARP_BINARY, '-p',
                str(self._omnisharp_port), '-s',
                u'{0}'.format(path_to_solutionfile)
            ]

            if not utils.OnWindows() and not utils.OnCygwin():
                command.insert(0, 'mono')

            if utils.OnCygwin():
                command.extend(['--client-path-mode', 'Cygwin'])

            solutionfile = os.path.basename(path_to_solutionfile)
            self._filename_stdout = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stdout'))
            self._filename_stderr = utils.CreateLogfile(
                LOGFILE_FORMAT.format(port=self._omnisharp_port,
                                      sln=solutionfile,
                                      std='stderr'))

            with utils.OpenForStdHandle(self._filename_stderr) as fstderr:
                with utils.OpenForStdHandle(self._filename_stdout) as fstdout:
                    self._omnisharp_phandle = utils.SafePopen(command,
                                                              stdout=fstdout,
                                                              stderr=fstderr)

            self._solution_path = path_to_solutionfile
Пример #29
0
    def _SetupServer(self):
        self._available_completers = {}
        server_port = utils.GetUnusedLocalhostPort()
        # The temp options file is deleted by ycmd during startup
        with tempfile.NamedTemporaryFile(delete=False) as options_file:
            hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
            options_dict = dict(self._user_options)
            options_dict['hmac_secret'] = base64.b64encode(hmac_secret)
            json.dump(options_dict, options_file)
            options_file.flush()

            args = [
                utils.PathToPythonInterpreter(),
                _PathToServerScript(), '--port={0}'.format(server_port),
                '--options_file={0}'.format(options_file.name),
                '--log={0}'.format(self._user_options['server_log_level']),
                '--idle_suicide_seconds={0}'.format(
                    SERVER_IDLE_SUICIDE_SECONDS)
            ]

            if not self._user_options['server_use_vim_stdout']:
                filename_format = os.path.join(utils.PathToTempDir(),
                                               'server_{port}_{std}.log')

                self._server_stdout = filename_format.format(port=server_port,
                                                             std='stdout')
                self._server_stderr = filename_format.format(port=server_port,
                                                             std='stderr')
                args.append('--stdout={0}'.format(self._server_stdout))
                args.append('--stderr={0}'.format(self._server_stderr))

                if self._user_options['server_keep_logfiles']:
                    args.append('--keep_logfiles')

            self._server_popen = utils.SafePopen(args,
                                                 stdin_windows=PIPE,
                                                 stdout=PIPE,
                                                 stderr=PIPE)
            BaseRequest.server_location = 'http://127.0.0.1:' + str(
                server_port)
            BaseRequest.hmac_secret = hmac_secret

        self._NotifyUserIfServerCrashed()
Пример #30
0
def IsPythonVersionCorrect(path):
    """Check if given path is the Python interpreter version 2.6+ or 3.3+."""
    from ycmd import utils

    if not EndsWithPython(path):
        return False

    command = [
        path,
        '-c',
        "import sys;"
        "major, minor = sys.version_info[ :2 ];"
        "good_python = ( major == 2 and minor >= 6 ) "
        "or ( major == 3 and minor >= 3 ) or major > 3;"
        # If this looks weird, remember that:
        #   int( True ) == 1
        #   int( False ) == 0
        "sys.exit( not good_python )"
    ]

    return utils.SafePopen(command).wait() == 0