File: AppResourceFilesCompiler.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (607 lines) | stat: -rw-r--r-- 18,154 bytes parent folder | download | duplicates (2)
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
//
// System.Web.Compilation.AppResourceFilesCompiler: A compiler for application resource files
//
// Authors:
//   Marek Habersack (grendello@gmail.com)
//
// (C) 2006 Marek Habersack
//

//
// 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.
//
#if NET_2_0
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Web.Util;

using Microsoft.CSharp;
//using Microsoft.VisualBasic;
//using Microsoft.JScript;

namespace System.Web.Compilation
{
	class LengthComparer<T>: Comparer<T>
	{
		private int CompareStrings (string a, string b)
		{
			if (a == null || b == null)
				return 0;
			return (int)b.Length - (int)a.Length;
		}

		public override int Compare (T _a, T _b) 
		{
			string a = null, b = null;
			if (_a is string && _b is string) {
				a = _a as string;
				b = _b as string;
			} else if (_a is List<string> && _b is List<string>) {
				List<string> tmp = _a as List<string>;
				a = tmp [0];
				tmp = _b as List<string>;
				b = tmp [0];
			} else
				return 0;
			return CompareStrings (a, b);
		}
	}
	
	internal class AppResourceFilesCompiler
	{
		public enum FcCodeGenerator
		{
			Typed,
			CSharp,
			VBasic,
			JScript
		};
		
		protected string []	  filePaths = null;
		protected FcCodeGenerator codeGenerator = FcCodeGenerator.CSharp;
		protected string          codeGenType = null;
		protected List<string> [] resxFiles = null;
		protected List<string>    resourceFiles = null;
		protected Dictionary<string,bool?> assemblies = null;
		protected string          tempdirectory = null;
		protected Random          rnd = null;
		
		public FcCodeGenerator CodeGen {
			get { return codeGenerator; }
			set { codeGenerator = value; }
		}

		virtual public string TempDir {
			get {
				if (tempdirectory != null)
					return tempdirectory;
				return (tempdirectory = GenTempDir (Path.GetTempPath ()));
			}
			set { tempdirectory = value; }
		}
		
		public string Source {
			get { return FilesToString (); }
		}

		public CodeCompileUnit CompileUnit {
			get { return FilesToDom (); }
		}

		protected AppResourceFilesCompiler ()
		{
			filePaths = new string [] {};
		}
		
		public AppResourceFilesCompiler (string filePath)
		{
			DoInit (filePath, FcCodeGenerator.CSharp);
		}
		
		public AppResourceFilesCompiler (string filePath, FcCodeGenerator cg)
		{
			DoInit (filePath, cg);
		}

		public AppResourceFilesCompiler (string[] filePaths)
		{
			DoInit (filePaths, FcCodeGenerator.CSharp);
		}
		
		public AppResourceFilesCompiler (string[] filePaths, FcCodeGenerator cg)
		{
			DoInit (filePaths, cg);
		}

		public AppResourceFilesCompiler (string filePath, string genType)
		{
			DoInit (filePath, genType);
		}

		public AppResourceFilesCompiler (string[] filePaths, string genType)
		{
			DoInit (filePaths, genType);
		}

		private void DoInit (string filePath, string genType)
		{
			this.codeGenType = genType;
			DoInit (filePath, FcCodeGenerator.Typed);
		}

		private void DoInit (string [] filePaths, string genType)
		{
			this.codeGenType = genType;
			DoInit (filePaths, FcCodeGenerator.Typed);
		}
		
		private void DoInit (string filePath, FcCodeGenerator cg)
		{
			this.codeGenerator = cg;
			if (filePath != null)
				this.filePaths = new string [] { filePath };
		}

		private void DoInit (string [] filePaths, FcCodeGenerator cg)
		{
			this.codeGenerator = cg;
			if (filePaths != null)
				this.filePaths = (string [])filePaths.Clone ();
		}

		protected CodeDomProvider GetCodeProvider ()
		{
			switch (codeGenerator) {
			default:
				goto case FcCodeGenerator.CSharp;
					
			case FcCodeGenerator.CSharp:
				return new CSharpCodeProvider ();

//                         case FcCodeGenerator.VBasic:
//                                 return new VBCodeProvider ();

//                         case FcCodeGenerator.JScript:
//                                 return new JScriptCodeProvider ();

			case FcCodeGenerator.Typed:
				return null;
			}
		}
		
