From 743d6098dab150f7571904c20620fb04e1ae5360 Mon Sep 17 00:00:00 2001 From: Nathan Baulch Date: Tue, 8 Jul 2025 16:28:01 +1000 Subject: [PATCH] code_style: general cleanup --- build/scripts/localization-check.js | 2 +- src/App.axaml.cs | 12 +- src/Commands/Apply.cs | 15 +- src/Commands/CherryPick.cs | 14 +- src/Commands/Clone.cs | 15 +- src/Commands/Commit.cs | 13 +- src/Commands/CompareRevisions.cs | 28 ++-- src/Commands/Fetch.cs | 15 +- src/Commands/Push.cs | 16 +- src/Commands/QueryLocalChanges.cs | 152 +++++------------- src/Commands/QueryStagedChangesWithAmend.cs | 27 ++-- src/Commands/QuerySubmodules.cs | 22 +-- src/Commands/SaveRevisionFile.cs | 5 +- src/Commands/Stash.cs | 3 +- src/Commands/Worktree.cs | 20 ++- src/Models/Change.cs | 4 +- src/Models/ConventionalCommitType.cs | 15 +- src/Models/DiffOption.cs | 6 +- src/Models/Remote.cs | 2 +- src/Models/TemplateEngine.cs | 2 +- src/Models/Watcher.cs | 11 +- src/Resources/Locales/en_US.axaml | 4 +- src/ViewModels/Clone.cs | 4 +- src/ViewModels/CreateBranch.cs | 1 - src/ViewModels/DeinitSubmodule.cs | 22 +-- src/ViewModels/Pull.cs | 5 +- src/ViewModels/Rebase.cs | 4 +- src/ViewModels/Repository.cs | 13 +- src/ViewModels/RepositoryConfigure.cs | 9 +- src/Views/BisectStateIndicator.cs | 2 +- src/Views/CommitMessagePresenter.cs | 8 +- src/Views/CommitRefsPresenter.cs | 2 +- .../ConventionalCommitMessageBuilder.axaml.cs | 7 +- src/Views/DirHistories.axaml.cs | 2 - src/Views/InteractiveRebase.axaml.cs | 35 ++-- src/Views/Launcher.axaml.cs | 6 +- src/Views/Reset.axaml.cs | 3 +- src/Views/SetSubmoduleBranch.axaml.cs | 1 - src/Views/TextDiffView.axaml.cs | 4 +- 39 files changed, 195 insertions(+), 336 deletions(-) diff --git a/build/scripts/localization-check.js b/build/scripts/localization-check.js index 8d636b5bb..24a9338e3 100644 --- a/build/scripts/localization-check.js +++ b/build/scripts/localization-check.js @@ -69,7 +69,7 @@ async function calculateTranslationRate() { const badgeColor = progress >= 75 ? 'yellow' : 'red'; lines.push(`### ![${locale}](https://img.shields.io/badge/${locale}-${progress.toFixed(2)}%25-${badgeColor})`); - lines.push(`
\nMissing keys in ${file}\n\n${missingKeys.map(key => `- ${key}`).join('\n')}\n\n
`) + lines.push(`
\nMissing keys in ${file}\n\n${missingKeys.map(key => `- \`${key}\``).join('\n')}\n\n
`) } else { lines.push(`### ![${locale}](https://img.shields.io/badge/${locale}-%E2%88%9A-brightgreen)`); } diff --git a/src/App.axaml.cs b/src/App.axaml.cs index f5c0559a1..51b5a6994 100644 --- a/src/App.axaml.cs +++ b/src/App.axaml.cs @@ -411,7 +411,7 @@ public override void OnFrameworkInitializationCompleted() if (!string.IsNullOrEmpty(arg)) { if (arg.StartsWith('"') && arg.EndsWith('"')) - arg = arg.Substring(1, arg.Length - 2).Trim(); + arg = arg[1..^1].Trim(); if (arg.Length > 0 && !Path.IsPathFullyQualified(arg)) arg = Path.GetFullPath(arg); @@ -687,12 +687,10 @@ private string FixFontFamilyName(string input) } var name = sb.ToString(); - if (name.Contains('#')) - { - if (!name.Equals("fonts:Inter#Inter", StringComparison.Ordinal) && - !name.Equals("fonts:SourceGit#JetBrains Mono", StringComparison.Ordinal)) - continue; - } + if (name.Contains('#') && + !name.Equals("fonts:Inter#Inter", StringComparison.Ordinal) && + !name.Equals("fonts:SourceGit#JetBrains Mono", StringComparison.Ordinal)) + continue; trimmed.Add(name); } diff --git a/src/Commands/Apply.cs b/src/Commands/Apply.cs index 189d43359..363b3d73d 100644 --- a/src/Commands/Apply.cs +++ b/src/Commands/Apply.cs @@ -1,4 +1,6 @@ -namespace SourceGit.Commands +using System.Text; + +namespace SourceGit.Commands { public class Apply : Command { @@ -6,14 +8,15 @@ public Apply(string repo, string file, bool ignoreWhitespace, string whitespaceM { WorkingDirectory = repo; Context = repo; - Args = "apply "; + + var builder = new StringBuilder("apply "); if (ignoreWhitespace) - Args += "--ignore-whitespace "; + builder.Append("--ignore-whitespace "); else - Args += $"--whitespace={whitespaceMode} "; + builder.Append("--whitespace=").Append(whitespaceMode).Append(' '); if (!string.IsNullOrEmpty(extra)) - Args += $"{extra} "; - Args += $"{file.Quoted()}"; + builder.Append(extra).Append(' '); + Args = builder.Append(file.Quoted()).ToString(); } } } diff --git a/src/Commands/CherryPick.cs b/src/Commands/CherryPick.cs index 0c82b9fda..228b9e2ac 100644 --- a/src/Commands/CherryPick.cs +++ b/src/Commands/CherryPick.cs @@ -1,4 +1,6 @@ -namespace SourceGit.Commands +using System.Text; + +namespace SourceGit.Commands { public class CherryPick : Command { @@ -7,14 +9,14 @@ public CherryPick(string repo, string commits, bool noCommit, bool appendSourceT WorkingDirectory = repo; Context = repo; - Args = "cherry-pick "; + var builder = new StringBuilder("cherry-pick "); if (noCommit) - Args += "-n "; + builder.Append("-n "); if (appendSourceToMessage) - Args += "-x "; + builder.Append("-x "); if (!string.IsNullOrEmpty(extraParams)) - Args += $"{extraParams} "; - Args += commits; + builder.Append(extraParams).Append(' '); + Args = builder.Append(commits).ToString(); } } } diff --git a/src/Commands/Clone.cs b/src/Commands/Clone.cs index efec264b8..74997d218 100644 --- a/src/Commands/Clone.cs +++ b/src/Commands/Clone.cs @@ -1,4 +1,6 @@ -namespace SourceGit.Commands +using System.Text; + +namespace SourceGit.Commands { public class Clone : Command { @@ -7,15 +9,14 @@ public Clone(string ctx, string path, string url, string localName, string sshKe Context = ctx; WorkingDirectory = path; SSHKey = sshKey; - Args = "clone --progress --verbose "; + var builder = new StringBuilder("clone --progress --verbose "); if (!string.IsNullOrEmpty(extraArgs)) - Args += $"{extraArgs} "; - - Args += $"{url} "; - + builder.Append(extraArgs).Append(' '); + builder.Append(url); if (!string.IsNullOrEmpty(localName)) - Args += localName; + builder.Append(' ').Append(localName); + Args = builder.ToString(); } } } diff --git a/src/Commands/Commit.cs b/src/Commands/Commit.cs index 41d650f76..d2a9be1c7 100644 --- a/src/Commands/Commit.cs +++ b/src/Commands/Commit.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Text; using System.Threading.Tasks; namespace SourceGit.Commands @@ -12,11 +13,17 @@ public Commit(string repo, string message, bool signOff, bool amend, bool resetA WorkingDirectory = repo; Context = repo; - Args = $"commit --allow-empty --file={_tmpFile.Quoted()}"; + + var builder = new StringBuilder("commit --allow-empty --file=").Append(_tmpFile.Quoted()); if (signOff) - Args += " --signoff"; + builder.Append(" --signoff"); if (amend) - Args += resetAuthor ? " --amend --reset-author --no-edit" : " --amend --no-edit"; + { + builder.Append(" --amend --no-edit"); + if (resetAuthor) + builder.Append(" --reset-author"); + } + Args = builder.ToString(); } public async Task RunAsync() diff --git a/src/Commands/CompareRevisions.cs b/src/Commands/CompareRevisions.cs index 7951e6adf..993e29ec0 100644 --- a/src/Commands/CompareRevisions.cs +++ b/src/Commands/CompareRevisions.cs @@ -64,24 +64,18 @@ private void ParseLine(List outs, string line) var change = new Models.Change() { Path = match.Groups[2].Value }; var status = match.Groups[1].Value; - switch (status[0]) + var state = status[0] switch { - case 'M': - change.Set(Models.ChangeState.Modified); - outs.Add(change); - break; - case 'A': - change.Set(Models.ChangeState.Added); - outs.Add(change); - break; - case 'D': - change.Set(Models.ChangeState.Deleted); - outs.Add(change); - break; - case 'C': - change.Set(Models.ChangeState.Copied); - outs.Add(change); - break; + 'M' => Models.ChangeState.Modified, + 'A' => Models.ChangeState.Added, + 'D' => Models.ChangeState.Deleted, + 'C' => Models.ChangeState.Copied, + _ => Models.ChangeState.None + }; + if (state != Models.ChangeState.None) + { + change.Set(state); + outs.Add(change); } } } diff --git a/src/Commands/Fetch.cs b/src/Commands/Fetch.cs index d25cc80c8..bf12732c3 100644 --- a/src/Commands/Fetch.cs +++ b/src/Commands/Fetch.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Text; +using System.Threading.Tasks; namespace SourceGit.Commands { @@ -10,18 +11,14 @@ public Fetch(string repo, string remote, bool noTags, bool force) WorkingDirectory = repo; Context = repo; - Args = "fetch --progress --verbose "; - if (noTags) - Args += "--no-tags "; - else - Args += "--tags "; + var builder = new StringBuilder("fetch --progress --verbose "); + builder.Append(noTags ? "--no-tags " : "--tags "); if (force) - Args += "--force "; - - Args += remote; + builder.Append("--force "); + Args = builder.Append(remote).ToString(); } public Fetch(string repo, Models.Branch local, Models.Branch remote) diff --git a/src/Commands/Push.cs b/src/Commands/Push.cs index b822af46d..94ef05544 100644 --- a/src/Commands/Push.cs +++ b/src/Commands/Push.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Text; +using System.Threading.Tasks; namespace SourceGit.Commands { @@ -10,18 +11,17 @@ public Push(string repo, string local, string remote, string remoteBranch, bool WorkingDirectory = repo; Context = repo; - Args = "push --progress --verbose "; + var builder = new StringBuilder("push --progress --verbose "); if (withTags) - Args += "--tags "; + builder.Append("--tags "); if (checkSubmodules) - Args += "--recurse-submodules=check "; + builder.Append("--recurse-submodules=check "); if (track) - Args += "-u "; + builder.Append("-u "); if (force) - Args += "--force-with-lease "; - - Args += $"{remote} {local}:{remoteBranch}"; + builder.Append("--force-with-lease "); + Args = builder.Append(remote).Append(' ').Append(local).Append(':').Append(remoteBranch).ToString(); } public Push(string repo, string remote, string refname, bool isDelete) diff --git a/src/Commands/QueryLocalChanges.cs b/src/Commands/QueryLocalChanges.cs index 9605014da..53a7c4e7a 100644 --- a/src/Commands/QueryLocalChanges.cs +++ b/src/Commands/QueryLocalChanges.cs @@ -38,121 +38,47 @@ public QueryLocalChanges(string repo, bool includeUntracked = true) var change = new Models.Change() { Path = match.Groups[2].Value }; var status = match.Groups[1].Value; - switch (status) + var index = status[0] switch { - case " M": - change.Set(Models.ChangeState.None, Models.ChangeState.Modified); - break; - case " T": - change.Set(Models.ChangeState.None, Models.ChangeState.TypeChanged); - break; - case " A": - change.Set(Models.ChangeState.None, Models.ChangeState.Added); - break; - case " D": - change.Set(Models.ChangeState.None, Models.ChangeState.Deleted); - break; - case " R": - change.Set(Models.ChangeState.None, Models.ChangeState.Renamed); - break; - case " C": - change.Set(Models.ChangeState.None, Models.ChangeState.Copied); - break; - case "M": - change.Set(Models.ChangeState.Modified); - break; - case "MM": - change.Set(Models.ChangeState.Modified, Models.ChangeState.Modified); - break; - case "MT": - change.Set(Models.ChangeState.Modified, Models.ChangeState.TypeChanged); - break; - case "MD": - change.Set(Models.ChangeState.Modified, Models.ChangeState.Deleted); - break; - case "T": - change.Set(Models.ChangeState.TypeChanged); - break; - case "TM": - change.Set(Models.ChangeState.TypeChanged, Models.ChangeState.Modified); - break; - case "TT": - change.Set(Models.ChangeState.TypeChanged, Models.ChangeState.TypeChanged); - break; - case "TD": - change.Set(Models.ChangeState.TypeChanged, Models.ChangeState.Deleted); - break; - case "A": - change.Set(Models.ChangeState.Added); - break; - case "AM": - change.Set(Models.ChangeState.Added, Models.ChangeState.Modified); - break; - case "AT": - change.Set(Models.ChangeState.Added, Models.ChangeState.TypeChanged); - break; - case "AD": - change.Set(Models.ChangeState.Added, Models.ChangeState.Deleted); - break; - case "D": - change.Set(Models.ChangeState.Deleted); - break; - case "R": - change.Set(Models.ChangeState.Renamed); - break; - case "RM": - change.Set(Models.ChangeState.Renamed, Models.ChangeState.Modified); - break; - case "RT": - change.Set(Models.ChangeState.Renamed, Models.ChangeState.TypeChanged); - break; - case "RD": - change.Set(Models.ChangeState.Renamed, Models.ChangeState.Deleted); - break; - case "C": - change.Set(Models.ChangeState.Copied); - break; - case "CM": - change.Set(Models.ChangeState.Copied, Models.ChangeState.Modified); - break; - case "CT": - change.Set(Models.ChangeState.Copied, Models.ChangeState.TypeChanged); - break; - case "CD": - change.Set(Models.ChangeState.Copied, Models.ChangeState.Deleted); - break; - case "DD": - change.ConflictReason = Models.ConflictReason.BothDeleted; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "AU": - change.ConflictReason = Models.ConflictReason.AddedByUs; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "UD": - change.ConflictReason = Models.ConflictReason.DeletedByThem; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "UA": - change.ConflictReason = Models.ConflictReason.AddedByThem; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "DU": - change.ConflictReason = Models.ConflictReason.DeletedByUs; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "AA": - change.ConflictReason = Models.ConflictReason.BothAdded; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "UU": - change.ConflictReason = Models.ConflictReason.BothModified; - change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); - break; - case "??": - change.Set(Models.ChangeState.None, Models.ChangeState.Untracked); - break; + 'M' => Models.ChangeState.Modified, + 'T' => Models.ChangeState.TypeChanged, + 'A' => Models.ChangeState.Added, + 'D' => Models.ChangeState.Deleted, + 'R' => Models.ChangeState.Renamed, + 'C' => Models.ChangeState.Copied, + 'U' => Models.ChangeState.Untracked, + _ => Models.ChangeState.None + }; + var workTree = Models.ChangeState.None; + if (status.Length > 1) + { + workTree = status[1] switch + { + 'M' => Models.ChangeState.Modified, + 'T' => Models.ChangeState.TypeChanged, + 'A' => Models.ChangeState.Added, + 'D' => Models.ChangeState.Deleted, + 'R' => Models.ChangeState.Renamed, + 'C' => Models.ChangeState.Copied, + 'U' or '?' => Models.ChangeState.Untracked, + _ => Models.ChangeState.None + }; } + change.ConflictReason = status switch + { + "DD" => Models.ConflictReason.BothDeleted, + "AU" => Models.ConflictReason.AddedByUs, + "UD" => Models.ConflictReason.DeletedByThem, + "UA" => Models.ConflictReason.AddedByThem, + "DU" => Models.ConflictReason.DeletedByUs, + "AA" => Models.ConflictReason.BothAdded, + "UU" => Models.ConflictReason.BothModified, + _ => Models.ConflictReason.None + }; + if (change.ConflictReason != Models.ConflictReason.None) + change.Set(Models.ChangeState.None, Models.ChangeState.Conflicted); + else + change.Set(index, workTree); if (change.Index != Models.ChangeState.None || change.WorkTree != Models.ChangeState.None) outs.Add(change); diff --git a/src/Commands/QueryStagedChangesWithAmend.cs b/src/Commands/QueryStagedChangesWithAmend.cs index bec033ff7..7c42b76b4 100644 --- a/src/Commands/QueryStagedChangesWithAmend.cs +++ b/src/Commands/QueryStagedChangesWithAmend.cs @@ -63,24 +63,17 @@ public QueryStagedChangesWithAmend(string repo, string parent) }; var type = match.Groups[3].Value; - switch (type) + var state = type switch { - case "A": - change.Set(Models.ChangeState.Added); - break; - case "C": - change.Set(Models.ChangeState.Copied); - break; - case "D": - change.Set(Models.ChangeState.Deleted); - break; - case "M": - change.Set(Models.ChangeState.Modified); - break; - case "T": - change.Set(Models.ChangeState.TypeChanged); - break; - } + "A" => Models.ChangeState.Added, + "C" => Models.ChangeState.Copied, + "D" => Models.ChangeState.Deleted, + "M" => Models.ChangeState.Modified, + "T" => Models.ChangeState.TypeChanged, + _ => Models.ChangeState.None + }; + if (state != Models.ChangeState.None) + change.Set(state); changes.Add(change); } } diff --git a/src/Commands/QuerySubmodules.cs b/src/Commands/QuerySubmodules.cs index 6063b3cf8..246be03da 100644 --- a/src/Commands/QuerySubmodules.cs +++ b/src/Commands/QuerySubmodules.cs @@ -40,22 +40,14 @@ public QuerySubmodules(string repo) var path = match.Groups[3].Value; var module = new Models.Submodule() { Path = path, SHA = sha }; - switch (stat[0]) + module.Status = stat[0] switch { - case '-': - module.Status = Models.SubmoduleStatus.NotInited; - break; - case '+': - module.Status = Models.SubmoduleStatus.RevisionChanged; - break; - case 'U': - module.Status = Models.SubmoduleStatus.Unmerged; - break; - default: - module.Status = Models.SubmoduleStatus.Normal; - needCheckLocalChanges = true; - break; - } + '-' => Models.SubmoduleStatus.NotInited, + '+' => Models.SubmoduleStatus.RevisionChanged, + 'U' => Models.SubmoduleStatus.Unmerged, + _ => Models.SubmoduleStatus.Normal + }; + needCheckLocalChanges = (module.Status == Models.SubmoduleStatus.Normal); map.Add(path, module); submodules.Add(module); diff --git a/src/Commands/SaveRevisionFile.cs b/src/Commands/SaveRevisionFile.cs index a3ca373f8..459bae841 100644 --- a/src/Commands/SaveRevisionFile.cs +++ b/src/Commands/SaveRevisionFile.cs @@ -45,10 +45,7 @@ private static async Task ExecCmdAsync(string repo, string args, string outputFi using var proc = Process.Start(starter); if (input != null) - { - var inputString = await new StreamReader(input).ReadToEndAsync().ConfigureAwait(false); - await proc.StandardInput.WriteAsync(inputString).ConfigureAwait(false); - } + await input.CopyToAsync(proc.StandardInput.BaseStream).ConfigureAwait(false); await proc.StandardOutput.BaseStream.CopyToAsync(sw).ConfigureAwait(false); await proc.WaitForExitAsync().ConfigureAwait(false); diff --git a/src/Commands/Stash.cs b/src/Commands/Stash.cs index ef8bbe087..fe6dded0a 100644 --- a/src/Commands/Stash.cs +++ b/src/Commands/Stash.cs @@ -59,8 +59,7 @@ public async Task PushOnlyStagedAsync(string message, bool keepIndex) builder.Append("stash push --staged "); if (keepIndex) builder.Append("--keep-index "); - builder.Append("-m ").Append(message.Quoted()); - Args = builder.ToString(); + Args = builder.Append("-m ").Append(message.Quoted()).ToString(); return await ExecAsync().ConfigureAwait(false); } diff --git a/src/Commands/Worktree.cs b/src/Commands/Worktree.cs index af03029f6..ac0fbbbb3 100644 --- a/src/Commands/Worktree.cs +++ b/src/Commands/Worktree.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using System.Threading.Tasks; namespace SourceGit.Commands @@ -59,25 +60,22 @@ public Worktree(string repo) public async Task AddAsync(string fullpath, string name, bool createNew, string tracking) { - Args = "worktree add "; + var builder = new StringBuilder("worktree add "); if (!string.IsNullOrEmpty(tracking)) - Args += "--track "; + builder.Append("--track "); if (!string.IsNullOrEmpty(name)) - { - if (createNew) - Args += $"-b {name} "; - else - Args += $"-B {name} "; - } + builder.Append(createNew ? "-b " : "-B ").Append(name).Append(' '); - Args += $"{fullpath.Quoted()} "; + builder.Append(fullpath.Quoted()); if (!string.IsNullOrEmpty(tracking)) - Args += tracking; + builder.Append(' ').Append(tracking); else if (!string.IsNullOrEmpty(name) && !createNew) - Args += name; + builder.Append(' ').Append(name); + + Args = builder.ToString(); return await ExecAsync().ConfigureAwait(false); } diff --git a/src/Models/Change.cs b/src/Models/Change.cs index 2ad448add..60e3e5101 100644 --- a/src/Models/Change.cs +++ b/src/Models/Change.cs @@ -73,10 +73,10 @@ public void Set(ChangeState index, ChangeState workTree = ChangeState.None) } if (Path[0] == '"') - Path = Path.Substring(1, Path.Length - 2); + Path = Path[1..^1]; if (!string.IsNullOrEmpty(OriginalPath) && OriginalPath[0] == '"') - OriginalPath = OriginalPath.Substring(1, OriginalPath.Length - 2); + OriginalPath = OriginalPath[1..^1]; } private static readonly string[] TYPE_DESCS = diff --git a/src/Models/ConventionalCommitType.cs b/src/Models/ConventionalCommitType.cs index 531a16c07..26b95b176 100644 --- a/src/Models/ConventionalCommitType.cs +++ b/src/Models/ConventionalCommitType.cs @@ -2,11 +2,11 @@ namespace SourceGit.Models { - public class ConventionalCommitType + public class ConventionalCommitType(string name, string type, string description) { - public string Name { get; set; } - public string Type { get; set; } - public string Description { get; set; } + public string Name { get; set; } = name; + public string Type { get; set; } = type; + public string Description { get; set; } = description; public static readonly List Supported = [ new("Features", "feat", "Adding a new feature"), @@ -22,12 +22,5 @@ public class ConventionalCommitType new("Tests", "test", "Adding or updating tests"), new("Chores", "chore", "Other changes that don't modify src or test files"), ]; - - public ConventionalCommitType(string name, string type, string description) - { - Name = name; - Type = type; - Description = description; - } } } diff --git a/src/Models/DiffOption.cs b/src/Models/DiffOption.cs index 2ecfe458f..b8d7583a0 100644 --- a/src/Models/DiffOption.cs +++ b/src/Models/DiffOption.cs @@ -100,13 +100,13 @@ public override string ToString() { var builder = new StringBuilder(); if (!string.IsNullOrEmpty(_extra)) - builder.Append($"{_extra} "); + builder.Append(_extra).Append(' '); foreach (var r in _revisions) - builder.Append($"{r} "); + builder.Append(r).Append(' '); builder.Append("-- "); if (!string.IsNullOrEmpty(_orgPath)) - builder.Append($"{_orgPath.Quoted()} "); + builder.Append(_orgPath.Quoted()).Append(' '); builder.Append(_path.Quoted()); return builder.ToString(); diff --git a/src/Models/Remote.cs b/src/Models/Remote.cs index 6e36cfb9e..499c4549b 100644 --- a/src/Models/Remote.cs +++ b/src/Models/Remote.cs @@ -63,7 +63,7 @@ public bool TryGetVisitURL(out string url) if (URL.StartsWith("http", StringComparison.Ordinal)) { // Try to remove the user before host and `.git` extension. - var uri = new Uri(URL.EndsWith(".git", StringComparison.Ordinal) ? URL.Substring(0, URL.Length - 4) : URL); + var uri = new Uri(URL.EndsWith(".git", StringComparison.Ordinal) ? URL[..^4] : URL); if (uri.Port != 80 && uri.Port != 443) url = $"{uri.Scheme}://{uri.Host}:{uri.Port}{uri.LocalPath}"; else diff --git a/src/Models/TemplateEngine.cs b/src/Models/TemplateEngine.cs index 87822fb11..486c81218 100644 --- a/src/Models/TemplateEngine.cs +++ b/src/Models/TemplateEngine.cs @@ -396,7 +396,7 @@ private static string GetFilesSliced(Context context, int count) sb.AppendJoin(", ", paths); if (max < context.changes.Count) - sb.Append($" and {context.changes.Count - max} other files"); + sb.Append(" and ").Append(context.changes.Count - max).Append(" other files"); return sb.ToString(); } diff --git a/src/Models/Watcher.cs b/src/Models/Watcher.cs index 9ba7ee9cb..a1bf65349 100644 --- a/src/Models/Watcher.cs +++ b/src/Models/Watcher.cs @@ -62,15 +62,10 @@ public Watcher(IRepository repo, string fullpath, string gitDir) public void SetEnabled(bool enabled) { - if (enabled) - { - if (_lockCount > 0) - _lockCount--; - } - else - { + if (!enabled) _lockCount++; - } + else if (_lockCount > 0) + _lockCount--; } public void SetSubmodules(List submodules) diff --git a/src/Resources/Locales/en_US.axaml b/src/Resources/Locales/en_US.axaml index 412aa4d69..f165abca6 100644 --- a/src/Resources/Locales/en_US.axaml +++ b/src/Resources/Locales/en_US.axaml @@ -145,7 +145,7 @@ AUTHOR CHILDREN COMMITTER - Check refs that contains this commit + Check refs that contain this commit COMMIT IS CONTAINED BY Shows only the first 100 changes. See all changes on the CHANGES tab. Key: @@ -500,7 +500,7 @@ {0} months ago {0} years ago Yesterday - Use 'Shift+Enter' to input a new line. 'Enter' is the hotkey of OK button + Use 'Shift+Enter' to input a new line. 'Enter' is the OK button hotkey Preferences AI Analyze Diff Prompt diff --git a/src/ViewModels/Clone.cs b/src/ViewModels/Clone.cs index b3aadb581..4e9bcc8c3 100644 --- a/src/ViewModels/Clone.cs +++ b/src/ViewModels/Clone.cs @@ -118,9 +118,9 @@ public override async Task Sure() { var name = Path.GetFileName(_remote)!; if (name.EndsWith(".git", StringComparison.Ordinal)) - name = name.Substring(0, name.Length - 4); + name = name[..^4]; else if (name.EndsWith(".bundle", StringComparison.Ordinal)) - name = name.Substring(0, name.Length - 7); + name = name[..^7]; path = Path.GetFullPath(Path.Combine(path, name)); } diff --git a/src/ViewModels/CreateBranch.cs b/src/ViewModels/CreateBranch.cs index c8d591d5b..afe42b1e9 100644 --- a/src/ViewModels/CreateBranch.cs +++ b/src/ViewModels/CreateBranch.cs @@ -206,7 +206,6 @@ public override async Task Sure() if (_repo.HistoriesFilterMode == Models.FilterMode.Included) _repo.SetBranchFilterMode(fake, Models.FilterMode.Included, true, false); - } _repo.MarkBranchesDirtyManually(); diff --git a/src/ViewModels/DeinitSubmodule.cs b/src/ViewModels/DeinitSubmodule.cs index 1769ef80c..4637b05c0 100644 --- a/src/ViewModels/DeinitSubmodule.cs +++ b/src/ViewModels/DeinitSubmodule.cs @@ -2,13 +2,12 @@ namespace SourceGit.ViewModels { - public class DeinitSubmodule : Popup + public class DeinitSubmodule(Repository repo, string submodule) : Popup { public string Submodule { get; - private set; - } + } = submodule; public bool Force { @@ -16,30 +15,21 @@ public bool Force set; } - public DeinitSubmodule(Repository repo, string submodule) - { - _repo = repo; - Submodule = submodule; - Force = false; - } - public override async Task Sure() { - _repo.SetWatcherEnabled(false); + repo.SetWatcherEnabled(false); ProgressDescription = "De-initialize Submodule"; - var log = _repo.CreateLog("De-initialize Submodule"); + var log = repo.CreateLog("De-initialize Submodule"); Use(log); - var succ = await new Commands.Submodule(_repo.FullPath) + var succ = await new Commands.Submodule(repo.FullPath) .Use(log) .DeinitAsync(Submodule, false); log.Complete(); - _repo.SetWatcherEnabled(true); + repo.SetWatcherEnabled(true); return succ; } - - private Repository _repo; } } diff --git a/src/ViewModels/Pull.cs b/src/ViewModels/Pull.cs index 9372f309f..8b22f614d 100644 --- a/src/ViewModels/Pull.cs +++ b/src/ViewModels/Pull.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; @@ -181,7 +182,7 @@ private void PostRemoteSelected() var autoSelectedBranch = false; if (!string.IsNullOrEmpty(Current.Upstream) && - Current.Upstream.StartsWith($"refs/remotes/{remoteName}/", System.StringComparison.Ordinal)) + Current.Upstream.StartsWith($"refs/remotes/{remoteName}/", StringComparison.Ordinal)) { foreach (var branch in branches) { diff --git a/src/ViewModels/Rebase.cs b/src/ViewModels/Rebase.cs index 1727bc868..025a90f43 100644 --- a/src/ViewModels/Rebase.cs +++ b/src/ViewModels/Rebase.cs @@ -20,7 +20,7 @@ public bool AutoStash { get; set; - } + } = true; public Rebase(Repository repo, Models.Branch current, Models.Branch on) { @@ -28,7 +28,6 @@ public Rebase(Repository repo, Models.Branch current, Models.Branch on) _revision = on.Head; Current = current; On = on; - AutoStash = true; } public Rebase(Repository repo, Models.Branch current, Models.Commit on) @@ -37,7 +36,6 @@ public Rebase(Repository repo, Models.Branch current, Models.Commit on) _revision = on.SHA; Current = current; On = on; - AutoStash = true; } public override async Task Sure() diff --git a/src/ViewModels/Repository.cs b/src/ViewModels/Repository.cs index e51347457..ca5b5e22a 100644 --- a/src/ViewModels/Repository.cs +++ b/src/ViewModels/Repository.cs @@ -1044,15 +1044,10 @@ public void UpdateBranchNodeIsExpanded(BranchTreeNode node) if (_settings == null || !string.IsNullOrWhiteSpace(_filter)) return; - if (node.IsExpanded) - { - if (!_settings.ExpandedBranchNodesInSideBar.Contains(node.Path)) - _settings.ExpandedBranchNodesInSideBar.Add(node.Path); - } - else - { + if (!node.IsExpanded) _settings.ExpandedBranchNodesInSideBar.Remove(node.Path); - } + else if (!_settings.ExpandedBranchNodesInSideBar.Contains(node.Path)) + _settings.ExpandedBranchNodesInSideBar.Add(node.Path); } public void SetTagFilterMode(Models.Tag tag, Models.FilterMode mode) @@ -1249,7 +1244,7 @@ public void RefreshCommits() Dispatcher.UIThread.Invoke(() => _histories.IsLoading = true); var builder = new StringBuilder(); - builder.Append($"-{Preferences.Instance.MaxHistoryCommits} "); + builder.Append('-').Append(Preferences.Instance.MaxHistoryCommits).Append(' '); if (_settings.EnableTopoOrderInHistories) builder.Append("--topo-order "); diff --git a/src/ViewModels/RepositoryConfigure.cs b/src/ViewModels/RepositoryConfigure.cs index 4bf5731f2..5838b9643 100644 --- a/src/ViewModels/RepositoryConfigure.cs +++ b/src/ViewModels/RepositoryConfigure.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading.Tasks; using Avalonia.Collections; @@ -202,7 +203,7 @@ public void AddSampleGitHubIssueTracker() var link = "https://github.com/username/repository/issues/$1"; foreach (var remote in _repo.Remotes) { - if (remote.URL.Contains("github.com", System.StringComparison.Ordinal) && + if (remote.URL.Contains("github.com", StringComparison.Ordinal) && remote.TryGetVisitURL(out string url)) { link = $"{url}/issues/$1"; @@ -258,7 +259,7 @@ public void AddSampleGiteeIssueTracker() var link = "https://gitee.com/username/repository/issues/$1"; foreach (var remote in _repo.Remotes) { - if (remote.URL.Contains("gitee.com", System.StringComparison.Ordinal) && + if (remote.URL.Contains("gitee.com", StringComparison.Ordinal) && remote.TryGetVisitURL(out string url)) { link = $"{url}/issues/$1"; @@ -274,7 +275,7 @@ public void AddSampleGiteePullRequestTracker() var link = "https://gitee.com/username/repository/pulls/$1"; foreach (var remote in _repo.Remotes) { - if (remote.URL.Contains("gitee.com", System.StringComparison.Ordinal) && + if (remote.URL.Contains("gitee.com", StringComparison.Ordinal) && remote.TryGetVisitURL(out string url)) { link = $"{url}/pulls/$1"; diff --git a/src/Views/BisectStateIndicator.cs b/src/Views/BisectStateIndicator.cs index 0a581f532..e8c2fc9c9 100644 --- a/src/Views/BisectStateIndicator.cs +++ b/src/Views/BisectStateIndicator.cs @@ -106,7 +106,7 @@ private Geometry LoadIcon(string key) var drawGeo = geo!.Clone(); var iconBounds = drawGeo.Bounds; var translation = Matrix.CreateTranslation(-(Vector)iconBounds.Position); - var scale = Math.Min(10.0 / iconBounds.Width, 10.0 / iconBounds.Height); + var scale = 10.0 / Math.Max(iconBounds.Width, iconBounds.Height); var transform = translation * Matrix.CreateScale(scale, scale); if (drawGeo.Transform == null || drawGeo.Transform.Value == Matrix.Identity) drawGeo.Transform = new MatrixTransform(transform); diff --git a/src/Views/CommitMessagePresenter.cs b/src/Views/CommitMessagePresenter.cs index ea1b98f27..4d82584d0 100644 --- a/src/Views/CommitMessagePresenter.cs +++ b/src/Views/CommitMessagePresenter.cs @@ -91,8 +91,8 @@ protected override void OnPointerMoved(PointerEventArgs e) else if (FullMessage is { Inlines: { Count: > 0 } links }) { var point = e.GetPosition(this) - new Point(Padding.Left, Padding.Top); - var x = Math.Min(Math.Max(point.X, 0), Math.Max(TextLayout.WidthIncludingTrailingWhitespace, 0)); - var y = Math.Min(Math.Max(point.Y, 0), Math.Max(TextLayout.Height, 0)); + var x = Math.Clamp(point.X, 0, TextLayout.WidthIncludingTrailingWhitespace); + var y = Math.Clamp(point.Y, 0, TextLayout.Height); point = new Point(x, y); var pos = TextLayout.HitTestPoint(point).TextPosition; @@ -195,8 +195,8 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) } var position = e.GetPosition(this) - new Point(Padding.Left, Padding.Top); - var x = Math.Min(Math.Max(position.X, 0), Math.Max(TextLayout.WidthIncludingTrailingWhitespace, 0)); - var y = Math.Min(Math.Max(position.Y, 0), Math.Max(TextLayout.Height, 0)); + var x = Math.Clamp(position.X, 0, TextLayout.WidthIncludingTrailingWhitespace); + var y = Math.Clamp(position.Y, 0, TextLayout.Height); position = new Point(x, y); var textPos = TextLayout.HitTestPoint(position).TextPosition; diff --git a/src/Views/CommitRefsPresenter.cs b/src/Views/CommitRefsPresenter.cs index d221c155a..0e096eb77 100644 --- a/src/Views/CommitRefsPresenter.cs +++ b/src/Views/CommitRefsPresenter.cs @@ -235,7 +235,7 @@ protected override Size MeasureOverride(Size availableSize) var drawGeo = geo!.Clone(); var iconBounds = drawGeo.Bounds; var translation = Matrix.CreateTranslation(-(Vector)iconBounds.Position); - var scale = Math.Min(10.0 / iconBounds.Width, 10.0 / iconBounds.Height); + var scale = 10.0 / Math.Max(iconBounds.Width, iconBounds.Height); var transform = translation * Matrix.CreateScale(scale, scale); if (drawGeo.Transform == null || drawGeo.Transform.Value == Matrix.Identity) drawGeo.Transform = new MatrixTransform(transform); diff --git a/src/Views/ConventionalCommitMessageBuilder.axaml.cs b/src/Views/ConventionalCommitMessageBuilder.axaml.cs index 3f2c7f394..e3ddb40f7 100644 --- a/src/Views/ConventionalCommitMessageBuilder.axaml.cs +++ b/src/Views/ConventionalCommitMessageBuilder.axaml.cs @@ -12,11 +12,8 @@ public ConventionalCommitMessageBuilder() private void OnApplyClicked(object _, RoutedEventArgs e) { - if (DataContext is ViewModels.ConventionalCommitMessageBuilder builder) - { - if (builder.Apply()) - Close(); - } + if (DataContext is ViewModels.ConventionalCommitMessageBuilder builder && builder.Apply()) + Close(); e.Handled = true; } diff --git a/src/Views/DirHistories.axaml.cs b/src/Views/DirHistories.axaml.cs index c25e545c9..3e26cd7ee 100644 --- a/src/Views/DirHistories.axaml.cs +++ b/src/Views/DirHistories.axaml.cs @@ -40,5 +40,3 @@ private void OnCommitSubjectPointerMoved(object sender, PointerEventArgs e) } } } - - diff --git a/src/Views/InteractiveRebase.axaml.cs b/src/Views/InteractiveRebase.axaml.cs index 33148113d..b4504f0d6 100644 --- a/src/Views/InteractiveRebase.axaml.cs +++ b/src/Views/InteractiveRebase.axaml.cs @@ -29,32 +29,17 @@ protected override void OnKeyDown(KeyEventArgs e) return; } - if (e.Key == Key.P) + var action = e.Key switch { - vm.ChangeAction(item, Models.InteractiveRebaseAction.Pick); - e.Handled = true; - } - else if (e.Key == Key.E) - { - vm.ChangeAction(item, Models.InteractiveRebaseAction.Edit); - e.Handled = true; - } - else if (e.Key == Key.R) - { - vm.ChangeAction(item, Models.InteractiveRebaseAction.Reword); - e.Handled = true; - } - else if (e.Key == Key.S) - { - vm.ChangeAction(item, Models.InteractiveRebaseAction.Squash); - e.Handled = true; - } - else if (e.Key == Key.F) - { - vm.ChangeAction(item, Models.InteractiveRebaseAction.Fixup); - e.Handled = true; - } - else if (e.Key == Key.D) + Key.P => Models.InteractiveRebaseAction.Pick, + Key.E => Models.InteractiveRebaseAction.Edit, + Key.R => Models.InteractiveRebaseAction.Reword, + Key.S => Models.InteractiveRebaseAction.Squash, + Key.F => Models.InteractiveRebaseAction.Fixup, + Key.D => Models.InteractiveRebaseAction.Drop, + _ => default(Models.InteractiveRebaseAction?) + }; + if (action != null) { vm.ChangeAction(item, Models.InteractiveRebaseAction.Drop); e.Handled = true; diff --git a/src/Views/Launcher.axaml.cs b/src/Views/Launcher.axaml.cs index 52ddd12ef..5853cf823 100644 --- a/src/Views/Launcher.axaml.cs +++ b/src/Views/Launcher.axaml.cs @@ -162,7 +162,7 @@ protected override async void OnKeyDown(KeyEventArgs e) return; } - // Ctrl+, opens preference dialog (macOS use hotkeys in system menu bar) + // Ctrl+, opens preference dialog (on macOS use hotkeys in system menu bar) if (!OperatingSystem.IsMacOS() && e is { KeyModifiers: KeyModifiers.Control, Key: Key.OemComma }) { await App.ShowDialog(new Preferences()); @@ -170,14 +170,14 @@ protected override async void OnKeyDown(KeyEventArgs e) return; } - // F1 opens preference dialog (macOS use hotkeys in system menu bar) + // F1 opens preference dialog (on macOS use hotkeys in system menu bar) if (!OperatingSystem.IsMacOS() && e.Key == Key.F1) { await App.ShowDialog(new Hotkeys()); return; } - // Ctrl+Q quits the application (macOS use hotkeys in system menu bar) + // Ctrl+Q quits the application (on macOS use hotkeys in system menu bar) if (!OperatingSystem.IsMacOS() && e is { KeyModifiers: KeyModifiers.Control, Key: Key.Q }) { App.Quit(0); diff --git a/src/Views/Reset.axaml.cs b/src/Views/Reset.axaml.cs index 8c3805385..801603e22 100644 --- a/src/Views/Reset.axaml.cs +++ b/src/Views/Reset.axaml.cs @@ -1,3 +1,4 @@ +using System; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; @@ -25,7 +26,7 @@ private void OnResetModeKeyDown(object sender, KeyEventArgs e) var key = e.Key.ToString(); for (int i = 0; i < Models.ResetMode.Supported.Length; i++) { - if (key.Equals(Models.ResetMode.Supported[i].Key, System.StringComparison.OrdinalIgnoreCase)) + if (key.Equals(Models.ResetMode.Supported[i].Key, StringComparison.OrdinalIgnoreCase)) { comboBox.SelectedIndex = i; e.Handled = true; diff --git a/src/Views/SetSubmoduleBranch.axaml.cs b/src/Views/SetSubmoduleBranch.axaml.cs index ecc06b2a7..7e2e3014d 100644 --- a/src/Views/SetSubmoduleBranch.axaml.cs +++ b/src/Views/SetSubmoduleBranch.axaml.cs @@ -10,4 +10,3 @@ public SetSubmoduleBranch() } } } - diff --git a/src/Views/TextDiffView.axaml.cs b/src/Views/TextDiffView.axaml.cs index 6b65dba29..02d506af8 100644 --- a/src/Views/TextDiffView.axaml.cs +++ b/src/Views/TextDiffView.axaml.cs @@ -1231,7 +1231,7 @@ protected override void OnDataContextChanged(EventArgs e) if (line.Content.Length > 10000) { builder.Append(line.Content.AsSpan(0, 1000)); - builder.Append($"...({line.Content.Length - 1000} character trimmed)"); + builder.Append("...(").Append(line.Content.Length - 1000).Append(" character trimmed)"); } else { @@ -1472,7 +1472,7 @@ protected override void OnDataContextChanged(EventArgs e) if (line.Content.Length > 1000) { builder.Append(line.Content.AsSpan(0, 1000)); - builder.Append($"...({line.Content.Length - 1000} characters trimmed)"); + builder.Append("...(").Append(line.Content.Length - 1000).Append(" characters trimmed)"); } else {