diff --git a/src/App.Commands.cs b/src/App.Commands.cs index d82a45bcf..f26919c73 100644 --- a/src/App.Commands.cs +++ b/src/App.Commands.cs @@ -45,8 +45,7 @@ public static bool IsCheckForUpdateCommandVisible public static readonly Command QuitCommand = new Command(_ => Quit(0)); public static readonly Command CopyTextBlockCommand = new Command(async p => { - var textBlock = p as TextBlock; - if (textBlock == null) + if (p is not TextBlock textBlock) return; if (textBlock.Inlines is { Count: > 0 } inlines) diff --git a/src/App.axaml.cs b/src/App.axaml.cs index 5d527dd38..cc93777b4 100644 --- a/src/App.axaml.cs +++ b/src/App.axaml.cs @@ -186,9 +186,7 @@ public static void SendNotification(string context, string message) public static void SetLocale(string localeKey) { - var app = Current as App; - var targetLocale = app?.Resources[localeKey] as ResourceDictionary; - if (targetLocale == null || targetLocale == app._activeLocale) + if (Current is not App app || app.Resources[localeKey] is not ResourceDictionary targetLocale || targetLocale == app._activeLocale) return; if (app._activeLocale != null) @@ -200,8 +198,7 @@ public static void SetLocale(string localeKey) public static void SetTheme(string theme, string themeOverridesFile) { - var app = Current as App; - if (app == null) + if (Current is not App app) return; if (theme.Equals("Light", StringComparison.OrdinalIgnoreCase)) @@ -254,8 +251,7 @@ public static void SetTheme(string theme, string themeOverridesFile) public static void SetFonts(string defaultFont, string monospaceFont, bool onlyUseMonospaceFontInEditor) { - var app = Current as App; - if (app == null) + if (Current is not App app) return; if (app._fontsOverrides != null) diff --git a/src/Commands/Blame.cs b/src/Commands/Blame.cs index aadbb2dbb..0d55a051c 100644 --- a/src/Commands/Blame.cs +++ b/src/Commands/Blame.cs @@ -40,9 +40,7 @@ public Blame(string repo, string file, string revision) foreach (var line in _result.LineInfos) { if (line.CommitSHA.Length > _minSHALen) - { line.CommitSHA = line.CommitSHA.Substring(0, _minSHALen); - } } } diff --git a/src/Commands/Command.cs b/src/Commands/Command.cs index 24ebdbb67..12fcb72fc 100644 --- a/src/Commands/Command.cs +++ b/src/Commands/Command.cs @@ -131,9 +131,9 @@ protected async Task ReadToEndAsync() } var rs = new Result() { IsSuccess = true }; - rs.StdOut = await proc.StandardOutput.ReadToEndAsync().ConfigureAwait(false); - rs.StdErr = await proc.StandardError.ReadToEndAsync().ConfigureAwait(false); - await proc.WaitForExitAsync().ConfigureAwait(false); + rs.StdOut = await proc.StandardOutput.ReadToEndAsync(CancellationToken).ConfigureAwait(false); + rs.StdErr = await proc.StandardError.ReadToEndAsync(CancellationToken).ConfigureAwait(false); + await proc.WaitForExitAsync(CancellationToken).ConfigureAwait(false); rs.IsSuccess = proc.ExitCode == 0; proc.Close(); diff --git a/src/Commands/Diff.cs b/src/Commands/Diff.cs index 0279f56fc..c4785e18f 100644 --- a/src/Commands/Diff.cs +++ b/src/Commands/Diff.cs @@ -249,14 +249,10 @@ private void ProcessInlineHighlights() foreach (var chunk in chunks) { if (chunk.DeletedCount > 0) - { left.Highlights.Add(new Models.TextInlineRange(chunk.DeletedStart, chunk.DeletedCount)); - } if (chunk.AddedCount > 0) - { right.Highlights.Add(new Models.TextInlineRange(chunk.AddedStart, chunk.AddedCount)); - } } } } diff --git a/src/Commands/QueryCommits.cs b/src/Commands/QueryCommits.cs index 5e7ef4e63..6391ff151 100644 --- a/src/Commands/QueryCommits.cs +++ b/src/Commands/QueryCommits.cs @@ -121,7 +121,7 @@ private void ParseParent(string data) if (data.Length < 8) return; - _current.Parents.AddRange(data.Split(separator: ' ', options: StringSplitOptions.RemoveEmptyEntries)); + _current.Parents.AddRange(data.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } private async Task MarkFirstMergedAsync() @@ -133,9 +133,7 @@ private async Task MarkFirstMergedAsync() if (shas.Length == 0) return; - var set = new HashSet(); - foreach (var sha in shas) - set.Add(sha); + var set = new HashSet(shas); foreach (var c in _commits) { diff --git a/src/Commands/QueryCommitsForInteractiveRebase.cs b/src/Commands/QueryCommitsForInteractiveRebase.cs index 0093d136b..81e28d4fc 100644 --- a/src/Commands/QueryCommitsForInteractiveRebase.cs +++ b/src/Commands/QueryCommitsForInteractiveRebase.cs @@ -86,7 +86,7 @@ private void ParseParent(string data) if (data.Length < 8) return; - _current.Commit.Parents.AddRange(data.Split(separator: ' ', options: StringSplitOptions.RemoveEmptyEntries)); + _current.Commit.Parents.AddRange(data.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } private List _commits = []; diff --git a/src/Commands/Submodule.cs b/src/Commands/Submodule.cs index 81c8140e0..2c0d71479 100644 --- a/src/Commands/Submodule.cs +++ b/src/Commands/Submodule.cs @@ -21,15 +21,10 @@ public async Task AddAsync(string url, string relativePath, bool recursive return false; if (recursive) - { Args = $"submodule update --init --recursive -- \"{relativePath}\""; - return await ExecAsync().ConfigureAwait(false); - } else - { Args = $"submodule update --init -- \"{relativePath}\""; - return await ExecAsync().ConfigureAwait(false); - } + return await ExecAsync().ConfigureAwait(false); } public async Task SetURL(string path, string url) diff --git a/src/Models/ApplyWhiteSpaceMode.cs b/src/Models/ApplyWhiteSpaceMode.cs index aad45f577..9bcd04b3d 100644 --- a/src/Models/ApplyWhiteSpaceMode.cs +++ b/src/Models/ApplyWhiteSpaceMode.cs @@ -1,6 +1,6 @@ namespace SourceGit.Models { - public class ApplyWhiteSpaceMode + public class ApplyWhiteSpaceMode(string n, string d, string a) { public static readonly ApplyWhiteSpaceMode[] Supported = [ @@ -10,15 +10,8 @@ public class ApplyWhiteSpaceMode new ApplyWhiteSpaceMode("Error All", "Similar to 'error', but shows more", "error-all"), ]; - public string Name { get; set; } - public string Desc { get; set; } - public string Arg { get; set; } - - public ApplyWhiteSpaceMode(string n, string d, string a) - { - Name = n; - Desc = d; - Arg = a; - } + public string Name { get; set; } = n; + public string Desc { get; set; } = d; + public string Arg { get; set; } = a; } } diff --git a/src/Models/AvatarManager.cs b/src/Models/AvatarManager.cs index 132e6f208..06c205e49 100644 --- a/src/Models/AvatarManager.cs +++ b/src/Models/AvatarManager.cs @@ -197,7 +197,10 @@ public void SetFromLocal(string email, string file) _resources[email] = image; - _requesting.Remove(email); + lock (_synclock) + { + _requesting.Remove(email); + } var store = Path.Combine(_storePath, GetEmailHash(email)); File.Copy(file, store, true); diff --git a/src/Models/CRLFMode.cs b/src/Models/CRLFMode.cs index 3f510f00c..46f5442f8 100644 --- a/src/Models/CRLFMode.cs +++ b/src/Models/CRLFMode.cs @@ -2,23 +2,16 @@ namespace SourceGit.Models { - public class CRLFMode + public class CRLFMode(string name, string value, string desc) { - public string Name { get; set; } - public string Value { get; set; } - public string Desc { get; set; } + public string Name { get; set; } = name; + public string Value { get; set; } = value; + public string Desc { get; set; } = desc; public static readonly List Supported = new List() { new CRLFMode("TRUE", "true", "Commit as LF, checkout as CRLF"), new CRLFMode("INPUT", "input", "Only convert for commit"), new CRLFMode("FALSE", "false", "Do NOT convert"), }; - - public CRLFMode(string name, string value, string desc) - { - Name = name; - Value = value; - Desc = desc; - } } } diff --git a/src/Models/DiffOption.cs b/src/Models/DiffOption.cs index 69f939800..fe32528cf 100644 --- a/src/Models/DiffOption.cs +++ b/src/Models/DiffOption.cs @@ -29,6 +29,8 @@ public DiffOption(Change change, bool isUnstaged) { _workingCopyChange = change; _isUnstaged = isUnstaged; + _path = change.Path; + _orgPath = change.OriginalPath; if (isUnstaged) { @@ -37,13 +39,8 @@ public DiffOption(Change change, bool isUnstaged) case ChangeState.Added: case ChangeState.Untracked: _extra = "--no-index"; - _path = change.Path; _orgPath = "/dev/null"; break; - default: - _path = change.Path; - _orgPath = change.OriginalPath; - break; } } else @@ -52,9 +49,6 @@ public DiffOption(Change change, bool isUnstaged) _extra = $"--cached {change.DataForAmend.ParentSHA}"; else _extra = "--cached"; - - _path = change.Path; - _orgPath = change.OriginalPath; } } diff --git a/src/Models/DiffResult.cs b/src/Models/DiffResult.cs index 429d24e05..95ffa99f1 100644 --- a/src/Models/DiffResult.cs +++ b/src/Models/DiffResult.cs @@ -210,21 +210,12 @@ public void GeneratePatchFromSelection(Change change, string fileTreeGuid, TextD var line = Lines[i]; if (line.Type == TextDiffLineType.Indicator) break; - if (revert) - { - if (line.Type == TextDiffLineType.Normal || line.Type == TextDiffLineType.Added) - { - tail = line.Content; - break; - } - } - else + if (line.Type == TextDiffLineType.Normal || + (revert && line.Type == TextDiffLineType.Added) || + (!revert && line.Type == TextDiffLineType.Deleted)) { - if (line.Type == TextDiffLineType.Normal || line.Type == TextDiffLineType.Deleted) - { - tail = line.Content; - break; - } + tail = line.Content; + break; } } } @@ -290,9 +281,7 @@ public void GeneratePatchFromSelection(Change change, string fileTreeGuid, TextD if (line.Type == TextDiffLineType.Indicator) { if (!ProcessIndicatorForPatch(writer, line, i, selection.StartLine, selection.EndLine, selection.IgnoredDeletes, selection.IgnoredAdds, revert, tail != null)) - { break; - } } else if (line.Type == TextDiffLineType.Normal) { @@ -414,9 +403,7 @@ public void GeneratePatchFromSelectionSingleSide(Change change, string fileTreeG if (line.Type == TextDiffLineType.Indicator) { if (!ProcessIndicatorForPatchSingleSide(writer, line, i, selection.StartLine, selection.EndLine, selection.IgnoredDeletes, selection.IgnoredAdds, revert, isOldSide, tail != null)) - { break; - } } else if (line.Type == TextDiffLineType.Normal) { diff --git a/src/Models/ExternalMerger.cs b/src/Models/ExternalMerger.cs index 815220df8..ddd0aa011 100644 --- a/src/Models/ExternalMerger.cs +++ b/src/Models/ExternalMerger.cs @@ -93,9 +93,7 @@ public ExternalMerger(int type, string icon, string name, string exec, string cm public string[] GetPatterns() { if (OperatingSystem.IsWindows()) - { return Exec.Split(';'); - } var choices = Exec.Split(';', StringSplitOptions.RemoveEmptyEntries); return Array.ConvertAll(choices, Path.GetFileName); diff --git a/src/Models/MergeMode.cs b/src/Models/MergeMode.cs index fdb26b51b..a217514e1 100644 --- a/src/Models/MergeMode.cs +++ b/src/Models/MergeMode.cs @@ -1,6 +1,6 @@ namespace SourceGit.Models { - public class MergeMode + public class MergeMode(string n, string d, string a) { public static readonly MergeMode Default = new MergeMode("Default", "Fast-forward if possible", ""); @@ -26,15 +26,8 @@ public static readonly MergeMode DontCommit DontCommit, ]; - public string Name { get; set; } - public string Desc { get; set; } - public string Arg { get; set; } - - public MergeMode(string n, string d, string a) - { - Name = n; - Desc = d; - Arg = a; - } + public string Name { get; set; } = n; + public string Desc { get; set; } = d; + public string Arg { get; set; } = a; } } diff --git a/src/Models/ResetMode.cs b/src/Models/ResetMode.cs index 827ccaa97..1c84dc8e0 100644 --- a/src/Models/ResetMode.cs +++ b/src/Models/ResetMode.cs @@ -2,7 +2,7 @@ namespace SourceGit.Models { - public class ResetMode + public class ResetMode(string n, string d, string a, string k, IBrush b) { public static readonly ResetMode[] Supported = [ @@ -13,19 +13,10 @@ public class ResetMode new ResetMode("Hard", "Discard all changes", "--hard", "H", Brushes.Red), ]; - public string Name { get; set; } - public string Desc { get; set; } - public string Arg { get; set; } - public string Key { get; set; } - public IBrush Color { get; set; } - - public ResetMode(string n, string d, string a, string k, IBrush b) - { - Name = n; - Desc = d; - Arg = a; - Key = k; - Color = b; - } + public string Name { get; set; } = n; + public string Desc { get; set; } = d; + public string Arg { get; set; } = a; + public string Key { get; set; } = k; + public IBrush Color { get; set; } = b; } } diff --git a/src/Models/TemplateEngine.cs b/src/Models/TemplateEngine.cs index 8f60bd74d..c2ce28b26 100644 --- a/src/Models/TemplateEngine.cs +++ b/src/Models/TemplateEngine.cs @@ -88,9 +88,7 @@ private void Reset() { var c = Peek(); if (c is not null) - { _pos++; - } return c; } @@ -129,7 +127,7 @@ private void Parse() { case ESCAPE: // allow to escape only \ and $ - if (Peek() is { } nc && (nc == ESCAPE || nc == VARIABLE_ANCHOR)) + if (Peek() is ESCAPE or VARIABLE_ANCHOR) { esc = true; FlushText(tok, _pos - 1); @@ -320,9 +318,7 @@ private static bool IsNameChar(char c) private static string EvalVariable(Context context, string name) { if (!s_variables.TryGetValue(name, out var getter)) - { return string.Empty; - } return getter(context); } @@ -334,9 +330,7 @@ private static string EvalVariable(Context context, Variable variable) private static string EvalVariable(Context context, SlicedVariable variable) { if (!s_slicedVariables.TryGetValue(variable.name, out var getter)) - { return string.Empty; - } return getter(context, variable.count); } diff --git a/src/Models/TextInlineChange.cs b/src/Models/TextInlineChange.cs index 81c26412d..bc1873e25 100644 --- a/src/Models/TextInlineChange.cs +++ b/src/Models/TextInlineChange.cs @@ -295,16 +295,12 @@ private static EditResult CheckModifiedEdit(List chunksOld, int startOld, private static void AddChunk(List chunks, Dictionary hashes, string data, int start) { - if (hashes.TryGetValue(data, out var hash)) - { - chunks.Add(new Chunk(hash, start, data.Length)); - } - else + if (!hashes.TryGetValue(data, out var hash)) { hash = hashes.Count; hashes.Add(data, hash); - chunks.Add(new Chunk(hash, start, data.Length)); } + chunks.Add(new Chunk(hash, start, data.Length)); } } } diff --git a/src/Models/TextMateHelper.cs b/src/Models/TextMateHelper.cs index b7efae72c..e9903890b 100644 --- a/src/Models/TextMateHelper.cs +++ b/src/Models/TextMateHelper.cs @@ -33,7 +33,7 @@ public static string GetScope(string file, RegistryOptions reg) var extension = Path.GetExtension(file); if (extension == ".h") extension = ".cpp"; - else if (extension == ".resx" || extension == ".plist" || extension == ".manifest") + else if (extension is ".resx" or ".plist" or ".manifest") extension = ".xml"; else if (extension == ".command") extension = ".sh"; diff --git a/src/Native/Windows.cs b/src/Native/Windows.cs index caccc5e3c..22eaeb59f 100644 --- a/src/Native/Windows.cs +++ b/src/Native/Windows.cs @@ -67,7 +67,7 @@ public void SetupWindow(Window window) window.ExtendClientAreaToDecorationsHint = true; window.Classes.Add("fix_maximized_padding"); - Win32Properties.AddWndProcHookCallback(window, (IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, ref bool handled) => + Win32Properties.AddWndProcHookCallback(window, (IntPtr hWnd, uint msg, IntPtr _, IntPtr lParam, ref bool handled) => { // Custom WM_NCHITTEST if (msg == 0x0084) diff --git a/src/ViewModels/AddWorktree.cs b/src/ViewModels/AddWorktree.cs index 3e6df1bb7..3c3d69ff5 100644 --- a/src/ViewModels/AddWorktree.cs +++ b/src/ViewModels/AddWorktree.cs @@ -82,8 +82,7 @@ public AddWorktree(Repository repo) public static ValidationResult ValidateWorktreePath(string path, ValidationContext ctx) { - var creator = ctx.ObjectInstance as AddWorktree; - if (creator == null) + if (ctx.ObjectInstance is not AddWorktree creator) return new ValidationResult("Missing runtime context to create branch!"); if (string.IsNullOrEmpty(path)) diff --git a/src/ViewModels/BlockNavigation.cs b/src/ViewModels/BlockNavigation.cs index 9a5a926c8..4a51244cb 100644 --- a/src/ViewModels/BlockNavigation.cs +++ b/src/ViewModels/BlockNavigation.cs @@ -70,9 +70,7 @@ public BlockNavigation(object context) foreach (var line in lines) { lineIdx++; - if (line.Type == Models.TextDiffLineType.Added || - line.Type == Models.TextDiffLineType.Deleted || - line.Type == Models.TextDiffLineType.None) + if (line.Type is Models.TextDiffLineType.Added or Models.TextDiffLineType.Deleted or Models.TextDiffLineType.None) { if (isNewBlock) { diff --git a/src/ViewModels/BranchCompare.cs b/src/ViewModels/BranchCompare.cs index 9db87c940..522e2a8cd 100644 --- a/src/ViewModels/BranchCompare.cs +++ b/src/ViewModels/BranchCompare.cs @@ -63,9 +63,7 @@ public string SearchFilter set { if (SetProperty(ref _searchFilter, value)) - { RefreshVisible(); - } } } @@ -127,13 +125,13 @@ public ContextMenu CreateChangeContextMenu() var diffWithMerger = new MenuItem(); diffWithMerger.Header = App.Text("DiffWithMerger"); diffWithMerger.Icon = App.CreateMenuIcon("Icons.OpenWith"); - diffWithMerger.Click += (_, ev) => + diffWithMerger.Click += async (_, ev) => { var toolType = Preferences.Instance.ExternalMergeToolType; var toolPath = Preferences.Instance.ExternalMergeToolPath; var opt = new Models.DiffOption(_based.Head, _to.Head, change); - _ = Commands.MergeTool.OpenForDiffAsync(_repo, toolType, toolPath, opt); + await Commands.MergeTool.OpenForDiffAsync(_repo, toolType, toolPath, opt); ev.Handled = true; }; menu.Items.Add(diffWithMerger); diff --git a/src/ViewModels/Checkout.cs b/src/ViewModels/Checkout.cs index 6df97c05a..1b8df6827 100644 --- a/src/ViewModels/Checkout.cs +++ b/src/ViewModels/Checkout.cs @@ -41,10 +41,6 @@ public override async Task Sure() var log = _repo.CreateLog($"Checkout '{Branch}'"); Use(log); - var updateSubmodules = IsRecurseSubmoduleVisible && RecurseSubmodules; - var succ = false; - var needPopStash = false; - if (_repo.CurrentBranch is { IsDetachedHead: true }) { var refs = await new Commands.QueryRefsContainsCommit(_repo.FullPath, _repo.CurrentBranch.Head).GetResultAsync(); @@ -60,6 +56,9 @@ public override async Task Sure() } } + var succ = false; + var needPopStash = false; + if (DiscardLocalChanges) { succ = await new Commands.Checkout(_repo.FullPath) @@ -91,7 +90,7 @@ public override async Task Sure() if (succ) { - if (updateSubmodules) + if (IsRecurseSubmoduleVisible && RecurseSubmodules) { var submodules = await new Commands.QueryUpdatableSubmodules(_repo.FullPath).GetResultAsync(); if (submodules.Count > 0) diff --git a/src/ViewModels/CheckoutAndFastForward.cs b/src/ViewModels/CheckoutAndFastForward.cs index 1be379819..0c321454e 100644 --- a/src/ViewModels/CheckoutAndFastForward.cs +++ b/src/ViewModels/CheckoutAndFastForward.cs @@ -46,10 +46,6 @@ public override async Task Sure() var log = _repo.CreateLog($"Checkout and Fast-Forward '{LocalBranch.Name}' ..."); Use(log); - var updateSubmodules = IsRecurseSubmoduleVisible && RecurseSubmodules; - var succ = false; - var needPopStash = false; - if (_repo.CurrentBranch is { IsDetachedHead: true }) { var refs = await new Commands.QueryRefsContainsCommit(_repo.FullPath, _repo.CurrentBranch.Head).GetResultAsync(); @@ -65,13 +61,10 @@ public override async Task Sure() } } - if (DiscardLocalChanges) - { - succ = await new Commands.Checkout(_repo.FullPath) - .Use(log) - .BranchAsync(LocalBranch.Name, RemoteBranch.Head, true, true); - } - else + var succ = false; + var needPopStash = false; + + if (!DiscardLocalChanges) { var changes = await new Commands.CountLocalChangesWithoutUntracked(_repo.FullPath).GetResultAsync(); if (changes > 0) @@ -88,15 +81,15 @@ public override async Task Sure() needPopStash = true; } - - succ = await new Commands.Checkout(_repo.FullPath) - .Use(log) - .BranchAsync(LocalBranch.Name, RemoteBranch.Head, false, true); } + succ = await new Commands.Checkout(_repo.FullPath) + .Use(log) + .BranchAsync(LocalBranch.Name, RemoteBranch.Head, DiscardLocalChanges, true); + if (succ) { - if (updateSubmodules) + if (IsRecurseSubmoduleVisible && RecurseSubmodules) { var submodules = await new Commands.QueryUpdatableSubmodules(_repo.FullPath).GetResultAsync(); diff --git a/src/ViewModels/CommitDetail.cs b/src/ViewModels/CommitDetail.cs index 12595972e..c2e337032 100644 --- a/src/ViewModels/CommitDetail.cs +++ b/src/ViewModels/CommitDetail.cs @@ -325,13 +325,13 @@ public ContextMenu CreateChangeContextMenu(Models.Change change) var diffWithMerger = new MenuItem(); diffWithMerger.Header = App.Text("DiffWithMerger"); diffWithMerger.Icon = App.CreateMenuIcon("Icons.OpenWith"); - diffWithMerger.Click += (_, ev) => + diffWithMerger.Click += async (_, ev) => { var toolType = Preferences.Instance.ExternalMergeToolType; var toolPath = Preferences.Instance.ExternalMergeToolPath; var opt = new Models.DiffOption(_commit, change); - _ = Commands.MergeTool.OpenForDiffAsync(_repo.FullPath, toolType, toolPath, opt); + await Commands.MergeTool.OpenForDiffAsync(_repo.FullPath, toolType, toolPath, opt); ev.Handled = true; }; diff --git a/src/ViewModels/Conflict.cs b/src/ViewModels/Conflict.cs index a9ddfb7a1..585fee0b9 100644 --- a/src/ViewModels/Conflict.cs +++ b/src/ViewModels/Conflict.cs @@ -17,13 +17,9 @@ public ConflictSourceBranch(string name, string head, Models.Commit revision) public ConflictSourceBranch(Repository repo, Models.Branch branch) { - var revision = new Commands.QuerySingleCommit(repo.FullPath, branch.Head).GetResultAsync().Result; - if (revision == null) - revision = new Models.Commit() { SHA = branch.Head }; - Name = branch.Name; Head = branch.Head; - Revision = revision; + Revision = new Commands.QuerySingleCommit(repo.FullPath, branch.Head).GetResultAsync().Result ?? new Models.Commit() { SHA = branch.Head }; } } @@ -75,36 +71,33 @@ public Conflict(Repository repo, WorkingCopy wc, Models.Change change) IsResolved = new Commands.IsConflictResolved(repo.FullPath, change).GetResultAsync().Result; } - var context = wc.InProgressContext; - if (context is CherryPickInProgress cherryPick) - { - Theirs = cherryPick.Head; - Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); - } - else if (context is RebaseInProgress rebase) - { - var b = repo.Branches.Find(x => x.IsLocal && x.Name == rebase.HeadName); - if (b != null) - Theirs = new ConflictSourceBranch(b.Name, b.Head, rebase.StoppedAt); - else - Theirs = new ConflictSourceBranch(rebase.HeadName, rebase.StoppedAt?.SHA ?? "----------", rebase.StoppedAt); - - Mine = rebase.Onto; - } - else if (context is RevertInProgress revert) - { - Theirs = revert.Head; - Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); - } - else if (context is MergeInProgress merge) - { - Theirs = merge.Source; - Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); - } - else + switch (wc.InProgressContext) { - Theirs = "Stash or Patch"; - Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); + case CherryPickInProgress cherryPick: + Theirs = cherryPick.Head; + Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); + break; + case RebaseInProgress rebase: + var b = repo.Branches.Find(x => x.IsLocal && x.Name == rebase.HeadName); + if (b != null) + Theirs = new ConflictSourceBranch(b.Name, b.Head, rebase.StoppedAt); + else + Theirs = new ConflictSourceBranch(rebase.HeadName, rebase.StoppedAt?.SHA ?? "----------", rebase.StoppedAt); + + Mine = rebase.Onto; + break; + case RevertInProgress revert: + Theirs = revert.Head; + Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); + break; + case MergeInProgress merge: + Theirs = merge.Source; + Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); + break; + default: + Theirs = "Stash or Patch"; + Mine = new ConflictSourceBranch(repo, repo.CurrentBranch); + break; } } diff --git a/src/ViewModels/CreateBranch.cs b/src/ViewModels/CreateBranch.cs index 5b930f684..8325ba169 100644 --- a/src/ViewModels/CreateBranch.cs +++ b/src/ViewModels/CreateBranch.cs @@ -4,7 +4,7 @@ namespace SourceGit.ViewModels { - public partial class CreateBranch : Popup + public class CreateBranch : Popup { [Required(ErrorMessage = "Branch name is required!")] [RegularExpression(@"^[\w \-/\.#\+]+$", ErrorMessage = "Bad branch name format!")] diff --git a/src/ViewModels/Histories.cs b/src/ViewModels/Histories.cs index a2192fa8c..02118969a 100644 --- a/src/ViewModels/Histories.cs +++ b/src/ViewModels/Histories.cs @@ -456,25 +456,24 @@ public ContextMenu MakeContextMenu(DataGrid list) { foreach (var d in commit.Decorators) { - if (d.Type == Models.DecoratorType.CurrentBranchHead) + switch (d.Type) { - FillCurrentBranchMenu(menu, current); - } - else if (d.Type == Models.DecoratorType.LocalBranchHead) - { - var b = _repo.Branches.Find(x => x.IsLocal && d.Name == x.Name); - FillOtherLocalBranchMenu(menu, b, current, commit.IsMerged); - } - else if (d.Type == Models.DecoratorType.RemoteBranchHead) - { - var b = _repo.Branches.Find(x => !x.IsLocal && d.Name == x.FriendlyName); - FillRemoteBranchMenu(menu, b, current, commit.IsMerged); - } - else if (d.Type == Models.DecoratorType.Tag) - { - var t = _repo.Tags.Find(x => x.Name == d.Name); - if (t != null) - tags.Add(t); + case Models.DecoratorType.CurrentBranchHead: + FillCurrentBranchMenu(menu, current); + break; + case Models.DecoratorType.LocalBranchHead: + var lb = _repo.Branches.Find(x => x.IsLocal && d.Name == x.Name); + FillOtherLocalBranchMenu(menu, lb, current, commit.IsMerged); + break; + case Models.DecoratorType.RemoteBranchHead: + var rb = _repo.Branches.Find(x => !x.IsLocal && d.Name == x.FriendlyName); + FillRemoteBranchMenu(menu, rb, current, commit.IsMerged); + break; + case Models.DecoratorType.Tag: + var t = _repo.Tags.Find(x => x.Name == d.Name); + if (t != null) + tags.Add(t); + break; } } @@ -600,10 +599,7 @@ public ContextMenu MakeContextMenu(DataGrid list) var parents = new List(); foreach (var sha in commit.Parents) { - var parent = _commits.Find(x => x.SHA == sha); - if (parent == null) - parent = await new Commands.QuerySingleCommit(_repo.FullPath, sha).GetResultAsync(); - + var parent = _commits.Find(x => x.SHA == sha) ?? await new Commands.QuerySingleCommit(_repo.FullPath, sha).GetResultAsync(); if (parent != null) parents.Add(parent); } diff --git a/src/ViewModels/ImageSource.cs b/src/ViewModels/ImageSource.cs index cd5eab1e3..3095e4c6f 100644 --- a/src/ViewModels/ImageSource.cs +++ b/src/ViewModels/ImageSource.cs @@ -37,13 +37,13 @@ public static Models.ImageDecoder GetDecoder(string file) public static async Task FromFileAsync(string fullpath, Models.ImageDecoder decoder) { - await using (var stream = File.OpenRead(fullpath)) - return await Task.Run(() => LoadFromStream(stream, decoder)).ConfigureAwait(false); + await using var stream = File.OpenRead(fullpath); + return await Task.Run(() => LoadFromStream(stream, decoder)).ConfigureAwait(false); } public static async Task FromRevisionAsync(string repo, string revision, string file, Models.ImageDecoder decoder) { - var stream = await Commands.QueryFileContent.RunAsync(repo, revision, file).ConfigureAwait(false); + await using var stream = await Commands.QueryFileContent.RunAsync(repo, revision, file).ConfigureAwait(false); return await Task.Run(() => LoadFromStream(stream, decoder)).ConfigureAwait(false); } diff --git a/src/ViewModels/RenameBranch.cs b/src/ViewModels/RenameBranch.cs index e3e558a4b..655a2d0ca 100644 --- a/src/ViewModels/RenameBranch.cs +++ b/src/ViewModels/RenameBranch.cs @@ -4,7 +4,7 @@ namespace SourceGit.ViewModels { - public partial class RenameBranch : Popup + public class RenameBranch : Popup { public Models.Branch Target { @@ -35,9 +35,7 @@ public static ValidationResult ValidateBranchName(string name, ValidationContext foreach (var b in rename._repo.Branches) { if (b.IsLocal && b != rename.Target && b.Name.Equals(fixedName, StringComparison.Ordinal)) - { return new ValidationResult("A branch with same name already exists!!!"); - } } } diff --git a/src/ViewModels/Repository.cs b/src/ViewModels/Repository.cs index c3346fb15..778bf3a65 100644 --- a/src/ViewModels/Repository.cs +++ b/src/ViewModels/Repository.cs @@ -823,15 +823,13 @@ public void ExecCustomAction(Models.CustomAction action, object scope) if (!CanCreatePopup()) return; - ExecuteCustomAction popup; - if (scope is Models.Branch b) - popup = new ExecuteCustomAction(this, action, b); - else if (scope is Models.Commit c) - popup = new ExecuteCustomAction(this, action, c); - else if (scope is Models.Tag t) - popup = new ExecuteCustomAction(this, action, t); - else - popup = new ExecuteCustomAction(this, action); + var popup = scope switch + { + Models.Branch b => new ExecuteCustomAction(this, action, b), + Models.Commit c => new ExecuteCustomAction(this, action, c), + Models.Tag t => new ExecuteCustomAction(this, action, t), + _ => new ExecuteCustomAction(this, action) + }; if (action.Controls.Count == 0) ShowAndStartPopup(popup); diff --git a/src/ViewModels/RepositoryConfigure.cs b/src/ViewModels/RepositoryConfigure.cs index ba0798191..10bf19288 100644 --- a/src/ViewModels/RepositoryConfigure.cs +++ b/src/ViewModels/RepositoryConfigure.cs @@ -331,20 +331,8 @@ public async Task SaveAsync() private async Task SetIfChangedAsync(string key, string value, string defValue) { - bool changed = false; - if (_cached.TryGetValue(key, out var old)) - { - changed = old != value; - } - else if (!string.IsNullOrEmpty(value) && value != defValue) - { - changed = true; - } - - if (changed) - { + if (value != _cached.GetValueOrDefault(key, defValue)) await new Commands.Config(_repo.FullPath).SetAsync(key, value); - } } private readonly Repository _repo = null; diff --git a/src/ViewModels/RevisionCompare.cs b/src/ViewModels/RevisionCompare.cs index 368533072..383786e3b 100644 --- a/src/ViewModels/RevisionCompare.cs +++ b/src/ViewModels/RevisionCompare.cs @@ -58,9 +58,7 @@ public string SearchFilter set { if (SetProperty(ref _searchFilter, value)) - { RefreshVisible(); - } } } diff --git a/src/ViewModels/WorkingCopy.cs b/src/ViewModels/WorkingCopy.cs index a4c7abd6e..0f10f3fa9 100644 --- a/src/ViewModels/WorkingCopy.cs +++ b/src/ViewModels/WorkingCopy.cs @@ -389,9 +389,7 @@ public async void UseTheirs(List changes) if (!change.IsConflicted) continue; - if (change.ConflictReason == Models.ConflictReason.BothDeleted || - change.ConflictReason == Models.ConflictReason.DeletedByThem || - change.ConflictReason == Models.ConflictReason.AddedByUs) + if (change.ConflictReason is Models.ConflictReason.BothDeleted or Models.ConflictReason.DeletedByThem or Models.ConflictReason.AddedByUs) { var fullpath = Path.Combine(_repo.FullPath, change.Path); if (File.Exists(fullpath)) @@ -438,9 +436,7 @@ public async void UseMine(List changes) if (!change.IsConflicted) continue; - if (change.ConflictReason == Models.ConflictReason.BothDeleted || - change.ConflictReason == Models.ConflictReason.DeletedByUs || - change.ConflictReason == Models.ConflictReason.AddedByThem) + if (change.ConflictReason is Models.ConflictReason.BothDeleted or Models.ConflictReason.DeletedByUs or Models.ConflictReason.AddedByThem) { var fullpath = Path.Combine(_repo.FullPath, change.Path); if (File.Exists(fullpath)) @@ -622,7 +618,6 @@ public ContextMenu CreateContextMenuForUnstagedChanges(string selectedSingleFold { var useTheirs = new MenuItem(); useTheirs.Icon = App.CreateMenuIcon("Icons.Incoming"); - useTheirs.Header = App.Text("FileCM.UseTheirs"); useTheirs.Click += (_, e) => { UseTheirs(_selectedUnstaged); @@ -631,7 +626,6 @@ public ContextMenu CreateContextMenuForUnstagedChanges(string selectedSingleFold var useMine = new MenuItem(); useMine.Icon = App.CreateMenuIcon("Icons.Local"); - useMine.Header = App.Text("FileCM.UseMine"); useMine.Click += (_, e) => { UseMine(_selectedUnstaged); @@ -647,25 +641,28 @@ public ContextMenu CreateContextMenuForUnstagedChanges(string selectedSingleFold e.Handled = true; }; - if (_inProgressContext is CherryPickInProgress cherryPick) + switch (_inProgressContext) { - useTheirs.Header = App.Text("FileCM.ResolveUsing", cherryPick.HeadName); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); - } - else if (_inProgressContext is RebaseInProgress rebase) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", rebase.HeadName); - useMine.Header = App.Text("FileCM.ResolveUsing", rebase.BaseName); - } - else if (_inProgressContext is RevertInProgress revert) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", $"{revert.Head.SHA.AsSpan(0, 10)} (revert)"); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); - } - else if (_inProgressContext is MergeInProgress merge) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", merge.SourceName); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + case CherryPickInProgress cherryPick: + useTheirs.Header = App.Text("FileCM.ResolveUsing", cherryPick.HeadName); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + case RebaseInProgress rebase: + useTheirs.Header = App.Text("FileCM.ResolveUsing", rebase.HeadName); + useMine.Header = App.Text("FileCM.ResolveUsing", rebase.BaseName); + break; + case RevertInProgress revert: + useTheirs.Header = App.Text("FileCM.ResolveUsing", $"{revert.Head.SHA.AsSpan(0, 10)} (revert)"); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + case MergeInProgress merge: + useTheirs.Header = App.Text("FileCM.ResolveUsing", merge.SourceName); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + default: + useTheirs.Header = App.Text("FileCM.UseTheirs"); + useMine.Header = App.Text("FileCM.UseMine"); + break; } menu.Items.Add(useTheirs); @@ -1020,7 +1017,6 @@ public ContextMenu CreateContextMenuForUnstagedChanges(string selectedSingleFold var useTheirs = new MenuItem(); useTheirs.Icon = App.CreateMenuIcon("Icons.Incoming"); - useTheirs.Header = App.Text("FileCM.UseTheirs"); useTheirs.Click += (_, e) => { UseTheirs(_selectedUnstaged); @@ -1029,32 +1025,34 @@ public ContextMenu CreateContextMenuForUnstagedChanges(string selectedSingleFold var useMine = new MenuItem(); useMine.Icon = App.CreateMenuIcon("Icons.Local"); - useMine.Header = App.Text("FileCM.UseMine"); useMine.Click += (_, e) => { UseMine(_selectedUnstaged); e.Handled = true; }; - if (_inProgressContext is CherryPickInProgress cherryPick) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", cherryPick.HeadName); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); - } - else if (_inProgressContext is RebaseInProgress rebase) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", rebase.HeadName); - useMine.Header = App.Text("FileCM.ResolveUsing", rebase.BaseName); - } - else if (_inProgressContext is RevertInProgress revert) - { - useTheirs.Header = App.Text("FileCM.ResolveUsing", $"{revert.Head.SHA.AsSpan(0, 10)} (revert)"); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); - } - else if (_inProgressContext is MergeInProgress merge) + switch (_inProgressContext) { - useTheirs.Header = App.Text("FileCM.ResolveUsing", merge.SourceName); - useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + case CherryPickInProgress cherryPick: + useTheirs.Header = App.Text("FileCM.ResolveUsing", cherryPick.HeadName); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + case RebaseInProgress rebase: + useTheirs.Header = App.Text("FileCM.ResolveUsing", rebase.HeadName); + useMine.Header = App.Text("FileCM.ResolveUsing", rebase.BaseName); + break; + case RevertInProgress revert: + useTheirs.Header = App.Text("FileCM.ResolveUsing", $"{revert.Head.SHA.AsSpan(0, 10)} (revert)"); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + case MergeInProgress merge: + useTheirs.Header = App.Text("FileCM.ResolveUsing", merge.SourceName); + useMine.Header = App.Text("FileCM.ResolveUsing", _repo.CurrentBranch.Name); + break; + default: + useTheirs.Header = App.Text("FileCM.UseTheirs"); + useMine.Header = App.Text("FileCM.UseMine"); + break; } menu.Items.Add(useTheirs); diff --git a/src/Views/AIAssistant.axaml.cs b/src/Views/AIAssistant.axaml.cs index 5b406b4c1..48dbb9008 100644 --- a/src/Views/AIAssistant.axaml.cs +++ b/src/Views/AIAssistant.axaml.cs @@ -72,9 +72,7 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang base.OnPropertyChanged(change); if (change.Property == ContentProperty) - { Text = Content; - } } private void OnTextViewContextRequested(object sender, ContextRequestedEventArgs e) diff --git a/src/Views/BranchTree.axaml.cs b/src/Views/BranchTree.axaml.cs index e19daa77f..891efa4fc 100644 --- a/src/Views/BranchTree.axaml.cs +++ b/src/Views/BranchTree.axaml.cs @@ -70,8 +70,7 @@ private void UpdateContent() private void CreateContent(Thickness margin, string iconKey, bool highlight) { - var geo = this.FindResource(iconKey) as StreamGeometry; - if (geo == null) + if (this.FindResource(iconKey) is not StreamGeometry geo) return; var path = new Path() @@ -481,7 +480,7 @@ private void OnTreeContextRequested(object _1, ContextRequestedEventArgs _2) }; menu.Items.Add(deleteMulti); - menu?.Open(this); + menu.Open(this); } } diff --git a/src/Views/CommitRefsPresenter.cs b/src/Views/CommitRefsPresenter.cs index 30b4d3f6a..d221c155a 100644 --- a/src/Views/CommitRefsPresenter.cs +++ b/src/Views/CommitRefsPresenter.cs @@ -174,8 +174,7 @@ protected override Size MeasureOverride(Size availableSize) { _items.Clear(); - var commit = DataContext as Models.Commit; - if (commit == null) + if (DataContext is not Models.Commit commit) return new Size(0, 0); var refs = commit.Decorators; @@ -196,8 +195,7 @@ protected override Size MeasureOverride(Size availableSize) if (!showTags && decorator.Type == Models.DecoratorType.Tag) continue; - var isHead = decorator.Type == Models.DecoratorType.CurrentBranchHead || - decorator.Type == Models.DecoratorType.CurrentCommitHead; + var isHead = decorator.Type is Models.DecoratorType.CurrentBranchHead or Models.DecoratorType.CurrentCommitHead; var label = new FormattedText( decorator.Name, diff --git a/src/Views/CommitTimeTextBlock.cs b/src/Views/CommitTimeTextBlock.cs index e6a038346..f83741776 100644 --- a/src/Views/CommitTimeTextBlock.cs +++ b/src/Views/CommitTimeTextBlock.cs @@ -118,8 +118,7 @@ private void StopTimer() private string GetDisplayText() { - var commit = DataContext as Models.Commit; - if (commit == null) + if (DataContext is not Models.Commit commit) return string.Empty; if (ShowAsDateTime) diff --git a/src/Views/ExecuteCustomAction.axaml.cs b/src/Views/ExecuteCustomAction.axaml.cs index 4218b4933..fa7e97139 100644 --- a/src/Views/ExecuteCustomAction.axaml.cs +++ b/src/Views/ExecuteCustomAction.axaml.cs @@ -36,8 +36,7 @@ private async void SelectPath(object sender, RoutedEventArgs e) var control = sender as Control; - var selector = control?.DataContext as ViewModels.CustomActionControlPathSelector; - if (selector == null) + if (control?.DataContext is not ViewModels.CustomActionControlPathSelector selector) return; if (selector.IsFolder) diff --git a/src/Views/FilterModeSwitchButton.axaml.cs b/src/Views/FilterModeSwitchButton.axaml.cs index c789bfe31..e0f117f75 100644 --- a/src/Views/FilterModeSwitchButton.axaml.cs +++ b/src/Views/FilterModeSwitchButton.axaml.cs @@ -57,12 +57,10 @@ private void OnChangeFilterModeButtonClicked(object sender, RoutedEventArgs e) { var repoView = this.FindAncestorOfType(); - var repo = repoView?.DataContext as ViewModels.Repository; - if (repo == null) + if (repoView?.DataContext is not ViewModels.Repository repo) return; - var button = sender as Button; - if (button == null) + if (sender is not Button button) return; var menu = new ContextMenu(); diff --git a/src/Views/Histories.axaml.cs b/src/Views/Histories.axaml.cs index f32b930d4..b33756a3e 100644 --- a/src/Views/Histories.axaml.cs +++ b/src/Views/Histories.axaml.cs @@ -236,8 +236,7 @@ private async void OnCommitListKeyDown(object sender, KeyEventArgs e) { var repoView = this.FindAncestorOfType(); - var repo = repoView?.DataContext as ViewModels.Repository; - if (repo == null || !repo.CanCreatePopup()) + if (repoView?.DataContext is not ViewModels.Repository repo || !repo.CanCreatePopup()) return; if (selected.Count == 1 && selected[0] is Models.Commit commit) diff --git a/src/Views/InteractiveRebase.axaml.cs b/src/Views/InteractiveRebase.axaml.cs index a08892fae..9b8505eb4 100644 --- a/src/Views/InteractiveRebase.axaml.cs +++ b/src/Views/InteractiveRebase.axaml.cs @@ -16,8 +16,7 @@ public class InteractiveRebaseListBox : ListBox /// protected override void OnKeyDown(KeyEventArgs e) { - var vm = DataContext as ViewModels.InteractiveRebase; - if (vm == null) + if (DataContext is not ViewModels.InteractiveRebase vm) return; var item = vm.SelectedItem; @@ -154,8 +153,7 @@ private void OnOpenCommitMessageEditor(object sender, RoutedEventArgs e) private async void OnStartJobs(object _1, RoutedEventArgs _2) { - var vm = DataContext as ViewModels.InteractiveRebase; - if (vm == null) + if (DataContext is not ViewModels.InteractiveRebase vm) return; Running.IsVisible = true; diff --git a/src/Views/Launcher.axaml.cs b/src/Views/Launcher.axaml.cs index 1f44b1f6f..7899aac3e 100644 --- a/src/Views/Launcher.axaml.cs +++ b/src/Views/Launcher.axaml.cs @@ -145,8 +145,7 @@ protected override void OnSizeChanged(SizeChangedEventArgs e) protected override async void OnKeyDown(KeyEventArgs e) { - var vm = DataContext as ViewModels.Launcher; - if (vm == null) + if (DataContext is not ViewModels.Launcher vm) return; // We should clear all unhandled key modifiers. @@ -243,39 +242,28 @@ protected override async void OnKeyDown(KeyEventArgs e) if (vm.ActivePage.Data is ViewModels.Repository repo) { - if (e.Key == Key.D1 || e.Key == Key.NumPad1) + switch (e.Key) { - repo.SelectedViewIndex = 0; - e.Handled = true; - return; - } - - if (e.Key == Key.D2 || e.Key == Key.NumPad2) - { - repo.SelectedViewIndex = 1; - e.Handled = true; - return; - } - - if (e.Key == Key.D3 || e.Key == Key.NumPad3) - { - repo.SelectedViewIndex = 2; - e.Handled = true; - return; - } - - if (e.Key == Key.F) - { - repo.IsSearching = true; - e.Handled = true; - return; - } - - if (e.Key == Key.H && e.KeyModifiers.HasFlag(KeyModifiers.Shift)) - { - repo.IsSearching = false; - e.Handled = true; - return; + case Key.D1 or Key.NumPad1: + repo.SelectedViewIndex = 0; + e.Handled = true; + return; + case Key.D2 or Key.NumPad2: + repo.SelectedViewIndex = 1; + e.Handled = true; + return; + case Key.D3 or Key.NumPad3: + repo.SelectedViewIndex = 2; + e.Handled = true; + return; + case Key.F: + repo.IsSearching = true; + e.Handled = true; + return; + case Key.H when e.KeyModifiers.HasFlag(KeyModifiers.Shift): + repo.IsSearching = false; + e.Handled = true; + return; } } else diff --git a/src/Views/Repository.axaml.cs b/src/Views/Repository.axaml.cs index ac243e55a..94149325d 100644 --- a/src/Views/Repository.axaml.cs +++ b/src/Views/Repository.axaml.cs @@ -121,8 +121,7 @@ private void OnSearchCommitPanelPropertyChanged(object sender, AvaloniaPropertyC private void OnSearchKeyDown(object _, KeyEventArgs e) { - var repo = DataContext as ViewModels.Repository; - if (repo == null) + if (DataContext is not ViewModels.Repository repo) return; if (e.Key == Key.Enter) @@ -199,9 +198,7 @@ private void OnWorktreeContextRequested(object sender, ContextRequestedEventArgs private void OnDoubleTappedWorktree(object sender, TappedEventArgs e) { if (sender is ListBox { SelectedItem: Models.Worktree worktree } && DataContext is ViewModels.Repository repo) - { repo.OpenWorktree(worktree); - } e.Handled = true; } @@ -343,8 +340,7 @@ private void UpdateLeftSidebarLayout() private void OnSearchSuggestionBoxKeyDown(object _, KeyEventArgs e) { - var repo = DataContext as ViewModels.Repository; - if (repo == null) + if (DataContext is not ViewModels.Repository repo) return; if (e.Key == Key.Escape) @@ -363,8 +359,7 @@ private void OnSearchSuggestionBoxKeyDown(object _, KeyEventArgs e) private void OnSearchSuggestionDoubleTapped(object sender, TappedEventArgs e) { - var repo = DataContext as ViewModels.Repository; - if (repo == null) + if (DataContext is not ViewModels.Repository repo) return; var content = (sender as StackPanel)?.DataContext as string; diff --git a/src/Views/RevisionCompare.axaml.cs b/src/Views/RevisionCompare.axaml.cs index 2c5482409..1f0e5fc19 100644 --- a/src/Views/RevisionCompare.axaml.cs +++ b/src/Views/RevisionCompare.axaml.cs @@ -37,8 +37,7 @@ private async void OnSaveAsPatch(object sender, RoutedEventArgs e) if (topLevel == null) return; - var vm = DataContext as ViewModels.RevisionCompare; - if (vm == null) + if (DataContext is not ViewModels.RevisionCompare vm) return; var options = new FilePickerSaveOptions(); diff --git a/src/Views/RevisionFileTreeView.axaml.cs b/src/Views/RevisionFileTreeView.axaml.cs index e0a915e15..a7ca36e06 100644 --- a/src/Views/RevisionFileTreeView.axaml.cs +++ b/src/Views/RevisionFileTreeView.axaml.cs @@ -81,8 +81,7 @@ private void UpdateContent() private void CreateContent(string iconKey, Thickness margin, IBrush fill = null) { - var geo = this.FindResource(iconKey) as StreamGeometry; - if (geo == null) + if (this.FindResource(iconKey) is not StreamGeometry geo) return; var icon = new Avalonia.Controls.Shapes.Path() @@ -320,8 +319,7 @@ private async void OnRowsSelectionChanged(object sender, SelectionChangedEventAr if (node.Children.Count > 0) return node.Children; - var vm = DataContext as ViewModels.CommitDetail; - if (vm == null) + if (DataContext is not ViewModels.CommitDetail vm) return null; var objects = await vm.GetRevisionFilesUnderFolderAsync(node.Backend.Path + "/"); diff --git a/src/Views/RevisionFiles.axaml.cs b/src/Views/RevisionFiles.axaml.cs index 3ebfc4e1b..dd51943c8 100644 --- a/src/Views/RevisionFiles.axaml.cs +++ b/src/Views/RevisionFiles.axaml.cs @@ -13,8 +13,7 @@ public RevisionFiles() private async void OnSearchBoxKeyDown(object _, KeyEventArgs e) { - var vm = DataContext as ViewModels.CommitDetail; - if (vm == null) + if (DataContext is not ViewModels.CommitDetail vm) return; if (e.Key == Key.Enter) @@ -47,8 +46,7 @@ private async void OnSearchBoxTextChanged(object _, TextChangedEventArgs e) private async void OnSearchSuggestionBoxKeyDown(object _, KeyEventArgs e) { - var vm = DataContext as ViewModels.CommitDetail; - if (vm == null) + if (DataContext is not ViewModels.CommitDetail vm) return; if (e.Key == Key.Escape) @@ -67,8 +65,7 @@ private async void OnSearchSuggestionBoxKeyDown(object _, KeyEventArgs e) private async void OnSearchSuggestionDoubleTapped(object sender, TappedEventArgs e) { - var vm = DataContext as ViewModels.CommitDetail; - if (vm == null) + if (DataContext is not ViewModels.CommitDetail vm) return; var content = (sender as StackPanel)?.DataContext as string; diff --git a/src/Views/StashesPage.axaml.cs b/src/Views/StashesPage.axaml.cs index 348a5ae31..34c44214f 100644 --- a/src/Views/StashesPage.axaml.cs +++ b/src/Views/StashesPage.axaml.cs @@ -12,8 +12,7 @@ public StashesPage() private void OnMainLayoutSizeChanged(object sender, SizeChangedEventArgs e) { - var grid = sender as Grid; - if (grid == null) + if (sender is not Grid grid) return; var layout = ViewModels.Preferences.Instance.Layout; diff --git a/src/Views/SubmodulesView.axaml.cs b/src/Views/SubmodulesView.axaml.cs index 5fe677c3c..524194458 100644 --- a/src/Views/SubmodulesView.axaml.cs +++ b/src/Views/SubmodulesView.axaml.cs @@ -71,8 +71,7 @@ private void UpdateContent() private void CreateContent(Thickness margin, string iconKey) { - var geo = this.FindResource(iconKey) as StreamGeometry; - if (geo == null) + if (this.FindResource(iconKey) is not StreamGeometry geo) return; Content = new Avalonia.Controls.Shapes.Path() diff --git a/src/Views/TagsView.axaml.cs b/src/Views/TagsView.axaml.cs index 5970e4dd4..b73a5b5e8 100644 --- a/src/Views/TagsView.axaml.cs +++ b/src/Views/TagsView.axaml.cs @@ -71,8 +71,7 @@ private void UpdateContent() private void CreateContent(Thickness margin, string iconKey) { - var geo = this.FindResource(iconKey) as StreamGeometry; - if (geo == null) + if (this.FindResource(iconKey) is not StreamGeometry geo) return; Content = new Avalonia.Controls.Shapes.Path() @@ -181,8 +180,7 @@ private void OnItemPointerPressed(object sender, PointerPressedEventArgs e) private void OnItemContextRequested(object sender, ContextRequestedEventArgs e) { - var control = sender as Control; - if (control == null) + if (sender is not Control control) return; Models.Tag selected; diff --git a/src/Views/TextDiffView.axaml.cs b/src/Views/TextDiffView.axaml.cs index cf9cb31db..8c7855542 100644 --- a/src/Views/TextDiffView.axaml.cs +++ b/src/Views/TextDiffView.axaml.cs @@ -634,9 +634,7 @@ public virtual void GotoNextChange() for (var idx = lastLineIdx + 1; idx < lines.Count; idx++) { var nextType = lines[idx].Type; - if (nextType == Models.TextDiffLineType.None || - nextType == Models.TextDiffLineType.Added || - nextType == Models.TextDiffLineType.Deleted) + if (nextType is Models.TextDiffLineType.None or Models.TextDiffLineType.Added or Models.TextDiffLineType.Deleted) { if (findNormalLine) { @@ -1005,15 +1003,10 @@ private async Task CopyWithoutIndicatorsAsync() if (startIdx == endIdx) { - var line = lines[startIdx]; - if (line.Type == Models.TextDiffLineType.Indicator || - line.Type == Models.TextDiffLineType.None) - { + if (lines[startIdx].Type is Models.TextDiffLineType.Indicator or Models.TextDiffLineType.None) await App.CopyTextAsync(string.Empty); - return; - } - - await App.CopyTextAsync(SelectedText); + else + await App.CopyTextAsync(SelectedText); return; } @@ -1021,8 +1014,7 @@ private async Task CopyWithoutIndicatorsAsync() for (var i = startIdx; i <= endIdx && i <= lines.Count - 1; i++) { var line = lines[i]; - if (line.Type == Models.TextDiffLineType.Indicator || - line.Type == Models.TextDiffLineType.None) + if (line.Type is Models.TextDiffLineType.Indicator or Models.TextDiffLineType.None) continue; // The first selected line (partial selection) @@ -1094,8 +1086,7 @@ public override int GetMaxLineNumber() public override void UpdateSelectedChunk(double y) { - var diff = DataContext as Models.TextDiff; - if (diff == null) + if (DataContext is not Models.TextDiff diff) return; var view = TextArea.TextView; @@ -1321,8 +1312,7 @@ public override void GotoLastChange() public override void UpdateSelectedChunk(double y) { - var diff = DataContext as ViewModels.TwoSideTextDiff; - if (diff == null) + if (DataContext is not ViewModels.TwoSideTextDiff diff) return; var parent = this.FindAncestorOfType(); @@ -1835,8 +1825,7 @@ private async void OnStageChunk(object _1, RoutedEventArgs _2) var repoView = this.FindAncestorOfType(); - var repo = repoView?.DataContext as ViewModels.Repository; - if (repo == null) + if (repoView?.DataContext is not ViewModels.Repository repo) return; repo.SetWatcherEnabled(false); @@ -1889,8 +1878,7 @@ private async void OnUnstageChunk(object _1, RoutedEventArgs _2) var repoView = this.FindAncestorOfType(); - var repo = repoView?.DataContext as ViewModels.Repository; - if (repo == null) + if (repoView?.DataContext is not ViewModels.Repository repo) return; repo.SetWatcherEnabled(false); @@ -1939,8 +1927,7 @@ private async void OnDiscardChunk(object _1, RoutedEventArgs _2) var repoView = this.FindAncestorOfType(); - var repo = repoView?.DataContext as ViewModels.Repository; - if (repo == null) + if (repoView?.DataContext is not ViewModels.Repository repo) return; repo.SetWatcherEnabled(false); diff --git a/src/Views/Welcome.axaml.cs b/src/Views/Welcome.axaml.cs index 0483a9903..712e674dd 100644 --- a/src/Views/Welcome.axaml.cs +++ b/src/Views/Welcome.axaml.cs @@ -209,8 +209,7 @@ private void DragOverTreeNode(object sender, DragEventArgs e) { var grid = sender as Grid; - var to = grid?.DataContext as ViewModels.RepositoryNode; - if (to == null) + if (grid?.DataContext is not ViewModels.RepositoryNode) return; e.DragEffects = DragDropEffects.Move; @@ -223,8 +222,7 @@ private void DropOnTreeNode(object sender, DragEventArgs e) if (sender is not Grid grid) return; - var to = grid.DataContext as ViewModels.RepositoryNode; - if (to == null) + if (grid.DataContext is not ViewModels.RepositoryNode to) { e.Handled = true; return; diff --git a/src/Views/WorkingCopy.axaml.cs b/src/Views/WorkingCopy.axaml.cs index a204634fa..48d383644 100644 --- a/src/Views/WorkingCopy.axaml.cs +++ b/src/Views/WorkingCopy.axaml.cs @@ -14,8 +14,7 @@ public WorkingCopy() private void OnMainLayoutSizeChanged(object sender, SizeChangedEventArgs e) { - var grid = sender as Grid; - if (grid == null) + if (sender is not Grid grid) return; var layout = ViewModels.Preferences.Instance.Layout;