-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCalcProtoOutputs.cs
74 lines (68 loc) · 2.54 KB
/
CalcProtoOutputs.cs
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
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System;
using System.Collections;
namespace MsBuild.ProtocolBuffers
{
public class CalcProtoOutputs : Task
{
[Required]
public ITaskItem[] Inputs { get; set; }
[Output]
public ITaskItem[] InputsWithOutput { get; set; }
public override bool Execute()
{
InputsWithOutput = Inputs.Select(inp => WithOutput(inp)).ToArray();
return true;
}
public static ITaskItem WithOutput(ITaskItem input)
{
var withOutput = new TaskItem(input);
var outDir = input.GetMetadata("RelativeDir");
var inputBase = input.GetMetadata("InputBase");
if (!string.IsNullOrEmpty(inputBase))
outDir = Relative(outDir, inputBase);
var outputBase = input.GetMetadata("OutputBase");
if (outputBase != null)
outDir = Path.Combine(outputBase, outDir);
var outName = Path.GetFileNameWithoutExtension(input.ItemSpec).SnakeToPascalCase() + Path.GetExtension(input.ItemSpec) + ".cs";
withOutput.SetMetadata("OutputSpec", Path.Combine(outDir, outName));
return withOutput;
}
public static string Relative(string inputPath, string contextPath)
{
var input = Regex.Split(inputPath, @"[/\\]+").Where(s => s != "").ToArray();
var context = Regex.Split(contextPath, @"[/\\]+").Where(s => s != "").ToArray();
while (input.Length > 0 && context.Length > 0 && input[0] == context[0])
{
input = Shift(input);
context = Shift(context);
}
while (context.Length > 0)
{
context = Shift(context);
input = Unshift(input, "..");
}
return string.Join("/", input);
}
public static string[] Shift(string[] input)
{
var shifted = new string[input.Length - 1];
Array.Copy(input, 1, shifted, 0, shifted.Length);
return shifted;
}
public static string[] Unshift(string[] input, string item)
{
var unshifted = new string[input.Length + 1];
unshifted[0] = item;
Array.Copy(input, 0, unshifted, 1, input.Length);
return unshifted;
}
}
}