This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
/
gitresolver.c
985 lines (909 loc) · 23.8 KB
/
gitresolver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/**
* @file
*
* @brief Source for gitresolver plugin
*
* @copyright BSD License (see doc/LICENSE.md or https://www.libelektra.org)
*
*/
#include <fcntl.h>
#include <git2.h>
#include <kdberrors.h>
#include <kdbhelper.h>
#include <libgen.h>
#include <openssl/md5.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include "../resolver/shared.h"
#include <kdbinvoke.h>
#include "gitresolver.h"
#define TV_MAX_DIGITS 26
#define DEFAULT_CHECKOUT_LOCATION "/tmp/"
#define REFSTRING "refs/heads/"
typedef enum
{
OBJECT,
HEAD,
} Tracking;
typedef struct
{
char * tmpFile; // temporary filename for checkout
char * repo; // path to repo (currently only local)
char * workdir; // repository workdir
char * subdirs; // subdirectores between file and workdir
char * branch; // branchname
char * file; // filename
char * refName; // git reference name e.g. refs/heads/master
char * headID; // id of the most recent commit
char * objID; // most recent id of the file
Tracking tracking; // track commit ids or object ids
int setPhase; // Set phase counter, 0 setresolver, 1 commit
mode_t dirmode; //
unsigned char lastHash[MD5_DIGEST_LENGTH]; // hash of the checkdout file
short checkout; // 1 = checkout file to repo, 0 = checkout to temporary file
short pull; // 0 = don't pull repo, 1 = pull repo
} GitData;
static int elektraResolveFilename (Key * parentKey, ElektraResolveTempfile tmpFile)
{
int rc = 0;
ElektraInvokeHandle * handle = elektraInvokeOpen ("resolver", 0, 0);
if (!handle)
{
rc = -1;
goto RESOLVE_FAILED;
}
ElektraResolved * resolved = NULL;
typedef ElektraResolved * (*resolveFileFunc) (elektraNamespace, const char *, ElektraResolveTempfile, Key *);
resolveFileFunc resolveFunc = *(resolveFileFunc *) elektraInvokeGetFunction (handle, "filename");
if (!resolveFunc)
{
rc = -1;
goto RESOLVE_FAILED;
}
typedef void (*freeHandleFunc) (ElektraResolved *);
freeHandleFunc freeHandle = *(freeHandleFunc *) elektraInvokeGetFunction (handle, "freeHandle");
if (!freeHandle)
{
rc = -1;
goto RESOLVE_FAILED;
}
resolved = resolveFunc (keyGetNamespace (parentKey), keyString (parentKey), tmpFile, parentKey);
if (!resolved)
{
rc = -1;
goto RESOLVE_FAILED;
}
else
{
keySetString (parentKey, resolved->fullPath);
freeHandle (resolved);
}
RESOLVE_FAILED:
elektraInvokeClose (handle, 0);
return rc;
}
int elektraGitresolverCheckFile (const char * filename)
{
if (filename[0] == '/') return 0;
return 1;
}
static void genCheckoutFileName (GitData * data)
{
// generate temp filename: /tmp/branch_filename_tv_sec:tv_usec
struct timeval tv;
gettimeofday (&tv, 0);
const char * fileName = strrchr (data->file, '/');
if (!fileName)
fileName = data->file;
else
fileName += 1;
size_t len = strlen (DEFAULT_CHECKOUT_LOCATION) + strlen (data->branch) + strlen (fileName) + TV_MAX_DIGITS + 1;
data->tmpFile = elektraCalloc (len);
snprintf (data->tmpFile, len, "%s%s_%s_%lu:" ELEKTRA_TIME_USEC_F, DEFAULT_CHECKOUT_LOCATION, data->branch, fileName, tv.tv_sec,
tv.tv_usec);
}
static unsigned char * hashBuffer (const void * buffer, size_t size)
{
MD5_CTX c;
unsigned char * out = elektraMalloc (MD5_DIGEST_LENGTH);
MD5_Init (&c);
MD5_Update (&c, buffer, size);
MD5_Final (out, &c);
return out;
}
int elektraGitresolverOpen (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
// plugin initialization logic
// this function is optional
return 1; // success
}
int elektraGitresolverClose (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
// free all plugin resources and shut it down
// this function is optional
GitData * data = elektraPluginGetData (handle);
if (!data) return 0;
if (data->headID) elektraFree (data->headID);
if (data->tmpFile)
{
unlink (data->tmpFile); // remove temporary checked out file when closing
elektraFree (data->tmpFile);
}
if (data->repo) elektraFree (data->repo);
if (data->workdir) elektraFree (data->workdir);
if (data->subdirs) elektraFree (data->subdirs);
if (data->file) elektraFree (data->file);
if (data->refName) elektraFree (data->refName);
elektraFree (data);
elektraPluginSetData (handle, NULL);
return 1; // success
}
static int initData (Plugin * handle, Key * parentKey)
{
GitData * data = elektraPluginGetData (handle);
if (!data)
{
KeySet * config = elektraPluginGetConfig (handle);
data = elektraCalloc (sizeof (GitData));
Key * key = ksLookupByName (config, "/path", KDB_O_NONE);
keySetString (parentKey, keyString (key));
if (elektraResolveFilename (parentKey, ELEKTRA_RESOLVER_TEMPFILE_NONE) == -1)
{
return -1;
}
data->repo = elektraStrDup (keyString (parentKey));
// default to master branch when no branchname is supplied
const char * defaultBranch = "master";
key = ksLookupByName (config, "/branch", KDB_O_NONE);
if (!key)
data->branch = (char *) defaultBranch;
else
data->branch = (char *) keyString (key);
key = ksLookupByName (config, "/tracking", KDB_O_NONE);
if (!key)
data->tracking = HEAD;
else
{
if (!strcmp (keyString (key), "object"))
data->tracking = OBJECT;
else
data->tracking = HEAD;
}
key = ksLookupByName (config, "/pull", KDB_O_NONE);
if (!key)
{
data->pull = 0;
}
else
{
data->pull = 1;
}
size_t refLen = strlen (REFSTRING) + strlen (data->branch) + 1;
data->refName = elektraCalloc (refLen);
snprintf (data->refName, refLen, "%s%s", REFSTRING, data->branch);
key = ksLookupByName (config, "/checkout", KDB_O_NONE);
if (!key)
{
data->checkout = 0;
}
else
{
data->checkout = 1;
}
elektraPluginSetData (handle, data);
}
return 0;
}
static git_buf * discover_repo (char * path)
{
if (!strcmp (path, "/")) return NULL;
git_buf * buf = elektraCalloc (sizeof (git_buf));
int rc = git_repository_discover (buf, path, 0, NULL);
if (rc)
{
git_buf_free (buf);
elektraFree (buf);
buf = discover_repo (dirname (path));
return buf;
}
else
{
return buf;
}
}
static git_repository * connectToLocalRepo (GitData * data)
{
git_libgit2_init ();
git_repository * repo;
int rc;
git_buf buf = GIT_BUF_INIT_CONST (NULL, 0);
rc = git_repository_discover (&buf, data->repo, 0, NULL);
if (rc)
{
char * repoCopy = elektraStrDup (data->repo);
git_buf * discovered = discover_repo (dirname (repoCopy));
if (discovered)
{
if (data->workdir) elektraFree (data->workdir);
data->workdir = elektraStrDup (discovered->ptr);
elektraFree (repoCopy);
git_buf_free (discovered);
elektraFree (discovered);
}
else
{
git_buf_free (&buf);
elektraFree (repoCopy);
return NULL;
}
}
else
{
if (data->workdir) elektraFree (data->workdir);
data->workdir = elektraStrDup (buf.ptr);
}
git_buf_free (&buf);
rc = git_repository_open_ext (&(repo), data->workdir, 0, NULL);
if (rc)
{
return NULL;
}
const char * repoPath = git_repository_workdir (repo);
if (data->workdir) elektraFree (data->workdir);
data->workdir = elektraStrDup (repoPath);
struct stat buffer;
if (stat (data->workdir, &buffer) == -1)
{
data->dirmode = 0100;
}
else
{
data->dirmode = buffer.st_mode;
}
char * repoCopy = elektraStrDup (data->repo);
char * dir = dirname (repoCopy);
if (data->subdirs) elektraFree (data->subdirs);
data->subdirs = elektraStrDup (dir + elektraStrLen (data->workdir) - 2);
if (!strcmp (data->subdirs, ""))
{
elektraFree (data->subdirs);
data->subdirs = NULL;
}
elektraFree (repoCopy);
repoCopy = elektraStrDup (data->repo);
if (data->file) elektraFree (data->file);
data->file = elektraStrDup (basename (data->repo));
elektraFree (repoCopy);
return repo;
}
static git_reference * getHeadRef (GitData * data, git_repository * repo)
{
git_reference * headRef;
int rc = git_reference_lookup (&headRef, repo, data->refName);
if (rc)
{
git_reference_free (headRef);
return NULL;
}
// compare newest commit id to last saved commit id
// only update if there's a newer commit
// const git_oid * headObj = git_reference_target (headRef);
// git_reference_free (headRef);
// return headObj;
return headRef;
}
static char * hasNewCommit (GitData * data, const git_oid * headObj)
{
size_t IDSize = GIT_OID_HEXSZ + 1;
char * commitID = elektraCalloc (IDSize);
git_oid_tostr (commitID, IDSize, headObj);
if (!data->headID)
{
return commitID;
}
else
{
if (!strcmp (data->headID, commitID))
{
elektraFree (commitID);
return NULL;
}
else
{
return commitID;
}
}
}
static char * hasNewObjectCommit (GitData * data, git_object * blob)
{
size_t IDSize = GIT_OID_HEXSZ + 1;
char * objID = elektraCalloc (IDSize);
git_oid_tostr (objID, IDSize, git_object_id (blob));
if (!data->objID)
{
return objID;
}
else
{
if (!strcmp (data->objID, objID))
{
elektraFree (objID);
return NULL;
}
else
{
return objID;
}
}
}
static git_object * getBlob (GitData * data, git_repository * repo)
{
git_object * blob;
size_t specSize = strlen (data->refName) + strlen (data->file) + 3;
if (data->subdirs) specSize += strlen (data->subdirs);
char spec[specSize];
if (!data->subdirs)
{
snprintf (spec, sizeof (spec), "%s:%s", data->refName, data->file);
}
else
{
snprintf (spec, sizeof (spec), "%s:%s/%s", data->refName, (data->subdirs) + 1, data->file);
}
int rc = git_revparse_single (&blob, repo, spec);
if (rc)
{
// file doesn't exist in repo
return NULL;
}
return blob;
}
// inspired by bash make_path
static void makePath (GitData * data)
{
if (!data->subdirs) return;
char * path = elektraStrDup (data->repo);
char * ptr = strrchr (path, '/');
*ptr = '\0';
ptr = path + strlen (data->workdir) - 2;
struct stat sb;
while ((ptr = strchr (ptr, '/')) != NULL)
{
*ptr = '\0';
if (stat (path, &sb) != 0)
{
if (mkdir (path, data->dirmode))
{
elektraFree (path);
return;
}
}
else if (S_ISDIR (sb.st_mode) == 0)
{
elektraFree (path);
return;
}
*ptr++ = '/';
}
if (stat (path, &sb) && mkdir (path, data->dirmode)) elektraFree (path);
return;
elektraFree (path);
}
typedef struct
{
char * branchName;
git_oid * oid;
} fetch_cb_data;
static int fetchhead_ref_cb (const char * name, const char * url ELEKTRA_UNUSED, const git_oid * oid, unsigned int is_merge, void * payload)
{
if (is_merge)
{
fetch_cb_data * data = payload;
data->branchName = elektraStrDup (name);
data->oid = elektraCalloc (sizeof (git_oid));
memcpy (data->oid, oid, sizeof (git_oid));
}
return 0;
}
typedef enum
{
ERROR,
NONE,
NORMAL,
UPTODATE,
FASTFORWARD,
UNBORN,
} MergeAnalysis;
static MergeAnalysis mergeAnalysis (git_repository * repo, const git_annotated_commit ** heads)
{
git_merge_analysis_t analysis;
git_merge_preference_t preference;
int rc = git_merge_analysis (&analysis, &preference, repo, (const git_annotated_commit **) heads, 1);
if (rc < 0)
{
return ERROR;
}
if (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD)
{
return FASTFORWARD;
}
else if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE)
{
return UPTODATE;
}
else if (analysis & GIT_MERGE_ANALYSIS_NORMAL)
{
return NORMAL;
}
else if (analysis & GIT_MERGE_ANALYSIS_NONE)
{
return NONE;
}
else if (analysis & GIT_MERGE_ANALYSIS_UNBORN)
{
return UNBORN;
}
else
{
return ERROR;
}
}
static int doMerge (git_repository * repo, const git_annotated_commit ** heads)
{
git_merge_options mergeOpts = { GIT_MERGE_OPTIONS_VERSION, .flags = GIT_MERGE_FAIL_ON_CONFLICT };
git_checkout_options checkoutOpts = { GIT_CHECKOUT_OPTIONS_VERSION, .checkout_strategy = GIT_CHECKOUT_FORCE };
int rc = git_merge (repo, (const git_annotated_commit **) heads, 1, &mergeOpts, &checkoutOpts);
if (rc < 0)
{
return -1;
}
return 0;
}
static int setFFTarget (git_repository * repo, git_oid * oid)
{
git_reference * out;
git_reference * ref;
git_repository_head (&ref, repo);
int rc = git_reference_set_target (&out, ref, oid, "fastforward");
if (rc)
{
return -1;
}
return 0;
}
static int ELEKTRA_UNUSED hasMergeConflicts (git_repository * repo)
{
git_index * cIdx;
int hasConflicts = 0;
git_repository_index (&cIdx, repo);
hasConflicts = git_index_has_conflicts (cIdx);
git_index_free (cIdx);
if (hasConflicts)
{
return -1;
}
return 0;
}
static int pullFromRemote (GitData * data ELEKTRA_UNUSED, git_repository * repo)
{
git_remote * remote;
int rc = git_remote_lookup (&remote, repo, "origin");
if (rc < 0)
{
return -1;
}
rc = git_remote_fetch (remote, NULL, NULL, NULL);
if (rc < 0)
{
return -1;
}
fetch_cb_data * cb_data = elektraCalloc (sizeof (fetch_cb_data));
git_repository_fetchhead_foreach (repo, fetchhead_ref_cb, cb_data);
git_annotated_commit * heads[1];
rc = git_annotated_commit_lookup (&heads[0], repo, cb_data->oid);
if (rc < 0)
{
return -1;
}
MergeAnalysis res = mergeAnalysis (repo, (const git_annotated_commit **) heads);
rc = 0;
switch (res)
{
case ERROR:
case UNBORN:
rc = -1;
goto PULL_CLEANUP;
break;
case NONE:
goto PULL_CLEANUP;
break;
case UPTODATE:
goto PULL_CLEANUP;
break;
case FASTFORWARD:
rc = doMerge (repo, (const git_annotated_commit **) heads);
if (rc)
{
goto PULL_CLEANUP;
}
rc = setFFTarget (repo, cb_data->oid);
if (rc)
{
goto PULL_CLEANUP;
}
rc = 0;
break;
case NORMAL:
// rc = doMerge(repo, heads);
// if(rc)
//{
// goto PULL_CLEANUP;
//}
// rc = hasMergeConflicts(repo);
// if(rc)
//{
// goto PULL_CLEANUP;
//}
rc = -1;
goto PULL_CLEANUP;
break;
default:
rc = -1;
goto PULL_CLEANUP;
break;
}
PULL_CLEANUP:
git_annotated_commit_free (heads[0]);
git_repository_state_cleanup (repo);
return rc;
}
int elektraGitresolverGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey)
{
if (!elektraStrCmp (keyName (parentKey), "system:/elektra/modules/gitresolver"))
{
KeySet * contract = ksNew (
30, keyNew ("system:/elektra/modules/gitresolver", KEY_VALUE, "gitresolver plugin waits for your orders", KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports", KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/open", KEY_FUNC, elektraGitresolverOpen, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/close", KEY_FUNC, elektraGitresolverClose, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/get", KEY_FUNC, elektraGitresolverGet, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/set", KEY_FUNC, elektraGitresolverSet, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/commit", KEY_FUNC, elektraGitresolverCommit, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/error", KEY_FUNC, elektraGitresolverError, KEY_END),
keyNew ("system:/elektra/modules/gitresolver/exports/checkfile", KEY_FUNC, elektraGitresolverCheckFile, KEY_END),
#include ELEKTRA_README
keyNew ("system:/elektra/modules/gitresolver/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; // success
}
// get all keys
if (initData (handle, parentKey)) return -1;
GitData * data = elektraPluginGetData (handle);
git_repository * repo = connectToLocalRepo (data);
if (!repo)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to open Repository %s\n", data->repo);
git_libgit2_shutdown ();
return -1;
}
genCheckoutFileName (data);
// TODO: check for empty repo and initialize repo
git_reference * headRef = getHeadRef (data, repo);
if (!headRef)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to get reference %s\n", data->refName);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
if (data->pull)
{
int rc = pullFromRemote (data, repo);
if (rc)
{
ELEKTRA_SET_CONFLICTING_STATE_ERROR (parentKey, "Fast-forward pull failed, please pull manually\n");
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
}
const git_oid * headObj = git_reference_target (headRef);
if (!headObj)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to get reference %s\n", data->refName);
git_reference_free (headRef);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
if (data->tracking == HEAD)
{
char * newCommit = hasNewCommit (data, headObj);
if (data->headID && !newCommit)
{
// still newest commit, no need to update
git_reference_free (headRef);
git_repository_free (repo);
git_libgit2_shutdown ();
return 0;
}
else if (data->headID && newCommit)
{
elektraFree (data->headID);
data->headID = newCommit;
}
else
{
data->headID = newCommit;
}
elektraPluginSetData (handle, data);
data = elektraPluginGetData (handle);
}
git_reference_free (headRef);
git_object * blob = getBlob (data, repo);
if (!blob)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "File %s not found in repository %s\n", data->file, data->repo);
git_repository_free (repo);
git_libgit2_shutdown ();
return 0;
}
if (data->tracking == OBJECT)
{
char * newObj = hasNewObjectCommit (data, blob);
if (!newObj)
{
git_object_free (blob);
git_repository_free (repo);
git_libgit2_shutdown ();
return 0;
}
else
{
if (data->objID)
{
elektraFree (data->objID);
data->objID = newObj;
}
else
{
data->objID = newObj;
}
}
elektraPluginSetData (handle, data);
data = elektraPluginGetData (handle);
}
FILE * outFile;
if (!data->checkout)
{
keySetString (parentKey, data->tmpFile);
}
else
{
keySetString (parentKey, data->repo);
if (data->subdirs) makePath (data);
}
outFile = fopen (keyString (parentKey), "w+");
if (!outFile)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to check out file %s to %s\n", data->file, keyString (parentKey));
git_object_free (blob);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
fwrite (git_blob_rawcontent ((git_blob *) blob), (size_t) git_blob_rawsize ((git_blob *) blob), 1, outFile);
unsigned char * hash = hashBuffer (git_blob_rawcontent ((git_blob *) blob), git_blob_rawsize ((git_blob *) blob));
if (!*(data->lastHash)) memcpy (data->lastHash, hash, MD5_DIGEST_LENGTH);
elektraFree (hash);
fclose (outFile);
git_object_free (blob);
git_repository_free (repo);
git_libgit2_shutdown ();
return 1; // success
}
static git_blob * addFileToIndex (git_repository * repo, GitData * data, git_index * index)
{
git_blob * blob = NULL;
git_oid blobID;
memset (&blobID, 0, sizeof (git_oid));
git_index_entry ie;
memset (&ie, 0, sizeof (git_index_entry));
ie.path = data->repo + elektraStrLen (data->workdir) - 1;
ie.mode = GIT_FILEMODE_BLOB;
git_blob_create_fromdisk (&blobID, repo, data->tmpFile);
git_blob_lookup (&blob, repo, &blobID);
git_index_add_frombuffer (index, &ie, git_blob_rawcontent (blob), git_blob_rawsize (blob));
return blob;
}
static int moveFile (const char * source, const char * dest)
{
FILE * inFile = NULL;
FILE * outFile = NULL;
struct stat buf;
if (stat (source, &buf) == -1) return -1;
size_t fileSize = buf.st_size;
char * buffer = elektraMalloc (fileSize);
inFile = fopen (source, "rb");
size_t bytesRead = 0;
while (bytesRead < fileSize)
{
size_t bytes = fread (buffer + bytesRead, 1, (size_t) fileSize, inFile);
if (bytes == 0) break;
bytesRead += bytes;
}
if (bytesRead < fileSize)
{
elektraFree (buffer);
fclose (inFile);
return -1;
}
fclose (inFile);
outFile = fopen (dest, "wb+");
size_t bytesWritten = 0;
while (bytesWritten < fileSize)
{
size_t bytes = fwrite (buffer, 1, fileSize, outFile);
if (bytes == 0) break;
bytesWritten += bytes;
}
fclose (outFile);
elektraFree (buffer);
if (bytesWritten < fileSize)
{
return -1;
}
unlink (source);
return 0;
}
int elektraGitresolverSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
// get all keys
// this function is optional
GitData * data = elektraPluginGetData (handle);
if (!data) return -1;
keySetString (parentKey, data->tmpFile);
git_repository * repo = connectToLocalRepo (data);
if (!repo)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to open Repository %s\n", data->repo);
git_libgit2_shutdown ();
return -1;
}
git_reference * headRef = getHeadRef (data, repo);
if (!headRef)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to get reference %s\n", data->refName);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
const git_oid * headObj = git_reference_target (headRef);
if (!headObj)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Failed to get reference %s\n", data->refName);
git_reference_free (headRef);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
if (data->tracking == HEAD)
{
char * newCommit = hasNewCommit (data, headObj);
if (newCommit)
{
// newer commit in repo - abort
ELEKTRA_SET_CONFLICTING_STATE_ERROR (parentKey, "The repository has been updated and is ahead of you");
elektraFree (newCommit);
git_reference_free (headRef);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
elektraFree (newCommit);
}
git_reference_free (headRef);
if (data->tracking == OBJECT)
{
git_object * blob = getBlob (data, repo);
if (blob)
{
char * newObj = hasNewObjectCommit (data, blob);
if (newObj)
{
ELEKTRA_SET_CONFLICTING_STATE_ERROR (parentKey, "The repository has been updated and is ahead of you");
elektraFree (newObj);
git_object_free (blob);
git_repository_free (repo);
git_libgit2_shutdown ();
return -1;
}
git_object_free (blob);
}
}
if (!data->setPhase)
{
++(data->setPhase);
}
else if (data->setPhase == 1)
{
// get repo index
git_index * index;
git_repository_index (&index, repo);
// add file
git_blob * buffer = addFileToIndex (repo, data, index);
unsigned char * hash = hashBuffer ((unsigned char *) git_blob_rawcontent (buffer), git_blob_rawsize (buffer));
if (!strncmp ((char *) data->lastHash, (char *) hash, MD5_DIGEST_LENGTH))
{
elektraFree (hash);
git_index_free (index);
git_blob_free (buffer);
git_repository_free (repo);
git_libgit2_shutdown ();
return 0;
}
elektraFree (hash);
git_index_write (index);
// get tree id
git_oid treeID;
git_index_write_tree (&treeID, index);
// get parent commit
git_oid parentID;
git_commit * parent;
git_reference_name_to_id (&parentID, repo, "HEAD");
git_commit_lookup (&parent, repo, &parentID);
// extract default git user
git_signature * sig;
int rc = git_signature_default (&sig, repo);
if (rc == GIT_ENOTFOUND)
{
git_signature_now (&sig, "Elektra", "@libelektra.org");
}
// get git tree
git_tree * tree;
git_tree_lookup (&tree, repo, &treeID);
// create default commit
git_oid commitID;
git_commit_create (&commitID, repo, "HEAD", sig, sig, NULL, "kdb git autocommit", tree, 1, (const git_commit **) &parent);
git_signature_free (sig);
git_tree_free (tree);
git_index_free (index);
git_blob_free (buffer);
git_commit_free (parent);
if (data->checkout)
{
moveFile (data->tmpFile, data->repo);
}
}
elektraPluginSetData (handle, data);
git_repository_free (repo);
git_libgit2_shutdown ();
return 1; // success
}
int elektraGitresolverError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
// set all keys
// this function is optional
return 1; // success
}
int elektraGitresolverCommit (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
return elektraGitresolverSet (handle, returned, parentKey);
}
Plugin * ELEKTRA_PLUGIN_EXPORT
{
// clang-format off
return elektraPluginExport ("gitresolver",
ELEKTRA_PLUGIN_OPEN, &elektraGitresolverOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraGitresolverClose,
ELEKTRA_PLUGIN_GET, &elektraGitresolverGet,
ELEKTRA_PLUGIN_SET, &elektraGitresolverSet,
ELEKTRA_PLUGIN_ERROR, &elektraGitresolverError,
ELEKTRA_PLUGIN_COMMIT, &elektraGitresolverCommit,
ELEKTRA_PLUGIN_END);
}