2009-04-03 Andrés G. Aragoneses <aaragoneses@novell.com>
[mono.git] / mcs / tools / mconfig / Mono.MonoConfig / Helpers.cs
1 //
2 // Authors:
3 //   Marek Habersack (mhabersack@novell.com)
4 //
5 // (C) 2007 Novell, Inc
6 //
7
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.ComponentModel;
31 using System.Text;
32 using System.Xml;
33 using System.Xml.XPath;
34
35 namespace Mono.MonoConfig
36 {
37         public static class Helpers
38         {
39                 public const string FakeRootName = "F_a_K_e_R_o_O_t_M_o_N_o_C_o_N_f_I_g_N_o_D_e";
40                 
41                 public static EnumType ConvertEnum <EnumType> (string value, string attrName)
42                 {
43                         try {
44                                 EnumConverter cvt = new EnumConverter (typeof (EnumType));
45                                 return (EnumType) cvt.ConvertFromInvariantString (value);
46                         } catch (Exception) {
47                                 throw new ApplicationException (
48                                         String.Format ("Failed to parse the '{0}' attribute '{1}'", attrName, value));
49                         }
50                 }
51
52                 public static string BreakLongLine (string line, string indent, int maxLineWidth)
53                 {
54                         StringBuilder sb = new StringBuilder ();
55
56                         int lineLen = line.Length;
57                         int segments = lineLen / maxLineWidth;
58                         int segmentStart = 0;
59                         int segmentLen = maxLineWidth - 1;
60                         int idx;
61
62                         while (segments-- >= 0) {
63                                 idx = line.LastIndexOf (' ', segmentStart + segmentLen);
64                                 if (idx > 0)
65                                         segmentLen = idx - segmentStart;
66                                 else
67                                         idx = segmentLen - 1;
68
69                                 sb.AppendFormat ("{0}{1}\n", indent, line.Substring (segmentStart, segmentLen));
70                                 segmentStart = idx + 1;
71                                 if (lineLen - segmentStart > maxLineWidth)
72                                         segmentLen = maxLineWidth;
73                                 else
74                                         segmentLen = lineLen - segmentStart - 1;
75                         }
76
77                         return sb.ToString ();
78                 }
79                 
80                 public static string GetRequiredNonEmptyAttribute (XPathNavigator node, string name)
81                 {
82                         string val = GetOptionalAttribute (node, name);
83                         
84                         if (String.IsNullOrEmpty (val))
85                                 ThrowMissingRequiredAttribute (node, name);
86                         return val;
87                 }
88                 
89                 public static string GetOptionalAttribute (XPathNavigator node, string name)
90                 {
91                         return node.GetAttribute (name, String.Empty);
92                 }
93                 
94                 static void ThrowMissingRequiredAttribute (XPathNavigator node, string name)
95                 {
96                         throw new ApplicationException (String.Format ("Element '{0}' is missing required attribute '{1}'",
97                                                                        node.LocalName, name));
98                 }
99
100                 public static void BuildSectionTree (XPathNodeIterator iter, Section section)
101                 {
102                         XPathNavigator nav, tmp;
103                         XPathNodeIterator children;
104                         List <Section> sectionChildren = section.Children;
105                         Section newSection, curSection;
106                         
107                         while (iter.MoveNext ()) {
108                                 nav = iter.Current;
109                                 children = nav.Select ("section[string-length(@name) > 0]");
110                                 curSection = new Section (nav);
111                                 
112                                 while (children.MoveNext ()) {
113                                         tmp = children.Current;
114                                         newSection = new Section (tmp);
115                                         BuildSectionTree (tmp.Select ("section[string-length(@name) > 0]"), newSection);
116                                         curSection.Children.Add (newSection);
117                                 }
118                                 sectionChildren.Add (curSection);
119                         }
120                 }
121
122                 public static XmlDocument FindDefault (IDefaultContainer[] defaults, string name, FeatureTarget target)
123                 {
124                         int len;
125                         
126                         if (defaults == null || (len = defaults.Length) == 0)
127                                 return null;
128                         
129                         IDefaultContainer cur;
130                         string text = null;
131                         
132                         for (int i = 0; i < len; i++) {
133                                 cur = defaults [i];
134                                 text = cur.FindDefault (name, target);
135                                 if (text != null)
136                                         break;
137                         }
138
139                         if (text == null)
140                                 return null;
141
142                         XmlDocument ret = new XmlDocument ();
143                         ret.LoadXml (String.Format ("<{0}>{1}</{0}>", FakeRootName, text));
144
145                         return ret;
146                 }
147
148                 public static ConfigBlockBlock FindConfigBlock (IConfigBlockContainer[] configBlocks, string name)
149                 {
150                         int len;
151
152                         if (configBlocks == null || (len = configBlocks.Length) == 0)
153                                 return null;
154                         
155                         IConfigBlockContainer cur;
156                         ConfigBlockBlock ret = null;
157
158                         for (int i = 0; i < len; i++) {
159                                 cur = configBlocks [i];
160                                 ret = cur.FindConfigBlock (name);
161                                 if (ret != null)
162                                         break;
163                         }
164
165                         return ret;
166                 }
167
168                 public static void SaveXml (XmlDocument doc, string targetFile)
169                 {
170                         XmlWriterSettings settings = new XmlWriterSettings ();
171                         settings.CloseOutput = true;
172                         settings.CheckCharacters = true;
173                         settings.Indent = true;
174                         settings.Encoding = Encoding.UTF8;
175                         settings.IndentChars = "\t";
176                         settings.NewLineHandling = NewLineHandling.Replace;
177
178                         XmlWriter writer = null;
179                         try {
180                                 writer = XmlWriter.Create (targetFile, settings);
181                                 doc.Save (writer);
182                                 writer.Flush ();
183                         } catch (Exception ex) {
184                                 throw new ApplicationException (
185                                         String.Format ("Failed to write XML file {1}", targetFile), ex);
186                         } finally {
187                                 if (writer != null)
188                                         writer.Close ();
189                         }
190                 }
191         }
192 }