Example #1
0
        internal static bool InitPlugins()
        {
            string pluginsPath = Path.Combine(SharedInfo.HomeDirectory, SharedInfo.PluginsDirectory);

            if (!Directory.Exists(pluginsPath))
            {
                ASF.ArchiLogger.LogGenericTrace(Strings.NothingFound);

                return(true);
            }

            HashSet <Assembly> assemblies = new HashSet <Assembly>();

            try {
                foreach (string assemblyPath in Directory.EnumerateFiles(pluginsPath, "*.dll", SearchOption.AllDirectories))
                {
                    Assembly assembly;

                    try {
                        assembly = Assembly.LoadFrom(assemblyPath);
                    } catch (Exception e) {
                        ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorIsInvalid, assemblyPath));
                        ASF.ArchiLogger.LogGenericWarningException(e);

                        continue;
                    }

                    assemblies.Add(assembly);
                }
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);

                return(false);
            }

            if (assemblies.Count == 0)
            {
                ASF.ArchiLogger.LogGenericTrace(Strings.NothingFound);

                return(true);
            }

            ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.Initializing, nameof(Plugins)));

            ConventionBuilder conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IPlugin>().Export <IPlugin>();

            ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            HashSet <IPlugin> activePlugins;

            try {
                using (CompositionHost container = configuration.CreateContainer()) {
                    activePlugins = container.GetExports <IPlugin>().ToHashSet();
                }
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);

                return(false);
            }

            if (activePlugins.Count == 0)
            {
                return(true);
            }

            HashSet <IPlugin> invalidPlugins = new HashSet <IPlugin>();

            foreach (IPlugin plugin in activePlugins)
            {
                try {
                    string pluginName = plugin.Name;

                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoading, pluginName, plugin.Version));
                    plugin.OnLoaded();
                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoaded, pluginName));
                } catch (Exception e) {
                    ASF.ArchiLogger.LogGenericException(e);
                    invalidPlugins.Add(plugin);
                }
            }

            if (invalidPlugins.Count > 0)
            {
                activePlugins.ExceptWith(invalidPlugins);

                if (activePlugins.Count == 0)
                {
                    return(false);
                }
            }

            ActivePlugins = activePlugins.ToImmutableHashSet();
            ASF.ArchiLogger.LogGenericInfo(Strings.PluginsWarning);

            return(invalidPlugins.Count == 0);
        }
Example #2
0
        private IDictionary <string, Lazy <EndpointHandler> > Initialize()
        {
            var workspace         = _compositionHost.GetExport <OmniSharpWorkspace>();
            var projectSystems    = _compositionHost.GetExports <IProjectSystem>();
            var endpointMetadatas = _compositionHost.GetExports <Lazy <IRequest, OmniSharpEndpointMetadata> >()
                                    .Select(x => x.Metadata)
                                    .ToArray();

            var handlers = _compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >();

            var updateBufferEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(
                () => (EndpointHandler <UpdateBufferRequest, object>)_endpointHandlers[OmniSharpEndpoints.UpdateBuffer].Value);
            var languagePredicateHandler      = new LanguagePredicateHandler(projectSystems);
            var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects");
            var nugetPredicateHandler         = new StaticLanguagePredicateHandler("NuGet");
            var endpointHandlers = endpointMetadatas.ToDictionary(
                x => x.EndpointName,
                endpoint => new Lazy <EndpointHandler>(() =>
            {
                IPredicateHandler handler;

                // Projects are a special case, this allows us to select the correct "Projects" language for them
                if (endpoint.EndpointName == OmniSharpEndpoints.ProjectInformation || endpoint.EndpointName == OmniSharpEndpoints.WorkspaceInformation)
                {
                    handler = projectSystemPredicateHandler;
                }
                else if (endpoint.EndpointName == OmniSharpEndpoints.PackageSearch || endpoint.EndpointName == OmniSharpEndpoints.PackageSource || endpoint.EndpointName == OmniSharpEndpoints.PackageVersion)
                {
                    handler = nugetPredicateHandler;
                }
                else
                {
                    handler = languagePredicateHandler;
                }

                // This lets any endpoint, that contains a Request object, invoke update buffer.
                // The language will be same language as the caller, this means any language service
                // must implement update buffer.
                var updateEndpointHandler = updateBufferEndpointHandler;
                if (endpoint.EndpointName == OmniSharpEndpoints.UpdateBuffer)
                {
                    // We don't want to call update buffer on update buffer.
                    updateEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(() => null);
                }

                return(EndpointHandler.Factory(handler, _compositionHost, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty <Plugin>()));
            }),
                StringComparer.OrdinalIgnoreCase
                );


            // Handled as alternative middleware in http
            endpointHandlers.Add(
                OmniSharpEndpoints.CheckAliveStatus,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x => Task.FromResult <object>(true)))
                );
            endpointHandlers.Add(
                OmniSharpEndpoints.CheckReadyStatus,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x => Task.FromResult <object>(workspace.Initialized)))
                );
            endpointHandlers.Add(
                OmniSharpEndpoints.StopServer,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x =>
            {
                _cancellationTokenSource.Cancel();
                return(Task.FromResult <object>(null));
            }))
                );

            return(endpointHandlers);
        }
