diff --git a/gitdriver.py b/gitdriver.py index 15473ed..2b74d55 100644 --- a/gitdriver.py +++ b/gitdriver.py @@ -22,6 +22,28 @@ def parse_args(): return p.parse_args() +def commit_revision(gd, opts, rev): + with open('content', 'w') as fd: + if 'exportLinks' in rev and not opts.raw: + # If the file provides an 'exportLinks' dictionary, + # download the requested MIME type. + r = gd.session.get(rev['exportLinks'][opts.mime_type]) + elif 'downloadUrl' in rev: + # Otherwise, if there is a downloadUrl, use that. + r = gd.session.get(rev['downloadUrl']) + else: + raise KeyError('unable to download revision') + + # Write file content into local file. + for chunk in r.iter_content(): + fd.write(chunk) + + # Commit changes to repository. + subprocess.call(['git', 'add', 'content']) + subprocess.call(['git', 'commit', '-m', + 'revision from %s' % rev['modifiedDate']]) + + def main(): opts = parse_args() if not opts.mime_type: @@ -41,33 +63,30 @@ def main(): # an exception if the file does not exist. md = gd.get_file_metadata(opts.docid) - # Initialize the git repository. - print 'Create repository "%(title)s"' % md - subprocess.call(['git','init',md['title']]) - os.chdir(md['title']) - - # Iterate over the revisions (from oldest to newest). - for rev in gd.revisions(opts.docid): - with open('content', 'w') as fd: - if 'exportLinks' in rev and not opts.raw: - # If the file provides an 'exportLinks' dictionary, - # download the requested MIME type. - r = gd.session.get(rev['exportLinks'][opts.mime_type]) - elif 'downloadUrl' in rev: - # Otherwise, if there is a downloadUrl, use that. - r = gd.session.get(rev['downloadUrl']) - else: - raise KeyError('unable to download revision') - - # Write file content into local file. - for chunk in r.iter_content(): - fd.write(chunk) - - # Commit changes to repository. - subprocess.call(['git', 'add', 'content']) - subprocess.call(['git', 'commit', '-m', - 'revision from %s' % rev['modifiedDate']]) + if os.path.isdir(md['title']): + # Find revision matching last commit and process only following revisions + os.chdir(md['title']) + print 'Update repository "%(title)s"' % md + last_commit_message = subprocess.check_output('git log -n 1 --format=%B', shell=True) + print 'Last commit: ' + last_commit_message + 'Iterating Google Drive revisions:' + revision_matched = False + for rev in gd.revisions(opts.docid): + if revision_matched: + print "New revision: " + rev['modifiedDate'] + commit_revision(gd, opts, rev) + if rev['modifiedDate'] in last_commit_message: + print "Found matching revision: " + rev['modifiedDate'] + revision_matched = True + print "Repository is up to date." + else: + # Initialize the git repository. + print 'Create repository "%(title)s"' % md + subprocess.call(['git','init',md['title']]) + os.chdir(md['title']) + # Iterate over the revisions (from oldest to newest). + for rev in gd.revisions(opts.docid): + commit_revision(gd, opts, rev) if __name__ == '__main__': main()