Created
January 24, 2017 05:47
-
-
Save brvier/db40b60c2f67b51935993b40cfb568a9 to your computer and use it in GitHub Desktop.
Autocommit git with dulwich
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dulwich import porcelain | |
import os | |
import os.path | |
import sys | |
import io | |
class GitRepository: | |
def __init__(self, localpath=os.path.expanduser('~/Notes'), remote=None): | |
self.localpath = localpath | |
self.remote = remote | |
try: | |
os.mkdir(self.localpath) | |
except: | |
pass | |
try: | |
porcelain.init(self.localpath) | |
except OSError as err: | |
porcelain.open_repo(self.localpath) | |
def addFiles(self): | |
for path, folders, files in os.walk(self.localpath): | |
for afile in files: | |
if '.git' not in path: | |
print('Adding file to index ', os.path.join(path, afile), | |
[os.path.relpath(os.path.join(path, afile), | |
self.localpath), ]) | |
porcelain.add(self.localpath, | |
[os.path.relpath(os.path.join(path, afile), | |
self.localpath), ]) | |
def removeFiles(self): | |
print(porcelain.get_tree_changes(self.localpath)) | |
status = porcelain.status(self.localpath) | |
porcelain.rm(self.localpath, [afile for afile in status.unstaged | |
if not os.path.exists(afile)]) | |
def removeFile(self, path): | |
print('Removing from index %s' % path) | |
porcelain.rm(repo=self.localpath, paths=[path, ]) | |
os.remove(os.path.join(self.localpath, path)) | |
self.commit() | |
def commit(self,): | |
print(porcelain.status(self.localpath)) | |
status = porcelain.status(self.localpath) | |
if ((len(status.staged['delete']) != 0) or | |
(len(status.staged['add']) != 0) or | |
(len(status.staged['modify']) != 0)): | |
porcelain.commit(self.localpath, | |
b'Automated commit', | |
author=b'git <git@khertan.net>', | |
committer=b'git <git@khertan.net>') | |
else: | |
print('Nothing to commit') | |
def sync(self,): | |
# autocommit | |
self.removeFiles() | |
self.addFiles() | |
self.commit() | |
stderr = io.BytesIO() | |
print('Pushing...') | |
# push | |
porcelain.push(self.localpath, | |
self.remote.encode('utf-8'), | |
errstream=stderr, | |
refspecs=b'refs/heads/master' | |
) | |
print(stderr.read().decode('utf-8')) | |
print('Pulling...') | |
# pull | |
porcelain.pull(self.localpath, | |
self.remote, | |
refspecs=b'refs/heads/master', | |
errstream=stderr) | |
print(stderr.read().decode('utf-8')) | |
print('Sync done') | |
if __name__ == '__main__': | |
repo = GitRepository(localpath=os.path.expanduser(sys.argv[1]), | |
remote=sys.argv[2]) | |
repo.sync() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do not use, didn t works as expected