-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodeFile.cs
More file actions
558 lines (500 loc) · 20.1 KB
/
Copy pathCodeFile.cs
File metadata and controls
558 lines (500 loc) · 20.1 KB
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
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using StatTag.Core.Interfaces;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StatTag.Core.Models
{
/// <summary>
/// A sequence of instructions saved in a text file that can be executed
/// in a statistical package (e.g. Stata, R, SAS), and will be used within
/// a Word document to derive values that are placed into the document text.
/// </summary>
public class CodeFile
{
[JsonIgnore] // Even though this is private, we want to ensure it never gets serialized
private List<string> ContentCache = null;
public string StatisticalPackage { get; set; }
public string FilePath { get; set; }
public DateTime? LastCached { get; set; }
[JsonIgnore]
public List<Tag> Tags { get; set; }
[JsonIgnore]
public List<string> Content
{
get { return ContentCache ?? (ContentCache = LoadFileContent()); }
set { ContentCache = value; }
}
/// <summary>
/// This is typically a lightweight wrapper around the standard
/// File class, but is used to allow us to mock file IO during
/// our unit tests.
/// </summary>
protected IFileHandler FileHandler { get; set; }
public CodeFile()
{
Initialize(null);
}
public CodeFile(CodeFile file)
{
Initialize(null);
if (file != null)
{
Tags = file.Tags;
StatisticalPackage = file.StatisticalPackage;
FilePath = file.FilePath;
LastCached = file.LastCached;
Content = file.Content;
}
}
public CodeFile(IFileHandler handler = null)
{
Initialize(handler);
}
protected void Initialize(IFileHandler handler)
{
Tags = new List<Tag>();
FileHandler = handler ?? new FileHandler();
}
public string GetChecksumFromFile()
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(FilePath))
{
return Encoding.Default.GetString(md5.ComputeHash(stream));
}
}
}
public string GetChecksumFromCache()
{
using (var md5 = MD5.Create())
{
var data = string.Join("\r\n", Content);
return Encoding.Default.GetString(md5.ComputeHash(Encoding.Default.GetBytes(data)));
}
}
public override string ToString()
{
return FilePath ?? string.Empty;
}
public override int GetHashCode()
{
return (FilePath != null ? FilePath.GetHashCode() : 0);
}
public override bool Equals(object obj)
{
var item = obj as CodeFile;
if (item == null)
{
return false;
}
return (string.Compare(item.FilePath, FilePath, StringComparison.CurrentCultureIgnoreCase) == 0);
}
/// <summary>
/// Determine if this is a valid code file
/// </summary>
/// <returns></returns>
public bool IsValid()
{
return (!string.IsNullOrWhiteSpace(FilePath) & FileHandler.Exists(FilePath));
}
/// <summary>
/// Return the contents of the CodeFile
/// </summary>
/// <returns></returns>
public virtual List<string> LoadFileContent()
{
if (!FileHandler.Exists(FilePath))
{
ContentCache = null;
}
else
{
RefreshContent();
}
return ContentCache;
}
/// <summary>
/// Read the contents of the code file from the underlying file on the file system.
/// </summary>
/// <returns></returns>
public void RefreshContent()
{
ContentCache = new List<string>(FileHandler.ReadAllLines(FilePath));
}
/// <summary>
/// Using the contents of this file, parse the instrutions and build the list
/// of tags that are present and cache them for later use.
/// </summary>
public void LoadTagsFromContent(bool preserveCache = true)
{
Tag[] savedTags = null;
if (preserveCache)
{
savedTags = new Tag[Tags.Count];
Tags.CopyTo(savedTags);
}
// Any time we try to load, reset the list of tags that may exist
Tags = new List<Tag>();
var content = LoadFileContent();
if (content == null || !content.Any())
{
return;
}
var parser = Factories.GetParser(this);
if (parser == null)
{
return;
}
Tags = new List<Tag>(parser.Parse(this).Where(x => !string.IsNullOrWhiteSpace(x.Type)));
Tags.ForEach(x => x.CodeFile = this);
if (preserveCache)
{
// Since we are reloading from a file, at this point if we had any cached results for
// a tag we want to associate that back with the tag.
foreach (var tag in Tags)
{
SetCachedTag(savedTags, tag);
}
}
}
/// <summary>
/// Given a set of existing tags (which are assumed to have cached results already set), update
/// the cached results in another tag.
/// <remarks>This is used primarily when a code file is reloaded, which resets its collection
/// of tags. Those tags will be valid, but will have their cached results reset.</remarks>
/// </summary>
/// <param name="existingTags">The tags that have cached results</param>
/// <param name="tag">The tag that needs to receive results</param>
protected void SetCachedTag(IEnumerable<Tag> existingTags, Tag tag)
{
var existingTag = existingTags.FirstOrDefault(x => x.Equals(tag));
if (existingTag != null && existingTag.CachedResult != null)
{
tag.CachedResult = new List<CommandResult>(existingTag.CachedResult);
}
}
/// <summary>
/// Save the content to the code file
/// </summary>
public virtual void Save()
{
if (FilePath != null && Content != null)
{
FileHandler.WriteAllLines(FilePath, Content);
}
}
/// <summary>
/// Save a backup copy of this code file, in the event we cause issues with the file and the
/// user needs to restore it.
/// </summary>
public void SaveBackup()
{
var backupFile = string.Format("{0}.{1}", FilePath, Constants.FileExtensions.Backup);
if (!FileHandler.Exists(backupFile))
{
FileHandler.Copy(FilePath, backupFile);
}
}
/// <summary>
/// Utility method to serialize the list of code files into a JSON array.
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public static string SerializeList(List<CodeFile> files)
{
return JsonConvert.SerializeObject(files);
}
/// <summary>
/// Utility method to take a JSON array string and convert it back into a list of
/// CodeFile objects. This does not resolve the list of tags that may be
/// associated with the CodeFile.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static List<CodeFile> DeserializeList(string value)
{
return JsonConvert.DeserializeObject<List<CodeFile>>(value);
}
/// <summary>
/// Given a file filter (e.g. "*.txt" or "*.txt;*.t", determine if the supplied
/// path parameter matches.
/// </summary>
/// <param name="filter"></param>
/// <param name="path"></param>
/// <returns></returns>
private static bool FilterMatches(string filter, string path)
{
string[] extensions = filter.Split(';');
string normalizedPath = path.ToUpper();
if (extensions.Any(extension => normalizedPath.EndsWith(extension.Replace("*", "").ToUpper())))
{
return true;
}
return false;
}
/// <summary>
/// Utility method to take a path and determine which statistical package is
/// most likely the right one This only returns a value if there is a high
/// degree of certainty of the guess, and is based purely on the file name
/// (not file content).
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GuessStatisticalPackage(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return string.Empty;
}
path = path.Trim();
if (FilterMatches(Constants.FileFilters.StataFilter, path))
{
return Constants.StatisticalPackages.Stata;
}
if (FilterMatches(Constants.FileFilters.SASFilter, path))
{
return Constants.StatisticalPackages.SAS;
}
if (FilterMatches(Constants.FileFilters.RFilter, path))
{
return Constants.StatisticalPackages.R;
}
if (FilterMatches(Constants.FileFilters.RMarkdownFilter, path))
{
return Constants.StatisticalPackages.RMarkdown;
}
if (FilterMatches(Constants.FileFilters.PythonFilter, path))
{
return Constants.StatisticalPackages.Python;
}
return string.Empty;
}
/// <summary>
/// Removes a tag from the file, and from the internal cache.
/// </summary>
/// <param name="tag"></param>
public void RemoveTag(Tag tag)
{
if (tag == null)
{
return;
}
if (!Tags.Remove(tag))
{
// If the exact object doesn't match, then search by equality
var foundTag = Tags.Find(x => x.Equals(tag));
if (foundTag == null)
{
return;
}
Tags.Remove(foundTag);
}
ContentCache.RemoveAt(tag.LineEnd.Value);
ContentCache.RemoveAt(tag.LineStart.Value);
// Any tags below the one being removed need to be adjusted
foreach (var otherTag in Tags)
{
// Tags can't overlap, so we can simply check for the start after the end.
if (otherTag.LineStart > tag.LineEnd)
{
otherTag.LineStart -= 2;
otherTag.LineEnd -= 2;
}
}
}
/// <summary>
/// Removes a tag from the file, and from the internal cache.
/// This is different from RemoveTag, in that it does additional
/// processing and handling of tags that may exist in the code file,
/// but aren't known (weren't loaded) because they collided with
/// another tag.
/// </summary>
/// <param name="tag"></param>
public void RemoveCollidingTag(Tag tag)
{
if (tag == null)
{
return;
}
if (!Tags.Remove(tag))
{
// If the exact object doesn't match, then search by equality
var foundTag = Tags.Find(x => x.Equals(tag));
if (foundTag != null)
{
Tags.Remove(foundTag);
}
}
ContentCache.RemoveAt(tag.LineEnd.Value);
ContentCache.RemoveAt(tag.LineStart.Value);
// Offset the list of tracked tags for this code file to reflect the removed lines
OffsetTagListByRemovedTag(Tags, tag);
}
/// <summary>
/// Utility function to offset the line indexes of a list of tags, given a tag that
/// is being removed. This will account for the various overlapping/embedding scenarios
/// that can affect line offsets.
/// </summary>
/// <param name="tagList"></param>
/// <param name="removedTag"></param>
public static void OffsetTagListByRemovedTag(IEnumerable<Tag> tagList, Tag removedTag)
{
// Any tags below the one being removed need to be adjusted
foreach (var otherTag in tagList)
{
// If the other tag starts after the removed tag ends, we need to offset
// the start and end by two (one for each of the lines that were removed
// for the start and end comments, respectively)
if (otherTag.LineStart > removedTag.LineEnd)
{
otherTag.LineStart -= 2;
otherTag.LineEnd -= 2;
}
// If the other tag only starts after the removed tag ends, we just offset
// by one to account for the removed start tag. The removed end tag
// won't affect us.
else if (otherTag.LineStart > removedTag.LineStart)
{
otherTag.LineStart -= 1;
otherTag.LineEnd -= 1;
}
// If the other tag starts before the removed tag starts, the start position
// isn't impacted. But if it ends after the removed tag starts, we need to
// offset just our end position by 2
else if (otherTag.LineStart < removedTag.LineStart && otherTag.LineEnd > removedTag.LineEnd)
{
otherTag.LineEnd -= 2;
}
// If the other tag starts before the removed tag starts, the start position
// isn't impacted. But if it ends after the removed tag end, we need to
// offset just our end position by 1
else if (otherTag.LineStart < removedTag.LineStart && otherTag.LineEnd > removedTag.LineStart)
{
otherTag.LineEnd -= 1;
}
}
}
/// <summary>
/// Updates or inserts a tag in the file. An update takes place only if oldTag
/// is defined, and it is able to match that old tag.
/// </summary>
/// <param name="newTag"></param>
/// <param name="oldTag"></param>
/// <param name="matchWithPosition">When looking to replace an existing tag (which assumes that oldTag is
/// specified), this parameter when set to true will only replace the tag if the line numbers match. This is to
/// be used when updating duplicate named tags, but shouldn't be used otherwise.</param>
/// <returns></returns>
public Tag AddTag(Tag newTag, Tag oldTag = null, bool matchWithPosition = false)
{
// Do some sanity checking before modifying anything
if (newTag == null || !newTag.LineStart.HasValue || !newTag.LineEnd.HasValue)
{
return null;
}
if (newTag.LineStart > newTag.LineEnd)
{
throw new InvalidDataException("The new tag start index is after the end index, which is not allowed.");
}
var updatedTag = new Tag(newTag);
var content = Content; // Force cache to load so we can reference it later w/o accessor overhead
if (oldTag != null)
{
//var refreshedOldTag = (matchWithPosition ? Tags.FirstOrDefault(tag => oldTag.EqualsWithPosition(tag)) : Tags.FirstOrDefault(tag => oldTag.Equals(tag)));
var refreshedOldTag =
Tags.FirstOrDefault(tag => oldTag.Equals(tag, matchWithPosition));
if (refreshedOldTag == null)
{
throw new InvalidDataException("Unable to find the existing tag to update.");
}
if (refreshedOldTag.LineStart > refreshedOldTag.LineEnd)
{
throw new InvalidDataException("The existing tag start index is after the end index, which is not allowed.");
}
// Remove the starting tag and then adjust indices as appropriate
ContentCache.RemoveAt(refreshedOldTag.LineStart.Value);
if (updatedTag.LineStart > refreshedOldTag.LineStart)
{
updatedTag.LineStart -= 1;
updatedTag.LineEnd -= 1; // We know line end >= line start
}
else if (updatedTag.LineEnd > refreshedOldTag.LineStart)
{
updatedTag.LineEnd -= 1;
}
refreshedOldTag.LineEnd -= 1; // Don't forget to adjust the old tag index
ContentCache.RemoveAt(refreshedOldTag.LineEnd.Value);
if (updatedTag.LineStart > refreshedOldTag.LineEnd)
{
updatedTag.LineStart -= 1;
updatedTag.LineEnd -= 1;
}
else if (updatedTag.LineEnd >= refreshedOldTag.LineEnd)
{
updatedTag.LineEnd -= 1;
}
var index = Tags.FindIndex(x => x.Equals(refreshedOldTag, matchWithPosition));
Tags.RemoveAt(index);
}
var generator = Factories.GetGenerator(this);
if (generator == null)
{
return null;
}
ContentCache.Insert(updatedTag.LineStart.Value, generator.CreateOpenTag(updatedTag));
updatedTag.LineEnd += 2; // Offset one line for the opening tag, the second line is for the closing tag
ContentCache.Insert(updatedTag.LineEnd.Value, generator.CreateClosingTag());
// Add to our collection of tags
Tags.Add(updatedTag);
return updatedTag;
}
/// <summary>
/// Look at all of the tags that are defined within this code file, and create a list
/// of any tags that have duplicate names.
/// </summary>
/// <returns></returns>
public Dictionary<Tag, List<Tag>> FindDuplicateTags()
{
var duplicates = new Dictionary<Tag, List<Tag>>();
if (Tags == null)
{
return duplicates;
}
var distinct = new Dictionary<string, Tag>();
foreach (var tag in Tags)
{
var searchLabel = tag.Name.ToUpper();
// See if we already have this in the distinct list of tag names
if (distinct.ContainsKey(searchLabel))
{
// If the duplicates collection hasn't been initialized, we will do that now.
if (!duplicates.ContainsKey(distinct[searchLabel]))
{
duplicates.Add(distinct[searchLabel], new List<Tag>());
}
duplicates[distinct[searchLabel]].Add(tag);
}
else
{
distinct.Add(tag.Name.ToUpper(), tag);
}
}
return duplicates;
}
/// <summary>
/// Given the content passed as a parameter, this method updates the file on disk with the new
/// content and refreshes the internal cache.
/// </summary>
/// <param name="text"></param>
public virtual void UpdateContent(string text)
{
FileHandler.WriteAllText(FilePath, text);
LoadTagsFromContent();
}
}
}