/// <summary> /// Initializes a new instance of the <see cref="CsvCompilerModule"/> class. /// </summary> public CSharpCompilerModule(Bootstrapper bootstrapper) : base(bootstrapper) { compiler = new CSharpCompiler(); workspace = new AdhocWorkspace(); project = workspace.AddProject("CSharpProject", LanguageNames.CSharp); document = project.AddDocument("current", ""); context = new CompilationContext(workspace, document); }
public static Project LoadDocuments(this Project project, params string[] paths) { foreach (var tree in LoadDocuments(paths.Select(Path.GetFullPath))) { var name = Path.GetFileNameWithoutExtension(tree.FilePath); project = project.AddDocument(name, tree.GetRoot(), null, tree.FilePath).Project; } return(project); }
public static Task<Document> GetDocumentFromMetadata(Project project, ISymbol symbol, CancellationToken cancellationToken = new CancellationToken()) { var filePath = GetFilePathForSymbol(project, symbol); var topLevelSymbol = GetTopLevelContainingNamedType(symbol); var temporaryDocument = project.AddDocument(filePath, string.Empty); object service = Activator.CreateInstance(_CSharpMetadataAsSourceService.Value, new object[] { temporaryDocument.Project.LanguageServices }); var method = _CSharpMetadataAsSourceService.Value.GetMethod("AddSourceToAsync"); return (Task<Document>)method.Invoke(service, new object[] { temporaryDocument, topLevelSymbol, cancellationToken }); }
public async void UpdatePreview(string text) { var workspace = new PreviewWorkspace(Ide.Composition.CompositionManager.Instance.HostServices); var fileName = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj"); project = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language); // use the mscorlib, system, and system.core that are loaded in the current process. string [] references = { "mscorlib", "System", "System.Core" }; var metadataService = workspace.Services.GetService <IMetadataService> (); var referenceAssemblies = Thread.GetDomain().GetAssemblies() .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase)) .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly)); project = project.WithMetadataReferences(referenceAssemblies); var document = project.AddDocument("document.cs", SourceText.From(text, Encoding.UTF8)); var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None); workspace.TryApplyChanges(project.Solution); TextViewHost.MimeType = "text/x-csharp"; TextViewHost.Text = (await document.GetTextAsync()).ToString(); TextViewHost.DocumentContext = new MyDocumentContext(workspace, document); TextViewHost.IsReadOnly = false; for (int i = 1; i <= TextViewHost.LineCount; i++) { var txt = TextViewHost.GetLineText(i); if (txt == "//[" || txt == "//]") { var line = TextViewHost.GetLine(i); TextViewHost.RemoveText(line.Offset, line.LengthIncludingDelimiter); i--; } } TextViewHost.IsReadOnly = true; if (curWorkspace != null) { curWorkspace.Dispose(); } this.curWorkspace = workspace; }
private void GetProjectWorkspaceItems(Microsoft.CodeAnalysis.Project project, WorkspaceItem projectItem, WorkspaceItem item) { var dirPath = Path.GetExtension(item.Path).Equals(".csproj", StringComparison.OrdinalIgnoreCase) ? Path.GetDirectoryName(item.Path) : item.Path; var directories = new DirectoryInfo(dirPath).GetDirectories(); foreach (var dir in directories) { if (!(item.Items.FirstOrDefault(x => x.Path.Equals(dir.FullName, StringComparison.OrdinalIgnoreCase)) is WorkspaceItem dirItem)) { dirItem = new WorkspaceItem(WorkspaceItemType.Folder, projectItem, dir.Name, dir.FullName); item.Items.AddItem(dirItem); } GetProjectWorkspaceItems(project, projectItem, dirItem); } foreach (var wsi in item.Items.Where(x => x.Type == WorkspaceItemType.Folder).ToArray()) { if (!directories.Any(x => x.FullName.Equals(wsi.Path, StringComparison.OrdinalIgnoreCase))) { item.Items.Remove(wsi); } } var files = new DirectoryInfo(dirPath).GetFiles().OrderBy(x => x.Name); foreach (var file in files) { if (file.Extension.Equals(".csproj", StringComparison.OrdinalIgnoreCase)) { continue; } if (projectItem.HasFile(file.FullName)) { continue; } if (item.Items.FirstOrDefault(x => !x.Name.Equals(file.Name, StringComparison.OrdinalIgnoreCase) && file.Name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && !item.HasFile(file.FullName)) is WorkspaceItem parent) { var doc = project.Documents.FirstOrDefault(x => x.FilePath.Equals(file.FullName, StringComparison.OrdinalIgnoreCase)); //TODO: specify source kind if (doc == null) { doc = project.AddDocument(file.Name, string.Empty, null, file.FullName); project = doc.Project; } parent.Items.AddItem(new WorkspaceItem(WorkspaceItemType.File, projectItem, file.Name, file.FullName, doc)); } else { var doc = project.Documents.FirstOrDefault(x => x.FilePath.Equals(file.FullName, StringComparison.OrdinalIgnoreCase)); //TODO: specify source kind if (doc == null) { doc = project.AddDocument(file.Name, string.Empty, null, file.FullName); project = doc.Project; } item.Items.AddItem(new WorkspaceItem(WorkspaceItemType.File, projectItem, file.Name, file.FullName, doc)); } } foreach (var wsi in item.Items.Where(x => x.Type == WorkspaceItemType.File).ToArray()) { if (!files.Any(x => x.FullName.Equals(wsi.Path, StringComparison.OrdinalIgnoreCase))) { item.Items.Remove(wsi); } } }
private static void AddPathToProject(ref Solution solution, ref Project project, string fileName, string contents) { var document = GetExistingDocument(project, fileName); if (document != null) { project = project.RemoveDocument(document.Id); solution = project.Solution; } Console.WriteLine($"\t - Adding {fileName} to project"); document = project.AddDocument(fileName, contents, null, Path.Combine(Path.GetDirectoryName(project.FilePath), fileName)); project = document.Project; solution = project.Solution; }
private static Workspace CompileHandlebarsFiles(Project project, Workspace workspace, List<string> hbsFiles, CompilerOptions options) { bool successFullCompilation = true; while(hbsFiles.Any() && successFullCompilation) { successFullCompilation = false; var nextRound = new List<string>(); foreach(var file in hbsFiles) { var fileInfo = new FileInfo(file); string @namespace; bool compiledVersionExists = File.Exists($"{file}.cs"); bool compiledVersionIsOlder = true; if (compiledVersionExists) {//Compiled Version already exists var compiledFileInfo = new FileInfo($"{file}.cs"); compiledVersionIsOlder = (fileInfo.LastWriteTimeUtc > compiledFileInfo.LastWriteTimeUtc); @namespace = DetermineNamespace(compiledFileInfo); } else { @namespace = DetermineNamespace(fileInfo, project); } if (compiledVersionIsOlder || options.ForceRecompilation) { string content = File.ReadAllText(file); string name = Path.GetFileNameWithoutExtension(file); var compilationResult = CompileHandlebarsTemplate(content, @namespace, name, project, options); if (!options.DryRun) { if (compilationResult?.Item2?.Any() ?? false) {//Errors occured if (compilationResult.Item2.OfType<HandlebarsTypeError>().Any(x => x.Kind == HandlebarsTypeErrorKind.UnknownPartial)) {//Unresolvable Partial... could be due to compiling sequence //Console.WriteLine($"Unresolved partial call for template '{name}'. Try again!"); nextRound.Add(file); } else foreach (var error in compilationResult.Item2) PrintError(error); } else { successFullCompilation = true; //Check if template already exits var doc = project.Documents.FirstOrDefault(x => x.Name.Equals(string.Concat(name, ".hbs.cs"))); if (doc != null) {//And change it if it does project = doc.WithSyntaxRoot(CSharpSyntaxTree.ParseText(SourceText.From(compilationResult.Item1)).GetRoot()).Project; } else {//Otherwise add a new document project = project.AddDocument(string.Concat(name, ".hbs.cs"), SourceText.From(compilationResult.Item1), GetFolderStructureForFile(fileInfo, project)).Project; } try { workspace.TryApplyChanges(project.Solution); project = workspace.CurrentSolution.Projects.First(x => x.Id.Equals(project.Id)); } catch(NotSupportedException) {//ProjectJsonWorkspace does not support adding documents (as of 2016-02-17). So just add it manually File.WriteAllText($"{file}.cs", compilationResult.Item1); } } } } } hbsFiles = nextRound; } return workspace; }
private static Project MoveTypeNodes(SemanticModel model, ImmutableArray<TypeToRemove> typesToRemove, Func<string, string> typeFolderGenerator, Project project, CancellationToken token) { var projectName = project.Name; foreach (var typeToRemove in typesToRemove) { token.ThrowIfCancellationRequested(); var fileName = $"{typeToRemove.Symbol.Name}.cs"; var containingNamespace = typeToRemove.Symbol.GetContainingNamespace(); var typeFolder = typeFolderGenerator(containingNamespace).Replace( projectName, string.Empty); if (typeFolder.StartsWith("\\")) { typeFolder = typeFolder.Remove(0, 1); } project = project.AddDocument(fileName, typeToRemove.Declaration.GetCompilationUnitForType(model, containingNamespace), folders: !string.IsNullOrWhiteSpace(typeFolder) ? new[] { typeFolder } : null).Project; } return project; }
private static Project AddDocument( Project project, KeyValuePair<INamedTypeSymbol, string> symbolAndText, HashSet<string> existingFileNames) { var symbol = symbolAndText.Key; var text = symbolAndText.Value; var sanitizedTypeName = Paths.SanitizeFileName(symbol.Name); if (symbol.IsGenericType) { sanitizedTypeName = sanitizedTypeName + "`" + symbol.TypeParameters.Length; } var fileName = sanitizedTypeName + ".cs"; var folders = GetFolderChain(symbol); if (folders == null) { // There was an unutterable namespace name - abort the entire document return null; } var foldersString = string.Join(".", folders ?? Enumerable.Empty<string>()); var fileNameAndFolders = foldersString + fileName; int index = 1; while (!existingFileNames.Add(fileNameAndFolders)) { fileName = sanitizedTypeName + index + ".cs"; fileNameAndFolders = foldersString + fileName; index++; } project = project.AddDocument(fileName, text, folders, fileName).Project; return project; }
protected override Project AddDocument(Project fromProject) => fromProject.AddDocument(DocumentInfo.Name, Text, DocumentInfo.Folders, DocumentInfo.FilePath).Project;
public static Document AddDocument(this Project project, DocumentTemplate fileTemplate) { return(project.AddDocument(fileTemplate.FileName, fileTemplate.Syntax, fileTemplate.SolutionFolders)); }