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