skilleter-modules 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1502 @@
1
+ #! /usr/bin/env python3
2
+
3
+ ################################################################################
4
+ """ Git module V2 - now implemented as a wrapper around pygit2 (work in progress)
5
+
6
+ Copyright (C) 2023 John Skilleter
7
+
8
+ Licence: GPL v3 or later
9
+
10
+ Except where stated otherwise, functions in this module:
11
+
12
+ * Return the output from the equivalent git command as an array of
13
+ strings.
14
+
15
+ * Functions will raise exceptions on error. If the underlying git command
16
+ returns an error, a git.GitError() exception is raised.
17
+
18
+ * TODO: [ ] Cache list of branches when git.branches/isbranch called
19
+ * TODO: [ ] API change - git_run_status should raise an exception on failure and just return the git output
20
+ """
21
+ ################################################################################
22
+
23
+ import os
24
+ import shutil
25
+ import sys
26
+ import re
27
+ import logging
28
+ import fnmatch
29
+ import subprocess
30
+
31
+ import pygit2
32
+
33
+ import run
34
+ import gitlab
35
+
36
+ ################################################################################
37
+ # Configuration files to access
38
+
39
+ (WORKTREE, LOCAL, GLOBAL, SYSTEM) = list(range(4))
40
+
41
+ # Options always passed to Git (disable autocorrect to stop it running the wrong command
42
+ # if an invalid command name has been specified).
43
+
44
+ STANDARD_GIT_OPTIONS = ['-c', 'help.autoCorrect=never']
45
+
46
+ # Default default branches (can be overridden in .gitconfig via skilleter-thingy.defaultBranches
47
+
48
+ DEFAULT_DEFAULT_BRANCHES = 'develop,main,master'
49
+
50
+ ################################################################################
51
+
52
+ class GitError(run.RunError):
53
+ """Run exception."""
54
+
55
+ def __init__(self, msg, exit_status=1):
56
+ super().__init__(msg, exit_status)
57
+
58
+ ################################################################################
59
+
60
+ def git(cmd, stdout=None, stderr=None, path=None):
61
+ """ Wrapper for run.run that raises a GitError instead of RunError
62
+ so that Git module users do not to include the run module just
63
+ to get the exception.
64
+ Optionally redirect stdout and stderr as specified. """
65
+
66
+ git_cmd = ['git'] + STANDARD_GIT_OPTIONS
67
+
68
+ if path:
69
+ git_cmd += ['-C', path]
70
+
71
+ git_cmd += cmd if isinstance(cmd, list) else [cmd]
72
+
73
+ logging.debug('Running %s', ' '.join(git_cmd))
74
+
75
+ sys.stdout.flush()
76
+ sys.stderr.flush()
77
+
78
+ try:
79
+ return run.run(git_cmd, stdout=stdout, stderr=stderr)
80
+ except run.RunError as exc:
81
+ raise GitError(exc.msg, exc.status) from exc
82
+ except FileNotFoundError as exc:
83
+ raise GitError(exc, 1)
84
+
85
+ ################################################################################
86
+
87
+ def git_run_status(cmd, stdout=None, stderr=None, path=None, redirect=True):
88
+ """ Wrapper for subprocess.run that returns the output and status, and
89
+ does not raise an exception on error.
90
+ Optionally redirect stdout and stderr as specified. """
91
+
92
+ logging.debug('Running git %s', ' '.join(cmd))
93
+
94
+ git_cmd = ['git'] + STANDARD_GIT_OPTIONS
95
+
96
+ if path:
97
+ git_cmd += ['-C', path]
98
+
99
+ git_cmd += cmd if isinstance(cmd, list) else [cmd]
100
+
101
+ sys.stdout.flush()
102
+ sys.stderr.flush()
103
+
104
+ if redirect:
105
+ result = subprocess.run(git_cmd,
106
+ stdout=stdout or subprocess.PIPE,
107
+ stderr=stderr or subprocess.PIPE,
108
+ text=True, check=False,
109
+ errors='ignore',
110
+ universal_newlines=True)
111
+ else:
112
+ result = subprocess.run(git_cmd, check=False)
113
+
114
+ return (result.stdout or result.stderr), result.returncode
115
+
116
+ ################################################################################
117
+
118
+ def clone(reponame, working_tree=None):
119
+ """ Clone a repo """
120
+
121
+ cmd = ['clone', reponame]
122
+
123
+ if working_tree:
124
+ cmd.append(working_tree)
125
+
126
+ return git(cmd)
127
+
128
+ ################################################################################
129
+
130
+ def init(reponame, bare=False, path=None):
131
+ """ Initialise a new working tree """
132
+
133
+ cmd = ['init']
134
+
135
+ if bare:
136
+ cmd.append('--bare')
137
+
138
+ cmd.append(reponame)
139
+
140
+ return git(cmd, path=path)
141
+
142
+ ################################################################################
143
+
144
+ def iscommit(commit, remote=False, remote_only=False, path=None):
145
+ """ Return True if "commit" is a valid SHA1, branch or tag
146
+ If remote==True then if there are no direct matches it will also
147
+ check for a matching remote branch
148
+ If remote_only==True, then ONLY remote branches will be checked."""
149
+
150
+ # Fail on empty commit
151
+
152
+ if not commit:
153
+ return False
154
+
155
+ # Optionally look for an exact matching local branch or commit
156
+
157
+ if not remote_only:
158
+ try:
159
+ git(['cat-file', '-t', commit], path=path)
160
+ return True
161
+
162
+ except GitError:
163
+ pass
164
+
165
+ # Optionally look for matching remote branch
166
+
167
+ if remote or remote_only:
168
+ for remote in remote_names(path=path):
169
+ try:
170
+ if git(['ls-remote', remote, commit], path=path):
171
+ return True
172
+
173
+ except GitError:
174
+ pass
175
+
176
+ # Nothing found
177
+
178
+ return False
179
+
180
+ ################################################################################
181
+
182
+ def branch(branchname='HEAD', path=None):
183
+ """ Return the name of the current git branch or None"""
184
+
185
+ try:
186
+ return git(['symbolic-ref', '--short', '-q', branchname], path=path)[0]
187
+ except GitError:
188
+ return None
189
+
190
+ ################################################################################
191
+
192
+ def tag(path=None):
193
+ """ If the current commit is tagged, return the tag(s) or None """
194
+
195
+ try:
196
+ return git(['describe', '--tags', '--exact-match'], path=path)[0]
197
+ except GitError:
198
+ return None
199
+
200
+ ################################################################################
201
+
202
+ def tags(path=None):
203
+ """ Return the list of tags in the current repo """
204
+
205
+ return git(['tag', '--list'], path=path)
206
+
207
+ ################################################################################
208
+
209
+ def tag_delete(tag, push=False, path=None):
210
+ """Delete a tag, optionally pushing the deletion"""
211
+
212
+ git(['tag', '-d', tag], path=path)
213
+
214
+ if push:
215
+ git(['push', 'origin', '--delete', tag], path=path)
216
+
217
+ ################################################################################
218
+
219
+ def tag_apply(tag, commit=None, push=False, path=None):
220
+ """Apply a tag, optionally pushing it"""
221
+
222
+ cmd = ['tag', tag]
223
+
224
+ if commit:
225
+ cmd.append(commit)
226
+
227
+ git(cmd, path=path)
228
+
229
+ if push:
230
+ git(['push', 'origin', tag], path=path)
231
+
232
+ ################################################################################
233
+
234
+ def current_commit(short=False, path=None):
235
+ """ Return the SHA1 of the current commit """
236
+
237
+ cmd = ['rev-parse']
238
+
239
+ if short:
240
+ cmd.append('--short')
241
+
242
+ cmd.append('HEAD')
243
+
244
+ return git(cmd, path=path)[0]
245
+
246
+ ################################################################################
247
+
248
+ def pull(repo=None, all=False, path=None):
249
+ """ Run a git pull """
250
+
251
+ cmd = ['pull']
252
+
253
+ if all:
254
+ cmd.append('--all')
255
+
256
+ if repo:
257
+ cmd.append(repo)
258
+
259
+ return git(cmd, path=path)
260
+
261
+ ################################################################################
262
+
263
+ def checkout(branch, create=False, commit=None, path=None):
264
+ """ Checkout a branch (optionally creating it or creating it from the
265
+ specified commit) """
266
+
267
+ cmd = ['checkout']
268
+
269
+ if create or commit:
270
+ cmd.append('-b')
271
+
272
+ cmd.append(branch)
273
+
274
+ if commit:
275
+ cmd.append(commit)
276
+
277
+ return git(cmd, path=path)
278
+
279
+ ################################################################################
280
+
281
+ def merge(branch, path=None):
282
+ """ Merge a branch """
283
+
284
+ cmd = ['merge', branch]
285
+
286
+ return git(cmd, path=path)
287
+
288
+ ################################################################################
289
+
290
+ def abort_merge(path=None):
291
+ """ Abort the current merge """
292
+
293
+ return git(['merge', '--abort'], path=path)
294
+
295
+ ################################################################################
296
+
297
+ def set_upstream(branch, upstream=None, path=None):
298
+ """ Set the default upstream branch """
299
+
300
+ if not upstream:
301
+ upstream = f'origin/{branch}'
302
+
303
+ cmd = ['branch', f'--set-upstream-to={upstream}', branch]
304
+
305
+ return git(cmd, path=path)
306
+
307
+ ################################################################################
308
+
309
+ def fetch(all=False, path=None):
310
+ """ Run git fetch """
311
+
312
+ cmd = ['fetch']
313
+
314
+ if all:
315
+ cmd.append('--all')
316
+
317
+ return git(cmd, path=path)
318
+
319
+ ################################################################################
320
+
321
+ def rebase_required(branch, parent, path=None):
322
+ """ Return True if the specified branch needs to be rebased against its
323
+ parent.
324
+ """
325
+
326
+ # Find the latest commit on the parent branch and the most recent commit
327
+ # that both branches have in common.
328
+
329
+ parent_tip = git(['show-ref', '--heads', '-s', parent], path=path)
330
+ common_commit = git(['merge-base', parent, branch], path=path)
331
+
332
+ # Different commits, so rebase is required
333
+
334
+ return parent_tip[0] != common_commit[0]
335
+
336
+ ################################################################################
337
+
338
+ def rebase(branch, path=None):
339
+ """ Rebase the current branch against the specified branch """
340
+
341
+ return git_run_status(['rebase', branch], path=path)
342
+
343
+ ################################################################################
344
+
345
+ def abort_rebase(path=None):
346
+ """ Abort the current rebase """
347
+
348
+ return git(['rebase', '--abort'], path=path)
349
+
350
+ ################################################################################
351
+
352
+ def rebasing(path=None):
353
+ """ Return True if currently rebasing, False otherwise """
354
+
355
+ gitdir = git_dir(path=path)
356
+
357
+ return os.path.isdir(os.path.join(gitdir, 'rebase-apply')) or \
358
+ os.path.isdir(os.path.join(gitdir, 'rebase-merge'))
359
+
360
+ ################################################################################
361
+
362
+ def bisecting(path=None):
363
+ """ Return True if currently rebasing, False otherwise """
364
+
365
+ gitdir = git_dir(path=path)
366
+
367
+ return os.path.isfile(os.path.join(gitdir, 'BISECT_START'))
368
+
369
+ ################################################################################
370
+
371
+ def merging(path=None):
372
+ """ Return True if currently merging, False otherwise """
373
+
374
+ gitdir = git_dir(path=path)
375
+
376
+ return os.path.isfile(os.path.join(gitdir, 'MERGE_MODE'))
377
+
378
+ ################################################################################
379
+
380
+ def remotes(path=None):
381
+ """ Return the list of git remotes """
382
+
383
+ repo = pygit2.Repository(git_dir(path=path))
384
+
385
+ git_remotes = {}
386
+
387
+ for name in repo.remotes.names():
388
+ git_remotes[name] = repo.remotes[name].url
389
+
390
+ return git_remotes
391
+
392
+ ################################################################################
393
+
394
+ def remote_names(path=None):
395
+ """ Return the list of remote names """
396
+
397
+ repo = pygit2.Repository(git_dir(path=path))
398
+
399
+ results = list(repo.remotes.names())
400
+
401
+ return results
402
+
403
+ ################################################################################
404
+
405
+ def project(short=False, path=None):
406
+ """ Return the name of the current git project """
407
+
408
+ git_remotes = remotes(path=path)
409
+ name = ''
410
+
411
+ for remote in git_remotes:
412
+ try:
413
+ if '//' in git_remotes[remote]:
414
+ name = git_remotes[remote].split('//')[-1].split('/', 1)[-1]
415
+ break
416
+
417
+ if '@' in git_remotes[remote]:
418
+ name = git_remotes[remote].split(':')[-1]
419
+ break
420
+
421
+ except ValueError:
422
+ continue
423
+
424
+ if name.endswith('.git'):
425
+ name = name[:-4]
426
+
427
+ if short:
428
+ name = os.path.basename(name)
429
+
430
+ return name
431
+
432
+ ################################################################################
433
+
434
+ def status_info(ignored=False, untracked=False, path=None, all_untracked=False):
435
+ """ Git status, optionally include files ignored in .gitignore and/or
436
+ untracked files.
437
+ Returns data in the same dictionary format as used by commit_info() """
438
+
439
+ cmd = ['status', '-z']
440
+
441
+ if ignored:
442
+ cmd.append('--ignored')
443
+
444
+ if all_untracked:
445
+ cmd.append('--untracked-files=all')
446
+
447
+ results = git(cmd, path=path)
448
+
449
+ # Dictionary of results, indexed by filename where the status is 2 characters
450
+ # the first representing the state of the file in the index and the second the state
451
+ # of the file in the working tree where:
452
+ # M=modified, A=added, D=deleted, R=renamed, C=copied, U=unmerged, ?=untracked, !=ignored
453
+ # Where a file has been renamed we don't report the original name
454
+
455
+ info = {}
456
+
457
+ if results:
458
+ result = results[0].split('\0')
459
+
460
+ for r in result:
461
+ if len(r) > 3 and r[2] == ' ':
462
+ git_status = r[0:2]
463
+ name = r[3:]
464
+
465
+ info[name] = git_status
466
+
467
+ return info
468
+
469
+ ################################################################################
470
+
471
+ def status(ignored=False, untracked=False, path=None, all_untracked=False):
472
+ """ Git status, optionally include files ignored in .gitignore and/or
473
+ untracked files.
474
+ Similar to status_info, but returns data as a list, rather than a
475
+ dictionary. """
476
+
477
+ cmd = ['status', '--porcelain']
478
+
479
+ if ignored:
480
+ cmd.append('--ignored')
481
+
482
+ if all_untracked:
483
+ cmd.append('--untracked-files=all')
484
+
485
+ results = git(cmd, path=path)
486
+
487
+ # Nested list of results. For each entry:
488
+ # item 0 is the status where: M=modified, A=added, D=deleted, R=renamed, C=copied, U=unmerged, ?=untracked, !=ignored
489
+ # item 1 is the name
490
+ # item 2 (if present) is the old name in cases where a file has been renamed.
491
+
492
+ # TODO: This can't handle the case where a file has ' -> ' in the filename
493
+ # TODO: This can't handle the case where a filename is enclosed in double quotes in the results
494
+
495
+ info = []
496
+
497
+ for result in results:
498
+ stats = []
499
+ stats.append(result[0:2])
500
+
501
+ if not untracked and result[0] == '?':
502
+ continue
503
+
504
+ name = result[3:]
505
+ if ' -> ' in name:
506
+ stats += name.split(' -> ', 1)
507
+ else:
508
+ stats.append(name)
509
+
510
+ info.append(stats)
511
+
512
+ return info
513
+
514
+ ################################################################################
515
+
516
+ def working_tree(path=None):
517
+ """ Location of the current working tree or None if we are not in a working tree """
518
+
519
+ repo_dir = git_dir(path=path)
520
+
521
+ if repo_dir:
522
+ return os.path.abspath(os.path.join(repo_dir, os.pardir))
523
+
524
+ return None
525
+
526
+ ################################################################################
527
+
528
+ def git_dir(path=None):
529
+ """ Return the relative path to the .git directory """
530
+
531
+ if not path:
532
+ path = os.getcwd()
533
+
534
+ return pygit2.discover_repository(path)
535
+
536
+ ################################################################################
537
+
538
+ def tree_path(filename, path=None):
539
+ """ Normalise a filename (absolute or relative to the current directory)
540
+ so that it is relative to the top-level directory of the working tree """
541
+
542
+ git_tree = working_tree(path=path)
543
+
544
+ return os.path.relpath(filename, git_tree)
545
+
546
+ ################################################################################
547
+
548
+ def difftool(commit_1=None, commit_2=None, files=None, tool=None, path=None):
549
+ """ Run git difftool """
550
+
551
+ cmd = ['difftool']
552
+
553
+ if tool:
554
+ cmd += ['--tool', tool]
555
+
556
+ if commit_1:
557
+ cmd.append(commit_1)
558
+
559
+ if commit_2:
560
+ cmd.append(commit_2)
561
+
562
+ if files:
563
+ cmd.append('--')
564
+
565
+ if isinstance(files, str):
566
+ cmd.append(files)
567
+ else:
568
+ cmd += files
569
+
570
+ return git(cmd, path=path)
571
+
572
+ ################################################################################
573
+
574
+ # Match 'git diff --numstat' output - first re splits into lines added, removed
575
+ # and name. Second one is used if a file has been renamed, to get the old and
576
+ # new name components.
577
+
578
+ _DIFF_OUTPUT_RE = re.compile(r'(-|\d+)\s+(-|\d+)\s+(.*)')
579
+ _DIFF_OUTPUT_RENAME_RE = re.compile(r'(.*)\{(.*) => (.*)\}(.*)')
580
+
581
+ def commit_info(commit_1=None, commit_2=None, paths=None, diff_stats=False, path=None):
582
+ """ Return details of changes either in single commit (defaulting to the most
583
+ recent one) or between two commits, optionally restricted a path or paths
584
+ and optionally returning diff statistics, with and/or without taking
585
+ whitespace into account.
586
+ """
587
+
588
+ def parse_diff_output(result):
589
+ """Extract previous and current filename (which may be the same) and lines added/deleted
590
+ from output from git diff --numstat"""
591
+
592
+ p = _DIFF_OUTPUT_RE.fullmatch(result)
593
+
594
+ # This shouldn't happen...
595
+
596
+ if not p:
597
+ return 'ERROR', 'ERROR', 0, 0
598
+
599
+ # Extract number of lines added/removed
600
+
601
+ lines_ins = 0 if p.group(1) == '-' else int(p.group(1))
602
+ lines_del = 0 if p.group(2) == '-' else int(p.group(2))
603
+
604
+ # Check for rename and get both old and new names
605
+ # The replace of '//' with '/' is to cope with the case where a file is moved
606
+ # to a parent or subdirectory where the git output will be 'PARENT/{SUBDIR => }/NAME'
607
+ # and the new name would otherwise be 'PARENT//NAME'
608
+
609
+ if ' => ' in p.group(3):
610
+ q = _DIFF_OUTPUT_RENAME_RE.fullmatch(p.group(3))
611
+
612
+ if q:
613
+ old_filename = (q.group(1) + q.group(2) + q.group(4)).replace('//', '/')
614
+ new_filename = (q.group(1) + q.group(3) + q.group(4)).replace('//', '/')
615
+ else:
616
+ old_filename, new_filename = p.group(3).split(' => ')
617
+ else:
618
+ old_filename = new_filename = p.group(3)
619
+
620
+ return old_filename, new_filename, lines_ins, lines_del
621
+
622
+ # Either get changes between the two commits, or changes in the specified commit
623
+
624
+ params = []
625
+
626
+ if commit_1:
627
+ params.append(commit_1)
628
+
629
+ if commit_2:
630
+ params.append(commit_2)
631
+
632
+ if paths:
633
+ params.append('--')
634
+
635
+ if isinstance(paths, str):
636
+ params.append(paths)
637
+ else:
638
+ params += paths
639
+
640
+ results = git(['diff', '--name-status'] + params, path=path)
641
+
642
+ # Parse the output
643
+
644
+ info = {}
645
+
646
+ for result in results:
647
+ if result == '':
648
+ continue
649
+
650
+ # Renames and copies have an extra field (which we ignore) for the destination
651
+ # file. We just get the status (Add, Move, Delete, Type-change, Copy, Rename)
652
+ # and the name.
653
+
654
+ if result[0] in ('R', 'C'):
655
+ filestatus, oldname, filename = result.split('\t')
656
+ info[filename] = {'status': filestatus[0], 'oldname': oldname}
657
+ else:
658
+ filestatus, filename = result.split('\t')
659
+ info[filename] = {'status': filestatus[0], 'oldname': filename}
660
+
661
+ # Add the diff stats, if requested
662
+
663
+ if diff_stats:
664
+ # Run git diff to get stats, and add them to the info
665
+ # TODO: Need to extract old name of renamed files
666
+
667
+ results = git(['diff', '--numstat'] + params, path=path)
668
+
669
+ for result in results:
670
+ old_filename, new_filename, lines_ins, lines_del = parse_diff_output(result)
671
+
672
+ info[new_filename]['deleted'] = lines_del
673
+ info[new_filename]['added'] = lines_ins
674
+
675
+ # Run git diff to get stats ignoring whitespace changes and add them
676
+
677
+ results = git(['diff', '--numstat', '--ignore-all-space', '--ignore-blank-lines'] + params, path=path)
678
+
679
+ for result in results:
680
+ old_filename, new_filename, lines_ins, lines_del = parse_diff_output(result)
681
+
682
+ info[new_filename]['non-ws deleted'] = lines_del
683
+ info[new_filename]['non-ws added'] = lines_ins
684
+
685
+ # Fill in the blanks - files
686
+
687
+ for filename in info:
688
+ if 'deleted' not in info[filename]:
689
+ info[filename]['deleted'] = info[filename]['added'] = 0
690
+
691
+ if 'non-ws deleted' not in info[filename]:
692
+ info[filename]['non-ws deleted'] = info[filename]['non-ws added'] = 0
693
+
694
+ return info
695
+
696
+ ################################################################################
697
+
698
+ def diff(commit=None, renames=True, copies=True, relative=False, path=None):
699
+ """ Return a list of differences between two commits, working tree and a commit or working tree and head """
700
+
701
+ if commit:
702
+ if isinstance(commit, list):
703
+ if len(commit) > 2:
704
+ raise GitError('git.diff - invalid parameters')
705
+
706
+ else:
707
+ commit = [commit]
708
+ else:
709
+ commit = []
710
+
711
+ cmd = ['diff', '--name-status']
712
+
713
+ if renames:
714
+ cmd.append('--find-renames')
715
+
716
+ if copies:
717
+ cmd.append('--find-copies')
718
+
719
+ if relative:
720
+ cmd.append('--relative')
721
+
722
+ cmd += commit
723
+
724
+ return git(cmd, path=path)
725
+
726
+ ################################################################################
727
+
728
+ def diff_status(commit1, commit2='HEAD', path=None):
729
+ """ Return True if there is no difference between the two commits, False otherwise """
730
+
731
+ cmd = ['diff', '--no-patch', '--exit-code', commit1, commit2]
732
+
733
+ try:
734
+ git(cmd, path=path)
735
+ except GitError:
736
+ return False
737
+
738
+ return True
739
+
740
+ ################################################################################
741
+
742
+ def show(revision, filename, outfile=None, path=None):
743
+ """ Return the output from git show revision:filename """
744
+
745
+ return git(['show', f'{revision}:{filename}'], stdout=outfile, path=path)
746
+
747
+ ################################################################################
748
+
749
+ def add(files, path=None):
750
+ """ Add file to git """
751
+
752
+ return git(['add'] + files, path=path)
753
+
754
+ ################################################################################
755
+
756
+ def rm(files, path=None):
757
+ """ Remove files from git """
758
+
759
+ return git(['rm'] + files, path=path)
760
+
761
+ ################################################################################
762
+
763
+ def commit(files=None,
764
+ message=None,
765
+ all=False, amend=False, foreground=False, patch=False, dry_run=False,
766
+ path=None):
767
+ """ Commit files to git """
768
+
769
+ cmd = ['commit']
770
+
771
+ if amend:
772
+ cmd.append('--amend')
773
+
774
+ if all:
775
+ cmd.append('--all')
776
+
777
+ if patch:
778
+ cmd.append('--patch')
779
+ foreground = True
780
+
781
+ if dry_run:
782
+ cmd.append('--dry-run')
783
+
784
+ if files is not None:
785
+ cmd += files
786
+
787
+ if message:
788
+ cmd += ['-m', message]
789
+
790
+ if foreground:
791
+ return git(cmd, stdout=sys.stdout, stderr=sys.stderr, path=path)
792
+
793
+ return git(cmd, path=path)
794
+
795
+ ################################################################################
796
+
797
+ def push(all=False, mirror=False, tags=False, atomic=False, dry_run=False,
798
+ follow_tags=False, receive_pack=False, repo=None, force=False, delete=False,
799
+ prune=False, verbose=False, set_upstream=False, push_options=None, signed=None,
800
+ force_with_lease=False, no_verify=False, repository=None, refspec=None,
801
+ path=None):
802
+ """ Push commits to a remote """
803
+
804
+ cmd = ['push']
805
+
806
+ if all:
807
+ cmd.append('--all')
808
+
809
+ if mirror:
810
+ cmd.append('--mirror')
811
+
812
+ if tags:
813
+ cmd.append('--tags')
814
+
815
+ if atomic:
816
+ cmd.append('--atomic')
817
+
818
+ if dry_run:
819
+ cmd.append('--dry-run')
820
+
821
+ if follow_tags:
822
+ cmd.append('--follow-tags')
823
+
824
+ if receive_pack:
825
+ cmd.append(f'--receive-pack={receive_pack}')
826
+
827
+ if repo:
828
+ cmd.append(f'--repo={repo}')
829
+
830
+ if force:
831
+ cmd.append('--force')
832
+
833
+ if delete:
834
+ cmd.append('--delete')
835
+
836
+ if prune:
837
+ cmd.append('--prune')
838
+
839
+ if verbose:
840
+ cmd.append('--verbose')
841
+
842
+ if set_upstream:
843
+ cmd.append('--set-upstream')
844
+
845
+ if push_options:
846
+ for option in push_options:
847
+ cmd.append(f'--push-option={option}')
848
+
849
+ if signed:
850
+ cmd.append(f'--signed={signed}')
851
+
852
+ if force_with_lease:
853
+ cmd.append('--force-with-lease')
854
+
855
+ if no_verify:
856
+ cmd.append('--no-verify')
857
+
858
+ if repository:
859
+ cmd.append(repository)
860
+
861
+ if refspec:
862
+ for ref in refspec:
863
+ cmd.append(ref)
864
+
865
+ return git(cmd, path=path)
866
+
867
+ ################################################################################
868
+
869
+ def reset(sha1, path=None):
870
+ """ Run git reset """
871
+
872
+ return git(['reset', sha1], path=path)
873
+
874
+ ################################################################################
875
+
876
+ def config_get(section, key, source=None, defaultvalue=None, path=None):
877
+ """ Return the specified configuration entry
878
+ Returns a default value if no matching configuration entry exists """
879
+
880
+ cmd = ['config']
881
+
882
+ if source == GLOBAL:
883
+ cmd.append('--global')
884
+ elif source == SYSTEM:
885
+ cmd.append('--system')
886
+ elif source == LOCAL:
887
+ cmd.append('--local')
888
+ elif source == WORKTREE:
889
+ cmd.append('--worktree')
890
+
891
+ cmd += ['--get', f'{section}.{key}']
892
+
893
+ try:
894
+ return git(cmd, path=path)[0]
895
+ except GitError:
896
+ return defaultvalue
897
+
898
+ ################################################################################
899
+
900
+ def config_set(section, key, value, source=None, path=None):
901
+ """ Set a configuration entry """
902
+
903
+ cmd = ['config']
904
+
905
+ if source == GLOBAL:
906
+ cmd.append('--global')
907
+ elif source == SYSTEM:
908
+ cmd.append('--system')
909
+ elif source == LOCAL:
910
+ cmd.append('--local')
911
+ elif source == WORKTREE:
912
+ cmd.append('--worktree')
913
+
914
+ cmd += ['--replace-all', f'{section}.{key}', value]
915
+
916
+ return git(cmd, path=path)
917
+
918
+ ################################################################################
919
+
920
+ def config_rm(section, key, source=LOCAL, path=None):
921
+ """ Remove a configuration entry """
922
+
923
+ cmd = ['config']
924
+
925
+ if source == GLOBAL:
926
+ cmd.append('--global')
927
+ elif source == SYSTEM:
928
+ cmd.append('--system')
929
+
930
+ cmd += ['--unset', f'{section}.{key}']
931
+
932
+ return git(cmd, path=path)
933
+
934
+ ################################################################################
935
+
936
+ def ref(fields=('objectname'), sort=None, remotes=False, path=None):
937
+ """ Wrapper for git for-each-ref """
938
+
939
+ cmd = ['for-each-ref']
940
+
941
+ if sort:
942
+ cmd.append(f'--sort={sort}')
943
+
944
+ field_list = []
945
+ for field in fields:
946
+ field_list.append('%%(%s)' % field)
947
+
948
+ cmd += ['--format=%s' % '%00'.join(field_list), 'refs/heads']
949
+
950
+ if remotes:
951
+ cmd.append('refs/remotes/origin')
952
+
953
+ for output in git(cmd, path=path):
954
+ yield output.split('\0')
955
+
956
+ ################################################################################
957
+
958
+ def branches(all=False, path=None, remote=False):
959
+ """ Return a list of all the branches in the current repo """
960
+
961
+ cmd = ['branch', '--format=%(refname:short)','--list']
962
+
963
+ if all:
964
+ cmd.append('--all')
965
+
966
+ if remote:
967
+ cmd.append('--remote')
968
+
969
+ results = []
970
+ for output in git(cmd, path=path):
971
+ if ' -> ' not in output and '(HEAD detached at ' not in output:
972
+ results.append(output)
973
+
974
+ return results
975
+
976
+ ################################################################################
977
+
978
+ def delete_branch(branch, force=False, remote=False, path=None):
979
+ """ Delete a branch, optionally forcefully and/or including the
980
+ remote tracking branch """
981
+
982
+ cmd = ['branch', '--delete']
983
+
984
+ if force:
985
+ cmd.append('--force')
986
+
987
+ if remote:
988
+ cmd.append('--remote')
989
+
990
+ cmd.append(branch)
991
+
992
+ return git(cmd, path=path)
993
+
994
+ ################################################################################
995
+
996
+ def remote_prune(remote, dry_run=False, path=None):
997
+ """ Return a list of remote tracking branches that no longer exist on the
998
+ specified remote """
999
+
1000
+ cmd = ['remote', 'prune', remote]
1001
+
1002
+ if dry_run:
1003
+ cmd.append('--dry-run')
1004
+
1005
+ results = git(cmd, path=path)
1006
+
1007
+ prunable_branches = []
1008
+
1009
+ prune_re = re.compile(r'\s[*]\s\[would prune\]\s(.*)')
1010
+
1011
+ for result in results:
1012
+ matches = prune_re.match(result)
1013
+ if matches:
1014
+ prunable_branches.append(matches.group(1))
1015
+
1016
+ return prunable_branches
1017
+
1018
+ ################################################################################
1019
+
1020
+ def get_commits(commit1, commit2, path=None):
1021
+ """ Get a list of commits separating two commits """
1022
+
1023
+ return git(['rev-list', commit1, f'^{commit2}'], path=path)
1024
+
1025
+ ################################################################################
1026
+
1027
+ def commit_count(commit1, commit2, path=None):
1028
+ """ Get a count of the number of commits between two commits """
1029
+
1030
+ return int(git(['rev-list', '--count', commit1, f'^{commit2}'], path=path)[0])
1031
+
1032
+ ################################################################################
1033
+
1034
+ def branch_name(branch, path=None):
1035
+ """ Return the full name of a branch given an abbreviation - e.g. @{upstream}
1036
+ for the upstream branch """
1037
+
1038
+ return git(['rev-parse', '--abbrev-ref', '--symbolic-full-name', branch], path=path)[0]
1039
+
1040
+ ################################################################################
1041
+
1042
+ def author(commit, path=None):
1043
+ """ Return the author of a commit """
1044
+
1045
+ return git(['show', '--format=format:%an', commit], path=path)[0]
1046
+
1047
+ ################################################################################
1048
+
1049
+ def commit_changes(commit='HEAD', path=None):
1050
+ """Return a list of the files changed in a commit"""
1051
+
1052
+ return git(['show', '--name-only', '--pretty=format:', commit], path=path)
1053
+
1054
+ ################################################################################
1055
+
1056
+ def files(dir=None, path=None):
1057
+ """ Return the output from 'git ls-files' """
1058
+
1059
+ cmd = ['ls-files']
1060
+
1061
+ if dir:
1062
+ cmd.append(dir)
1063
+
1064
+ return git(cmd, path=path)
1065
+
1066
+ ################################################################################
1067
+
1068
+ def stash(path=None):
1069
+ """ Return the list of stashed items (if any) """
1070
+
1071
+ cmd = ['stash', 'list']
1072
+
1073
+ return git(cmd, path=path)
1074
+
1075
+ ################################################################################
1076
+
1077
+ def parents(commit=None, ignore=None, path=None):
1078
+ """ Look at the commits down the history of the specified branch,
1079
+ looking for another branch or branches that also contain the same commit.
1080
+ The first found is the parent (or equally-likely parents) of the
1081
+ branch - note due to fundamental git-ness a given branch can have multiple
1082
+ equally-plasuible parents.
1083
+
1084
+ Return the list of possible parents and the distance down the branch
1085
+ from the current commit to those posible parents """
1086
+
1087
+ # Get the history of the branch
1088
+
1089
+ current_branch = commit or branch('HEAD', path=path)
1090
+
1091
+ current_history = git(['rev-list', current_branch], path=path)
1092
+
1093
+ # Look down the commits on the current branch for other branches that have
1094
+ # the same commit, using the ignore pattern if there is one.
1095
+
1096
+ for distance, ancestor in enumerate(current_history):
1097
+ branches = []
1098
+ for brnch in git(['branch', '--contains', ancestor], path=path):
1099
+ brnch = brnch[2:]
1100
+ if brnch != current_branch and '(HEAD detached at' not in brnch:
1101
+ if not ignore or (ignore and not fnmatch.fnmatch(brnch, ignore)):
1102
+ branches.append(brnch)
1103
+
1104
+ if branches:
1105
+ break
1106
+ else:
1107
+ return None, 0
1108
+
1109
+ return branches, distance
1110
+
1111
+ ################################################################################
1112
+
1113
+ def find_common_ancestor(branch1='HEAD', branch2='master', path=None):
1114
+ """ Find the first (oldest) commit that the two branches have in common
1115
+ i.e. the point where one branch was forked from the other """
1116
+
1117
+ return git(['merge-base', branch1, branch2], path=path)[0]
1118
+
1119
+ ################################################################################
1120
+
1121
+ # List of boolean options to git.grep with corresponding command line option to use if option is True
1122
+
1123
+ _GREP_OPTLIST = \
1124
+ (
1125
+ ('color', '--color=always'),
1126
+ ('count', '--count'),
1127
+ ('follow', '--follow'),
1128
+ ('unmatch', '-I'),
1129
+ ('textconf', '--textconv'),
1130
+ ('ignore_case', '--ignore-case'),
1131
+ ('word_regexp', '--word-regexp'),
1132
+ ('invert_match', '--invert-match'),
1133
+ ('full_name', '--full-name'),
1134
+ ('extended_regexp', '--extended-regexp'),
1135
+ ('basic_regexp', '--basic-regexp'),
1136
+ ('perl_regexp', '--perl-regexp'),
1137
+ ('fixed_strings', '--fixed-strings'),
1138
+ ('line_number', '--line-number'),
1139
+ ('files_with_matches', '--files-with-matches'),
1140
+ ('files_without_match', '--files-without-match'),
1141
+ ('names_only', '--names-only'),
1142
+ ('null', '--null'),
1143
+ ('all_match', '--all-match'),
1144
+ ('quiet', '--quiet'),
1145
+ ('no_color', '--no-color'),
1146
+ ('break', '--break'),
1147
+ ('heading', '--heading'),
1148
+ ('show_function', '--show-function'),
1149
+ ('function_context', '--function-context'),
1150
+ ('only_matching', '--only-matching'),
1151
+ )
1152
+
1153
+ # List of non-boolean options to git.grep with corresponding command line option
1154
+
1155
+ _GREP_NON_BOOL_OPTLIST = \
1156
+ (
1157
+ ('root', '--root'),
1158
+ ('max_depth', '--max-depth'),
1159
+ ('after_context', '--after-context'),
1160
+ ('before_context', '--before-context'),
1161
+ ('context', '--context'),
1162
+ ('threads', '--threads'),
1163
+ ('file', '--file'),
1164
+ ('parent_basename', '--parent-basename')
1165
+ )
1166
+
1167
+ def grep(pattern, git_dir=None, work_tree=None, options=None, wildcards=None, path=None):
1168
+ """ Run git grep - takes a painfully large number of options passed
1169
+ as a dictionary. """
1170
+
1171
+ cmd = []
1172
+
1173
+ if git_dir:
1174
+ cmd += ['--git-dir', git_dir]
1175
+
1176
+ if work_tree:
1177
+ cmd += ['--work-tree', work_tree]
1178
+
1179
+ cmd += ['grep']
1180
+
1181
+ if options:
1182
+ # Boolean options
1183
+
1184
+ for opt in _GREP_OPTLIST:
1185
+ if options.get(opt[0], False):
1186
+ cmd.append(opt[1])
1187
+
1188
+ # Non-boolean options
1189
+
1190
+ for opt in _GREP_NON_BOOL_OPTLIST:
1191
+ value = options.get(opt[0], None)
1192
+ if value:
1193
+ cmd += (opt[1], value)
1194
+
1195
+ if isinstance(pattern, list):
1196
+ cmd += pattern
1197
+ else:
1198
+ cmd += [pattern]
1199
+
1200
+ if wildcards:
1201
+ cmd.append('--')
1202
+ cmd += wildcards
1203
+
1204
+ return git_run_status(cmd, path=path)
1205
+
1206
+ ################################################################################
1207
+
1208
+ def isbranch(branchname, path=None):
1209
+ """ Return true if the specified branch exists """
1210
+
1211
+ return branchname in branches(True, path=path)
1212
+
1213
+ ################################################################################
1214
+
1215
+ def default_branch(path=None):
1216
+ """ Return the name of the default branch, attempting to interrogate GitLab
1217
+ if the repo appears to have been cloned from there and falling back to
1218
+ returning whichever one of 'develop', 'main' or 'master' exists. """
1219
+
1220
+ remote_list = remotes(path=path)
1221
+ if remote_list:
1222
+ for name in remote_list:
1223
+ if 'gitlab' in remote_list[name]:
1224
+ url = remote_list[name].split('@')[1].split(':')[0]
1225
+ repo = remote_list[name].split(':')[1]
1226
+
1227
+ if not url.startswith('http://') and not url.startswith('https://'):
1228
+ url = f'https://{url}'
1229
+
1230
+ if repo.endswith('.git'):
1231
+ repo = repo[:-4]
1232
+
1233
+ try:
1234
+ gl = gitlab.GitLab(url)
1235
+ return gl.default_branch(repo)
1236
+
1237
+ except gitlab.GitLabError:
1238
+ return None
1239
+
1240
+ git_branches = branches(path=path)
1241
+ default_branches = config_get('skilleter-thingy', 'defaultBranches', defaultvalue=DEFAULT_DEFAULT_BRANCHES, path=path).split(',')
1242
+
1243
+ for branch in default_branches:
1244
+ if branch in git_branches:
1245
+ return branch
1246
+
1247
+ raise GitError('Unable to determine default branch in the repo')
1248
+
1249
+ ################################################################################
1250
+
1251
+ def matching_branch(branchname, case=False, path=None):
1252
+ """ Look for a branch matching the specified name and return it
1253
+ out if it is an exact match or there is only one partial
1254
+ match. If there are multiple branches that match, return them
1255
+ as a list.
1256
+
1257
+ If case == True then the comparison is case-sensitive.
1258
+
1259
+ If the branchname contains '*' or '?' wildcard matching is used,.
1260
+ otherwise, it just checks for a branches containing the branchname
1261
+ as a substring. """
1262
+
1263
+ local_branches = branches(path=path)
1264
+ remote_branches = branches(path=path, remote=True)
1265
+
1266
+ all_branches = local_branches + remote_branches
1267
+
1268
+ # Always return exact matches
1269
+
1270
+ if branchname in all_branches:
1271
+ return [branchname]
1272
+
1273
+ matching = []
1274
+ matching_remote = []
1275
+
1276
+ if not case:
1277
+ branchname = branchname.lower()
1278
+
1279
+ if branchname == '-' * len(branchname):
1280
+ matching = [branchname]
1281
+ else:
1282
+ wildcard = '?' in branchname or '*' in branchname
1283
+
1284
+ if wildcard:
1285
+ if branchname[0] not in ('?', '*'):
1286
+ branchname = f'*{branchname}'
1287
+
1288
+ if branchname[-1] not in ('?', '*'):
1289
+ branchname = f'{branchname}*'
1290
+
1291
+ for branch in all_branches:
1292
+ branchmatch = branch if case else branch.lower()
1293
+
1294
+ # We have a partial match
1295
+
1296
+ if (not wildcard and branchname in branchmatch) or (wildcard and fnmatch.fnmatch(branchmatch, branchname)):
1297
+ # If the match is a remote branch, ignore it if we already have the equivalent
1298
+ # local branch, otherwise add the name of the local branch that would be created.
1299
+
1300
+ if branch in remote_branches:
1301
+ localbranch = '/'.join(branch.split('/')[1:])
1302
+ if localbranch not in matching:
1303
+ matching_remote.append(localbranch)
1304
+ else:
1305
+ matching.append(branch)
1306
+
1307
+ # If we don't have matching local branches use the remote branch list (which may also be empty)
1308
+
1309
+ if not matching:
1310
+ matching = matching_remote
1311
+
1312
+ # Return the list of matches
1313
+
1314
+ return matching
1315
+
1316
+ ################################################################################
1317
+
1318
+ def update(clean=False, all=False, path=None):
1319
+ """ Run git update (which is a thingy command, and may end up as a module
1320
+ but for the moment, we'll treat it as any other git command) """
1321
+
1322
+ cmd = ['update']
1323
+
1324
+ if clean:
1325
+ cmd.append('--clean')
1326
+
1327
+ if all:
1328
+ cmd.append('--all')
1329
+
1330
+ return git(cmd, path=path)
1331
+
1332
+ ################################################################################
1333
+
1334
+ def object_type(name, path=None):
1335
+ """ Return the git object type (commit, tag, blob, ...) """
1336
+
1337
+ return git(['cat-file', '-t', name], path=path)[0]
1338
+
1339
+ ################################################################################
1340
+
1341
+ def matching_commit(name, path=None):
1342
+ """ Similar to matching_branch() (see above).
1343
+ If the name uniquely matches a branch, return that
1344
+ If it matches multiple branches return a list
1345
+ If it doesn't match any branches, repeat the process for tags
1346
+ if it doesn't match any tags, repeat the process for commit IDs
1347
+
1348
+ TODO: Currently matches multiple branches, tag, but only a unique commit - not sure if this the best behaviour, but it works """
1349
+
1350
+ # First, look for exact matching object
1351
+
1352
+ if iscommit(name, path=path):
1353
+ return [name]
1354
+
1355
+ # Look for at least one matching branch
1356
+
1357
+ matches = matching_branch(name, path=path)
1358
+
1359
+ if matches:
1360
+ return matches
1361
+
1362
+ # Look for at least one matching tag
1363
+
1364
+ matches = []
1365
+ for tag in tags(path=path):
1366
+ if name in tag:
1367
+ matches.append(tag)
1368
+
1369
+ if matches:
1370
+ return matches
1371
+
1372
+ # Look for a matching commit
1373
+
1374
+ try:
1375
+ commit_type = object_type(name, path=path)
1376
+
1377
+ if commit_type == 'commit':
1378
+ matches = [name]
1379
+ except GitError:
1380
+ matches = []
1381
+
1382
+ return matches
1383
+
1384
+ ################################################################################
1385
+
1386
+ def log(branch1, branch2=None, path=None):
1387
+ """ Return the git log between the given commits """
1388
+
1389
+ if branch2:
1390
+ cmd = ['log', f'{branch1}...{branch2}']
1391
+ else:
1392
+ cmd = ['log', '-n1', branch1]
1393
+
1394
+ return git(cmd, path=path)
1395
+
1396
+ ################################################################################
1397
+
1398
+ def clean(recurse=False, force=False, dry_run=False, quiet=False,
1399
+ exclude=None, ignore_rules=False, remove_only_ignored=False, path=None):
1400
+ """ Run git clean """
1401
+
1402
+ cmd = ['clean']
1403
+
1404
+ if recurse:
1405
+ cmd.append('-d')
1406
+
1407
+ if force:
1408
+ cmd.append('--force')
1409
+
1410
+ if dry_run:
1411
+ cmd.append('--dry-run')
1412
+
1413
+ if quiet:
1414
+ cmd.append('--quiet')
1415
+
1416
+ if exclude:
1417
+ cmd += ['--exclude', exclude]
1418
+
1419
+ if ignore_rules:
1420
+ cmd.append('-x')
1421
+
1422
+ if remove_only_ignored:
1423
+ cmd.append('-X')
1424
+
1425
+ return git(cmd, path=path)
1426
+
1427
+ ################################################################################
1428
+
1429
+ def run_tests():
1430
+ """Test suite for the module"""
1431
+
1432
+ print('Creating local git repo')
1433
+
1434
+ init('test-repo')
1435
+ os.chdir('test-repo')
1436
+
1437
+ try:
1438
+ print('Initial status:')
1439
+ print(' User name: %s' % config_get('user', 'name'))
1440
+ print(' Project: %s' % project())
1441
+ print(' Remotes: %s' % remotes())
1442
+ print(' Current branch: %s' % branch())
1443
+ print(' Current working tree: %s' % working_tree())
1444
+ print(' Rebasing? %s' % rebasing())
1445
+ print(' Status: %s' % status())
1446
+ print()
1447
+
1448
+ print('Adding a removing a configuration value')
1449
+
1450
+ config_set('user', 'size', 'medium')
1451
+
1452
+ print(' User size config: %s' % config_get('user', 'size'))
1453
+
1454
+ config_rm('user', 'size')
1455
+
1456
+ value = config_get('user', 'size')
1457
+ if value is None:
1458
+ print(' Successfully failed to read the newly-deleted config data')
1459
+ else:
1460
+ raise GitError('Unexpected lack of error reading configuration data', 1)
1461
+
1462
+ config_set('user', 'email', 'user@localhost')
1463
+ config_set('user', 'name', 'User Name')
1464
+
1465
+ print('')
1466
+
1467
+ with open('newfile.txt', 'w', encoding='utf8') as newfile:
1468
+ newfile.write('THIS IS A TEST')
1469
+
1470
+ print('Adding and committing "newfile.txt"')
1471
+
1472
+ add(['newfile.txt'])
1473
+
1474
+ commit(['newfile.txt'], 'Test the add and commit functionality')
1475
+
1476
+ print('Removing and committing "newfile.txt"')
1477
+
1478
+ rm(['newfile.txt'])
1479
+
1480
+ commit(None, 'Removed "newfile.txt"')
1481
+
1482
+ print('Removing the last commit')
1483
+
1484
+ reset('HEAD~1')
1485
+
1486
+ print('Commit info for HEAD %s' % commit_info('HEAD'))
1487
+
1488
+ except GitError as exc:
1489
+ sys.stderr.write(f'ERROR: {exc.msg}')
1490
+ sys.exit(1)
1491
+
1492
+ finally:
1493
+ # If anything fails, then clean up afterwards
1494
+
1495
+ os.chdir('..')
1496
+ shutil.rmtree('test-repo')
1497
+
1498
+ ################################################################################
1499
+ # Entry point
1500
+
1501
+ if __name__ == '__main__':
1502
+ run_tests()