Example #3
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name                 = "ApiCompat",
                FullName             = "A command line tool to verify that two sets of APIs are compatible.",
                ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated
            };

            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument contracts = app.Argument("contracts", "Comma delimited list of assemblies or directories of assemblies for all the contract assemblies.");

            contracts.IsRequired();
            CommandOption implDirs = app.Option("-i|--impl-dirs", "Comma delimited list of directories to find the implementation assemblies for each contract assembly.", CommandOptionType.SingleValue);

            implDirs.IsRequired(allowEmptyStrings: true);
            CommandOption baseline                     = app.Option("-b|--baseline", "Baseline file to skip known diffs.", CommandOptionType.SingleValue);
            CommandOption mdil                         = app.Option("-m|--mdil", "Enforce MDIL servicing rules in addition to IL rules.", CommandOptionType.NoValue);
            CommandOption outFilePath                  = app.Option("-o|--out", "Output file path. Default is the console.", CommandOptionType.SingleValue);
            CommandOption leftOperand                  = app.Option("-l|--left-operand", "Name for left operand in comparison, default is 'contract'.", CommandOptionType.SingleValue);
            CommandOption rightOperand                 = app.Option("-r|--right-operand", "Name for right operand in comparison, default is 'implementation'.", CommandOptionType.SingleValue);
            CommandOption listRules                    = app.Option("--list-rules", "Outputs all the rules. If this options is supplied all other options are ignored.", CommandOptionType.NoValue);
            CommandOption remapFile                    = app.Option("--remap-file", "File with a list of type and/or namespace remappings to consider apply to names while diffing.", CommandOptionType.SingleValue);
            CommandOption skipGroupByAssembly          = app.Option("--skip-group-by-assembly", "Skip grouping the differences by assembly instead of flattening the namespaces.", CommandOptionType.NoValue);
            CommandOption skipUnifyToLibPath           = app.Option("--skip-unify-to-lib-path", "Skip unifying the assembly references to the loaded assemblies and the assemblies found in the given directories (contractDepends and implDirs).", CommandOptionType.NoValue);
            CommandOption resolveFx                    = app.Option("--resolve-fx", "If a contract or implementation dependency cannot be found in the given directories, fallback to try to resolve against the framework directory on the machine.", CommandOptionType.NoValue);
            CommandOption contractDepends              = app.Option("--contract-depends", "Comma delimited list of directories used to resolve the dependencies of the contract assemblies.", CommandOptionType.SingleValue);
            CommandOption contractCoreAssembly         = app.Option("--contract-core-assembly", "Simple name for the core assembly to use.", CommandOptionType.SingleValue);
            CommandOption ignoreDesignTimeFacades      = app.Option("--ignore-design-time-facades", "Ignore design time facades in the contract set while analyzing.", CommandOptionType.NoValue);
            CommandOption warnOnIncorrectVersion       = app.Option("--warn-on-incorrect-version", "Warn if the contract version number doesn't match the found implementation version number.", CommandOptionType.NoValue);
            CommandOption warnOnMissingAssemblies      = app.Option("--warn-on-missing-assemblies", "Warn if the contract assembly cannot be found in the implementation directories. Default is to error and not do analysis.", CommandOptionType.NoValue);
            CommandOption excludeNonBrowsable          = app.Option("--exclude-non-browsable", "When MDIL servicing rules are not being enforced, exclude validation on types that are marked with EditorBrowsable(EditorBrowsableState.Never).", CommandOptionType.NoValue);
            CommandOption excludeAttributes            = app.Option("--exclude-attributes", "Specify a api list in the DocId format of which attributes to exclude.", CommandOptionType.SingleValue);
            CommandOption enforceOptionalRules         = app.Option("--enforce-optional-rules", "Enforce optional rules, in addition to the mandatory set of rules.", CommandOptionType.NoValue);
            CommandOption allowDefaultInterfaceMethods = app.Option("--allow-default-interface-methods", "Allow default interface methods additions to not be considered breaks. This flag should only be used if you know your consumers support DIM", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                string leftOperandValue  = leftOperand.HasValue() ? leftOperand.Value() : "contract";
                string rightOperandValue = rightOperand.HasValue() ? rightOperand.Value() : "implementation";

                if (listRules.HasValue())
                {
                    CompositionHost c = GetCompositionHost();
                    ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                    var rules = c.GetExports <IDifferenceRule>();

                    foreach (var rule in rules.OrderBy(r => r.GetType().Name, StringComparer.OrdinalIgnoreCase))
                    {
                        string ruleName = rule.GetType().Name;

                        if (IsOptionalRule(rule))
                        {
                            ruleName += " (optional)";
                        }

                        Console.WriteLine(ruleName);
                    }

                    return(0);
                }

                using (TextWriter output = GetOutput(outFilePath.Value()))
                {
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    if (output != Console.Out)
                    {
                        Trace.Listeners.Add(new TextWriterTraceListener(output)
                        {
                            Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                        });
                    }

                    try
                    {
                        BaselineDifferenceFilter filter             = GetBaselineDifferenceFilter(baseline.Value());
                        NameTable sharedNameTable                   = new NameTable();
                        HostEnvironment contractHost                = new HostEnvironment(sharedNameTable);
                        contractHost.UnableToResolve               += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {leftOperandValue} assembly '{e.Referrer}'.");
                        contractHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        contractHost.UnifyToLibPath                 = !skipUnifyToLibPath.HasValue();
                        contractHost.AddLibPaths(HostEnvironment.SplitPaths(contractDepends.Value()));
                        IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(contracts.Value, contractCoreAssembly.Value());

                        if (ignoreDesignTimeFacades.HasValue())
                        {
                            contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                        }

                        HostEnvironment implHost  = new HostEnvironment(sharedNameTable);
                        implHost.UnableToResolve += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {rightOperandValue} assembly '{e.Referrer}'.");
                        implHost.ResolveAgainstRunningFramework = resolveFx.HasValue();
                        implHost.UnifyToLibPath = !skipUnifyToLibPath.HasValue();
                        implHost.AddLibPaths(HostEnvironment.SplitPaths(implDirs.Value()));
                        if (warnOnMissingAssemblies.HasValue())
                        {
                            implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                        }

                        // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                        IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), warnOnIncorrectVersion.HasValue());

                        // Exit after loading if the code is set to non-zero
                        if (DifferenceWriter.ExitCode != 0)
                        {
                            return(0);
                        }

                        ICciDifferenceWriter writer = GetDifferenceWriter(output, filter, enforceOptionalRules.HasValue(), mdil.HasValue(),
                                                                          excludeNonBrowsable.HasValue(), remapFile.Value(), !skipGroupByAssembly.HasValue(), leftOperandValue, rightOperandValue, excludeAttributes.Value(), allowDefaultInterfaceMethods.HasValue());
                        writer.Write(implDirs.Value(), implAssemblies, contracts.Value, contractAssemblies);

                        return(0);
                    }
                    catch (FileNotFoundException)
                    {
                        // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                        // OR if GetComparers doesn't find the remap file.
                        return(2);
                    }
                }
            });

            return(app.Execute(args));
        }
        public static ImmutableArray <T> GetExports <T>(IEnumerable <Assembly> assemblies)
        {
            CompositionHost container = CreateCompositionContainer <T>(assemblies);

            return(container.GetExports <T>().ToImmutableArray());
        }
