コード例 #1
0
        public void ResolveReference()
        {
            using var temp = new TempRoot();

            var gitDir = temp.CreateDirectory();

            var commonDir    = temp.CreateDirectory();
            var refsHeadsDir = commonDir.CreateDirectory("refs").CreateDirectory("heads");

            refsHeadsDir.CreateFile("master").WriteAllText("0000000000000000000000000000000000000000");
            refsHeadsDir.CreateFile("br1").WriteAllText("ref: refs/heads/br2");
            refsHeadsDir.CreateFile("br2").WriteAllText("ref: refs/heads/master");

            var resolver = new GitReferenceResolver(gitDir.Path, commonDir.Path);

            Assert.Equal("0123456789ABCDEFabcdef000000000000000000", resolver.ResolveReference("0123456789ABCDEFabcdef000000000000000000"));

            Assert.Equal("0000000000000000000000000000000000000000", resolver.ResolveReference("ref: refs/heads/master"));
            Assert.Equal("0000000000000000000000000000000000000000", resolver.ResolveReference("ref: refs/heads/br1"));
            Assert.Equal("0000000000000000000000000000000000000000", resolver.ResolveReference("ref: refs/heads/br2"));

            // branch without commits (emtpy repository) will have not file in refs/heads:
            Assert.Null(resolver.ResolveReference("ref: refs/heads/none"));

            Assert.Null(resolver.ResolveReference("ref: refs/heads/rec1   "));
            Assert.Null(resolver.ResolveReference("ref: refs/heads/none" + string.Join("/", Path.GetInvalidPathChars())));
        }
コード例 #2
0
        public void DoesNotRewriteContentIfFileContentIsSame()
        {
            using var temp = new TempRoot();
            var tempFile = temp.CreateFile();

            var engine = new MockEngine();
            var task   = new GenerateSourceLinkFile()
            {
                BuildEngine = engine,
                SourceRoots = new[]
                {
                    new MockItem(@"/_""_/", KVP("SourceLinkUrl", "https://raw.githubusercontent.com/repo/*"), KVP("SourceControl", "git")),
                },
                OutputFile = tempFile.Path
            };

            var result = task.Execute();

            var beforeWriteTime = File.GetLastWriteTime(tempFile.Path);

            result = task.Execute();

            var afterWriteTime = File.GetLastWriteTime(tempFile.Path);

            Assert.Equal(beforeWriteTime, afterWriteTime);
        }
コード例 #3
0
        public async Task ShadowCopied_Analyzer_Serailization_Desktop_Test()
        {
            using (var tempRoot = new TempRoot())
            {
                var hostServices = MefHostServices.Create(
                    MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

                var workspace  = new AdhocWorkspace(hostServices);
                var serializer = workspace.Services.GetService <ISerializerService>();

                // use 2 different files as shadow copied content
                var original = typeof(AdhocWorkspace).Assembly.Location;

                var shadow = tempRoot.CreateFile("shadow", "dll");
                shadow.CopyContentFrom(typeof(object).Assembly.Location);

                var reference = new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary <string, string> .Empty.Add(original, shadow.Path)));

                // make sure this doesn't throw
                var assetFromFile = SolutionAsset.Create(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);

                // this will verify serialized analyzer reference return same checksum as the original one
                var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);
            }
        }
コード例 #4
0
        public void LocateRepository_Submodule()
        {
            using var temp = new TempRoot();

            var mainWorkingDir = temp.CreateDirectory();
            var mainGitDir     = mainWorkingDir.CreateDirectory(".git");

            mainGitDir.CreateFile("HEAD");

            var submoduleGitDir = mainGitDir.CreateDirectory("modules").CreateDirectory("sub");

            var submoduleWorkDir = temp.CreateDirectory();

            submoduleWorkDir.CreateFile(".git").WriteAllText("gitdir: " + submoduleGitDir.Path);

            submoduleGitDir.CreateFile("HEAD");
            submoduleGitDir.CreateDirectory("objects");
            submoduleGitDir.CreateDirectory("refs");

            // start under submodule working directory:
            Assert.True(GitRepository.TryFindRepository(submoduleWorkDir.Path, out var location));

            Assert.Equal(submoduleGitDir.Path, location.GitDirectory);
            Assert.Equal(submoduleGitDir.Path, location.CommonDirectory);
            Assert.Equal(submoduleWorkDir.Path, location.WorkingDirectory);

            // start under submodule git directory:
            Assert.True(GitRepository.TryFindRepository(submoduleGitDir.Path, out location));

            Assert.Equal(submoduleGitDir.Path, location.GitDirectory);
            Assert.Equal(submoduleGitDir.Path, location.CommonDirectory);
            Assert.Null(location.WorkingDirectory);
        }
