code_style: general cleanup (#1543)

* code_style: general cleanup

* feedback fixes
This commit is contained in:
Nathan Baulch
2025-07-09 18:12:03 +10:00
committed by GitHub
parent 666305e40c
commit 796f8898c9
42 changed files with 127 additions and 166 deletions

View File

@@ -292,6 +292,7 @@ indent_size = 2
# Shell scripts
[*.sh]
end_of_line = lf
[*.{cmd,bat}]
end_of_line = crlf

View File

@@ -6,23 +6,23 @@ jobs:
strategy:
matrix:
include:
- name : Windows x64
- name: Windows x64
os: windows-2022
runtime: win-x64
- name : Windows ARM64
- name: Windows ARM64
os: windows-2022
runtime: win-arm64
- name : macOS (Intel)
- name: macOS (Intel)
os: macos-13
runtime: osx-x64
- name : macOS (Apple Silicon)
- name: macOS (Apple Silicon)
os: macos-latest
runtime: osx-arm64
- name : Linux
- name: Linux
os: ubuntu-latest
runtime: linux-x64
container: ubuntu:20.04
- name : Linux (arm64)
- name: Linux (arm64)
os: ubuntu-latest
runtime: linux-arm64
container: ubuntu:20.04

View File

@@ -1,7 +1,9 @@
name: Format Check
on:
push:
branches: [ develop ]
branches: [develop]
pull_request:
branches: [develop]
workflow_dispatch:
workflow_call:

View File

@@ -1,7 +1,7 @@
name: Localization Check
on:
push:
branches: [ develop ]
branches: [develop]
paths:
- 'src/Resources/Locales/**'
workflow_dispatch:

View File

@@ -12,7 +12,7 @@ jobs:
runs-on: windows-2022
strategy:
matrix:
runtime: [ win-x64, win-arm64 ]
runtime: [win-x64, win-arm64]
steps:
- name: Checkout sources
uses: actions/checkout@v4

View File

@@ -221,7 +221,8 @@ namespace SourceGit
try
{
var resDic = new ResourceDictionary();
var overrides = JsonSerializer.Deserialize(File.ReadAllText(themeOverridesFile), JsonCodeGen.Default.ThemeOverrides);
using var stream = File.OpenRead(themeOverridesFile);
var overrides = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.ThemeOverrides);
foreach (var kv in overrides.BasicColors)
{
if (kv.Key.Equals("SystemAccentColor", StringComparison.Ordinal))
@@ -449,31 +450,21 @@ namespace SourceGit
if (!File.Exists(jobsFile))
return true;
var collection = JsonSerializer.Deserialize(File.ReadAllText(jobsFile), JsonCodeGen.Default.InteractiveRebaseJobCollection);
using var stream = File.OpenRead(jobsFile);
var collection = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.InteractiveRebaseJobCollection);
using var writer = new StreamWriter(file);
foreach (var job in collection.Jobs)
{
switch (job.Action)
var code = job.Action switch
{
case Models.InteractiveRebaseAction.Pick:
writer.WriteLine($"p {job.SHA}");
break;
case Models.InteractiveRebaseAction.Edit:
writer.WriteLine($"e {job.SHA}");
break;
case Models.InteractiveRebaseAction.Reword:
writer.WriteLine($"r {job.SHA}");
break;
case Models.InteractiveRebaseAction.Squash:
writer.WriteLine($"s {job.SHA}");
break;
case Models.InteractiveRebaseAction.Fixup:
writer.WriteLine($"f {job.SHA}");
break;
default:
writer.WriteLine($"d {job.SHA}");
break;
}
Models.InteractiveRebaseAction.Pick => 'p',
Models.InteractiveRebaseAction.Edit => 'e',
Models.InteractiveRebaseAction.Reword => 'r',
Models.InteractiveRebaseAction.Squash => 's',
Models.InteractiveRebaseAction.Fixup => 'f',
_ => 'd'
};
writer.WriteLine($"{code} {job.SHA}");
}
writer.Flush();
@@ -506,7 +497,8 @@ namespace SourceGit
var origHead = File.ReadAllText(origHeadFile).Trim();
var onto = File.ReadAllText(ontoFile).Trim();
var collection = JsonSerializer.Deserialize(File.ReadAllText(jobsFile), JsonCodeGen.Default.InteractiveRebaseJobCollection);
using var stream = File.OpenRead(jobsFile);
var collection = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.InteractiveRebaseJobCollection);
if (!collection.Onto.Equals(onto) || !collection.OrigHead.Equals(origHead))
return true;
@@ -626,7 +618,8 @@ namespace SourceGit
try
{
// Fetch latest release information.
var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) };
using var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(5);
var data = await client.GetStringAsync("https://sourcegit-scm.github.io/data/version.json");
// Parse JSON into Models.Version.

