summaryrefslogtreecommitdiffstats
path: root/tools/Sandcastle/Source/XslTransform/XslTransform.cs
blob: 6b6d76c8f3954deef4ef48f8a5f7724c93d47a5b (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
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
// Copyright © Microsoft Corporation.
// This source file is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.Ddue.Tools.CommandLine;


namespace Microsoft.Ddue.Tools
{
    public class XslTransformer
    {
        public static int Main(string[] args)
        {
            // specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new ListOption("xsl", "Sepcify transform files.", "xsltPath"));
            options.Add(new ListOption("arg", "Sepcify arguments.", "name=value"));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new SwitchOption("w", "Do not ignore insignificant whitespace. By default insignificant whitespace is ignored."));

            ConsoleApplication.WriteBanner();

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("XslTransformer xsl_file [xml_file] [options]");
                options.WriteOptionSummary(Console.Out);
                return (0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return (1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("Specify one input XML input file.");
                return (1);
            }

            if (!results.Options["xsl"].IsPresent)
            {
                Console.WriteLine("Specify at least one XSL transform file.");
                return (1);
            }

            // set whitespace setting
            bool ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles = (string[])results.Options["xsl"].Value;
            XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length];
            for (int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]);
                transforms[i] = new XslCompiledTransform();
                XsltSettings transformSettings = new XsltSettings(true, true);
                try
                {
                    transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver());
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
                catch (XsltException e)
                {
                    if (e.InnerException != null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.InnerException.Message));
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.Message));
                    }
                    return (1);
                }
                catch (XmlException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' is not well-formed. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
            }

            // Compose the arguments
            XsltArgumentList arguments = new XsltArgumentList();
            if (results.Options["arg"].IsPresent)
            {
                string[] nameValueStrings = (string[])results.Options["arg"].Value;
                foreach (string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');
                    if (nameValuePair.Length != 2) continue;
                    arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]);
                }
            }

            string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]);

            // prepare the reader
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = ignoreWhitespace;

            // Do each transform
            for (int i = 0; i < transforms.Length; i++)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Applying XSL transformation '{0}'.", transformFiles[i]));

                // get the transform
                XslCompiledTransform transform = transforms[i];

                // figure out where to put the output
                string output;
                if (i < (transforms.Length - 1))
                {
                    try
                    {
                        output = Path.GetTempFileName();
                        File.SetAttributes(output, FileAttributes.Temporary);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create a temporary file. The error message is: {0}", e.Message));
                        return (1);
                    }
                }
                else
                {
                    if (results.Options["out"].IsPresent)
                    {
                        output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value);
                    }
                    else
                    {
                        output = null;
                    }
                }

                // create a reader
                Stream readStream;
                try
                {
                    readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return (1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return (1);
                }

                using (XmlReader reader = XmlReader.Create(readStream, readerSettings))
                {
                    // create a writer
                    Stream outputStream;
                    if (output == null)
                    {
                        outputStream = Console.OpenStandardOutput();
                    }
                    else
                    {
                        try
                        {
                            outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Delete);
                        }
                        catch (IOException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return (1);
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return (1);
                        }
                    }

                    using (XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings))
                    {
                        try
                        {
                            // do the deed
                            transform.Transform(reader, arguments, writer);
                        }
                        catch (XsltException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured during the transformation. The error message is: {0}",
                                (e.InnerException == null) ? e.Message : e.InnerException.Message));
                            return (1);
                        }
                        catch (XmlException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' is not well-formed. The error is: {1}", input, e.Message));
                            return (1);
                        }
                    }
                }

                // if the last input was a temp file, delete it
                if (i > 0)
                {
                    // Console.WriteLine("deleting {0}", input);
                    try
                    {
                        File.Delete(input);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, String.Format("The temporary file '{0}' could not be deleted. The error message is: {1}", input, e.Message));
                    }
                }

                // the last output file is the next input file
                input = output;

            }

            return (0);
        }
    }

    internal class TransformInfo
    {
        public TransformInfo(string file)
        {
            this.file = file;
            transform.Load(file, settings, resolver);
        }

        private string file;

        private XslCompiledTransform transform = new XslCompiledTransform();

        public string File
        {
            get
            {
                return (file);
            }
        }

        public XslCompiledTransform Transform
        {
            get
            {
                return (transform);
            }
        }

        private static XsltSettings settings = new XsltSettings(true, true);

        private static XmlUrlResolver resolver = new XmlUrlResolver();
    }
}