-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathgit.py
1353 lines (1039 loc) · 46.3 KB
/
git.py
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2020 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Santiago Dueñas <[email protected]>
# Valerio Cosentino <[email protected]>
# Israel Herraiz <[email protected]>
# anveshc05 <[email protected]>
# Jesus M. Gonzalez-Barahona <[email protected]>
# Harshal Mittal <[email protected]>
# Victor Morales <[email protected]>
# animesh <[email protected]>
#
import collections
import io
import logging
import os
import re
import subprocess
import threading
import dulwich.client
import dulwich.repo
from grimoirelab_toolkit.datetime import datetime_to_utc, str_to_datetime
from ...backend import (Backend,
BackendCommand,
BackendCommandArgumentParser)
from ...errors import RepositoryError, ParseError
from ...utils import DEFAULT_DATETIME, DEFAULT_LAST_DATETIME
CATEGORY_COMMIT = 'commit'
logger = logging.getLogger(__name__)
class Git(Backend):
"""Git backend.
This class allows the fetch the commits from a Git repository
(local or remote) or from a log file. To initialize this class,
you have to provide the URI repository and a value for `gitpath`.
This `uri` will be set as the origin of the data.
When `gitpath` is a directory or does not exist, it will be
considered as the place where the repository is/will be cloned;
when `gitpath` is a file it will be considered as a Git log file.
:param uri: URI of the Git repository
:param gitpath: path to the repository or to the log file
:param tag: label used to mark the data
:param archive: archive to store/retrieve items
:param ssl_verify: enable/disable SSL verification
:raises RepositoryError: raised when there was an error cloning or
updating the repository.
"""
version = '0.12.1'
CATEGORIES = [CATEGORY_COMMIT]
def __init__(self, uri, gitpath, tag=None, archive=None, ssl_verify=True):
origin = uri
super().__init__(origin, tag=tag, archive=archive, ssl_verify=ssl_verify)
self.uri = uri
self.gitpath = gitpath
def fetch(self, category=CATEGORY_COMMIT, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME,
branches=None, latest_items=False, no_update=False):
"""Fetch commits.
The method retrieves from a Git repository or a log file
a list of commits. Commits are returned in the same order
they were obtained.
When `from_date` parameter is given it returns items committed
since the given date.
The list of `branches` is a list of strings, with the names of
the branches to fetch. If the list of branches is empty, no
commit is fetched. If the list of branches is None, all commits
for all branches will be fetched.
The parameter `latest_items` returns only those commits which
are new since the last time this method was called.
The parameter `no_update` returns all commits without performing
an update of the repository before.
Take into account that `from_date` and `branches` are ignored
when the commits are fetched from a Git log file or when
`latest_items` flag is set.
The class raises a `RepositoryError` exception when an error
occurs accessing the repository.
:param category: the category of items to fetch
:param from_date: obtain commits newer than a specific date
(inclusive)
:param to_date: obtain commits older than a specific date
:param branches: names of branches to fetch from (default: None)
:param latest_items: sync with the repository to fetch only the
newest commits
:param no_update: if enabled, don't update the repo with the latest changes
:returns: a generator of commits
"""
if not from_date:
from_date = DEFAULT_DATETIME
if not to_date:
to_date = DEFAULT_LAST_DATETIME
kwargs = {
'from_date': from_date,
'to_date': to_date,
'branches': branches,
'latest_items': latest_items,
'no_update': no_update
}
items = super().fetch(category, **kwargs)
return items
def fetch_items(self, category, **kwargs):
"""Fetch the commits
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
to_date = kwargs['to_date']
branches = kwargs['branches']
latest_items = kwargs['latest_items']
no_update = kwargs['no_update']
ncommits = 0
try:
if os.path.isfile(self.gitpath):
commits = self.__fetch_from_log()
else:
commits = self.__fetch_from_repo(from_date, to_date, branches,
latest_items, no_update)
for commit in commits:
yield commit
ncommits += 1
except EmptyRepositoryError:
pass
logger.info("Fetch process completed: %s commits fetched",
ncommits)
@classmethod
def has_archiving(cls):
"""Returns whether it supports archiving items on the fetch process.
:returns: this backend does not support items archive
"""
return False
@classmethod
def has_resuming(cls):
"""Returns whether it supports to resume the fetch process.
:returns: this backend supports items resuming
"""
return True
@staticmethod
def metadata_id(item):
"""Extracts the identifier from a Git item."""
return item['commit']
@staticmethod
def metadata_updated_on(item):
"""Extracts the update time from a Git item.
The timestamp used is extracted from 'CommitDate' field.
This date is converted to UNIX timestamp format taking into
account the timezone of the date.
:param item: item generated by the backend
:returns: a UNIX timestamp
"""
ts = item['CommitDate']
ts = str_to_datetime(ts)
return ts.timestamp()
@staticmethod
def metadata_category(item):
"""Extracts the category from a Git item.
This backend only generates one type of item which is
'commit'.
"""
return CATEGORY_COMMIT
@staticmethod
def parse_git_log_from_file(filepath):
"""Parse a Git log file.
The method parses the Git log file and returns an iterator of
dictionaries. Each one of this, contains a commit.
:param filepath: path to the log file
:returns: a generator of parsed commits
:raises ParseError: raised when the format of the Git log file
is invalid
:raises OSError: raised when an error occurs reading the
given file
"""
with open(filepath, 'r', errors='surrogateescape',
newline=os.linesep) as f:
parser = GitParser(f)
for commit in parser.parse():
yield commit
@staticmethod
def parse_git_log_from_iter(iterator):
"""Parse a Git log obtained from an iterator.
The method parses the Git log fetched from an iterator, where
each item is a line of the log. It returns and iterator of
dictionaries. Each dictionary contains a commit.
:param iterator: iterator of Git log lines
:raises ParseError: raised when the format of the Git log
is invalid
"""
parser = GitParser(iterator)
for commit in parser.parse():
yield commit
def _init_client(self, from_archive=False):
pass
def __fetch_from_log(self):
logger.info("Fetching commits: '%s' git repository from log file %s",
self.uri, self.gitpath)
return self.parse_git_log_from_file(self.gitpath)
def __fetch_from_repo(self, from_date, to_date, branches, latest_items=False, no_update=False):
# When no latest items are set or the repository has not
# been cloned use the default mode
default_mode = not latest_items or not os.path.exists(self.gitpath)
repo = self.__create_git_repository()
if default_mode:
commits = self.__fetch_commits_from_repo(repo, from_date, to_date, branches, no_update)
else:
commits = self.__fetch_newest_commits_from_repo(repo)
return commits
def __fetch_commits_from_repo(self, repo, from_date, to_date, branches, no_update):
if branches is None:
branches_text = "all"
elif len(branches) == 0:
branches_text = "no"
else:
branches_text = ", ".join(branches)
logger.info("Fetching commits: '%s' git repository from %s to %s; %s branches",
self.uri, str(from_date), str(to_date), branches_text)
# Ignore default datetime to avoid problems with git
# or convert to UTC
if to_date == DEFAULT_LAST_DATETIME:
to_date = None
else:
to_date = datetime_to_utc(to_date)
if from_date == DEFAULT_DATETIME:
from_date = None
else:
from_date = datetime_to_utc(from_date)
if not no_update:
repo.update()
gitlog = repo.log(from_date, to_date, branches)
return self.parse_git_log_from_iter(gitlog)
def __fetch_newest_commits_from_repo(self, repo):
logger.info("Fetching latest commits: '%s' git repository",
self.uri)
hashes = repo.sync()
if not hashes:
return []
gitshow = repo.show(hashes)
return self.parse_git_log_from_iter(gitshow)
def __create_git_repository(self):
if not os.path.exists(self.gitpath):
repo = GitRepository.clone(self.uri, self.gitpath, self.ssl_verify)
elif os.path.isdir(self.gitpath):
repo = GitRepository(self.uri, self.gitpath)
return repo
class GitCommand(BackendCommand):
"""Class to run Git backend from the command line."""
BACKEND = Git
def _pre_init(self):
"""Initialize repositories directory path"""
if self.parsed_args.git_log:
git_path = self.parsed_args.git_log
elif self.parsed_args.git_path:
git_path = self.parsed_args.git_path
else:
if self.parsed_args.base_path:
base_path = self.parsed_args.base_path
else:
base_path = os.path.expanduser('~/.perceval/repositories/')
processed_uri = self.parsed_args.uri.lstrip('/')
git_path = os.path.join(base_path, processed_uri) + '-git'
setattr(self.parsed_args, 'gitpath', git_path)
@classmethod
def setup_cmd_parser(cls):
"""Returns the Git argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND,
from_date=True,
to_date=True,
ssl_verify=True)
# Optional arguments
group = parser.parser.add_argument_group('Git arguments')
group.add_argument('--branches', dest='branches',
nargs='+', type=str, default=None,
help="Fetch commits only from these branches")
# Mutual exclusive parameters
exgroup = group.add_mutually_exclusive_group()
exgroup.add_argument('--base-path', dest='base_path',
help="Base path where the Git repositories will be cloned")
exgroup.add_argument('--git-path', dest='git_path',
help="Path where the Git repository will be cloned")
exgroup.add_argument('--git-log', dest='git_log',
help="Path to the Git log file")
exgroup_fetch = group.add_mutually_exclusive_group()
exgroup_fetch.add_argument('--latest-items', dest='latest_items',
action='store_true',
help="Fetch latest commits added to the repository")
exgroup_fetch.add_argument('--no-update', dest='no_update',
action='store_true',
help="Fetch all commits without updating the repository")
# Required arguments
parser.parser.add_argument('uri',
help="URI of the Git log repository")
return parser
class GitParser:
"""Git log parser.
This class parses a plain Git log stream, converting plain commits
into dict items.
Not every Git log output is valid to be parsed. The Git log stream
must have a specific structure. It must contain raw commits data and
stats about modified files. The next excerpt shows an example of a
valid log:
commit aaa7a9209f096aaaadccaaa7089aaaa3f758a703
Author: John Smith <[email protected]>
AuthorDate: Tue Aug 14 14:30:13 2012 -0300
Commit: John Smith <[email protected]>
CommitDate: Tue Aug 14 14:30:13 2012 -0300
Commit for testing
:000000 100644 0000000... aaaaaaa... A aaa/otherthing
:000000 100644 0000000... aaaaaaa... A aaa/something
:000000 100644 0000000... aaaaaaa... A bbb/bthing
0 0 aaa/otherthing
0 0 aaa/something
0 0 bbb/bthing
Each commit starts with the 'commit' tag that is followed by the
SHA-1 of the commit, its parents (two or more parents in the case
of a merge) and a list of refs, if any.
commit 456a68ee1407a77f3e804a30dff245bb6c6b872f
ce8e0b86a1e9877f42fe9453ede418519115f367
51a3b654f252210572297f47597b31527c475fb8
(HEAD -> refs/heads/master)
The commit line is followed by one or more headers. Each header
has a key and a value:
Author: John Smith <[email protected]>
AuthorDate: Tue Aug 14 14:30:13 2012 -0300
Commit: John Smith <[email protected]>
CommitDate: Tue Aug 14 14:30:13 2012 -0300
Then, an empty line divides the headers from the commit message.
First line of the commit
Commit message splitted into one or several lines.
Each line of the message stars with 4 spaces.
Commit messages can contain a list of 'trailers'. These trailers
have the same format of headers but their meaning is project
dependent. This is an example of a commit message with trailers:
Commit message with trailers
This is the body of the message where trailers are included.
Trailers are part of the body so each line of the message
stars with 4 spaces.
Signed-off-by: John Doe <[email protected]>
Signed-off-by: Jane Rae <[email protected]>
After a new empty line, actions and stats over files can be found.
A action line starts with one or more ':' chars and contain data
about the old and new permissions of a file, its old and new indexes,
the action code and the filepath to the file. In the case of a copied,
renamed or moved file, the new filepath to that file is included.
:100644 100644 e69de29... e69de29... R100 aaa/otherthing aaa/otherthing.renamed
Stats lines include the number of lines added and removed, and the
name of the file. The new name is also included for moved or renamed
files.
10 0 aaa/{otherthing => otherthing.renamed}
The commit ends with an empty line.
Take into account that one empty line is valid at the beginning
of the log. This allows to parse empty logs without raising
exceptions.
This example was generated using the next command:
git log --raw --numstat --pretty=fuller --decorate=full \
--parents -M -C -c --remotes=origin --all
:param stream: a file object which stores the log
"""
COMMIT_PATTERN = r"""^commit[ \t](?P<commit>[a-f0-9]{40})
(?:[ \t](?P<parents>[a-f0-9][a-f0-9 \t]+))?
(?:[ \t]\((?P<refs>.+)\))?$
"""
HEADER_TRAILER_PATTERN = r"^(?P<name>[a-zA-z0-9\-]+)\:[ \t]+(?P<value>.+)$"
MESSAGE_LINE_PATTERN = r"^[\s]{4}(?P<msg>.*)$"
ACTION_PATTERN = r"""^(?P<sc>\:+)
(?P<modes>(?:\d{6}[ \t])+)
(?P<indexes>(?:[a-f0-9]+\.{,3}[ \t])+)
(?P<action>[^\t]+)\t+
(?P<file>[^\t]+)
(?:\t+(?P<newfile>.+))?$"""
STATS_PATTERN = r"^(?P<added>\d+|-)[ \t]+(?P<removed>\d+|-)[ \t]+(?P<file>.+)$"
EMPTY_LINE_PATTERN = r"^$"
# Compiled patterns
GIT_COMMIT_REGEXP = re.compile(COMMIT_PATTERN, re.VERBOSE)
GIT_HEADER_TRAILER_REGEXP = re.compile(HEADER_TRAILER_PATTERN, re.VERBOSE)
GIT_MESSAGE_REGEXP = re.compile(MESSAGE_LINE_PATTERN, re.VERBOSE)
GIT_ACTION_REGEXP = re.compile(ACTION_PATTERN, re.VERBOSE)
GIT_STATS_REGEXP = re.compile(STATS_PATTERN, re.VERBOSE)
GIT_NEXT_STATE_REGEXP = re.compile(EMPTY_LINE_PATTERN, re.VERBOSE)
# Git parser status
(INIT,
COMMIT,
HEADER,
MESSAGE,
FILE) = range(5)
# Git trailers
TRAILERS = ['Signed-off-by']
def __init__(self, stream):
self.stream = stream
self.nline = 0
self.state = self.INIT
# Aux vars to store the commit that is being parsed
self.commit = None
self.commit_files = {}
self.handlers = {
self.INIT: self._handle_init,
self.COMMIT: self._handle_commit,
self.HEADER: self._handle_header,
self.MESSAGE: self._handle_message,
self.FILE: self._handle_file
}
def parse(self):
"""Parse the Git log stream."""
for line in self.stream:
line = line.rstrip('\n')
parsed = False
self.nline += 1
while not parsed:
parsed = self.handlers[self.state](line)
if self.state == self.COMMIT and self.commit:
commit = self._build_commit()
logger.debug("Commit %s parsed", commit['commit'])
yield commit
# Return the last commit, if any
if self.commit:
commit = self._build_commit()
logger.debug("Commit %s parsed", commit['commit'])
yield commit
def _build_commit(self):
def remove_none_values(d):
return {k: v for k, v in d.items() if v is not None}
commit = self.commit
commit = remove_none_values(commit)
commit['files'] = [remove_none_values(item)
for _, item in sorted(self.commit_files.items())]
self.commit = None
self.commit_files = {}
return commit
def _handle_init(self, line):
m = self.GIT_NEXT_STATE_REGEXP.match(line)
# In both cases, the parser advances to the next state.
# It only has to check whether the line has to be parsed
# again or not
self.state = self.COMMIT
parsed = m is not None
return parsed
def _handle_commit(self, line):
m = self.GIT_COMMIT_REGEXP.match(line)
if not m:
msg = "commit expected on line %s" % (str(self.nline))
raise ParseError(cause=msg)
parents = self.__parse_data_list(m.group('parents'))
refs = self.__parse_data_list(m.group('refs'), sep=',')
# Initialize a new commit
self.commit = {}
self.commit['commit'] = m.group('commit')
self.commit['parents'] = parents
self.commit['refs'] = refs
self.state = self.HEADER
return True
def _handle_header(self, line):
m = self.GIT_NEXT_STATE_REGEXP.match(line)
if m:
self.state = self.MESSAGE
return True
m = self.GIT_HEADER_TRAILER_REGEXP.match(line)
if not m:
msg = "invalid header format on line %s" % (str(self.nline))
raise ParseError(cause=msg)
header = m.group('name')
value = m.group('value')
self.commit[header] = value
return True
def _handle_message(self, line):
m = self.GIT_NEXT_STATE_REGEXP.match(line)
if m:
self.state = self.FILE
return True
m = self.GIT_MESSAGE_REGEXP.match(line)
if not m:
logger.debug("Invalid message format on line %s. Skipping.",
str(self.nline))
self.state = self.FILE
return False
msg_line = m.group('msg')
# Concatenate message lines
if 'message' not in self.commit:
self.commit['message'] = ''
else:
self.commit['message'] += '\n'
self.commit['message'] += msg_line
# Check trailers
self._handle_trailer(msg_line)
return True
def _handle_file(self, line):
m = self.GIT_NEXT_STATE_REGEXP.match(line)
if m:
self.state = self.COMMIT
return True
m = self.GIT_ACTION_REGEXP.match(line)
if m:
data = m.groupdict()
self._handle_action_data(data)
return True
m = self.GIT_STATS_REGEXP.match(line)
if m:
data = m.groupdict()
self._handle_stats_data(data)
return True
# No match case
logger.debug("Invalid action format on line %s. Skipping.",
str(self.nline))
self.state = self.COMMIT
return False
def _handle_trailer(self, line):
m = self.GIT_HEADER_TRAILER_REGEXP.match(line)
if not m:
return
trailer = m.group('name')
value = m.group('value')
if trailer not in self.TRAILERS:
logger.debug("Trailer %s found on line %s but is not a core trailer. Skipping.",
trailer, str(self.nline))
return
self.commit.setdefault(trailer, []).append(value)
def _handle_action_data(self, data):
modes = self.__parse_data_list(data['modes'])
indexes = self.__parse_data_list(data['indexes'])
filename = data['file']
if filename not in self.commit_files:
self.commit_files[filename] = {}
self.commit_files[filename]['modes'] = modes
self.commit_files[filename]['indexes'] = indexes
self.commit_files[filename]['action'] = data['action']
self.commit_files[filename]['file'] = filename
self.commit_files[filename]['newfile'] = data['newfile']
def _handle_stats_data(self, data):
filename = self.__get_old_filepath(data['file'])
if filename not in self.commit_files:
self.commit_files[filename] = {'file': filename}
self.commit_files[filename]['added'] = data['added']
self.commit_files[filename]['removed'] = data['removed']
def __parse_data_list(self, data, sep=' '):
if data:
lst = data.strip().split(sep)
return [e.strip() for e in lst]
else:
return []
def __get_old_filepath(self, f):
"""Get the old filepath of a moved/renamed file.
Moved or renamed files can be found in the log with any of the
next patterns:
'old_name => new_name'
'{old_prefix => new_prefix}/name'
'name/{old_suffix => new_suffix}'
This method returns the filepath before the file was moved or
renamed.
"""
i = f.find('{')
j = f.find('}')
if i > -1 and j > -1:
prefix = f[0:i]
inner = f[i + 1:f.find(' => ', i)]
suffix = f[j + 1:]
return prefix + inner + suffix
elif ' => ' in f:
return f.split(' => ')[0]
else:
return f
class EmptyRepositoryError(RepositoryError):
"""Exception raised when a repository is empty"""
message = "%(repository)s is empty"
GitRef = collections.namedtuple('GitRef', ['hash', 'refname'])
class _GraphWalker:
"""Commit walker needed by fetch_pack"""
def __init__(self, local_refs):
self.heads = [
ref.hash.encode('utf-8') for ref in local_refs
if ref.refname.startswith('refs/heads/')
]
def ack(self, sha):
pass
def next(self):
if self.heads:
ret = self.heads.pop()
return ret
return None
__next__ = next
class GitRepository:
"""Manage a Git repository.
This class provides access to a Git repository running some
common commands such as `clone`, `pull` or `log`.
To create an instance from a remote repository, use `clone()`
class method.
:param uri: URI of the repository
:param dirpath: local directory where the repository is stored
"""
GIT_PRETTY_OUTPUT_OPTS = [
'--raw', # show data in raw format
'--numstat', # show added/deleted lines per file
'--pretty=fuller', # pretty output
'--decorate=full', # show full refs
'--parents', # show parents information
'-M', # detect and report renames
'-C', # detect and report copies
'-c', # show merge info
]
def __init__(self, uri, dirpath):
gitdir = os.path.join(dirpath, 'HEAD')
if not os.path.exists(dirpath):
cause = "directory '%s' for Git repository '%s' does not exist" % (dirpath, uri)
raise RepositoryError(cause=cause)
elif not os.path.exists(gitdir):
warning = "Working directories for Git repositories no longer supported." \
"Please remove it or clone it using --mirror option."
logger.warning(warning)
cause = "directory '%s' is not a Git mirror of repository '%s'" % (dirpath, uri)
raise RepositoryError(cause=cause)
self.uri = uri
self.dirpath = dirpath
self.gitenv = {
'LANG': 'C',
'PAGER': '',
'HTTP_PROXY': os.getenv('HTTP_PROXY', ''),
'HTTPS_PROXY': os.getenv('HTTPS_PROXY', ''),
'NO_PROXY': os.getenv('NO_PROXY', ''),
'HOME': os.getenv('HOME', '')
}
@classmethod
def clone(cls, uri, dirpath, ssl_verify=True):
"""Clone a Git repository.
Make a bare copy of the repository stored in `uri` into `dirpath`.
The repository would be either local or remote.
:param uri: URI of the repository
:param dirpath: directory where the repository will be cloned
:param ssl_verify: enable/disable SSL verification
:returns: a `GitRepository` class having cloned the repository
:raises RepositoryError: when an error occurs cloning the given
repository
"""
cmd = ['git', 'clone', '--bare', uri, dirpath]
if not ssl_verify:
cmd += ['-c', 'http.sslVerify=false']
env = {
'LANG': 'C',
'HOME': os.getenv('HOME', '')
}
cls._exec(cmd, env=env)
logger.debug("Git %s repository cloned into %s",
uri, dirpath)
return cls(uri, dirpath)
def count_objects(self):
"""Count the objects of a repository.
The method returns the total number of objects (packed and unpacked)
available on the repository.
:raises RepositoryError: when an error occurs counting the objects
of a repository
"""
cmd_count = ['git', 'count-objects', '-v']
outs = self._exec(cmd_count, cwd=self.dirpath, env=self.gitenv)
outs = outs.decode('utf-8', errors='surrogateescape').rstrip()
try:
cobjs = {k: v for k, v in (x.split(': ') for x in outs.split('\n'))}
nobjs = int(cobjs['count']) + int(cobjs['in-pack'])
except KeyError as e:
error = "unable to parse 'count-objects' output; reason: '%s' entry not found" \
% e.args[0]
raise RepositoryError(cause=error)
except ValueError as e:
error = "unable to parse 'count-objects' output; reason: %s" % str(e)
raise RepositoryError(cause=error)
logger.debug("Git %s repository has %s objects",
self.uri, str(nobjs))
return nobjs
def is_detached(self):
"""Check if the repo is in a detached state.
The repository is in a detached state when HEAD is not a symbolic
reference.
:returns: whether the repository is detached or not
:raises RepositoryError: when an error occurs checking the state
of the repository
"""
cmd_sym = ['git', 'symbolic-ref', 'HEAD']
try:
self._exec(cmd_sym, cwd=self.dirpath, env=self.gitenv)
except RepositoryError as e:
if e.msg.find("ref HEAD is not a symbolic ref") == -1:
raise e
return True
else:
return False
def is_empty(self):
"""Determines whether the repository is empty or not.
Returns `True` when the repository is empty. Under the hood,
it checks the number of objects on the repository. When
this number is 0, the repositoy is empty.
:raises RepositoryError: when an error occurs accessing the
repository
"""
return self.count_objects() == 0
def update(self):
"""Update repository from its remote.
Calling this method, the repository will be synchronized with
the remote repository using 'fetch' command for 'heads' refs.
Any commit stored in the local copy will be removed; refs
will be overwritten.
:raises RepositoryError: when an error occurs updating the
repository
"""
cmd_update = ['git', 'fetch', 'origin', '+refs/heads/*:refs/heads/*', '--prune']
self._exec(cmd_update, cwd=self.dirpath, env=self.gitenv)
logger.debug("Git %s repository updated into %s",
self.uri, self.dirpath)
def sync(self):
"""Keep the repository in sync.
This method will synchronize the repository with its 'origin',
fetching newest objects and updating references. It uses low
level commands which allow to keep track of which things
have changed in the repository.
The method also returns a list of hashes related to the new
commits fetched during the process.
:returns: list of new commits
:raises RepositoryError: when an error occurs synchronizing
the repository
"""
pack_name, refs = self._fetch_pack()
if pack_name:
commits = self._read_commits_from_pack(pack_name)
else:
commits = []
logger.debug("Git repository %s (%s) does not have any new object",
self.uri, self.dirpath)
self._update_references(refs)
logger.debug("Git repository %s (%s) is synced",
self.uri, self.dirpath)
return commits
def rev_list(self, branches=None):
"""Read the list commits from the repository
The list of branches is a list of strings, with the names of the
branches to fetch. If the list of branches is empty, no commit
is fetched. If the list of branches is None, all commits
for all branches will be fetched.
The method returns the Git rev-list of the repository using the
following options:
git rev-list --topo-order
:param branches: names of branches to fetch from (default: None)
:raises EmptyRepositoryError: when the repository is empty and
the action cannot be performed
:raises RepositoryError: when an error occurs executing the command
"""
if self.is_empty():
logger.warning("Git %s repository is empty; unable to get the rev-list",
self.uri)
raise EmptyRepositoryError(repository=self.uri)
cmd_rev_list = ['git', 'rev-list', '--topo-order']
if branches is None:
cmd_rev_list.extend(['--branches', '--tags', '--remotes=origin'])
elif len(branches) == 0:
cmd_rev_list.extend(['--branches', '--tags', '--max-count=0'])
else:
branches = ['refs/heads/' + branch for branch in branches]
cmd_rev_list.extend(branches)
for line in self._exec_nb(cmd_rev_list, cwd=self.dirpath, env=self.gitenv):
yield line.rstrip('\n')