View File

@@ -54,9 +54,9 @@ namespace SourceGit.Commands
{
Log?.AppendLine($"$ git {Args}\n");
var start = CreateGitStartInfo(true);
var errs = new List<string>();
var proc = new Process() { StartInfo = start };
using var proc = new Process();
proc.StartInfo = CreateGitStartInfo(true);
proc.OutputDataReceived += (_, e) => HandleOutput(e.Data, errs);
proc.ErrorDataReceived += (_, e) => HandleOutput(e.Data, errs);
@@ -67,7 +67,7 @@ namespace SourceGit.Commands
{
proc.Start();
// It not safe, please only use `CancellationToken` in readonly commands.
// Not safe, please only use `CancellationToken` in readonly commands.
if (CancellationToken.CanBeCanceled)
{
dummy = proc;
@@ -110,11 +110,9 @@ namespace SourceGit.Commands
}
}
int exitCode = proc.ExitCode;
proc.Close();
Log?.AppendLine(string.Empty);
if (!CancellationToken.IsCancellationRequested && exitCode != 0)
if (!CancellationToken.IsCancellationRequested && proc.ExitCode != 0)
{
if (RaiseError)
{
@@ -131,8 +129,8 @@ namespace SourceGit.Commands
protected async Task<Result> ReadToEndAsync()
{
var start = CreateGitStartInfo(true);
var proc = new Process() { StartInfo = start };
using var proc = new Process();
proc.StartInfo = CreateGitStartInfo(true);
try
{
@@ -149,7 +147,6 @@ namespace SourceGit.Commands
await proc.WaitForExitAsync(CancellationToken).ConfigureAwait(false);
rs.IsSuccess = proc.ExitCode == 0;
proc.Close();
return rs;
}
@@ -191,8 +188,8 @@ namespace SourceGit.Commands
// Force using this app as git editor.
start.Arguments += Editor switch
{
EditorType.CoreEditor => $"-c core.editor=\"\\\"{selfExecFile}\\\" --core-editor\" ",
EditorType.RebaseEditor => $"-c core.editor=\"\\\"{selfExecFile}\\\" --rebase-message-editor\" -c sequence.editor=\"\\\"{selfExecFile}\\\" --rebase-todo-editor\" -c rebase.abbreviateCommands=true ",
EditorType.CoreEditor => $"""-c core.editor="\"{selfExecFile}\" --core-editor" """,
EditorType.RebaseEditor => $"""-c core.editor="\"{selfExecFile}\" --rebase-message-editor" -c sequence.editor="\"{selfExecFile}\" --rebase-todo-editor" -c rebase.abbreviateCommands=true """,
_ => "-c core.editor=true ",
};

View File

@@ -67,10 +67,8 @@ namespace SourceGit.Commands
});
}
responseBuilder.Append("\n");
summaryBuilder.Append("(file: ");
summaryBuilder.Append(change.Path);
summaryBuilder.Append(")\n");
responseBuilder.AppendLine();
summaryBuilder.Append("(file: ").Append(change.Path).AppendLine(")");
}
if (_cancelToken.IsCancellationRequested)

View File

@@ -80,8 +80,8 @@ namespace SourceGit.Commands
break;
case 2:
_current.ParseDecorators(line);
if (_current.IsMerged && !_isHeadFounded)
_isHeadFounded = true;
if (_current.IsMerged && !_isHeadFound)
_isHeadFound = true;
break;
case 3:
_current.Author = Models.User.FindOrAdd(line);
@@ -110,7 +110,7 @@ namespace SourceGit.Commands
if (start < rs.StdOut.Length)
_current.Subject = rs.StdOut.Substring(start);
if (_findFirstMerged && !_isHeadFounded && _commits.Count > 0)
if (_findFirstMerged && !_isHeadFound && _commits.Count > 0)
await MarkFirstMergedAsync().ConfigureAwait(false);
return _commits;
@@ -148,6 +148,6 @@ namespace SourceGit.Commands
private List<Models.Commit> _commits = new List<Models.Commit>();
private Models.Commit _current = null;
private bool _findFirstMerged = false;
private bool _isHeadFounded = false;
private bool _isHeadFound = false;
}
}

