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