Example #5
0
 private IEnumerable <IServiceRegistrar> GetDerivedRegistrars(CompositionHost container)
 {
     return(container
            .GetExports <IServiceRegistrar>()
            .Where(b => b.GetType() != typeof(RegistrarLoader)));
 }
Example #6
0
 public static IEnumerable <T> GetInstances <T>()
 {
     return(s_compositionHost.GetExports <T>());
 }
        public static int Main(string[] args)
        {
            ParseCommandLine(args);
            CommandLineTraceHandler.Enable();

            if (s_listRules)
            {
                CompositionHost c = GetCompositionHost();
                ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                var rules = c.GetExports <IDifferenceRule>();

                foreach (var rule in rules.Select(r => r.GetType().Name).OrderBy(r => r, StringComparer.OrdinalIgnoreCase))
                {
                    Console.WriteLine(rule);
                }

                return(0);
            }

            using (TextWriter output = GetOutput())
            {
                if (DifferenceWriter.ExitCode != 0)
                {
                    return(0);
                }

                if (output != Console.Out)
                {
                    Trace.Listeners.Add(new TextWriterTraceListener(output)
                    {
                        Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                    });
                }
                try
                {
                    BaselineDifferenceFilter filter = GetBaselineDifferenceFilter();
                    NameTable       sharedNameTable = new NameTable();
                    HostEnvironment contractHost    = new HostEnvironment(sharedNameTable);
                    contractHost.UnableToResolve += new EventHandler <UnresolvedReference <IUnit, AssemblyIdentity> >(contractHost_UnableToResolve);
                    contractHost.ResolveAgainstRunningFramework = s_resolveFx;
                    contractHost.UnifyToLibPath = s_unifyToLibPaths;
                    contractHost.AddLibPaths(HostEnvironment.SplitPaths(s_contractLibDirs));
                    IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(s_contractSet, s_contractCoreAssembly);

                    if (s_ignoreDesignTimeFacades)
                    {
                        contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                    }

                    HostEnvironment implHost = new HostEnvironment(sharedNameTable);
                    implHost.UnableToResolve += new EventHandler <UnresolvedReference <IUnit, AssemblyIdentity> >(implHost_UnableToResolve);
                    implHost.ResolveAgainstRunningFramework = s_resolveFx;
                    implHost.UnifyToLibPath = s_unifyToLibPaths;
                    implHost.AddLibPaths(HostEnvironment.SplitPaths(s_implDirs));
                    if (s_warnOnMissingAssemblies)
                    {
                        implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                    }

                    // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                    IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), s_warnOnIncorrectVersion);

                    // Exit after loading if the code is set to non-zero
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    ICciDifferenceWriter writer = GetDifferenceWriter(output, filter);
                    writer.Write(s_implDirs, implAssemblies, s_contractSet, contractAssemblies);
                    return(0);
                }
                catch (FileNotFoundException)
                {
                    // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                    // OR if GetComparers doesn't find the remap file.
                    return(2);
                }
            }
        }
