Skip to content

Instantly share code, notes, and snippets.

@cloderic
Created August 13, 2015 14:21
Show Gist options
  • Select an option

  • Save cloderic/78322313786b401e28de to your computer and use it in GitHub Desktop.

Select an option

Save cloderic/78322313786b401e28de to your computer and use it in GitHub Desktop.
Script to publish the content of a directory to git (useful for gh-pages)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import subprocess
import os
import shutil
import sys
import datetime
FILE_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
def main():
# Parse command line arguments
args_parser = argparse.ArgumentParser(
description="Publish the content of directory to a git repository.")
args_parser.add_argument(
"--repository",
required=True,
help="The target git repository")
args_parser.add_argument(
"--branch",
required=True,
help="The target git branch")
args_parser.add_argument(
"--working-directory",
help="The directory that is used as a basis to push (default is '%(default)s')",
default=os.path.relpath(os.path.join(FILE_DIR, 'publish')))
args_parser.add_argument(
"--directory",
help="The directory that you wish to publish (default is '%(default)s')",
default="./")
args_parser.add_argument(
"--author",
help="Author of the commit",
required=True)
args_parser.add_argument(
"--message",
help="Message of the commit",
required=True)
args = args_parser.parse_args()
print "Publishing '{}', to '{}/{}'.".format(args.directory, args.repository, args.branch)
try:
if os.path.exists(args.working_directory):
shutil.rmtree(args.working_directory)
shutil.copytree(args.directory, args.working_directory)
subprocess.check_output(
["git", "init"],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
subprocess.check_output(
["git", "checkout", "-B", args.branch],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
subprocess.check_output(
["git", "add", "*"],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
subprocess.check_output(
[
"git", "commit",
"--author={}".format(args.author),
"-m{} - {}".format(args.message, datetime.datetime.utcnow())
],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
subprocess.check_output(
["git", "remote", "add", "origin", args.repository],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
subprocess.check_output(
["git", "push", "origin", "+{}".format(args.branch)],
stderr=subprocess.STDOUT,
cwd=args.working_directory)
except subprocess.CalledProcessError, e:
raise RuntimeError("Error while publishing to git: {}".format(e.output))
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment