Skip to content

Commit 6a3911a

Browse files
committed
using c#8 using declarations
1 parent eb131da commit 6a3911a

File tree

10 files changed

+156
-186
lines changed

10 files changed

+156
-186
lines changed

src/GitVersionCore/Cache/GitVersionCache.cs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,12 @@ public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKe
3636

3737
void WriteCacheOperation()
3838
{
39-
using (var stream = fileSystem.OpenWrite(cacheFileName))
39+
using var stream = fileSystem.OpenWrite(cacheFileName);
40+
using var sw = new StreamWriter(stream);
41+
using (log.IndentLog("Storing version variables to cache file " + cacheFileName))
4042
{
41-
using (var sw = new StreamWriter(stream))
42-
{
43-
using (log.IndentLog("Storing version variables to cache file " + cacheFileName))
44-
{
45-
var serializer = new Serializer();
46-
serializer.Serialize(sw, dictionary);
47-
}
48-
}
43+
var serializer = new Serializer();
44+
serializer.Serialize(sw, dictionary);
4945
}
5046
}
5147

src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,11 @@ private static string GetHash(string textToHash)
184184
return string.Empty;
185185
}
186186

187-
using (var sha1 = SHA1.Create())
188-
{
189-
var bytes = Encoding.UTF8.GetBytes(textToHash);
190-
var hashedBytes = sha1.ComputeHash(bytes);
191-
var hashedString = BitConverter.ToString(hashedBytes);
192-
return hashedString.Replace("-", "");
193-
}
187+
using var sha1 = SHA1.Create();
188+
var bytes = Encoding.UTF8.GetBytes(textToHash);
189+
var hashedBytes = sha1.ComputeHash(bytes);
190+
var hashedString = BitConverter.ToString(hashedBytes);
191+
return hashedString.Replace("-", "");
194192
}
195193
}
196194
}

src/GitVersionCore/Configuration/ConfigurationProvider.cs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -253,13 +253,11 @@ public static void Init(string workingDirectory, IFileSystem fileSystem, IConsol
253253
var config = new ConfigInitWizard(console, fileSystem, log).Run(currentConfiguration, workingDirectory);
254254
if (config == null) return;
255255

256-
using (var stream = fileSystem.OpenWrite(configFilePath))
257-
using (var writer = new StreamWriter(stream))
258-
{
259-
log.Info("Saving config file");
260-
ConfigSerialiser.Write(config, writer);
261-
stream.Flush();
262-
}
256+
using var stream = fileSystem.OpenWrite(configFilePath);
257+
using var writer = new StreamWriter(stream);
258+
log.Info("Saving config file");
259+
ConfigSerialiser.Write(config, writer);
260+
stream.Flush();
263261
}
264262
}
265263
}

src/GitVersionCore/Extensions/WixVersionFileUpdater.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,8 @@ public void Update()
3535
XmlElement root = doc.DocumentElement;
3636
doc.InsertBefore(xmlDecl, root);
3737

38-
using (var fs = fileSystem.OpenWrite(WixVersionFile))
39-
{
40-
doc.Save(fs);
41-
}
38+
using var fs = fileSystem.OpenWrite(WixVersionFile);
39+
doc.Save(fs);
4240
}
4341

4442
private string GetWixFormatFromVersionVariables()

src/GitVersionCore/GitPreparer.cs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,8 @@ private void CleanupDuplicateOrigin()
9393

9494
public TResult WithRepository<TResult>(Func<IRepository, TResult> action)
9595
{
96-
using (IRepository repo = new Repository(GetDotGitDirectory()))
97-
{
98-
return action(repo);
99-
}
96+
using IRepository repo = new Repository(GetDotGitDirectory());
97+
return action(repo);
10098
}
10199

