Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TemplateGenerator.cs « Mono.TextTemplating « Mono.TextTemplating « TextTemplating « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3ca28d88c24905561743d75f8f0bee7d6ac5cf6a (plain)
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
// 
// TemplatingHost.cs
//  
// Author:
//       Michael Hutchinson <mhutchinson@novell.com>
// 
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TextTemplating;

namespace Mono.TextTemplating
{
	public class TemplateGenerator : MarshalByRefObject, ITextTemplatingEngineHost
	{
		//re-usable
		TemplatingEngine engine;
		
		//per-run variables
		string inputFile, outputFile;
		Encoding encoding;
		
		//host fields
		readonly CompilerErrorCollection errors = new CompilerErrorCollection ();
		readonly List<string> refs = new List<string> ();
		readonly List<string> imports = new List<string> ();
		readonly List<string> includePaths = new List<string> ();
		readonly List<string> referencePaths = new List<string> ();
		
		//host properties for consumers to access
		public CompilerErrorCollection Errors { get { return errors; } }
		public List<string> Refs { get { return refs; } }
		public List<string> Imports { get { return imports; } }
		public List<string> IncludePaths { get { return includePaths; } }
		public List<string> ReferencePaths { get { return referencePaths; } }
		public string OutputFile { get { return outputFile; } }
		public bool UseRelativeLinePragmas { get; set; }
		
		public TemplateGenerator ()
		{
			Refs.Add (typeof (TextTransformation).Assembly.Location);
			Refs.Add (typeof(Uri).Assembly.Location);
			Imports.Add ("System");
		}
		
		public CompiledTemplate CompileTemplate (string content)
		{
			if (String.IsNullOrEmpty (content))
				throw new ArgumentNullException ("content");

			errors.Clear ();
			encoding = Encoding.UTF8;
			
			return Engine.CompileTemplate (content, this);
		}
		
		protected TemplatingEngine Engine {
			get {
				if (engine == null)
					engine = new TemplatingEngine ();
				return engine;
			}
		}
		
		public bool ProcessTemplate (string inputFile, string outputFile)
		{
			if (String.IsNullOrEmpty (inputFile))
				throw new ArgumentNullException ("inputFile");
			if (String.IsNullOrEmpty (outputFile))
				throw new ArgumentNullException ("outputFile");
			
			string content;
			try {
				content = File.ReadAllText (inputFile);
			} catch (IOException ex) {
				errors.Clear ();
				AddError ("Could not read input file '" + inputFile + "':\n" + ex);
				return false;
			}
			
			string output;
			ProcessTemplate (inputFile, content, ref outputFile, out output);
			
			try {
				if (!errors.HasErrors)
					File.WriteAllText (outputFile, output, encoding);
			} catch (IOException ex) {
				AddError ("Could not write output file '" + outputFile + "':\n" + ex);
			}
			
			return !errors.HasErrors;
		}
		
		public bool ProcessTemplate (string inputFileName, string inputContent, ref string outputFileName, out string outputContent)
		{
			errors.Clear ();
			encoding = Encoding.UTF8;
			
			outputFile = outputFileName;
			inputFile = inputFileName;
			outputContent = Engine.ProcessTemplate (inputContent, this);
			outputFileName = outputFile;
			
			return !errors.HasErrors;
		}
		
		public bool PreprocessTemplate (string inputFile, string className, string classNamespace, 
			string outputFile, Encoding encoding, out string language, out string[] references)
		{
			language = null;
			references = null;

			if (string.IsNullOrEmpty (inputFile))
				throw new ArgumentNullException ("inputFile");
			if (string.IsNullOrEmpty (outputFile))
				throw new ArgumentNullException ("outputFile");
			
			string content;
			try {
				content = File.ReadAllText (inputFile);
			} catch (IOException ex) {
				errors.Clear ();
				AddError ("Could not read input file '" + inputFile + "':\n" + ex);
				return false;
			}
			
			string output;
			PreprocessTemplate (inputFile, className, classNamespace, content, out language, out references, out output);
			
			try {
				if (!errors.HasErrors)
					File.WriteAllText (outputFile, output, encoding);
			} catch (IOException ex) {
				AddError ("Could not write output file '" + outputFile + "':\n" + ex);
			}
			
			return !errors.HasErrors;
		}
		
		public bool PreprocessTemplate (string inputFileName, string className, string classNamespace, string inputContent, 
			out string language, out string[] references, out string outputContent)
		{
			errors.Clear ();
			encoding = Encoding.UTF8;
			
			inputFile = inputFileName;
			outputContent = Engine.PreprocessTemplate (inputContent, this, className, classNamespace, out language, out references);
			
			return !errors.HasErrors;
		}
		
		CompilerError AddError (string error)
		{
			var err = new CompilerError ();
			err.ErrorText = error;
			Errors.Add (err);
			return err;
		}
		
		#region Virtual members
		
		public virtual object GetHostOption (string optionName)
		{
			switch (optionName) {
			case "UseRelativeLinePragmas":
				return UseRelativeLinePragmas;
			}
			return null;
		}
		
		public virtual AppDomain ProvideTemplatingAppDomain (string content)
		{
			return null;
		}
		
		protected virtual string ResolveAssemblyReference (string assemblyReference)
		{
			if (System.IO.Path.IsPathRooted (assemblyReference))
 				return assemblyReference;
 			foreach (string referencePath in ReferencePaths) {
 				var path = System.IO.Path.Combine (referencePath, assemblyReference);
 				if (System.IO.File.Exists (path))
 					return path;
 			}
			return assemblyReference;
		}
		
