forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilePreProcessor.cs
More file actions
78 lines (64 loc) · 2.5 KB
/
FilePreProcessor.cs
File metadata and controls
78 lines (64 loc) · 2.5 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
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
namespace ScriptCs
{
public class FilePreProcessor : IFilePreProcessor
{
private const string LoadString = "#load ";
private const string UsingString = "using ";
private readonly IFileSystem _fileSystem;
[ImportingConstructor]
public FilePreProcessor(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
public string ProcessFile(string path)
{
var entryFile = _fileSystem.ReadFileLines(path);
var parsed = ParseFile(entryFile);
var result = string.Join(_fileSystem.NewLine, parsed.Item1);
result += _fileSystem.NewLine + parsed.Item2;
return result;
}
private Tuple<List<string>, string> ParseFile(IEnumerable<string> file)
{
var usings = new List<string>();
var fileList = file.ToList();
for (var i = 0; i < fileList.Count; i++)
{
var line = fileList[i];
if (IsUsingLine(line))
{
usings.Add(line);
}
if (IsLoadLine(line))
{
var filepath = line.Trim(' ').Replace(LoadString, "").Replace("\"", "").Replace(";","");
var filecontent = _fileSystem.IsPathRooted(filepath)
? _fileSystem.ReadFileLines(filepath)
: _fileSystem.ReadFileLines(_fileSystem.CurrentDirectory + @"\" + filepath);
if (filecontent != null)
{
var parsed = ParseFile(filecontent);
fileList[i] = parsed.Item2;
usings.AddRange(parsed.Item1);
}
}
}
var result = string.Join(_fileSystem.NewLine, fileList.Where(line => !IsUsingLine(line)));
var tuple = new Tuple<List<string>, string>(usings.Distinct().ToList(), result);
return tuple;
}
private static bool IsUsingLine(string line)
{
return line.TrimStart(' ').StartsWith(UsingString) && !line.Contains("{") && line.Contains(";");
}
private static bool IsLoadLine(string line)
{
return line.TrimStart(' ').StartsWith(LoadString);
}
}
}