static async Task <int> Main(string[] args) { try { var arguments = Args.Parse <Arguments>(args); var language = arguments.Language.GetValueOrDefault(DetermineLanguageByOutputFileName(arguments.OutputFile)); var logSink = arguments.Verbose ? (ILogSink)ConsoleLogSink.Instance : NullLogSink.Instance; var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new LogSinkLoggerProvider(logSink)); var options = new AnalyzerManagerOptions { LoggerFactory = loggerFactory, }; var manager = new AnalyzerManager(arguments.SolutionFile, options); var workspace = manager.GetWorkspace(); var compilationTasks = workspace .CurrentSolution .Projects .Select(project => project.GetCompilationAsync()); var compilations = await Task.WhenAll(compilationTasks); var syntaxNodes = XmlBasedGenerator.GenerateMocks( logSink, language, compilations.ToImmutableList(), arguments.ConfigurationFile); var result = syntaxNodes .Aggregate( new StringBuilder(), (acc, next) => acc.AppendLine(next.ToFullString()).AppendLine(), acc => acc.ToString()); var log = logSink.ToString(); File.WriteAllText(arguments.OutputFile, result); return(0); } catch (ArgException ex) { WriteLine(OutputType.Error, ex.Message); WriteLine(); WriteLine(ArgUsage.GenerateUsageFromTemplate <Arguments>().ToNormalString()); return(-1); } catch (Exception ex) { WriteLine(OutputType.Error, "Failed to generate code: {0}", ex); return(-1); } }
private AnalyzerManager GetAnalyzerManager() { AnalyzerManager analyzerManager; var analyzerManagerOptions = new AnalyzerManagerOptions { LogWriter = _writer }; if (IsSolutionFile()) { analyzerManager = new AnalyzerManager(WorkspacePath, analyzerManagerOptions); } else { analyzerManager = new AnalyzerManager(analyzerManagerOptions); } return(analyzerManager); }
public static async Task GoAsync(string[] args) { //.NET core csprojects are not supported all that well. // https://github.com/dotnet/roslyn/issues/21660 :sadpanda: // Use Buildalyzer to get a workspace from the solution. var options = new AnalyzerManagerOptions() { }; var analyzer = new AnalyzerManager(Path.Combine(Program.InputDirPath, "CodeGeneration", "ElasticsearchCodeGeneration.sln")); var workspace = analyzer.GetWorkspace(); workspace.WorkspaceFailed += (s, e) => { Console.Error.WriteLine(e.Diagnostic.Message); }; // Buildalyzer, similar to MsBuildWorkspace with the new csproj file format, does // not pick up source documents in the project directory. Manually add them // AddDocumentsToWorkspace(workspace); var projects = workspace.CurrentSolution.Projects .ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); DeleteExistingDocs(); foreach (var file in GetDocumentFiles(projects).SelectMany(s => s)) { await file.SaveToDocumentationFolderAsync(); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Documentation generated."); Console.ResetColor(); if (Debugger.IsAttached) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } }
public static async Task <Compilation> GetCompilationFromProject(string csprojPath, params string[] preprocessorSymbols) { var analyzerOptions = new AnalyzerManagerOptions(); // analyzerOptions.LogWriter = Console.Out; var manager = new AnalyzerManager(); var projectAnalyzer = manager.GetProject(csprojPath); // addproj // projectAnalyzer.AddBuildLogger(new Microsoft.Build.Logging.ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity.Minimal)); var workspace = manager.GetWorkspaceWithPreventBuildEvent(); workspace.WorkspaceFailed += WorkSpaceFailed; var project = workspace.CurrentSolution.Projects.First(); project = project .WithParseOptions((project.ParseOptions as CSharpParseOptions).WithPreprocessorSymbols(preprocessorSymbols)) .WithCompilationOptions((project.CompilationOptions as CSharpCompilationOptions).WithAllowUnsafe(true)); var compilation = await project.GetCompilationAsync().ConfigureAwait(false); return(compilation); }
static void Main(string[] args) { try { System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += (ctx, name) => { Console.WriteLine($"asm name={name}"); return(null); }; // another workaround, read required assemblies before compile. foreach (var dllname in new string[] { "NuGet.Versioning", "NuGet.Common", "NuGet.Frameworks" }) { const string sdkdir = @"C:\Program Files\dotnet\sdk\2.1.300"; System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(sdkdir, $"{dllname}.dll")); } var manageropts = new AnalyzerManagerOptions(); manageropts.LogWriter = Console.Out; manageropts.LoggerVerbosity = LoggerVerbosity.Normal; var manager = new AnalyzerManager(manageropts); var analyzer = manager.GetProject(args[0]); var project = analyzer.Compile(); if (project != null) { foreach (var x in project.Items) { var meta = x.Metadata.Select(y => $"{y.Name}={y.EvaluatedValue}"); Console.WriteLine($"{x.ItemType},{string.Join("|", meta)}"); } } else { Console.WriteLine($"project instance is null"); } } catch (Exception e) { Console.WriteLine($"{e}"); } }
public static async Task <int> GoAsync(string[] args) { //.NET core csprojects are not supported all that well. // https://github.com/dotnet/roslyn/issues/21660 :sadpanda: // Use Buildalyzer to get a workspace from the solution. var options = new AnalyzerManagerOptions() { ProjectFilter = p => ProjectsWeWant.Contains(p.ProjectName) }; var analyzer = new AnalyzerManager(Path.Combine(Program.InputDirPath, "..", "Elasticsearch.sln"), options); var workspace = analyzer.GetWorkspace(); var seenFailures = false; workspace.WorkspaceFailed += (s, e) => { Console.Error.WriteLine($"Workplace failure: {e.Diagnostic.Message}"); seenFailures = true; }; var projects = workspace.CurrentSolution.Projects .ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); if (seenFailures) { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("Documentation failed to generate."); Console.ResetColor(); return(2); } DeleteExistingTmpDocs(); foreach (var file in GetDocumentFiles(projects).SelectMany(s => s)) { await file.SaveToDocumentationFolderAsync(); } if (seenFailures) { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("Documentation failed to generate."); Console.ResetColor(); return(2); } CopyBreakingChangesDocs(); CopyReleaseNotes(); DeleteExistingDocsAndSwap(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Documentation generated."); Console.ResetColor(); if (Debugger.IsAttached) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } return(0); }
public static async Task <Compilation> GetCompilationFromProject(string csprojPath, int verbosityLevel, Dictionary <string, string> additionalProperties, IEnumerable <string> conditionalSymbols) { conditionalSymbols = conditionalSymbols != null? conditionalSymbols.Where(x => !string.IsNullOrEmpty(x)).ToArray() : Enumerable.Empty <string>(); // f*****g workaround of resolve reference... var externalReferences = new List <PortableExecutableReference>(); { var locations = new List <string>(); locations.Add(typeof(object).Assembly.Location); // mscorlib locations.Add(typeof(System.Linq.Enumerable).Assembly.Location); // core var xElem = XElement.Load(csprojPath); var ns = xElem.Name.Namespace; var csProjRoot = Path.GetDirectoryName(csprojPath); var framworkRoot = Path.GetDirectoryName(typeof(object).Assembly.Location); foreach (var item in xElem.Descendants(ns + "Reference")) { var hintPath = item.Element(ns + "HintPath")?.Value; if (hintPath == null) { var path = Path.Combine(framworkRoot, item.Attribute("Include").Value + ".dll"); locations.Add(path); } else { locations.Add(Path.Combine(csProjRoot, hintPath)); } } foreach (var item in locations.Distinct()) { if (File.Exists(item)) { externalReferences.Add(MetadataReference.CreateFromFile(item)); } } } EnvironmentHelper.Setup(); var analyzerOptions = new AnalyzerManagerOptions(); if (verbosityLevel > 0) { analyzerOptions.LogWriter = Console.Out; } var manager = new AnalyzerManager(analyzerOptions); var projectAnalyzer = manager.GetProject(csprojPath); projectAnalyzer.AddBuildLogger(new Microsoft.Build.Logging.ConsoleLogger(verbosityLevel.ToLoggerVerbosity())); var buildopts = new EnvironmentOptions(); if (additionalProperties != null) { foreach (var kv in additionalProperties) { buildopts.GlobalProperties[kv.Key] = kv.Value; projectAnalyzer.SetGlobalProperty(kv.Key, kv.Value); } } if (conditionalSymbols.Any()) { buildopts.GlobalProperties["DefineConstants"] = string.Join("%3b", conditionalSymbols); } var analyzerResults = projectAnalyzer.Build(buildopts); var analyzerResult = analyzerResults.FirstOrDefault(x => x.Succeeded); if (analyzerResult == null) { throw new Exception("no succeeded analyzer result found"); } var ws = new AdhocWorkspace(); var project = analyzerResult.AddToWorkspace(ws); var parseopts = project.ParseOptions as CSharpParseOptions; if (parseopts != null) { var symbols = analyzerResult.Properties.ContainsKey("DefineConstants") ? conditionalSymbols.Concat( analyzerResult.Properties["DefineConstants"].Split(';') ).OrderBy(x => x).Distinct() : conditionalSymbols ; project = project.WithParseOptions(parseopts.WithPreprocessorSymbols(symbols)); } var compilation = await project.GetCompilationAsync().ConfigureAwait(false); return(compilation); }
public IAnalyzerManager Provide(string solutionFilePath, AnalyzerManagerOptions options = null) { return(new AnalyzerManager(solutionFilePath, options)); }
public IAnalyzerManager Provide(AnalyzerManagerOptions options = null) { return(new AnalyzerManager(options)); }