コード例 #5
0
        public void WorkspaceAnalyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var tempRoot  = new TempRoot();
            using var workspace = new AdhocWorkspace(hostServices);
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var assetBuilder = new CustomAssetBuilder(workspace);
            var asset        = assetBuilder.Build(reference, CancellationToken.None);

            // verify checksum from custom asset builder uses different checksum than regular one
            var service          = workspace.Services.GetService <IReferenceSerializationService>();
            var expectedChecksum = Checksum.Create(
                WellKnownSynchronizationKind.AnalyzerReference,
                service.CreateChecksum(reference, usePathFromAssembly: false, CancellationToken.None));

            Assert.Equal(expectedChecksum, asset.Checksum);

            // verify usePathFromAssembly return different checksum for same reference
            var fromFilePath = service.CreateChecksum(reference, usePathFromAssembly: false, CancellationToken.None);
            var fromAssembly = service.CreateChecksum(reference, usePathFromAssembly: true, CancellationToken.None);

            Assert.NotEqual(fromFilePath, fromAssembly);
        }
コード例 #6
0
        public async Task OnlyStartOneServer()
        {
            ServerData?serverData = null;

            try
            {
                var pipeName         = ServerUtil.GetPipeName();
                var workingDirectory = TempRoot.CreateDirectory().Path;
                for (var i = 0; i < 5; i++)
                {
                    var response = await BuildServerConnection.RunServerBuildRequestAsync(
                        ProtocolUtil.CreateEmptyCSharp(workingDirectory),
                        pipeName,
                        timeoutOverride : Timeout.Infinite,
                        tryCreateServerFunc : (pipeName, logger) =>
                    {
                        Assert.Null(serverData);
                        serverData = ServerData.Create(logger, pipeName);
                        return(true);
                    },
                        Logger,
                        cancellationToken : default);

                    Assert.True(response is CompletedBuildResponse);
                }
            }
            finally
            {
                serverData?.Dispose();
            }
        }
コード例 #7
0
        public async Task UseExistingServer()
        {
            using var serverData = await ServerUtil.CreateServer(Logger);

            var ran = false;
            var workingDirectory = TempRoot.CreateDirectory().Path;

            for (var i = 0; i < 5; i++)
            {
                var response = await BuildServerConnection.RunServerBuildRequestAsync(
                    ProtocolUtil.CreateEmptyCSharp(workingDirectory),
                    serverData.PipeName,
                    timeoutOverride : Timeout.Infinite,
                    tryCreateServerFunc : (_, _) =>
                {
                    ran = true;
                    return(false);
                },
                    Logger,
                    cancellationToken : default);

                Assert.True(response is CompletedBuildResponse);
            }

            Assert.False(ran);
        }
コード例 #8
0
        /// <summary>
        /// Compiles some source code and returns the bytes that were contained in the compiled DLL file.
        ///
        /// Each time that this function is called, it will be compiled in a different directory.
        ///
        /// The default flags are "/shared /deterministic+ /nologo /t:library".
        /// </summary>
        /// <param name="source"> The source code for the program that will be compiled </param>
        /// <param name="additionalFlags"> A string containing any additional compiler flags </param>
        /// <returns> An array of bytes that were read from the compiled DLL</returns>
        private byte[] CompileAndGetBytes(string source, string additionalFlags, out string finalFlags)
        {
            var tempRoot = new TempRoot();

            // Setup
            var tempDir = tempRoot.CreateDirectory();
            var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path;
            var outFile = srcFile.Replace("test.cs", "test.dll");

            finalFlags = $"{ _flags } { additionalFlags } /pathmap:{tempDir.Path}=/";
            try
            {
                var errorsFile = srcFile + ".errors";

                // Compile
                var result = ProcessUtilities.Run("cmd", $"/C {CompilerServerUnitTests.s_csharpCompilerExecutableSrc} { finalFlags } { srcFile } /out:{ outFile } > { errorsFile }");
                if (result.ExitCode != 0)
                {
                    var errors = File.ReadAllText(errorsFile);
                    AssertEx.Fail($"Deterministic compile failed \n stderr: { result.Errors } \n stdout:  { errors }");
                }
                var bytes = File.ReadAllBytes(outFile);
                AssertEx.NotNull(bytes);

                return(bytes);
            }
            finally
            {
                File.Delete(srcFile);
                File.Delete(outFile);
            }
        }