102100
private static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation)
@@ -128,10 +126,8 @@ private static bool GitRepoHasMatchingRemote(string possiblePath, string targetU
128126
{
129127
try
130128
{
131-
using (var repository = new Repository(possiblePath))
132-
{
133-
return repository.Network.Remotes.Any(r => r.Url == targetUrl);
134-
}
129+
using var repository = new Repository(possiblePath);
130+
return repository.Network.Remotes.Any(r => r.Url == targetUrl);
135131
}
136132
catch (Exception)
137133
{
@@ -167,12 +163,10 @@ public string GetProjectRootDirectory()
167163
if (string.IsNullOrEmpty(dotGitDirectory))
168164
throw new DirectoryNotFoundException($"Can't find the .git directory in {WorkingDirectory}");
169165

170-
using (var repo = new Repository(dotGitDirectory))
171-
{
172-
var result = repo.Info.WorkingDirectory;
173-
log.Info($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}");
174-
return result;
175-
}
166+
using var repo = new Repository(dotGitDirectory);
167+
var result = repo.Info.WorkingDirectory;
168+
log.Info($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}");
169+
return result;
176170
}
177171

178172
private string CreateDynamicRepository(string targetPath, AuthenticationInfo auth, string repositoryUrl, string targetBranch, bool noFetch)

src/GitVersionCore/Helpers/EncodingHelper.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,21 +28,19 @@ public static Encoding DetectEncoding(string filename)
2828
ScanEncodings();
2929
}
3030

31-
using (var stream = File.OpenRead(filename))
31+
using var stream = File.OpenRead(filename);
32+
// No bytes? No encoding!
33+
if (stream.Length == 0)
3234
{
33-
// No bytes? No encoding!
34-
if (stream.Length == 0)
35-
{
36-
return null;
37-
}
35+
return null;
36+
}
3837

39-
// Read the minimum amount necessary.
40-
var length = stream.Length > MaxPreambleLength ? MaxPreambleLength : stream.Length;
38+
// Read the minimum amount necessary.
39+
var length = stream.Length > MaxPreambleLength ? MaxPreambleLength : stream.Length;
4140

42-
var bytes = new byte[length];
43-
stream.Read(bytes, 0, (int)length);
44-
return DetectEncoding(bytes);
45-
}
41+
var bytes = new byte[length];
42+
stream.Read(bytes, 0, (int)length);
43+
return DetectEncoding(bytes);
4644
}
4745

4846
/// <summary>

src/GitVersionCore/Helpers/GitRepositoryHelper.cs

Lines changed: 83 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -16,120 +16,118 @@ public static class GitRepositoryHelper
1616
public static void NormalizeGitDirectory(ILog log, string gitDirectory, AuthenticationInfo authentication,
1717
bool noFetch, string currentBranch, bool isDynamicRepository)
1818
{
19-
using (var repo = new Repository(gitDirectory))
19+
using var repo = new Repository(gitDirectory);
20+
// Need to ensure the HEAD does not move, this is essentially a BugCheck
21+
var expectedSha = repo.Head.Tip.Sha;
22+
var expectedBranchName = repo.Head.CanonicalName;
23+
24+
try
2025
{
21-
// Need to ensure the HEAD does not move, this is essentially a BugCheck
22-
var expectedSha = repo.Head.Tip.Sha;
23-
var expectedBranchName = repo.Head.CanonicalName;
26+
var remote = EnsureOnlyOneRemoteIsDefined(log, repo);
27+
28+
AddMissingRefSpecs(log, repo, remote);
2429

25-
try
30+
//If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
31+
if (noFetch)
2632
{
27-
var remote = EnsureOnlyOneRemoteIsDefined(log, repo);
33+
log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
34+
}
35+
else
36+
{
37+
Fetch(log, authentication, remote, repo);
38+
}
2839

29-
AddMissingRefSpecs(log, repo, remote);
40+
EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch);
41+
CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name);
3042

31-
//If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
32-
if (noFetch)
33-
{
34-
log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
35-
}
36-
else
37-
{
38-
Fetch(log, authentication, remote, repo);
39-
}
40-
41-
EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch);
42-
CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name);
43+
// Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
44+
// if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
45+
if (expectedSha != repo.Head.Tip.Sha &&
46+
(isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
47+
{
48+
var newExpectedSha = repo.Head.Tip.Sha;
49+
var newExpectedBranchName = repo.Head.CanonicalName;
4350

44-
// Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
45-
// if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
46-
if (expectedSha != repo.Head.Tip.Sha &&
47-
(isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
48-
{
49-
var newExpectedSha = repo.Head.Tip.Sha;
50-
var newExpectedBranchName = repo.Head.CanonicalName;
51+
log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");
5152

52-
log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");
53+
expectedSha = newExpectedSha;
54+
}
5355

54-
expectedSha = newExpectedSha;
55-
}
56+
var headSha = repo.Refs.Head.TargetIdentifier;
5657

57-
var headSha = repo.Refs.Head.TargetIdentifier;
58+
if (!repo.Info.IsHeadDetached)
59+
{
60+
log.Info($"HEAD points at branch '{headSha}'.");
61+
return;
62+
}
5863

59-
if (!repo.Info.IsHeadDetached)
60-
{
61-
log.Info($"HEAD points at branch '{headSha}'.");
62-
return;
63-
}
64+
log.Info($"HEAD is detached and points at commit '{headSha}'.");
65+
log.Info(string.Format("Local Refs:\r\n" + string.Join(Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})"))));
6466

65-
log.Info($"HEAD is detached and points at commit '{headSha}'.");
66-
log.Info(string.Format("Local Refs:\r\n" + string.Join(Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})"))));
67+
// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
68+
// If they do, go ahead and checkout that branch
69+
// If no, go ahead and check out a new branch, using the known commit SHA as the pointer
70+
var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();
6771

68-
// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
69-
// If they do, go ahead and checkout that branch
70-
// If no, go ahead and check out a new branch, using the known commit SHA as the pointer
71-
var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();
72+
var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
73+
? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
74+
: null;
75+
if (matchingCurrentBranch != null)
76+
{
77+
log.Info($"Checking out local branch '{currentBranch}'.");
78+
Commands.Checkout(repo, matchingCurrentBranch);
79+
}
80+
else if (localBranchesWhereCommitShaIsHead.Count > 1)
81+
{
82+
var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
83+
var csvNames = string.Join(", ", branchNames);
84+
const string moveBranchMsg = "Move one of the branches along a commit to remove warning";
7285

73-
var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
74-
? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
75-
: null;
76-
if (matchingCurrentBranch != null)
86+
log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
87+
var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
88+
if (master != null)
7789
{
78-
log.Info($"Checking out local branch '{currentBranch}'.");
79-
Commands.Checkout(repo, matchingCurrentBranch);
90+
log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
91+
Commands.Checkout(repo, master);
8092
}
81-
else if (localBranchesWhereCommitShaIsHead.Count > 1)
93+
else
8294
{
83-
var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
84-
var csvNames = string.Join(", ", branchNames);
85-
const string moveBranchMsg = "Move one of the branches along a commit to remove warning";
86-
87-
log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
88-
var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
89-
if (master != null)
95+
var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
96+
if (branchesWithoutSeparators.Count == 1)
9097
{
91-
log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
92-
Commands.Checkout(repo, master);
98+
var branchWithoutSeparator = branchesWithoutSeparators[0];
99+
log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
100+
Commands.Checkout(repo, branchWithoutSeparator);
93101
}
94102
else
95103
{
96-
var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
97-
if (branchesWithoutSeparators.Count == 1)
98-
{
99-
var branchWithoutSeparator = branchesWithoutSeparators[0];
100-
log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
101-
Commands.Checkout(repo, branchWithoutSeparator);
102-
}
103-
else
104-
{
105-
throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
106-
}
104+
throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
107105
}
108106
}
109-
else if (localBranchesWhereCommitShaIsHead.Count == 0)
110-
{
111-
log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
112-
CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication);
113-
}
114-
else
115-
{
116-
log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
117-
Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
118-
}
119107
}
120-
finally
108+
else if (localBranchesWhereCommitShaIsHead.Count == 0)
109+
{
110+
log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
111+
CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication);
112+
}
113+
else
121114
{
122-
if (repo.Head.Tip.Sha != expectedSha)
115+
log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
116+
Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
117+
}
118+
}
119+
finally
120+
{
121+
if (repo.Head.Tip.Sha != expectedSha)
122+
{
123+
if (Environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
123124
{
124-
if (Environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
125-
{
126-
// Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
127-
throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.
125+
// Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
126+
throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.
128127
129128
To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1
130129
131130
Please run `git {CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
132-
}
133131
}
134132
}
135133
}

0 commit comments

Comments
 (0)