Skip to content

Instantly share code, notes, and snippets.

@zeroidentidad
Forked from lggomez/mass_git_updater.py
Created June 30, 2021 15:08
Show Gist options
  • Save zeroidentidad/4f4315bdf4a43bfcdfa422e3ff07772e to your computer and use it in GitHub Desktop.
Save zeroidentidad/4f4315bdf4a43bfcdfa422e3ff07772e to your computer and use it in GitHub Desktop.
[Python] Mass git updater
__author__ = "lggomez"
__copyright__ = "Copyright 2017"
__credits__ = ["Luis Gomez"]
__license__ = "MIT"
__version__ = "0.3"
__maintainer__ = "lggomez"
__status__ = "Production"
import argparse
import os
import subprocess
argsParser = argparse.ArgumentParser()
argsParser.add_argument('-dir', nargs=1)
argsParser.add_argument('-fetch', action='store_true')
argsParser.add_argument('-master', action='store_true')
argsParser.add_argument('-safe', action='store_true')
argsParser.add_argument('-silent', action='store_true')
args = argsParser.parse_args()
if not any([args.dir]):
argsParser.print_usage()
quit()
pipe = subprocess.PIPE
def executeCommand(command, outputPipe):
process = subprocess.Popen(command, stdout=outputPipe, stderr=outputPipe)
stdoutput, stderroutput = process.communicate()
success = True
if 'fatal' in stderroutput:
success = False
else:
if not args.silent:
print '\t' + stdoutput
return success, stdoutput, stderroutput
def processGitRepository(directory):
_, output, _ = executeCommand(['git', '-C', directory, 'branch'], pipe)
branches = [k for k in output.strip().split('\n') if '* ' in k]
currentBranch = "master"
if len(branches) > 0:
currentBranch = branches[0].replace("* ", "")
if args.fetch:
executeCommand(['git', '-C', directory, 'fetch'], pipe)
if args.master:
executeCommand(['git', '-C', directory, 'checkout', 'master'], pipe)
currentBranch = "master"
if args.safe:
_, stdoutput, _ = executeCommand(['git', '-C', directory, 'status'], pipe)
if "nothing to commit, working tree clean" in stdoutput:
executeCommand(['git', '-C', directory, 'pull', 'origin', currentBranch], pipe)
else:
executeCommand(['git', '-C', directory, 'pull', 'origin', currentBranch], pipe)
def isGitRepository(directory):
process = subprocess.Popen(['git', '-C', directory, 'rev-parse', '--is-inside-work-tree'], stdout=pipe, stderr=pipe)
stdoutput, stderroutput = process.communicate()
if 'fatal' in stdoutput or 'fatal' in stderroutput:
return False
else:
return stdoutput.strip() == "true"
user = os.path.expanduser("~")
rootDir = os.path.normpath(args.dir[0].strip().replace("~", user))
for root, dirs, _ in os.walk(rootDir):
for entry in dirs:
currDir = os.path.join(root, entry)
if isGitRepository(currDir):
print "*Git repo found at " + currDir
processGitRepository(currDir)
# break after first level
break
print "DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment