-
Notifications
You must be signed in to change notification settings - Fork 94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rebase absolute URIs relative to the closest enclosing repo root. #2047
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e0fa956
Rename GitInformation to GitHelper.
5810a9a
Make GitHelper.GetRepositoryRoot a public API.
5467352
Introduce directory-to-repo-root-path cache in GitHelper.
c6ee774
Introduce flag to turn off caching.
abad5ee
Introduce static instance that won't let you run cached.
347652e
Tighten up the exception message.
5032ca4
Implement URI rebasing on repo roots.
a8f4a23
Handle multiple repo roots.
dbd4e51
Move private helpers down to the end.
689079a
Add more tests (multiple roots; pre-existing originalUriBaseIds, abso…
f31886c
Fix broken test by removing enlistment path dependency.
2272e55
PR feedback: Replace IProcessRunner interface with a delegate.
e500a20
Merge branch 'master' into users/lgolding/rebase-with-git-information-2
7d17656
Merge branch 'master' into users/lgolding/rebase-with-git-information-2
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,192 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Threading; | ||
|
||
namespace Microsoft.CodeAnalysis.Sarif | ||
{ | ||
public class GitHelper : IDisposable | ||
{ | ||
public static readonly GitHelper Default = new GitHelper(); | ||
|
||
public delegate string ProcessRunner(string workingDirectory, string exePath, string arguments); | ||
|
||
private static readonly ProcessRunner DefaultProcessRunner = | ||
(string workingDirectory, string exePath, string arguments) | ||
=> new ExternalProcess(workingDirectory, exePath, arguments, stdOut: null, acceptableReturnCodes: null).StdOut.Text; | ||
|
||
private readonly IFileSystem fileSystem; | ||
private readonly ProcessRunner processRunner; | ||
private readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(); | ||
|
||
internal static readonly string s_expectedGitExePath = Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Git\cmd\git.exe"); | ||
|
||
// A cache that maps directory names to the root directory of the repository, if any, that | ||
// contains them. | ||
// | ||
// The case-insensitive key comparison is correct on Windows systems and wrong on Linux/MacOS. | ||
// This is a general problem in the SDK. See /~https://github.com/microsoft/sarif-sdk/issues/1736, | ||
// "File path comparisons are not file-system-appropriate". | ||
// | ||
// The cache is internal rather than private so that tests can verify that the cache is | ||
// being populated appropriately. It's not so easy to verify that it's being _used_ | ||
// appropriately. | ||
internal readonly Dictionary<string, string> directoryToRepoRootPathDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); | ||
|
||
public bool IsRepositoryRoot(string repositoryPath) => this.fileSystem.DirectoryExists(Path.Combine(repositoryPath, ".git")); | ||
|
||
public GitHelper(IFileSystem fileSystem = null, ProcessRunner processRunner = null) | ||
{ | ||
this.fileSystem = fileSystem ?? new FileSystem(); | ||
this.processRunner = processRunner ?? DefaultProcessRunner; | ||
|
||
GitExePath = GetGitExePath(); | ||
} | ||
|
||
public string GitExePath { get; } | ||
|
||
public Uri GetRemoteUri(string repoPath) | ||
{ | ||
string uriText = GetSimpleGitCommandOutput( | ||
repoPath, | ||
args: $"remote get-url origin"); | ||
|
||
return uriText == null | ||
? null | ||
: new Uri(uriText, UriKind.Absolute); | ||
} | ||
|
||
public string GetCurrentCommit(string repoPath) | ||
{ | ||
return GetSimpleGitCommandOutput( | ||
repoPath, | ||
args: "rev-parse --verify HEAD"); | ||
} | ||
|
||
public void Checkout(string repoPath, string commitSha) | ||
{ | ||
GetSimpleGitCommandOutput( | ||
repoPath, | ||
args: $"checkout {commitSha}"); | ||
} | ||
|
||
private string GetGitExePath() | ||
=> this.fileSystem.FileExists(s_expectedGitExePath) ? s_expectedGitExePath : null; | ||
|
||
public string GetCurrentBranch(string repoPath) | ||
{ | ||
return GetSimpleGitCommandOutput( | ||
repoPath, | ||
args: "rev-parse --abbrev-ref HEAD"); | ||
} | ||
|
||
private string GetSimpleGitCommandOutput(string repositoryPath, string args) | ||
{ | ||
string gitPath = this.GitExePath; | ||
|
||
if (gitPath == null || !IsRepositoryRoot(repositoryPath)) | ||
{ | ||
return null; | ||
} | ||
|
||
string stdOut = this.processRunner( | ||
workingDirectory: repositoryPath, | ||
exePath: gitPath, | ||
arguments: args); | ||
|
||
return TrimNewlines(stdOut); | ||
} | ||
|
||
private static string TrimNewlines(string text) => text | ||
.Replace("\r", string.Empty) | ||
.Replace("\n", string.Empty); | ||
|
||
public string GetRepositoryRoot(string path, bool useCache = true) | ||
{ | ||
// The "default" instance won't let you use the cache, to prevent independent users | ||
// from interfering with each other. | ||
if (useCache && object.ReferenceEquals(this, Default)) | ||
{ | ||
throw new ArgumentException(SdkResources.GitHelperDefaultInstanceDoesNotPermitCaching, nameof(useCache)); | ||
} | ||
|
||
if (this.fileSystem.FileExists(path)) | ||
{ | ||
path = Path.GetDirectoryName(path); | ||
} | ||
|
||
string repoRootPath; | ||
if (useCache) | ||
{ | ||
cacheLock.EnterReadLock(); | ||
try | ||
{ | ||
if (directoryToRepoRootPathDictionary.TryGetValue(path, out repoRootPath)) | ||
{ | ||
return repoRootPath; | ||
} | ||
} | ||
finally | ||
{ | ||
cacheLock.ExitReadLock(); | ||
} | ||
} | ||
|
||
repoRootPath = path; | ||
while (!string.IsNullOrEmpty(repoRootPath) && !IsRepositoryRoot(repoRootPath)) | ||
{ | ||
repoRootPath = Path.GetDirectoryName(repoRootPath); | ||
} | ||
|
||
// It's important to terminate with a slash because the value returned from this method | ||
// will be used to create an absolute URI on which MakeUriRelative will be called. For | ||
// example, suppose this method returns @"C:\\dev\sarif-sdk\". The caller will use it | ||
// to create an absolute URI (call it repoRootUri) "file:///C:/dev/sarif-sdk/". The | ||
// caller will use this URI to "rebase" another URI (call it artifactUri) such as | ||
// "file:///C:/dev/sarif-sdk/src/Sarif". The caller will do that by calling | ||
// repoRootUri.MakeRelativeUri(artifactUri). It turns out that unless repoRootUri | ||
// ends with a slash, this call will return "sarif-sdk/src/Sarif" rather than the | ||
// expected (at least for me) "src/Sarif". | ||
if (repoRootPath != null && !repoRootPath.EndsWith(@"\")) { repoRootPath += @"\"; } | ||
|
||
if (useCache) | ||
{ | ||
cacheLock.EnterWriteLock(); | ||
try | ||
{ | ||
// Add whatever we found to the cache, even if it was null (in which case we now know | ||
// that this path isn't under source control). | ||
directoryToRepoRootPathDictionary.Add(path, repoRootPath); | ||
} | ||
finally | ||
{ | ||
cacheLock.ExitWriteLock(); | ||
} | ||
} | ||
|
||
return repoRootPath; | ||
} | ||
|
||
/// <summary> | ||
/// Dispose pattern as required by style | ||
/// </summary> | ||
/// <param name="disposing">Set to true to actually dispose</param> | ||
protected virtual void Dispose(bool disposing) | ||
{ | ||
if (disposing) | ||
{ | ||
cacheLock.Dispose(); | ||
} | ||
} | ||
|
||
/// <inheritdoc/> | ||
public void Dispose() | ||
{ | ||
Dispose(true); | ||
GC.SuppressFinalize(this); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Has to be public now because
InsertOptionalDataVisitor
takes the delegate as a parameter, andInsertOptionalDataVisitor
is a public type, so the parameter type has to be public -- meaning both the delegate declaration (Line 15) and the class have to be public. #ByDesign