]>
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 return cls
.GOOD
+ msg
+ cls
.NORMAL
58 return cls
.BAD
+ msg
+ cls
.NORMAL
62 """Show an error |msg| then exit."""
63 print(Color
.bad(f
'{PROG}: error: {msg}'), file=sys
.stderr
)
67 def git(args
, **kwargs
):
69 kwargs
.setdefault('check', True)
70 kwargs
.setdefault('stdout', subprocess
.PIPE
)
71 kwargs
.setdefault('stderr', subprocess
.STDOUT
)
72 kwargs
.setdefault('encoding', 'utf-8')
73 #print('+', 'git', *args)
74 return subprocess
.run(['git'] + args
, **kwargs
)
77 @functools.lru_cache(maxsize
=None)
78 def checkout_is_dirty():
79 """Determine whether the checkout is dirty (e.g. modified files)."""
80 output
= git(['status', '--porcelain']).stdout
81 return any(x
for x
in output
.splitlines() if '?' not in x
[0:2])
84 @functools.lru_cache(maxsize
=None)
85 def rebase_inprogress():
86 """Determine whether a rebase is already in progress."""
87 output
= git(['rev-parse', '--git-path', 'rebase-merge']).stdout
.strip()
88 if Path(output
).exists():
91 output
= git(['rev-parse', '--git-path', 'rebase-apply']).stdout
.strip()
92 if Path(output
).exists():
98 @functools.lru_cache(maxsize
=None)
99 def cherry_pick_inprogress():
100 """Determine whether a cherry-pick is in progress."""
101 output
= git(['rev-parse', '--git-path', 'CHERRY_PICK_HEAD']).stdout
.strip()
102 return Path(output
).exists()
105 class AppendOption(argparse
.Action
):
106 """Append the command line option (with no arguments) to dest.
108 parser.add_argument('-b', '--barg', dest='out', action='append_option')
109 options = parser.parse_args(['-b', '--barg'])
110 options.out == ['-b', '--barg']
113 def __init__(self
, option_strings
, dest
, **kwargs
):
114 if 'nargs' in kwargs
:
115 raise ValueError('nargs is not supported for append_option action')
116 super().__init
__(option_strings
, dest
, nargs
=0, **kwargs
)
118 def __call__(self
, parser
, namespace
, values
, option_string
=None):
119 if getattr(namespace
, self
.dest
, None) is None:
120 setattr(namespace
, self
.dest
, [])
121 getattr(namespace
, self
.dest
).append(option_string
)
125 """Get CLI parser."""
126 parser
= argparse
.ArgumentParser(description
=__doc__
)
128 '--catchup', action
='store_true',
129 help='run git-rb-catchup when rebasing')
131 '-q', '--quiet', dest
='git_options', action
=AppendOption
, default
=['-q'],
132 help='passthru to git rebase')
137 """The main entry point for scripts."""
138 parser
= get_parser()
139 opts
= parser
.parse_args(argv
)
141 # Switch to the top dir in case the working dir doesn't exist in every branch.
142 topdir
= git(['rev-parse', '--show-toplevel']).stdout
.strip()
146 # ||m|refs/remotes/origin/master|ahead 2, behind 203
147 # *||master|refs/remotes/origin/master|ahead 1
148 # |/usr/local/src/gnu/gdb/build/release|release||behind 10
151 ['for-each-ref', '--format=%(HEAD)|%(worktreepath)|%(refname:short)|%(upstream)|%(upstream:track,nobracket)',
152 'HEAD', 'refs/heads/*']).stdout
.splitlines()
158 head
, worktreepath
, branch
, tracking
, ahead_behind
= line
.split('|')
159 branch_width
= max(branch_width
, len(branch
))
162 if not (worktreepath
and worktreepath
!= topdir
):
164 # If there are no branches to rebase, go silently.
168 # Are we in a detached head state?
169 if not git(['symbolic-ref', '-q', 'HEAD'], check
=False).returncode
:
170 fatal('unable to resolve current branch')
171 curr_state
= git(['rev-parse', 'HEAD']).stdout
.strip()
173 switched_head
= False
176 _
, worktreepath
, branch
, tracking
, ahead_behind
= line
.split('|')
178 # If it's a branch in another worktree, ignore it.
179 if worktreepath
and worktreepath
!= topdir
:
182 print(f
'{Color.BRACKET}### {Color.GOOD}{branch:{branch_width}}{Color.NORMAL} ',
185 print(f
'{Color.WARN}skipping{Color.NORMAL} due to missing merge branch')
188 m
= re
.match(r
'ahead ([0-9]+)', ahead_behind
)
189 ahead
= int(m
.group(1)) if m
else 0
190 m
= re
.search(r
'behind ([0-9]+)', ahead_behind
)
191 behind
= int(m
.group(1)) if m
else 0
193 print(Color
.good('up-to-date'))
196 # If we haven't switched the checkout, update-ref on current HEAD
197 # will get us into a dirty checkout, so use merge to handle it.
198 if switched_head
or curr_state
!= branch
:
199 git(['update-ref', f
'refs/heads/{branch}', tracking
])
200 print('fast forwarded [updated ref]')
202 result
= git(['merge', '-q', '--ff-only'], check
=False)
203 if result
.returncode
:
204 print(Color
.bad('unable to merge') + '\n' + result
.stdout
.strip())
206 print('fast forwarded [merged]')
209 # Skip this ref if tree is in a bad state.
210 if rebase_inprogress():
211 print(Color
.bad('skipping due to active rebase'))
213 if cherry_pick_inprogress():
214 print(Color
.bad('skipping due to active cherry-pick'))
216 if checkout_is_dirty():
217 print(Color
.bad('unable to rebase: tree is dirty'))
220 print(f
'rebasing [{ahead_behind}] ', end
='', flush
=True)
221 result
= git(['checkout', '-q', branch
], check
=False)
222 if result
.returncode
:
223 print(Color
.bad('unable to checkout') + '\n' + result
.stdout
.strip())
228 result
= git(['rb-catchup'], capture_output
=False, check
=False)
230 result
= git(['rebase'] + opts
.git_options
, check
=False)
231 if result
.returncode
:
232 git(['rebase', '--abort'])
233 print(Color
.bad('failed') + '\n' + result
.stdout
.strip())
235 print(Color
.good('OK'))
238 git(['checkout', '-q', curr_state
])
242 if __name__
== '__main__':
243 sys
.exit(main(sys
.argv
[1:]))