Example #8
0
        public void Configure(IApplicationBuilder app,
                              IServiceProvider serviceProvider,
                              IOmnisharpEnvironment env,
                              ILoggerFactory loggerFactory,
                              ISharedTextWriter writer,
                              IOmnisharpAssemblyLoader loader,
                              IOptions <OmniSharpOptions> optionsAccessor)
        {
            Func <RuntimeLibrary, bool> shouldLoad = lib => lib.Dependencies.Any(dep => dep.Name == "OmniSharp.Abstractions" ||
                                                                                 dep.Name == "OmniSharp.Roslyn");

            var dependencyContext = DependencyContext.Default;
            var assemblies        = dependencyContext.RuntimeLibraries
                                    .Where(shouldLoad)
                                    .SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext))
                                    .Select(each => loader.Load(each.Name))
                                    .ToList();

            PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies);

            Workspace = PluginHost.GetExport <OmnisharpWorkspace>();

            if (env.TransportType == TransportType.Stdio)
            {
                loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env));
            }
            else
            {
                loggerFactory.AddConsole((category, level) => LogFilter(category, level, env));
            }

            var logger = loggerFactory.CreateLogger <Startup>();

            foreach (var assembly in assemblies)
            {
                logger.LogDebug($"Loaded {assembly.FullName}");
            }

            app.UseRequestLogging();
            app.UseExceptionHandler("/error");
            app.UseMiddleware <EndpointMiddleware>();
            app.UseMiddleware <StatusMiddleware>();
            app.UseMiddleware <StopServerMiddleware>();

            if (env.TransportType == TransportType.Stdio)
            {
                logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{env.Path}' on host {env.HostPID}.");
            }
            else
            {
                logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}.");
            }

            // ProjectEventForwarder register event to OmnisharpWorkspace during instantiation
            PluginHost.GetExport <ProjectEventForwarder>();

            // Initialize all the project systems
            foreach (var projectSystem in PluginHost.GetExports <IProjectSystem>())
            {
                try
                {
                    projectSystem.Initalize(Configuration.GetSection(projectSystem.Key));
                }
                catch (Exception e)
                {
                    var message = $"The project system '{projectSystem.GetType().Name}' threw exception during initialization.\n{e.Message}\n{e.StackTrace}";
                    // if a project system throws an unhandled exception it should not crash the entire server
                    logger.LogError(message);
                }
            }

            // Mark the workspace as initialized
            Workspace.Initialized = true;

            logger.LogInformation("Configuration finished.");
        }
        internal static RequestHandlers ConfigureCompositionHost(ILanguageServer server,
                                                                 CompositionHost compositionHost)
        {
            var projectSystems = compositionHost.GetExports <IProjectSystem>();

            var documentSelectors = projectSystems
                                    .GroupBy(x => x.Language)
                                    .Select(x => (
                                                language: x.Key,
                                                selector: new DocumentSelector(x
                                                                               .SelectMany(z => z.Extensions)
                                                                               .Distinct()
                                                                               .SelectMany(z =>
            {
                if (x.Key == LanguageNames.CSharp && z == ".cs")
                {
                    return(new[]
                    {
                        new DocumentFilter()
                        {
                            Pattern = $"**/*{z}"
                        },
                        new DocumentFilter()
                        {
                            Scheme = "csharp"
                        }
                    });
                }

                return(new[]
                {
                    new DocumentFilter()
                    {
                        Pattern = $"**/*{z}"
                    },
                });
            })
                                                                               )
                                                ))
                                    .ToArray();

            var logger = compositionHost.GetExport <ILoggerFactory>().CreateLogger <LanguageServerHost>();

            logger.LogTrace(
                "Configured Document Selectors {@DocumentSelectors}",
                documentSelectors.Select(x => new { x.language, x.selector })
                );

            var omnisharpRequestHandlers =
                compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >();
            // TODO: Get these with metadata so we can attach languages
            // This will then let us build up a better document filter, and add handles foreach type of handler
            // This will mean that we will have a strategy to create handlers from the interface type
            var handlers = new RequestHandlers(omnisharpRequestHandlers, documentSelectors);

            logger.LogTrace("--- Handler Definitions ---");
            foreach (var handlerCollection in handlers)
            {
                foreach (var handler in handlerCollection)
                {
                    logger.LogTrace(
                        "Handler: {Language}:{DocumentSelector}:{Handler}",
                        handlerCollection.Language,
                        handlerCollection.DocumentSelector.ToString(),
                        handler.GetType().FullName
                        );
                }
            }

            // the goal here is add interoperability between omnisharp and LSP
            // This way an existing client (say vscode) that is using the custom omnisharp protocol can migrate to the new one
            // and not loose any functionality.
            server.Register(r =>
            {
                var defaultOptions = new JsonRpcHandlerOptions()
                {
                    RequestProcessType = RequestProcessType.Parallel
                };
                var interop = InitializeInterop(compositionHost);
                foreach (var osHandler in interop)
                {
                    var method = $"o#/{osHandler.Key.Trim('/').ToLowerInvariant()}";
                    r.OnJsonRequest(method, CreateInteropHandler(osHandler.Value), defaultOptions);
                    logger.LogTrace("O# Handler: {Method}", method);
                }
Example #10
0
 protected override IEnumerable <object> GetAllInstances(Type serviceType)
 {
     return(_compositionHost.GetExports(serviceType));
 }
Example #11
0
        public void Configure(IApplicationBuilder app,
                              IServiceProvider serviceProvider,
                              IOmnisharpEnvironment env,
                              ILoggerFactory loggerFactory,
                              ISharedTextWriter writer,
                              IOptions <OmniSharpOptions> optionsAccessor)
        {
            var assemblies = DnxPlatformServices.Default.LibraryManager.GetReferencingLibraries("OmniSharp.Abstractions")
                             .SelectMany(libraryInformation => libraryInformation.Assemblies)
                             .Concat(
                DnxPlatformServices.Default.LibraryManager.GetReferencingLibraries("OmniSharp.Roslyn")
                .SelectMany(libraryInformation => libraryInformation.Assemblies)
                )
                             .Select(assemblyName => Assembly.Load(assemblyName));

            PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies);

            Workspace = PluginHost.GetExport <OmnisharpWorkspace>();

            if (env.TransportType == TransportType.Stdio)
            {
                loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env));
            }
            else
            {
                loggerFactory.AddConsole((category, level) => LogFilter(category, level, env));
            }

            var logger = loggerFactory.CreateLogger <Startup>();

            app.UseRequestLogging();
            app.UseExceptionHandler("/error");
            app.UseMiddleware <EndpointMiddleware>();
            app.UseMiddleware <StatusMiddleware>();
            app.UseMiddleware <StopServerMiddleware>();

            if (env.TransportType == TransportType.Stdio)
            {
                logger.LogInformation($"Omnisharp server running using stdio at location '{env.Path}' on host {env.HostPID}.");
            }
            else
            {
                logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}.");
            }

            // Forward workspace events
            PluginHost.GetExport <ProjectEventForwarder>();
            foreach (var projectSystem in PluginHost.GetExports <IProjectSystem>())
            {
                try
                {
                    projectSystem.Initalize(Configuration.GetSection(projectSystem.Key));
                }
                catch (Exception e)
                {
                    //if a project system throws an unhandled exception
                    //it should not crash the entire server
                    logger.LogError($"The project system '{projectSystem.GetType().Name}' threw an exception.", e);
                }
            }

            // Mark the workspace as initialized
            Workspace.Initialized = true;

            logger.LogInformation("Solution has finished loading");
        }
