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