public async Task ProvideCompletionAsync_DoesNotProvideCompletionsForDocumentWithoutPath() { // Arrange var project = ProjectInfo .Create(ProjectId.CreateNewId(), VersionStamp.Default, "TestProject", "TestAssembly", LanguageNames.CSharp) .WithFilePath("/TestProject.csproj"); var workspace = new AdhocWorkspace(); workspace.AddProject(project); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Test.cshtml"); var document = workspace.AddDocument(documentInfo); var codeDocumentProvider = new Mock <RazorCodeDocumentProvider>(MockBehavior.Strict); var completionProvider = new FailOnGetCompletionsProvider(new Lazy <RazorCodeDocumentProvider>(() => codeDocumentProvider.Object)); var context = CreateContext(1, completionProvider, document); // Act & Assert await completionProvider.ProvideCompletionsAsync(context); }
private Document AddDocumentToProject(string filePath, string language, string projectName) { var project = CurrentSolution.Projects.FirstOrDefault(p => p.Name == projectName && p.Language == language); if (project == null) { var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), projectName, projectName, language); OnManagedProjectAdded(projectInfo); project = CurrentSolution.GetProject(projectInfo.Id); } var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), name: Path.GetFileName(filePath), loader: new FileTextLoader(filePath, null), filePath: filePath); OnDocumentAdded(docInfo); return(CurrentSolution.GetDocument(docInfo.Id)); }
static TSymbol FindSymbol <TSymbol>(string code) where TSymbol : ISymbol { var position = code.IndexOf('$'); var cleanedCode = code.Remove(position, 1); var workspace = new DiagnosticTestBase.TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var docInfo = DocumentInfo.Create(documentId, "Document1.cs", loader: TextLoader.From(TextAndVersion.Create(SourceText.From(cleanedCode), VersionStamp.Create()))); var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "Project", "Project", LanguageNames.CSharp, metadataReferences: new[] { mscorlib }, documents: new[] { docInfo } ); workspace.Open(projectInfo); var document = workspace.CurrentSolution.GetDocument(documentId); var semanticModel = document.GetSemanticModelAsync().Result; var diag = semanticModel.GetDiagnostics(); Assert.That(diag, Is.Empty, "No errors reported"); var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace); Assert.That(symbol, Is.Not.Null, "Symbol should be found"); Assert.That(symbol, Is.InstanceOf <TSymbol>()); return((TSymbol)symbol); }
public DocumentId AddProjectWithDocument(string documentFileName, string text) { var fileName = Path.GetFileName(documentFileName); var name = Path.GetFileNameWithoutExtension(documentFileName) + counter++; var projectId = ProjectId.CreateNewId(); defaultMetadataReferences = defaultReferences.Select(CreateReference).ToList(); var projectInfo = ProjectInfo.Create(projectId, new VersionStamp(), name, name + ".dll", LanguageNames.CSharp, metadataReferences: defaultMetadataReferences, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); OnProjectAdded(projectInfo); var documentId = DocumentId.CreateNewId(projectId); var documentInfo = DocumentInfo.Create(documentId, fileName, loader: TextLoader.From(TextAndVersion.Create(SourceText.From(text, Encoding.UTF8), VersionStamp.Create()))); OnDocumentAdded(documentInfo); return(documentId); }
void VBWorkspaceSetup(out CSharpDiagnosticTestBase.TestWorkspace workspace, out Document doc, VisualBasicParseOptions parseOptions = null) { workspace = new CSharpDiagnosticTestBase.TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); if (parseOptions == null) { parseOptions = new VisualBasicParseOptions( Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14, DocumentationMode.Diagnose | DocumentationMode.Parse, SourceCodeKind.Regular ); } workspace.Options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, false); var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithRootNamespace("TestProject") .WithGlobalImports(GlobalImport.Parse("System", "System.Collections.Generic", "System.Linq", "Microsoft.VisualBasic")); workspace.Open(ProjectInfo.Create( projectId, VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.VisualBasic, null, null, compilationOptions, parseOptions, new[] { DocumentInfo.Create( documentId, "a.vb", null, SourceCodeKind.Regular ) }, null, DiagnosticTestBase.DefaultMetadataReferences ) ); doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId); }
private bool TryAddTransientDocument(string fileName, string fileContent) { if (string.IsNullOrWhiteSpace(fileName)) { return(false); } var projects = FindProjectsByFileName(fileName); if (!projects.Any()) { return(false); } var sourceText = SourceText.From(fileContent); var documentInfos = new List <DocumentInfo>(); foreach (var project in projects) { var id = DocumentId.CreateNewId(project.Id); var version = VersionStamp.Create(); var documentInfo = DocumentInfo.Create( id, fileName, filePath: fileName, loader: TextLoader.From(TextAndVersion.Create(sourceText, version))); documentInfos.Add(documentInfo); } lock (_lock) { var documentIds = documentInfos.Select(document => document.Id); _transientDocuments.Add(fileName, documentIds); _transientDocumentIds.UnionWith(documentIds); } foreach (var documentInfo in documentInfos) { _workspace.AddDocument(documentInfo); } return(true); }
public async Task TestLooseFile_MovedToRegisteredWorkspace() { var source = @"class A { void M() { } }"; // Create the server and verify no misc files present. using var testLspServer = await CreateTestLspServerAsync(string.Empty); Assert.Null(GetMiscellaneousDocument(testLspServer)); // Open an empty loose file and make a request to verify it gets added to the misc workspace. var looseFileUri = new Uri(@"C:\SomeFile.cs"); var looseFileTextDocumentIdentifier = new LSP.TextDocumentIdentifier { Uri = looseFileUri }; await testLspServer.OpenDocumentAsync(looseFileUri, source).ConfigureAwait(false); // Verify that the file returned by the manager is in the lsp misc files workspace. await AssertFileInMiscWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); // Update the workspace to contain the loose file. var project = testLspServer.GetCurrentSolution().Projects.Single(); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(project.Id), looseFileUri.AbsolutePath, sourceCodeKind: SourceCodeKind.Regular, loader: new TestTextLoader(source), filePath: looseFileUri.AbsolutePath); testLspServer.TestWorkspace.OnDocumentAdded(documentInfo); await WaitForWorkspaceOperationsAsync(testLspServer.TestWorkspace); Assert.Contains(looseFileUri.AbsolutePath, testLspServer.GetCurrentSolution().Projects.Single().Documents.Select(d => d.FilePath)); // Verify that the manager returns the file that has been added to the main workspace. await AssertFileInMainWorkspaceAsync(testLspServer, looseFileUri).ConfigureAwait(false); }
IEnumerable <DocumentInfo> GenerateProjections(MonoDevelop.Projects.ProjectFile f, DocumentMap documentMap, MonoDevelop.Projects.Project p, ProjectData oldProjectData, HashSet <DocumentId> duplicates) { var mimeType = DesktopService.GetMimeTypeForUri(f.FilePath); var node = TypeSystemService.GetTypeSystemParserNode(mimeType, f.BuildAction); if (node == null || !node.Parser.CanGenerateProjection(mimeType, f.BuildAction, p.SupportedLanguages)) { yield break; } var options = new ParseOptions { FileName = f.FilePath, Project = p, Content = TextFileProvider.Instance.GetReadOnlyTextEditorData(f.FilePath), }; var generatedProjections = node.Parser.GenerateProjections(options); var list = new List <Projection> (); var entry = new ProjectionEntry { File = f, Projections = list, }; foreach (var projection in generatedProjections.Result) { list.Add(projection); if (duplicates != null && !duplicates.Add(documentMap.GetOrCreate(projection.Document.FileName, oldProjectData?.DocumentData))) { continue; } var plainName = projection.Document.FileName.FileName; var folders = GetFolders(p.Name, f); yield return(DocumentInfo.Create( documentMap.GetOrCreate(projection.Document.FileName, oldProjectData?.DocumentData), plainName, folders, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(new MonoDevelopSourceText(projection.Document), VersionStamp.Create(), projection.Document.FileName)), projection.Document.FileName, false )); } projections.AddProjectionEntry(entry); }
/// <summary> /// Creates a ProjectInfo to represent the fake project created for metadata as source documents. /// </summary> /// <param name="workspace">The containing workspace.</param> /// <param name="loadFileFromDisk">Whether the source file already exists on disk and should be included. If /// this is a false, a document is still created, but it's not backed by the file system and thus we won't /// try to load it.</param> public Tuple <ProjectInfo, DocumentId> GetProjectInfoAndDocumentId(Workspace workspace, bool loadFileFromDisk) { var projectId = ProjectId.CreateNewId(); // Just say it's always a DLL since we probably won't have a Main method var compilationOptions = workspace.Services.GetLanguageServices(LanguageName).CompilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var extension = LanguageName == LanguageNames.CSharp ? ".cs" : ".vb"; // We need to include the version information of the assembly so InternalsVisibleTo and stuff works var assemblyInfoDocumentId = DocumentId.CreateNewId(projectId); var assemblyInfoFileName = "AssemblyInfo" + extension; var assemblyInfoString = LanguageName == LanguageNames.CSharp ? string.Format(@"[assembly: System.Reflection.AssemblyVersion(""{0}"")]", AssemblyIdentity.Version) : string.Format(@"<Assembly: System.Reflection.AssemblyVersion(""{0}"")>", AssemblyIdentity.Version); var assemblyInfoSourceTextContainer = SourceText.From(assemblyInfoString, Encoding).Container; var assemblyInfoDocument = DocumentInfo.Create( assemblyInfoDocumentId, assemblyInfoFileName, loader: TextLoader.From(assemblyInfoSourceTextContainer, VersionStamp.Default)); var generatedDocumentId = DocumentId.CreateNewId(projectId); var generatedDocument = DocumentInfo.Create( generatedDocumentId, Path.GetFileName(TemporaryFilePath), filePath: TemporaryFilePath, loader: loadFileFromDisk ? new FileTextLoader(TemporaryFilePath, Encoding) : null); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Default, "MetadataAsSourceProject", AssemblyIdentity.Name, LanguageName, compilationOptions: compilationOptions, documents: new[] { assemblyInfoDocument, generatedDocument }, metadataReferences: References); return(Tuple.Create(projectInfo, generatedDocumentId)); }
public void TestAddProject_TryApplyChanges() { using var ws = new AdhocWorkspace(); var pid = ProjectId.CreateNewId(); var docInfo = DocumentInfo.Create( DocumentId.CreateNewId(pid), "MyDoc.cs", loader: TextLoader.From( TextAndVersion.Create(SourceText.From(""), VersionStamp.Create()) ) ); var projInfo = ProjectInfo.Create( pid, VersionStamp.Create(), "NewProject", "NewProject.dll", LanguageNames.CSharp, documents: new[] { docInfo } ); var newSolution = ws.CurrentSolution.AddProject(projInfo); Assert.Equal(0, ws.CurrentSolution.Projects.Count()); var result = ws.TryApplyChanges(newSolution); Assert.True(result); Assert.Equal(1, ws.CurrentSolution.Projects.Count()); var proj = ws.CurrentSolution.Projects.First(); Assert.Equal("NewProject", proj.Name); Assert.Equal("NewProject.dll", proj.AssemblyName); Assert.Equal(LanguageNames.CSharp, proj.Language); Assert.Equal(1, proj.Documents.Count()); var doc = proj.Documents.First(); Assert.Equal("MyDoc.cs", doc.Name); }
public async Task CheckCrossLanguageReferencesSameAfterSolutionChangedTest() { using (var ws = new AdhocWorkspace()) { var referenceInfo = ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "ReferenceProject", "ReferenceProject", LanguageNames.VisualBasic, metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location))); var referenceProject = ws.AddProject(referenceInfo); var projectInfo = ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.CSharp, projectReferences: ImmutableArray.Create <ProjectReference>(new ProjectReference(referenceInfo.Id)), metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location))); var project = ws.AddProject(projectInfo); // get original references var compilation1 = await project.GetCompilationAsync(); var references1 = compilation1.ExternalReferences; // just some arbitary action to create new snpahost that doesnt affect references var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs"); var document = ws.AddDocument(info); // get new compilation var compilation2 = await document.Project.GetCompilationAsync(); var references2 = compilation2.ExternalReferences; Assert.Equal(references1, references2); } }
public async Task SemanticChange_Propagation_Direct() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, true); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(3, worker.DocumentIds.Count); } }
RoslynCodeDocument CreateDocument(ProjectId projectId, CompilerDocumentInfo doc) { var options = new CodeEditorOptions(); options.ContentTypeString = ContentType; options.Roles.Add(PredefinedDsTextViewRoles.RoslynCodeEditor); options.Roles.Add(TextViewRole); var codeEditor = codeEditorProvider.Create(options); codeEditor.TextView.Options.SetOptionValue(DefaultWpfViewOptions.AppearanceCategory, AppearanceCategory); codeEditor.TextView.Options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, true); var textBuffer = codeEditor.TextView.TextBuffer; textBuffer.Replace(new Span(0, textBuffer.CurrentSnapshot.Length), doc.Code); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), doc.Name, null, SourceCodeKind.Regular, TextLoader.From(codeEditor.TextBuffer.AsTextContainer(), VersionStamp.Create())); return(new RoslynCodeDocument(codeEditor, documentInfo)); }
private static OmniSharpWorkspace CreateSimpleWorkspace(string fileName, string contents) { var workspace = new OmniSharpWorkspace( new HostServicesAggregator( Enumerable.Empty <IHostServicesProvider>(), new LoggerFactory()), new LoggerFactory()); var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "ProjectNameVal", "AssemblyNameVal", LanguageNames.CSharp); var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), fileName, null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(contents), VersionStamp.Create())), fileName); workspace.AddProject(projectInfo); workspace.AddDocument(documentInfo); return(workspace); }
public void Create_Folders() { var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId()); var info1 = DocumentInfo.Create(documentId, "doc", folders: new[] { "folder" }); Assert.Equal("folder", ((ImmutableArray <string>)info1.Folders).Single()); var info2 = DocumentInfo.Create(documentId, "doc"); Assert.True(((ImmutableArray <string>)info2.Folders).IsEmpty); var info3 = DocumentInfo.Create(documentId, "doc", folders: new string[0]); Assert.True(((ImmutableArray <string>)info3.Folders).IsEmpty); var info4 = DocumentInfo.Create(documentId, "doc", folders: ImmutableArray <string> .Empty); Assert.True(((ImmutableArray <string>)info4.Folders).IsEmpty); }
public static OmnisharpWorkspace CreateSimpleWorkspace(string source, string fileName = "dummy.cs") { var workspace = new OmnisharpWorkspace(); var projectId = ProjectId.CreateNewId(); var versionStamp = VersionStamp.Create(); var mscorlib = MetadataReference.CreateFromAssembly(AssemblyFromType(typeof(object))); var systemCore = MetadataReference.CreateFromAssembly(AssemblyFromType(typeof(Enumerable))); var references = new [] { mscorlib, systemCore }; var projectInfo = ProjectInfo.Create(projectId, versionStamp, "ProjectName", "AssemblyName", LanguageNames.CSharp, "project.json", metadataReferences: references); var document = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), fileName, null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(source), versionStamp)), fileName); workspace.AddProject(projectInfo); workspace.AddDocument(document); return(workspace); }
IEnumerable <DocumentInfo> GenerateProjections(MonoDevelop.Projects.ProjectFile f, ProjectData projectData, MonoDevelop.Projects.Project p, HashSet <DocumentId> duplicates = null) { var mimeType = DesktopService.GetMimeTypeForUri(f.FilePath); var node = TypeSystemService.GetTypeSystemParserNode(mimeType, f.BuildAction); if (node == null || !node.Parser.CanGenerateProjection(mimeType, f.BuildAction, p.SupportedLanguages)) { yield break; } var options = new ParseOptions { FileName = f.FilePath, Project = p, Content = StringTextSource.ReadFrom(f.FilePath), }; var projections = node.Parser.GenerateProjections(options); var entry = new ProjectionEntry(); entry.File = f; var list = new List <Projection> (); entry.Projections = list; foreach (var projection in projections.Result) { list.Add(projection); if (duplicates != null && !duplicates.Add(projectData.GetOrCreateDocumentId(projection.Document.FileName))) { continue; } var plainName = projection.Document.FileName.FileName; yield return(DocumentInfo.Create( projectData.GetOrCreateDocumentId(projection.Document.FileName), plainName, new [] { p.Name }.Concat(f.ProjectVirtualPath.ParentDirectory.ToString().Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(new MonoDevelopSourceText(projection.Document), VersionStamp.Create(), projection.Document.FileName)), projection.Document.FileName, false )); } projectionList.Add(entry); }
public void Create_AdditionalDocuments() { var version = VersionStamp.Default; var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(ProjectId.CreateNewId()), "doc"); var info1 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new[] { documentInfo }); Assert.Same(documentInfo, ((ImmutableArray <DocumentInfo>)info1.AdditionalDocuments).Single()); var info2 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#"); Assert.True(((ImmutableArray <DocumentInfo>)info2.AdditionalDocuments).IsEmpty); var info3 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: new DocumentInfo[0]); Assert.True(((ImmutableArray <DocumentInfo>)info3.AdditionalDocuments).IsEmpty); var info4 = ProjectInfo.Create(ProjectId.CreateNewId(), version, "proj", "assembly", "C#", additionalDocuments: ImmutableArray <DocumentInfo> .Empty); Assert.True(((ImmutableArray <DocumentInfo>)info4.AdditionalDocuments).IsEmpty); }
public void SolutionAdded_Simple() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } }
public void Project_Add() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List <DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } }
public async Task PersistentService_IdentifierSet() { var solution = CreateOrOpenSolution(); var newId = DocumentId.CreateNewId(solution.ProjectIds[0]); string documentFile = Path.Combine(Path.GetDirectoryName(solution.FilePath), "IdentifierSet.cs"); File.WriteAllText(documentFile, @" class A { public int Test(int i, A a) { return a; } }"); var newSolution = solution.AddDocument(DocumentInfo.Create(newId, "IdentifierSet", loader: new FileTextLoader(documentFile, Encoding.UTF8), filePath: documentFile)); using (var storage = GetStorage(newSolution)) { var syntaxTreeStorage = storage as ISyntaxTreeInfoPersistentStorage; Assert.NotNull(syntaxTreeStorage); var document = newSolution.GetDocument(newId); var version = await document.GetSyntaxVersionAsync(); var root = await document.GetSyntaxRootAsync(); Assert.True(syntaxTreeStorage.WriteIdentifierLocations(document, version, root, CancellationToken.None)); Assert.Equal(version, syntaxTreeStorage.GetIdentifierSetVersion(document)); List <int> positions = new List <int>(); Assert.True(syntaxTreeStorage.ReadIdentifierPositions(document, version, "Test", positions, CancellationToken.None)); Assert.Equal(1, positions.Count); Assert.Equal(29, positions[0]); } }
private void AddDocumentCore(DocumentId documentId, IEnumerable <string> folders, string name, SourceText text = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, bool isAdditionalDocument = false) { System.Diagnostics.Debug.Assert(this.applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(documentId.ProjectId); IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(project.FilePath, ReportMode.Ignore, out loader)) { var extension = isAdditionalDocument ? Path.GetExtension(name) : this.applyChangesProjectFile.GetDocumentExtension(sourceCodeKind); var fileName = Path.ChangeExtension(name, extension); var relativePath = folders != null?Path.Combine(Path.Combine(folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath)); var encoding = (text != null) ? text.Encoding : Encoding.UTF8; var documentInfo = DocumentInfo.Create(documentId, fileName, folders, sourceCodeKind, new FileTextLoader(fullPath, encoding), fullPath, encoding, isGenerated: false); // add document to project file this.applyChangesProjectFile.AddDocument(relativePath); // add to solution if (isAdditionalDocument) { this.OnAdditionalDocumentAdded(documentInfo); } else { this.OnDocumentAdded(documentInfo); } // save text to disk if (text != null) { this.SaveDocumentText(documentId, fullPath, text); } } }
public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray <string> folders) { if (string.IsNullOrEmpty(fullPath)) { throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } var documentId = DocumentId.CreateNewId(_project.Id, fullPath); var textLoader = new FileTextLoader(fullPath, defaultEncoding: null); var documentInfo = DocumentInfo.Create( documentId, FileNameUtilities.GetFileName(fullPath), folders: folders.IsDefault ? null : (IEnumerable <string>)folders, sourceCodeKind: sourceCodeKind, loader: textLoader, filePath: fullPath); lock (_project._gate) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath)); } _documentPathsToDocumentIds.Add(fullPath, documentId); _project._fileWatchingTokens.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath)); if (_project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); _project._workspace.CheckForOpenDocuments(ImmutableArray.Create(fullPath)); } } return(documentId); }
static DocumentInfo CreateDocumentInfo( SolutionData data, string projectName, ProjectData id, FilePath filePath, FilePath projectVirtualPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) { var folders = GetFolders(projectName, projectVirtualPath); return(DocumentInfo.Create( id.DocumentData.GetOrCreate(filePath), Path.GetFileName(filePath), folders, sourceCodeKind, CreateTextLoader(filePath), filePath, isGenerated: false )); TextLoader CreateTextLoader(string fileName) => data.Files.GetOrAdd(fileName, a => new MonoDevelopTextLoader(a)); }
private static ImmutableArray <DocumentInfo> CreateDocumentInfos(IReadOnlyList <DocumentFileInfo> documentFileInfos, ProjectId projectId, Encoding encoding) { var results = ImmutableArray.CreateBuilder <DocumentInfo>(); foreach (var info in documentFileInfos) { GetDocumentNameAndFolders(info.LogicalPath, out var name, out var folders); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: info.FilePath), name, folders, info.SourceCodeKind, new FileTextLoader(info.FilePath, encoding), info.FilePath, info.IsGenerated); results.Add(documentInfo); } return(results.ToImmutable()); }
public async Task UpdateBuffer_TransientDocumentsDisappearWhenProjectAddsThem() { var testFile = new TestFile("test.cs", "class C {}"); using (var host = CreateOmniSharpHost(testFile)) { await host.Workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = "transient.cs", Buffer = "interface I {}" }); var docIds = host.Workspace.CurrentSolution.GetDocumentIdsWithFilePath("transient.cs"); Assert.Equal(2, docIds.Length); // simulate a project system adding the file for real var project1 = host.Workspace.CurrentSolution.Projects.First(); var document = DocumentInfo.Create(DocumentId.CreateNewId(project1.Id), "transient.cs", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("enum E{}"), VersionStamp.Create())), filePath: "transient.cs"); var newSolution = host.Workspace.CurrentSolution.AddDocument(document); host.Workspace.TryApplyChanges(newSolution); docIds = host.Workspace.CurrentSolution.GetDocumentIdsWithFilePath("transient.cs"); Assert.Equal(2, docIds.Length); await host.Workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = "transient.cs", Buffer = "enum E {}" }); var sourceText = await host.Workspace.CurrentSolution.GetDocument(docIds.First()).GetTextAsync(); Assert.Equal("enum E {}", sourceText.ToString()); sourceText = await host.Workspace.CurrentSolution.GetDocument(docIds.Last()).GetTextAsync(); Assert.Equal("enum E {}", sourceText.ToString()); } }
private async Task <DocumentInfo> CreateDocumentInfoAsync(Checksum documentChecksum) { var documentSnapshot = await _assetService.GetAssetAsync <DocumentStateChecksums>(documentChecksum, _cancellationToken).ConfigureAwait(false); var documentInfo = await _assetService.GetAssetAsync <DocumentInfo.DocumentAttributes>(documentSnapshot.Info, _cancellationToken).ConfigureAwait(false); var textLoader = TextLoader.From( TextAndVersion.Create( await _assetService.GetAssetAsync <SourceText>(documentSnapshot.Text, _cancellationToken).ConfigureAwait(false), VersionStamp.Create(), documentInfo.FilePath)); // TODO: do we need version? return(DocumentInfo.Create( documentInfo.Id, documentInfo.Name, documentInfo.Folders, documentInfo.SourceCodeKind, textLoader, documentInfo.FilePath, documentInfo.IsGenerated)); }
public async Task SolutionAdded_Simple() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } }
public async Task Project_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List <DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } }
private async Task CheckUpdatedDocumentTextIsObservablyConstantAsync(AdhocWorkspace ws) { var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); ws.AddProject(projInfo); var doc = ws.CurrentSolution.GetDocument(docInfo.Id); // change document var root = await doc.GetSyntaxRootAsync(); var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id); Assert.NotSame(doc, newDoc); var newDocText = await newDoc.GetTextAsync(); var sameText = await newDoc.GetTextAsync(); Assert.Same(newDocText, sameText); var newDocTree = await newDoc.GetSyntaxTreeAsync(); var treeText = newDocTree.GetText(); Assert.Same(newDocText, treeText); }