Skip to content

Instantly share code, notes, and snippets.

@hobroker
Created December 3, 2019 01:13
Show Gist options
  • Save hobroker/50da45e7de11b178e2bc9caef34b2544 to your computer and use it in GitHub Desktop.
Save hobroker/50da45e7de11b178e2bc9caef34b2544 to your computer and use it in GitHub Desktop.
Lazy commit in python
#!/usr/bin/env python3
from argparse import ArgumentParser
import os
from subprocess import check_output
import sys
import yaml
FZF_HEIGHT = 8
def logError(*msg): print('\033[91m', *msg, '\033[0m')
def logSuccess(*msg): print('\033[92m', *msg, '\033[0m')
def logWarn(*msg): print('\033[93m', *msg, '\033[0m')
def logInfo(*msg): print('\033[94m', *msg, '\033[0m')
def exec(cmd):
if not cmd:
return
logInfo(f'$ {cmd}')
os.system(cmd)
def exitWith(*message):
if message:
logError(*message)
sys.exit()
def search(what):
if isinstance(what, list) or isinstance(what, dict):
what = '\n'.join(what)
tmp_file = '/tmp/glc_search'
fzf_cmd = f'fzf --preview \'\' --height {FZF_HEIGHT}'
search_cmd = f'echo "{what}" | {fzf_cmd} > {tmp_file}'
os.system(search_cmd)
data = check_output(['cat', tmp_file]).decode('utf-8').rstrip()
os.system(f'rm {tmp_file}')
if not data:
exitWith()
return data
def readMessages():
with open('messages.yaml', 'r') as file:
return yaml.safe_load(file)
def resolveScope(scopes, scope):
if not scope:
return search(scopes)
if scope in messages:
return scope
return None
def resolveSummary(messages, message):
if message:
return ' '.join(message)
return search(messages)
parser = ArgumentParser()
parser.add_argument('scope', nargs='?', default=None, type=str)
parser.add_argument('message', nargs='*', default=[])
parser.add_argument('-a', '--amend', nargs='?', default=False, type=bool)
parser.add_argument('-p', '--push', nargs='?', default=False, type=bool)
parser.add_argument('-f', '--force', nargs='?', default=False, type=bool)
parser.add_argument('-s', '--stage', nargs='?', default=None)
commands = []
args = parser.parse_args()
gitStage = args.stage
gitPush = args.push is not False
gitAmend = '--amend' if args.amend is not False else ''
useForce = args.force is not False
messages = readMessages()
scope = resolveScope(messages, args.scope)
if scope is None:
exitWith(
f'Scope "{args.scope}" not found. Should be one of:', list(messages))
summary = resolveSummary(messages[scope], args.message)
message = f'{scope}: {summary}'
if gitStage:
commands.append(f'git add -v {gitStage}')
commands.append(f'git commit {gitAmend} -m "{message}"')
if gitPush:
commands.append(f'git push origin HEAD')
for cmd in commands:
logInfo('#', cmd)
try:
if not useForce:
input()
for cmd in commands:
exec(cmd)
except KeyboardInterrupt:
exitWith('not executing anything')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment