summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.BuildTasks/HardLinkCopy.cs
blob: eb6e7c5bdd6ff8fb8ddd1d7f76f6dcd1702bc542 (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
//-----------------------------------------------------------------------
// <copyright file="HardLinkCopy.cs" company="Outercurve Foundation">
//     Copyright (c) Outercurve Foundation. 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;

	public class HardLinkCopy : Task {
		[Required]
		public ITaskItem[] SourceFiles { get; set; }

		[Required]
		public ITaskItem[] DestinationFiles { get; set; }

		/// <summary>
		/// Executes this instance.
		/// </summary>
		public override bool Execute() {
			if (this.SourceFiles.Length != this.DestinationFiles.Length) {
				this.Log.LogError("SourceFiles has {0} elements and DestinationFiles has {1} elements.", this.SourceFiles.Length, this.DestinationFiles.Length);
				return false;
			}

			for (int i = 0; i < this.SourceFiles.Length; i++) {
				bool hardLink;
				bool.TryParse(this.DestinationFiles[i].GetMetadata("HardLink"), out hardLink);
				string sourceFile = this.SourceFiles[i].ItemSpec;
				string destinationFile = this.DestinationFiles[i].ItemSpec;
				this.Log.LogMessage(
					MessageImportance.Low,
					"Copying {0} -> {1}{2}.",
					sourceFile,
					destinationFile,
					hardLink ? " as hard link" : string.Empty);

				if (!Directory.Exists(Path.GetDirectoryName(destinationFile))) {
					Directory.CreateDirectory(Path.GetDirectoryName(destinationFile));
				}

				if (hardLink) {
					if (File.Exists(destinationFile)) {
						File.Delete(destinationFile);
					}
					NativeMethods.CreateHardLink(sourceFile, destinationFile);
				} else {
					File.Copy(sourceFile, destinationFile, true);
				}
			}

			return !this.Log.HasLoggedErrors;
		}
	}
}