Beispiel #1
0
        public DnxProjectSystem(OmnisharpWorkspace workspace,
                                IOmnisharpEnvironment env,
                                IOptions <OmniSharpOptions> optionsAccessor,
                                ILoggerFactory loggerFactory,
                                IMetadataFileReferenceCache metadataFileReferenceCache,
                                IApplicationLifetime lifetime,
                                IFileSystemWatcher watcher,
                                IEventEmitter emitter,
                                DnxContext context)
        {
            _workspace = workspace;
            _env       = env;
            _logger    = loggerFactory.CreateLogger <DnxProjectSystem>();
            _metadataFileReferenceCache = metadataFileReferenceCache;
            _options  = optionsAccessor.Options;
            _dnxPaths = new DnxPaths(env, _options, loggerFactory);
            _designTimeHostManager = new DesignTimeHostManager(loggerFactory, _dnxPaths);
            _packagesRestoreTool   = new PackagesRestoreTool(_options, loggerFactory, emitter, context, _dnxPaths);
            _context             = context;
            _watcher             = watcher;
            _emitter             = emitter;
            _directoryEnumerator = new DirectoryEnumerator(loggerFactory);

            lifetime.ApplicationStopping.Register(OnShutdown);
        }
        public CSharpDiagnosticWorkerWithAnalyzers(
            OmniSharpWorkspace workspace,
            [ImportMany] IEnumerable <ICodeActionProvider> providers,
            ILoggerFactory loggerFactory,
            DiagnosticEventForwarder forwarder,
            OmniSharpOptions options)
        {
            _logger    = loggerFactory.CreateLogger <CSharpDiagnosticWorkerWithAnalyzers>();
            _providers = providers.ToImmutableArray();
            _workQueue = new AnalyzerWorkQueue(loggerFactory, timeoutForPendingWorkMs: options.RoslynExtensionsOptions.DocumentAnalysisTimeoutMs * 3);

            _forwarder = forwarder;
            _options   = options;
            _workspace = workspace;

            _workspaceAnalyzerOptionsConstructor = Assembly
                                                   .Load("Microsoft.CodeAnalysis.Features")
                                                   .GetType("Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions")
                                                   .GetConstructor(new Type[] { typeof(AnalyzerOptions), typeof(Solution) })
                                                   ?? throw new InvalidOperationException("Could not resolve 'Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions' for IDE analyzers.");

            _workspace.WorkspaceChanged += OnWorkspaceChanged;
            _workspace.OnInitialized    += OnWorkspaceInitialized;

            Task.Factory.StartNew(() => Worker(AnalyzerWorkType.Foreground), TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(() => Worker(AnalyzerWorkType.Background), TaskCreationOptions.LongRunning);

            OnWorkspaceInitialized(_workspace.Initialized);
        }
        private void UpdateImplementation(OmniSharpOptions options)
        {
            var firstRun = _implementation is null;

            if (options.RoslynExtensionsOptions.EnableAnalyzersSupport && (firstRun || _implementation is CSharpDiagnosticWorker))
            {
                var old = Interlocked.Exchange(ref _implementation, new CSharpDiagnosticWorkerWithAnalyzers(_workspace, _providers, _loggerFactory, _forwarder, options));
                if (old is IDisposable disposable)
                {
                    disposable.Dispose();
                }
            }
            else if (!options.RoslynExtensionsOptions.EnableAnalyzersSupport && (firstRun || _implementation is CSharpDiagnosticWorkerWithAnalyzers))
            {
                var old = Interlocked.Exchange(ref _implementation, new CSharpDiagnosticWorker(_workspace, _forwarder, _loggerFactory));
                if (old is IDisposable disposable)
                {
                    disposable.Dispose();
                }

                if (!firstRun)
                {
                    _implementation.QueueDocumentsForDiagnostics();
                }
            }
        }
Beispiel #4
0
 public WorkspaceHelper(CompositionHost compositionHost, IConfiguration configuration, OmniSharpOptions options, ILoggerFactory loggerFactory)
 {
     _compositionHost = compositionHost;
     _configuration   = configuration;
     _options         = options;
     _logger          = loggerFactory.CreateLogger <WorkspaceHelper>();
 }
Beispiel #5
0
        public ExternalFeaturesHostServicesProvider(IAssemblyLoader loader, OmniSharpOptions options, IOmniSharpEnvironment environment, ILoggerFactory loggerFactory)
        {
            var builder = ImmutableArray.CreateBuilder <Assembly>();

            var roslynExtensionsLocations = options.RoslynExtensionsOptions.GetNormalizedLocationPaths(environment);

            if (roslynExtensionsLocations?.Any() == true)
            {
                var logger = loggerFactory.CreateLogger <ExternalFeaturesHostServicesProvider>();
                foreach (var roslynExtensionsLocation in roslynExtensionsLocations)
                {
                    var loadedAssemblies = loader.LoadAllFrom(roslynExtensionsLocation);
                    if (loadedAssemblies.Any())
                    {
                        builder.AddRange(loadedAssemblies);
                    }
                    else
                    {
                        logger.LogWarning($"The path '{roslynExtensionsLocation}' is configured in the RoslynExtensionsOptions as the external features source but no assemblies were found at this path.");
                    }
                }
            }

            Assemblies = builder.ToImmutable();
        }
        public CSharpDiagnosticWorker(OmniSharpWorkspace workspace, DiagnosticEventForwarder forwarder, ILoggerFactory loggerFactory, OmniSharpOptions options)
        {
            _workspace = workspace;
            _forwarder = forwarder;
            _logger    = loggerFactory.CreateLogger <CSharpDiagnosticWorker>();
            _options   = options;

            var openDocumentsSubject = new Subject <string>();

            _openDocuments = openDocumentsSubject;

            _workspace.WorkspaceChanged += OnWorkspaceChanged;
            _workspace.DocumentOpened   += OnDocumentOpened;
            _workspace.DocumentClosed   += OnDocumentOpened;

            _disposable = openDocumentsSubject
                          .Buffer(() => Observable.Amb(
                                      openDocumentsSubject.Skip(99).Select(z => Unit.Default),
                                      Observable.Timer(TimeSpan.FromMilliseconds(100)).Select(z => Unit.Default)
                                      ))
                          .SubscribeOn(TaskPoolScheduler.Default)
                          .Select(ProcessQueue)
                          .Merge()
                          .Subscribe();
        }
 public GotoTypeDefinitionHandler(
     OmniSharpWorkspace workspace,
     ExternalSourceServiceFactory externalSourceServiceFactory,
     OmniSharpOptions omniSharpOptions)
     : base(workspace)
 {
     _externalSourceService = externalSourceServiceFactory?.Create(omniSharpOptions) ?? throw new ArgumentNullException(nameof(externalSourceServiceFactory));
 }
        public static async Task <string> GetFormattedText(Document document, OmniSharpOptions omnisharpOptions, ILoggerFactory loggerFactory)
        {
            var newDocument = await FormatDocument(document, omnisharpOptions, loggerFactory);

            var text = await newDocument.GetTextAsync();

            return(text.ToString());
        }
Beispiel #9
0
 public CodeCheckService(
     OmniSharpWorkspace workspace,
     ILoggerFactory loggerFactory,
     OmniSharpOptions options,
     ICsDiagnosticWorker diagWorker)
 {
     _diagWorker = diagWorker;
     _logger     = loggerFactory.CreateLogger <CodeCheckService>();
 }
 public FixUsingService(
     OmniSharpWorkspace workspace,
     OmniSharpOptions options,
     [ImportMany] IEnumerable <ICodeActionProvider> codeActionProviders)
 {
     _workspace = workspace;
     _options   = options;
     _providers = codeActionProviders;
 }
Beispiel #11
0
        public static CompositionHost ConfigureMef(IServiceProvider serviceProvider,
                                                   OmniSharpOptions options,
                                                   IEnumerable <Assembly> assemblies,
                                                   Func <ContainerConfiguration, ContainerConfiguration> configure = null)
        {
            var config = new ContainerConfiguration();

            assemblies = assemblies
                         .Concat(new[] { typeof(OmnisharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                         .Distinct();

            foreach (var assembly in assemblies)
            {
                config = config.WithAssembly(assembly);
            }

            var memoryCache         = serviceProvider.GetService <IMemoryCache>();
            var loggerFactory       = serviceProvider.GetService <ILoggerFactory>();
            var env                 = serviceProvider.GetService <IOmnisharpEnvironment>();
            var writer              = serviceProvider.GetService <ISharedTextWriter>();
            var applicationLifetime = serviceProvider.GetService <IApplicationLifetime>();
            var loader              = serviceProvider.GetService <IOmnisharpAssemblyLoader>();

            config = config
                     .WithProvider(MefValueProvider.From(serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(new ManualFileSystemWatcher()))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(env))
                     .WithProvider(MefValueProvider.From(writer))
                     .WithProvider(MefValueProvider.From(applicationLifetime))
                     .WithProvider(MefValueProvider.From(options))
                     .WithProvider(MefValueProvider.From(options.FormattingOptions))
                     .WithProvider(MefValueProvider.From(loader))
                     .WithProvider(MefValueProvider.From(new MetadataHelper(loader))); // other way to do singleton and autowire?

            if (env.TransportType == TransportType.Stdio)
            {
                config = config
                         .WithProvider(MefValueProvider.From <IEventEmitter>(new StdioEventEmitter(writer)));
            }
            else
            {
                config = config
                         .WithProvider(MefValueProvider.From <IEventEmitter>(new NullEventEmitter()));
            }

            if (configure != null)
            {
                config = configure(config);
            }

            var container = config.CreateContainer();

            return(container);
        }
        public FixUsingsWorker(IEnumerable <ICodeActionProvider> providers, OmniSharpOptions options)
        {
            _providers = providers;

            var codeFixProviders = providers.SelectMany(p => p.CodeFixProviders);

            _addImportProvider = FindCodeFixProviderByTypeFullName(codeFixProviders, CodeActionHelper.AddImportProviderName);
            _removeUnnecessaryUsingsProvider = FindCodeFixProviderByTypeFullName(codeFixProviders, CodeActionHelper.RemoveUnnecessaryUsingsProviderName);
            _options = options;
        }
Beispiel #13
0
        private FileSystemHelper CreateFileSystemHelper(params string[] excludePatterns)
        {
            var environment = new OmniSharpEnvironment(TestAssets.Instance.TestAssetsFolder, 1000, LogLevel.Information, null);
            var options     = new OmniSharpOptions();

            options.FileOptions.ExcludeSearchPatterns = excludePatterns;
            var helper = new FileSystemHelper(options, environment);

            return(helper);
        }
        public CancellationToken CreateCancellationToken(OmniSharpOptions omniSharpOptions, int timeout)
        {
            var enableDecompilationSupport = omniSharpOptions.RoslynExtensionsOptions.EnableDecompilationSupport;
            // since decompilation is slower, use a larger cancellation time (default is 2s per request)
            var cancellationTimeout = enableDecompilationSupport
                ? timeout <= 10000 ? 10000 : timeout // minimum 10s for decompilation
                : timeout;                           // request defined for metadata

            return(new CancellationTokenSource(cancellationTimeout).Token);
        }
Beispiel #15
0
 public GetFixAllCodeActionService(
     OmniSharpWorkspace workspace,
     [ImportMany] IEnumerable <ICodeActionProvider> providers,
     ILoggerFactory loggerFactory,
     ICsDiagnosticWorker diagnostics,
     CachingCodeFixProviderForProjects codeFixesForProject,
     OmniSharpOptions options
     ) : base(workspace, providers, loggerFactory.CreateLogger <GetFixAllCodeActionService>(), diagnostics, codeFixesForProject, options)
 {
 }
Beispiel #16
0
 public PackagesRestoreTool(OmniSharpOptions options, ILoggerFactory logger, IEventEmitter emitter, DnxContext context, DnxPaths paths)
 {
     _options      = options;
     _logger       = logger.CreateLogger <PackagesRestoreTool>();
     _emitter      = emitter;
     _context      = context;
     _paths        = paths;
     _lock         = new object();
     _projectLocks = new Dictionary <string, object>();
     _semaphore    = new SemaphoreSlim(Environment.ProcessorCount / 2);
 }
Beispiel #17
0
 public PackagesRestoreTool(OmniSharpOptions options, ILoggerFactory logger, IEventEmitter emitter, DnxContext context, DotNetCorePaths paths)
 {
     _options      = options;
     _logger       = logger.CreateLogger <PackagesRestoreTool>();
     _emitter      = emitter;
     _context      = context;
     _paths        = paths;
     _lock         = new object();
     _projectLocks = new Dictionary <string, object>();
     _semaphore    = new SemaphoreSlim(GetNumConcurrentRestores());
 }
Beispiel #18
0
 public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omniSharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
 {
     return(currentOptionSet
            .WithChangedOption(
                OmniSharpBlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions,
                LanguageNames.CSharp,
                true)
            .WithChangedOption(
                OmniSharpBlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions,
                LanguageNames.CSharp,
                true));
 }
Beispiel #19
0
        public static async Task <string> GetFormattedText(Document document, OmniSharpOptions omnisharpOptions, ILoggerFactory loggerFactory)
        {
            var optionSet = omnisharpOptions.FormattingOptions.EnableEditorConfigSupport
                ? await document.Project.Solution.Workspace.Options.WithEditorConfigOptions(document.FilePath, loggerFactory)
                : document.Project.Solution.Workspace.Options;

            var newDocument = await Formatter.FormatAsync(document, optionSet);

            var text = await newDocument.GetTextAsync();

            return(text.ToString());
        }
Beispiel #20
0
 public GotoDefinitionService(
     ILoggerFactory loggerFactory,
     ICodeSearchProvider codeSearchServiceProvider,
     OmniSharpWorkspace workspace,
     ExternalSourceServiceFactory externalSourceServiceFactory,
     OmniSharpOptions omnisharpOptions)
 {
     _logger = loggerFactory.CreateLogger <GotoDefinitionService>();
     _codeSearchServiceProvider = codeSearchServiceProvider;
     _workspace = workspace;
     _externalSourceServiceFactory = externalSourceServiceFactory;
     _omnisharpOptions             = omnisharpOptions;
 }
 public AspNet5Initializer(OmnisharpWorkspace workspace,
                           IOmnisharpEnvironment env,
                           IOptions <OmniSharpOptions> optionsAccessor,
                           ILoggerFactory loggerFactory,
                           IMetadataFileReferenceCache metadataFileReferenceCache)
 {
     _workspace = workspace;
     _env       = env;
     _options   = optionsAccessor.Options;
     _logger    = loggerFactory.Create <AspNet5Initializer>();
     _metadataFileReferenceCache = metadataFileReferenceCache;
     _designTimeHostManager      = new DesignTimeHostManager(loggerFactory);
 }
Beispiel #22
0
        public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omnisharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
        {
            if (!omnisharpOptions.FormattingOptions.EnableEditorConfigSupport)
            {
                return(currentOptionSet);
            }

            // this is a dummy file that doesn't exist, but we simply want to tell .editorconfig to load *.cs specific settings
            var filePath         = Path.Combine(omnisharpEnvironment.TargetDirectory, "omnisharp.cs");
            var changedOptionSet = currentOptionSet.WithEditorConfigOptions(filePath, _loggerFactory).GetAwaiter().GetResult();

            return(changedOptionSet);
        }
        public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omniSharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
        {
            if (_blockStructureOptions.Value.GetField("ShowBlockStructureGuidesForCommentsAndPreprocessorRegions", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is IOption showBlockStructureGuidesForCommentsAndPreprocessorRegionsOptionValue)
            {
                currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(showBlockStructureGuidesForCommentsAndPreprocessorRegionsOptionValue, LanguageNames.CSharp), true);
            }

            if (_blockStructureOptions.Value.GetField("ShowOutliningForCommentsAndPreprocessorRegions", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is IOption showOutliningForCommentsAndPreprocessorRegionsOptionValue)
            {
                currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(showOutliningForCommentsAndPreprocessorRegionsOptionValue, LanguageNames.CSharp), true);
            }

            return(currentOptionSet);
        }
 public RunCodeActionService(
     IAssemblyLoader loader,
     OmniSharpWorkspace workspace,
     CodeActionHelper helper,
     [ImportMany] IEnumerable <ICodeActionProvider> providers,
     ILoggerFactory loggerFactory,
     ICsDiagnosticWorker diagnostics,
     CachingCodeFixProviderForProjects codeFixesForProjects,
     OmniSharpOptions options)
     : base(workspace, providers, loggerFactory.CreateLogger <RunCodeActionService>(), diagnostics, codeFixesForProjects, options)
 {
     _loader            = loader;
     _workspaceAssembly = _loader.LazyLoad(Configuration.RoslynWorkspaces);
 }
Beispiel #25
0
        public AspNet5Paths(IOmnisharpEnvironment env,
                            OmniSharpOptions options,
                            ILoggerFactory loggerFactory)
        {
            _env     = env;
            _options = options;
            _logger  = loggerFactory.Create <AspNet5Paths>();

            RuntimePath = GetRuntimePath();
            Dnx         = FirstPath(RuntimePath, "dnx", "dnx.exe");
            Dnu         = FirstPath(RuntimePath, "dnu", "dnu.cmd");
            Klr         = FirstPath(RuntimePath, "klr", "klr.exe");
            Kpm         = FirstPath(RuntimePath, "kpm", "kpm.cmd");
        }
        public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omniSharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
        {
            if (omniSharpOptions.ImplementTypeOptions.InsertionBehavior != null)
            {
                currentOptionSet = OmniSharpImplementTypeOptions.SetInsertionBehavior(currentOptionSet, LanguageNames.CSharp, (OmniSharpImplementTypeInsertionBehavior)omniSharpOptions.ImplementTypeOptions.InsertionBehavior);
            }

            if (omniSharpOptions.ImplementTypeOptions.PropertyGenerationBehavior != null)
            {
                currentOptionSet = OmniSharpImplementTypeOptions.SetPropertyGenerationBehavior(currentOptionSet, LanguageNames.CSharp, (OmniSharpImplementTypePropertyGenerationBehavior)omniSharpOptions.ImplementTypeOptions.PropertyGenerationBehavior);
            }

            return(currentOptionSet);
        }
        public static OmniSharpTestHost Create(string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, bool useLegacyDotNetCli = false)
        {
            var dotNetPath = Path.Combine(
                TestAssets.Instance.RootFolder,
                useLegacyDotNetCli ? ".dotnet-legacy" : ".dotnet",
                "dotnet");

            if (!File.Exists(dotNetPath))
            {
                dotNetPath = Path.ChangeExtension(dotNetPath, ".exe");
            }

            if (!File.Exists(dotNetPath))
            {
                throw new InvalidOperationException($"Local .NET CLI path does not exist. Did you run build.(ps1|sh) from the command line?");
            }

            var builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(configurationData);
            var configuration = builder.Build();

            var environment      = new OmniSharpEnvironment(path);
            var loggerFactory    = new LoggerFactory().AddXunit(testOutput);
            var sharedTextWriter = new TestSharedTextWriter(testOutput);
            var serviceProvider  = new TestServiceProvider(environment, loggerFactory, sharedTextWriter);

            var omnisharpOptions = new OmniSharpOptions();

            ConfigurationBinder.Bind(configuration, omnisharpOptions);

            var compositionHost = Startup.CreateCompositionHost(
                serviceProvider,
                options: omnisharpOptions,
                assemblies: s_lazyAssemblies.Value);

            var workspace = compositionHost.GetExport <OmniSharpWorkspace>();
            var logger    = loggerFactory.CreateLogger <OmniSharpTestHost>();

            var dotNetCli = compositionHost.GetExport <DotNetCliService>();

            dotNetCli.SetDotNetPath(dotNetPath);

            var workspaceHelper = new WorkspaceHelper(compositionHost, configuration, omnisharpOptions, loggerFactory);

            workspaceHelper.Initialize(workspace);

            return(new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost));
        }
Beispiel #28
0
        private static async Task <Document> FormatDocument(Document document, OmniSharpOptions omnisharpOptions, ILoggerFactory loggerFactory, TextSpan?textSpan = null)
        {
            var optionSet = omnisharpOptions.FormattingOptions.EnableEditorConfigSupport
                ? await document.Project.Solution.Workspace.Options.WithEditorConfigOptions(document.FilePath, loggerFactory)
                : document.Project.Solution.Workspace.Options;

            var newDocument = textSpan != null ? await Formatter.FormatAsync(document, textSpan.Value, optionSet) : await Formatter.FormatAsync(document, optionSet);

            if (omnisharpOptions.FormattingOptions.OrganizeImports)
            {
                newDocument = await Formatter.OrganizeImportsAsync(newDocument);
            }

            return(newDocument);
        }
        private static async Task <Document> FormatDocument(Document document, OmniSharpOptions omnisharpOptions, ILoggerFactory loggerFactory, TextSpan?textSpan = null)
        {
            // If we are not using .editorconfig for formatting options then we can avoid any overhead of calculating document options.
            var optionSet = omnisharpOptions.FormattingOptions.EnableEditorConfigSupport
                ? await document.GetOptionsAsync()
                : document.Project.Solution.Options;

            var newDocument = textSpan != null ? await Formatter.FormatAsync(document, textSpan.Value, optionSet) : await Formatter.FormatAsync(document, optionSet);

            if (omnisharpOptions.FormattingOptions.OrganizeImports)
            {
                newDocument = await Formatter.OrganizeImportsAsync(newDocument);
            }

            return(newDocument);
        }
 public CsharpDiagnosticWorkerComposer(
     OmniSharpWorkspace workspace,
     [ImportMany] IEnumerable <ICodeActionProvider> providers,
     ILoggerFactory loggerFactory,
     DiagnosticEventForwarder forwarder,
     OmniSharpOptions options)
 {
     if (options.RoslynExtensionsOptions.EnableAnalyzersSupport)
     {
         _implementation = new CSharpDiagnosticWorkerWithAnalyzers(workspace, providers, loggerFactory, forwarder, options);
     }
     else
     {
         _implementation = new CSharpDiagnosticWorker(workspace, forwarder, loggerFactory);
     }
 }