r17548: It is a good idea to commit the fix (from mkhl) before the test that
[jra/samba/.git] / source4 / scripting / libjs / base.js
1 /*
2         base js library functions
3         Copyright Andrew Tridgell 2005
4         released under the GNU GPL v2 or later
5 */
6
7 if (global["HAVE_BASE_JS"] != undefined) {
8    return;
9 }
10 HAVE_BASE_JS=1
11
12 /* bring the string functions into the global frame */
13 string_init(global);
14
15 /*
16   an essential function!
17 */
18 function printf()
19 {
20         print(vsprintf(arguments));
21 }
22
23 /*
24   helper function to setup a rpc io object, ready for input
25 */
26 function irpcObj()
27 {
28         var o = new Object();
29         o.input = new Object();
30         return o;
31 }
32
33 /*
34   check that a status result is OK
35 */
36 function check_status_ok(status)
37 {
38         if (status.is_ok != true) {
39                 printVars(status);
40         }
41         assert(status.is_ok == true);
42 }
43
44 /*
45   check that two arrays are equal
46 */
47 function check_array_equal(a1, a2)
48 {
49         assert(a1.length == a2.length);
50         for (i=0; i<a1.length; i++) {
51                 assert(a1[i] == a2[i]);
52         }
53 }
54
55 /*
56   check that an array is all zeros
57 */
58 function check_array_zero(a)
59 {
60         for (i=0; i<a.length; i++) {
61                 assert(a[i] == 0);
62         }
63 }
64
65 /*
66   substitute strings of the form ${NAME} in str, replacing
67   with substitutions from subobj
68 */
69 function substitute_var(str, subobj)
70 {
71         var list = split("${", str);
72         var i;
73         for (i=1;i<list.length;i++) {
74                 var list2 = split("}", list[i], 1);
75                 if ((list2.length < 2) && (list2[0] + "}" != list[i])) {
76                         return undefined;
77                 }
78                 var key = list2[0];
79                 var val;
80                 if (typeof(subobj[key]) == "undefined") {
81                         val = "${" + key + "}";
82                 } else if (typeof(subobj[key]) == "string") {
83                         val = subobj[key];
84                 } else {
85                         var fn = subobj[key];
86                         val = fn(key);
87                 }
88                 list2[0] = "" + val;
89                 list[i] = join("", list2);
90         }
91         return join("", list);
92 }
93
94 /*
95   return "s" if a number should be shown as plural
96 */
97 function plural(n)
98 {
99         if (n == 1) {
100                 return "";
101         }
102         return "s";
103 }