-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
682 lines (603 loc) · 25.8 KB
/
MainWindow.xaml.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Linq;
using IWshRuntimeLibrary;
using Ookii.Dialogs.Wpf;
using updateFromGit.wins;
namespace updateFromGit
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// имя каталога со сценариями
/// </summary>
private string dirOfScenaries = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
Properties.Settings.Default.dirOfScenaries
);
/// <summary>
/// Текущий сценарий
/// </summary>
private Scenario currentScenario;
/// <summary>
/// Наличие сценария в работе
/// </summary>
private bool isActive = false;
/// <summary>
/// Текущий сценарий сохранён
/// </summary>
private bool isSaved = true;
/// <summary>
/// Выполняется обновление
/// </summary>
private bool isUpdating = false;
/// <summary>
/// Регулярное выражение проверки ссылки на Git репозиторий
/// </summary>
//private Regex gitlink = new Regex(
// string.Format(@"^http://{0}/scm/git/\w*$", Properties.Settings.Default.scm_server)
// );
/// <summary>
/// Заголовок окна по умолчанию
/// </summary>
private string windowDefaultTitle = "massUpdateFromGit";
private CancellationTokenSource cts;
public MainWindow()
{
InitializeComponent();
this.Closing += windowClosing;
// создание директории, если нету
if (!Directory.Exists(dirOfScenaries))
{
Directory.CreateDirectory(dirOfScenaries);
}
activateWindow(false);
}
public void windowClosing(object sender, CancelEventArgs e)
{
if (!checkBeforeExit()) { e.Cancel = true; }
}
/// <summary>
/// Отображение интерфейса в зависимости от наличия сценария
/// </summary>
/// <param name="activate">наличие сценария, созданного или открытого</param>
private void activateWindow(bool activate)
{
if (activate)
{
isActive = true;
greetGrid.Visibility = System.Windows.Visibility.Hidden;
mainGrid.Visibility = System.Windows.Visibility.Visible;
crntScenName.Content = currentScenario.name;
crntScenName.Foreground = new SolidColorBrush(Colors.Black);
mn_update.IsEnabled = true;
mn_shortcut.IsEnabled = true;
this.Title = windowDefaultTitle;
this.Title = string.Format("{0} | {1}", this.Title, currentScenario.name);
}
else
{
isActive = false;
greetGrid.Visibility = System.Windows.Visibility.Visible;
mainGrid.Visibility = System.Windows.Visibility.Hidden;
crntScenName.Content = "неизвестно";
crntScenName.Foreground = new SolidColorBrush(Colors.Red);
mn_save.IsEnabled = false;
mn_update.IsEnabled = false;
mn_shortcut.IsEnabled = false;
this.Title = windowDefaultTitle;
}
}
/// <summary>
/// Окно "О программе"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void showAbout(object sender, RoutedEventArgs e)
{
HelpWindow about = new HelpWindow();
about.ShowDialog();
}
/// <summary>
/// Выход из приложения
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void shutdownApp(object sender, RoutedEventArgs e)
{
if (checkBeforeExit())
{
App.Current.Shutdown(0);
}
}
private bool checkBeforeExit()
{
//if (!isActive) { return true; }
if (currentScenario != null && !isSaved)
{
MessageBoxResult what2do = MessageBox.Show(
"В текущем сценарии имеются несохранённые изменения. Вы хотите их сохранить?",
"Изменения не сохранены",
MessageBoxButton.YesNoCancel,
MessageBoxImage.Question
);
if (what2do == MessageBoxResult.Yes)
{
saveScenario();
isActive = false;
return true;
}
else
{
if (what2do == MessageBoxResult.No)
{
isActive = false;
return true;
}
else
{
return false;
}
}
}
return true;
}
private void createNew_clicked(object sender, RoutedEventArgs e)
{
if (!checkBeforeExit()) { return; }
try
{
NewScenario newscen = new NewScenario();
if (newscen.ShowDialog() == true)
{
currentScenario = new Scenario(
newscen.NameOfScenario,
System.IO.Path.Combine(dirOfScenaries, newscen.NameOfScenario + ".xml")
);
if (!currentScenario.exportScenario2XML(dirOfScenaries))
{
MessageBox.Show(
"Не удалось экспортировать сценарий в XML. Однако, вы можете продолжать работать с ним.",
"Ошибка экспорта сценария",
MessageBoxButton.OK,
MessageBoxImage.Warning
);
}
gitRepo.Clear();
lb_paths.Items.Clear();
activateWindow(true);
changeSavedStatus(true);
}
}
catch (Exception ex)
{
MessageBox.Show(
"Ошибка при создании файла сценария. " + ex.Message,
"Ошибка создания нового сценария",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
private void save_clicked(object sender, RoutedEventArgs e)
{
saveScenario();
}
private bool saveScenario()
{
List<string> paths = new List<string>();
foreach (var item in lb_paths.Items) { paths.Add(item.ToString()); }
try
{
currentScenario.updateScenario(
gitRepo.Text.Trim(),
tb_localRepo.Text.Trim(),
tb_branch.Text.Trim(),
paths
);
changeSavedStatus(true);
return true;
//MessageBox.Show(
// string.Format("Сценарий {0} успешно сохранён.", currentScenario.name),
// "Сценарий сохранён",
// MessageBoxButton.OK,
// MessageBoxImage.Information
// );
}
catch (Exception ex)
{
MessageBox.Show(
"Ошибка при сохранении сценария в файл. " + ex.Message,
"Ошибка сохранения сценария",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
}
private void open_clicked(object sender, RoutedEventArgs e)
{
if (!checkBeforeExit()) { return; }
string path = string.Empty;
VistaOpenFileDialog dialog = new VistaOpenFileDialog();
dialog.Multiselect = false;
dialog.Filter = "XML file (*.xml)|*.xml";
if ((bool)dialog.ShowDialog(this)) { path = dialog.FileName; } else { return;}
loadScenario(path);
}
public void loadScenario(string path)
{
try { currentScenario = new Scenario(path); }
catch (Exception ex)
{
MessageBox.Show(
"Ошибка при открытии сценария. Возможно, этот файл не является сценарием для обновления. Перехваченное исключение: " + ex.Message,
"Не удалось открыть сценарий",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return;
}
crntScenName.Content = currentScenario.name;
gitRepo.Text = currentScenario.gitLink;
tb_localRepo.Text = currentScenario.gitLocal;
tb_branch.Text = currentScenario.gitBranch;
lb_paths.Items.Clear();
foreach (string p2s in currentScenario.paths2servers) { lb_paths.Items.Add(p2s); }
activateWindow(true); // if (!isActive) { activateWindow(true); }
changeSavedStatus(true);
}
private void update_clicked(object sender, RoutedEventArgs e)
{
if (!updateORstop(isUpdating)) { return; }
if (!isUpdating)
{
// запуск процесса обновления без блокировки GUI с возможностью его отмены
cts = new CancellationTokenSource();
var task = Task.Run(() => doTheShit(currentScenario, cts.Token), cts.Token);
Task uiTask = task.ContinueWith((continuation) =>
{
updateORstop(true);
isUpdating = false;
MessageBox.Show(
"Выполнение задания по сценарию обновления закончено.",
"Процесс завершён"
);
}, TaskScheduler.FromCurrentSynchronizationContext());
isUpdating = true;
}
}
private void doTheShit(Scenario currentScenario, CancellationToken cancellationToken)
{
int max = currentScenario.paths2servers.Count;
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
pb_updating.Value = 0;
pb_updating.Maximum = max;
}
));
try
{
foreach (string path2update in currentScenario.paths2servers)
{
string path = path2update.TrimEnd('\\');
// [debug]
//Thread.Sleep(1500);
// получить из центрального репозитория последнюю инфу
using (Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = string.Format("--git-dir=\"{0}\" --work-tree=\"{1}\" fetch --all",
System.IO.Path.Combine(path, ".git"),
path
),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
})
{
proc.Start();
while (!proc.HasExited) { }
}
// выкатить в репозиторий свежую ветку
using (Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = string.Format("--git-dir=\"{0}\" --work-tree=\"{1}\" reset --hard {2}",
System.IO.Path.Combine(path, ".git"),
path,
currentScenario.gitBranch
),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
})
{
proc.Start();
while (!proc.HasExited) { }
}
// прогресс
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
pb_updating.Value++;
}
));
// проверяем, не был ли процесс отменён
cancellationToken.ThrowIfCancellationRequested();
}
}
catch (Exception ex)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
MessageBox.Show(
"Во время обновления произошла ошибка. Перехваченное исключение: " + ex.Message,
"Ошибка обновления репозиториев на серверах",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
));
}
}
private bool updateORstop(bool isUpdating)
{
if (isUpdating)
{
cts.Cancel();
mn_create.IsEnabled = true;
mn_open.IsEnabled = true;
mn_shortcut.IsEnabled = true;
dp_repo.Visibility = System.Windows.Visibility.Visible;
pb_updating.Visibility = System.Windows.Visibility.Hidden;
mn_update.Header = "Выполнить обновление";
mn_update.ToolTip = "Выполнить обновление на серверах по текущему сценарию";
mn_update.Icon = new System.Windows.Controls.Image
{
Source = new BitmapImage(new Uri("/reses/update.ico", UriKind.Relative)),
Width = 16
};
btn_doTheShit.Content = FindResource("update");
return true;
}
else
{
// сохранение сценария перед его выполнением
if (!saveScenario())
{
MessageBox.Show(
"Не удалось сохранить сценарий перед обновлением.",
"Обновление отменено",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
// проверка на отсутствующую ссылку на репозиторий
//if (string.IsNullOrEmpty(currentScenario.gitLink)
// || !gitlink.IsMatch(currentScenario.gitLink)
// )
//{
// MessageBox.Show(
// "В сценарии не указан корректный Git-репозиторий проекта.",
// "Обновление отменено",
// MessageBoxButton.OK,
// MessageBoxImage.Error
// );
// return false;
//}
// проверка на пустой список путей обновления
if (currentScenario.paths2servers.Count == 0)
{
MessageBox.Show(
"В сценарии отсутствуют пути обновления проекта на серверах.",
"Обновление отменено",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
// проверка существования локального репозитория
if (!Directory.Exists(System.IO.Path.Combine(tb_localRepo.Text.Trim(), ".git")))
{
MessageBox.Show(
"Не найден локальный репозиторий по указанному пути.",
"Обновление отменено",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
// проверка существования указанной ветви
if (string.IsNullOrEmpty(tb_branch.Text.Trim()))
{
MessageBox.Show(
"Не указана ветвь для обновления.",
"Обновление отменено",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
bool branchIsOk = false;
try
{
using (Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = string.Format("--git-dir={0} branch -r",
System.IO.Path.Combine(tb_localRepo.Text.Trim(), ".git")),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
})
{
proc.Start();
string output = App.getProcessOutput(proc);
string[] outputs = output.Split(new string[] {"\r\n", " "}, StringSplitOptions.None);
foreach (string o in outputs)
{
if (o == tb_branch.Text.Trim()) { branchIsOk = true; break; }
}
}
}
catch { branchIsOk = false; }
if (!branchIsOk)
{
MessageBox.Show(
"В репозитории отсутствует указанная ветвь.",
"Обновление отменено",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return false;
}
mn_create.IsEnabled = false;
mn_open.IsEnabled = false;
mn_shortcut.IsEnabled = false;
dp_repo.Visibility = System.Windows.Visibility.Hidden;
pb_updating.Visibility = System.Windows.Visibility.Visible;
mn_update.Header = "Остановить обновление";
mn_update.ToolTip = "Остановить процесс обновления (не рекомендуется)";
mn_update.Icon = new System.Windows.Controls.Image
{
Source = new BitmapImage(new Uri("/reses/stop.ico", UriKind.Relative)),
Width = 16
};
btn_doTheShit.Content = FindResource("stop");
return true;
}
}
private void shortcut_clicked(object sender, RoutedEventArgs e)
{
try
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
object shDesktop = (object)"Desktop";
WshShell shell = new WshShell();
string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + string.Format(@"\Сценарий обновления {0}.lnk", currentScenario.name);
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "Открытие сценария обновления";
shortcut.TargetPath = Assembly.GetExecutingAssembly().Location;
shortcut.Arguments = string.Format("-s {0}", currentScenario.path2save);
shortcut.IconLocation = Assembly.GetExecutingAssembly().Location + ", 0 ";
shortcut.Save();
}
catch (Exception ex)
{
MessageBox.Show(
"Ошибка при создании ярлыка. Перехваченное исключение: " + ex.Message,
"Не удалось создать ярлык",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return;
}
MessageBox.Show(
"Ярлык для запуска приложения с текущим сценарием создан на вашем Рабочем столе",
"Ярлык успешно создан",
MessageBoxButton.OK,
MessageBoxImage.Information
);
}
private void btn_addPath_clicked(object sender, RoutedEventArgs e)
{
NewPath newpath = new NewPath();
if (newpath.ShowDialog() == true)
{
if (!lb_paths.Items.Contains(newpath.path2dir))
{
lb_paths.Items.Add(newpath.path2dir);
changeSavedStatus(false);
}
else
{
MessageBox.Show(
"Этот путь уже содержится в списке",
"Повтор",
MessageBoxButton.OK,
MessageBoxImage.Warning
);
}
}
}
private void btn_delPath_clicked(object sender, RoutedEventArgs e)
{
if (lb_paths.SelectedIndex >= 0)
{
lb_paths.Items.RemoveAt(lb_paths.SelectedIndex);
changeSavedStatus(false);
}
}
/// <summary>
/// Меняет статус сценария и включает или отключает пункт сохранения
/// </summary>
/// <param name="saved">новое значение статуса</param>
public void changeSavedStatus(bool saved)
{
isSaved = saved;
mn_save.IsEnabled = !saved;
if (saved) { this.Title = this.Title.Replace("*", string.Empty); }
else { if (!this.Title.Contains("*")) { this.Title = this.Title + "*"; } }
}
private void gitRepo_changed(object sender, TextChangedEventArgs e)
{
//if (gitlink.IsMatch(gitRepo.Text.Trim()))
//{
// gitRepo.BorderBrush = Brushes.Green;
//}
//else
//{
// gitRepo.BorderBrush = Brushes.Red;
//}
if (currentScenario != null) { changeSavedStatus(false); }
}
private void gitLocal_changed(object sender, TextChangedEventArgs e)
{
if (currentScenario != null) { changeSavedStatus(false); }
}
private void gitBranch_changed(object sender, TextChangedEventArgs e)
{
if (currentScenario != null) { changeSavedStatus(false); }
}
private void btn_dir_clicked(object sender, RoutedEventArgs e)
{
NewPath newpath = new NewPath();
if (newpath.ShowDialog() == true)
{
tb_localRepo.Text = newpath.path2dir;
}
}
}
}