		protected virtual string ResolveParameterValue (string directiveId, string processorName, string parameterName)
		{
			var key = new ParameterKey (processorName, directiveId, parameterName);
			string value;
			if (parameters.TryGetValue (key, out value))
				return value;
			if (processorName != null || directiveId != null)
				return ResolveParameterValue (null, null, parameterName);
			return null;
		}
		
		protected virtual Type ResolveDirectiveProcessor (string processorName)
		{
			KeyValuePair<string,string> value;
			if (!directiveProcessors.TryGetValue (processorName, out value))
				throw new Exception (string.Format ("No directive processor registered as '{0}'", processorName));
			var asmPath = ResolveAssemblyReference (value.Value);
			if (asmPath == null)
				throw new Exception (string.Format ("Could not resolve assembly '{0}' for directive processor '{1}'", value.Value, processorName));
			var asm = System.Reflection.Assembly.LoadFrom (asmPath);
			return asm.GetType (value.Key, true);
		}
		
		protected virtual string ResolvePath (string path)
		{
			path = Environment.ExpandEnvironmentVariables (path);
			if (Path.IsPathRooted (path))
				return path;
			var dir = Path.GetDirectoryName (inputFile);
			var test = Path.Combine (dir, path);
			if (File.Exists (test))
				return test;
			return null;
		}
		
		#endregion
		
		readonly Dictionary<ParameterKey,string> parameters = new Dictionary<ParameterKey, string> ();
		readonly Dictionary<string,KeyValuePair<string,string>> directiveProcessors = new Dictionary<string, KeyValuePair<string,string>> ();
		
		public void AddDirectiveProcessor (string name, string klass, string assembly)
		{
			directiveProcessors.Add (name, new KeyValuePair<string,string> (klass,assembly));
		}
		
		public void AddParameter (string processorName, string directiveName, string parameterName, string value)
		{
			parameters.Add (new ParameterKey (processorName, directiveName, parameterName), value);
		}
		
		protected virtual bool LoadIncludeText (string requestFileName, out string content, out string location)
		{
			content = "";
			location = ResolvePath (requestFileName);
			
			if (location == null) {
				foreach (string path in includePaths) {
					string f = Path.Combine (path, requestFileName);
					if (File.Exists (f)) {
						location = f;
						break;
					}
				}
			}
			
			if (location == null)
				return false;
			
			try {
				content = File.ReadAllText (location);
				return true;
			} catch (IOException ex) {
				AddError ("Could not read included file '" + location + "':\n" + ex);
			}
			return false;
		}
		
		#region Explicit ITextTemplatingEngineHost implementation
		
		bool ITextTemplatingEngineHost.LoadIncludeText (string requestFileName, out string content, out string location)
		{
			return LoadIncludeText (requestFileName, out content, out location);
		}
		
		void ITextTemplatingEngineHost.LogErrors (CompilerErrorCollection errors)
		{
			this.errors.AddRange (errors);
		}
		
		string ITextTemplatingEngineHost.ResolveAssemblyReference (string assemblyReference)
		{
			return ResolveAssemblyReference (assemblyReference);
		}
		
		string ITextTemplatingEngineHost.ResolveParameterValue (string directiveId, string processorName, string parameterName)
		{
			return ResolveParameterValue (directiveId, processorName, parameterName);
		}
		
		Type ITextTemplatingEngineHost.ResolveDirectiveProcessor (string processorName)
		{
			return ResolveDirectiveProcessor (processorName);
		}
		
		string ITextTemplatingEngineHost.ResolvePath (string path)
		{
			return ResolvePath (path);
		}
		
		void ITextTemplatingEngineHost.SetFileExtension (string extension)
		{
			extension = extension.TrimStart ('.');
			if (Path.HasExtension (outputFile)) {
				outputFile = Path.ChangeExtension (outputFile, extension);
			} else {
				outputFile = outputFile + "." + extension;
			}
		}
		
		void ITextTemplatingEngineHost.SetOutputEncoding (Encoding encoding, bool fromOutputDirective)
		{
			this.encoding = encoding;
		}
		
		IList<string> ITextTemplatingEngineHost.StandardAssemblyReferences {
			get { return refs; }
		}
		
		IList<string> ITextTemplatingEngineHost.StandardImports {
			get { return imports; }
		}
		
		string ITextTemplatingEngineHost.TemplateFile {
			get { return inputFile; }
		}
		
		#endregion
		
		struct ParameterKey : IEquatable<ParameterKey>
		{
			public ParameterKey (string processorName, string directiveName, string parameterName)
			{
				this.processorName = processorName ?? "";
				this.directiveName = directiveName ?? "";
				this.parameterName = parameterName ?? "";
				unchecked {
					hashCode = this.processorName.GetHashCode ()
						^ this.directiveName.GetHashCode ()
						^ this.parameterName.GetHashCode ();
				}
			}
			
			string processorName, directiveName, parameterName;
			readonly int hashCode;
			
			public override bool Equals (object obj)
			{
				return obj is ParameterKey && Equals ((ParameterKey)obj);
			}
			
			public bool Equals (ParameterKey other)
			{
				return processorName == other.processorName && directiveName == other.directiveName && parameterName == other.parameterName;
			}
			
			public override int GetHashCode ()
			{
				return hashCode;
			}
		}

		/// <summary>
		/// If non-null, the template's Host property will be the full type of this host.
		/// </summary>
		public virtual Type SpecificHostType { get { return null; } }

		/// <summary>
		/// Gets any additional directive processors to be included in the processing run.
		/// </summary>
		public virtual IEnumerable<IDirectiveProcessor> GetAdditionalDirectiveProcessors ()
		{
			yield break;
		}
	}
}