		protected string FilesToString ()
		{
			CodeCompileUnit unit = FilesToDom ();
			CodeDomProvider provider = GetCodeProvider ();
			StringWriter writer = new StringWriter ();
			CodeGeneratorOptions opts = new CodeGeneratorOptions ();

			opts.BlankLinesBetweenMembers = false;
			provider.GenerateCodeFromCompileUnit (unit, writer, opts);
			
			string ret = writer.ToString ();
			writer.Close ();
			return ret;
		}
		
		protected CodeCompileUnit FilesToDom ()
		{
			CollectFiles ();
			if (resxFiles == null || resxFiles.Length == 0)
				return null;
			
			string destdir = TempDir;

			string s, resfile;
			resourceFiles = new List<string> (resxFiles.Length);
			CodeCompileUnit ret = new CodeCompileUnit ();
			foreach (List<string> al in resxFiles) {
				if (al == null)
					continue;
				for (int i = 0; i < al.Count; i++) {
					s = al [i];
					if (s == null)
						continue;
					resfile = CompileFile (destdir, s);
					resourceFiles.Add (resfile);				 
					if (i > 0 || resfile == null)
						continue;
					
					// Default file. Generate the class
					DomFromResource (resfile, ret);
				}
			}
			if (assemblies != null)
				foreach (KeyValuePair<string,bool?> de in assemblies)
					ret.ReferencedAssemblies.Add (de.Key);
			
			return ret;
		}

		private void DomFromResource (string resfile, CodeCompileUnit unit)
		{
			string fname, nsname, classname;

			fname = Path.GetFileNameWithoutExtension (resfile);
			nsname = Path.GetFileNameWithoutExtension (fname);
			classname = Path.GetExtension (fname);
			if (classname == null || classname.Length == 0) {
				classname = nsname;
				nsname = "Resources";
			} else {
				nsname = String.Format ("Resources.{0}", nsname);
				classname = classname.Substring(1);
			}		 

			Dictionary<string,bool> imports = new Dictionary<string,bool> ();
			if (assemblies == null)
				assemblies = new Dictionary<string,bool?> ();
			CodeNamespace ns = new CodeNamespace (nsname);
			imports ["System"] = true;
			imports ["System.Globalization"] = true;
			imports ["System.Reflection"] = true;
			imports ["System.Resources"] = true;

			CodeTypeDeclaration cls = new CodeTypeDeclaration (classname);
			cls.IsClass = true;
			cls.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;

			CodeMemberField cmf = new CodeMemberField (typeof(CultureInfo), "culture");
			cmf.InitExpression = new CodePrimitiveExpression (null);
			cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
			cls.Members.Add (cmf);

			cmf = new CodeMemberField (typeof(ResourceManager), "resourceManager");
			cmf.InitExpression = new CodePrimitiveExpression (null);
			cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
			cls.Members.Add (cmf);
			
			// Property: ResourceManager
			CodeMemberProperty cmp = new CodeMemberProperty ();
			cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
			cmp.Name = "ResourceManager";
			cmp.HasGet = true;
			cmp.Type = new CodeTypeReference (typeof(ResourceManager));
			CodePropertyResourceManagerGet (cmp.GetStatements, resfile, classname);
			cls.Members.Add (cmp);

			// Property: Culture
			cmp = new CodeMemberProperty ();
			cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
			cmp.Name = "Culture";
			cmp.HasGet = true;
			cmp.HasSet = true;
			cmp.Type = new CodeTypeReference (typeof(CultureInfo));
			CodePropertyGenericGet (cmp.GetStatements, "culture", classname);
			CodePropertyGenericSet (cmp.SetStatements, "culture", classname);
			cls.Members.Add (cmp);

			// Add the resource properties
			try {
				ResourceReader res = new ResourceReader (resfile);
				foreach (DictionaryEntry de in res) {
					Type type = de.Value.GetType ();

					if (!imports.ContainsKey (type.Namespace))
						imports [type.Namespace] = true;

					string asname = new AssemblyName (type.Assembly.FullName).Name;
					if (!assemblies.ContainsKey (asname))
						assemblies [asname] = true;
					
					cmp = new CodeMemberProperty ();
					cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
					cmp.Name = SanitizeResourceName ((string)de.Key);
					cmp.HasGet = true;
					CodePropertyResourceGet (cmp.GetStatements, (string)de.Key, type, classname);
					cmp.Type = new CodeTypeReference (type);
					cls.Members.Add (cmp);
				}
			} catch (Exception ex) {
			}
			foreach (KeyValuePair<string,bool> de in imports)
				ns.Imports.Add (new CodeNamespaceImport(de.Key));
			
			ns.Types.Add (cls);
			unit.Namespaces.Add (ns);
		}

