aboutsummaryrefslogtreecommitdiffstats
path: root/qt_template.targets
blob: 5807bc8d64b6db23d3c2a92aea81156b9d240f77 (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
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <!--
      QtTemplateFile: Explicitly replaces specified tokens in a template file and writes the result
      to OutputFileName.

      Tokens: ITaskItem[]
        - ItemSpec = string to be replaced (e.g., "__PACKAGE_VERSION__")
        - Metadata "ReplacementValue" = target value
    -->

  <UsingTask TaskName="QtTemplateFile"
             TaskFactory="RoslynCodeTaskFactory"
             AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
    <ParameterGroup>
      <Template ParameterType="System.String" Required="true" />
      <OutputFileName ParameterType="System.String" Required="true" />
      <Tokens ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="false" />
    </ParameterGroup>
    <Task>
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Using Namespace="System.Collections.Generic" />
      <Using Namespace="Microsoft.Build.Framework" />
      <Code Type="Fragment" Language="cs"><![CDATA[

        const string MetadataReplacementValue = "ReplacementValue";
        try {
            if (File.Exists(Template)) {
                string content = File.ReadAllText(Template);

                if (Tokens != null) {
                    foreach (ITaskItem taskItem in Tokens) {
                        var token = taskItem.ItemSpec;
                        if (string.IsNullOrEmpty(token))
                            continue;
                        content = content.Replace(token,
                            taskItem.GetMetadata(MetadataReplacementValue) ?? "");
                    }
                }

                var dir = Path.GetDirectoryName(OutputFileName);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                File.WriteAllText(OutputFileName, content);
                Log.LogMessage(MessageImportance.Low,
                    "Template '{0}' processed and written to '{1}'.", Template, OutputFileName);
            } else {
                Log.LogError("Template file '{0}' does not exist.", Template);
            }
        } catch (System.Exception ex) {
            Log.LogErrorFromException(ex, true);
        }

      ]]></Code>
    </Task>
  </UsingTask>

</Project>