コード例 #9
0
        public async Task FailedServer()
        {
            var pipeName         = ServerUtil.GetPipeName();
            var workingDirectory = TempRoot.CreateDirectory().Path;
            var count            = 0;

            for (var i = 0; i < 5; i++)
            {
                var response = await BuildServerConnection.RunServerBuildRequestAsync(
                    ProtocolUtil.CreateEmptyCSharp(workingDirectory),
                    pipeName,
                    timeoutOverride : Timeout.Infinite,
                    tryCreateServerFunc : (_, _) =>
                {
                    count++;
                    return(false);
                },
                    Logger,
                    cancellationToken : default);

                Assert.True(response is RejectedBuildResponse);
            }

            Assert.Equal(5, count);
        }
コード例 #10
0
        public void OpenRepository_Worktree_GitdirFileMissing()
        {
            using var temp = new TempRoot();

            var mainWorkingDir = temp.CreateDirectory();
            var mainGitDir     = mainWorkingDir.CreateDirectory(".git");

            mainGitDir.CreateFile("HEAD");

            var worktreesDir    = mainGitDir.CreateDirectory("worktrees");
            var worktreeGitDir  = worktreesDir.CreateDirectory("myworktree");
            var worktreeDir     = temp.CreateDirectory();
            var worktreeGitFile = worktreeDir.CreateFile(".git").WriteAllText("gitdir: " + worktreeGitDir + " \r\n\t\v");

            worktreeGitDir.CreateFile("HEAD");
            worktreeGitDir.CreateFile("commondir").WriteAllText("../..\n");
            // gitdir file that links back to the worktree working directory is missing from worktreeGitDir

            Assert.True(GitRepository.TryFindRepository(worktreeDir.Path, out var location));
            Assert.Equal(worktreeGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Equal(worktreeDir.Path, location.WorkingDirectory);

            var repository = GitRepository.OpenRepository(location, GitEnvironment.Empty);

            Assert.Equal(repository.GitDirectory, location.GitDirectory);
            Assert.Equal(repository.CommonDirectory, location.CommonDirectory);
            Assert.Equal(repository.WorkingDirectory, location.WorkingDirectory);
        }
コード例 #11
0
        public void OpenRepository()
        {
            using var temp = new TempRoot();

            var homeDir = temp.CreateDirectory();

            var workingDir = temp.CreateDirectory();
            var gitDir     = workingDir.CreateDirectory(".git");

            gitDir.CreateFile("HEAD").WriteAllText("ref: refs/heads/master");
            gitDir.CreateDirectory("refs").CreateDirectory("heads").CreateFile("master").WriteAllText("0000000000000000000000000000000000000000");
            gitDir.CreateDirectory("objects");

            gitDir.CreateFile("config").WriteAllText("[x]a = 1");

            var src = workingDir.CreateDirectory("src");

            var repository = GitRepository.OpenRepository(src.Path, new GitEnvironment(homeDir.Path)) !;

            Assert.Equal(gitDir.Path, repository.CommonDirectory);
            Assert.Equal(gitDir.Path, repository.GitDirectory);
            Assert.Equal("1", repository.Config.GetVariableValue("x", "a"));
            Assert.Empty(repository.GetSubmodules());
            Assert.Equal("0000000000000000000000000000000000000000", repository.GetHeadCommitSha());
        }
コード例 #12
0
        public void OpenRepository_Worktree_GitdirFileDifferentPath()
        {
            using var temp = new TempRoot();

            var mainWorkingDir = temp.CreateDirectory();
            var mainGitDir     = mainWorkingDir.CreateDirectory(".git");

            mainGitDir.CreateFile("HEAD");

            var worktreesDir    = mainGitDir.CreateDirectory("worktrees");
            var worktreeGitDir  = worktreesDir.CreateDirectory("myworktree");
            var worktreeDir     = temp.CreateDirectory();
            var worktreeGitFile = worktreeDir.CreateFile(".git").WriteAllText("gitdir: " + worktreeGitDir + " \r\n\t\v");

            var worktreeDir2     = temp.CreateDirectory();
            var worktreeGitFile2 = worktreeDir2.CreateFile(".git").WriteAllText("gitdir: " + worktreeGitDir + " \r\n\t\v");

            worktreeGitDir.CreateFile("HEAD");
            worktreeGitDir.CreateFile("commondir").WriteAllText("../..\n");
            worktreeGitDir.CreateFile("gitdir").WriteAllText(worktreeGitFile2.Path + " \r\n\t\v");

            Assert.True(GitRepository.TryFindRepository(worktreeDir.Path, out var location));
            Assert.Equal(worktreeGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Equal(worktreeDir.Path, location.WorkingDirectory);

            var repository = GitRepository.OpenRepository(location, GitEnvironment.Empty);

            Assert.Equal(repository.GitDirectory, location.GitDirectory);
            Assert.Equal(repository.CommonDirectory, location.CommonDirectory);

            // actual working dir is not affected:
            Assert.Equal(worktreeDir.Path, location.WorkingDirectory);
        }
コード例 #13
0
        public async Task SnapshotWithIdenticalAnalyzerFiles()
        {
            using var workspace = CreateWorkspace();
            var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            using var temp = new TempRoot();
            var dir = temp.CreateDirectory();

            // create two analyzer assembly files whose content is identical but path is different:
            var file1 = dir.CreateFile("analyzer1.dll").WriteAllBytes(TestResources.AnalyzerTests.FaultyAnalyzer);
            var file2 = dir.CreateFile("analyzer2.dll").WriteAllBytes(TestResources.AnalyzerTests.FaultyAnalyzer);

            var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
            var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);

            project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 });

            var validator = new SerializationValidator(workspace.Services);

            using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);

            var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);

            AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath));
        }
