resources/RooUsage.txt
[app.Builder.js] / old-javascript / Spawn.js
1 ///<script type="text/javascript">
2
3 var Gio      = imports.gi.Gio;
4 var GLib      = imports.gi.GLib;
5
6
7 /**
8 * @namespace Spawn
9
10 * Library to wrap GLib.spawn_async_with_pipes
11
12 * usage:
13
14 * Spawn = import.Spawn;
15
16 * simple version..
17 * var output = Spawn.run({
18 *   cwd : '/home',
19 *   args : [ 'ls', '-l' ],
20 *   env : [], // optional
21 *   listeners : {
22         output : function (line) { Seed.print(line); },
23 *       stderr :  function (line) {Seed.print("ERROR" + line);  },
24 *       input : function() { return 'xxx' },
25 *   }
26 *  });
27 *
28 *
29 *
30
31 *
32 *
33 *  CRITICAL - needs this change to gir in GLib-2.0.gir g_spawn_async_with_pipes
34 *  Fixed in Ubuntu 12.10
35     <parameter name="argv" transfer-ownership="none">
36          <array c:type="gchar**">
37             <type name="utf8"/>
38           </array>
39         </parameter>
40         <parameter name="envp" transfer-ownership="none" allow-none="1">
41           <array c:type="gchar**">
42             <type name="utf8"/>
43           </array>
44         </parameter>
45 *
46 *  ALSO in GLib-2.0.gir
47
48 <method name="read_line"
49               c:identifier="g_io_channel_read_line"
50               throws="1">
51         <return-value transfer-ownership="none">
52           <type name="IOStatus" c:type="GIOStatus"/>
53         </return-value>
54         <parameters>
55           <parameter name="str_return" transfer-ownership="full" direction="out">
56             <type name="utf8" c:type="gchar**"/>
57           </parameter>
58           <parameter name="length" transfer-ownership="none" direction="out">
59             <type name="gsize" c:type="gsize*"/>
60           </parameter>
61           <parameter name="terminator_pos" transfer-ownership="none"  direction="out">
62             <type name="gsize" c:type="gsize*"/>
63           </parameter>
64         </parameters>
65       </method>
66 *
67 * run g-ir-compile -o /usr/lib/girepostitory-1.0/GLib-2.0.typelib GLib-2.0.gir
68 *
69
70 */
71
72
73 /**
74  * @class Spawn
75  * @param cfg {Object} settings - see properties.
76  * 
77  * @arg cwd {String}            working directory. (defaults to home directory)
78  * @arg args {Array}            arguments eg. [ 'ls', '-l' ]
79  * @arg listeners {Object} (optional) handlers for output, stderr, input
80  *     stderr/output both receive output line as argument
81  *     input should return any standard input
82  *     finish recieves result as argument.
83  * @arg env {Array}             enviroment eg. [ 'GITDIR=/home/test' ]
84  * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
85  * @arg exceptions {Boolean}    throw exception on failure (default no)
86  * @arg debug {Boolean}    print out what's going on.. (default no)
87  * 
88  */
89 function Spawn(cfg) {
90     for(var i in cfg) {
91         this[i] = cfg[i];
92     }
93     // set defaults?
94     this.listeners = this.listeners || {};
95     this.cwd =  this.cwd || GLib.get_home_dir();
96     if (!this.args || !this.args.length) {
97         throw "No arguments";
98     }
99     
100 }
101
102
103 Spawn.prototype = {
104     
105     ctx : false, // the mainloop ctx.
106     listeners : false,
107     async : false,
108     env : null,
109     cwd: false,
110     args: false,
111     exceptions : false,
112     debug : false,
113     /**
114      * @property output {String} resulting output
115      */
116     output  : '',
117     /**
118      * @property stderr {String} resulting output from stderr
119      */
120     stderr  : '',
121      /**
122      * @property result {Number} execution result.
123      */
124     result: 0,
125     /**
126      * @property pid {Number} pid of child process (of false if it's not running)
127      */
128     pid : false,
129     /**
130      * @property in_ch {GLib.IOChannel} input io channel
131      */
132     in_ch : false,
133     /**
134      * @property out_ch {GLib.IOChannel} output io channel
135      */
136     out_ch : false,
137     /**
138      * @property err_ch {GLib.IOChannel} stderr io channel
139      */
140     err_ch : false,
141     /**
142      * 
143      * @method run
144      * Run the configured command.
145      * result is applied to object properties (eg. 'output' or 'stderr')
146      * @returns {Object} self.
147      */
148     run : function()
149     {
150         
151         var _this = this;
152         
153         var err_src = false;
154         var out_src = false;
155         var ret = {};
156         
157         if (this.debug) {
158             print("cd " + this.cwd +";" + this.args.join(" "));
159         }
160         
161         var gret = GLib.spawn_async_with_pipes(this.cwd, this.args, this.env, 
162             GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH , 
163             null, null, ret);
164         
165                 var isSeed = true;
166                 if (typeof(Seed) == 'undefined') {
167                         ret = {
168                                 child_pid : gret[1],
169                                 standard_input : gret[2],
170                             standard_output: gret[3], 
171                             standard_error: gret[4]
172                         };
173                         isSeed = false; 
174                 }
175                 
176         //print(JSON.stringify(gret));    
177         this.pid = ret.child_pid;
178         
179         if (this.debug) {
180             print("PID: " + this.pid);
181         }
182          
183         
184         
185         GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
186             _this.result = result;
187             if (_this.debug) {
188                 print("child_watch_add : result: " + result);
189             }
190             _this.read(_this.out_ch);
191             _this.read(_this.err_ch);
192             
193                         
194             GLib.spawn_close_pid(_this.pid);
195             _this.pid = false;
196             if (_this.ctx) {
197                 _this.ctx.quit();
198             }
199             tidyup();
200             //print("DONE TIDYUP");
201             if (_this.listeners.finish) {
202                 _this.listeners.finish.call(this, _this.result);
203             }
204         });
205         
206         function tidyup()
207         {
208             if (_this.pid) {
209                 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
210                 _this.pid = false;
211             }
212             if (_this.in_ch)  _this.in_ch.close();
213             if (_this.out_ch)  _this.out_ch.close();
214             if (_this.err_ch)  _this.err_ch.close();
215             // blank out channels
216             _this.in_ch = false;
217             _this.err_ch = false;
218             _this.out_ch = false;
219             // rmeove listeners !! important otherwise we kill the CPU
220             if (err_src !== false) GLib.source_remove(err_src);
221             if (out_src !== false) GLib.source_remove(out_src);
222             err_src = false;
223             out_src = false;
224             
225         }
226         
227         
228         this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
229         this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
230         this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
231         
232         // make everything non-blocking!
233         
234         
235       
236                         // using NONBLOCKING only works if io_add_watch
237            //returns true/false in right conditions
238            this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
239            this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
240            this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
241                         
242
243       
244         // add handlers for output and stderr.
245         out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT, 
246             GLib.IOCondition.OUT + GLib.IOCondition.IN  + GLib.IOCondition.PRI +  GLib.IOCondition.HUP +  GLib.IOCondition.ERR,
247             function() {
248                 
249                return  _this.read(_this.out_ch);
250             
251             }
252         );
253         err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT, 
254             GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT +  GLib.IOCondition.HUP, 
255             function()
256         {
257             return _this.read(_this.err_ch);
258              
259         });
260         
261       
262         
263         // call input.. 
264         if (this.pid !== false) {
265             // child can exit before 1we get this far..
266             if (this.listeners.input) {
267                                 print("Trying to call listeners");
268                 try {
269                     this.write(this.listeners.input.call(this));
270                      // this probably needs to be a bit smarter...
271                     //but... let's close input now..
272                     this.in_ch.close();
273                     _this.in_ch = false;
274                    
275                     
276                     
277                     
278                     
279                 } catch (e) {
280                     tidyup();
281                     throw e;
282                     
283                 }
284                 
285             }
286         }
287         // async - if running - return..
288         if (this.async && this.pid) {
289             return this;
290         }
291          
292         // start mainloop if not async..
293         
294         if (this.pid !== false) {
295             if (this.debug) {
296                 print("starting main loop");
297             }
298             
299             this.ctx = isSeed ? new GLib.MainLoop.c_new (null, false) : GLib.MainLoop.new (null, false);;
300             this.ctx.run(false); // wait fore exit?
301             
302             //print("main_loop done!");
303         } else {
304             tidyup(); // tidyup get's called in main loop. 
305         }
306         
307         if (this.exceptions && this.result != 0) {
308             print(this.stderr);
309             print(this.output);
310             this.toString = function() { return this.stderr; };
311             throw this; // we throw self...
312         }
313         
314         // finally throw, or return self..
315         
316         return this;
317     
318     },
319     /**
320      * write to stdin of process
321      * @arg str {String} string to write to stdin of process
322      * @returns GLib.IOStatus (0 == error, 1= NORMAL)
323      */
324     write : function(str) // write a line to 
325     {
326         if (!this.in_ch) {
327             return 0; // input is closed
328         }
329         //print("write: " + str);
330         // NEEDS GIR FIX! for return value.. let's ignore for the time being..
331         //var ret = {};
332             //var res = this.in_ch.write_chars(str, str.length, ret);
333         var res = this.in_ch.write_chars(str, str.length);
334         
335         //print("write_char retunred:" + JSON.stringify(res) +  ' ' +JSON.stringify(ret)  );
336         
337         if (res != GLib.IOStatus.NORMAL) {
338             throw "Write failed";
339         }
340         //return ret.value;
341         return str.length;
342         
343     },
344     
345     /**
346      * read from pipe and call appropriate listerner and add to output or stderr string.
347      * @arg giochannel to read from.
348      * @returns none
349      */
350     read: function(ch) 
351     {
352         var prop = ch == this.out_ch ? 'output' : 'stderr';
353        // print("prop: " + prop);
354         var _this = this;
355         
356         
357         //print(JSON.stringify(ch, null,4));
358         while (true) {
359  
360             var x =   {};
361             var status = ch.read_line( x);
362             // print('status: '  +JSON.stringify(status));
363             // print(JSON.stringify(x));
364              switch(status) {
365                 case GLib.IOStatus.NORMAL:
366                 
367                     //write(fn, x.str);
368                     if (this.listeners[prop]) {
369                         this.listeners[prop].call(this, x.str_return);
370                     }
371                     _this[prop] += x.str_return;
372                     if (_this.debug) {
373                         print(prop + ':' + x.str_return.replace(/\n/, ''));
374                     }
375                     if (this.async) {
376                         try {
377                             if (imports.gi.Gtk.events_pending()) {
378                                 imports.gi.Gtk.main_iteration();
379                             }
380                         } catch(e) {
381                             
382                         }
383                     }
384                     
385                     //this.ctx.iteration(true);
386                    continue;
387                 case GLib.IOStatus.AGAIN:
388                     //print("Should be called again.. waiting for more data..");
389                     return true;
390                     break;
391                 case GLib.IOStatus.ERROR:    
392                 case GLib.IOStatus.EOF:
393                     return false;
394                    break;
395                 
396             }
397             break;
398         }
399        
400         //print("RETURNING");
401          return false; // allow it to be called again..
402     }
403     
404 };
405 /**
406  * @function run 
407  * 
408  * simple run a process - returns result, or throws stderr result...
409  * @param cfg {Object}  see spawn
410  * @return {string} stdout output.
411  */
412 function run(cfg) {
413     cfg.exceptions = true;
414     cfg.async = false;
415     var s = new Spawn(cfg);
416     var ret = s.run();
417     return s.output;
418 }
419  /*
420 // test
421 try { 
422     Seed.print(run({
423         args: ['ls', '/tmp'],
424         debug : true
425     }));
426 } catch (e) { print(JSON.stringify(e)); }
427  
428 var secs = (new Date()).getSeconds() 
429
430 try {      
431 Seed.print(run({
432     args: ['/bin/touch', '/tmp/spawntest-' + secs ],
433     debug : true
434 }));
435 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }
436
437  
438  */
439