Example #12
0
 public IEsotericInterpreter InterpreterFor(string language)
 {
     return(Container.GetExports <IEsotericInterpreter>().FirstOrDefault(interp => interp.Language == language));
 }
Example #13
0
 /// <summary>Enumerates plugin providers exported from assemblies in the current executable folder.</summary>
 public static IEnumerable <IWpPluginProvider> GetProviders(CompositionHost host) => host.GetExports <IWpPluginProvider>();
Example #14
0
 /// <summary>
 /// Finds all the extensions from the given base type.
 /// </summary>
 /// <returns>The extensions.</returns>
 /// <typeparam name="T">Type of the extension point.</typeparam>
 public IEnumerable <T> FindExtensions <T>()
 {
     return(container.GetExports <T>());
 }
Example #15
0
        private void CreateCompositionHost(InitializeParams initializeParams)
        {
            _environment = new OmniSharpEnvironment(
                Helpers.FromUri(initializeParams.RootUri),
                Convert.ToInt32(initializeParams.ProcessId ?? -1L),
                GetLogLevel(initializeParams.Trace),
                _application.OtherArgs.ToArray());

            // TODO: Make this work with logger factory differently
            // Maybe create a child logger factory?
            _loggerFactory.AddProvider(_server, _environment);
            _logger = _loggerFactory.CreateLogger <LanguageServerHost>();

            var configurationRoot = new ConfigurationBuilder(_environment).Build();
            var eventEmitter      = new LanguageServerEventEmitter(_server);

            _serviceProvider = CompositionHostBuilder.CreateDefaultServiceProvider(_environment, configurationRoot, eventEmitter, _services);

            var plugins = _application.CreatePluginAssemblies();

            var assemblyLoader         = _serviceProvider.GetRequiredService <IAssemblyLoader>();
            var compositionHostBuilder = new CompositionHostBuilder(_serviceProvider)
                                         .WithOmniSharpAssemblies()
                                         .WithAssemblies(typeof(LanguageServerHost).Assembly)
                                         .WithAssemblies(assemblyLoader.LoadByAssemblyNameOrPath(plugins.AssemblyNames).ToArray());

            _compositionHost = compositionHostBuilder.Build();

            var projectSystems = _compositionHost.GetExports <IProjectSystem>();

            var documentSelectors = projectSystems
                                    .GroupBy(x => x.Language)
                                    .Select(x => (
                                                language: x.Key,
                                                selector: new DocumentSelector(x
                                                                               .SelectMany(z => z.Extensions)
                                                                               .Distinct()
                                                                               .Select(z => new DocumentFilter()
            {
                Pattern = $"**/*{z}"
            }))
                                                ));

            _logger.LogTrace(
                "Configured Document Selectors {@DocumentSelectors}",
                documentSelectors.Select(x => new { x.language, x.selector })
                );

            // TODO: Get these with metadata so we can attach languages
            // This will thne let us build up a better document filter, and add handles foreach type of handler
            // This will mean that we will have a strategy to create handlers from the interface type
            _handlers = new RequestHandlers(
                _compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >(),
                documentSelectors
                );

            _logger.LogTrace("--- Handler Definitions ---");
            foreach (var handlerCollection in _handlers)
            {
                foreach (var handler in handlerCollection)
                {
                    _logger.LogTrace(
                        "Handler: {Language}:{DocumentSelector}:{Handler}",
                        handlerCollection.Language,
                        handlerCollection.DocumentSelector.ToString(),
                        handler.GetType().FullName
                        );
                }
            }
            _logger.LogTrace("--- Handler Definitions ---");
        }
Example #16
0
 public IEnumerable <T> GetServices <T>()
 {
     return(_container.GetExports <T>());
 }
Example #17
0
        internal static bool InitPlugins()
        {
            HashSet <Assembly> assemblies = LoadAssemblies();

            if ((assemblies == null) || (assemblies.Count == 0))
            {
                ASF.ArchiLogger.LogGenericTrace(Strings.NothingFound);

                return(true);
            }

            ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.Initializing, nameof(Plugins)));

            ConventionBuilder conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IPlugin>().Export <IPlugin>();

            ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            HashSet <IPlugin> activePlugins;

            try {
                using (CompositionHost container = configuration.CreateContainer()) {
                    activePlugins = container.GetExports <IPlugin>().ToHashSet();
                }
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);

                return(false);
            }

            if (activePlugins.Count == 0)
            {
                return(true);
            }

            HashSet <IPlugin> invalidPlugins = new HashSet <IPlugin>();

            foreach (IPlugin plugin in activePlugins)
            {
                try {
                    string pluginName = plugin.Name;

                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoading, pluginName, plugin.Version));
                    plugin.OnLoaded();
                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoaded, pluginName));
                } catch (Exception e) {
                    ASF.ArchiLogger.LogGenericException(e);
                    invalidPlugins.Add(plugin);
                }
            }

            if (invalidPlugins.Count > 0)
            {
                activePlugins.ExceptWith(invalidPlugins);

                if (activePlugins.Count == 0)
                {
                    return(false);
                }
            }

            ActivePlugins = activePlugins.ToImmutableHashSet();
            ASF.ArchiLogger.LogGenericInfo(Strings.PluginsWarning);

            return(invalidPlugins.Count == 0);
        }
