]>
git.wh0rd.org - home.git/blob - .bin/git-rb-all
3 """Helper to rebase all local branches."""
8 from pathlib
import Path
14 # Not sure if newer features are used.
15 assert sys
.version_info
>= (3, 6), f
'Python 3.6+ required but found {sys.version}'
18 PROG
= os
.path
.basename(__file__
)
22 """Terminal escape sequences."""
28 _BLACK
, _RED
, _GREEN
, _YELLOW
, _BLUE
, _MAGENTA
, _CYAN
, _WHITE
= range(0, 8)
31 FG_BLACK
= str(_FG
+ _BLACK
)
32 FG_RED
= str(_FG
+ _RED
)
33 FG_GREEN
= str(_FG
+ _GREEN
)
34 FG_YELLOW
= str(_FG
+ _YELLOW
)
35 FG_BLUE
= str(_FG
+ _BLUE
)
36 FG_MAGENTA
= str(_FG
+ _MAGENTA
)
37 FG_CYAN
= str(_FG
+ _CYAN
)
38 FG_WHITE
= str(_FG
+ _WHITE
)
44 _combine
= lambda *args
: Terminal
.CSI_PREFIX
+ ';'.join(args
) + Terminal
.SGR_SUFFIX
45 NORMAL
= _combine(Terminal
.NORMAL
)
46 GOOD
= _combine(Terminal
.FG_GREEN
)
47 WARN
= _combine(Terminal
.FG_YELLOW
)
48 BAD
= _combine(Terminal
.FG_RED
)
49 HILITE
= _combine(Terminal
.BOLD
, Terminal
.FG_CYAN
)
50 BRACKET
= _combine(Terminal
.BOLD
, Terminal
.FG_BLUE
)
54 """Show an error |msg| then exit."""
55 print(f
'{Color.BAD}{PROG}: error: {msg}{Color.NORMAL}', file=sys
.stderr
)
59 def git(args
, **kwargs
):
61 kwargs
.setdefault('check', True)
62 kwargs
.setdefault('stdout', subprocess
.PIPE
)
63 kwargs
.setdefault('stderr', subprocess
.STDOUT
)
64 kwargs
.setdefault('encoding', 'utf-8')
65 #print('+', 'git', *args)
66 return subprocess
.run(['git'] + args
, **kwargs
)
69 @functools.lru_cache(maxsize
=None)
70 def checkout_is_dirty():
71 """Determine whether the checkout is dirty (e.g. modified files)."""
72 output
= git(['status', '--porcelain']).stdout
73 return any(x
for x
in output
.splitlines() if '?' not in x
[0:2])
76 @functools.lru_cache(maxsize
=None)
77 def rebase_inprogress():
78 """Determine whether a rebase is already in progress."""
79 output
= git(['rev-parse', '--git-path', 'rebase-merge']).stdout
.strip()
80 if Path(output
).exists():
83 output
= git(['rev-parse', '--git-path', 'rebase-apply']).stdout
.strip()
84 if Path(output
).exists():
90 class AppendOption(argparse
.Action
):
91 """Append the command line option (with no arguments) to dest.
93 parser.add_argument('-b', '--barg', dest='out', action='append_option')
94 options = parser.parse_args(['-b', '--barg'])
95 options.out == ['-b', '--barg']
98 def __init__(self
, option_strings
, dest
, **kwargs
):
100 raise ValueError('nargs is not supported for append_option action')
101 super().__init
__(option_strings
, dest
, nargs
=0, **kwargs
)
103 def __call__(self
, parser
, namespace
, values
, option_string
=None):
104 if getattr(namespace
, self
.dest
, None) is None:
105 setattr(namespace
, self
.dest
, [])
106 getattr(namespace
, self
.dest
).append(option_string
)
110 """Get CLI parser."""
111 parser
= argparse
.ArgumentParser(description
=__doc__
)
113 '--catchup', action
='store_true',
114 help='run git-rb-catchup when rebasing')
116 '-q', '--quiet', dest
='git_options', action
=AppendOption
, default
=['-q'],
117 help='passthru to git rebase')
122 """The main entry point for scripts."""
123 parser
= get_parser()
124 opts
= parser
.parse_args(argv
)
126 # Skip if rebase is in progress.
127 if rebase_inprogress():
128 fatal('skipping due to active rebase')
130 # Switch to the top dir in case the working dir doesn't exist in every branch.
131 topdir
= git(['rev-parse', '--show-toplevel']).stdout
.strip()
135 # ||m|refs/remotes/origin/master|ahead 2, behind 203
136 # *||master|refs/remotes/origin/master|ahead 1
137 # |/usr/local/src/gnu/gdb/build/release|release||behind 10
140 ['for-each-ref', '--format=%(HEAD)|%(worktreepath)|%(refname:short)|%(upstream)|%(upstream:track,nobracket)',
141 'refs/heads/*']).stdout
.splitlines()
147 head
, worktreepath
, branch
, tracking
, ahead_behind
= line
.split('|')
148 branch_width
= max(branch_width
, len(branch
))
151 if not (worktreepath
and worktreepath
!= topdir
):
153 # If there are no branches to rebase, go silently.
157 fatal('unable to resolve current branch')
159 switched_head
= False
162 _
, worktreepath
, branch
, tracking
, ahead_behind
= line
.split('|')
164 # If it's a branch in another worktree, ignore it.
165 if worktreepath
and worktreepath
!= topdir
:
168 print(f
'{Color.BRACKET}### {Color.GOOD}{branch:{branch_width}}{Color.NORMAL} ',
171 print(f
'{Color.WARN}skipping{Color.NORMAL} due to missing merge branch')
174 m
= re
.match(r
'ahead ([0-9]+)', ahead_behind
)
175 ahead
= int(m
.group(1)) if m
else 0
176 m
= re
.search(r
'behind ([0-9]+)', ahead_behind
)
177 behind
= int(m
.group(1)) if m
else 0
182 # If we haven't switched the checkout, update-ref on current HEAD
183 # will get us into a dirty checkout, so use merge to handle it.
184 if switched_head
or curr_state
!= branch
:
185 git(['update-ref', f
'refs/heads/{branch}', tracking
])
186 print('fast forwarded [updated ref]')
188 result
= git(['merge', '-q', '--ff-only'], check
=False)
189 if result
.returncode
:
190 print(f
'{Color.BAD}unable to merge{Color.NORMAL}\n' + result
.stdout
.strip())
192 print('fast forwarded [merged]')
195 if checkout_is_dirty():
196 print(f
'{Color.BAD}unable to rebase: tree is dirty{Color.NORMAL}')
199 print(f
'rebasing [{ahead_behind}] ', end
='', flush
=True)
200 git(['checkout', '-q', branch
])
204 result
= git(['rb-catchup'], capture_output
=False, check
=False)
206 result
= git(['rebase'] + opts
.git_options
, check
=False)
207 if result
.returncode
:
208 git(['rebase', '--abort'])
209 print(f
'{Color.BAD}failed{Color.NORMAL}\n' + result
.stdout
.strip())
214 git(['checkout', '-q', curr_state
])
218 if __name__
== '__main__':
219 sys
.exit(main(sys
.argv
[1:]))