From 796f8898c9c296740548aaa11180754517cf25b0 Mon Sep 17 00:00:00 2001 From: Nathan Baulch Date: Wed, 9 Jul 2025 18:12:03 +1000 Subject: [PATCH] code_style: general cleanup (#1543) * code_style: general cleanup * feedback fixes --- .editorconfig | 1 + .github/workflows/build.yml | 12 +++--- .github/workflows/format-check.yml | 4 +- .github/workflows/localization-check.yml | 2 +- .github/workflows/package.yml | 2 +- src/App.axaml.cs | 41 ++++++++----------- src/Commands/Command.cs | 19 ++++----- src/Commands/GenerateCommitMessage.cs | 6 +-- src/Commands/QueryCommits.cs | 8 ++-- src/Commands/QueryFileContent.cs | 8 +--- src/Commands/SaveChangesAsPatch.cs | 8 +--- src/Commands/SaveRevisionFile.cs | 4 +- src/Commands/UnstageChangesForAmend.cs | 6 +-- src/Models/AvatarManager.cs | 8 ++-- src/Models/Commit.cs | 8 ++-- src/Models/DiffOption.cs | 1 - src/Models/ExternalTool.cs | 20 +++++---- src/Models/IssueTrackerRule.cs | 6 +-- src/Models/OpenAI.cs | 2 +- src/Models/TemplateEngine.cs | 8 ++-- src/Native/Linux.cs | 6 +-- src/Native/MacOS.cs | 6 +-- src/Native/OS.cs | 6 +-- src/Native/Windows.cs | 6 +-- src/Resources/Locales/en_US.axaml | 2 +- src/ViewModels/CommitDetail.cs | 12 +----- .../ConventionalCommitMessageBuilder.cs | 6 +-- src/ViewModels/ExecuteCustomAction.cs | 5 +-- src/ViewModels/Histories.cs | 4 +- src/ViewModels/InitGitFlow.cs | 4 +- src/ViewModels/Preferences.cs | 3 +- src/ViewModels/Repository.cs | 9 ++-- src/ViewModels/RepositoryConfigure.cs | 16 ++++---- src/ViewModels/ScanRepositories.cs | 2 +- src/Views/CommitSubjectPresenter.cs | 6 +-- src/Views/ConfigureCustomActionControls.axaml | 2 +- src/Views/Histories.axaml | 2 +- src/Views/Histories.axaml.cs | 2 +- src/Views/SetSubmoduleBranch.axaml | 2 +- src/Views/SubmodulesView.axaml | 10 ++--- src/Views/TextDiffView.axaml.cs | 6 +-- src/Views/UpdateSubmodules.axaml | 2 +- 42 files changed, 127 insertions(+), 166 deletions(-) diff --git a/.editorconfig b/.editorconfig index 720f49b7..89d2090c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -292,6 +292,7 @@ indent_size = 2 # Shell scripts [*.sh] end_of_line = lf + [*.{cmd,bat}] end_of_line = crlf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2e265201..369a122a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,23 +6,23 @@ jobs: strategy: matrix: include: - - name : Windows x64 + - name: Windows x64 os: windows-2022 runtime: win-x64 - - name : Windows ARM64 + - name: Windows ARM64 os: windows-2022 runtime: win-arm64 - - name : macOS (Intel) + - name: macOS (Intel) os: macos-13 runtime: osx-x64 - - name : macOS (Apple Silicon) + - name: macOS (Apple Silicon) os: macos-latest runtime: osx-arm64 - - name : Linux + - name: Linux os: ubuntu-latest runtime: linux-x64 container: ubuntu:20.04 - - name : Linux (arm64) + - name: Linux (arm64) os: ubuntu-latest runtime: linux-arm64 container: ubuntu:20.04 diff --git a/.github/workflows/format-check.yml b/.github/workflows/format-check.yml index 4d20b20e..5e75fb2a 100644 --- a/.github/workflows/format-check.yml +++ b/.github/workflows/format-check.yml @@ -1,7 +1,9 @@ name: Format Check on: push: - branches: [ develop ] + branches: [develop] + pull_request: + branches: [develop] workflow_dispatch: workflow_call: diff --git a/.github/workflows/localization-check.yml b/.github/workflows/localization-check.yml index 8dcd61c8..c5970870 100644 --- a/.github/workflows/localization-check.yml +++ b/.github/workflows/localization-check.yml @@ -1,7 +1,7 @@ name: Localization Check on: push: - branches: [ develop ] + branches: [develop] paths: - 'src/Resources/Locales/**' workflow_dispatch: diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 4fb5dca3..37d8afba 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -12,7 +12,7 @@ jobs: runs-on: windows-2022 strategy: matrix: - runtime: [ win-x64, win-arm64 ] + runtime: [win-x64, win-arm64] steps: - name: Checkout sources uses: actions/checkout@v4 diff --git a/src/App.axaml.cs b/src/App.axaml.cs index 24f034d5..a4efa41a 100644 --- a/src/App.axaml.cs +++ b/src/App.axaml.cs @@ -221,7 +221,8 @@ namespace SourceGit try { var resDic = new ResourceDictionary(); - var overrides = JsonSerializer.Deserialize(File.ReadAllText(themeOverridesFile), JsonCodeGen.Default.ThemeOverrides); + using var stream = File.OpenRead(themeOverridesFile); + var overrides = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.ThemeOverrides); foreach (var kv in overrides.BasicColors) { if (kv.Key.Equals("SystemAccentColor", StringComparison.Ordinal)) @@ -449,31 +450,21 @@ namespace SourceGit if (!File.Exists(jobsFile)) return true; - var collection = JsonSerializer.Deserialize(File.ReadAllText(jobsFile), JsonCodeGen.Default.InteractiveRebaseJobCollection); + using var stream = File.OpenRead(jobsFile); + var collection = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.InteractiveRebaseJobCollection); using var writer = new StreamWriter(file); foreach (var job in collection.Jobs) { - switch (job.Action) + var code = job.Action switch { - case Models.InteractiveRebaseAction.Pick: - writer.WriteLine($"p {job.SHA}"); - break; - case Models.InteractiveRebaseAction.Edit: - writer.WriteLine($"e {job.SHA}"); - break; - case Models.InteractiveRebaseAction.Reword: - writer.WriteLine($"r {job.SHA}"); - break; - case Models.InteractiveRebaseAction.Squash: - writer.WriteLine($"s {job.SHA}"); - break; - case Models.InteractiveRebaseAction.Fixup: - writer.WriteLine($"f {job.SHA}"); - break; - default: - writer.WriteLine($"d {job.SHA}"); - break; - } + Models.InteractiveRebaseAction.Pick => 'p', + Models.InteractiveRebaseAction.Edit => 'e', + Models.InteractiveRebaseAction.Reword => 'r', + Models.InteractiveRebaseAction.Squash => 's', + Models.InteractiveRebaseAction.Fixup => 'f', + _ => 'd' + }; + writer.WriteLine($"{code} {job.SHA}"); } writer.Flush(); @@ -506,7 +497,8 @@ namespace SourceGit var origHead = File.ReadAllText(origHeadFile).Trim(); var onto = File.ReadAllText(ontoFile).Trim(); - var collection = JsonSerializer.Deserialize(File.ReadAllText(jobsFile), JsonCodeGen.Default.InteractiveRebaseJobCollection); + using var stream = File.OpenRead(jobsFile); + var collection = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.InteractiveRebaseJobCollection); if (!collection.Onto.Equals(onto) || !collection.OrigHead.Equals(origHead)) return true; @@ -626,7 +618,8 @@ namespace SourceGit try { // Fetch latest release information. - var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) }; + using var client = new HttpClient(); + client.Timeout = TimeSpan.FromSeconds(5); var data = await client.GetStringAsync("https://sourcegit-scm.github.io/data/version.json"); // Parse JSON into Models.Version. diff --git a/src/Commands/Command.cs b/src/Commands/Command.cs index 53d0b643..9a6f27cb 100644 --- a/src/Commands/Command.cs +++ b/src/Commands/Command.cs @@ -54,9 +54,9 @@ namespace SourceGit.Commands { Log?.AppendLine($"$ git {Args}\n"); - var start = CreateGitStartInfo(true); var errs = new List(); - var proc = new Process() { StartInfo = start }; + using var proc = new Process(); + proc.StartInfo = CreateGitStartInfo(true); proc.OutputDataReceived += (_, e) => HandleOutput(e.Data, errs); proc.ErrorDataReceived += (_, e) => HandleOutput(e.Data, errs); @@ -67,7 +67,7 @@ namespace SourceGit.Commands { proc.Start(); - // It not safe, please only use `CancellationToken` in readonly commands. + // Not safe, please only use `CancellationToken` in readonly commands. if (CancellationToken.CanBeCanceled) { dummy = proc; @@ -110,11 +110,9 @@ namespace SourceGit.Commands } } - int exitCode = proc.ExitCode; - proc.Close(); Log?.AppendLine(string.Empty); - if (!CancellationToken.IsCancellationRequested && exitCode != 0) + if (!CancellationToken.IsCancellationRequested && proc.ExitCode != 0) { if (RaiseError) { @@ -131,8 +129,8 @@ namespace SourceGit.Commands protected async Task ReadToEndAsync() { - var start = CreateGitStartInfo(true); - var proc = new Process() { StartInfo = start }; + using var proc = new Process(); + proc.StartInfo = CreateGitStartInfo(true); try { @@ -149,7 +147,6 @@ namespace SourceGit.Commands await proc.WaitForExitAsync(CancellationToken).ConfigureAwait(false); rs.IsSuccess = proc.ExitCode == 0; - proc.Close(); return rs; } @@ -191,8 +188,8 @@ namespace SourceGit.Commands // Force using this app as git editor. start.Arguments += Editor switch { - EditorType.CoreEditor => $"-c core.editor=\"\\\"{selfExecFile}\\\" --core-editor\" ", - EditorType.RebaseEditor => $"-c core.editor=\"\\\"{selfExecFile}\\\" --rebase-message-editor\" -c sequence.editor=\"\\\"{selfExecFile}\\\" --rebase-todo-editor\" -c rebase.abbreviateCommands=true ", + EditorType.CoreEditor => $"""-c core.editor="\"{selfExecFile}\" --core-editor" """, + EditorType.RebaseEditor => $"""-c core.editor="\"{selfExecFile}\" --rebase-message-editor" -c sequence.editor="\"{selfExecFile}\" --rebase-todo-editor" -c rebase.abbreviateCommands=true """, _ => "-c core.editor=true ", }; diff --git a/src/Commands/GenerateCommitMessage.cs b/src/Commands/GenerateCommitMessage.cs index 9b6fc4ff..4889881b 100644 --- a/src/Commands/GenerateCommitMessage.cs +++ b/src/Commands/GenerateCommitMessage.cs @@ -67,10 +67,8 @@ namespace SourceGit.Commands }); } - responseBuilder.Append("\n"); - summaryBuilder.Append("(file: "); - summaryBuilder.Append(change.Path); - summaryBuilder.Append(")\n"); + responseBuilder.AppendLine(); + summaryBuilder.Append("(file: ").Append(change.Path).AppendLine(")"); } if (_cancelToken.IsCancellationRequested) diff --git a/src/Commands/QueryCommits.cs b/src/Commands/QueryCommits.cs index 6391ff15..9493b339 100644 --- a/src/Commands/QueryCommits.cs +++ b/src/Commands/QueryCommits.cs @@ -80,8 +80,8 @@ namespace SourceGit.Commands break; case 2: _current.ParseDecorators(line); - if (_current.IsMerged && !_isHeadFounded) - _isHeadFounded = true; + if (_current.IsMerged && !_isHeadFound) + _isHeadFound = true; break; case 3: _current.Author = Models.User.FindOrAdd(line); @@ -110,7 +110,7 @@ namespace SourceGit.Commands if (start < rs.StdOut.Length) _current.Subject = rs.StdOut.Substring(start); - if (_findFirstMerged && !_isHeadFounded && _commits.Count > 0) + if (_findFirstMerged && !_isHeadFound && _commits.Count > 0) await MarkFirstMergedAsync().ConfigureAwait(false); return _commits; @@ -148,6 +148,6 @@ namespace SourceGit.Commands private List _commits = new List(); private Models.Commit _current = null; private bool _findFirstMerged = false; - private bool _isHeadFounded = false; + private bool _isHeadFound = false; } } diff --git a/src/Commands/QueryFileContent.cs b/src/Commands/QueryFileContent.cs index 38ee6e4a..193614f9 100644 --- a/src/Commands/QueryFileContent.cs +++ b/src/Commands/QueryFileContent.cs @@ -21,11 +21,9 @@ namespace SourceGit.Commands var stream = new MemoryStream(); try { - var proc = new Process() { StartInfo = starter }; - proc.Start(); + using var proc = Process.Start(starter); await proc.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false); await proc.WaitForExitAsync().ConfigureAwait(false); - proc.Close(); stream.Position = 0; } @@ -52,14 +50,12 @@ namespace SourceGit.Commands var stream = new MemoryStream(); try { - var proc = new Process() { StartInfo = starter }; - proc.Start(); + using var proc = Process.Start(starter); await proc.StandardInput.WriteLineAsync("version https://git-lfs.github.com/spec/v1").ConfigureAwait(false); await proc.StandardInput.WriteLineAsync($"oid sha256:{oid}").ConfigureAwait(false); await proc.StandardInput.WriteLineAsync($"size {size}").ConfigureAwait(false); await proc.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false); await proc.WaitForExitAsync().ConfigureAwait(false); - proc.Close(); stream.Position = 0; } diff --git a/src/Commands/SaveChangesAsPatch.cs b/src/Commands/SaveChangesAsPatch.cs index 659d5329..c86fc0e0 100644 --- a/src/Commands/SaveChangesAsPatch.cs +++ b/src/Commands/SaveChangesAsPatch.cs @@ -62,14 +62,10 @@ namespace SourceGit.Commands try { - var proc = new Process() { StartInfo = starter }; - proc.Start(); + using var proc = Process.Start(starter); await proc.StandardOutput.BaseStream.CopyToAsync(writer).ConfigureAwait(false); await proc.WaitForExitAsync().ConfigureAwait(false); - var rs = proc.ExitCode == 0; - proc.Close(); - - return rs; + return proc.ExitCode == 0; } catch (Exception e) { diff --git a/src/Commands/SaveRevisionFile.cs b/src/Commands/SaveRevisionFile.cs index 24d803df..42163d6c 100644 --- a/src/Commands/SaveRevisionFile.cs +++ b/src/Commands/SaveRevisionFile.cs @@ -42,13 +42,11 @@ namespace SourceGit.Commands { try { - var proc = new Process() { StartInfo = starter }; - proc.Start(); + using var proc = Process.Start(starter); if (input != null) await proc.StandardInput.WriteAsync(await new StreamReader(input).ReadToEndAsync()); await proc.StandardOutput.BaseStream.CopyToAsync(sw); await proc.WaitForExitAsync(); - proc.Close(); } catch (Exception e) { diff --git a/src/Commands/UnstageChangesForAmend.cs b/src/Commands/UnstageChangesForAmend.cs index 049811e5..5a826d9c 100644 --- a/src/Commands/UnstageChangesForAmend.cs +++ b/src/Commands/UnstageChangesForAmend.cs @@ -44,7 +44,7 @@ namespace SourceGit.Commands _patchBuilder.Append(c.Path); } - _patchBuilder.Append("\n"); + _patchBuilder.AppendLine(); } } @@ -63,15 +63,13 @@ namespace SourceGit.Commands try { - var proc = new Process() { StartInfo = starter }; - proc.Start(); + using var proc = Process.Start(starter); await proc.StandardInput.WriteAsync(_patchBuilder.ToString()); proc.StandardInput.Close(); var err = await proc.StandardError.ReadToEndAsync().ConfigureAwait(false); await proc.WaitForExitAsync().ConfigureAwait(false); var rs = proc.ExitCode == 0; - proc.Close(); if (!rs) App.RaiseException(_repo, err); diff --git a/src/Models/AvatarManager.cs b/src/Models/AvatarManager.cs index f098a05f..65786e38 100644 --- a/src/Models/AvatarManager.cs +++ b/src/Models/AvatarManager.cs @@ -82,11 +82,9 @@ namespace SourceGit.Models Bitmap img = null; try { - var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) }; - var task = client.GetAsync(url); - task.Wait(); - - var rsp = task.Result; + using var client = new HttpClient(); + client.Timeout = TimeSpan.FromSeconds(2); + var rsp = client.GetAsync(url).Result; if (rsp.IsSuccessStatusCode) { using (var stream = rsp.Content.ReadAsStream()) diff --git a/src/Models/Commit.cs b/src/Models/Commit.cs index 1bfed55b..ac38c243 100644 --- a/src/Models/Commit.cs +++ b/src/Models/Commit.cs @@ -110,10 +110,10 @@ namespace SourceGit.Models Decorators.Sort((l, r) => { - if (l.Type != r.Type) - return (int)l.Type - (int)r.Type; - else - return NumericSort.Compare(l.Name, r.Name); + var delta = (int)l.Type - (int)r.Type; + if (delta != 0) + return delta; + return NumericSort.Compare(l.Name, r.Name); }); } } diff --git a/src/Models/DiffOption.cs b/src/Models/DiffOption.cs index fe32528c..37c89b72 100644 --- a/src/Models/DiffOption.cs +++ b/src/Models/DiffOption.cs @@ -96,7 +96,6 @@ namespace SourceGit.Models /// /// Converts to diff command arguments. /// - /// public override string ToString() { var builder = new StringBuilder(); diff --git a/src/Models/ExternalTool.cs b/src/Models/ExternalTool.cs index f884fb4a..1ccacd35 100644 --- a/src/Models/ExternalTool.cs +++ b/src/Models/ExternalTool.cs @@ -88,7 +88,7 @@ namespace SourceGit.Models public class ExternalToolsFinder { - public List Founded + public List Tools { get; private set; @@ -100,7 +100,10 @@ namespace SourceGit.Models try { if (File.Exists(customPathsConfig)) - _customPaths = JsonSerializer.Deserialize(File.ReadAllText(customPathsConfig), JsonCodeGen.Default.ExternalToolPaths); + { + using var stream = File.OpenRead(customPathsConfig); + _customPaths = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.ExternalToolPaths); + } } catch { @@ -114,13 +117,13 @@ namespace SourceGit.Models { if (_customPaths.Tools.TryGetValue(name, out var customPath) && File.Exists(customPath)) { - Founded.Add(new ExternalTool(name, icon, customPath, execArgsGenerator)); + Tools.Add(new ExternalTool(name, icon, customPath, execArgsGenerator)); } else { var path = finder(); if (!string.IsNullOrEmpty(path) && File.Exists(path)) - Founded.Add(new ExternalTool(name, icon, path, execArgsGenerator)); + Tools.Add(new ExternalTool(name, icon, path, execArgsGenerator)); } } @@ -162,19 +165,20 @@ namespace SourceGit.Models public void FindJetBrainsFromToolbox(Func platformFinder) { var exclude = new List { "fleet", "dotmemory", "dottrace", "resharper-u", "androidstudio" }; - var supported_icons = new List { "CL", "DB", "DL", "DS", "GO", "JB", "PC", "PS", "PY", "QA", "QD", "RD", "RM", "RR", "WRS", "WS" }; + var supportedIcons = new List { "CL", "DB", "DL", "DS", "GO", "JB", "PC", "PS", "PY", "QA", "QD", "RD", "RM", "RR", "WRS", "WS" }; var state = Path.Combine(platformFinder(), "state.json"); if (File.Exists(state)) { - var stateData = JsonSerializer.Deserialize(File.ReadAllText(state), JsonCodeGen.Default.JetBrainsState); + using var stream = File.OpenRead(state); + var stateData = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.JetBrainsState); foreach (var tool in stateData.Tools) { if (exclude.Contains(tool.ToolId.ToLowerInvariant())) continue; - Founded.Add(new ExternalTool( + Tools.Add(new ExternalTool( $"{tool.DisplayName} {tool.DisplayVersion}", - supported_icons.Contains(tool.ProductCode) ? $"JetBrains/{tool.ProductCode}" : "JetBrains/JB", + supportedIcons.Contains(tool.ProductCode) ? $"JetBrains/{tool.ProductCode}" : "JetBrains/JB", Path.Combine(tool.InstallLocation, tool.LaunchCommand))); } } diff --git a/src/Models/IssueTrackerRule.cs b/src/Models/IssueTrackerRule.cs index 40c84b9e..40bb295a 100644 --- a/src/Models/IssueTrackerRule.cs +++ b/src/Models/IssueTrackerRule.cs @@ -51,12 +51,8 @@ namespace SourceGit.Models return; var matches = _regex.Matches(message); - for (var i = 0; i < matches.Count; i++) + foreach (Match match in matches) { - var match = matches[i]; - if (!match.Success) - continue; - var start = match.Index; var len = match.Length; if (outs.Intersect(start, len) != null) diff --git a/src/Models/OpenAI.cs b/src/Models/OpenAI.cs index 70b319c6..f8d76328 100644 --- a/src/Models/OpenAI.cs +++ b/src/Models/OpenAI.cs @@ -85,7 +85,7 @@ namespace SourceGit.Models _hasTrimmedStart = true; } - _onUpdate.Invoke(text); + _onUpdate?.Invoke(text); } [GeneratedRegex(@"<(think|thought|thinking|thought_chain)>.*?", RegexOptions.Singleline)] diff --git a/src/Models/TemplateEngine.cs b/src/Models/TemplateEngine.cs index c2ce28b2..87822fb1 100644 --- a/src/Models/TemplateEngine.cs +++ b/src/Models/TemplateEngine.cs @@ -170,18 +170,18 @@ namespace SourceGit.Models { if (Next() != VARIABLE_START) return null; - int name_start = _pos; + var nameStart = _pos; while (Next() is { } c) { // name character, continue advancing if (IsNameChar(c)) continue; - var name_end = _pos - 1; + var nameEnd = _pos - 1; // not a name character but name is empty, cancel - if (name_start >= name_end) + if (nameStart >= nameEnd) return null; - var name = new string(_chars, name_start, name_end - name_start); + var name = new string(_chars, nameStart, nameEnd - nameStart); return c switch { diff --git a/src/Native/Linux.cs b/src/Native/Linux.cs index 03608649..e5684345 100644 --- a/src/Native/Linux.cs +++ b/src/Native/Linux.cs @@ -54,10 +54,10 @@ namespace SourceGit.Native finder.VSCodium(() => FindExecutable("codium")); finder.Cursor(() => FindExecutable("cursor")); finder.Fleet(FindJetBrainsFleet); - finder.FindJetBrainsFromToolbox(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/JetBrains/Toolbox"); + finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "JetBrains/Toolbox")); finder.SublimeText(() => FindExecutable("subl")); finder.Zed(() => FindExecutable("zeditor")); - return finder.Founded; + return finder.Tools; } public void OpenBrowser(string url) @@ -134,7 +134,7 @@ namespace SourceGit.Native private string FindJetBrainsFleet() { - var path = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/JetBrains/Toolbox/apps/fleet/bin/Fleet"; + var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "JetBrains/Toolbox/apps/fleet/bin/Fleet"); return File.Exists(path) ? path : FindExecutable("fleet"); } } diff --git a/src/Native/MacOS.cs b/src/Native/MacOS.cs index 1e7ac59e..38a073e6 100644 --- a/src/Native/MacOS.cs +++ b/src/Native/MacOS.cs @@ -75,11 +75,11 @@ namespace SourceGit.Native finder.VSCodeInsiders(() => "/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code"); finder.VSCodium(() => "/Applications/VSCodium.app/Contents/Resources/app/bin/codium"); finder.Cursor(() => "/Applications/Cursor.app/Contents/Resources/app/bin/cursor"); - finder.Fleet(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/Applications/Fleet.app/Contents/MacOS/Fleet"); - finder.FindJetBrainsFromToolbox(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/Library/Application Support/JetBrains/Toolbox"); + finder.Fleet(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Applications/Fleet.app/Contents/MacOS/Fleet")); + finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library/Application Support/JetBrains/Toolbox")); finder.SublimeText(() => "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"); finder.Zed(() => File.Exists("/usr/local/bin/zed") ? "/usr/local/bin/zed" : "/Applications/Zed.app/Contents/MacOS/cli"); - return finder.Founded; + return finder.Tools; } public void OpenBrowser(string url) diff --git a/src/Native/OS.cs b/src/Native/OS.cs index 3e616b18..27fce1c3 100644 --- a/src/Native/OS.cs +++ b/src/Native/OS.cs @@ -203,11 +203,9 @@ namespace SourceGit.Native start.StandardOutputEncoding = Encoding.UTF8; start.StandardErrorEncoding = Encoding.UTF8; - var proc = new Process() { StartInfo = start }; try { - proc.Start(); - + using var proc = Process.Start(start); var rs = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); if (proc.ExitCode == 0 && !string.IsNullOrWhiteSpace(rs)) @@ -229,8 +227,6 @@ namespace SourceGit.Native { // Ignore errors } - - proc.Close(); } [GeneratedRegex(@"^git version[\s\w]*(\d+)\.(\d+)[\.\-](\d+).*$")] diff --git a/src/Native/Windows.cs b/src/Native/Windows.cs index e71bf782..9c21903e 100644 --- a/src/Native/Windows.cs +++ b/src/Native/Windows.cs @@ -185,11 +185,11 @@ namespace SourceGit.Native finder.VSCodeInsiders(FindVSCodeInsiders); finder.VSCodium(FindVSCodium); finder.Cursor(FindCursor); - finder.Fleet(() => $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Programs\Fleet\Fleet.exe"); - finder.FindJetBrainsFromToolbox(() => $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\JetBrains\Toolbox"); + finder.Fleet(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Programs\Fleet\Fleet.exe")); + finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"JetBrains\Toolbox")); finder.SublimeText(FindSublimeText); finder.TryAdd("Visual Studio", "vs", FindVisualStudio, GenerateCommandlineArgsForVisualStudio); - return finder.Founded; + return finder.Tools; } public void OpenBrowser(string url) diff --git a/src/Resources/Locales/en_US.axaml b/src/Resources/Locales/en_US.axaml index b2bcc366..ed490988 100644 --- a/src/Resources/Locales/en_US.axaml +++ b/src/Resources/Locales/en_US.axaml @@ -607,7 +607,7 @@ Sort By Committer Date By Name - Cleanup(GC & Prune) + Cleanup (GC & Prune) Run `git gc` command for this repository. Clear all Clear diff --git a/src/ViewModels/CommitDetail.cs b/src/ViewModels/CommitDetail.cs index e07dd6bf..3fce223b 100644 --- a/src/ViewModels/CommitDetail.cs +++ b/src/ViewModels/CommitDetail.cs @@ -771,12 +771,8 @@ namespace SourceGit.ViewModels } var urlMatches = REG_URL_FORMAT().Matches(message); - for (int i = 0; i < urlMatches.Count; i++) + foreach (Match match in urlMatches) { - var match = urlMatches[i]; - if (!match.Success) - continue; - var start = match.Index; var len = match.Length; if (inlines.Intersect(start, len) != null) @@ -788,12 +784,8 @@ namespace SourceGit.ViewModels } var shaMatches = REG_SHA_FORMAT().Matches(message); - for (int i = 0; i < shaMatches.Count; i++) + foreach (Match match in shaMatches) { - var match = shaMatches[i]; - if (!match.Success) - continue; - var start = match.Index; var len = match.Length; if (inlines.Intersect(start, len) != null) diff --git a/src/ViewModels/ConventionalCommitMessageBuilder.cs b/src/ViewModels/ConventionalCommitMessageBuilder.cs index 5eb9494c..824d0a86 100644 --- a/src/ViewModels/ConventionalCommitMessageBuilder.cs +++ b/src/ViewModels/ConventionalCommitMessageBuilder.cs @@ -77,19 +77,19 @@ namespace SourceGit.ViewModels builder.Append(": "); builder.Append(_description); - builder.Append("\n\n"); + builder.AppendLine("\n"); if (!string.IsNullOrEmpty(_detail)) { builder.Append(_detail); - builder.Append("\n\n"); + builder.AppendLine("\n"); } if (!string.IsNullOrEmpty(_breakingChanges)) { builder.Append("BREAKING CHANGE: "); builder.Append(_breakingChanges); - builder.Append("\n\n"); + builder.AppendLine("\n"); } if (!string.IsNullOrEmpty(_closedIssue)) diff --git a/src/ViewModels/ExecuteCustomAction.cs b/src/ViewModels/ExecuteCustomAction.cs index daffdc52..4c070841 100644 --- a/src/ViewModels/ExecuteCustomAction.cs +++ b/src/ViewModels/ExecuteCustomAction.cs @@ -250,7 +250,8 @@ namespace SourceGit.ViewModels start.StandardErrorEncoding = Encoding.UTF8; start.WorkingDirectory = _repo.FullPath; - var proc = new Process() { StartInfo = start }; + using var proc = new Process(); + proc.StartInfo = start; var builder = new StringBuilder(); proc.OutputDataReceived += (_, e) => @@ -287,8 +288,6 @@ namespace SourceGit.ViewModels { App.RaiseException(_repo.FullPath, e.Message); } - - proc.Close(); } private readonly Repository _repo = null; diff --git a/src/ViewModels/Histories.cs b/src/ViewModels/Histories.cs index ab554b9a..6e56b9cf 100644 --- a/src/ViewModels/Histories.cs +++ b/src/ViewModels/Histories.cs @@ -272,7 +272,7 @@ namespace SourceGit.ViewModels _repo.CheckoutBranch(b); return; } - else if (d.Type == Models.DecoratorType.RemoteBranchHead) + if (d.Type == Models.DecoratorType.RemoteBranchHead) { var rb = _repo.Branches.Find(x => x.FriendlyName == d.Name); if (rb == null) @@ -424,7 +424,7 @@ namespace SourceGit.ViewModels { var builder = new StringBuilder(); foreach (var c in selected) - builder.AppendLine($"{c.SHA.AsSpan(0, 10)} - {c.Subject}"); + builder.Append(c.SHA.AsSpan(0, 10)).Append(" - ").AppendLine(c.Subject); await App.CopyTextAsync(builder.ToString()); e.Handled = true; diff --git a/src/ViewModels/InitGitFlow.cs b/src/ViewModels/InitGitFlow.cs index d179fee0..aa72b11b 100644 --- a/src/ViewModels/InitGitFlow.cs +++ b/src/ViewModels/InitGitFlow.cs @@ -9,7 +9,7 @@ namespace SourceGit.ViewModels public partial class InitGitFlow : Popup { [GeneratedRegex(@"^[\w\-/\.]+$")] - private static partial Regex TAG_PREFIX(); + private static partial Regex REG_TAG_PREFIX(); [Required(ErrorMessage = "Master branch name is required!!!")] [RegularExpression(@"^[\w\-/\.]+$", ErrorMessage = "Bad branch name format!")] @@ -94,7 +94,7 @@ namespace SourceGit.ViewModels public static ValidationResult ValidateTagPrefix(string tagPrefix, ValidationContext ctx) { - if (!string.IsNullOrWhiteSpace(tagPrefix) && !TAG_PREFIX().IsMatch(tagPrefix)) + if (!string.IsNullOrWhiteSpace(tagPrefix) && !REG_TAG_PREFIX().IsMatch(tagPrefix)) return new ValidationResult("Bad tag prefix format!"); return ValidationResult.Success; diff --git a/src/ViewModels/Preferences.cs b/src/ViewModels/Preferences.cs index d7fe73f9..8e5f24c5 100644 --- a/src/ViewModels/Preferences.cs +++ b/src/ViewModels/Preferences.cs @@ -541,7 +541,8 @@ namespace SourceGit.ViewModels try { - return JsonSerializer.Deserialize(File.ReadAllText(path), JsonCodeGen.Default.Preferences); + using var stream = File.OpenRead(path); + return JsonSerializer.Deserialize(stream, JsonCodeGen.Default.Preferences); } catch { diff --git a/src/ViewModels/Repository.cs b/src/ViewModels/Repository.cs index b2161d9e..0bf07728 100644 --- a/src/ViewModels/Repository.cs +++ b/src/ViewModels/Repository.cs @@ -492,7 +492,8 @@ namespace SourceGit.ViewModels { try { - _settings = JsonSerializer.Deserialize(File.ReadAllText(settingsFile), JsonCodeGen.Default.RepositorySettings); + using var stream = File.OpenRead(settingsFile); + _settings = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.RepositorySettings); } catch { @@ -545,10 +546,10 @@ namespace SourceGit.ViewModels _settings.LastCommitMessage = _workingCopy.CommitMessage; - var settingsSerialized = JsonSerializer.Serialize(_settings, JsonCodeGen.Default.RepositorySettings); try { - File.WriteAllText(Path.Combine(_gitDir, "sourcegit.settings"), settingsSerialized); + using var stream = File.OpenWrite(Path.Combine(_gitDir, "sourcegit.settings")); + JsonSerializer.Serialize(stream, _settings, JsonCodeGen.Default.RepositorySettings); } catch { @@ -702,7 +703,7 @@ namespace SourceGit.ViewModels { menu.Items.Add(new MenuItem() { Header = "-" }); - foreach (var tool in Native.OS.ExternalTools) + foreach (var tool in tools) { var dupTool = tool; diff --git a/src/ViewModels/RepositoryConfigure.cs b/src/ViewModels/RepositoryConfigure.cs index 9764fccc..4bf5731f 100644 --- a/src/ViewModels/RepositoryConfigure.cs +++ b/src/ViewModels/RepositoryConfigure.cs @@ -210,17 +210,17 @@ namespace SourceGit.ViewModels } } - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitHub ISSUE", "#(\\d+)", link); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitHub ISSUE", @"#(\d+)", link); } public void AddSampleJiraIssueTracker() { - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Jira Tracker", "PROJ-(\\d+)", "https://jira.yourcompany.com/browse/PROJ-$1"); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Jira Tracker", @"PROJ-(\d+)", "https://jira.yourcompany.com/browse/PROJ-$1"); } public void AddSampleAzureWorkItemTracker() { - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Azure DevOps Tracker", "#(\\d+)", "https://dev.azure.com/yourcompany/workspace/_workitems/edit/$1"); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Azure DevOps Tracker", @"#(\d+)", "https://dev.azure.com/yourcompany/workspace/_workitems/edit/$1"); } public void AddSampleGitLabIssueTracker() @@ -235,7 +235,7 @@ namespace SourceGit.ViewModels } } - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab ISSUE", "#(\\d+)", link); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab ISSUE", @"#(\d+)", link); } public void AddSampleGitLabMergeRequestTracker() @@ -250,7 +250,7 @@ namespace SourceGit.ViewModels } } - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab MR", "!(\\d+)", link); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab MR", @"!(\d+)", link); } public void AddSampleGiteeIssueTracker() @@ -266,7 +266,7 @@ namespace SourceGit.ViewModels } } - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee ISSUE", "#([0-9A-Z]{6,10})", link); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee ISSUE", @"#([0-9A-Z]{6,10})", link); } public void AddSampleGiteePullRequestTracker() @@ -281,12 +281,12 @@ namespace SourceGit.ViewModels } } - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee Pull Request", "!(\\d+)", link); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee Pull Request", @"!(\d+)", link); } public void NewIssueTracker() { - SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("New Issue Tracker", "#(\\d+)", "https://xxx/$1"); + SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("New Issue Tracker", @"#(\d+)", "https://xxx/$1"); } public void RemoveSelectedIssueTracker() diff --git a/src/ViewModels/ScanRepositories.cs b/src/ViewModels/ScanRepositories.cs index e90e711f..b0154770 100644 --- a/src/ViewModels/ScanRepositories.cs +++ b/src/ViewModels/ScanRepositories.cs @@ -51,7 +51,7 @@ namespace SourceGit.ViewModels IgnoreInaccessible = true, }); - // Make sure this task takes at least 0.5s to avoid that the popup panel do not disappear very quickly. + // Make sure this task takes at least 0.5s to avoid the popup panel disappearing too quickly. await minDelay; var normalizedRoot = rootDir.FullName.Replace('\\', '/').TrimEnd('/'); diff --git a/src/Views/CommitSubjectPresenter.cs b/src/Views/CommitSubjectPresenter.cs index bfeab34f..5fc4cb5d 100644 --- a/src/Views/CommitSubjectPresenter.cs +++ b/src/Views/CommitSubjectPresenter.cs @@ -163,12 +163,8 @@ namespace SourceGit.Views _elements.Add(new Models.InlineElement(Models.InlineElementType.Keyword, 0, keywordMatch.Length, string.Empty)); var codeMatches = REG_INLINECODE_FORMAT().Matches(subject); - for (var i = 0; i < codeMatches.Count; i++) + foreach (Match match in codeMatches) { - var match = codeMatches[i]; - if (!match.Success) - continue; - var start = match.Index; var len = match.Length; if (_elements.Intersect(start, len) != null) diff --git a/src/Views/ConfigureCustomActionControls.axaml b/src/Views/ConfigureCustomActionControls.axaml index 21b6b8f1..1e7c9fa8 100644 --- a/src/Views/ConfigureCustomActionControls.axaml +++ b/src/Views/ConfigureCustomActionControls.axaml @@ -205,7 +205,7 @@ Margin="8,0,0,0" Height="28" IsChecked="{Binding BoolValue, Mode=TwoWay}"/> - + diff --git a/src/Views/Histories.axaml b/src/Views/Histories.axaml index 6ed3072b..904f1c60 100644 --- a/src/Views/Histories.axaml +++ b/src/Views/Histories.axaml @@ -50,7 +50,7 @@ - +