Skip to content

Instantly share code, notes, and snippets.

@brvier
Created January 24, 2017 05:47
Show Gist options
  • Save brvier/db40b60c2f67b51935993b40cfb568a9 to your computer and use it in GitHub Desktop.
Save brvier/db40b60c2f67b51935993b40cfb568a9 to your computer and use it in GitHub Desktop.
Autocommit git with dulwich
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()
@brvier
Copy link
Author

brvier commented Jan 24, 2017

Do not use, didn t works as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment