diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e69d09493..2e265201c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,7 +31,7 @@ jobs: container: ${{ matrix.container || '' }} steps: - name: Install common CLI tools - if: ${{ startsWith(matrix.runtime, 'linux-') }} + if: startsWith(matrix.runtime, 'linux-') run: | export DEBIAN_FRONTEND=noninteractive ln -fs /usr/share/zoneinfo/Etc/UTC /etc/localtime @@ -45,7 +45,7 @@ jobs: with: dotnet-version: 9.0.x - name: Configure arm64 packages - if: ${{ matrix.runtime == 'linux-arm64' }} + if: matrix.runtime == 'linux-arm64' run: | sudo dpkg --add-architecture arm64 echo 'deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ focal main restricted @@ -55,7 +55,7 @@ jobs: sudo sed -i -e 's/^deb http/deb [arch=amd64] http/g' /etc/apt/sources.list sudo sed -i -e 's/^deb mirror/deb [arch=amd64] mirror/g' /etc/apt/sources.list - name: Install cross-compiling dependencies - if: ${{ matrix.runtime == 'linux-arm64' }} + if: matrix.runtime == 'linux-arm64' run: | sudo apt-get update sudo apt-get install -y llvm gcc-aarch64-linux-gnu @@ -64,10 +64,10 @@ jobs: - name: Publish run: dotnet publish src/SourceGit.csproj -c Release -o publish -r ${{ matrix.runtime }} - name: Rename executable file - if: ${{ startsWith(matrix.runtime, 'linux-') }} + if: startsWith(matrix.runtime, 'linux-') run: mv publish/SourceGit publish/sourcegit - name: Tar artifact - if: ${{ startsWith(matrix.runtime, 'linux-') || startsWith(matrix.runtime, 'osx-') }} + if: startsWith(matrix.runtime, 'linux-') || startsWith(matrix.runtime, 'osx-') run: | tar -cvf "sourcegit.${{ matrix.runtime }}.tar" -C publish . rm -r publish/* diff --git a/src/App.axaml.cs b/src/App.axaml.cs index 669d095a6..3d5f88f4a 100644 --- a/src/App.axaml.cs +++ b/src/App.axaml.cs @@ -148,23 +148,21 @@ public static void ShowWindow(object data, bool showAsDialog) public static void RaiseException(string context, string message) { - if (Current is App app && app._launcher != null) + if (Current is App { _launcher: not null } app) app._launcher.DispatchNotification(context, message, true); } public static void SendNotification(string context, string message) { - if (Current is App app && app._launcher != null) + if (Current is App { _launcher: not null } app) app._launcher.DispatchNotification(context, message, false); } public static void SetLocale(string localeKey) { var app = Current as App; - if (app == null) - return; - var targetLocale = app.Resources[localeKey] as ResourceDictionary; + var targetLocale = app?.Resources[localeKey] as ResourceDictionary; if (targetLocale == null || targetLocale == app._activeLocale) return; @@ -286,22 +284,14 @@ public static void SetFonts(string defaultFont, string monospaceFont, bool onlyU public static async void CopyText(string data) { - if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - if (desktop.MainWindow?.Clipboard is { } clipboard) - await clipboard.SetTextAsync(data ?? ""); - } + if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow.Clipboard: { } clipboard }) + await clipboard.SetTextAsync(data ?? ""); } public static async Task GetClipboardTextAsync() { - if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - if (desktop.MainWindow?.Clipboard is { } clipboard) - { - return await clipboard.GetTextAsync(); - } - } + if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow.Clipboard: { } clipboard }) + return await clipboard.GetTextAsync(); return null; } @@ -562,7 +552,7 @@ private void TryLaunchAsNormal(IClassicDesktopStyleApplicationLifetime desktop) Models.AvatarManager.Instance.Start(); string startupRepo = null; - if (desktop.Args != null && desktop.Args.Length == 1 && Directory.Exists(desktop.Args[0])) + if (desktop.Args is { Length: 1 } && Directory.Exists(desktop.Args[0])) startupRepo = desktop.Args[0]; var pref = ViewModels.Preferences.Instance; diff --git a/src/Commands/Command.cs b/src/Commands/Command.cs index caf5d0a48..9ef0faf84 100644 --- a/src/Commands/Command.cs +++ b/src/Commands/Command.cs @@ -43,7 +43,7 @@ public bool Exec() proc.OutputDataReceived += (_, e) => HandleOutput(e.Data, errs); proc.ErrorDataReceived += (_, e) => HandleOutput(e.Data, errs); - var dummy = null as Process; + Process dummy = null; var dummyProcLock = new object(); try { diff --git a/src/Commands/QueryCommits.cs b/src/Commands/QueryCommits.cs index 8ac9cbc5e..e52c933da 100644 --- a/src/Commands/QueryCommits.cs +++ b/src/Commands/QueryCommits.cs @@ -132,9 +132,7 @@ private void MarkFirstMerged() 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/QueryRevisionFileNames.cs b/src/Commands/QueryRevisionFileNames.cs index c6fd73735..09f9bde40 100644 --- a/src/Commands/QueryRevisionFileNames.cs +++ b/src/Commands/QueryRevisionFileNames.cs @@ -18,10 +18,7 @@ public List Result() return []; var lines = rs.StdOut.Split('\0', System.StringSplitOptions.RemoveEmptyEntries); - var outs = new List(); - foreach (var line in lines) - outs.Add(line); - return outs; + return [.. lines]; } } } diff --git a/src/Commands/Worktree.cs b/src/Commands/Worktree.cs index 1198a4430..f9f342bf8 100644 --- a/src/Commands/Worktree.cs +++ b/src/Commands/Worktree.cs @@ -18,7 +18,7 @@ public Worktree(string repo) var rs = ReadToEnd(); var worktrees = new List(); - var last = null as Models.Worktree; + Models.Worktree last = null; if (rs.IsSuccess) { var lines = rs.StdOut.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); diff --git a/src/Models/AvatarManager.cs b/src/Models/AvatarManager.cs index f00066522..132e6f208 100644 --- a/src/Models/AvatarManager.cs +++ b/src/Models/AvatarManager.cs @@ -55,7 +55,7 @@ public void Start() { while (true) { - var email = null as string; + string email = null; lock (_synclock) { @@ -79,7 +79,7 @@ public void Start() $"https://www.gravatar.com/avatar/{md5}?d=404"; var localFile = Path.Combine(_storePath, md5); - var img = null as Bitmap; + Bitmap img = null; try { var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) }; @@ -113,7 +113,7 @@ public void Start() _requesting.Remove(email); } - Dispatcher.UIThread.InvokeAsync(() => + Dispatcher.UIThread.Post(() => { _resources[email] = img; NotifyResourceChanged(email, img); diff --git a/src/Models/CommitGraph.cs b/src/Models/CommitGraph.cs index 8d7f2c339..cb5696101 100644 --- a/src/Models/CommitGraph.cs +++ b/src/Models/CommitGraph.cs @@ -82,7 +82,7 @@ public static CommitGraph Parse(List commits, bool firstParentOnlyEnable foreach (var commit in commits) { - var major = null as PathHelper; + PathHelper major = null; var isMerged = commit.IsMerged; // Update current y offset diff --git a/src/Models/CommitLink.cs b/src/Models/CommitLink.cs index 2891e5d65..023089758 100644 --- a/src/Models/CommitLink.cs +++ b/src/Models/CommitLink.cs @@ -27,19 +27,19 @@ public static List Get(List remotes) trimmedUrl = url.AsSpan(0, url.Length - 4); if (url.StartsWith("https://github.com/", StringComparison.Ordinal)) - outs.Add(new($"Github ({trimmedUrl.Slice(19)})", $"{url}/commit/")); + outs.Add(new($"Github ({trimmedUrl[19..]})", $"{url}/commit/")); else if (url.StartsWith("https://gitlab.", StringComparison.Ordinal)) - outs.Add(new($"GitLab ({trimmedUrl.Slice(trimmedUrl.Slice(15).IndexOf('/') + 16)})", $"{url}/-/commit/")); + outs.Add(new($"GitLab ({trimmedUrl[(trimmedUrl[15..].IndexOf('/') + 16)..]})", $"{url}/-/commit/")); else if (url.StartsWith("https://gitee.com/", StringComparison.Ordinal)) - outs.Add(new($"Gitee ({trimmedUrl.Slice(18)})", $"{url}/commit/")); + outs.Add(new($"Gitee ({trimmedUrl[18..]})", $"{url}/commit/")); else if (url.StartsWith("https://bitbucket.org/", StringComparison.Ordinal)) - outs.Add(new($"BitBucket ({trimmedUrl.Slice(22)})", $"{url}/commits/")); + outs.Add(new($"BitBucket ({trimmedUrl[22..]})", $"{url}/commits/")); else if (url.StartsWith("https://codeberg.org/", StringComparison.Ordinal)) - outs.Add(new($"Codeberg ({trimmedUrl.Slice(21)})", $"{url}/commit/")); + outs.Add(new($"Codeberg ({trimmedUrl[21..]})", $"{url}/commit/")); else if (url.StartsWith("https://gitea.org/", StringComparison.Ordinal)) - outs.Add(new($"Gitea ({trimmedUrl.Slice(18)})", $"{url}/commit/")); + outs.Add(new($"Gitea ({trimmedUrl[18..]})", $"{url}/commit/")); else if (url.StartsWith("https://git.sr.ht/", StringComparison.Ordinal)) - outs.Add(new($"sourcehut ({trimmedUrl.Slice(18)})", $"{url}/commit/")); + outs.Add(new($"sourcehut ({trimmedUrl[18..]})", $"{url}/commit/")); } } diff --git a/src/Models/DealWithChangesAfterStashing.cs b/src/Models/DealWithChangesAfterStashing.cs index 63889c969..9393ce749 100644 --- a/src/Models/DealWithChangesAfterStashing.cs +++ b/src/Models/DealWithChangesAfterStashing.cs @@ -2,21 +2,15 @@ namespace SourceGit.Models { - public class DealWithChangesAfterStashing + public class DealWithChangesAfterStashing(string label, string desc) { - public string Label { get; set; } - public string Desc { get; set; } + public string Label { get; set; } = label; + public string Desc { get; set; } = desc; public static readonly List Supported = [ new ("Discard", "All (or selected) changes will be discarded"), new ("Keep Index", "Staged changes are left intact"), new ("Keep All", "All (or selected) changes are left intact"), ]; - - public DealWithChangesAfterStashing(string label, string desc) - { - Label = label; - Desc = desc; - } } } diff --git a/src/Models/DiffResult.cs b/src/Models/DiffResult.cs index c76a0cefe..429d24e05 100644 --- a/src/Models/DiffResult.cs +++ b/src/Models/DiffResult.cs @@ -199,7 +199,7 @@ public void GeneratePatchFromSelection(Change change, string fileTreeGuid, TextD writer.WriteLine($"+++ b/{change.Path}"); // If last line of selection is a change. Find one more line. - var tail = null as string; + string tail = null; if (selection.EndLine < Lines.Count) { var lastLine = Lines[selection.EndLine - 1]; @@ -323,7 +323,7 @@ public void GeneratePatchFromSelectionSingleSide(Change change, string fileTreeG writer.WriteLine($"+++ b/{change.Path}"); // If last line of selection is a change. Find one more line. - var tail = null as string; + string tail = null; if (selection.EndLine < Lines.Count) { var lastLine = Lines[selection.EndLine - 1]; diff --git a/src/Models/ExternalMerger.cs b/src/Models/ExternalMerger.cs index fe67ad6af..815220df8 100644 --- a/src/Models/ExternalMerger.cs +++ b/src/Models/ExternalMerger.cs @@ -96,16 +96,9 @@ public string[] GetPatterns() { return Exec.Split(';'); } - else - { - var patterns = new List(); - var choices = Exec.Split(';', StringSplitOptions.RemoveEmptyEntries); - foreach (var c in choices) - { - patterns.Add(Path.GetFileName(c)); - } - return patterns.ToArray(); - } + + var choices = Exec.Split(';', StringSplitOptions.RemoveEmptyEntries); + return Array.ConvertAll(choices, Path.GetFileName); } } } diff --git a/src/Models/TextInlineChange.cs b/src/Models/TextInlineChange.cs index afe5bec40..81c26412d 100644 --- a/src/Models/TextInlineChange.cs +++ b/src/Models/TextInlineChange.cs @@ -50,7 +50,7 @@ public static List Compare(string oldValue, string newValue) var ret = new List(); var posOld = 0; var posNew = 0; - var last = null as TextInlineChange; + TextInlineChange last = null; do { while (posOld < sizeOld && posNew < sizeNew && !chunksOld[posOld].Modified && !chunksNew[posNew].Modified) diff --git a/src/Native/Windows.cs b/src/Native/Windows.cs index 02d8142b6..caccc5e3c 100644 --- a/src/Native/Windows.cs +++ b/src/Native/Windows.cs @@ -257,7 +257,7 @@ private void FixWindowFrameOnWin10(Window w) { // Schedule the DWM frame extension to run in the next render frame // to ensure proper timing with the window initialization sequence - Dispatcher.UIThread.InvokeAsync(() => + Dispatcher.UIThread.Post(() => { var platformHandle = w.TryGetPlatformHandle(); if (platformHandle == null) diff --git a/src/ViewModels/Blame.cs b/src/ViewModels/Blame.cs index a189215a1..546e122b5 100644 --- a/src/ViewModels/Blame.cs +++ b/src/ViewModels/Blame.cs @@ -34,7 +34,7 @@ private set public bool IsBinary { - get => _data != null && _data.IsBinary; + get => _data?.IsBinary ?? false; } public bool CanBack diff --git a/src/ViewModels/BranchCompare.cs b/src/ViewModels/BranchCompare.cs index 64ceea1c7..600ae1b63 100644 --- a/src/ViewModels/BranchCompare.cs +++ b/src/ViewModels/BranchCompare.cs @@ -49,7 +49,7 @@ public List SelectedChanges { if (SetProperty(ref _selectedChanges, value)) { - if (value != null && value.Count == 1) + if (value?.Count == 1) DiffContext = new DiffContext(_repo, new Models.DiffOption(_based.Head, _to.Head, value[0]), _diffContext); else DiffContext = null; diff --git a/src/ViewModels/BranchTreeNode.cs b/src/ViewModels/BranchTreeNode.cs index dffbf671f..85b4b8518 100644 --- a/src/ViewModels/BranchTreeNode.cs +++ b/src/ViewModels/BranchTreeNode.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Avalonia; +using AvaloniaEdit.Utils; using CommunityToolkit.Mvvm.ComponentModel; namespace SourceGit.ViewModels @@ -86,8 +87,7 @@ public Builder(Models.BranchSortMode localSortMode, Models.BranchSortMode remote public void SetExpandedNodes(List expanded) { - foreach (var node in expanded) - _expanded.Add(node); + _expanded.AddRange(expanded); } public void Run(List branches, List remotes, bool bForceExpanded) @@ -165,7 +165,7 @@ private void MakeBranchNode(Models.Branch branch, List roots, Di return; } - var lastFolder = null as BranchTreeNode; + BranchTreeNode lastFolder = null; var start = 0; while (sepIdx != -1) @@ -250,8 +250,7 @@ private void SortNodesByTime(List nodes) { if (r.Backend is Models.Branch) return r.TimeToSort == l.TimeToSort ? Models.NumericSort.Compare(l.Name, r.Name) : r.TimeToSort.CompareTo(l.TimeToSort); - else - return 1; + return 1; } if (r.Backend is Models.Branch) diff --git a/src/ViewModels/CheckoutAndFastForward.cs b/src/ViewModels/CheckoutAndFastForward.cs index 9ae931fee..e66b3d845 100644 --- a/src/ViewModels/CheckoutAndFastForward.cs +++ b/src/ViewModels/CheckoutAndFastForward.cs @@ -49,7 +49,7 @@ public override Task Sure() var updateSubmodules = IsRecurseSubmoduleVisible && RecurseSubmodules; return Task.Run(() => { - var succ = false; + bool succ; var needPopStash = false; if (!_repo.ConfirmCheckoutBranch()) diff --git a/src/ViewModels/Clone.cs b/src/ViewModels/Clone.cs index bc742b37f..6db6902a8 100644 --- a/src/ViewModels/Clone.cs +++ b/src/ViewModels/Clone.cs @@ -151,7 +151,7 @@ public override Task Sure() { var node = Preferences.Instance.FindOrAddNodeByRepositoryPath(path, null, true); var launcher = App.GetLauncher(); - var page = null as LauncherPage; + LauncherPage page = null; foreach (var one in launcher.Pages) { if (one.Node.Id == _pageId) diff --git a/src/ViewModels/ConfigureWorkspace.cs b/src/ViewModels/ConfigureWorkspace.cs index 5be066aed..638caf5df 100644 --- a/src/ViewModels/ConfigureWorkspace.cs +++ b/src/ViewModels/ConfigureWorkspace.cs @@ -17,7 +17,7 @@ public Workspace Selected set { if (SetProperty(ref _selected, value)) - CanDeleteSelected = value != null && !value.IsActive; + CanDeleteSelected = value is { IsActive: false }; } } diff --git a/src/ViewModels/ConventionalCommitMessageBuilder.cs b/src/ViewModels/ConventionalCommitMessageBuilder.cs index 8faabe86e..5eb9494c9 100644 --- a/src/ViewModels/ConventionalCommitMessageBuilder.cs +++ b/src/ViewModels/ConventionalCommitMessageBuilder.cs @@ -72,10 +72,9 @@ public bool Apply() builder.Append(")"); } - if (string.IsNullOrEmpty(_breakingChanges)) - builder.Append(": "); - else - builder.Append("!: "); + if (!string.IsNullOrEmpty(_breakingChanges)) + builder.Append("!"); + builder.Append(": "); builder.Append(_description); builder.Append("\n\n"); diff --git a/src/ViewModels/CreateBranch.cs b/src/ViewModels/CreateBranch.cs index 6e01eb398..e9f1e24e7 100644 --- a/src/ViewModels/CreateBranch.cs +++ b/src/ViewModels/CreateBranch.cs @@ -112,10 +112,8 @@ public static ValidationResult ValidateBranchName(string name, ValidationContext return ValidationResult.Success; } - else - { - return new ValidationResult("Missing runtime context to create branch!"); - } + + return new ValidationResult("Missing runtime context to create branch!"); } public override Task Sure() @@ -188,7 +186,7 @@ public override Task Sure() if (succ && CheckoutAfterCreated) { var fake = new Models.Branch() { IsLocal = true, FullName = $"refs/heads/{fixedName}" }; - if (BasedOn is Models.Branch based && !based.IsLocal) + if (BasedOn is Models.Branch { IsLocal: false } based) fake.Upstream = based.FullName; var folderEndIdx = fake.FullName.LastIndexOf('/'); diff --git a/src/ViewModels/DiffContext.cs b/src/ViewModels/DiffContext.cs index 9bb3c7107..02635a344 100644 --- a/src/ViewModels/DiffContext.cs +++ b/src/ViewModels/DiffContext.cs @@ -120,7 +120,7 @@ private void LoadDiffContent() _info = info; - var rs = null as object; + object rs = null; if (latest.TextDiff != null) { var count = latest.TextDiff.Lines.Count; diff --git a/src/ViewModels/ExecuteCustomAction.cs b/src/ViewModels/ExecuteCustomAction.cs index fa734ed5f..9527619e2 100644 --- a/src/ViewModels/ExecuteCustomAction.cs +++ b/src/ViewModels/ExecuteCustomAction.cs @@ -207,14 +207,13 @@ private string PrepareStringByTarget(string org) { org = org.Replace("${REPO}", GetWorkdir()); - if (Target is Models.Branch b) - return org.Replace("${BRANCH}", b.FriendlyName); - else if (Target is Models.Commit c) - return org.Replace("${SHA}", c.SHA); - else if (Target is Models.Tag t) - return org.Replace("${TAG}", t.Name); - - return org; + return Target switch + { + Models.Branch b => org.Replace("${BRANCH}", b.FriendlyName), + Models.Commit c => org.Replace("${SHA}", c.SHA), + Models.Tag t => org.Replace("${TAG}", t.Name), + _ => org + }; } private string GetWorkdir() diff --git a/src/ViewModels/Histories.cs b/src/ViewModels/Histories.cs index 8d159419e..92b6d3632 100644 --- a/src/ViewModels/Histories.cs +++ b/src/ViewModels/Histories.cs @@ -261,7 +261,7 @@ public void CheckoutBranchByCommit(Models.Commit commit) if (commit.IsCurrentHead) return; - var firstRemoteBranch = null as Models.Branch; + Models.Branch firstRemoteBranch = null; foreach (var d in commit.Decorators) { if (d.Type == Models.DecoratorType.LocalBranchHead) @@ -379,7 +379,7 @@ public ContextMenu MakeContextMenu(DataGrid list) return; var options = new FolderPickerOpenOptions() { AllowMultiple = false }; - var log = null as CommandLog; + CommandLog log = null; try { var picker = await storageProvider.OpenFolderPickerAsync(options); @@ -753,7 +753,7 @@ public ContextMenu MakeContextMenu(DataGrid list) return; var options = new FolderPickerOpenOptions() { AllowMultiple = false }; - var log = null as CommandLog; + CommandLog log = null; try { var selected = await storageProvider.OpenFolderPickerAsync(options); diff --git a/src/ViewModels/LFSLocks.cs b/src/ViewModels/LFSLocks.cs index 0ee149d06..8d8ad0378 100644 --- a/src/ViewModels/LFSLocks.cs +++ b/src/ViewModels/LFSLocks.cs @@ -86,19 +86,11 @@ private void UpdateVisibleLocks() { var visible = new List(); - if (!_showOnlyMyLocks) + foreach (var lfsLock in _cachedLocks) { - foreach (var lfsLock in _cachedLocks) + if (!_showOnlyMyLocks || lfsLock.User == _userName) visible.Add(lfsLock); } - else - { - foreach (var lfsLock in _cachedLocks) - { - if (lfsLock.User == _userName) - visible.Add(lfsLock); - } - } VisibleLocks = visible; } diff --git a/src/ViewModels/Launcher.cs b/src/ViewModels/Launcher.cs index fcb34ceba..05afbf3f1 100644 --- a/src/ViewModels/Launcher.cs +++ b/src/ViewModels/Launcher.cs @@ -417,8 +417,7 @@ public void DispatchNotification(string pageId, string message, bool isError) } } - if (_activePage != null) - _activePage.Notifications.Add(notification); + _activePage?.Notifications.Add(notification); } public ContextMenu CreateContextForWorkspace() diff --git a/src/ViewModels/Preferences.cs b/src/ViewModels/Preferences.cs index 4cff477ad..6df1240c4 100644 --- a/src/ViewModels/Preferences.cs +++ b/src/ViewModels/Preferences.cs @@ -584,13 +584,6 @@ private void PrepareWorkspaces() } } - private void SortNodesRecursive(List collection) - { - SortNodes(collection); - foreach (var node in collection) - SortNodesRecursive(node.SubNodes); - } - private RepositoryNode FindNodeRecursive(string id, List collection) { foreach (var node in collection) diff --git a/src/ViewModels/Pull.cs b/src/ViewModels/Pull.cs index 1ddd6d999..20585a2df 100644 --- a/src/ViewModels/Pull.cs +++ b/src/ViewModels/Pull.cs @@ -83,7 +83,7 @@ public Pull(Repository repo, Models.Branch specifiedRemoteBranch) } else { - var autoSelectedRemote = null as Models.Remote; + Models.Remote autoSelectedRemote = null; if (!string.IsNullOrEmpty(Current.Upstream)) { var remoteNameEndIdx = Current.Upstream.IndexOf('/', 13); @@ -96,7 +96,7 @@ public Pull(Repository repo, Models.Branch specifiedRemoteBranch) if (autoSelectedRemote == null) { - var remote = null as Models.Remote; + Models.Remote remote = null; if (!string.IsNullOrEmpty(_repo.Settings.DefaultRemote)) remote = _repo.Remotes.Find(x => x.Name == _repo.Settings.DefaultRemote); _selectedRemote = remote ?? _repo.Remotes[0]; diff --git a/src/ViewModels/Push.cs b/src/ViewModels/Push.cs index 917935b04..7313dd900 100644 --- a/src/ViewModels/Push.cs +++ b/src/ViewModels/Push.cs @@ -102,7 +102,7 @@ public Push(Repository repo, Models.Branch localBranch) // Gather all local branches and find current branch. LocalBranches = new List(); - var current = null as Models.Branch; + Models.Branch current = null; foreach (var branch in _repo.Branches) { if (branch.IsLocal) @@ -142,7 +142,7 @@ public Push(Repository repo, Models.Branch localBranch) // Set default remote to the first if it has not been set. if (_selectedRemote == null) { - var remote = null as Models.Remote; + Models.Remote remote = null; if (!string.IsNullOrEmpty(_repo.Settings.DefaultRemote)) remote = repo.Remotes.Find(x => x.Name == _repo.Settings.DefaultRemote); diff --git a/src/ViewModels/RevisionCompare.cs b/src/ViewModels/RevisionCompare.cs index 0af66a309..573bac54c 100644 --- a/src/ViewModels/RevisionCompare.cs +++ b/src/ViewModels/RevisionCompare.cs @@ -39,7 +39,7 @@ public List SelectedChanges { if (SetProperty(ref _selectedChanges, value)) { - if (value != null && value.Count == 1) + if (value?.Count == 1) { var option = new Models.DiffOption(GetSHA(_startPoint), GetSHA(_endPoint), value[0]); DiffContext = new DiffContext(_repo, option, _diffContext); @@ -85,12 +85,9 @@ public void Dispose() _repo = null; _startPoint = null; _endPoint = null; - if (_changes != null) - _changes.Clear(); - if (_visibleChanges != null) - _visibleChanges.Clear(); - if (_selectedChanges != null) - _selectedChanges.Clear(); + _changes?.Clear(); + _visibleChanges?.Clear(); + _selectedChanges?.Clear(); _searchFilter = null; _diffContext = null; } diff --git a/src/ViewModels/RevisionFileTreeNode.cs b/src/ViewModels/RevisionFileTreeNode.cs index 083e9d332..2f94d40d9 100644 --- a/src/ViewModels/RevisionFileTreeNode.cs +++ b/src/ViewModels/RevisionFileTreeNode.cs @@ -18,7 +18,7 @@ public string Name public bool IsFolder { - get => Backend != null && Backend.Type == Models.ObjectType.Tree; + get => Backend?.Type == Models.ObjectType.Tree; } public bool IsExpanded diff --git a/src/ViewModels/StashesPage.cs b/src/ViewModels/StashesPage.cs index 431f61e63..5e97f3f2d 100644 --- a/src/ViewModels/StashesPage.cs +++ b/src/ViewModels/StashesPage.cs @@ -67,8 +67,7 @@ public Models.Stash SelectedStash untracked = new Commands.CompareRevisions(_repo.FullPath, Models.Commit.EmptyTreeSHA1, value.Parents[2]).Result(); var needSort = changes.Count > 0 && untracked.Count > 0; - foreach (var c in untracked) - changes.Add(c); + changes.AddRange(untracked); if (needSort) changes.Sort((l, r) => Models.NumericSort.Compare(l.Path, r.Path)); diff --git a/src/ViewModels/WorkingCopy.cs b/src/ViewModels/WorkingCopy.cs index b53d0d2f6..6dbd4cdc6 100644 --- a/src/ViewModels/WorkingCopy.cs +++ b/src/ViewModels/WorkingCopy.cs @@ -167,7 +167,7 @@ public List SelectedUnstaged } else { - if (_selectedStaged != null && _selectedStaged.Count > 0) + if (_selectedStaged?.Count > 0) SelectedStaged = []; if (value.Count == 1) @@ -193,7 +193,7 @@ public List SelectedStaged } else { - if (_selectedUnstaged != null && _selectedUnstaged.Count > 0) + if (_selectedUnstaged?.Count > 0) SelectedUnstaged = []; if (value.Count == 1) @@ -269,12 +269,12 @@ public void SetData(List changes) var lastSelectedUnstaged = new HashSet(); var lastSelectedStaged = new HashSet(); - if (_selectedUnstaged != null && _selectedUnstaged.Count > 0) + if (_selectedUnstaged?.Count > 0) { foreach (var c in _selectedUnstaged) lastSelectedUnstaged.Add(c.Path); } - else if (_selectedStaged != null && _selectedStaged.Count > 0) + else if (_selectedStaged?.Count > 0) { foreach (var c in _selectedStaged) lastSelectedStaged.Add(c.Path); @@ -1203,7 +1203,7 @@ public ContextMenu CreateContextMenuForStagedChanges(string selectedSingleFolder var menu = new ContextMenu(); - var ai = null as MenuItem; + MenuItem ai = null; var services = _repo.GetPreferredOpenAIServices(); if (services.Count > 0) { @@ -1796,7 +1796,7 @@ private async void StageChanges(List changes, Models.Change next) else { var pathSpecFile = Path.GetTempFileName(); - using (var writer = new StreamWriter(pathSpecFile)) + await using (var writer = new StreamWriter(pathSpecFile)) { foreach (var c in changes) await writer.WriteLineAsync(c.Path); @@ -1833,7 +1833,7 @@ private async void UnstageChanges(List changes, Models.Change nex else { var pathSpecFile = Path.GetTempFileName(); - using (var writer = new StreamWriter(pathSpecFile)) + await using (var writer = new StreamWriter(pathSpecFile)) { foreach (var c in changes) { diff --git a/src/Views/AddWorktree.axaml.cs b/src/Views/AddWorktree.axaml.cs index c39c89285..4ac2d85f1 100644 --- a/src/Views/AddWorktree.axaml.cs +++ b/src/Views/AddWorktree.axaml.cs @@ -25,7 +25,7 @@ private async void SelectLocation(object _, RoutedEventArgs e) if (selected.Count == 1) { var folder = selected[0]; - var folderPath = folder is { Path: { IsAbsoluteUri: true } path } ? path.LocalPath : folder?.Path.ToString(); + var folderPath = folder is { Path: { IsAbsoluteUri: true } path } ? path.LocalPath : folder.Path.ToString(); TxtLocation.Text = folderPath.TrimEnd('\\', '/'); } } diff --git a/src/Views/Blame.axaml.cs b/src/Views/Blame.axaml.cs index 5f49fa340..d760f7971 100644 --- a/src/Views/Blame.axaml.cs +++ b/src/Views/Blame.axaml.cs @@ -90,7 +90,7 @@ protected override Size MeasureOverride(Size availableSize) { var view = TextView; var maxWidth = 0.0; - if (view != null && view.VisualLinesValid && _editor.BlameData != null) + if (view is { VisualLinesValid: true } && _editor.BlameData != null) { var typeface = view.CreateTypeface(); var calculated = new HashSet(); diff --git a/src/Views/BranchTree.axaml.cs b/src/Views/BranchTree.axaml.cs index 57cfa88da..e19daa77f 100644 --- a/src/Views/BranchTree.axaml.cs +++ b/src/Views/BranchTree.axaml.cs @@ -401,7 +401,7 @@ private void OnNodesSelectionChanged(object _, SelectionChangedEventArgs e) if (selected == null || selected.Count == 0) return; - var prev = null as ViewModels.BranchTreeNode; + ViewModels.BranchTreeNode prev = null; foreach (var row in Rows) { if (row.IsSelected) diff --git a/src/Views/CaptionButtons.axaml.cs b/src/Views/CaptionButtons.axaml.cs index 650ccef0f..806d9cb5e 100644 --- a/src/Views/CaptionButtons.axaml.cs +++ b/src/Views/CaptionButtons.axaml.cs @@ -42,8 +42,7 @@ private void MaximizeOrRestoreWindow(object _, RoutedEventArgs e) private void CloseWindow(object _, RoutedEventArgs e) { var window = this.FindAncestorOfType(); - if (window != null) - window.Close(); + window?.Close(); e.Handled = true; } diff --git a/src/Views/ChangeCollectionView.axaml.cs b/src/Views/ChangeCollectionView.axaml.cs index 6623a60b5..3a59b87cc 100644 --- a/src/Views/ChangeCollectionView.axaml.cs +++ b/src/Views/ChangeCollectionView.axaml.cs @@ -379,9 +379,7 @@ private void UpdateDataSource(bool onlyViewModeChange) } else if (selected.Count > 0) { - var sets = new HashSet(); - foreach (var c in selected) - sets.Add(c); + var sets = new HashSet(selected); var nodes = new List(); foreach (var row in tree.Rows) @@ -447,9 +445,7 @@ private void UpdateSelection() if (selected.Count > 0) { - var sets = new HashSet(); - foreach (var c in selected) - sets.Add(c); + var sets = new HashSet(selected); var nodes = new List(); foreach (var row in tree.Rows) diff --git a/src/Views/ChromelessWindow.cs b/src/Views/ChromelessWindow.cs index 1662bcd77..d097275d8 100644 --- a/src/Views/ChromelessWindow.cs +++ b/src/Views/ChromelessWindow.cs @@ -70,7 +70,7 @@ protected override void OnApplyTemplate(TemplateAppliedEventArgs e) private void OnWindowBorderPointerPressed(object sender, PointerPressedEventArgs e) { - if (sender is Border border && border.Tag is WindowEdge edge && CanResize) + if (sender is Border { Tag: WindowEdge edge } && CanResize) BeginResizeDrag(edge, e); } } diff --git a/src/Views/CommitDetail.axaml.cs b/src/Views/CommitDetail.axaml.cs index f0599c660..23c6bd42f 100644 --- a/src/Views/CommitDetail.axaml.cs +++ b/src/Views/CommitDetail.axaml.cs @@ -12,7 +12,7 @@ public CommitDetail() private void OnChangeDoubleTapped(object sender, TappedEventArgs e) { - if (DataContext is ViewModels.CommitDetail detail && sender is Grid grid && grid.DataContext is Models.Change change) + if (DataContext is ViewModels.CommitDetail detail && sender is Grid { DataContext: Models.Change change }) { detail.ActivePageIndex = 1; detail.SelectedChanges = new() { change }; @@ -23,7 +23,7 @@ private void OnChangeDoubleTapped(object sender, TappedEventArgs e) private void OnChangeContextRequested(object sender, ContextRequestedEventArgs e) { - if (DataContext is ViewModels.CommitDetail detail && sender is Grid grid && grid.DataContext is Models.Change change) + if (DataContext is ViewModels.CommitDetail detail && sender is Grid { DataContext: Models.Change change } grid) { var menu = detail.CreateChangeContextMenu(change); menu?.Open(grid); diff --git a/src/Views/CommitRefsPresenter.cs b/src/Views/CommitRefsPresenter.cs index 7a473f8bd..d9b0e57e4 100644 --- a/src/Views/CommitRefsPresenter.cs +++ b/src/Views/CommitRefsPresenter.cs @@ -179,7 +179,7 @@ protected override Size MeasureOverride(Size availableSize) return new Size(0, 0); var refs = commit.Decorators; - if (refs != null && refs.Count > 0) + if (refs?.Count > 0) { var typeface = new Typeface(FontFamily); var typefaceBold = new Typeface(FontFamily, FontStyle.Normal, FontWeight.Bold); diff --git a/src/Views/ConfirmRestart.axaml.cs b/src/Views/ConfirmRestart.axaml.cs index ea49bea17..f77a0dc12 100644 --- a/src/Views/ConfirmRestart.axaml.cs +++ b/src/Views/ConfirmRestart.axaml.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; using Avalonia.Interactivity; @@ -12,12 +11,6 @@ public ConfirmRestart() InitializeComponent(); } - private void CloseWindow(object _1, RoutedEventArgs _2) - { - Console.Out.WriteLine("No passphrase entered."); - App.Quit(-1); - } - private void Restart(object _1, RoutedEventArgs _2) { var selfExecFile = Process.GetCurrentProcess().MainModule!.FileName; diff --git a/src/Views/DiffView.axaml.cs b/src/Views/DiffView.axaml.cs index 54f9617af..53fe08030 100644 --- a/src/Views/DiffView.axaml.cs +++ b/src/Views/DiffView.axaml.cs @@ -45,10 +45,8 @@ private void OnBlockNavigationChanged(object sender, RoutedEventArgs e) private void OnUseFullTextDiffClicked(object sender, RoutedEventArgs e) { var textDiffView = this.FindDescendantOfType(); - if (textDiffView == null) - return; - var presenter = textDiffView.FindDescendantOfType(); + var presenter = textDiffView?.FindDescendantOfType(); if (presenter == null) return; diff --git a/src/Views/ExecuteCustomAction.axaml.cs b/src/Views/ExecuteCustomAction.axaml.cs index e454d4a12..4218b4933 100644 --- a/src/Views/ExecuteCustomAction.axaml.cs +++ b/src/Views/ExecuteCustomAction.axaml.cs @@ -35,10 +35,8 @@ private async void SelectPath(object sender, RoutedEventArgs e) return; var control = sender as Control; - if (control == null) - return; - var selector = control.DataContext as ViewModels.CustomActionControlPathSelector; + var selector = control?.DataContext as ViewModels.CustomActionControlPathSelector; if (selector == null) return; diff --git a/src/Views/FilterModeSwitchButton.axaml.cs b/src/Views/FilterModeSwitchButton.axaml.cs index b3b2c3daa..c789bfe31 100644 --- a/src/Views/FilterModeSwitchButton.axaml.cs +++ b/src/Views/FilterModeSwitchButton.axaml.cs @@ -56,10 +56,8 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang private void OnChangeFilterModeButtonClicked(object sender, RoutedEventArgs e) { var repoView = this.FindAncestorOfType(); - if (repoView == null) - return; - var repo = repoView.DataContext as ViewModels.Repository; + var repo = repoView?.DataContext as ViewModels.Repository; if (repo == null) return; diff --git a/src/Views/Histories.axaml b/src/Views/Histories.axaml index eafb7c32e..ae8bb3bdd 100644 --- a/src/Views/Histories.axaml +++ b/src/Views/Histories.axaml @@ -47,10 +47,6 @@ ContextRequested="OnCommitListContextRequested" DoubleTapped="OnCommitListDoubleTapped" KeyDown="OnCommitListKeyDown"> - - - - - + - + @@ -159,7 +155,7 @@ - + @@ -188,7 +184,7 @@ - + diff --git a/src/Views/Histories.axaml.cs b/src/Views/Histories.axaml.cs index 82928ebaa..1856e7634 100644 --- a/src/Views/Histories.axaml.cs +++ b/src/Views/Histories.axaml.cs @@ -161,11 +161,9 @@ private void OnCommitListLayoutUpdated(object _1, EventArgs _2) double startY = 0; foreach (var child in rowsPresenter.Children) { - var row = child as DataGridRow; - if (row.IsVisible) + if (child is DataGridRow { IsVisible: true } row) { - if (rowHeight != row.Bounds.Height) - rowHeight = row.Bounds.Height; + rowHeight = row.Bounds.Height; if (row.Bounds.Top <= 0 && row.Bounds.Top > -rowHeight) { @@ -237,10 +235,8 @@ private void OnCommitListKeyDown(object sender, KeyEventArgs e) if (e.Key == Key.B) { var repoView = this.FindAncestorOfType(); - if (repoView == null) - return; - var repo = repoView.DataContext as ViewModels.Repository; + var repo = repoView?.DataContext as ViewModels.Repository; if (repo == null || !repo.CanCreatePopup()) return; @@ -260,7 +256,7 @@ private void OnCommitListDoubleTapped(object sender, TappedEventArgs e) if (DataContext is ViewModels.Histories histories && CommitListContainer.SelectedItems is { Count: 1 } && sender is DataGrid grid && - e.Source != grid) + !Equals(e.Source, grid)) { if (e.Source is CommitRefsPresenter crp) { diff --git a/src/Views/InteractiveRebase.axaml.cs b/src/Views/InteractiveRebase.axaml.cs index 0facc781c..e40ce276a 100644 --- a/src/Views/InteractiveRebase.axaml.cs +++ b/src/Views/InteractiveRebase.axaml.cs @@ -87,7 +87,7 @@ private void OnSetupRowHeaderDragDrop(object sender, RoutedEventArgs e) private void OnRowHeaderPointerPressed(object sender, PointerPressedEventArgs e) { - if (sender is Border border && border.DataContext is ViewModels.InteractiveRebaseItem item) + if (sender is Border { DataContext: ViewModels.InteractiveRebaseItem item }) { var data = new DataObject(); data.Set("InteractiveRebaseItem", item); diff --git a/src/Views/RepositoryConfigure.axaml b/src/Views/RepositoryConfigure.axaml index c3fd68f11..2cc935ddc 100644 --- a/src/Views/RepositoryConfigure.axaml +++ b/src/Views/RepositoryConfigure.axaml @@ -499,7 +499,7 @@ - + diff --git a/src/Views/RepositoryToolbar.axaml.cs b/src/Views/RepositoryToolbar.axaml.cs index e18b0e810..aad6fef31 100644 --- a/src/Views/RepositoryToolbar.axaml.cs +++ b/src/Views/RepositoryToolbar.axaml.cs @@ -118,8 +118,7 @@ private void OpenGitLFSMenu(object sender, RoutedEventArgs e) private void StartBisect(object sender, RoutedEventArgs e) { - if (DataContext is ViewModels.Repository { IsBisectCommandRunning: false } repo && - repo.InProgressContext == null && + if (DataContext is ViewModels.Repository { IsBisectCommandRunning: false, InProgressContext: null } repo && repo.CanCreatePopup()) { if (repo.LocalChangesCount > 0) diff --git a/src/Views/RevisionFileTreeView.axaml.cs b/src/Views/RevisionFileTreeView.axaml.cs index 65ef462f4..8b7d8b402 100644 --- a/src/Views/RevisionFileTreeView.axaml.cs +++ b/src/Views/RevisionFileTreeView.axaml.cs @@ -216,7 +216,7 @@ public void ToggleNodeIsExpanded(ViewModels.RevisionFileTreeNode node) if (node.IsExpanded) { var subtree = GetChildrenOfTreeNode(node); - if (subtree != null && subtree.Count > 0) + if (subtree?.Count > 0) { var subrows = new List(); MakeRows(subrows, subtree, depth + 1); @@ -320,10 +320,8 @@ private void OnRowsSelectionChanged(object sender, SelectionChangedEventArgs _) return node.Children; var vm = DataContext as ViewModels.CommitDetail; - if (vm == null) - return null; - var objects = vm.GetRevisionFilesUnderFolder(node.Backend.Path + "/"); + var objects = vm?.GetRevisionFilesUnderFolder(node.Backend.Path + "/"); if (objects == null || objects.Count == 0) return null; diff --git a/src/Views/StashChanges.axaml b/src/Views/StashChanges.axaml index 8ddc3adf0..212259418 100644 --- a/src/Views/StashChanges.axaml +++ b/src/Views/StashChanges.axaml @@ -32,7 +32,7 @@ - + + Foreground="{DynamicResource Brush.FG2}"/> (); - if (repoView == null) - return; - var repo = repoView.DataContext as ViewModels.Repository; + var repo = repoView?.DataContext as ViewModels.Repository; if (repo == null) return; @@ -1888,10 +1878,8 @@ private void OnUnstageChunk(object _1, RoutedEventArgs _2) return; var diff = DataContext as Models.TextDiff; - if (diff == null) - return; - var change = diff.Option.WorkingCopyChange; + var change = diff?.Option.WorkingCopyChange; if (change == null) return; @@ -1900,10 +1888,8 @@ private void OnUnstageChunk(object _1, RoutedEventArgs _2) return; var repoView = this.FindAncestorOfType(); - if (repoView == null) - return; - var repo = repoView.DataContext as ViewModels.Repository; + var repo = repoView?.DataContext as ViewModels.Repository; if (repo == null) return; @@ -1942,10 +1928,8 @@ private void OnDiscardChunk(object _1, RoutedEventArgs _2) return; var diff = DataContext as Models.TextDiff; - if (diff == null) - return; - var change = diff.Option.WorkingCopyChange; + var change = diff?.Option.WorkingCopyChange; if (change == null) return; @@ -1954,10 +1938,8 @@ private void OnDiscardChunk(object _1, RoutedEventArgs _2) return; var repoView = this.FindAncestorOfType(); - if (repoView == null) - return; - var repo = repoView.DataContext as ViewModels.Repository; + var repo = repoView?.DataContext as ViewModels.Repository; if (repo == null) return; diff --git a/src/Views/Welcome.axaml.cs b/src/Views/Welcome.axaml.cs index 75ac40797..0483a9903 100644 --- a/src/Views/Welcome.axaml.cs +++ b/src/Views/Welcome.axaml.cs @@ -208,10 +208,8 @@ private void DragOverTreeNode(object sender, DragEventArgs e) if (e.Data.Contains("MovedRepositoryTreeNode") || e.Data.Contains(DataFormats.Files)) { var grid = sender as Grid; - if (grid == null) - return; - var to = grid.DataContext as ViewModels.RepositoryNode; + var to = grid?.DataContext as ViewModels.RepositoryNode; if (to == null) return;