This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathRepositoryCreationViewModel.cs
341 lines (291 loc) · 14 KB
/
RepositoryCreationViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GitHub.App;
using GitHub.Collections;
using GitHub.Extensions;
using GitHub.Extensions.Reactive;
using GitHub.Factories;
using GitHub.Logging;
using GitHub.Models;
using GitHub.Services;
using GitHub.UserErrors;
using GitHub.Validation;
using Octokit;
using ReactiveUI;
using Rothko;
using Serilog;
using IConnection = GitHub.Models.IConnection;
using UserError = ReactiveUI.Legacy.UserError;
namespace GitHub.ViewModels.Dialog
{
[Export(typeof(IRepositoryCreationViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class RepositoryCreationViewModel : RepositoryFormViewModel, IRepositoryCreationViewModel
{
static readonly ILogger log = LogManager.ForContext<RepositoryCreationViewModel>();
readonly ReactiveCommand<Unit, Unit> browseForDirectoryCommand = ReactiveCommand.Create(() => { });
readonly IModelServiceFactory modelServiceFactory;
readonly IRepositoryCreationService repositoryCreationService;
readonly ObservableAsPropertyHelper<bool> isCreating;
readonly IOperatingSystem operatingSystem;
readonly IUsageTracker usageTracker;
ObservableAsPropertyHelper<IReadOnlyList<IAccount>> accounts;
IModelService modelService;
[ImportingConstructor]
public RepositoryCreationViewModel(
IModelServiceFactory modelServiceFactory,
IOperatingSystem operatingSystem,
IRepositoryCreationService repositoryCreationService,
IUsageTracker usageTracker)
{
Guard.ArgumentNotNull(modelServiceFactory, nameof(modelServiceFactory));
Guard.ArgumentNotNull(operatingSystem, nameof(operatingSystem));
Guard.ArgumentNotNull(repositoryCreationService, nameof(repositoryCreationService));
Guard.ArgumentNotNull(usageTracker, nameof(usageTracker));
this.modelServiceFactory = modelServiceFactory;
this.operatingSystem = operatingSystem;
this.repositoryCreationService = repositoryCreationService;
this.usageTracker = usageTracker;
SelectedGitIgnoreTemplate = GitIgnoreItem.None;
SelectedLicense = LicenseItem.None;
browseForDirectoryCommand.Subscribe(_ => ShowBrowseForDirectoryDialog());
BaseRepositoryPathValidator = ReactivePropertyValidator.ForObservable(this.WhenAny(x => x.BaseRepositoryPath, x => x.Value))
.IfNullOrEmpty(Resources.RepositoryCreationClonePathEmpty)
.IfTrue(x => x.Length > 200, Resources.RepositoryCreationClonePathTooLong)
.IfContainsInvalidPathChars(Resources.RepositoryCreationClonePathInvalidCharacters)
.IfPathNotRooted(Resources.RepositoryCreationClonePathInvalid);
var nameValidationConditions = this.WhenAny(
model => model.RepositoryName,
model => model.SelectedAccount,
(repositoryName, account) => (repositoryName: repositoryName.Value, connection: (IConnection) null, account: account.Value))
.Where(tuple => tuple.repositoryName != null);
RepositoryNameValidator = ReactivePropertyValidator.ForObservable(nameValidationConditions)
.IfTrue(tuple => string.IsNullOrEmpty(tuple.repositoryName), Resources.RepositoryNameValidatorEmpty)
.IfTrue(tuple => tuple.repositoryName.Length > 100, Resources.RepositoryNameValidatorTooLong);
SafeRepositoryNameWarningValidator = ReactivePropertyValidator.ForObservable(nameValidationConditions)
.Add(tuple =>
{
var parsedReference = GetSafeRepositoryName(tuple.repositoryName);
return parsedReference != tuple.repositoryName ? String.Format(CultureInfo.CurrentCulture, Resources.SafeRepositoryNameWarning, parsedReference) : null;
});
CreateRepository = InitializeCreateRepositoryCommand();
isCreating = CreateRepository.IsExecuting
.ToProperty(this, x => x.IsCreating);
BaseRepositoryPath = repositoryCreationService.DefaultClonePath;
}
public string Title { get; private set; }
string baseRepositoryPath;
/// <summary>
/// Path to clone repositories into
/// </summary>
public string BaseRepositoryPath
{
get { return baseRepositoryPath; }
set { this.RaiseAndSetIfChanged(ref baseRepositoryPath, StripSurroundingQuotes(value)); }
}
/// <summary>
/// Fires up a file dialog to select the directory to clone into
/// </summary>
public ReactiveCommand<Unit, Unit> BrowseForDirectory { get { return browseForDirectoryCommand; } }
/// <summary>
/// Is running the creation process
/// </summary>
public bool IsCreating { get { return isCreating.Value; } }
IReadOnlyList<GitIgnoreItem> gitIgnoreTemplates;
public IReadOnlyList<GitIgnoreItem> GitIgnoreTemplates
{
get { return gitIgnoreTemplates; }
set { this.RaiseAndSetIfChanged(ref gitIgnoreTemplates, value); }
}
IReadOnlyList<LicenseItem> licenses;
public IReadOnlyList<LicenseItem> Licenses
{
get { return licenses; }
set { this.RaiseAndSetIfChanged(ref licenses, value); }
}
GitIgnoreItem selectedGitIgnoreTemplate;
public GitIgnoreItem SelectedGitIgnoreTemplate
{
get { return selectedGitIgnoreTemplate; }
set { this.RaiseAndSetIfChanged(ref selectedGitIgnoreTemplate, value ?? GitIgnoreItem.None); }
}
LicenseItem selectedLicense;
public LicenseItem SelectedLicense
{
get { return selectedLicense; }
set { this.RaiseAndSetIfChanged(ref selectedLicense, value ?? LicenseItem.None); }
}
/// <summary>
/// List of accounts (at least one)
/// </summary>
public IReadOnlyList<IAccount> Accounts { get { return accounts.Value; } }
public ReactivePropertyValidator<string> BaseRepositoryPathValidator { get; private set; }
/// <summary>
/// Fires off the process of creating the repository remotely and then cloning it locally
/// </summary>
public ReactiveCommand<Unit, Unit> CreateRepository { get; private set; }
public IObservable<object> Done => CreateRepository.Select(_ => (object)null);
public async Task InitializeAsync(IConnection connection)
{
modelService = await modelServiceFactory.CreateAsync(connection).ConfigureAwait(true);
Title = string.Format(CultureInfo.CurrentCulture, Resources.CreateTitle, connection.HostAddress.Title);
accounts = modelService.GetAccounts()
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, vm => vm.Accounts, initialValue: new ReadOnlyCollection<IAccount>(Array.Empty<IAccount>()));
this.WhenAny(x => x.Accounts, x => x.Value)
.Select(accts => accts?.FirstOrDefault())
.WhereNotNull()
.Subscribe(a => SelectedAccount = a);
modelService.GetGitIgnoreTemplates()
.Where(x => x != null)
.ToList()
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x =>
{
var sorted = x
.Distinct()
.OrderByDescending(item => item.Recommended)
.ThenBy(item => item.Name);
GitIgnoreTemplates = new[] { GitIgnoreItem.None }.Concat(sorted).ToList();
SelectedGitIgnoreTemplate = GitIgnoreTemplates
.FirstOrDefault(i => i?.Name.Equals("VisualStudio", StringComparison.OrdinalIgnoreCase) == true);
});
modelService.GetLicenses()
.Where(x => x != null)
.ToList()
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x =>
{
var sorted = x
.Distinct()
.OrderByDescending(item => item.Recommended)
.ThenBy(item => item.Key);
Licenses = new[] { LicenseItem.None }.Concat(sorted).ToList();
});
}
protected override NewRepository GatherRepositoryInfo()
{
var gitHubRepository = base.GatherRepositoryInfo();
if (SelectedLicense != LicenseItem.None)
{
gitHubRepository.LicenseTemplate = SelectedLicense.Key;
gitHubRepository.AutoInit = true;
}
if (SelectedGitIgnoreTemplate != GitIgnoreItem.None)
{
gitHubRepository.GitignoreTemplate = SelectedGitIgnoreTemplate.Name;
gitHubRepository.AutoInit = true;
}
return gitHubRepository;
}
IObservable<Unit> ShowBrowseForDirectoryDialog()
{
return Observable.Start(() =>
{
// We store this in a local variable to prevent it changing underneath us while the
// folder dialog is open.
var localBaseRepositoryPath = BaseRepositoryPath;
var browseResult = operatingSystem.Dialog.BrowseForDirectory(localBaseRepositoryPath,
Resources.BrowseForDirectory);
if (!browseResult.Success)
return;
var directory = browseResult.DirectoryPath ?? localBaseRepositoryPath;
try
{
BaseRepositoryPath = directory;
}
catch (Exception e)
{
// TODO: We really should limit this to exceptions we know how to handle.
log.Error(e, "Failed to set base repository path {@0}",
new { localBaseRepositoryPath, BaseRepositoryPath, directory });
}
}, RxApp.MainThreadScheduler);
}
bool IsAlreadyRepoAtPath(string potentialRepositoryName)
{
Guard.ArgumentNotNull(potentialRepositoryName, nameof(potentialRepositoryName));
bool isAlreadyRepoAtPath = false;
var validationResult = BaseRepositoryPathValidator.ValidationResult;
string safeRepositoryName = GetSafeRepositoryName(potentialRepositoryName);
if (validationResult != null && validationResult.IsValid)
{
if (Path.GetInvalidPathChars().Any(chr => BaseRepositoryPath.Contains(chr)))
return false;
string potentialPath = Path.Combine(BaseRepositoryPath, safeRepositoryName);
isAlreadyRepoAtPath = operatingSystem.Directory.Exists(potentialPath);
}
return isAlreadyRepoAtPath;
}
IObservable<Unit> OnCreateRepository()
{
var newRepository = GatherRepositoryInfo();
return repositoryCreationService.CreateRepository(
newRepository,
SelectedAccount,
BaseRepositoryPath,
modelService.ApiClient)
.Do(_ => usageTracker.IncrementCounter(x => x.NumberOfReposCreated).Forget());
}
ReactiveCommand<Unit, Unit> InitializeCreateRepositoryCommand()
{
var canCreate = this.WhenAny(
x => x.RepositoryNameValidator.ValidationResult.IsValid,
x => x.BaseRepositoryPathValidator.ValidationResult.IsValid,
(x, y) => x.Value && y.Value);
var createCommand = ReactiveCommand.CreateFromObservable(OnCreateRepository, canCreate);
createCommand.ThrownExceptions.Subscribe(ex =>
{
if (!Extensions.ExceptionExtensions.IsCriticalException(ex))
{
log.Error(ex, "Error creating repository");
#pragma warning disable CS0618 // Type or member is obsolete
UserError.Throw(TranslateRepositoryCreateException(ex));
#pragma warning restore CS0618 // Type or member is obsolete
}
});
return createCommand;
}
static string StripSurroundingQuotes(string path)
{
Guard.ArgumentNotNull(path, nameof(path));
if (string.IsNullOrEmpty(path)
|| path.Length < 2
|| !path.StartsWith("\"", StringComparison.Ordinal)
|| !path.EndsWith("\"", StringComparison.Ordinal))
{
return path;
}
return path.Substring(1, path.Length - 2);
}
PublishRepositoryUserError TranslateRepositoryCreateException(Exception ex)
{
Guard.ArgumentNotNull(ex, nameof(ex));
var existsException = ex as RepositoryExistsException;
if (existsException != null && SelectedAccount != null)
{
string message = string.Format(
CultureInfo.InvariantCulture,
Resources.RepositoryCreationFailedAlreadyExists,
SelectedAccount.Login, RepositoryName);
return new PublishRepositoryUserError(message, Resources.RepositoryCreationFailedAlreadyExistsMessage);
}
var quotaExceededException = ex as PrivateRepositoryQuotaExceededException;
if (quotaExceededException != null && SelectedAccount != null)
{
return new PublishRepositoryUserError(Resources.RepositoryCreationFailedQuota, quotaExceededException.Message);
}
return new PublishRepositoryUserError(ex.Message);
}
}
}