optimize<GitURL>: use regex to validate git repository urls

This commit is contained in:
leo 2023-06-02 10:29:43 +08:00
parent a39b44ea2e
commit 611d3c7db0
2 changed files with 26 additions and 12 deletions

View file

@ -2,6 +2,7 @@
using SourceGit.Views.Validations;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
@ -12,6 +13,10 @@ namespace SourceGit.Views {
/// 克隆
/// </summary>
public partial class Clone : Controls.Window {
private static readonly Regex[] SSH_PROTOCOAL = new Regex[] {
new Regex(@"[\w\-]+@[\w\.\-]+(\:[0-9]+)?/[\w\-]+/[\w\-]+\.git$"),
new Regex(@"^ssh://([\w\-]+@)?[\w\.\-]+(\:[0-9]+)?/[\w\-]+/[\w\-]+\.git$"),
};
public string Uri { get; set; }
public string Folder { get; set; }
@ -112,13 +117,16 @@ namespace SourceGit.Views {
}
private void OnUrlChanged(object sender, TextChangedEventArgs e) {
if (!string.IsNullOrEmpty(txtUrl.Text)) {
rowSSHKey.Height = new GridLength(txtUrl.Text.StartsWith("git@") ? 32 : 0, GridUnitType.Pixel);
} else {
rowSSHKey.Height = new GridLength(0, GridUnitType.Pixel);
foreach (var check in SSH_PROTOCOAL) {
if (check.IsMatch(txtUrl.Text)) {
rowSSHKey.Height = new GridLength(32, GridUnitType.Pixel);
return;
}
}
rowSSHKey.Height = new GridLength(0, GridUnitType.Pixel);
}
private void OnCloseException(object s, RoutedEventArgs e) {
exception.Visibility = Visibility.Collapsed;
e.Handled = true;

View file

@ -1,19 +1,25 @@
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;
namespace SourceGit.Views.Validations {
public class GitURL : ValidationRule {
private static readonly Regex[] VALID_FORMATS = new Regex[] {
new Regex(@"^http[s]?://[\w\.\-]+(\:[0-9]+)?/[\w\-]+/[\w\-]+\.git$"),
new Regex(@"[\w\-]+@[\w\.\-]+(\:[0-9]+)?/[\w\-]+/[\w\-]+\.git$"),
new Regex(@"^ssh://([\w\-]+@)?[\w\.\-]+(\:[0-9]+)?/[\w\-]+/[\w\-]+\.git$"),
};
public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
string url = value as string;
bool valid = !string.IsNullOrEmpty(url)
&& (url.StartsWith("http://", StringComparison.Ordinal)
|| url.StartsWith("https://", StringComparison.Ordinal)
|| url.StartsWith("git@", StringComparison.Ordinal)
|| url.StartsWith("file://", StringComparison.Ordinal)
|| url.StartsWith("ssh://", StringComparison.Ordinal));
return valid ? ValidationResult.ValidResult : new ValidationResult(false, App.Text("BadRemoteUri"));
if (!string.IsNullOrEmpty(url)) {
foreach (var format in VALID_FORMATS) {
if (format.IsMatch(url)) return ValidationResult.ValidResult;
}
}
return new ValidationResult(false, App.Text("BadRemoteUri")); ;
}
}
}