fix date calc
[gitlive] / 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         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         //print(JSON.stringify(ret));    
166         this.pid = ret.child_pid;
167         
168         if (this.debug) {
169             print("PID: " + this.pid);
170         }
171         
172         
173         
174         GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
175             _this.result = result;
176             if (_this.debug) {
177                 print("child_watch_add : result: " + result);
178             }
179             _this.read(_this.out_ch);
180             _this.read(_this.err_ch);
181             
182             GLib.spawn_close_pid(_this.pid);
183             _this.pid = false;
184             if (_this.ctx) {
185                 _this.ctx.quit();
186             }
187             tidyup();
188             //print("DONE TIDYUP");
189             if (_this.listeners.finish) {
190                 _this.listeners.finish.call(this, _this.result);
191             }
192         });
193         
194         function tidyup()
195         {
196             if (_this.pid) {
197                 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
198                 _this.pid = false;
199             }
200             if (_this.in_ch)  _this.in_ch.close();
201             if (_this.out_ch)  _this.out_ch.close();
202             if (_this.err_ch)  _this.err_ch.close();
203             // blank out channels
204             _this.in_ch = false;
205             _this.err_ch = false;
206             _this.out_ch = false;
207             // rmeove listeners !! important otherwise we kill the CPU
208             if (err_src !== false) GLib.source_remove(err_src);
209             if (out_src !== false) GLib.source_remove(out_src);
210             err_src = false;
211             out_src = false;
212             
213         }
214         
215         
216         this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
217         this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
218         this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
219         
220         // make everything non-blocking!
221         
222         
223       
224          // using NONBLOCKING only works if io_add_watch
225         //returns true/false in right conditions
226         this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
227         this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
228         this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
229          
230
231       
232         // add handlers for output and stderr.
233         out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT, 
234             GLib.IOCondition.OUT + GLib.IOCondition.IN  + GLib.IOCondition.PRI +  GLib.IOCondition.HUP +  GLib.IOCondition.ERR,
235             function() {
236                 
237                return  _this.read(_this.out_ch);
238             
239             }
240         );
241         err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT, 
242             GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT +  GLib.IOCondition.HUP, 
243             function()
244         {
245             return _this.read(_this.err_ch);
246              
247         });
248         
249       
250         
251         // call input.. 
252         if (this.pid !== false) {
253             // child can exit before we get this far..
254             if (this.listeners.input) {
255                 print("Trying to call listeners");
256                 try {
257                     this.write(this.listeners.input.call(this));
258                      // this probably needs to be a bit smarter...
259                     //but... let's close input now..
260                     this.in_ch.close();
261                     _this.in_ch = false;
262                    
263                     
264                     
265                     
266                     
267                 } catch (e) {
268                     tidyup();
269                     throw e;
270                     
271                 }
272                 
273             }
274         }
275         // async - if running - return..
276         if (this.async && this.pid) {
277             return this;
278         }
279         
280         
281         // start mainloop if not async..
282         
283         if (this.pid !== false) {
284             if (this.debug) {
285                 print("starting main loop");
286             }
287             
288             this.ctx = new GLib.MainLoop.c_new (null, false);
289             this.ctx.run(false); // wait fore exit?
290             
291             //print("main_loop done!");
292         } else {
293             tidyup(); // tidyup get's called in main loop. 
294         }
295         
296         if (this.exceptions && this.result != 0) {
297             this.toString = function() { return this.stderr; };
298             throw this; // we throw self...
299         }
300         
301         // finally throw, or return self..
302         
303         return this;
304     
305     },
306     /**
307      * write to stdin of process
308      * @arg str {String} string to write to stdin of process
309      * @returns GLib.IOStatus (0 == error, 1= NORMAL)
310      */
311     write : function(str) // write a line to 
312     {
313         if (!this.in_ch) {
314             return 0; // input is closed
315         }
316         //print("write: " + str);
317         // NEEDS GIR FIX! for return value.. let's ignore for the time being..
318         //var ret = {};
319         //var res = this.in_ch.write_chars(str, str.length, ret);
320         var res = this.in_ch.write_chars(str, str.length);
321         
322         //print("write_char retunred:" + JSON.stringify(res) +  ' ' +JSON.stringify(ret)  );
323         
324         if (res != GLib.IOStatus.NORMAL) {
325             throw "Write failed";
326         }
327         //return ret.value;
328         return str.length;
329         
330     },
331     
332     /**
333      * read from pipe and call appropriate listerner and add to output or stderr string.
334      * @arg giochannel to read from.
335      * @returns none
336      */
337     read: function(ch) 
338     {
339         var prop = ch == this.out_ch ? 'output' : 'stderr';
340        // print("prop: " + prop);
341         var _this = this;
342         
343         
344         //print(JSON.stringify(ch, null,4));
345         while (true) {
346  
347             var x =   {};
348             var status = ch.read_line( x);
349             // print('status: '  +JSON.stringify(status));
350             // print(JSON.stringify(x));
351              switch(status) {
352                 case GLib.IOStatus.NORMAL:
353                 
354                     //write(fn, x.str);
355                     if (this.listeners[prop]) {
356                         this.listeners[prop].call(this, x.str_return);
357                     }
358                     _this[prop] += x.str_return;
359                     if (_this.debug) {
360                         print(prop + ':' + x.str_return.replace(/\n/, ''));
361                     }
362                     if (this.async) {
363                         try {
364                             if (imports.gi.Gtk.events_pending()) {
365                                 imports.gi.Gtk.main_iteration();
366                             }
367                         } catch(e) {
368                             
369                         }
370                     }
371                     
372                     //this.ctx.iteration(true);
373                    continue;
374                 case GLib.IOStatus.AGAIN:
375                     //print("Should be called again.. waiting for more data..");
376                     return true;
377                     break;
378                 case GLib.IOStatus.ERROR:    
379                 case GLib.IOStatus.EOF:
380                     return false;
381                    break;
382                 
383             }
384             break;
385         }
386        
387         //print("RETURNING");
388          return false; // allow it to be called again..
389     }
390     
391 };
392 /**
393  * @function run 
394  * 
395  * simple run a process - returns result, or throws stderr result...
396  * @param cfg {Object}  see spawn
397  * @return {string} stdout output.
398  */
399 function run(cfg) {
400     cfg.exceptions = true;
401     cfg.async = false;
402     var s = new Spawn(cfg);
403     var ret = s.run();
404     return s.output;
405 }
406  /*
407 // test
408 try { 
409     Seed.print(run({
410         args: ['ls', '/tmp'],
411         debug : true
412     }));
413 } catch (e) { print(JSON.stringify(e)); }
414  
415 var secs = (new Date()).getSeconds() 
416
417 try {      
418 Seed.print(run({
419     args: ['/bin/touch', '/tmp/spawntest-' + secs ],
420     debug : true
421 }));
422 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }
423
424  
425  */
426