Skip to content

Commit 8d0e2d3

Browse files
committed
code_style: cleanup code about SSH key helper
Signed-off-by: leo <longshuang@msn.cn>
1 parent 141b299 commit 8d0e2d3

5 files changed

Lines changed: 45 additions & 62 deletions

File tree

src/Models/SSHKeyPair.cs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,19 @@ namespace SourceGit.Models
66
{
77
public class SSHKeyPair
88
{
9-
public string Name { get; set; }
10-
public string FullPath { get; set; }
11-
public string PublicKey { get; set; }
9+
public string PrivateKeyPath { get; set; }
10+
public string PublicKeyPath { get; set; }
11+
public string RawPublicKey { get; set; }
1212
public string Fingerprint { get; set; } = "--- (invalid)";
13+
public string Name => Path.GetFileName(PrivateKeyPath);
1314

14-
public SSHKeyPair(string file)
15+
public SSHKeyPair(string privateKey, string publicKey)
1516
{
16-
Name = Path.GetFileName(file);
17-
FullPath = file;
18-
PublicKey = File.ReadAllText($"{file}.pub");
17+
PrivateKeyPath = privateKey;
18+
PublicKeyPath = publicKey;
19+
RawPublicKey = File.ReadAllText(publicKey);
1920

20-
var parts = PublicKey.Split(' ', StringSplitOptions.RemoveEmptyEntries);
21+
var parts = RawPublicKey.Split(' ', StringSplitOptions.RemoveEmptyEntries);
2122
if (parts.Length != 3)
2223
return;
2324

src/ViewModels/SSHKeyGenerator.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,6 @@ public string ErrorMessage
6363
set => SetProperty(ref _errorMessage, value);
6464
}
6565

66-
public SSHKeyGenerator(string baseDir)
67-
{
68-
_baseDir = baseDir;
69-
}
70-
7166
public static ValidationResult ValidatePassphrase(string password, ValidationContext context)
7267
{
7368
var instance = (SSHKeyGenerator)context.ObjectInstance;
@@ -95,16 +90,17 @@ public static ValidationResult ValidateConfirmedPassphrase(string confirmedPassw
9590
return ValidationResult.Success;
9691
}
9792

98-
public bool Run()
93+
public Models.SSHKeyPair Run()
9994
{
10095
ErrorMessage = string.Empty;
10196

10297
ValidateAllProperties();
10398
if (HasErrors)
104-
return false;
99+
return null;
105100

101+
var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh");
106102
var passphrase = _usePassphrase ? _passphrase : string.Empty;
107-
var keyFile = Path.Combine(_baseDir, _name);
103+
var keyFile = Path.Combine(dir, _name);
108104
var start = new ProcessStartInfo();
109105
start.FileName = "ssh-keygen";
110106
start.Arguments = $"-q -t ed25519 -N {passphrase.Quoted()} -C {_email.Quoted()} -f {keyFile.Quoted()}";
@@ -120,16 +116,20 @@ public bool Run()
120116
catch (Exception e)
121117
{
122118
ErrorMessage = $"Failed to generate SSH key: {e.Message}";
123-
return false;
119+
return null;
124120
}
125121

126-
return true;
122+
var publicKeyFile = keyFile + ".pub";
123+
if (File.Exists(keyFile) && File.Exists(publicKeyFile))
124+
return new Models.SSHKeyPair(keyFile, publicKeyFile);
125+
126+
ErrorMessage = "Failed to generate SSH key: Key files not found.";
127+
return null;
127128
}
128129

129130
[GeneratedRegex(@"^[0-9a-zA-Z_\-\@\#\$\%\!\&\+\=]+$")]
130131
private static partial Regex REG_PSWD_FORMAT();
131132

132-
private string _baseDir;
133133
private string _name;
134134
private string _email;
135135
private bool _usePassphrase;

src/ViewModels/SSHKeyHelper.cs

Lines changed: 20 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
using System;
22
using System.Collections.Generic;
33
using System.IO;
4-
using System.Threading.Tasks;
54

65
using Avalonia.Collections;
7-
using Avalonia.Threading;
8-
96
using CommunityToolkit.Mvvm.ComponentModel;
107

118
namespace SourceGit.ViewModels
@@ -31,41 +28,33 @@ public SSHKeyGenerator Generator
3128

3229
public SSHKeyHelper()
3330
{
34-
_baseDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh");
3531
Keys = new AvaloniaList<Models.SSHKeyPair>();
3632

37-
Task.Run(() =>
33+
var sshDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh"));
34+
if (sshDir.Exists)
3835
{
39-
var sshDir = new DirectoryInfo(_baseDir);
36+
var files = sshDir.GetFiles("*.pub");
4037
var keys = new List<Models.SSHKeyPair>();
4138

42-
if (sshDir.Exists)
39+
foreach (var file in files)
4340
{
44-
var files = sshDir.GetFiles("*.pub");
45-
foreach (var file in files)
46-
{
47-
var privateKeyPath = file.FullName.Substring(0, file.FullName.Length - 4);
48-
if (File.Exists(privateKeyPath))
49-
keys.Add(new(privateKeyPath));
50-
}
51-
52-
keys.Sort((l, r) => l.Name.CompareTo(r.Name));
41+
var privateKeyPath = file.FullName.Substring(0, file.FullName.Length - 4);
42+
if (File.Exists(privateKeyPath))
43+
keys.Add(new(privateKeyPath, file.FullName));
5344
}
5445

5546
if (keys.Count > 0)
5647
{
57-
Dispatcher.UIThread.Post(() =>
58-
{
59-
Keys.AddRange(keys);
60-
SelectedKey = keys[0];
61-
});
48+
keys.Sort((l, r) => l.Name.CompareTo(r.Name));
49+
Keys.AddRange(keys);
50+
SelectedKey = keys[0];
6251
}
63-
});
52+
}
6453
}
6554

6655
public void OpenGenerator()
6756
{
68-
Generator = new SSHKeyGenerator(_baseDir);
57+
Generator = new SSHKeyGenerator();
6958
}
7059

7160
public void CloseGenerator()
@@ -75,18 +64,12 @@ public void CloseGenerator()
7564

7665
public void Generate()
7766
{
78-
var succ = _generator.Run();
79-
if (!succ)
67+
var key = _generator.Run();
68+
if (key == null)
8069
return;
8170

82-
var keyFile = Path.Combine(_baseDir, $"{_generator.Name}");
83-
if (File.Exists(keyFile))
84-
{
85-
var added = new Models.SSHKeyPair(keyFile);
86-
Keys.Add(added);
87-
SelectedKey = added;
88-
}
89-
71+
Keys.Add(key);
72+
SelectedKey = key;
9073
Generator = null;
9174
}
9275

@@ -98,10 +81,10 @@ public void DeleteSelected()
9881

9982
try
10083
{
101-
if (File.Exists(key.FullPath))
102-
File.Delete(key.FullPath);
103-
if (File.Exists($"{key.FullPath}.pub"))
104-
File.Delete($"{key.FullPath}.pub");
84+
if (File.Exists(key.PrivateKeyPath))
85+
File.Delete(key.PrivateKeyPath);
86+
if (File.Exists(key.PublicKeyPath))
87+
File.Delete(key.PublicKeyPath);
10588

10689
var idx = Keys.IndexOf(key);
10790
if (idx >= 0)
@@ -122,7 +105,6 @@ public void DeleteSelected()
122105
}
123106
}
124107

125-
private string _baseDir = null;
126108
private Models.SSHKeyPair _selectedKey = null;
127109
private SSHKeyGenerator _generator = null;
128110
}