コード例 #14
0
        public async Task SnapshotWithIdenticalAnalyzerFiles()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var project = new AdhocWorkspace(hostServices).CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            using var temp = new TempRoot();
            var dir = temp.CreateDirectory();

            // create two analyzer assembly files whose content is identical but path is different:
            var file1 = dir.CreateFile("analyzer1.dll").WriteAllBytes(TestResources.AnalyzerTests.FaultyAnalyzer);
            var file2 = dir.CreateFile("analyzer2.dll").WriteAllBytes(TestResources.AnalyzerTests.FaultyAnalyzer);

            var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
            var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);

            project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 });

            var snapshotService = (IRemotableDataService) new RemotableDataServiceFactory().CreateService(project.Solution.Workspace.Services);

            using var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);

            var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false);

            AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath));
        }
コード例 #15
0
ファイル: GitIgnoreTests.cs プロジェクト: dotnet/sourcelink
        public void IsIgnored_IgnoreCase()
        {
            using var temp = new TempRoot();

            var rootDir    = temp.CreateDirectory();
            var workingDir = rootDir.CreateDirectory("Repo");

            // root
            // A (.gitignore)
            // diR
            var dirA = workingDir.CreateDirectory("A");

            dirA.CreateDirectory("diR");

            dirA.CreateFile(".gitignore").WriteAllText(@"
*.txt
!a.TXT
dir/
");

            var ignore  = new GitIgnore(root: null, PathUtils.ToPosixDirectoryPath(workingDir.Path), ignoreCase: true);
            var matcher = ignore.CreateMatcher();

            // outside of the working directory:
            Assert.Null(matcher.IsPathIgnored(rootDir.Path.ToUpperInvariant()));

            // special case:
            Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, ".GIT")));

            // matches "*.txt"
            Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "b.TXT")));

            // matches "!a.TXT"
            Assert.False(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "a.txt")));

            // matches directory name "dir/"
            Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "DIr", "a.txt")));

            // matches "dir/" (treated as a directory path)
            Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "DiR") + Path.DirectorySeparatorChar));

            if (Path.DirectorySeparatorChar == '\\')
            {
                // matches "dir/" (existing directory path, the directory DIR only exists on case-insensitive FS)
                Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "DIR")));
            }

            Assert.True(matcher.IsPathIgnored(Path.Combine(workingDir.Path, "A", "diR")));

            AssertEx.SetEqual(new[]
            {
                "/Repo/A/DIr: True",
                "/Repo/A: False",
                "/Repo: False",
            }, matcher.DirectoryIgnoreStateCache.Select(kvp => $"{kvp.Key.Substring(rootDir.Path.Length)}: {kvp.Value}"));
        }
