Fix #5560 - Gitlive - branching wip
[gitlive] / Monitor.vala
1 //<Script type="text/javascript">
2 //var Gio     = imports.gi.Gio;
3 //var GLib    = imports.gi.GLib;
4
5 //var XObject = imports.XObject.XObject;
6 //var File    = imports.File.File;
7
8 /// # valac  --pkg gio-2.0  --pkg posix Monitor.vala -o /tmp/Monitor
9
10  
11 //using Gee; // for array list?
12 /*
13 static int main (string[] args) {
14     // A reference to our file
15     //var file = File.new_for_path ("data.txt");
16     MainLoop loop = new MainLoop ();
17     print("starting");
18     var m = new Monitor();
19     
20     m.add("/home/alan/gitlive");
21     m.start();
22     loop.run ();
23
24     return 0;
25
26 }
27 */
28
29 public class  MonitorNamePathDir {
30     public string action;
31     public string name;
32     public string path;
33     public string dir;
34     
35     public MonitorNamePathDir(string name, string path, string dir)
36     {
37         this.name = name;
38         this.path = path;
39         this.dir = dir;
40         this.action = "?";
41         
42     }
43 }
44
45
46
47 public delegate void onEventHander (FileMonitor fm, File f_orig, File of_orig, FileMonitorEvent event_type);
48
49
50 /**
51  * Monitor class - handles monitor managment for a large tree...
52  *
53  *
54  * This 
55  * 
56  * usage : 
57  * x = new Monitor({
58      change : function () {
59          * ....
60          *}
61   }
62  * x.add('/somepath')
63  * x.stop() // stops all scanning.
64  * x.play(); // starts the scanning
65  * 
66  * 
67  * 
68  * 
69  */
70  
71 public abstract class gitMonitorBase : Object
72 {
73         public abstract void monitor(string path, int depth = 0);
74
75  
76 public class Monitor : gitMonitorBase
77 {
78
79
80
81     public Monitor()
82     {
83        
84      
85         this.monitors = new Array<FileMonitor> ();
86         this.top = new Array<string> ();
87         this.paused = false;
88     }
89      
90     public Array<FileMonitor> monitors;// Array of MonitorNamePathDirileMonitors
91     public Array<string> top; // list of top level directories..
92     public bool paused;
93     /**
94      * add a directory or file to monitor
95      */
96     public void add (string add)
97     {
98         
99         print("Monitor.add: " + add);
100         this.top.append_val(add);
101     }
102     /**
103      * start monitoring
104      */
105     public void start()
106     {
107         for(int i = 0; i < this.top.length ; i++) {
108             this.monitor(this.top.index(i));
109         }
110     }
111     /**
112      * stop / pause monitoring
113      * 
114      */
115     public void stop()
116     {
117         
118         for(int i = 0; i < this.monitors.length ; i++) {
119             this.monitors.index(i).cancel();
120         } 
121         this.monitors = new Array<FileMonitor>(); // clean /destroy/ kill old?
122     }
123     /**
124      * pause monitoring - without changing what's monitored 
125      */
126     public void pause()
127     {
128         this.paused = true;
129     }
130     /**
131      * resume monitoring - without changing what's monitored 
132      */
133     public void resume()
134     {
135         this.paused = false;
136     }
137     /**
138      * monitor a file or directory (privatish)
139      *
140      * initially called with ~/gitlive  null 0 (effectvely)
141      * 
142      * 
143      */
144     public override void monitor(string path, int depth = 0)
145     {
146          
147         //GLib.debug("ADD: (%d): %s\n", depth, path);
148         
149         //depth = typeof(depth) == 'number'  ? depth *1 : 0;
150         depth = depth > 0  ? depth *1 : 0;
151         
152         
153         //fn = fn || function (fm, f, of, event_type, uh) {
154         //    _this.onEvent(fm, f, of, event_type, uh);
155         //}
156                  
157         var f = File.new_for_path(path);
158             //var cancel = new Gio.Cancellable ();
159         if (depth > 0) { 
160   
161             try {
162                  var fm = f.monitor(FileMonitorFlags.SEND_MOVED + FileMonitorFlags.WATCH_MOVES,null);  
163                  //var fm = f.monitor(FileMonitorFlags.WATCH_MOVES,null);
164  
165                  fm.changed.connect( this.onEvent );
166                 this.monitors.append_val(fm);
167
168             } catch (Error e) {
169                   GLib.debug("Error adding monitor: %s", e.message);
170                 // FIXME -- show error? do nothing..            
171             }
172             // print("ADD path " + depth + ' ' + path);
173         }
174         // iterate children?
175         // - this is not used.
176         //if (GLib.file_test(path + '/.git' , GLib.FileTest.IS_DIR) && this.initRepo) {
177             
178         //    this.initRepo(path);
179         //}
180         FileEnumerator file_enum;
181         var cancellable = new Cancellable ();
182         try {      
183             file_enum = f.enumerate_children(
184                FileAttribute.STANDARD_DISPLAY_NAME + "," +   FileAttribute.STANDARD_TYPE,
185                         FileQueryInfoFlags.NOFOLLOW_SYMLINKS,  // FileQueryInfoFlags.NONE,
186                cancellable);
187         } catch (Error e) {
188             // FIXME - show error..
189             return;
190         }
191         FileInfo next_file;
192         
193         while (cancellable.is_cancelled () == false ) {
194             try {
195                 next_file = file_enum .next_file (cancellable);
196             } catch(Error e) {
197                 print(e.message);
198                 break;
199             }
200
201             if (next_file == null) {
202                 break;
203             }
204
205             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
206
207             if (next_file.get_file_type() != FileType.DIRECTORY) {
208                 next_file = null;
209                 continue;
210             }
211
212
213             //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
214             //        next_file.get_display_name(), next_file.get_file_type());
215
216
217             if (next_file.get_is_symlink()) {
218                 next_file = null;
219                 continue;
220             }
221             
222             if (next_file.get_display_name()[0] == '.') {
223                 next_file = null;
224                 continue;
225             }
226             var sp = path+"/"+next_file.get_display_name();
227             // skip modules.
228             //print("got a file : " + sp);
229          
230             next_file = null;
231             
232             
233             
234             this.monitor(sp, depth + 1);
235             
236         }
237         try {
238             file_enum.close(null);
239         } catch(Error e) {
240             // ignore?
241         }
242     }
243     
244     
245     
246     public File realpath(File file)
247     {
248         if (file != null) {
249             return file;
250         }
251         
252         if (FileUtils.test(file.get_path(), FileTest.EXISTS)) {
253             var rp = Posix.realpath(file.get_path());
254             return File.new_for_path(rp);  
255             
256         }
257         // file does not currently exist..
258         // check parent.
259         
260 // FIX ME - string split?/? 
261         var bn = file.get_basename();
262         var ar =  file.get_path().split("/");
263         ar.resize(ar.length-1);
264         var dirname = string.joinv("/",ar );
265         var rp = Posix.realpath(dirname);
266         return File.new_for_path(rp + "/" + bn);
267         
268     }
269    
270     
271     
272      
273     public void onEvent(File f_orig, File? of_orig, FileMonitorEvent event_type)
274     {
275         if (this.paused) {
276             return;
277         }
278        // print("onEvent\n");
279         var f = this.realpath(f_orig);
280         
281  
282         MonitorNamePathDir src = new MonitorNamePathDir( f.get_basename(), f.get_path() , Path.get_dirname(f.get_path()));
283  
284         
285        
286         //string event_name = "UKNOWN";
287         
288         
289         // extract the event names ... - not sure if introspection is feasible in vala..
290         //for(var i in Gio.FileMonitorEvent) {
291          //    if (Gio.FileMonitorEvent[i] == event_type) {
292          //        event_name = i;
293          //    }
294          //}
295         
296
297
298
299         //print (JSON.stringify([event_name , f.get_path(), of ? of.get_path() : false ] ));
300         //print ("got src: " + src.toString());
301         //print ("got event: " + src.toString());
302         try {
303                 
304
305             switch(event_type) {
306                 case FileMonitorEvent.CHANGED:
307                     src.action = "changed";
308                     this.onChanged(src);
309                     return; // ingore thise?? -wait for changes_done_htin?
310                     
311                 case FileMonitorEvent.CHANGES_DONE_HINT:
312                     src.action = "changed";
313                     this.onChangesDoneHint(src);
314                     return;
315                     
316                 case FileMonitorEvent.DELETED:
317                     src.action = "rm";
318                     this.onDeleted(src);
319                     return;
320                     
321                 case FileMonitorEvent.CREATED:
322                     src.action = "created";
323                     this.onCreated(src);
324                     return;
325                 
326                 case FileMonitorEvent.ATTRIBUTE_CHANGED: // eg. chmod/chatt
327                     src.action = "attrib";
328                     this.onAttributeChanged(src);
329                     return;
330                 
331                 case FileMonitorEvent.MOVED: // eg. chmod/chatt
332                 case FileMonitorEvent.MOVED_IN: // eg. chmod/chatt
333                 case FileMonitorEvent.MOVED_OUT: // eg. chmod/chatt                                
334                 case FileMonitorEvent.RENAMED: // eg. chmod/chatt                      
335
336                   var of = this.realpath(of_orig);
337                    var   dest = new MonitorNamePathDir(
338                                 of.get_basename(), 
339                                 of.get_path(),  
340                                 Path.get_dirname(of.get_path())
341                     );
342
343                     src.action = "moved";
344                     dest.action = "moved";
345                     this.onMoved(src,dest);
346                     return; 
347                     
348  
349                 default:
350                     stdout.printf("event type not handled %u", event_type);
351                     break;
352                 // rest are mount related - not really relivant.. maybe add later..
353             } 
354         } catch(Error e) {
355             print(e.message);
356         }
357         
358     }
359     
360
361     /** override these to do stuff.. */
362     //public void initRepo(MonitorNamePathDir src) { } // called on startup at the top level repo dir.
363     public virtual void  onChanged(MonitorNamePathDir src) { }
364     public virtual void onChangesDoneHint(MonitorNamePathDir src) { }
365     public virtual void onDeleted(MonitorNamePathDir src) { }
366     public virtual void onCreated(MonitorNamePathDir src) { }
367     public virtual void onAttributeChanged(MonitorNamePathDir src) { }
368     public virtual void onMoved(MonitorNamePathDir src,MonitorNamePathDir dest) { }
369           
370     
371 }
372  
373  
374
375
376
377
378