View File

@@ -21,11 +21,9 @@ namespace SourceGit.Commands
var stream = new MemoryStream();
try
{
var proc = new Process() { StartInfo = starter };
proc.Start();
using var proc = Process.Start(starter);
await proc.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false);
await proc.WaitForExitAsync().ConfigureAwait(false);
proc.Close();
stream.Position = 0;
}
@@ -52,14 +50,12 @@ namespace SourceGit.Commands
var stream = new MemoryStream();
try
{
var proc = new Process() { StartInfo = starter };
proc.Start();
using var proc = Process.Start(starter);
await proc.StandardInput.WriteLineAsync("version https://git-lfs.github.com/spec/v1").ConfigureAwait(false);
await proc.StandardInput.WriteLineAsync($"oid sha256:{oid}").ConfigureAwait(false);
await proc.StandardInput.WriteLineAsync($"size {size}").ConfigureAwait(false);
await proc.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false);
await proc.WaitForExitAsync().ConfigureAwait(false);
proc.Close();
stream.Position = 0;
}

View File

@@ -62,14 +62,10 @@ namespace SourceGit.Commands
try
{
var proc = new Process() { StartInfo = starter };
proc.Start();
using var proc = Process.Start(starter);
await proc.StandardOutput.BaseStream.CopyToAsync(writer).ConfigureAwait(false);
await proc.WaitForExitAsync().ConfigureAwait(false);
var rs = proc.ExitCode == 0;
proc.Close();
return rs;
return proc.ExitCode == 0;
}
catch (Exception e)
{

View File

@@ -42,13 +42,11 @@ namespace SourceGit.Commands
{
try
{
var proc = new Process() { StartInfo = starter };
proc.Start();
using var proc = Process.Start(starter);
if (input != null)
await proc.StandardInput.WriteAsync(await new StreamReader(input).ReadToEndAsync());
await proc.StandardOutput.BaseStream.CopyToAsync(sw);
await proc.WaitForExitAsync();
proc.Close();
}
catch (Exception e)
{

View File

@@ -44,7 +44,7 @@ namespace SourceGit.Commands
_patchBuilder.Append(c.Path);
}
_patchBuilder.Append("\n");
_patchBuilder.AppendLine();
}
}
@@ -63,15 +63,13 @@ namespace SourceGit.Commands
try
{
var proc = new Process() { StartInfo = starter };
proc.Start();
using var proc = Process.Start(starter);
await proc.StandardInput.WriteAsync(_patchBuilder.ToString());
proc.StandardInput.Close();
var err = await proc.StandardError.ReadToEndAsync().ConfigureAwait(false);
await proc.WaitForExitAsync().ConfigureAwait(false);
var rs = proc.ExitCode == 0;
proc.Close();
if (!rs)
App.RaiseException(_repo, err);

View File

@@ -82,11 +82,9 @@ namespace SourceGit.Models
Bitmap img = null;
try
{
var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) };
var task = client.GetAsync(url);
task.Wait();
var rsp = task.Result;
using var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(2);
var rsp = client.GetAsync(url).Result;
if (rsp.IsSuccessStatusCode)
{
using (var stream = rsp.Content.ReadAsStream())

View File

@@ -110,10 +110,10 @@ namespace SourceGit.Models
Decorators.Sort((l, r) =>
{
if (l.Type != r.Type)
return (int)l.Type - (int)r.Type;
else
return NumericSort.Compare(l.Name, r.Name);
var delta = (int)l.Type - (int)r.Type;
if (delta != 0)
return delta;
return NumericSort.Compare(l.Name, r.Name);
});
}
}

View File

@@ -96,7 +96,6 @@ namespace SourceGit.Models
/// <summary>
/// Converts to diff command arguments.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var builder = new StringBuilder();

View File

@@ -88,7 +88,7 @@ namespace SourceGit.Models
public class ExternalToolsFinder
{
public List<ExternalTool> Founded
public List<ExternalTool> Tools
{
get;
private set;
@@ -100,7 +100,10 @@ namespace SourceGit.Models
try
{
if (File.Exists(customPathsConfig))
_customPaths = JsonSerializer.Deserialize(File.ReadAllText(customPathsConfig), JsonCodeGen.Default.ExternalToolPaths);
{
using var stream = File.OpenRead(customPathsConfig);
_customPaths = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.ExternalToolPaths);
}
}
catch
{
@@ -114,13 +117,13 @@ namespace SourceGit.Models
{
if (_customPaths.Tools.TryGetValue(name, out var customPath) && File.Exists(customPath))
{
Founded.Add(new ExternalTool(name, icon, customPath, execArgsGenerator));
Tools.Add(new ExternalTool(name, icon, customPath, execArgsGenerator));
}
else
{
var path = finder();
if (!string.IsNullOrEmpty(path) && File.Exists(path))
Founded.Add(new ExternalTool(name, icon, path, execArgsGenerator));
Tools.Add(new ExternalTool(name, icon, path, execArgsGenerator));
}
}
@@ -162,19 +165,20 @@ namespace SourceGit.Models
public void FindJetBrainsFromToolbox(Func<string> platformFinder)
{
var exclude = new List<string> { "fleet", "dotmemory", "dottrace", "resharper-u", "androidstudio" };
var supported_icons = new List<string> { "CL", "DB", "DL", "DS", "GO", "JB", "PC", "PS", "PY", "QA", "QD", "RD", "RM", "RR", "WRS", "WS" };
var supportedIcons = new List<string> { "CL", "DB", "DL", "DS", "GO", "JB", "PC", "PS", "PY", "QA", "QD", "RD", "RM", "RR", "WRS", "WS" };
var state = Path.Combine(platformFinder(), "state.json");
if (File.Exists(state))
{
var stateData = JsonSerializer.Deserialize(File.ReadAllText(state), JsonCodeGen.Default.JetBrainsState);
using var stream = File.OpenRead(state);
var stateData = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.JetBrainsState);
foreach (var tool in stateData.Tools)
{
if (exclude.Contains(tool.ToolId.ToLowerInvariant()))
continue;
Founded.Add(new ExternalTool(
Tools.Add(new ExternalTool(
$"{tool.DisplayName} {tool.DisplayVersion}",
supported_icons.Contains(tool.ProductCode) ? $"JetBrains/{tool.ProductCode}" : "JetBrains/JB",
supportedIcons.Contains(tool.ProductCode) ? $"JetBrains/{tool.ProductCode}" : "JetBrains/JB",
Path.Combine(tool.InstallLocation, tool.LaunchCommand)));
}
}

View File

@@ -51,12 +51,8 @@ namespace SourceGit.Models
return;
var matches = _regex.Matches(message);
for (var i = 0; i < matches.Count; i++)
foreach (Match match in matches)
{
var match = matches[i];
if (!match.Success)
continue;
var start = match.Index;
var len = match.Length;
if (outs.Intersect(start, len) != null)

View File

@@ -85,7 +85,7 @@ namespace SourceGit.Models
_hasTrimmedStart = true;
}
_onUpdate.Invoke(text);
_onUpdate?.Invoke(text);
}
[GeneratedRegex(@"<(think|thought|thinking|thought_chain)>.*?</\1>", RegexOptions.Singleline)]

View File

@@ -170,18 +170,18 @@ namespace SourceGit.Models
{
if (Next() != VARIABLE_START)
return null;
int name_start = _pos;
var nameStart = _pos;
while (Next() is { } c)
{
// name character, continue advancing
if (IsNameChar(c))
continue;
var name_end = _pos - 1;
var nameEnd = _pos - 1;
// not a name character but name is empty, cancel
if (name_start >= name_end)
if (nameStart >= nameEnd)
return null;
var name = new string(_chars, name_start, name_end - name_start);
var name = new string(_chars, nameStart, nameEnd - nameStart);
return c switch
{

View File

@@ -54,10 +54,10 @@ namespace SourceGit.Native
finder.VSCodium(() => FindExecutable("codium"));
finder.Cursor(() => FindExecutable("cursor"));
finder.Fleet(FindJetBrainsFleet);
finder.FindJetBrainsFromToolbox(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/JetBrains/Toolbox");
finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "JetBrains/Toolbox"));
finder.SublimeText(() => FindExecutable("subl"));
finder.Zed(() => FindExecutable("zeditor"));
return finder.Founded;
return finder.Tools;
}
public void OpenBrowser(string url)
@@ -134,7 +134,7 @@ namespace SourceGit.Native
private string FindJetBrainsFleet()
{
var path = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/JetBrains/Toolbox/apps/fleet/bin/Fleet";
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "JetBrains/Toolbox/apps/fleet/bin/Fleet");
return File.Exists(path) ? path : FindExecutable("fleet");
}
}

View File

@@ -75,11 +75,11 @@ namespace SourceGit.Native
finder.VSCodeInsiders(() => "/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code");
finder.VSCodium(() => "/Applications/VSCodium.app/Contents/Resources/app/bin/codium");
finder.Cursor(() => "/Applications/Cursor.app/Contents/Resources/app/bin/cursor");
finder.Fleet(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/Applications/Fleet.app/Contents/MacOS/Fleet");
finder.FindJetBrainsFromToolbox(() => $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/Library/Application Support/JetBrains/Toolbox");
finder.Fleet(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Applications/Fleet.app/Contents/MacOS/Fleet"));
finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library/Application Support/JetBrains/Toolbox"));
finder.SublimeText(() => "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl");
finder.Zed(() => File.Exists("/usr/local/bin/zed") ? "/usr/local/bin/zed" : "/Applications/Zed.app/Contents/MacOS/cli");
return finder.Founded;
return finder.Tools;
}
public void OpenBrowser(string url)

View File

@@ -203,11 +203,9 @@ namespace SourceGit.Native
start.StandardOutputEncoding = Encoding.UTF8;
start.StandardErrorEncoding = Encoding.UTF8;
var proc = new Process() { StartInfo = start };
try
{
proc.Start();
using var proc = Process.Start(start);
var rs = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
if (proc.ExitCode == 0 && !string.IsNullOrWhiteSpace(rs))
@@ -229,8 +227,6 @@ namespace SourceGit.Native
{
// Ignore errors
}
proc.Close();
}
[GeneratedRegex(@"^git version[\s\w]*(\d+)\.(\d+)[\.\-](\d+).*$")]

View File

@@ -185,11 +185,11 @@ namespace SourceGit.Native
finder.VSCodeInsiders(FindVSCodeInsiders);
finder.VSCodium(FindVSCodium);
finder.Cursor(FindCursor);
finder.Fleet(() => $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Programs\Fleet\Fleet.exe");
finder.FindJetBrainsFromToolbox(() => $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\JetBrains\Toolbox");
finder.Fleet(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Programs\Fleet\Fleet.exe"));
finder.FindJetBrainsFromToolbox(() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"JetBrains\Toolbox"));
finder.SublimeText(FindSublimeText);
finder.TryAdd("Visual Studio", "vs", FindVisualStudio, GenerateCommandlineArgsForVisualStudio);
return finder.Founded;
return finder.Tools;
}
public void OpenBrowser(string url)

View File

@@ -607,7 +607,7 @@
<x:String x:Key="Text.Repository.BranchSort" xml:space="preserve">Sort</x:String>
<x:String x:Key="Text.Repository.BranchSort.ByCommitterDate" xml:space="preserve">By Committer Date</x:String>
<x:String x:Key="Text.Repository.BranchSort.ByName" xml:space="preserve">By Name</x:String>
<x:String x:Key="Text.Repository.Clean" xml:space="preserve">Cleanup(GC &amp; Prune)</x:String>
<x:String x:Key="Text.Repository.Clean" xml:space="preserve">Cleanup (GC &amp; Prune)</x:String>
<x:String x:Key="Text.Repository.CleanTips" xml:space="preserve">Run `git gc` command for this repository.</x:String>
<x:String x:Key="Text.Repository.ClearAllCommitsFilter" xml:space="preserve">Clear all</x:String>
<x:String x:Key="Text.Repository.ClearStashes" xml:space="preserve">Clear</x:String>

View File

@@ -771,12 +771,8 @@ namespace SourceGit.ViewModels
}
var urlMatches = REG_URL_FORMAT().Matches(message);
for (int i = 0; i < urlMatches.Count; i++)
foreach (Match match in urlMatches)
{
var match = urlMatches[i];
if (!match.Success)
continue;
var start = match.Index;
var len = match.Length;
if (inlines.Intersect(start, len) != null)
@@ -788,12 +784,8 @@ namespace SourceGit.ViewModels
}
var shaMatches = REG_SHA_FORMAT().Matches(message);
for (int i = 0; i < shaMatches.Count; i++)
foreach (Match match in shaMatches)
{
var match = shaMatches[i];
if (!match.Success)
continue;
var start = match.Index;
var len = match.Length;
if (inlines.Intersect(start, len) != null)

View File

@@ -77,19 +77,19 @@ namespace SourceGit.ViewModels
builder.Append(": ");
builder.Append(_description);
builder.Append("\n\n");
builder.AppendLine("\n");
if (!string.IsNullOrEmpty(_detail))
{
builder.Append(_detail);
builder.Append("\n\n");
builder.AppendLine("\n");
}
if (!string.IsNullOrEmpty(_breakingChanges))
{
builder.Append("BREAKING CHANGE: ");
builder.Append(_breakingChanges);
builder.Append("\n\n");
builder.AppendLine("\n");
}
if (!string.IsNullOrEmpty(_closedIssue))

View File

@@ -250,7 +250,8 @@ namespace SourceGit.ViewModels
start.StandardErrorEncoding = Encoding.UTF8;
start.WorkingDirectory = _repo.FullPath;
var proc = new Process() { StartInfo = start };
using var proc = new Process();
proc.StartInfo = start;
var builder = new StringBuilder();
proc.OutputDataReceived += (_, e) =>
@@ -287,8 +288,6 @@ namespace SourceGit.ViewModels
{
App.RaiseException(_repo.FullPath, e.Message);
}
proc.Close();
}
private readonly Repository _repo = null;

View File

@@ -272,7 +272,7 @@ namespace SourceGit.ViewModels
_repo.CheckoutBranch(b);
return;
}
else if (d.Type == Models.DecoratorType.RemoteBranchHead)
if (d.Type == Models.DecoratorType.RemoteBranchHead)
{
var rb = _repo.Branches.Find(x => x.FriendlyName == d.Name);
if (rb == null)
@@ -424,7 +424,7 @@ namespace SourceGit.ViewModels
{
var builder = new StringBuilder();
foreach (var c in selected)
builder.AppendLine($"{c.SHA.AsSpan(0, 10)} - {c.Subject}");
builder.Append(c.SHA.AsSpan(0, 10)).Append(" - ").AppendLine(c.Subject);
await App.CopyTextAsync(builder.ToString());
e.Handled = true;

View File

@@ -9,7 +9,7 @@ namespace SourceGit.ViewModels
public partial class InitGitFlow : Popup
{
[GeneratedRegex(@"^[\w\-/\.]+$")]
private static partial Regex TAG_PREFIX();
private static partial Regex REG_TAG_PREFIX();
[Required(ErrorMessage = "Master branch name is required!!!")]
[RegularExpression(@"^[\w\-/\.]+$", ErrorMessage = "Bad branch name format!")]
@@ -94,7 +94,7 @@ namespace SourceGit.ViewModels
public static ValidationResult ValidateTagPrefix(string tagPrefix, ValidationContext ctx)
{
if (!string.IsNullOrWhiteSpace(tagPrefix) && !TAG_PREFIX().IsMatch(tagPrefix))
if (!string.IsNullOrWhiteSpace(tagPrefix) && !REG_TAG_PREFIX().IsMatch(tagPrefix))
return new ValidationResult("Bad tag prefix format!");
return ValidationResult.Success;

View File

@@ -541,7 +541,8 @@ namespace SourceGit.ViewModels
try
{
return JsonSerializer.Deserialize(File.ReadAllText(path), JsonCodeGen.Default.Preferences);
using var stream = File.OpenRead(path);
return JsonSerializer.Deserialize(stream, JsonCodeGen.Default.Preferences);
}
catch
{

View File

@@ -492,7 +492,8 @@ namespace SourceGit.ViewModels
{
try
{
_settings = JsonSerializer.Deserialize(File.ReadAllText(settingsFile), JsonCodeGen.Default.RepositorySettings);
using var stream = File.OpenRead(settingsFile);
_settings = JsonSerializer.Deserialize(stream, JsonCodeGen.Default.RepositorySettings);
}
catch
{
@@ -545,10 +546,10 @@ namespace SourceGit.ViewModels
_settings.LastCommitMessage = _workingCopy.CommitMessage;
var settingsSerialized = JsonSerializer.Serialize(_settings, JsonCodeGen.Default.RepositorySettings);
try
{
File.WriteAllText(Path.Combine(_gitDir, "sourcegit.settings"), settingsSerialized);
using var stream = File.OpenWrite(Path.Combine(_gitDir, "sourcegit.settings"));
JsonSerializer.Serialize(stream, _settings, JsonCodeGen.Default.RepositorySettings);
}
catch
{
@@ -702,7 +703,7 @@ namespace SourceGit.ViewModels
{
menu.Items.Add(new MenuItem() { Header = "-" });
foreach (var tool in Native.OS.ExternalTools)
foreach (var tool in tools)
{
var dupTool = tool;

View File

@@ -210,17 +210,17 @@ namespace SourceGit.ViewModels
}
}
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitHub ISSUE", "#(\\d+)", link);
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitHub ISSUE", @"#(\d+)", link);
}
public void AddSampleJiraIssueTracker()
{
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Jira Tracker", "PROJ-(\\d+)", "https://jira.yourcompany.com/browse/PROJ-$1");
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Jira Tracker", @"PROJ-(\d+)", "https://jira.yourcompany.com/browse/PROJ-$1");
}
public void AddSampleAzureWorkItemTracker()
{
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Azure DevOps Tracker", "#(\\d+)", "https://dev.azure.com/yourcompany/workspace/_workitems/edit/$1");
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Azure DevOps Tracker", @"#(\d+)", "https://dev.azure.com/yourcompany/workspace/_workitems/edit/$1");
}
public void AddSampleGitLabIssueTracker()
@@ -235,7 +235,7 @@ namespace SourceGit.ViewModels
}
}
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab ISSUE", "#(\\d+)", link);
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab ISSUE", @"#(\d+)", link);
}
public void AddSampleGitLabMergeRequestTracker()
@@ -250,7 +250,7 @@ namespace SourceGit.ViewModels
}
}
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab MR", "!(\\d+)", link);
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("GitLab MR", @"!(\d+)", link);
}
public void AddSampleGiteeIssueTracker()
@@ -266,7 +266,7 @@ namespace SourceGit.ViewModels
}
}
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee ISSUE", "#([0-9A-Z]{6,10})", link);
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee ISSUE", @"#([0-9A-Z]{6,10})", link);
}
public void AddSampleGiteePullRequestTracker()
@@ -281,12 +281,12 @@ namespace SourceGit.ViewModels
}
}
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee Pull Request", "!(\\d+)", link);
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("Gitee Pull Request", @"!(\d+)", link);
}
public void NewIssueTracker()
{
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("New Issue Tracker", "#(\\d+)", "https://xxx/$1");
SelectedIssueTrackerRule = _repo.Settings.AddIssueTracker("New Issue Tracker", @"#(\d+)", "https://xxx/$1");
}
public void RemoveSelectedIssueTracker()

View File

@@ -51,7 +51,7 @@ namespace SourceGit.ViewModels
IgnoreInaccessible = true,
});
// Make sure this task takes at least 0.5s to avoid that the popup panel do not disappear very quickly.
// Make sure this task takes at least 0.5s to avoid the popup panel disappearing too quickly.
await minDelay;
var normalizedRoot = rootDir.FullName.Replace('\\', '/').TrimEnd('/');

View File

@@ -163,12 +163,8 @@ namespace SourceGit.Views
_elements.Add(new Models.InlineElement(Models.InlineElementType.Keyword, 0, keywordMatch.Length, string.Empty));
var codeMatches = REG_INLINECODE_FORMAT().Matches(subject);
for (var i = 0; i < codeMatches.Count; i++)
foreach (Match match in codeMatches)
{
var match = codeMatches[i];
if (!match.Success)
continue;
var start = match.Index;
var len = match.Length;
if (_elements.Intersect(start, len) != null)

View File

@@ -205,7 +205,7 @@
Margin="8,0,0,0"
Height="28"
IsChecked="{Binding BoolValue, Mode=TwoWay}"/>
</Grid>
</Grid>
</StackPanel>
</DataTemplate>
</ContentControl.DataTemplates>

View File

@@ -50,7 +50,7 @@
<DataGrid.Resources>
<SolidColorBrush x:Key="DataGridGridLinesBrush" Color="{DynamicResource Color.Border0}" />
</DataGrid.Resources>
<DataGrid.Styles>
<Style Selector="DataGridColumnHeader">
<Setter Property="MinHeight" Value="24"/>

View File

@@ -232,7 +232,7 @@ namespace SourceGit.Views
foreach (var item in selected)
{
if (item is Models.Commit commit)
builder.AppendLine($"{commit.SHA.AsSpan(0, 10)} - {commit.Subject}");
builder.Append(commit.SHA.AsSpan(0, 10)).Append(" - ").AppendLine(commit.Subject);
}
await App.CopyTextAsync(builder.ToString());

View File

@@ -19,7 +19,7 @@
<Path Width="14" Height="14" Data="{StaticResource Icons.Submodule}"/>
<TextBlock Margin="6,0,0,0" Text="{Binding Submodule.Path}"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0,0,8,0"

View File

@@ -36,7 +36,7 @@
<Path Width="14" Height="14" Margin="2,0,0,0" Data="{StaticResource Icons.Branch}"/>
<TextBlock Margin="6,0,0,0" Text="{Binding Branch, Mode=OneWay}"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="0"
Classes="info_label"
HorizontalAlignment="Left" VerticalAlignment="Center"
@@ -45,7 +45,7 @@
Orientation="Horizontal"
Margin="8,0,0,0">
<Path Width="14" Height="14" Data="{StaticResource Icons.Commit}"/>
<TextBlock Margin="8,0,0,0"
Text="{Binding SHA, Converter={x:Static c:StringConverters.ToShortSHA}}"
VerticalAlignment="Center"/>
@@ -172,7 +172,7 @@
<Path Width="14" Height="14" Margin="2,0,0,0" Data="{StaticResource Icons.Branch}"/>
<TextBlock Margin="6,0,0,0" Text="{Binding Branch, Mode=OneWay}"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="0"
Classes="info_label"
HorizontalAlignment="Left" VerticalAlignment="Center"
@@ -181,7 +181,7 @@
Orientation="Horizontal"
Margin="8,0,0,0">
<Path Width="14" Height="14" Data="{StaticResource Icons.Commit}"/>
<TextBlock Margin="8,0,0,0"
Text="{Binding SHA, Converter={x:Static c:StringConverters.ToShortSHA}}"
VerticalAlignment="Center"/>
@@ -218,7 +218,7 @@
</Grid>
</Border>
</StackPanel>
<TextBlock Grid.Row="2" Grid.Column="0"
Classes="info_label"
HorizontalAlignment="Left" VerticalAlignment="Center"

View File

@@ -1241,7 +1241,7 @@ namespace SourceGit.Views
if (line.NoNewLineEndOfFile)
builder.Append("\u26D4");
builder.Append('\n');
builder.AppendLine();
}
Text = builder.ToString();
@@ -1469,7 +1469,7 @@ namespace SourceGit.Views
var lines = IsOld ? diff.Old : diff.New;
foreach (var line in lines)
{
if (line.Content.Length > 10000)
if (line.Content.Length > 1000)
{
builder.Append(line.Content.AsSpan(0, 1000));
builder.Append($"...({line.Content.Length - 1000} characters trimmed)");
@@ -1482,7 +1482,7 @@ namespace SourceGit.Views
if (line.NoNewLineEndOfFile)
builder.Append("\u26D4");
builder.Append('\n');
builder.AppendLine();
}
Text = builder.ToString();

View File

@@ -27,7 +27,7 @@
<Binding Path="HasPreSelectedSubmodule" Converter="{x:Static BoolConverters.Not}"/>
</MultiBinding>
</ComboBox.IsEnabled>
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="m:Submodule">
<StackPanel Orientation="Horizontal" Height="20" VerticalAlignment="Center">