skilleter-thingy 0.2.4__py3-none-any.whl → 0.2.7__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.

Potentially problematic release.


This version of skilleter-thingy might be problematic. Click here for more details.

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