summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.BuildTasks/JsPack.cs
blob: a6a5b279bc2d220412ca6662572533208fadbb38 (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
//-----------------------------------------------------------------------
// <copyright file="JsPack.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOpenAuth.BuildTasks {
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Linq;
	using System.Text;
	using Microsoft.Build.Framework;
	using Microsoft.Build.Utilities;

	/// <summary>
	/// Compresses .js files.
	/// </summary>
	public class JsPack : Task {
		/// <summary>
		/// The Javascript packer to use.
		/// </summary>
		private Dean.Edwards.ECMAScriptPacker packer = new Dean.Edwards.ECMAScriptPacker();

		/// <summary>
		/// Gets or sets the set of javascript files to compress.
		/// </summary>
		/// <value>The inputs.</value>
		[Required]
		public ITaskItem[] Inputs { get; set; }

		/// <summary>
		/// Gets or sets the paths where the packed javascript files should be saved.
		/// </summary>
		/// <value>The outputs.</value>
		[Required]
		public ITaskItem[] Outputs { get; set; }

		/// <summary>
		/// Executes this instance.
		/// </summary>
		/// <returns>A value indicating whether the packing was successful.</returns>
		public override bool Execute() {
			if (this.Inputs.Length != this.Outputs.Length) {
				Log.LogError("{0} inputs and {1} outputs given.", this.Inputs.Length, this.Outputs.Length);
				return false;
			}

			for (int i = 0; i < this.Inputs.Length; i++) {
				if (!File.Exists(this.Outputs[i].ItemSpec) || File.GetLastWriteTime(this.Outputs[i].ItemSpec) < File.GetLastWriteTime(this.Inputs[i].ItemSpec)) {
					Log.LogMessage(MessageImportance.Normal, TaskStrings.PackingJsFile, this.Inputs[i].ItemSpec, this.Outputs[i].ItemSpec);
					string input = File.ReadAllText(this.Inputs[i].ItemSpec);
					string output = this.packer.Pack(input);
					if (!Directory.Exists(Path.GetDirectoryName(this.Outputs[i].ItemSpec))) {
						Directory.CreateDirectory(Path.GetDirectoryName(this.Outputs[i].ItemSpec));
					}

					File.WriteAllText(this.Outputs[i].ItemSpec, output, Encoding.UTF8);
				} else {
					Log.LogMessage(MessageImportance.Low, TaskStrings.SkipPackingJsFile, this.Inputs[i].ItemSpec);
				}
			}

			return true;
		}
	}
}