Debian Codegraph @

Nasal/io.nas

raw
1 # Reads and returns a complete file as a string
2 var readfile = func(file) {
3 if ((var st = stat(file)) == nil)
4 die("Cannot stat file: " ~ file);
5 var sz = st[7];
6 var buf = bits.buf(sz);
7 read(open(file), buf, sz);
8 return buf;
9 }
10
11 # basename(<path>), dirname(<path>)
12 #
13 # Work like standard Unix commands: basename returns the file name from a given
14 # path, and dirname returns the directory part.
15
16 var basename = func(path) {
17 split("/", string.normpath(path))[-1];
18 };
19
20 var dirname = func(path) {
21 path = string.normpath(path);
22 substr(path, 0, size(path) - size(basename(path)));
23 };
24
25 var is_directory = func(path) {
26 var tmp = stat(path);
27 if (tmp != nil and tmp[11] == "dir") return 1;
28 else return 0;
29 };
30
31 var is_regular_file = func(path) {
32 var tmp = stat(path);
33 if (tmp != nil and tmp[11] == "reg") return 1;
34 else return 0;
35 };
36
37 var exists = func(path) {
38 var tmp = stat(path);
39 return tmp != nil;
40 };
41
42 # <path> the path that should be searched for subdirectories
43 # returns a vector of subdirectory names
44 var subdirectories = func(path) {
45 if (!is_directory(path))
46 return;
47 var list = subvec(directory(path), 2);
48 var subdirs = [];
49 foreach (var entry; list) {
50 if (is_directory(path~"/"~entry)) {
51 append(subdirs, entry);
52 }
53 }
54 return subdirs;
55 }
56
57 # include(<filename>)
58 #
59 # Loads and executes a Nasal file in place. The file is searched for in the
60 # calling script directory and in standard FG directories (in that order).
61 #
62 # Examples:
63 #
64 # io.include("Aircraft/Generic/library.nas");
65 # io.include("my_other_file.nas");
66
67 var include = func(file) {
68
69 file = string.normpath(file);
70 var clr = caller();
71 var (ns, fn, fl) = clr;
72
73 var local_file = dirname(fl) ~ file;
74 var path = (stat(local_file) != nil)? local_file : resolvepath(file);
75
76 if (path == "") die("File not found: ", file);
77
78 var module = "__" ~ path ~ "__";
79 if (contains(ns, module))
80 return;
81
82 var code = call(compile, [readfile(path), path], var err = []);
83 if (size(err)) {
84 if (find("Parse error:", err[0]) < 0)
85 die(err[0]);
86 else
87 die(sprintf("%s\n in included file: %s", err[0], path));
88 }
89
90 ns[module] = "included";
91 call(bind(code, ns, fn), [], nil, ns);
92 }
93
94 # Loads Nasal file into namespace and executes it. The namespace
95 # (module name) is taken from the optional second argument, or
96 # derived from the Nasal file's name.
97 #
98 # Usage: io.load_nasal(<filename> [, <modulename>]);
99 #
100 # Example:
101 #
102 # io.load_nasal(getprop("/sim/fg-root") ~ "/Local/test.nas");
103 # io.load_nasal("/tmp/foo.nas", "test");
104 #
105 var load_nasal = func(file, module = nil) {
106 if (module == nil)
107 module = split(".", split("/", file)[-1])[0];
108
109 logprint(LOG_DEBUG, "loading ", file, " into namespace ", module);
110
111 if (!contains(globals, module))
112 globals[module] = {};
113 elsif (!ishash(globals[module]))
114 die("io.load_nasal(): namespace '" ~ module ~ "' already in use, but not a hash");
115
116 var code = call(func compile(readfile(file), file), nil, var err = []);
117 if (size(err)) {
118 if (substr(err[0], 0, 12) == "Parse error:") { # hack around Nasal feature
119 var e = split(" at line ", err[0]);
120 if (size(e) == 2)
121 err[0] = string.join("", [e[0], "\n at ", file, ", line ", e[1], "\n "]);
122 }
123 for (var i = 1; (var c = caller(i)) != nil; i += 1)
124 err ~= subvec(c, 2, 2);
125 debug.printerror(err);
126 return 0;
127 }
128 call(bind(code, globals), nil, nil, globals[module], err);
129 debug.printerror(err);
130 return !size(err);
131 }
132
133
134 # Load XML file in FlightGear's native <PropertyList> format.
135 # If the second, optional target parameter is set, then the properties
136 # are loaded to this node in the global property tree. Otherwise they
137 # are returned as a separate props.Node tree. Returns the data as a
138 # props.Node on success or nil on error.
139 #
140 # Usage: io.read_properties(<filename> [, <props.Node or property-path>, <quiet>]);
141 #
142 # Examples:
143 #
144 # var target = props.globals.getNode("/sim/model");
145 # io.read_properties("/tmp/foo.xml", target);
146 #
147 # var data = io.read_properties("/tmp/foo.xml", "/sim/model");
148 # var data = io.read_properties("/tmp/foo.xml");
149 #
150 var read_properties = func(path, target = nil, quiet = 0) {
151 var args = props.Node.new({ filename: path });
152 if (target == nil) {
153 var ret = args.getNode("data", 1);
154 } elsif (isa(target, props.Node)) {
155 args.getNode("targetnode", 1).setValue(target.getPath());
156 var ret = target;
157 } else {
158 args.getNode("targetnode", 1).setValue(target);
159 var ret = props.globals.getNode(target, 1);
160 }
161
162 # set the quiet flag if requested
163 if (quiet)
164 args.getNode("quiet", 1).setValue(1);
165
166 return fgcommand("loadxml", args) ? ret : nil;
167 }
168
169 # Load XML file in FlightGear's native <PropertyList> format.
170 # file will be located in the airport-scenery directories according to
171 # ICAO and filename, i,e in Airports/I/C/A/ICAO.filename.xml
172 # If the second, optional target parameter is set, then the properties
173 # are loaded to this node in the global property tree. Otherwise they
174 # are returned as a separate props.Node tree. Returns the data as a
175 # props.Node on success or nil on error.
176 #
177 # Usage: io.read_airport_properties(<icao>, <filename> [, <props.Node or property-path>]);
178 #
179 # Examples:
180 #
181 # var data = io.read_properties("KSFO", "rwyuse");
182 #
183 var read_airport_properties = func(icao, fname, target = nil, quiet = 0) {
184 var args = props.Node.new({ filename: fname, icao:icao });
185 if (target == nil) {
186 var ret = args.getNode("data", 1);
187 } elsif (isa(target, props.Node)) {
188 args.getNode("targetnode", 1).setValue(target.getPath());
189 var ret = target;
190 } else {
191 args.getNode("targetnode", 1).setValue(target);
192 var ret = props.globals.getNode(target, 1);
193 }
194
195 # set the quiet flag if requested
196 if (quiet)
197 args.getNode("quiet", 1).setValue(1);
198
199 return fgcommand("loadxml", args) ? ret : nil;
200 }
201
202 # Write XML file in FlightGear's native <PropertyList> format.
203 # Returns the filename on success or nil on error. If the source
204 # is a props.Node that refers to a node in the main tree, then
205 # the data are directly written from the tree, yielding a more
206 # accurate result. Otherwise the data need to be copied first,
207 # which may slightly change node types (FLOAT becomes DOUBLE etc.)
208 #
209 # Usage: io.write_properties(<filename>, <props.Node or property-path>);
210 #
211 # Examples:
212 #
213 # var data = props.Node.new({ a:1, b:2, c:{ d:3, e:4 } });
214 # io.write_properties("/tmp/foo.xml", data);
215 # io.write_properties("/tmp/foo.xml", "/sim/model");
216 #
217 var write_properties = func(path, prop) {
218 var args = props.Node.new({ filename: path });
219 # default attributes of a new node plus the lowest unused bit
220 var attr = args.getAttribute() + args.getAttribute("last") * 2;
221 props.globals.setAttribute(attr);
222 if (isa(prop, props.Node)) {
223 for (var root = prop; (var p = root.getParent()) != nil;)
224 root = p;
225 if (root.getAttribute() == attr)
226 args.getNode("sourcenode", 1).setValue(prop.getPath());
227 else
228 props.copy(prop, args.getNode("data", 1), 1);
229 } else {
230 args.getNode("sourcenode", 1).setValue(prop);
231 }
232 return fgcommand("savexml", args) ? path : nil;
233 }
234
235
236 # The following two functions are for reading generic XML files into
237 # the property tree and for writing them from there to the disk. The
238 # built-in fgcommands (load, save, loadxml, savexml) are for FlightGear's
239 # own <PropertyList> XML files only, as they only handle a limited
240 # number of very specific attributes. The io.readxml() loader turns
241 # attributes into regular children with a configurable prefix prepended
242 # to their name, while io.writexml() turns such nodes back into
243 # attributes. The two functions have their own limitations, but can
244 # easily get extended to whichever needs. The underlying parsexml()
245 # command will handle any XML file.
246
247 # Reads an XML file from an absolute path and returns it as property
248 # tree. All nodes will be of type STRING. Data are only written to
249 # leafs. Attributes are written as regular nodes with the optional
250 # prefix prepended to the name. If the prefix is nil, then attributes
251 # are ignored. Returns nil on error.
252 #
253 var readxml = func(path, prefix = "___") {
254 var stack = [[{}, ""]];
255 var node = props.Node.new();
256 var tree = node; # prevent GC
257 var start = func(name, attr) {
258 var index = stack[-1][0];
259 if (!contains(index, name))
260 index[name] = 0;
261
262 node = node.getChild(name, index[name], 1);
263 if (prefix != nil)
264 foreach (var n; keys(attr))
265 node.getNode(prefix ~ n, 1).setValue(attr[n]);
266
267 index[name] += 1;
268 append(stack, [{}, ""]);
269 }
270 var end = func(name) {
271 var buf = pop(stack);
272 if (!size(buf[0]) and size(buf[1]))
273 node.setValue(buf[1]);
274 node = node.getParent();
275 }
276 var data = func(d) stack[-1][1] ~= d;
277 return parsexml(path, start, end, data) == nil ? nil : tree;
278 }
279
280
281 # Writes a property tree as returned by readxml() to a file. Children
282 # with name starting with <prefix> are again turned into attributes of
283 # their parent. <node> must contain exactly one child, which will
284 # become the XML file's outermost element.
285 #
286 var writexml = func(path, node, indent = "\t", prefix = "___") {
287 var root = node.getChildren();
288 if (!size(root))
289 die("writexml(): tree doesn't have a root node");
290 if (substr(path, -4) != ".xml")
291 path ~= ".xml";
292 var file = open(path, "w");
293 write(file, "<?xml version=\"1.0\"?>\n\n");
294 var writenode = func(n, ind = "") {
295 var name = n.getName();
296 var name_attr = name;
297 var children = [];
298 foreach (var c; n.getChildren()) {
299 var a = c.getName();
300 if (substr(a, 0, size(prefix)) == prefix)
301 name_attr ~= " " ~ substr(a, size(prefix)) ~ '="' ~ c.getValue() ~ '"';
302 else
303 append(children, c);
304 }
305 if (size(children)) {
306 write(file, ind ~ "<" ~ name_attr ~ ">\n");
307 foreach (var c; children)
308 writenode(c, ind ~ indent);
309 write(file, ind ~ "</" ~ name ~ ">\n");
310 } elsif ((var value = n.getValue()) != nil) {
311 write(file, ind ~ "<" ~ name_attr ~ ">" ~ value ~ "</" ~ name ~ ">\n");
312 } else {
313 write(file, ind ~ "<" ~ name_attr ~ "/>\n");
314 }
315 }
316 writenode(root[0]);
317 close(file);
318 if (size(root) != 1)
319 die("writexml(): tree has more than one root node");
320 }