src/Views/SSHKeyHelper.axaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@
122122
<TextBlock Classes="group_header_label"
123123
Text="{DynamicResource Text.SSHKeyHelper.Path}"/>
124124
<SelectableTextBlock Margin="0,6,0,0"
125-
Text="{Binding FullPath, Mode=OneWay}"
125+
Text="{Binding PrivateKeyPath, Mode=OneWay}"
126126
TextWrapping="Wrap"/>
127127

128128
<TextBlock Classes="group_header_label"
@@ -137,7 +137,7 @@
137137
Text="{DynamicResource Text.SSHKeyHelper.PublicKey}"/>
138138
<TextBox Height="80"
139139
Margin="0,6,0,0" Padding="2"
140-
Text="{Binding PublicKey}"
140+
Text="{Binding RawPublicKey}"
141141
IsReadOnly="True"
142142
CornerRadius="4"
143143
TextWrapping="Wrap"

src/Views/SSHKeyHelper.axaml.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Text;
1+
using System.Text;
22
using Avalonia.Interactivity;
33

44
namespace SourceGit.Views
@@ -46,8 +46,8 @@ private async void OnDeleteSelectedKey(object sender, RoutedEventArgs e)
4646
message
4747
.AppendLine(App.Text("SSHKeyHelper.ConfirmDeletion"))
4848
.AppendLine()
49-
.Append("- ").Append(key.FullPath).AppendLine()
50-
.Append("- ").Append(key.FullPath).Append(".pub");
49+
.Append(" ").Append(key.PrivateKeyPath).AppendLine()
50+
.Append(" ").Append(key.PublicKeyPath);
5151

5252
var yes = await App.AskConfirmAsync(message.ToString(), Models.ConfirmButtonType.YesNo);
5353
if (yes)

0 commit comments

Comments
 (0)