コード例 #16
0
 public void RejectEmptyTempPath()
 {
     using (var temp = new TempRoot())
     {
         var host     = new TestableCompilerServerHost();
         var request  = new RunRequest(LanguageNames.CSharp, currentDirectory: temp.CreateDirectory().Path, tempDirectory: null, libDirectory: null, arguments: Array.Empty <string>());
         var response = host.RunCompilation(request, CancellationToken.None);
         Assert.Equal(ResponseType.Rejected, response.Type);
     }
 }
コード例 #17
0
        public async Task RejectEmptyTempPath()
        {
            using var temp       = new TempRoot();
            using var serverData = await ServerUtil.CreateServer();

            var request  = BuildRequest.Create(RequestLanguage.CSharpCompile, workingDirectory: temp.CreateDirectory().Path, tempDirectory: null, BuildProtocolConstants.GetCommitHash(), libDirectory: null, args: Array.Empty <string>());
            var response = await ServerUtil.Send(serverData.PipeName, request);

            Assert.Equal(ResponseType.Rejected, response.Type);
        }
コード例 #18
0
        private static AnalyzerFileReference CreateShadowCopiedAnalyzerReference(TempRoot tempRoot)
        {
            // use 2 different files as shadow copied content
            var original = typeof(AdhocWorkspace).Assembly.Location;

            var shadow = tempRoot.CreateFile("shadow", "dll");

            shadow.CopyContentFrom(typeof(object).Assembly.Location);

            return(new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary <string, string> .Empty.Add(original, shadow.Path))));
        }
コード例 #19
0
        public async Task ShadowCopied_Analyzer_Serialization_Desktop_Test()
        {
            using var tempRoot  = new TempRoot();
            using var workspace = new AdhocWorkspace();
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var serializer = workspace.Services.GetService <ISerializerService>();

            // make sure this doesn't throw
            var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);

            // this will verify serialized analyzer reference return same checksum as the original one
            var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);
        }
コード例 #20
0
        public void ShadowCopied_Analyzer_Serialization_Desktop_Test()
        {
            using var tempRoot  = new TempRoot();
            using var workspace = CreateWorkspace();
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var serializer = workspace.Services.GetService <ISerializerService>();

            // make sure this doesn't throw
            var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);

            // this will verify serialized analyzer reference return same checksum as the original one
            _ = CloneAsset(serializer, assetFromFile);
        }
