-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMainViewModel.cs
698 lines (614 loc) · 23.4 KB
/
MainViewModel.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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Xml;
using System.Xml.Linq;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.WindowsAPICodePack.Dialogs;
using Microsoft.WindowsAPICodePack.Shell.Interop;
using ResxUnusedFinder.Properties;
namespace ResxUnusedFinder
{
public class MainViewModel : ViewModelBase
{
private XDocument resourceDocument;
private HashSet<string> resourceKeys;
private List<string> files;
private List<string> extensionList;
private List<string> referenceFormatList;
private List<string> excludePrefixesList;
private Dictionary<string, Regex> regexCache;
public MainViewModel()
{
this.ProjectFolder = Settings.Default.ProjectFolder;
this.ResourceFile = Settings.Default.ResourceFile;
this.Extensions = Settings.Default.Extensions;
this.ExcludePrefixes = Settings.Default.ExcludePrefixes;
this.UseRegex = Settings.Default.UseRegex;
this.regexCache = new Dictionary<string, Regex>();
StringCollection settingsReferenceFormatList = Settings.Default.ReferenceFormatsList;
if (settingsReferenceFormatList == null || settingsReferenceFormatList.Count == 0)
{
string oldReferenceFormats = Settings.Default.ReferenceFormats;
if (string.IsNullOrEmpty(oldReferenceFormats))
{
this.ReferenceFormats = new ObservableCollection<ReferenceFormatViewModel>
{
new ReferenceFormatViewModel { Value = "AppResources.%" }
};
}
else
{
this.ReferenceFormats = new ObservableCollection<ReferenceFormatViewModel>(
oldReferenceFormats
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(format => new ReferenceFormatViewModel { Value = format }));
}
}
else
{
this.ReferenceFormats = new ObservableCollection<ReferenceFormatViewModel>();
foreach (string referenceFormat in Settings.Default.ReferenceFormatsList)
{
this.ReferenceFormats.Add(new ReferenceFormatViewModel { Value = referenceFormat });
}
}
this.RaisePropertyChanged(nameof(this.CanRemoveReferenceFormat));
if (string.IsNullOrEmpty(this.Extensions))
{
this.Extensions = ".cs,.xaml";
}
}
public void OnClose()
{
var referenceFormatsList = new StringCollection();
foreach (string format in this.ReferenceFormats.Select(f => f.Value))
{
referenceFormatsList.Add(format);
}
Settings.Default.ProjectFolder = this.ProjectFolder;
Settings.Default.ResourceFile = this.ResourceFile;
Settings.Default.Extensions = this.Extensions;
Settings.Default.ReferenceFormatsList = referenceFormatsList;
Settings.Default.ExcludePrefixes = this.ExcludePrefixes;
Settings.Default.UseRegex = this.UseRegex;
}
private string projectFolder;
public string ProjectFolder
{
get { return this.projectFolder; }
set { this.Set(ref this.projectFolder, value); }
}
private string resourceFile;
public string ResourceFile
{
get { return this.resourceFile; }
set { this.Set(ref this.resourceFile, value); }
}
private string extensions;
public string Extensions
{
get { return this.extensions; }
set { this.Set(ref this.extensions, value); }
}
public ObservableCollection<ReferenceFormatViewModel> ReferenceFormats { get; }
private string excludePrefixes;
public string ExcludePrefixes
{
get { return this.excludePrefixes; }
set { this.Set(ref this.excludePrefixes, value); }
}
private ObservableCollection<StringResource> unusedResources;
public ObservableCollection<StringResource> UnusedResources
{
get { return this.unusedResources; }
set { this.Set(ref this.unusedResources, value); }
}
private string status;
public string Status
{
get { return this.status; }
set { this.Set(ref this.status, value); }
}
private bool working;
public bool Working
{
get { return this.working; }
set
{
this.Set(ref this.working, value);
DispatchService.BeginInvoke(() =>
{
this.RefreshCommand.RaiseCanExecuteChanged();
this.CopyCommand.RaiseCanExecuteChanged();
this.DeleteAllCommand.RaiseCanExecuteChanged();
this.DeleteSelectedCommand.RaiseCanExecuteChanged();
this.ExcludeSelectedCommand.RaiseCanExecuteChanged();
this.BrowseFolderCommand.RaiseCanExecuteChanged();
this.BrowseResourceFileCommand.RaiseCanExecuteChanged();
});
}
}
public bool ItemsSelected
{
get { return this.UnusedResources != null && this.UnusedResources.Any(r => r.IsSelected); }
}
public bool CanRemoveReferenceFormat
{
get { return this.ReferenceFormats.Count > 1; }
}
private bool useRegex;
public bool UseRegex
{
get { return this.useRegex; }
set { this.Set(ref this.useRegex, value); }
}
private RelayCommand browseFolderCommand;
public RelayCommand BrowseFolderCommand
{
get
{
return this.browseFolderCommand ?? (this.browseFolderCommand = new RelayCommand(
() =>
{
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
dialog.EnsurePathExists = true;
dialog.EnsureValidNames = true;
dialog.Multiselect = false;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
this.ProjectFolder = dialog.FileName;
}
},
() =>
{
return !this.Working;
}));
}
}
private RelayCommand browseResourceFileCommand;
public RelayCommand BrowseResourceFileCommand
{
get
{
return this.browseResourceFileCommand ?? (this.browseResourceFileCommand = new RelayCommand(
() =>
{
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = false;
dialog.EnsurePathExists = true;
dialog.EnsureValidNames = true;
dialog.Multiselect = false;
dialog.Filters.Add(new CommonFileDialogFilter("RESX file", ".resx"));
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
this.ResourceFile = dialog.FileName;
}
},
() =>
{
return !this.Working;
}));
}
}
private RelayCommand addReferenceFormatCommand;
public RelayCommand AddReferenceFormatCommand
{
get
{
return this.addReferenceFormatCommand ?? (this.addReferenceFormatCommand = new RelayCommand(
() =>
{
this.ReferenceFormats.Add(new ReferenceFormatViewModel { Value = string.Empty });
this.RaisePropertyChanged(nameof(this.CanRemoveReferenceFormat));
}));
}
}
private RelayCommand<ReferenceFormatViewModel> removeReferenceFormatCommand;
public RelayCommand<ReferenceFormatViewModel> RemoveReferenceFormatCommand
{
get
{
return this.removeReferenceFormatCommand ?? (this.removeReferenceFormatCommand = new RelayCommand<ReferenceFormatViewModel>(
vm =>
{
this.ReferenceFormats.Remove(vm);
this.RaisePropertyChanged(nameof(this.CanRemoveReferenceFormat));
}));
}
}
private RelayCommand refreshCommand;
public RelayCommand RefreshCommand
{
get
{
return this.refreshCommand ?? (this.refreshCommand = new RelayCommand(
() =>
{
Task.Run(() =>
{
this.RefreshUnusedList();
});
},
() =>
{
return !this.Working;
}));
}
}
private RelayCommand copyCommand;
public RelayCommand CopyCommand
{
get
{
return this.copyCommand ?? (this.copyCommand = new RelayCommand(
() =>
{
string clipboardText = string.Join(Environment.NewLine, this.UnusedResources.Select(r => r.Key));
if (ClipboardService.SetText(clipboardText))
{
MessageBox.Show("Copied " + this.UnusedResources.Count + " key(s) to the clipboard.");
}
},
() =>
{
return !this.Working && this.UnusedResources != null && this.UnusedResources.Count > 0;
}));
}
}
private RelayCommand deleteSelectedCommand;
public RelayCommand DeleteSelectedCommand
{
get
{
return this.deleteSelectedCommand ?? (this.deleteSelectedCommand = new RelayCommand(
() =>
{
this.Delete(new HashSet<string>(this.UnusedResources.Where(r => r.IsSelected).Select(r => r.Key)));
},
() =>
{
return !this.Working;
}));
}
}
private RelayCommand deleteAllCommand;
public RelayCommand DeleteAllCommand
{
get
{
return this.deleteAllCommand ?? (this.deleteAllCommand = new RelayCommand(
() =>
{
if (MessageBox.Show("Are you sure you want to delete " + this.UnusedResources.Count + " resources?", "Confirm delete", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
Task.Run(() =>
{
this.Delete(new HashSet<string>(this.resourceKeys));
});
}
},
() =>
{
return !this.Working && this.UnusedResources != null && this.UnusedResources.Count > 0;
}));
}
}
private RelayCommand excludeSelectedCommand;
public RelayCommand ExcludeSelectedCommand
{
get
{
return this.excludeSelectedCommand ?? (this.excludeSelectedCommand = new RelayCommand(
() =>
{
var selectedItems = this.UnusedResources.Where(r => r.IsSelected).ToList();
foreach (var selectedItem in selectedItems)
{
this.UnusedResources.Remove(selectedItem);
this.resourceKeys.Remove(selectedItem.Key);
}
this.Status = "Excluded " + selectedItems.Count + " item(s).";
this.CopyCommand.RaiseCanExecuteChanged();
this.DeleteAllCommand.RaiseCanExecuteChanged();
},
() =>
{
return !this.Working;
}));
}
}
private RelayCommand<SelectionChangedEventArgs> onSelectionChangedCommand;
public RelayCommand<SelectionChangedEventArgs> OnSelectionChangedCommand
{
get
{
return this.onSelectionChangedCommand ?? (this.onSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(e =>
{
this.RaisePropertyChanged(() => this.ItemsSelected);
}));
}
}
private void RefreshUnusedList()
{
try
{
if (!this.ValidateRegexPatterns())
{
return;
}
this.Working = true;
this.PopulateSearchList();
this.FindUnusedResources();
this.Working = false;
}
catch (FileException exception)
{
HandleException(exception);
}
catch (ParseException exception)
{
HandleException(exception);
}
}
private void PopulateSearchList()
{
this.Status = "Populating search list...";
this.resourceKeys = new HashSet<string>();
this.excludePrefixesList = this.ExcludePrefixes == null ?
new List<string>() :
this.ExcludePrefixes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList();
this.resourceDocument = XDocument.Load(this.ResourceFile);
ForEveryDataElement(this.resourceDocument, dataElement =>
{
string name = GetName(dataElement);
bool addName = true;
foreach (string excludedPrefix in this.excludePrefixesList)
{
if (name.StartsWith(excludedPrefix))
{
addName = false;
break;
}
}
if (addName)
{
this.resourceKeys.Add(name);
}
});
}
private void FindUnusedResources()
{
this.PopulateFileList();
this.Status = "Finding unused keys...";
this.referenceFormatList = this.ReferenceFormats.Select(f => f.Value).Where(v => !string.IsNullOrWhiteSpace(v)).ToList();
foreach (string file in this.files)
{
this.RemoveFoundKeys(file);
}
// Remaining keys are unused
var newUnusedResources = new ObservableCollection<StringResource>();
foreach (string unusedKey in this.resourceKeys)
{
newUnusedResources.Add(new StringResource { Key = unusedKey });
}
this.UnusedResources = newUnusedResources;
this.Status = "Getting resource values...";
this.PopulateUnusedResourceValues();
this.Status = "Found " + this.UnusedResources.Count + " unused resource(s).";
}
private bool ValidateRegexPatterns()
{
if (!this.UseRegex)
{
return true;
}
foreach (string format in this.ReferenceFormats.Select(f => f.Value))
{
string testPattern = format.Replace("%", "Test");
try
{
var regex = new Regex(testPattern);
}
catch (Exception)
{
MessageBox.Show("Regex is not valid: " + format);
return false;
}
}
return true;
}
private void PopulateUnusedResourceValues()
{
ForEveryDataElement(this.resourceDocument, dataElement =>
{
var unusedResource = this.UnusedResources.FirstOrDefault(r => r.Key == GetName(dataElement));
if (unusedResource != null)
{
var valueElement = dataElement.Element("value");
if (valueElement != null)
{
unusedResource.Value = valueElement.Value;
}
}
});
}
private void PopulateFileList()
{
this.Status = "Populating file list...";
this.extensionList = this.Extensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(e => CleanExtension(e.Trim())).ToList();
this.files = new List<string>();
try
{
this.PopulateFileList(this.ProjectFolder);
}
catch (IOException exception)
{
throw new FileException("Could not populate file list.", exception);
}
catch (UnauthorizedAccessException exception)
{
throw new FileException("Could not populate file list.", exception);
}
}
private static string CleanExtension(string extension)
{
if (extension.StartsWith("."))
{
return extension;
}
return "." + extension;
}
private void PopulateFileList(string directoryPath)
{
foreach (string file in Directory.GetFiles(directoryPath))
{
foreach (string extension in this.extensionList)
{
if (file.EndsWith(extension))
{
this.files.Add(file);
break;
}
}
}
foreach (string subDirectory in Directory.GetDirectories(directoryPath))
{
this.PopulateFileList(subDirectory);
}
}
// Finds instances of resourceKeys in the given file and removes them from the collection if they are found
private void RemoveFoundKeys(string filePath)
{
string fileText = File.ReadAllText(filePath, Encoding.Default);
var foundResources = new List<string>();
foreach (string key in this.resourceKeys)
{
foreach (string referenceFormat in this.referenceFormatList)
{
string searchString = referenceFormat.Replace("%", key);
bool fileHasMatch;
if (this.UseRegex)
{
Regex regex;
if (!this.regexCache.TryGetValue(searchString, out regex))
{
regex = new Regex(searchString);
this.regexCache.Add(searchString, regex);
}
fileHasMatch = regex.IsMatch(fileText);
}
else
{
fileHasMatch = fileText.Contains(searchString);
}
if (fileHasMatch)
{
foundResources.Add(key);
break;
}
}
}
foreach (string key in foundResources)
{
this.resourceKeys.Remove(key);
}
}
private void Delete(HashSet<string> stringsToDelete)
{
try
{
this.Working = true;
int count = stringsToDelete.Count;
this.Status = "Deleting " + count + " unused resource(s)...";
var document = XDocument.Load(this.ResourceFile);
ForEveryDataElement(document, dataElement =>
{
if (stringsToDelete.Contains(GetName(dataElement)))
{
dataElement.Remove();
}
});
try
{
document.Save(this.ResourceFile);
}
catch (IOException exception)
{
throw new FileException("Error saving resource file.", exception);
}
catch (UnauthorizedAccessException exception)
{
throw new FileException("Error saving resource file.", exception);
}
catch (XmlException exception)
{
throw new FileException("Error saving resource file.", exception);
}
// Remove them from the collections
foreach (string deletedKey in stringsToDelete)
{
this.resourceKeys.Remove(deletedKey);
}
DispatchService.BeginInvoke(() =>
{
for (int i = this.UnusedResources.Count - 1; i >= 0; i--)
{
if (stringsToDelete.Contains(this.UnusedResources[i].Key))
{
this.UnusedResources.RemoveAt(i);
}
}
});
this.Status = "Deleted " + count + " unused resource(s).";
this.Working = false;
}
catch (FileException exception)
{
HandleException(exception);
}
catch (ParseException exception)
{
HandleException(exception);
}
}
private static void ForEveryDataElement(XDocument document, Action<XElement> action)
{
if (document.Root == null)
{
throw new ParseException("No root element found.");
}
foreach (var dataElement in document.Root.Elements("data").ToList())
{
action(dataElement);
}
}
private static string GetName(XElement dataElement)
{
var nameAttribute = dataElement.Attribute("name");
if (nameAttribute == null)
{
throw new ParseException("Name attribute missing on data.");
}
return nameAttribute.Value;
}
private static void HandleException(Exception exception)
{
DispatchService.BeginInvoke(() =>
{
MessageBox.Show(exception.Message);
});
}
}
}