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