Example #18
0
        /// <summary>
        /// The core part of ApiCompat which accepts a given set of arguments and
        /// performs api compatibility checks.
        /// </summary>
        public static int Run(bool usesMSBuildLog,
                              bool disableAssemblyResolveTraceListener,
                              IEnumerable <string> contracts,
                              IEnumerable <string> implementationDirectories,
                              TextWriter output,
                              string rightOperand = "implementation",
                              string leftOperand  = "contract",
                              bool listRules      = false,
                              IEnumerable <string> baselineFileNames = null,
                              bool validateBaseline   = false,
                              bool resolveFramework   = false,
                              bool skipUnifyToLibPath = false,
                              IEnumerable <string> contractDependsFileNames = null,
                              string contractCoreAssembly  = null,
                              bool ignoreDesignTimeFacades = false,
                              bool warnOnMissingAssemblies = false,
                              bool respectInternals        = false,
                              bool warnOnIncorrectVersion  = false,
                              bool enforceOptionalRules    = false,
                              bool mdil = false,
                              bool excludeNonBrowsable      = false,
                              bool excludeCompilerGenerated = false,
                              string remapFile         = null,
                              bool skipGroupByAssembly = false,
                              IEnumerable <string> excludeAttributes = null,
                              bool allowDefaultInterfaceMethods      = false)
        {
            // Clear exit code from previous runs on the same domain given this is a static property.
            DifferenceWriter.ExitCode = 0;

            if (listRules)
            {
                CompositionHost c = GetCompositionHost();
                ExportCciSettings.StaticSettings = CciComparers.Default.GetEqualityComparer <ITypeReference>();

                IEnumerable <IDifferenceRule> rules = c.GetExports <IDifferenceRule>();

                foreach (IDifferenceRule rule in rules.OrderBy(r => r.GetType().Name, StringComparer.OrdinalIgnoreCase))
                {
                    string ruleName = rule.GetType().Name;

                    if (IsOptionalRule(rule))
                    {
                        ruleName += " (optional)";
                    }

                    output.WriteLine(ruleName);
                }

                return(0);
            }

            using (output)
            {
                if (DifferenceWriter.ExitCode != 0)
                {
                    return(0);
                }

                if (!disableAssemblyResolveTraceListener)
                {
                    Trace.Listeners.Add(new TextWriterTraceListener(output)
                    {
                        Filter = new EventTypeFilter(SourceLevels.Error | SourceLevels.Warning)
                    });
                }

                try
                {
                    BaselineDifferenceFilter filter = GetBaselineDifferenceFilter(baselineFileNames, validateBaseline);
                    NameTable       sharedNameTable = new();
                    HostEnvironment contractHost    = new(sharedNameTable);
                    contractHost.UnableToResolve += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {leftOperand} assembly '{e.Referrer}'.");
                    contractHost.ResolveAgainstRunningFramework = resolveFramework;
                    contractHost.UnifyToLibPath = !skipUnifyToLibPath;
                    contractHost.AddLibPaths(contractDependsFileNames);
                    IEnumerable <IAssembly> contractAssemblies = contractHost.LoadAssemblies(contracts, contractCoreAssembly);

                    if (ignoreDesignTimeFacades)
                    {
                        contractAssemblies = contractAssemblies.Where(a => !a.IsFacade());
                    }

                    HostEnvironment implHost = new(sharedNameTable);
                    implHost.UnableToResolve += (sender, e) => Trace.TraceError($"Unable to resolve assembly '{e.Unresolved}' referenced by the {rightOperand} assembly '{e.Referrer}'.");
                    implHost.ResolveAgainstRunningFramework = resolveFramework;
                    implHost.UnifyToLibPath = !skipUnifyToLibPath;
                    implHost.AddLibPaths(implementationDirectories);
                    if (warnOnMissingAssemblies)
                    {
                        implHost.LoadErrorTreatment = ErrorTreatment.TreatAsWarning;
                    }

                    // The list of contractAssemblies already has the core assembly as the first one (if _contractCoreAssembly was specified).
                    IEnumerable <IAssembly> implAssemblies = implHost.LoadAssemblies(contractAssemblies.Select(a => a.AssemblyIdentity), warnOnIncorrectVersion);

                    // Exit after loading if the code is set to non-zero
                    if (DifferenceWriter.ExitCode != 0)
                    {
                        return(0);
                    }

                    bool includeInternals = respectInternals &&
                                            contractAssemblies.Any(assembly => assembly.Attributes.HasAttributeOfType(
                                                                       "System.Runtime.CompilerServices.InternalsVisibleToAttribute"));
                    ICciDifferenceWriter writer = GetDifferenceWriter(
                        output,
                        filter,
                        enforceOptionalRules,
                        mdil,
                        excludeNonBrowsable,
                        includeInternals,
                        excludeCompilerGenerated,
                        remapFile,
                        !skipGroupByAssembly,
                        leftOperand,
                        rightOperand,
                        excludeAttributes,
                        allowDefaultInterfaceMethods,
                        usesMSBuildLog);
                    writer.Write(string.Join(",", implementationDirectories), implAssemblies, string.Join(",", contracts), contractAssemblies);

                    return(0);
                }
                catch (FileNotFoundException)
                {
                    // FileNotFoundException will be thrown by GetBaselineDifferenceFilter if it doesn't find the baseline file
                    // OR if GetComparers doesn't find the remap file.
                    return(2);
                }
            }
        }