forked from pypingou/gitsync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitsync.py
executable file
·437 lines (363 loc) · 13.1 KB
/
gitsync.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# gitsync - a git-based synchronisation deamon.
#
# Copyright (C) 2011-2016 Pierre-Yves Chibon
# Author: Pierre-Yves Chibon <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.
# See http://www.gnu.org/copyleft/gpl.html for the full text of the
# license.
"""
import argparse
try:
import ConfigParser
except ImportError:
# PY3
import configparser as ConfigParser
import logging
import os
import subprocess
import threading
import time
import watchdog.events
from watchdog.observers import Observer
from pygit2 import Repository, Signature, Commit
from pygit2 import (GIT_STATUS_WT_NEW, GIT_STATUS_WT_DELETED,
GIT_STATUS_WT_MODIFIED)
__version__ = '1.1.0'
# Initial simple logging stuff
logging.basicConfig()
LOG = logging.getLogger('gitsync')
SETTINGS_FILE = os.path.join(
os.path.expanduser('~'), '.config', 'gitsync')
if not os.path.exists(SETTINGS_FILE):
SETTINGS_FILE = '/etc/gitsync.cfg'
OFFLINE_FILE = os.path.join(
os.environ['HOME'], '.config', 'gitsync.offline')
# Five seconds of sleep before pushing.
WAIT_N = 10
def get_arguments():
""" Set the command line parser and retrieve the arguments provided
by the command line.
"""
parser = argparse.ArgumentParser(
description='gitsync')
parser.add_argument(
'--config', dest='config', default=SETTINGS_FILE,
help='Configuration file to use instead of `%s`.' % SETTINGS_FILE)
parser.add_argument(
'--info', dest='info', action='store_true',
default=False,
help='Expand the level of information returned')
parser.add_argument(
'--debug', dest='debug', action='store_true',
default=False,
help='Expand even more the level of information returned')
parser.add_argument(
'--daemon', dest='daemon', action='store_true',
default=False,
help='Run gitsync in a daemon mode')
return parser.parse_args()
def run_cmd(cmd):
""" Run a given command using the popen module.
"""
LOG.debug('run cmd: `%s`' % ' '.join(cmd))
process = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE)
output = process.communicate()[0].strip().decode('utf-8')
if not process.returncode:
LOG.info('OUTPUT: ' + output)
return (process.returncode, output)
def run_pull_rebase(repo_path):
""" Run the git pull --rebase command and react accordingly to the
success of the task.
"""
cwd = os.getcwd()
os.chdir(repo_path)
run_cmd(['git', 'fetch'])
branch = run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[1]
no_fast_forward = run_cmd(f"git merge-base --is-ancestor origin/{branch} {branch}".split(" "))[0]
if no_fast_forward:
run_cmd(['git', 'stash'])
outcode_pull = run_cmd(['git', 'pull', '--rebase'])[0]
run_cmd(['git', 'stash', 'pop'])
os.chdir(cwd)
if not outcode_pull:
if os.path.exists(OFFLINE_FILE):
os.remove(OFFLINE_FILE)
else:
if not os.path.exists(OFFLINE_FILE):
open(OFFLINE_FILE, 'w')
print('Could not fetch from the remote repository')
else:
LOG.info('Could not fetch from the remote repository')
def run_push(repo_path):
""" Run the git push command. """
cwd = os.getcwd()
os.chdir(repo_path)
outcode = subprocess.call('git push', shell=True)
os.chdir(cwd)
return outcode
def docommit(repo, index, msg):
index.write()
tree = index.write_tree()
head = repo.lookup_reference('HEAD').peel(Commit)
commit = repo[head.oid]
committer = Signature(
'gitsync',
'root@localhost',
int(time.time()),
0)
LOG.info('Doing commit: %s' % msg)
sha = repo.create_commit(
'refs/heads/master', committer, committer, msg, tree, [head.hex])
commit = repo[sha]
return commit
def update_repo(reponame):
""" For a given path to a repo, pull/rebase the last changes if
it can, add/remove/commit the new changes and push them to the
remote repo if any.
:kwarg reponame, full path to a git repo.
"""
LOG.info('Processing %s' % reponame)
if not os.path.exists(reponame):
raise GitSyncError(
'The indicated working directory does not exists: %s' %
reponame)
try:
repo = Repository(reponame)
except Exception as err:
print(err)
raise GitSyncError(
'The indicated working directory is not a valid git '
'repository: %s' % reponame)
index = repo.index
dopush = False
origin = None
index = repo.index
# Add or remove to staging the files according to their status
if repo.status:
status = repo.status()
for filepath, flag in status.items():
if flag == GIT_STATUS_WT_DELETED:
msg = 'Remove file %s' % filepath
LOG.info(msg)
index.remove(filepath)
docommit(repo, index, msg)
dopush = True
elif flag == GIT_STATUS_WT_NEW:
msg = 'Add file %s' % filepath
LOG.info(msg)
index.add(filepath)
docommit(repo, index, msg)
dopush = True
elif flag == GIT_STATUS_WT_MODIFIED:
msg = 'Change file %s' % filepath
LOG.info(msg)
index.add(filepath)
docommit(repo, index, msg)
dopush = True
return dopush
class GitSyncEventHandler(watchdog.events.FileSystemEventHandler):
""" Dedicated Event Handler for gitsync. """
def __init__(self, repopath):
""" Constructor for the GitSyncEventHandler class.
Instanciate a pygit2.Repository object using the path to the repo
provided.
"""
self.repo = Repository(repopath)
self.log = LOG
self.do_push = False
self.thread = None
def pusher_thread(self):
self.log.debug("pusher thread is waiting %i seconds", WAIT_N)
self.log.debug("pusher thread waking up...")
if self.do_push:
self.log.debug("Pushing")
if not os.path.exists(OFFLINE_FILE):
run_pull_rebase(self.repo.workdir)
run_push(self.repo.workdir)
# Set this flag back to false when we're done
self.do_push = False
self.log.debug(" do push: %s", self.do_push)
else:
self.log.debug(" (push not actually set.. bailing out.)")
return
def on_any_event(self, event):
if '.git' in event.src_path:
return
if not self.do_push:
self.log.debug("Something changed, prepare to push")
self.do_push = True
self.thread = threading.Timer(WAIT_N, function=self.pusher_thread)
self.thread.start()
def on_deleted(self, event):
""" Upon deletion, delete the file from the git repo. """
if '.git' in event.src_path:
return
self.log.debug('on_deleted')
self.log.debug(event)
update_repo(self.repo.workdir)
def on_modified(self, event):
""" Upon modification, update the file in the git repo. """
if '.git' in event.src_path:
return
self.log.debug('on_modified')
self.log.debug(event)
update_repo(self.repo.workdir)
def on_moved(self, event):
""" Upon move, update the file in the git repo. """
if '.git' in event.src_path:
return
self.log.debug('on_moved')
self.log.debug(event)
update_repo(self.repo.workdir)
class GitSync(object):
""" Main class of the project, handles the command line arguments,
set the deamon, manage the Git repo.
"""
def __init__(self, configfile=SETTINGS_FILE, daemon=False):
self.log = LOG
self.settings = Settings(configfile)
if not self.settings.work_dir:
raise GitSyncError(
'No git repository set in %s' % configfile)
def update_sync_repo(repo):
"""
Local, internal method used to do the initial sync of the
repo in daemon mode, or the sync in single-run mode.
"""
run_pull_rebase(repo)
dopush = update_repo(os.path.expanduser(repo))
# if there is a remote, push to it
if dopush and not os.path.exists(OFFLINE_FILE):
run_pull_rebase(repo)
run_push(repo)
self.observers = []
if not daemon:
for repo in self.settings.work_dir.split(','):
repo = repo.strip()
if repo:
update_sync_repo(repo)
else:
for repo in self.settings.work_dir.split(','):
repo = repo.strip()
if repo:
# First update the repo as it is now
update_sync_repo(repo)
# Then starts the daemon mode
observer = Observer()
observer.schedule(
GitSyncEventHandler(repo), repo, recursive=True)
observer.start()
self.observers.append(observer)
class GitSyncError(Exception):
""" General Error class for gitsync. """
def __init__(self, value):
""" Instanciante the error. """
self.value = value
def __str__(self):
""" Represent the error. """
return repr(self.value)
class Settings(object):
""" gitsync Settings """
# Work directory
work_dir = ''
def __init__(self, configfile=SETTINGS_FILE):
"""Constructor of the Settings object.
This instanciate the Settings object and load into the _dict
attributes the default configuration which each available option.
"""
self._dict = {'work_dir': self.work_dir}
self.load_config(configfile, 'gitsync')
def load_config(self, configfile, sec):
"""Load the configuration in memory.
:arg configfile, name of the configuration file loaded.
:arg sec, section of the configuration retrieved.
"""
parser = ConfigParser.ConfigParser()
configfile = os.path.join(os.environ['HOME'], configfile)
is_new = self.create_conf(configfile)
parser.read(configfile)
if not parser.has_section(sec):
parser.add_section(sec)
self.populate(parser, sec)
if is_new:
self.save_config(configfile, parser)
def create_conf(self, configfile):
"""Check if the provided configuration file exists, generate the
folder if it does not and return True or False according to the
initial check.
:arg configfile, name of the configuration file looked for.
"""
if not os.path.exists(configfile):
dirname = os.path.dirname(configfile)
if not os.path.exists(dirname):
os.makedirs(dirname)
return True
return False
def save_config(self, configfile, parser):
"""Save the configuration into the specified file.
:arg configfile, name of the file in which to write the configuration
:arg parser, ConfigParser object containing the configuration to
write down.
"""
with open(configfile, 'w') as conf:
parser.write(conf)
def __getitem__(self, key):
hashstr = self._get_hash(key)
if not hashstr:
raise KeyError(key)
return self._dict.get(hashstr)
def populate(self, parser, section):
"""Set option values from a INI file section.
:arg parser: ConfigParser instance (or subclass)
:arg section: INI file section to read use.
"""
if parser.has_section(section):
opts = set(parser.options(section))
else:
opts = set()
for name in self._dict:
value = None
if name in opts:
value = parser.get(section, name)
setattr(self, name, value)
parser.set(section, name, value)
else:
parser.set(section, name, self._dict[name])
def main():
""" Main function of the programm.
"""
# Retrieve arguments
args = get_arguments()
if args.debug:
LOG.setLevel(logging.DEBUG)
else:
LOG.setLevel(logging.INFO)
try:
gitsync = GitSync(configfile=args.config, daemon=args.daemon)
except GitSyncError as msg:
print(msg)
return 1
if args.daemon:
try:
while True:
time.sleep(1)
except (KeyboardInterrupt, Exception):
LOG.info('Stopping thread')
for observer in gitsync.observers:
observer.stop()
LOG.debug('Waiting for threads to stop')
for observer in gitsync.observers:
observer.join()
return 0
if __name__ == '__main__':
main()