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