sync
[gitlive] / Git.vala
1
2 // valac -o /tmp/ggit Git.vala --pkg libgit2-glib-1.0 --pkg libsoup-2.4 -pkg gee-0.8 -g
3
4
5
6 void main()
7 {
8          GLib.Log.set_handler(null, 
9             GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO, 
10             (dom, lvl, msg) => {
11                                         
12                                         
13                // should we debug..
14                                         
15                         
16                print("%s\n", msg);
17             }
18          ); 
19
20         Ggit.init();
21         
22         var a = new GitLive.Repo("/home/alan/gitlive/gitlive");
23         a.loadLocalBranches();
24         a.fetchAll();
25         //
26         /*
27         var a = new GitLive.Repo("/home/alan/git/test1-clone");
28         //a.fetchAll();
29         var str = (new GLib.DateTime.now_utc()).format("%Y-%m-%d %H:%M:%S");
30         GLib.FileUtils.set_contents("/home/alan/git/test1-clone/test1",  str); 
31         
32         var ix = a.repo.get_index();
33         ix.add_path("test1");
34         ix.write();
35         var treeoid = ix.write_tree();
36
37         var head = a.repo.get_head();
38         var parent = head.lookup() as Ggit.Commit;
39         Ggit.Commit[] parents = (parent == null) ? 
40                 new Ggit.Commit[] {} :
41                 new Ggit.Commit[] { parent };
42
43         var tree = a.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;// odd format.. 
44         
45         var sig = new Ggit.Signature.now("Alan Knowles", "alan@roojs.com");
46         a.repo.create_commit("HEAD", sig, sig, null, "test commit " + str, tree, parents);
47         */
48         // mmh.. no git add/commit in library...
49 //      string[] spawn_args = {"git", "commit", "-m", "test", "-a"};
50         //string[] spawn_env = Environ.get ();
51 //      Process.spawn_sync ("/home/alan/git/test1-clone", spawn_args, spawn_env, SpawnFlags.SEARCH_PATH, null);
52  
53         a.pushAll();
54 }
55  
56
57 namespace  GitLive {
58
59         public class Repo : Object {
60
61                 public Ggit.Repository  repo;
62                 Callbacks callbacks;
63
64                 public Repo(string path)
65                 {
66                         this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
67                         this.callbacks = new Callbacks(this);
68                 
69                 }
70                 
71             Gee.ArrayList<Ggit.Branch>          branches = null;
72                 public void loadLocalBranches()
73                 {
74                         this.branches =  new Gee.ArrayList<Ggit.Branch>();
75                         var r = this.repo.enumerate_branches(Ggit.BranchType.LOCAL);
76                         while (r.next()) {
77                                 var br = r.get() as Ggit.Branch;
78                                 //var head = this.repo.revparse("refs/heads/" + br.get_name() ).get_id();
79                                 //var rhead = this.repo.revparse(br.get_upstream().get_name() ).get_id();
80                                 //GLib.debug("got branch: name = %s upstream = %s oid = %s ", 
81                                 //              br.get_name(), br.get_upstream().get_name(), 
82                                 //              head.to_string());
83                                 this.branches.add(br);
84                                 
85                         }
86                 }
87                 
88                 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
89                 {
90                          //GLib.debug("bn=%s",remote_branch_name);
91                          if (remote_branch_name.has_prefix("refs/remotes/")) {
92                                  return null;
93                          }
94
95                          var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
96                         if (target == "HEAD") {
97                                 target = remote_name +"/master";
98                         }
99                          
100                         foreach(var br in this.branches) {
101                         //      GLib.debug("test:%s=%s", br.get_upstream().get_shorthand() , target);
102                                 if ( br.get_upstream().get_shorthand() == target) {
103                                         return br;
104                                 }
105                                 
106                         }
107                         //GLib.debug("missing %s", remote_branch_name);                 
108                         return null;
109                 
110                 }
111                 
112                 
113                 
114                 public void fetchAll()
115                 {
116                         this.loadLocalBranches();
117                         // remotes probably will not work with http auth..
118                         var ar = this.repo.list_remotes();
119                         foreach(var n in ar) {
120                                 GLib.debug("got remote '%s'", n);
121                                 var r = this.repo.lookup_remote(n);
122                                 GLib.debug("connecting '%s'", r.get_url());
123                                  
124                                 try {
125                                         string[] h = { "a = 1" };
126                                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
127                                         
128                                 } catch (Error e) {
129                                         GLib.debug("Got Error Message: %s", e.message);
130                                         return;
131                                 }
132                                 string[] far = {};
133                                 var heads = r.list();
134                                 foreach(var rh in heads) {
135                                         if (rh.get_name().has_prefix("refs/remotes/")) {
136                                                    continue;
137                                          }
138                                 
139                                         var br = this.getBranch(n, rh.get_name());
140                                  
141                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
142                                                 rh.get_name(), 
143                                                 rh.get_oid().to_string(),
144                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
145                                         );
146                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
147                                         size_t ahead, behind;
148                                         this.repo.get_ahead_behind(
149                                                 loc_oid,
150                                                 rh.get_oid(),
151                                                 out ahead,
152                                                 out behind
153                                         );
154                                         
155                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
156                                                 continue;
157                                         }
158                                         if (ahead > 0) {
159                                                 continue;
160                                         }
161                                         far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
162                                 } 
163                                 
164                                 if (far.length < 1) {
165                                         GLib.debug("no fetch required.. it's uptodate");
166                                         return;
167                                 }
168                                 
169                                 GLib.debug("getting remote specs '%s', %d", n, far.length);
170                                 
171 /*
172                                 var far = r.get_fetch_specs();
173                                 */
174                                 foreach(var rs in far) {
175                                         GLib.debug("got remote spec: %s", rs);
176                                         
177                                 }
178
179                                 var options = new Ggit.FetchOptions();
180                                 options.set_remote_callbacks(this.callbacks);
181                                 //yield Async.thread(() => {
182         
183                                         r.download(far, options);
184                                 //});
185                                 r.disconnect();
186                                 
187                                 //r.download(
188                         }
189                 
190                 }
191                 
192                 
193                 
194                 public void pushAll()
195                 {
196                         // remotes probably will not work with http auth..
197                         var ar = this.repo.list_remotes();
198                         foreach(var n in ar) {
199                                 GLib.debug("got remote '%s'", n);
200                                 var r = this.repo.lookup_remote(n);
201                                 GLib.debug("connecting '%s'", r.get_url());
202                                  
203                                 try {
204                                         string[] h = { "a = 1" };
205                                          r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
206                                         
207                                 } catch (Error e) {
208                                         GLib.debug("Got Error Message: %s", e.message);
209                                         return;
210                                 }
211                                 //GLib.debug("getting specs '%s'", n);
212                                 /* 
213                                 
214                                 this.repo.add_remote_push(
215                                         "origin",
216                                         "+%s:%s".printf(head.get_shorthand(),head.get_name())
217                                 );
218  */
219  
220                                 string[] far = {};
221                                 var heads = r.list();
222                                 foreach(var rh in heads) {
223                                         if (rh.get_name().has_prefix("refs/remotes/")) {
224                                                    continue;
225                                          }
226                                 
227                                         var br = this.getBranch(n, rh.get_name());
228                                  
229                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
230                                                 rh.get_name(), 
231                                                 rh.get_oid().to_string(),
232                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
233                                         );
234                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
235                                         size_t ahead, behind;
236                                         this.repo.get_ahead_behind(
237                                                 loc_oid,
238                                                 rh.get_oid(),
239                                                 out ahead,
240                                                 out behind
241                                         );
242                                         
243                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
244                                                 continue;
245                                         }
246                                         if (behind > 0) {
247                                                 continue;
248                                         }
249                                         far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
250                                 }  
251                                 
252                                 if (far.length < 1) {
253                                         GLib.debug("no push required.. it's uptodate");
254                                         return;
255                                 }
256  
257                                 /*var head = this.repo.get_head();
258                                 string[] far = {};
259                                 far += "+%s:%s".printf(head.get_name(),head.get_name());
260                                 */
261                                 foreach(var rs in far) {
262                                         GLib.debug("got remote spec: %s", rs);
263                                         
264                                 }
265                                         
266                                 var popts = new Ggit.PushOptions();
267                                  popts.callbacks = this.callbacks;
268                                 GLib.debug("Push?");
269                                 r.upload(far,popts);
270                                 GLib.debug("Push done?");
271                                 r.disconnect();
272                                 
273                                 
274                                 //r.download(
275                         }
276                 
277                 }
278                 
279                 
280                 
281
282         }
283         
284         private class Callbacks : Ggit.RemoteCallbacks
285         {
286                 //private Remote d_remote;
287                 private Ggit.RemoteCallbacks? d_proxy = null;
288
289                 public delegate void TransferProgress(Ggit.TransferProgress stats);
290                 //private TransferProgress? d_transfer_progress;
291
292                 public Callbacks( Repo repo)  //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
293                 {
294                         //d_remote = remote;
295                         //d_proxy = proxy;
296                         //d_transfer_progress = (owned)transfer_progress;
297                 }
298
299                 protected override void progress(string message)
300                 {
301                         GLib.debug("progress");
302                         if (d_proxy != null)
303                         {
304                                 d_proxy.progress(message);
305                         }
306                 }
307
308                 protected override void transfer_progress(Ggit.TransferProgress stats)
309                 {
310                         GLib.debug("transfer_progress");
311                         /*
312                         if (d_transfer_progress != null)
313                         {
314                                 d_transfer_progress(stats);
315                         }
316
317                         if (d_proxy != null)
318                         {
319                                 d_proxy.transfer_progress(stats);
320                         }
321                         */
322                 }
323
324                 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
325                 {
326                         GLib.debug("update_tips");
327                         //d_remote.tip_updated(refname, a, b);
328
329                         if (d_proxy != null)
330                         {
331                                 d_proxy.update_tips(refname, a, b);
332                         }
333                 }
334
335                 protected override void completion(Ggit.RemoteCompletionType type)
336                 {
337                         GLib.debug("completion");
338                         if (d_proxy != null)
339                         {
340                                 d_proxy.completion(type);
341                         }
342                 }
343
344                 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
345                 {
346  
347                         GLib.debug("get credentials %s  UN=%s", url, username_from_url);
348                         var uri = new Soup.URI(url);
349
350                         if (uri != null) {
351                                 var ret = this.netrc(uri.get_host());
352                                 if (ret != null) {
353                                         return ret;
354                                 }
355                                 
356                                 //return new Ggit.CredPlaintext(username_from_url, "test");
357                         }
358                         return null;
359                         /*var provider = d_remote.credentials_provider;
360
361                         if (provider != null)
362                         {
363                                 ret = provider.credentials(url, username_from_url, allowed_types);
364                         }
365
366                         if (ret == null && d_proxy != null)
367                         {
368                                 ret = d_proxy.credentials(url, username_from_url, allowed_types);
369                         }
370                         
371                         return ret;
372                         */
373                 }
374                 public  Ggit.Cred netrc(string domain) 
375                 {
376                         string str;
377                         GLib.FileUtils.get_contents(GLib.Environment.get_home_dir() + "/.netrc", out str);
378                         var lines = str.split("\n");
379                         for(var i=0; i< lines.length; i++) {
380                                 // assumes one line per entry.. if not we are buggered...
381                                 //GLib.debug("got %s" , lines[i]);
382                         
383                                 var bits =  Regex.split_simple ("[ \t]+", lines[i].strip());
384                                 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
385                                         continue;
386                                 }
387                                 GLib.debug("found password?");
388                                 // we are gussing.... 
389                                 return new Ggit.CredPlaintext(bits[3], bits[5]);
390
391                         }
392                         return null;
393
394
395                 
396                 
397                 }
398                 
399         }
400         
401         
402
403 }