コード例 #21
0
        public void TryFindRepository_Worktree_Realistic()
        {
            using var temp = new TempRoot();

            var mainWorkingDir    = temp.CreateDirectory();
            var mainWorkingSubDir = mainWorkingDir.CreateDirectory("A");
            var mainGitDir        = mainWorkingDir.CreateDirectory(".git");

            mainGitDir.CreateFile("HEAD");

            var worktreesDir      = mainGitDir.CreateDirectory("worktrees");
            var worktreeGitDir    = worktreesDir.CreateDirectory("myworktree");
            var worktreeGitSubDir = worktreeGitDir.CreateDirectory("B");
            var worktreeDir       = temp.CreateDirectory();
            var worktreeSubDir    = worktreeDir.CreateDirectory("C");
            var worktreeGitFile   = worktreeDir.CreateFile(".git").WriteAllText("gitdir: " + worktreeGitDir + " \r\n\t\v");

            worktreeGitDir.CreateFile("HEAD");
            worktreeGitDir.CreateFile("commondir").WriteAllText("../..\n");
            worktreeGitDir.CreateFile("gitdir").WriteAllText(worktreeGitFile.Path + " \r\n\t\v");

            // start under main repository directory:
            Assert.True(GitRepository.TryFindRepository(mainWorkingSubDir.Path, out var location));

            Assert.Equal(mainGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Equal(mainWorkingDir.Path, location.WorkingDirectory);

            // start at main git directory (git config works from this dir, but git status requires work dir):
            Assert.True(GitRepository.TryFindRepository(mainGitDir.Path, out location));

            Assert.Equal(mainGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Null(location.WorkingDirectory);

            // start under worktree directory:
            Assert.True(GitRepository.TryFindRepository(worktreeSubDir.Path, out location));

            Assert.Equal(worktreeGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Equal(worktreeDir.Path, location.WorkingDirectory);

            // start under worktree git directory (git config works from this dir, but git status requires work dir):
            Assert.True(GitRepository.TryFindRepository(worktreeGitSubDir.Path, out location));

            Assert.Equal(worktreeGitDir.Path, location.GitDirectory);
            Assert.Equal(mainGitDir.Path, location.CommonDirectory);
            Assert.Null(location.WorkingDirectory);
        }
コード例 #22
0
        public static void TestReferenceResolutionWithMissingTargets(bool isProjectJsonBased, string errorResourceName)
        {
            using (var tempRoot = new TempRoot())
                using (var disposableFile = new DisposableFile(tempRoot.CreateFile(extension: "assets.json").Path))
                {
                    var exception = Assert.Throws <ExceptionFromResource>(() =>
                                                                          NuGetTestHelpers.ResolvePackagesWithJsonFileContents(
                                                                              Encoding.UTF8.GetString(Json.Json.WithoutTargets_assets, 0, Json.Json.WithoutTargets_assets.Length),
                                                                              targetMoniker: "MissingFrameworkMoniker,Version=v42.0",
                                                                              runtimeIdentifier: "",
                                                                              allowFallbackOnTargetSelection: true,
                                                                              isLockFileProjectJsonBased: isProjectJsonBased));

                    Assert.Equal(errorResourceName, exception.ResourceName);
                }
        }
コード例 #23
0
        public static void TestReferenceResolutionWithMissingTargetFrameworkAndFallbackInProjectCsproj()
        {
            using (var tempRoot = new TempRoot())
                using (var disposableFile = new DisposableFile(tempRoot.CreateFile(extension: "assets.json").Path))
                {
                    var result = NuGetTestHelpers.ResolvePackagesWithJsonFileContents(
                        Encoding.UTF8.GetString(Json.Json.WithTargets_assets, 0, Json.Json.WithTargets_assets.Length),
                        targetMoniker: "MissingFrameworkMoniker,Version=v42.0",
                        runtimeIdentifier: "",
                        allowFallbackOnTargetSelection: true,
                        isLockFileProjectJsonBased: false);

                    // We should still have references. Since we have no runtime ID, we should have no copy local items
                    AssertHelpers.AssertCountOf(1, result.References);
                    AssertHelpers.AssertCountOf(0, result.CopyLocalItems);
                }
        }
コード例 #24
0
        public void GetHeadCommitSha()
        {
            using var temp = new TempRoot();

            var commonDir    = temp.CreateDirectory();
            var refsHeadsDir = commonDir.CreateDirectory("refs").CreateDirectory("heads");

            refsHeadsDir.CreateFile("master").WriteAllText("0000000000000000000000000000000000000000 \t\v\r\n");

            var gitDir = temp.CreateDirectory();

            gitDir.CreateFile("HEAD").WriteAllText("ref: refs/heads/master \t\v\r\n");

            var repository = new GitRepository(GitEnvironment.Empty, GitConfig.Empty, gitDir.Path, commonDir.Path, workingDirectory: null);

            Assert.Equal("0000000000000000000000000000000000000000", repository.GetHeadCommitSha());
        }
コード例 #25
0
        public static void TestReferenceResolutionWithMissingTargetFrameworkAndNoFallbackInProjectCsproj()
        {
            using (var tempRoot = new TempRoot())
                using (var disposableFile = new DisposableFile(tempRoot.CreateFile(extension: "assets.json").Path))
                {
                    var exception = Assert.Throws <ExceptionFromResource>(() =>
                                                                          NuGetTestHelpers.ResolvePackagesWithJsonFileContents(
                                                                              Encoding.UTF8.GetString(Json.Json.WithoutTargets_assets, 0, Json.Json.WithoutTargets_assets.Length),
                                                                              targetMoniker: "Missing,Version=1.0",
                                                                              runtimeIdentifier: "missing-runtime-identifier",
                                                                              allowFallbackOnTargetSelection: false,
                                                                              isLockFileProjectJsonBased: false));

                    Assert.Equal(nameof(Strings.MissingFrameworkInProjectFile), exception.ResourceName);
                    Assert.Equal(new[] { "Missing,Version=1.0" }, exception.MessageArgs);
                }
        }
コード例 #26
0
        public static void TestReferenceResolutionWithAliases()
        {
            using (var tempRoot = new TempRoot())
                using (var disposableFile = new DisposableFile(tempRoot.CreateFile(extension: "assets.json").Path))
                {
                    var result = NuGetTestHelpers.ResolvePackagesWithJsonFileContents(
                        Encoding.UTF8.GetString(Json.Json.WithTargets_assets, 0, Json.Json.WithTargets_assets.Length),
                        targetMoniker: ".NETFramework,Version=v4.5",
                        runtimeIdentifier: "",
                        allowFallbackOnTargetSelection: true,
                        isLockFileProjectJsonBased: false);

                    // We should still have references. Since we have no runtime ID, we should have no copy local items
                    AssertHelpers.AssertCountOf(1, result.References);
                    Assert.Equal("Core", result.References.Single().GetMetadata("Aliases"));
                }
        }
コード例 #27
0
        public async Task ShadowCopied_Analyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var tempRoot  = new TempRoot();
            using var workspace = new AdhocWorkspace(hostServices);
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var serializer = workspace.Services.GetService <ISerializerService>();

            // make sure this doesn't throw
            var assetFromFile = SolutionAsset.Create(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);

            // this will verify serialized analyzer reference return same checksum as the original one
            var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);
        }
コード例 #28
0
        public void OrderingOfEditorConfigMaintained()
        {
            using var tempRoot = new TempRoot();
            var tempDirectory = tempRoot.CreateDirectory();

            // Write out an .editorconfig. We'll write out 100 random GUIDs
            var expectedKeysInOrder = new List <string>();

            using (var writer = new StreamWriter(tempDirectory.CreateFile(".editorconfig").Path))
            {
                writer.WriteLine("root = true");
                writer.WriteLine("[*.cs]");

                for (int i = 0; i < 100; i++)
                {
                    var key = Guid.NewGuid().ToString();
                    expectedKeysInOrder.Add(key);
                    writer.WriteLine($"{key} = value");
                }
            }

            // Create a workspace with a file in that path
            var codingConventionsCatalog = ExportProviderCache.GetOrCreateAssemblyCatalog(typeof(ICodingConventionsManager).Assembly).WithPart(typeof(MockFileWatcher));
            var exportProvider           = ExportProviderCache.GetOrCreateExportProviderFactory(TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(codingConventionsCatalog)).CreateExportProvider();

            using var workspace = TestWorkspace.CreateWorkspace(
                      new XElement("Workspace",
                                   new XElement("Project", new XAttribute("Language", "C#"),
                                                new XElement("Document", new XAttribute("FilePath", tempDirectory.CreateFile("Test.cs").Path)))), exportProvider: exportProvider);

            var document = workspace.CurrentSolution.Projects.Single().Documents.Single();

            var providerFactory = workspace.ExportProvider.GetExportedValues <IDocumentOptionsProviderFactory>().OfType <LegacyEditorConfigDocumentOptionsProviderFactory>().Single();
            var provider        = providerFactory.TryCreate(workspace);

            var option    = new Option <List <string> >(nameof(LegacyEditorConfigDocumentOptionsProviderTests), nameof(OrderingOfEditorConfigMaintained), null, new[] { new KeysReturningStorageLocation() });
            var optionKey = new OptionKey(option);

            // Fetch the underlying option order with a "option" that returns the keys
            provider.GetOptionsForDocumentAsync(document, CancellationToken.None).Result.TryGetDocumentOption(optionKey, workspace.Options, out object actualKeysInOrderObject);

            var actualKeysInOrder = Assert.IsAssignableFrom <IEnumerable <string> >(actualKeysInOrderObject);

            Assert.Equal(expectedKeysInOrder, actualKeysInOrder);
        }
コード例 #29
0
        public async Task TestAddProject_CommandLineProjectAsync()
        {
            using var tempRoot = new TempRoot();
            var tempDirectory = tempRoot.CreateDirectory();
            var tempFile      = tempDirectory.CreateFile("CSharpClass.cs");

            tempFile.WriteAllText("class CSharpClass { }");

            using var ws = new AdhocWorkspace();
            var commandLine = @"CSharpClass.cs /out:goo.dll /target:library";
            var info        = CommandLineProject.CreateProjectInfo(
                "TestProject",
                LanguageNames.CSharp,
                commandLine,
                tempDirectory.Path,
                ws
                );

            ws.AddProject(info);
            var project = ws.CurrentSolution.GetProject(info.Id);

            Assert.Equal("TestProject", project.Name);
            Assert.Equal("goo", project.AssemblyName);
            Assert.Equal(
                OutputKind.DynamicallyLinkedLibrary,
                project.CompilationOptions.OutputKind
                );

            Assert.Equal(1, project.Documents.Count());

            var gooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs");

            Assert.Equal(0, gooDoc.Folders.Count);
            Assert.Equal(tempFile.Path, gooDoc.FilePath);

            var text = (await gooDoc.GetTextAsync()).ToString();

            Assert.Equal(tempFile.ReadAllText(), text);

            var tree = await gooDoc.GetSyntaxRootAsync();

            Assert.False(tree.ContainsDiagnostics);

            var compilation = await project.GetCompilationAsync();
        }
コード例 #30
0
        private async Task <string> GetXmlDocumentAsync(HostServices services)
        {
            using (var tempRoot = new TempRoot())
            {
                // get original assembly location
                var mscorlibLocation = typeof(object).Assembly.Location;

                // set up dll and xml doc content
                var tempDir       = tempRoot.CreateDirectory();
                var tempCorlib    = tempDir.CopyFile(mscorlibLocation);
                var tempCorlibXml = tempDir.CreateFile(Path.ChangeExtension(tempCorlib.Path, "xml"));
                tempCorlibXml.WriteAllText(@"<?xml version=""1.0"" encoding=""utf-8""?>
<doc>
  <assembly>
    <name>mscorlib</name>
  </assembly>
  <members>
    <member name=""T:System.Object"">
      <summary>Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.To browse the .NET Framework source code for this type, see the Reference Source.</summary>
    </member>
  </members>
</doc>");

                // currently portable layer doesn't support xml documment
                var solution = new AdhocWorkspace(services).CurrentSolution
                               .AddProject("Project", "Project.dll", LanguageNames.CSharp)
                               .AddMetadataReference(MetadataReference.CreateFromFile(tempCorlib.Path))
                               .Solution;

                var snapshotService = (new RemotableDataServiceFactory()).CreateService(solution.Workspace.Services) as IRemotableDataService;
                using (var scope = await snapshotService.CreatePinnedRemotableDataScopeAsync(solution, CancellationToken.None))
                {
                    // recover solution from given snapshot
                    var recovered = await GetSolutionAsync(snapshotService, scope);

                    var compilation = await recovered.Projects.First().GetCompilationAsync(CancellationToken.None);

                    var objectType    = compilation.GetTypeByMetadataName("System.Object");
                    var xmlDocComment = objectType.GetDocumentationCommentXml();

                    return(xmlDocComment);
                }
            }
        }