forked from ahzf/CsQuery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptCollection.cs
More file actions
738 lines (613 loc) · 21.8 KB
/
Copy pathScriptCollection.cs
File metadata and controls
738 lines (613 loc) · 21.8 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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.IO;
using System.Text.RegularExpressions;
using CsQuery.Mvc;
namespace CsQuery.Mvc.ClientScript
{
/// <summary>
/// Collection of scripts used by the ScriptManager, and methods to process them
/// </summary>
public class ScriptCollection: ICollection<ScriptRef>
{
#region constructor
/// <summary>
/// Constructor for Script Collection.
/// </summary>
///
/// <param name="scriptEnvironment">
/// The ScriptEnvironment for this collection
/// </param>
public ScriptCollection(ScriptEnvironment scriptEnvironment)
{
ScriptEnvironment = scriptEnvironment;
Scripts = new HashSet<ScriptRef>();
DependenciesOrdered = new List<string>();
}
#endregion
#region private properties
private ScriptEnvironment ScriptEnvironment;
internal static ConcurrentDictionary<string, ScriptRef> ResolvedDependencies
= new ConcurrentDictionary<string, ScriptRef>();
/// <summary>
/// The file paths at the top level (the members of this collection)
/// </summary>
private HashSet<ScriptRef> Scripts;
/// <summary>
/// The dependencies in the order the were resolved
/// </summary>
private List<string> DependenciesOrdered;
#endregion
#region public properties
/// <summary>
/// Gets or sets options for controlling the operation.
/// </summary>
public ViewEngineOptions Options { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore errors.
/// </summary>
///
/// <value>
/// true if ignore errors, false if not.
/// </value>
public bool IgnoreErrors { get; set; }
#endregion
#region public methods
/// <summary>
/// Adds inputs from all the scripts found in a CQ object.
/// </summary>
///
/// <param name="scripts">
/// The scripts.
/// </param>
///
/// <returns>
/// The first script with dependencies
/// </returns>
public IDomObject AddFromCq(CQ scripts)
{
IDomObject first=null;
foreach (var script in scripts)
{
var scriptRef = AddPath(script.UrlSource());
if (first==null && scriptRef.Dependencies.Count > 0)
{
first = script;
}
}
return first;
}
/// <summary>
/// Adds a script reference by path.
/// </summary>
///
/// <param name="virtualPath">
/// Virtual path to the script.
/// </param>
public ScriptRef AddPath(string virtualPath)
{
var scriptRef = GetScriptRef(virtualPath);
Scripts.Add(scriptRef);
return scriptRef;
}
/// <summary>
/// Return dependencies found in the document.
/// </summary>
///
/// <returns>
/// An enumerator that allows foreach to be used to process get dependencies in this collection.
/// </returns>
public IEnumerable<ScriptRef> GetDependencies()
{
return GetDependencies(Scripts);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
///
/// <returns>
/// A hash code for the current <see cref="CsQuery.Mvc.ClientScript.ScriptCollection" />.
/// </returns>
public override int GetHashCode()
{
return Scripts.Select(item => item.GetHashCode()).Aggregate((cur, next) =>
{
return cur + next;
});
}
/// <summary>
/// Determines whether the specified <see cref="CsQuery.Mvc.ClientScript.ScriptCollection" /> is equal to the current
/// <see cref="CsQuery.Mvc.ClientScript.ScriptCollection" />.
/// </summary>
///
/// <param name="obj">
/// The object to compare with the current object.
/// </param>
///
/// <returns>
/// true if the objects are the same; false otherwise.
/// </returns>
public override bool Equals(object obj)
{
ScriptCollection other = obj as ScriptCollection;
return other != null &&
other.Scripts.Count == Count &&
other.Scripts.OrderBy(item=>item.Path).SequenceEqual(Scripts.OrderBy(item=>item.Path));
}
#endregion
#region private methods
/// <summary>
/// Return dependencies found in a sequence of files.
/// </summary>
///
/// <exception cref="FileNotFoundException">
/// Thrown when the requested file is not present.
/// </exception>
///
/// <param name="sources">
/// The sources.
/// </param>
///
/// <returns>
/// An enumerator that allows foreach to be used to process get dependencies in this collection.
/// </returns>
protected IEnumerable<ScriptRef> GetDependencies(IEnumerable<ScriptRef> sources)
{
HashSet<string> FoundDependencies = new HashSet<string>();
List<ScriptRef> OrderedDependencies = new List<ScriptRef>();
foreach (var script in sources)
{
try
{
foreach (var dep in GetDependencies(script))
{
if (FoundDependencies.Add(dep.Path))
{
OrderedDependencies.Add(dep);
}
}
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException(String.Format("Unable to resolve dependencies for \"{0}\": " + e.Message,
script.Path));
}
}
return OrderedDependencies;
}
/// <summary>
/// Gets a script reference given a path.
/// </summary>
///
/// <param name="virtualPath">
/// Virtual path to the script.
/// </param>
///
/// <returns>
/// The script reference.
/// </returns>
protected ScriptRef GetScriptRef(string virtualPath)
{
ScriptRef scriptRef;
var uniquePath = ScriptEnvironment.UniquePath(virtualPath);
if (ResolvedDependencies.TryGetValue(uniquePath, out scriptRef))
{
return scriptRef;
}
ScriptParser parser = new ScriptParser(ScriptEnvironment, uniquePath);
scriptRef = new ScriptRef
{
Path = uniquePath
};
if (parser.IsPhysicalFile)
{
string textOnly = "";
using (parser)
{
string line;
while ((line = parser.ReadLine()) != null
&& !parser.AnyCodeYet)
{
textOnly += line + System.Environment.NewLine;
ScriptRef dependencyRef;
if (TryGetDependencyRef_UsingFormat(scriptRef,line, out dependencyRef)) {
scriptRef.Dependencies.Add(dependencyRef);
}
}
scriptRef.ScriptHash = parser.FileHash;
}
// now parse the entire text again for the XML format
if (Options.HasFlag(ViewEngineOptions.ResolveXmlReferences))
{
var xml = CQ.CreateFragment(textOnly);
foreach (var el in xml["reference"])
{
ScriptRef dependencyRef;
if (TryGetDependencyRef_CQ(scriptRef, el, out dependencyRef))
{
scriptRef.Dependencies.Add(dependencyRef);
}
}
}
}
if (!Options.HasFlag(ViewEngineOptions.NoCache))
{
ResolvedDependencies[uniquePath] = scriptRef;
}
return scriptRef;
}
/// <summary>
/// Try get dependency reference from a "reference" element.
/// </summary>
///
/// <param name="parent">
/// The parent.
/// </param>
/// <param name="element">
/// The element.
/// </param>
/// <param name="scriptRef">
/// The relative path to the file to analyze.
/// </param>
///
/// <returns>
/// true if it succeeds, false if it fails.
/// </returns>
protected bool TryGetDependencyRef_CQ(ScriptRef parent, IDomObject element, out ScriptRef scriptRef)
{
bool noCombine = element.HasAttribute("nocombine");
bool ignore = element.HasAttribute("ignore");
scriptRef = null;
string options = element["options"];
if (!string.IsNullOrEmpty(options))
{
var optList = options.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
ignore =ignore || optList.Contains("ignore", StringComparer.CurrentCultureIgnoreCase);
noCombine = noCombine || optList.Contains("nocombine", StringComparer.CurrentCultureIgnoreCase);
}
if (ignore) {
return false;
}
var depName = element["path"];
string path;
if (!TryResolvePath(parent.RelativePathRoot,depName, out path) && !IgnoreErrors) {
throw new FileNotFoundException(String.Format("Unable to find dependency \"{0}\" in the file \"{1}\".", depName, parent.Path));
}
scriptRef = new ScriptRef
{
Path = path,
NoCombine = noCombine
};
return true;
}
/// <summary>
/// Analyzes a line and returns a dependency ScriptRef if it matches the "using xxx" format.
/// </summary>
///
/// <param name="parent">
/// The parent.
/// </param>
/// <param name="line">
/// The line.
/// </param>
/// <param name="scriptRef">
/// The relative path to the file to analyze.
/// </param>
///
/// <returns>
/// The dependency reference using format.
/// </returns>
protected bool TryGetDependencyRef_UsingFormat(ScriptRef parent, string line, out ScriptRef scriptRef)
{
var match = Patterns.Dependency.Match(line);
//var matchOptions = Patterns.Options.Match(line);
if (match.Success)
{
string depName = match.Groups["dep"].Value;
var optGroup = match.Groups["opt"];
// see if they omitted a file extension
var lastDot = depName.LastIndexOf(".");
var lastSlash = depName.Replace("\\","/").LastIndexOf("/");
if (lastDot<0 || lastDot < lastSlash)
{
depName += ".js";
}
string path;
if (!TryResolvePath(parent.RelativePathRoot, depName, out path) && !IgnoreErrors)
{
throw new FileNotFoundException(String.Format("Unable to find dependency \"{0}\" in the file \"{1}\".", depName, parent.Path));
}
scriptRef = new ScriptRef
{
Path = path,
NoCombine = optGroup.Captures.Any<Capture>(item => item.Value == "nocombine")
};
return true;
} else {
scriptRef = null;
return false;
}
}
/// <summary>
/// Return dependencies in the form of a virtual file path, e.g "~/scripts/something.js" for each
/// "//using xxx" found in a single file.
/// </summary>
///
/// <exception cref="FileNotFoundException">
/// Thrown when the requested file is not present.
/// </exception>
///
/// <param name="scriptRef">
/// The relative path to the file to analyze.
/// </param>
///
/// <returns>
/// An enumerator that allows foreach to be used to process get dependencies in this collection.
/// </returns>
protected IEnumerable<ScriptRef> GetDependencies(ScriptRef scriptRef)
{
foreach (var dep in scriptRef.Dependencies)
{
ScriptRef depRef;
if (!ResolvedDependencies.TryGetValue(dep.Path, out depRef))
{
depRef = GetScriptRef(dep.Path);
}
// When we resolve a dependency, whether it was created or resolved from the cache, update the
// active one with its settings, except for NoCombine which should only be updated when it's
// true for the resolved version. That is, we want to use the most conservative NoCombine so we
// don't combine if the script is included with that setting, or the script itself has that
// setting. If we just returned the ref we got from the cache, it would have incorrect
// NoCombine settings, and we don't want to alter the cached settings.
dep.UpdateFrom(depRef);
if (depRef.NoCombine)
{
dep.NoCombine = true;
}
foreach (var innerDep in GetDependencies(depRef))
{
yield return innerDep;
}
yield return dep;
}
}
private bool TryResolvePath(string relativePathRoot, string fileName, out string path)
{
string appRelativePath;
bool isFileRelativePath = IsFileRelativePath(fileName);
if (!isFileRelativePath)
{
appRelativePath = ScriptEnvironment.MapToAppRelativePath(fileName);
}
else
{
appRelativePath = ScriptEnvironment.ResolveParents(relativePathRoot + fileName);
}
string fsPath = ScriptEnvironment.MapPath(appRelativePath);
bool exists = !String.IsNullOrEmpty(fsPath) && File.Exists(fsPath);
// try to search the library for any paths that have no root or app root (~/)
if (!exists && isFileRelativePath)
{
path = PathToLibraryFile(fileName);
} else {
path = appRelativePath;
}
if (path == null && !IgnoreErrors)
{
return false;
}
else {
return true;
}
}
/// <summary>
/// Searches the LibraryPath for a match for this file.
/// </summary>
///
/// <remarks>
/// TODO: Optimize this to cache information about which files are in which paths so we don't
/// have to look up every time. (Or is this worth it, since the overall bundles are cached?)
/// </remarks>
///
/// <param name="fileName">
/// Filename of the file.
/// </param>
///
/// <returns>
/// The found dependency.
/// </returns>
private string PathToLibraryFile(string fileName)
{
string pattern = null;
if (Patterns.NonLiteralFilenames.IsMatch(fileName))
{
pattern = Regex.Escape(fileName)
.Replace("\\{version}", Patterns.FileVersionRegex);
}
foreach (var libPath in ScriptEnvironment.LibraryPath.ToList())
{
string matchingFile = null;
string dir = ScriptEnvironment.MapPath(libPath);
if (!Directory.Exists(dir))
{
ScriptEnvironment.LibraryPath.Remove(libPath);
continue;
}
// check if this is a special pattern
if (pattern!=null)
{
matchingFile = GetBestMatchingFile(dir, pattern);
}
else
{
string path = Path.Combine(dir, fileName);
if (!ScriptEnvironment.IsValidFileName(path))
{
path += ".js";
}
if (File.Exists(path))
{
matchingFile = fileName;
}
}
if (matchingFile != null)
{
return (libPath + matchingFile).Replace("//", "/");
}
}
return null;
}
/// <summary>
/// Gets best matching file given a path and a regex.
/// </summary>
///
/// <param name="path">
/// Full pathname to search
/// </param>
/// <param name="regexFilePattern">
/// A pattern specifying the regular expression pattern to match against files.
/// </param>
///
/// <returns>
/// The best matching file, or null if none matches.
/// </returns>
private string GetBestMatchingFile(string path, string regexFilePattern)
{
var files = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly);
Regex pattern = new Regex(regexFilePattern);
List<string> matches = new List<string>();
foreach (var fullFilePath in files)
{
var file = fullFilePath.AfterLast("\\");
if (pattern.IsMatch(file))
{
matches.Add(file);
}
}
if (matches.Count > 0)
{
return matches.OrderByDescending(item => item, StringComparer.CurrentCultureIgnoreCase).First();
}
else
{
return null;
}
}
/// <summary>
/// The file is a relative path - is not rooted and is not ~/ rooted to the app.
/// </summary>
///
/// <param name="file">
/// The file.
/// </param>
///
/// <returns>
/// true if relative path, false if not.
/// </returns>
private bool IsFileRelativePath(string file)
{
return !file.StartsWith("/") && !file.StartsWith("~/");
}
#endregion
#region ICollection methods
/// <summary>
/// Adds a script path.
/// </summary>
///
/// <param name="item">
/// The item to add.
/// </param>
public void Add(ScriptRef item)
{
Scripts.Add(item);
}
/// <summary>
/// Clears this object to its blank/initial state.
/// </summary>
public void Clear()
{
Scripts.Clear();
}
/// <summary>
/// Test whether the item is present in the collection
/// </summary>
///
/// <param name="item">
/// The ScriptRef to test for containment.
/// </param>
///
/// <returns>
/// true if the object is in this collection, false if not.
/// </returns>
public bool Contains(ScriptRef item)
{
return Scripts.Contains(item);
}
/// <summary>
/// Copies the collection to an array
/// </summary>
///
/// <param name="array">
/// The array.
/// </param>
/// <param name="arrayIndex">
/// Zero-based index of the array.
/// </param>
public void CopyTo(ScriptRef[] array, int arrayIndex)
{
Scripts.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of items in the ScriptCollection
/// </summary>
public int Count
{
get { return Scripts.Count; }
}
/// <summary>
/// Gets a value indicating whether this object is read only; a ScriptCollection is never read
/// only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the item from the script collection
/// </summary>
///
/// <param name="item">
/// The item to remove.
/// </param>
///
/// <returns>
/// true if the item was removed, false if it didn't exist
/// </returns>
public bool Remove(ScriptRef item)
{
return Scripts.Remove(item);
}
/// <summary>
/// Gets the enumerator.
/// </summary>
///
/// <returns>
/// The enumerator.
/// </returns>
public IEnumerator<ScriptRef> GetEnumerator()
{
return Scripts.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}