		private string SanitizeResourceName (string name)
		{
			return name.Replace (' ', '_').Replace ('-', '_').Replace ('.', '_');
		}
		
		private CodeObjectCreateExpression NewResourceManager (string name, string typename)
		{
			CodeExpression resname = new CodePrimitiveExpression (name);
			CodePropertyReferenceExpression asm = new CodePropertyReferenceExpression (
				new CodeTypeOfExpression (new CodeTypeReference (typename)),
				"Assembly");
			
			return new CodeObjectCreateExpression ("System.Resources.ResourceManager",
							       new CodeExpression [] {resname, asm});
		}
		
		private void CodePropertyResourceManagerGet (CodeStatementCollection csc, string resfile, string typename)
		{
			string name = Path.GetFileNameWithoutExtension (resfile);
			CodeStatement st;
			CodeExpression exp;

			exp = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), "resourceManager");
			st = new CodeConditionStatement (
				new CodeBinaryOperatorExpression (
					exp,
					CodeBinaryOperatorType.IdentityInequality,
					new CodePrimitiveExpression (null)),
				new CodeStatement [] { new CodeMethodReturnStatement (exp) });
			csc.Add (st);

			st = new CodeAssignStatement (exp, NewResourceManager (name, typename));
			csc.Add (st);
			csc.Add (new CodeMethodReturnStatement (exp));
		}

		private void CodePropertyResourceGet (CodeStatementCollection csc, string resname, Type restype, string typename)
		{
			CodeStatement st = new CodeVariableDeclarationStatement (
				typeof (ResourceManager),
				"rm",
				new CodePropertyReferenceExpression (
					new CodeTypeReferenceExpression (typename), "ResourceManager"));
			csc.Add (st);

			st = new CodeConditionStatement (
				new CodeBinaryOperatorExpression (
					new CodeVariableReferenceExpression ("rm"),
					CodeBinaryOperatorType.IdentityEquality,
					new CodePrimitiveExpression (null)),
				new CodeStatement [] { new CodeMethodReturnStatement (new CodePrimitiveExpression (null)) });
			csc.Add (st);

			bool gotstr = (restype == typeof (string));
			CodeExpression exp = new CodeMethodInvokeExpression (
				new CodeVariableReferenceExpression ("rm"),
				gotstr ? "GetString" : "GetObject",
				new CodeExpression [] { new CodePrimitiveExpression (resname),
							new CodeFieldReferenceExpression (
								new CodeTypeReferenceExpression (typename), "culture") });
			st = new CodeVariableDeclarationStatement (
				restype,
				"obj",
				gotstr ? exp : new CodeCastExpression (restype, exp));
			csc.Add (st);
			csc.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("obj")));
		}
		
		private void CodePropertyGenericGet (CodeStatementCollection csc, string field, string typename)
		{
			csc.Add(new CodeMethodReturnStatement (
					new CodeFieldReferenceExpression (
						new CodeTypeReferenceExpression (typename), field)));
		}

		private void CodePropertyGenericSet (CodeStatementCollection csc, string field, string typename)
		{
			csc.Add(new CodeAssignStatement (
					new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), field),
					new CodeVariableReferenceExpression ("value")));
		}
		
		private uint CountChars (char c, string s)
		{
			uint ret = 0;
			foreach (char ch in s) {
				if (ch == c)
					ret++;
			}
			return ret;
		}
		
		private void CollectFiles ()
		{
			List<string> files = new List<string> (filePaths);
			List<List<string>> groups = new List<List<string>> ();
			LengthComparer<string> lcString = new LengthComparer<string> ();
			LengthComparer<List<string>> lcList = new LengthComparer<List<string>> ();
			
			files.Sort (lcString);
			Array.Sort (filePaths, lcString);

			string tmp;
			foreach (string s in filePaths) {
				tmp = Path.GetExtension (s);
				if (tmp == null)
					continue;
				tmp = tmp.ToLower ();
				if (tmp != ".resx")
					continue;

				string basename = Path.GetFileNameWithoutExtension (s);
				uint basedots = CountChars ('.', basename);
				uint filedots;
				bool gotdefault = false;

				// If there are any files that start with this baseName, we have a default file
				for (int i = 0; i < files.Count; i++) {
					string s2 = files [i];
					if (s2 == null || s == s2)
						continue;
					tmp = Path.GetFileNameWithoutExtension (s2);
					filedots = CountChars ('.', tmp);

					if (filedots == basedots + 1 && tmp.StartsWith (basename)) {
						gotdefault = true;
						break;
					}
				}
				if (gotdefault) {
					List<string> al = new List<string> ();
					al.Add (s);
					int	idx = files.IndexOf (s);
					if (idx != -1)
						files [idx] = null;
					groups.Add (al);
				}
			}
			groups.Sort (lcList);

			string tmp2;
			// Now find their translated counterparts
			foreach (List<string> al in groups) {
				string s = al [0];
				tmp = Path.GetFileNameWithoutExtension (s);
				for (int i = 0; i < files.Count; i++) {
					s = files [i];
					if (s == null)
						continue;
					tmp2 = Path.GetFileName (s);
					if (tmp2.StartsWith (tmp)) {
						al.Add (s);
						files [i] = null;
					}
				}
			}

			// Anything that's left here might be orphans or lone default files.
			// For those files we check the part following the last dot
			// before the .resx extension and test whether it's a registered
			// culture or not. If it is not a culture, then we have a
			// default file that doesn't have any translations. Otherwise,
			// the file is ignored (it's the same thing MS.NET does)
			CultureInfo ci;
			foreach (string s in files) {
				if (s == null)
					continue;
				
				tmp = Path.GetFileNameWithoutExtension (s);
				tmp = Path.GetExtension (tmp);
				if (tmp == null || tmp.Length == 0)
					continue;
				tmp = tmp.Substring (1);
				try {
					ci = CultureInfo.GetCultureInfo (tmp);
					continue; // Culture found, we reject the file
				} catch {
				}

				// A single default file, create a group
				List<string> al = new List<string> ();
				al.Add (s);
				groups.Add (al);
			}
			groups.Sort (lcList);
			resxFiles = groups.ToArray ();
		}		 

		private IResourceReader GetReader (Stream stream, string path)
		{
			string ext = Path.GetExtension (path);
			if (ext == null)
				throw new Exception ("Unknown resource type.");
			switch (ext.ToLower ()) {
			case ".resx":
				return new ResXResourceReader (stream);

			default:
				throw new Exception ("Unknown resource type.");
			}
		}
		
		private string CompileFile (string destdir, string path)
		{
			string resfile = String.Format ("{1}{0}{2}.resources",
							Path.DirectorySeparatorChar,
							destdir,
							Path.GetFileNameWithoutExtension (path));

			FileStream source = null, dest = null;
			IResourceReader reader = null;
			ResourceWriter writer = null;
			
			try {
				source = new FileStream (path, FileMode.Open, FileAccess.Read);
				dest = new FileStream (resfile, FileMode.Create, FileAccess.Write);
				reader = GetReader (source, path);
				writer = new ResourceWriter (dest);
				foreach (DictionaryEntry de in reader) {
					object val = de.Value;
					if (val is string)
						writer.AddResource ((string)de.Key, (string)val);
					else
						writer.AddResource ((string)de.Key, val);
				}
			} catch (Exception ex) {
				Console.WriteLine ("Resource compiler error: {0}", ex.Message);
				Exception inner = ex.InnerException;
				if (inner != null)
					Console.WriteLine ("Inner exception: {0}", inner.Message);
				return null;
			} finally {
				if (reader != null)
					reader.Close ();
				else if (source != null)
					source.Close ();
				if (writer != null)
					writer.Close ();
				else if (dest != null)
					dest.Close ();
			}
			return resfile;
		}

		object OnCreateRandomFile (string path)
		{
			FileStream f = new FileStream (path, FileMode.CreateNew);
			f.Close ();
			return path;
		}
		
		protected string GenRandomFileName (string basepath)
		{
			return GenRandomFileName (basepath, null);
		}
		
		protected string GenRandomFileName (string basepath, string ext)
		{
			return (string)FileUtils.CreateTemporaryFile (basepath, ext, OnCreateRandomFile);
		}

		object OnCreateRandomDir (string path)
		{
			DirectoryInfo di = Directory.CreateDirectory (path);
			return di.FullName;
		}
		
		protected string GenTempDir (string basepath)
		{
			return (string)FileUtils.CreateTemporaryFile (basepath, OnCreateRandomDir);
		}
	}
}
#endif