code_style: general cleanup (#1497)

This commit is contained in:
Nathan Baulch
2025-07-03 12:32:03 +10:00
committed by GitHub
parent baeef2d924
commit ec17ea9901
58 changed files with 134 additions and 236 deletions

View File

@@ -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/*

View File

@@ -148,23 +148,21 @@ namespace SourceGit
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 @@ namespace SourceGit
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<string> 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 @@ namespace SourceGit
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;

View File

@@ -43,7 +43,7 @@ namespace SourceGit.Commands
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
{

View File

@@ -132,9 +132,7 @@ namespace SourceGit.Commands
if (shas.Length == 0)
return;
var set = new HashSet<string>();
foreach (var sha in shas)
set.Add(sha);
var set = new HashSet<string>(shas);
foreach (var c in _commits)
{

View File

@@ -18,10 +18,7 @@ namespace SourceGit.Commands
return [];
var lines = rs.StdOut.Split('\0', System.StringSplitOptions.RemoveEmptyEntries);
var outs = new List<string>();
foreach (var line in lines)
outs.Add(line);
return outs;
return [.. lines];
}
}
}

View File

@@ -18,7 +18,7 @@ namespace SourceGit.Commands
var rs = ReadToEnd();
var worktrees = new List<Models.Worktree>();
var last = null as Models.Worktree;
Models.Worktree last = null;
if (rs.IsSuccess)
{
var lines = rs.StdOut.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);

View File

@@ -55,7 +55,7 @@ namespace SourceGit.Models
{
while (true)
{
var email = null as string;
string email = null;
lock (_synclock)
{
@@ -79,7 +79,7 @@ namespace SourceGit.Models
$"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 @@ namespace SourceGit.Models
_requesting.Remove(email);
}
Dispatcher.UIThread.InvokeAsync(() =>
Dispatcher.UIThread.Post(() =>
{
_resources[email] = img;
NotifyResourceChanged(email, img);

View File

@@ -82,7 +82,7 @@ namespace SourceGit.Models
foreach (var commit in commits)
{
var major = null as PathHelper;
PathHelper major = null;
var isMerged = commit.IsMerged;
// Update current y offset

View File

@@ -27,19 +27,19 @@ namespace SourceGit.Models
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/"));
}
}

View File

@@ -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<DealWithChangesAfterStashing> 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;
}
}
}

View File

@@ -199,7 +199,7 @@ namespace SourceGit.Models
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 @@ namespace SourceGit.Models
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];

View File

@@ -96,16 +96,9 @@ namespace SourceGit.Models
{
return Exec.Split(';');
}
else
{
var patterns = new List<string>();
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);
}
}
}

View File

@@ -50,7 +50,7 @@ namespace SourceGit.Models
var ret = new List<TextInlineChange>();
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)

View File

@@ -257,7 +257,7 @@ namespace SourceGit.Native
{
// 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)

View File

@@ -34,7 +34,7 @@ namespace SourceGit.ViewModels
public bool IsBinary
{
get => _data != null && _data.IsBinary;
get => _data?.IsBinary ?? false;
}
public bool CanBack

View File

@@ -49,7 +49,7 @@ namespace SourceGit.ViewModels
{
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;

View File

@@ -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 @@ namespace SourceGit.ViewModels
public void SetExpandedNodes(List<string> expanded)
{
foreach (var node in expanded)
_expanded.Add(node);
_expanded.AddRange(expanded);
}
public void Run(List<Models.Branch> branches, List<Models.Remote> remotes, bool bForceExpanded)
@@ -165,7 +165,7 @@ namespace SourceGit.ViewModels
return;
}
var lastFolder = null as BranchTreeNode;
BranchTreeNode lastFolder = null;
var start = 0;
while (sepIdx != -1)
@@ -250,8 +250,7 @@ namespace SourceGit.ViewModels
{
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)

View File

@@ -49,7 +49,7 @@ namespace SourceGit.ViewModels
var updateSubmodules = IsRecurseSubmoduleVisible && RecurseSubmodules;
return Task.Run(() =>
{
var succ = false;
bool succ;
var needPopStash = false;
if (!_repo.ConfirmCheckoutBranch())

View File

@@ -151,7 +151,7 @@ namespace SourceGit.ViewModels
{
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)

View File

@@ -17,7 +17,7 @@ namespace SourceGit.ViewModels
set
{
if (SetProperty(ref _selected, value))
CanDeleteSelected = value != null && !value.IsActive;
CanDeleteSelected = value is { IsActive: false };
}
}

View File

@@ -72,10 +72,9 @@ namespace SourceGit.ViewModels
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");

View File

@@ -112,10 +112,8 @@ namespace SourceGit.ViewModels
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<bool> Sure()
@@ -188,7 +186,7 @@ namespace SourceGit.ViewModels
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('/');

View File

@@ -120,7 +120,7 @@ namespace SourceGit.ViewModels
_info = info;
var rs = null as object;
object rs = null;
if (latest.TextDiff != null)
{
var count = latest.TextDiff.Lines.Count;

View File

@@ -207,14 +207,13 @@ namespace SourceGit.ViewModels
{
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()

View File

@@ -261,7 +261,7 @@ namespace SourceGit.ViewModels
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 @@ namespace SourceGit.ViewModels
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 @@ namespace SourceGit.ViewModels
return;
var options = new FolderPickerOpenOptions() { AllowMultiple = false };
var log = null as CommandLog;
CommandLog log = null;
try
{
var selected = await storageProvider.OpenFolderPickerAsync(options);

View File

@@ -86,19 +86,11 @@ namespace SourceGit.ViewModels
{
var visible = new List<Models.LFSLock>();
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;
}

View File

@@ -417,8 +417,7 @@ namespace SourceGit.ViewModels
}
}
if (_activePage != null)
_activePage.Notifications.Add(notification);
_activePage?.Notifications.Add(notification);
}
public ContextMenu CreateContextForWorkspace()

View File

@@ -584,13 +584,6 @@ namespace SourceGit.ViewModels
}
}
private void SortNodesRecursive(List<RepositoryNode> collection)
{
SortNodes(collection);
foreach (var node in collection)
SortNodesRecursive(node.SubNodes);
}
private RepositoryNode FindNodeRecursive(string id, List<RepositoryNode> collection)
{
foreach (var node in collection)

View File

@@ -83,7 +83,7 @@ namespace SourceGit.ViewModels
}
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 @@ namespace SourceGit.ViewModels
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];

View File

@@ -102,7 +102,7 @@ namespace SourceGit.ViewModels
// Gather all local branches and find current branch.
LocalBranches = new List<Models.Branch>();
var current = null as Models.Branch;
Models.Branch current = null;
foreach (var branch in _repo.Branches)
{
if (branch.IsLocal)
@@ -142,7 +142,7 @@ namespace SourceGit.ViewModels
// 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);

View File

@@ -39,7 +39,7 @@ namespace SourceGit.ViewModels
{
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 @@ namespace SourceGit.ViewModels
_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;
}

View File

@@ -18,7 +18,7 @@ namespace SourceGit.ViewModels
public bool IsFolder
{
get => Backend != null && Backend.Type == Models.ObjectType.Tree;
get => Backend?.Type == Models.ObjectType.Tree;
}
public bool IsExpanded

View File

@@ -67,8 +67,7 @@ namespace SourceGit.ViewModels
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));

View File

@@ -167,7 +167,7 @@ namespace SourceGit.ViewModels
}
else
{
if (_selectedStaged != null && _selectedStaged.Count > 0)
if (_selectedStaged?.Count > 0)
SelectedStaged = [];
if (value.Count == 1)
@@ -193,7 +193,7 @@ namespace SourceGit.ViewModels
}
else
{
if (_selectedUnstaged != null && _selectedUnstaged.Count > 0)
if (_selectedUnstaged?.Count > 0)
SelectedUnstaged = [];
if (value.Count == 1)
@@ -269,12 +269,12 @@ namespace SourceGit.ViewModels
var lastSelectedUnstaged = new HashSet<string>();
var lastSelectedStaged = new HashSet<string>();
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 @@ namespace SourceGit.ViewModels
var menu = new ContextMenu();
var ai = null as MenuItem;
MenuItem ai = null;
var services = _repo.GetPreferredOpenAIServices();
if (services.Count > 0)
{
@@ -1796,7 +1796,7 @@ namespace SourceGit.ViewModels
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 @@ namespace SourceGit.ViewModels
else
{
var pathSpecFile = Path.GetTempFileName();
using (var writer = new StreamWriter(pathSpecFile))
await using (var writer = new StreamWriter(pathSpecFile))
{
foreach (var c in changes)
{

View File

@@ -25,7 +25,7 @@ namespace SourceGit.Views
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('\\', '/');
}
}

View File

@@ -90,7 +90,7 @@ namespace SourceGit.Views
{
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<string>();

View File

@@ -401,7 +401,7 @@ namespace SourceGit.Views
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)

View File

@@ -42,8 +42,7 @@ namespace SourceGit.Views
private void CloseWindow(object _, RoutedEventArgs e)
{
var window = this.FindAncestorOfType<Window>();
if (window != null)
window.Close();
window?.Close();
e.Handled = true;
}

View File

@@ -379,9 +379,7 @@ namespace SourceGit.Views
}
else if (selected.Count > 0)
{
var sets = new HashSet<Models.Change>();
foreach (var c in selected)
sets.Add(c);
var sets = new HashSet<Models.Change>(selected);
var nodes = new List<ViewModels.ChangeTreeNode>();
foreach (var row in tree.Rows)
@@ -447,9 +445,7 @@ namespace SourceGit.Views
if (selected.Count > 0)
{
var sets = new HashSet<Models.Change>();
foreach (var c in selected)
sets.Add(c);
var sets = new HashSet<Models.Change>(selected);
var nodes = new List<ViewModels.ChangeTreeNode>();
foreach (var row in tree.Rows)

View File

@@ -70,7 +70,7 @@ namespace SourceGit.Views
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);
}
}

View File

@@ -12,7 +12,7 @@ namespace SourceGit.Views
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 @@ namespace SourceGit.Views
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);

View File

@@ -179,7 +179,7 @@ namespace SourceGit.Views
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);

View File

@@ -1,4 +1,3 @@
using System;
using System.Diagnostics;
using Avalonia.Interactivity;
@@ -12,12 +11,6 @@ namespace SourceGit.Views
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;

View File

@@ -45,10 +45,8 @@ namespace SourceGit.Views
private void OnUseFullTextDiffClicked(object sender, RoutedEventArgs e)
{
var textDiffView = this.FindDescendantOfType<TextDiffView>();
if (textDiffView == null)
return;
var presenter = textDiffView.FindDescendantOfType<ThemedTextDiffPresenter>();
var presenter = textDiffView?.FindDescendantOfType<ThemedTextDiffPresenter>();
if (presenter == null)
return;

View File

@@ -35,10 +35,8 @@ namespace SourceGit.Views
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;

View File

@@ -56,10 +56,8 @@ namespace SourceGit.Views
private void OnChangeFilterModeButtonClicked(object sender, RoutedEventArgs e)
{
var repoView = this.FindAncestorOfType<Repository>();
if (repoView == null)
return;
var repo = repoView.DataContext as ViewModels.Repository;
var repo = repoView?.DataContext as ViewModels.Repository;
if (repo == null)
return;

View File

@@ -47,10 +47,6 @@
ContextRequested="OnCommitListContextRequested"
DoubleTapped="OnCommitListDoubleTapped"
KeyDown="OnCommitListKeyDown">
<DataGrid.Resources>
<SolidColorBrush x:Key="DataGridGridLinesBrush" Color="{DynamicResource Color.Border0}" />
</DataGrid.Resources>
<DataGrid.Styles>
<Style Selector="DataGridColumnHeader">
<Setter Property="MinHeight" Value="24"/>
@@ -75,7 +71,7 @@
VerticalAlignment="Stretch"
Fill="{DynamicResource Brush.Border0}"
IsVisible="{TemplateBinding AreSeparatorsVisible}" />
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter>
@@ -96,13 +92,13 @@
</Setter>
</Style>
</DataGrid.Styles>
<DataGrid.Columns>
<DataGridTemplateColumn Width="*" IsReadOnly="True">
<DataGridTemplateColumn.Header>
<TextBlock Classes="table_header" Text="{DynamicResource Text.Histories.Header.GraphAndSubject}" HorizontalAlignment="Center"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="m:Commit">
<Border Padding="{Binding Margin}" ClipToBounds="True" Background="Transparent">
@@ -159,7 +155,7 @@
<DataGridTemplateColumn.Header>
<TextBlock Classes="table_header" Text="{DynamicResource Text.Histories.Header.Author}" HorizontalAlignment="Center"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="m:Commit">
<Grid ColumnDefinitions="20,*" Background="Transparent">
@@ -188,7 +184,7 @@
<DataGridTemplateColumn.Header>
<TextBlock Classes="table_header" Text="{DynamicResource Text.Histories.Header.SHA}" HorizontalAlignment="Center"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="m:Commit">
<Border Padding="8,0,0,0" Background="Transparent" ClipToBounds="True">

View File

@@ -161,11 +161,9 @@ namespace SourceGit.Views
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 @@ namespace SourceGit.Views
if (e.Key == Key.B)
{
var repoView = this.FindAncestorOfType<Repository>();
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 @@ namespace SourceGit.Views
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)
{

View File

@@ -87,7 +87,7 @@ namespace SourceGit.Views
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);

View File

@@ -499,7 +499,7 @@
</StackPanel>
</Button>
<TextBlock Margin="0,2,0,0" TextWrapping="Wrap" Text="{DynamicResource Text.Configure.CustomAction.InputControls.Tip}" Foreground="{DynamicResource Brush.FG2}"/>
<CheckBox Margin="0,8,0,0" Content="{DynamicResource Text.Configure.CustomAction.WaitForExit}" IsChecked="{Binding WaitForExit, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>

View File

@@ -118,8 +118,7 @@ namespace SourceGit.Views
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)

View File

@@ -216,7 +216,7 @@ namespace SourceGit.Views
if (node.IsExpanded)
{
var subtree = GetChildrenOfTreeNode(node);
if (subtree != null && subtree.Count > 0)
if (subtree?.Count > 0)
{
var subrows = new List<ViewModels.RevisionFileTreeNode>();
MakeRows(subrows, subtree, depth + 1);
@@ -320,10 +320,8 @@ namespace SourceGit.Views
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;

View File

@@ -32,7 +32,7 @@
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0,8,8,0"
@@ -54,7 +54,7 @@
Margin="0,2,4,4"
Text="{DynamicResource Text.PopupEnterKeyTip}"
TextWrapping="Wrap"
Foreground="{DynamicResource Brush.FG2}"/>
Foreground="{DynamicResource Brush.FG2}"/>
<CheckBox Grid.Row="3" Grid.Column="1"
Height="32"

View File

@@ -67,7 +67,7 @@ namespace SourceGit.Views
var foreground = Foreground;
var x = 0.0;
var h = Bounds.Height;
var prefix = null as FormattedText;
FormattedText prefix = null;
var match = REG_KEYWORD_ON().Match(subject);
if (match.Success)

View File

@@ -164,7 +164,7 @@ namespace SourceGit.Views
{
if (sender is Control control && DataContext is ViewModels.Repository repo)
{
if (control.DataContext is ViewModels.SubmoduleTreeNode node && node.Module != null)
if (control.DataContext is ViewModels.SubmoduleTreeNode { Module: not null } node)
{
var menu = repo.CreateContextMenuForSubmodule(node.Module);
menu?.Open(control);

View File

@@ -205,7 +205,7 @@ namespace SourceGit.Views
private void OnSelectionChanged(object sender, SelectionChangedEventArgs _)
{
var selected = (sender as ListBox)?.SelectedItem;
var selectedTag = null as Models.Tag;
Models.Tag selectedTag = null;
if (selected is ViewModels.TagTreeNode node)
selectedTag = node.Tag;
else if (selected is Models.Tag tag)

View File

@@ -101,7 +101,7 @@ namespace SourceGit.Views
var lines = presenter.GetLines();
var view = TextView;
if (view != null && view.VisualLinesValid)
if (view?.VisualLinesValid ?? false)
{
var typeface = view.CreateTypeface();
foreach (var line in view.VisualLines)
@@ -175,7 +175,7 @@ namespace SourceGit.Views
var lines = presenter.GetLines();
var view = TextView;
if (view != null && view.VisualLinesValid)
if (view?.VisualLinesValid ?? false)
{
var typeface = view.CreateTypeface();
foreach (var line in view.VisualLines)
@@ -189,7 +189,7 @@ namespace SourceGit.Views
var info = lines[index - 1];
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.LineMiddle) - view.VerticalOffset;
var indicator = null as FormattedText;
FormattedText indicator = null;
if (info.Type == Models.TextDiffLineType.Added)
{
indicator = new FormattedText(
@@ -545,14 +545,11 @@ namespace SourceGit.Views
public virtual void GotoFirstChange()
{
var blockNavigation = BlockNavigation;
if (blockNavigation != null)
var prev = blockNavigation?.GotoFirst();
if (prev != null)
{
var prev = blockNavigation.GotoFirst();
if (prev != null)
{
TextArea.Caret.Line = prev.Start;
ScrollToLine(prev.Start);
}
TextArea.Caret.Line = prev.Start;
ScrollToLine(prev.Start);
}
}
@@ -657,14 +654,11 @@ namespace SourceGit.Views
public virtual void GotoLastChange()
{
var blockNavigation = BlockNavigation;
if (blockNavigation != null)
var next = blockNavigation?.GotoLast();
if (next != null)
{
var next = blockNavigation.GotoLast();
if (next != null)
{
TextArea.Caret.Line = next.Start;
ScrollToLine(next.Start);
}
TextArea.Caret.Line = next.Start;
ScrollToLine(next.Start);
}
}
@@ -1830,10 +1824,8 @@ namespace SourceGit.Views
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;
@@ -1842,10 +1834,8 @@ namespace SourceGit.Views
return;
var repoView = this.FindAncestorOfType<Repository>();
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 @@ namespace SourceGit.Views
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 @@ namespace SourceGit.Views
return;
var repoView = this.FindAncestorOfType<Repository>();
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 @@ namespace SourceGit.Views
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 @@ namespace SourceGit.Views
return;
var repoView = this.FindAncestorOfType<Repository>();
if (repoView == null)
return;
var repo = repoView.DataContext as ViewModels.Repository;
var repo = repoView?.DataContext as ViewModels.Repository;
if (repo == null)
return;

View File

@@ -208,10 +208,8 @@ namespace SourceGit.Views
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;