90007cf5431531571f000d29c1e5b57f9a93a22d
[gitlive] / gitlive2.js
1 #!/usr/bin/seed
2 ///<script type="text/javascript">
3 /**
4 * Git Live
5
6 * inotify hooks for ~/gitlive
7 * that commit and push any changes made.
8 * Bit like a revision controled backed up file system!?
9 *
10 *
11 * The aims of this
12 * A) have a gitlive branch - where all our commits go.. - so they can be replicated on the server 
13 * B) HEAD branch - where things get merged to..
14 *    -- eventually on closing issues..
15 *    -- currently when we switch from one feature to another..
16 *
17 * CURRENT HEAD?   
18 * git log -n 1 --pretty=format:%H BRANCHNAME
19
20
21 *
22 * Notes on feature branch implementation
23 * We need to add a gitlive branch on the remote server..
24 *   git push origin origin:refs/heads/gitlive 
25 *   git checkout --track -b gitlive origin/gitlive << means pull will use both branches..
26 *
27 *
28 * On our feature tree..  
29 *   git push origin origin:refs/heads/feature_2
30
31 * we clone directory into gitlive_feature/XXXXX
32 *     git branch issue_XXX
33 *     git checkout issue_XXX
34 *    
35 * run this on the feature branch it merges and commits..
36 *  git pull origin master << or gitlive..
37 *  
38 *
39 * Standard change file (same bug as before..)
40 *   cd gitlive
41 *     commit etc.. (with bug no..)
42 *   cd featuredir
43 *     git pull origin gitlive
44 *     git push
45 *   cd gitlive
46 *     git push
47 *     
48 *  Change to new bug number..
49 *  cd featuredir
50 *    git checkout -b master origin/master
51 *    git checkout master <<< make sure
52 *    git pull --squash origin gitlive
53 *    git commit -m 'done with old bug number'
54 *    git push
55 *  cd gitlive
56 *    git push
57 *  cd featuredir
58 *     git push origin origin:refs/heads/feature_XXX
59 *     git checkout feature_XXX
60 *   cd gitlive
61 *     commit etc. (with new bug number) 
62 *    cd featuredir
63 *     git pull origin gitlive
64 *     git push
65 *   cd gitlive
66 *     git push
67
68 */
69
70 GI      = imports.gi.GIRepository
71 GLib        = imports.gi.GLib;
72
73 // we add this in, as it appears to get lost sometimes if we set it using the ENV. variable in builder.sh
74 GI.IRepository.prepend_search_path(GLib.get_home_dir() + '/.Builder/girepository-1.1');
75
76 Gio         = imports.gi.Gio;
77 Gtk         = imports.gi.Gtk;
78 Notify      = imports.gi.Notify;
79
80 Spawn       = imports.Spawn;
81 Git         = imports.Git;
82 StatusIcon  = imports.StatusIcon.StatusIcon;
83 Monitor     = imports.Monitor.Monitor;
84 File        = imports.File.File;
85
86
87
88 //File = imports[__script_path__+'/../introspection-doc-generator/File.js'].File
89 Gtk.init (null, null);
90
91 var gitlive = GLib.get_home_dir() + "/gitlive";
92
93 if (!GLib.file_test(gitlive, GLib.FileTest.IS_DIR)) {
94     var msg = new Gtk.MessageDialog({message_type:
95         Gtk.MessageType.INFO, buttons : Gtk.ButtonsType.OK, text: "GIT Live - ~/gitlive does not exist."});
96     msg.run();
97     msg.destroy();
98     
99     Seed.quit();
100 }
101
102  
103 var monitor = new Monitor({
104     /**
105      *
106      * queue objects
107      *  action: 'add' | rm | update
108      *  repo : 'gitlive'
109      *  file : XXXXX
110      *
111      * 
112      *
113      */
114     action_queue : [],
115     queueRunning : false,
116      
117     start: function()
118     {
119         
120         
121         
122         this.dot_gitlive = GLib.get_home_dir() + "/.gitlive";
123         if (!File.exists(this.dot_gitlive)) {
124             File.mkdir(this.dot_gitlive);
125         }
126         
127         
128         var _this = this;
129         this.lastAdd = new Date();
130          
131         // start monitoring first..
132         Monitor.prototype.start.call(this);
133         
134         // then start our queue runner..
135         GLib.timeout_add(GLib.PRIORITY_LOW, 500, function() {
136             //TIMEOUT", _this.queue.length , _this.queueRunning].join(', '));
137             if (!_this.queue.length || _this.queueRunning) {
138                 return 1;
139             }
140             var last = Math.floor(((new Date()) - this.lastAdd) / 100);
141             if (last < 4) { // wait 1/2 a seconnd before running.
142                 return 1;
143             }
144             _this.runQueue();
145             return 1;
146         },null,null);
147         
148         
149         var notification = new Notify.Notification({
150             summary: "Git Live",
151             body : gitlive + "\nMonitoring " + this.monitors.length + " Directories"
152         });
153
154         notification.set_timeout(2000);
155         notification.show();   
156     },
157     
158     initRepo : function(src)
159     {
160         print("INIT REPO " + src);
161         
162         function logrun(sp) {
163             print("LOGRUN?" + typeof(sp));
164             switch (sp.result * 1) {
165                 case 0: // success:
166                     print(sp.args.join(' '));
167                     if (sp.output.length) print(sp.output + '');
168                   // if (sp.stderr.length) success.push(sp.stderr + '');
169                     break;
170                 default: 
171                     print(sp.args.join(' '));
172                     if (sp.output.length) print(sp.output);
173                     if (sp.stderr.length) print(sp.stderr);
174                     break;
175             }
176         }
177         
178         // make hour mirrored directory
179         var rname = src.split('/').pop();
180         var dotdir = this.dot_gitlive + '/' + rname;
181         
182         print("CHECK WORKING CACHE " + dotdir);
183
184         if (!File.isDirectory(dotdir)) {
185            // print("Not a dir?");
186             logrun(Git.run(this.dot_gitlive, 'clone', src  , {   shared :  true }  ));
187         }
188         // refresh - always..
189         logrun(Git.run(src, 'pull'));
190         
191         // create and checkout gitlive branch.
192         logrun(Git.run(src, 'push', 'origin', 'origin:refs/heads/gitlive'));
193         logrun(Git.run(src, 'checkout', { track : true ,  'b'  : 'gitlive' } , 'origin/gitlive'));
194         
195         
196         
197          
198         
199         
200         
201         
202     },
203     
204     
205     /**
206      * run the queue.
207      * - pulls the items off the queue 
208      *    (as commands run concurrently and new items may get added while it's running)
209      * - runs the queue items
210      * - pushes upstream.
211      * 
212      */
213     runQueue: function()
214     {
215         this.queueRunning = true;
216         var cmds = [];
217         //this.queue.forEach(function (q) {
218         //    cmds.push(q);
219         //});
220         
221         this.action_queue.forEach(function (q) {
222             cmds.push(q);
223         });
224         //this.queue = []; // empty queue!
225         this.action_queue = [];
226         var success = [];
227         var failure = [];
228         var repos = [];
229         var done = [];
230         
231         function readResult(sp) {
232             switch (sp.result * 1) {
233                 case 0: // success:
234                     success.push(sp.args.join(' '));
235                     if (sp.output.length) success.push(sp.output + '');
236                   // if (sp.stderr.length) success.push(sp.stderr + '');
237                     break;
238                 default: 
239                     failure.push(sp.args.join(' '));
240                     if (sp.output.length) failure.push(sp.output);
241                     if (sp.stderr.length) failure.push(sp.stderr);
242                     break;
243             }
244         }
245             
246         cmds.forEach(function(cmd) {
247             // prevent duplicate calls..
248             if (done.indexOf(JSON.stringify(cmd)) > -1) {
249                 return;
250             }
251             done.push(JSON.stringify(cmd));
252             // --- we keep a list of repositories that will be pushed to at the end..
253             
254             if (repos.indexOf(cmd.repos) < 0) {
255                 repos.push(cmd.repos);
256                 //    Git.run(cmd.repos , 'pull'); // pull before we push!
257             }
258             
259             var gp  = gitlive + '/' + cmd.repo;
260             
261             switch( cmd.action ) {
262                 case 'add':
263                     readResult(Git.run(gp, 'add',  cmd.file ));
264                     readResult(Git.run(gp, 'commit',  src.file, { message: cmd.file}  ));
265                     break;
266                     
267                 case 'rm':
268                     readResult(Git.run(gp, 'rm',  cmd.file ));
269                     readResult(Git.run(gp, 'commit',  { all: true, message: cmd.file}  ));
270                     break;
271                      
272                 case 'update':
273                     readResult(Git.run(gp, 'commit', cmd.file  , {   message: cmd.file}  ));
274                     break;
275                     
276                 case 'mv':
277                     readResult(Git.run(gp, 'mv', cmd.file , cmd.target));
278                     readResult(Git.run(gp, 'commit', cmd.file  , cmd.target,
279                             {   message: 'MOVED ' + src.file +' to ' + dest.target }  ));
280                     break; 
281             }
282             
283              
284             
285         });
286          
287         // push upstream.
288         repos.forEach(function(r) {
289             var sp = Git.run(gitlive + '/' +r , 'push', { all: true } );
290             if (sp.length) {
291                 success.push(sp);
292             }
293             
294         });
295         
296         if (success.length) {
297             print(success.join("\n"));
298             var notification = new Notify.Notification({
299                 summary: "Git Live Commited",
300                 body : success.join("\n")
301                 
302             });
303
304             notification.set_timeout(2000);
305             notification.show();   
306         }
307         if (failure.length) {
308         
309             var notification = new Notify.Notification({
310                 summary: "Git Live ERROR!!",
311                 body : failure.join("\n")
312                 
313             });
314
315             notification.set_timeout(5000); // show errros for longer
316             notification.show();   
317         }
318         this.queueRunning = false;
319     },
320     
321     shouldIgnore: function(f)
322     {
323         if (f.name[0] == '.') {
324             // except!
325             if (f.name == '.htaccess') {
326                 return false;
327             }
328             
329             return true;
330         }
331         if (f.name.match(/~$/)) {
332             return true;
333         }
334         // ignore anything in top level!!!!
335         if (!f.vpath.length) {
336             return true;
337         }
338         
339         return false;
340         
341     },
342     
343     /**
344      * set gitpath and vpath
345      * 
346      * 
347      */
348     
349     parsePath: function(f)
350     {
351            
352         var vpath_ar = f.path.substring(gitlive.length +1).split('/');
353         f.repo = vpath_ar.shift();
354         f.gitpath = gitlive + '/' + f.repo;
355         f.vpath =  vpath_ar.join('/');
356         
357         
358     },
359     
360     just_created : {},
361       
362     onChanged : function(src) 
363     { 
364         return; // always ignore this..?
365         //this.parsePath(src);
366     },
367     
368     /**
369      *  results in  git add  + git commit..
370      *  
371      *
372      *
373      */
374     
375     onChangesDoneHint : function(src) 
376     { 
377         this.parsePath(src);
378         if (this.shouldIgnore(src)) {
379             return;
380         }
381         
382         var add_it = false;
383         if (typeof(this.just_created[src.path]) !='undefined') {
384             delete this.just_created[src.path];
385             this.lastAdd = new Date();
386             //this.queue.push( 
387             //    [ src.gitpath,  'add', src.vpath ],
388             //    [ src.gitpath,  'commit',  src.vpath, { message: src.vpath} ] 
389             //    
390             //);
391             this.action_queue.push({
392                 action: 'add',
393                 repo : src.repo,
394                 file : src.vpath
395             });
396             
397             
398          
399             return;
400         }
401         this.lastAdd = new Date();
402         //this.queue.push( 
403         //    [ src.gitpath,  'add', src.vpath ],
404         //    [ src.gitpath,  'commit', src.vpath, {  message: src.vpath} ]
405         //
406         //);
407         
408         this.action_queue.push({
409             action: 'add',
410             repo : src.repo,
411             file : src.vpath
412         });
413         
414
415     },
416     onDeleted : function(src) 
417     { 
418         this.parsePath(src);
419         if (this.shouldIgnore(src)) {
420             return;
421         }
422         // should check if monitor needs removing..
423         // it should also check if it was a directory.. - so we dont have to commit all..
424         
425         this.lastAdd = new Date();
426         //this.queue.push( 
427         //    [ src.gitpath, 'rm' , src.vpath ],
428         //    [ src.gitpath, 'commit', { all: true, message: src.vpath} ]
429         //    
430         //);
431         this.action_queue.push({
432             action: 'rm',
433             repo : src.repo,
434             file : src.vpath
435         });
436         
437     },
438     onCreated : function(src) 
439     { 
440         this.parsePath(src);
441         if (this.shouldIgnore(src)) {
442             return;
443         }
444         
445         if (!GLib.file_test(src.path, GLib.FileTest.IS_DIR)) {
446             this.just_created[src.path] = true;
447             return; // we do not handle file create flags... - use done hint.
448         }
449         // director has bee created
450         this.monitor(src.path);
451         
452         /*
453           since git does not really handle directory adds...
454          
455         this.lastAdd = new Date();
456         this.action_queue.push({
457             action: 'add',
458             repo : src.repo,
459             file : src.vpath
460         });
461         
462         this.queue.push( 
463             [ src.gitpath, 'add' , src.vpath,  { all: true } ],
464             [ src.gitpath, 'commit' , { all: true, message: src.vpath} ]
465             
466         );
467         */
468         
469         
470     },
471     onAttributeChanged : function(src) { 
472         this.parsePath(src);
473         if (this.shouldIgnore(src)) {
474             return;
475         }
476         this.lastAdd = new Date();
477         
478         
479         //this.queue.push( 
480        //     [ src.gitpath, 'commit' ,  src.vpath, { message: src.vpath} ]
481        // );
482         this.action_queue.push({
483             action: 'update',
484             repo : src.repo,
485             file : src.vpath
486         });
487  
488     
489     },
490     
491     onMoved : function(src,dest)
492     { 
493         this.parsePath(src);
494         this.parsePath(dest);
495         
496         if (src.gitpath != dest.gitpath) {
497             this.onDeleted(src);
498             this.onCreated(dest);
499             this.onChangedDoneHint(dest);
500             return;
501         }
502         // needs to handle move to/from unsupported types..
503         
504         if (this.shouldIgnore(src)) {
505             return;
506         }
507         if (this.shouldIgnore(dest)) {
508             return;
509         }
510         this.lastAdd = new Date();
511        // this.queue.push( 
512        //     [ src.gitpath, 'mv',  '-k', src.vpath, dest.vpath ],
513        //     [ src.gitpath, 'commit' ,  src.vpath, dest.vpath ,
514        //         { message:   'MOVED ' + src.vpath +' to ' + dest.vpath} ]
515        // );
516         
517         this.action_queue.push({
518             action: 'mv',
519             repo : src.repo,
520             file : src.vpath,
521             target : dest.vpath
522             
523         });
524         
525     }
526           
527     
528 });
529  
530  
531   
532
533 function errorDialog(data) {
534     var msg = new Gtk.MessageDialog({
535             message_type: Gtk.MessageType.ERROR, 
536             buttons : Gtk.ButtonsType.OK, 
537             text: data
538     });
539     msg.run();
540     msg.destroy();
541 }
542
543  
544
545
546
547 //
548 // need a better icon...
549
550
551 StatusIcon.init();   
552
553
554 Notify.init("gitlive");
555
556 monitor.add(GLib.get_home_dir() + "/gitlive");
557 monitor.start();
558 Gtk.main();
559 //icon.signal["activate"].connect(on_left_click);
560