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