-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathrepo_dir_sync.py
More file actions
363 lines (296 loc) · 14.9 KB
/
repo_dir_sync.py
File metadata and controls
363 lines (296 loc) · 14.9 KB
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
# -*- coding: utf-8 -*-
import glob
import os
import shutil
from subprocess import Popen, PIPE
import re
import sys
from typing import List, Optional, Sequence
import platform
def popen(cmd):
shell = platform.system() != "Windows"
p = Popen(cmd, shell=shell, stdin=PIPE, stdout=PIPE)
return p
def call(cmd):
p = popen(cmd)
return p.stdout.read().decode("utf-8")
def execute(cmd, exceptionOnError=True):
"""
:param cmd: the command to execute
:param exceptionOnError: if True, raise on exception on error (return code not 0); if False return
whether the call was successful
:return: True if the call was successful, False otherwise (if exceptionOnError==False)
"""
p = popen(cmd)
p.wait()
success = p.returncode == 0
if exceptionOnError:
if not success:
raise Exception("Command failed: %s" % cmd)
else:
return success
def gitLog(path, arg):
oldPath = os.getcwd()
os.chdir(path)
lg = call("git log --no-merges " + arg)
os.chdir(oldPath)
return lg
def gitCommit(msg):
with open(COMMIT_MSG_FILENAME, "wb") as f:
f.write(msg.encode("utf-8"))
gitCommitWithMessageFromFile(COMMIT_MSG_FILENAME)
def gitCommitWithMessageFromFile(commitMsgFilename):
if not os.path.exists(commitMsgFilename):
raise FileNotFoundError(f"{commitMsgFilename} not found in {os.path.abspath(os.getcwd())}")
os.system(f"git commit --file={commitMsgFilename}")
os.unlink(commitMsgFilename)
COMMIT_MSG_FILENAME = "commitmsg.txt"
class OtherRepo:
SYNC_COMMIT_ID_FILE_LIB_REPO = ".syncCommitId.remote"
SYNC_COMMIT_ID_FILE_THIS_REPO = ".syncCommitId.this"
SYNC_COMMIT_MESSAGE = f"Updated %s sync commit identifiers"
SYNC_BACKUP_DIR = ".syncBackup"
def __init__(self, name, branch, pathToLib):
self.pathToLibInThisRepo = os.path.abspath(pathToLib)
if not os.path.exists(self.pathToLibInThisRepo):
raise ValueError(f"Repository directory '{self.pathToLibInThisRepo}' does not exist")
self.name = name
self.branch = branch
self.libRepo: Optional[LibRepo] = None
def isSyncEstablished(self):
return os.path.exists(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO))
def lastSyncIdThisRepo(self):
with open(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_THIS_REPO), "r") as f:
commitId = f.read().strip()
return commitId
def lastSyncIdLibRepo(self):
with open(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO), "r") as f:
commitId = f.read().strip()
return commitId
def gitLogThisRepoSinceLastSync(self):
lg = gitLog(self.pathToLibInThisRepo, '--name-only HEAD "^%s" .' % self.lastSyncIdThisRepo())
lg = re.sub(r'commit [0-9a-z]{8,40}\n.*\n.*\n\s*\n.*\n\s*(\n.*\.syncCommitId\.(this|remote))+', r"", lg, flags=re.MULTILINE) # remove commits with sync commit id update
indent = " "
lg = indent + lg.replace("\n", "\n" + indent)
return lg
def gitLogLibRepoSinceLastSync(self, libRepo: "LibRepo"):
syncIdFile = os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO)
if not os.path.exists(syncIdFile):
return ""
with open(syncIdFile, "r") as f:
syncId = f.read().strip()
lg = gitLog(libRepo.libPath, '--name-only HEAD "^%s" .' % syncId)
lg = re.sub(r"Sync (\w+)\n\s*\n", r"Sync\n\n", lg, flags=re.MULTILINE)
indent = " "
lg = indent + lg.replace("\n", "\n" + indent)
return "\n\n" + lg
def _userInputYesNo(self, question) -> bool:
result = None
while result not in ("y", "n"):
result = input(question + " [y|n]: ").strip()
return result == "y"
def pull(self, libRepo: "LibRepo"):
"""
Pulls in changes from this repository into the lib repo
"""
# switch to branch in lib repo
os.chdir(libRepo.rootPath)
execute("git checkout %s" % self.branch)
# check if the branch contains the commit that is referenced as the remote commit
remoteCommitId = self.lastSyncIdLibRepo()
remoteCommitExists = execute("git rev-list HEAD..%s" % remoteCommitId, exceptionOnError=False)
if not remoteCommitExists:
if not self._userInputYesNo(f"\nWARNING: The referenced remote commit {remoteCommitId} does not exist "
f"in your {self.libRepo.name} branch '{self.branch}'!\nSomeone else may have "
f"pulled/pushed in the meantime.\nIt is recommended that you do not continue. "
f"Continue?"):
return
# check if this branch is clean
lgLib = self.gitLogLibRepoSinceLastSync(libRepo).strip()
if lgLib != "":
print(f"The following changes have been added to this branch in the library:\n\n{lgLib}\n\n")
print(f"ERROR: You must push these changes before you can pull or reset this branch to {remoteCommitId}")
sys.exit(1)
# get log with relevant commits in this repo that are to be pulled
lg = self.gitLogThisRepoSinceLastSync()
os.chdir(libRepo.rootPath)
# create commit message file
commitMsg = f"Sync {self.name}\n\n" + lg
with open(COMMIT_MSG_FILENAME, "w") as f:
f.write(commitMsg)
# ask whether to commit these changes
print("Relevant commits:\n\n" + lg + "\n\n")
if not self._userInputYesNo(f"The above changes will be pulled from {self.name}.\n"
f"You may change the commit message by editing {os.path.abspath(COMMIT_MSG_FILENAME)}.\n"
"Continue?"):
os.unlink(COMMIT_MSG_FILENAME)
return
# prepare restoration of ignored files
self.prepare_restoration_of_ignored_files(libRepo.rootPath)
# remove library tree in lib repo
shutil.rmtree(self.libRepo.libDirectory)
# copy tree from this repo to lib repo (but drop the sync commit id files)
shutil.copytree(self.pathToLibInThisRepo, self.libRepo.libDirectory)
for fn in (self.SYNC_COMMIT_ID_FILE_LIB_REPO, self.SYNC_COMMIT_ID_FILE_THIS_REPO):
p = os.path.join(self.libRepo.libDirectory, fn)
if os.path.exists(p):
os.unlink(p)
# restore ignored directories/files
self.restore_ignored_files(libRepo.rootPath)
# make commit in lib repo
os.system("git add %s" % self.libRepo.libDirectory)
gitCommitWithMessageFromFile(COMMIT_MSG_FILENAME)
newSyncCommitIdLibRepo = call("git rev-parse HEAD").strip()
# update commit ids in this repo
os.chdir(self.pathToLibInThisRepo)
newSyncCommitIdThisRepo = call("git rev-parse HEAD").strip()
with open(self.SYNC_COMMIT_ID_FILE_LIB_REPO, "w") as f:
f.write(newSyncCommitIdLibRepo)
with open(self.SYNC_COMMIT_ID_FILE_THIS_REPO, "w") as f:
f.write(newSyncCommitIdThisRepo)
execute('git add %s %s' % (self.SYNC_COMMIT_ID_FILE_LIB_REPO, self.SYNC_COMMIT_ID_FILE_THIS_REPO))
execute(f'git commit -m "{self.SYNC_COMMIT_MESSAGE % self.libRepo.name} (pull)"')
print(f"\n\nIf everything was successful, you should now push your changes to branch "
f"'{self.branch}'\nand get your branch merged into develop (issuing a pull request where appropriate)")
def push(self, libRepo: "LibRepo"):
"""
Pushes changes from the lib repo to this repo
"""
os.chdir(libRepo.rootPath)
# switch to the source repo branch
execute(f"git checkout {self.branch}")
if self.isSyncEstablished():
# check if there are any commits that have not yet been pulled
unpulledCommits = self.gitLogThisRepoSinceLastSync().strip()
if unpulledCommits != "":
print(f"\n{unpulledCommits}\n\n")
if not self._userInputYesNo(f"WARNING: The above changes in repository '{self.name}' have not"
f" yet been pulled.\nYou might want to pull them.\n"
f"If you continue with the push, they will be lost. Continue?"):
return
# get change log in lib repo since last sync
libLogSinceLastSync = self.gitLogLibRepoSinceLastSync(libRepo)
print("Relevant commits:\n\n" + libLogSinceLastSync + "\n\n")
if not self._userInputYesNo("The above changes will be pushed. Continue?"):
return
print()
else:
libLogSinceLastSync = ""
# prepare restoration of ignored files in target repo
base_dir_this_repo = os.path.join(self.pathToLibInThisRepo, "..")
self.prepare_restoration_of_ignored_files(base_dir_this_repo)
# remove the target repo tree and update it with the tree from the source repo
shutil.rmtree(self.pathToLibInThisRepo)
shutil.copytree(libRepo.libPath, self.pathToLibInThisRepo)
# get the commit id of the source repo we just copied
commitId = call("git rev-parse HEAD").strip()
# restore ignored directories and files
self.restore_ignored_files(base_dir_this_repo)
# go to the target repo
os.chdir(self.pathToLibInThisRepo)
# commit new version in this repo
execute("git add .")
with open(self.SYNC_COMMIT_ID_FILE_LIB_REPO, "w") as f:
f.write(commitId)
execute("git add %s" % self.SYNC_COMMIT_ID_FILE_LIB_REPO)
gitCommit(f"{self.libRepo.name} {commitId}" + libLogSinceLastSync)
commitId = call("git rev-parse HEAD").strip()
# update information on the commit id we just added
with open(self.SYNC_COMMIT_ID_FILE_THIS_REPO, "w") as f:
f.write(commitId)
execute("git add %s" % self.SYNC_COMMIT_ID_FILE_THIS_REPO)
execute(f'git commit -m "{self.SYNC_COMMIT_MESSAGE % self.libRepo.name} (push)"')
os.chdir(libRepo.rootPath)
print(f"\n\nIf everything was successful, you should now update the remote branch:\ngit push")
def prepare_restoration_of_ignored_files(self, base_dir: str):
"""
:param base_dir: the directory containing the lib directory, to which ignored paths are relative
"""
cwd = os.getcwd()
os.chdir(base_dir)
# ensure backup dir exists and is empty
if os.path.exists(self.SYNC_BACKUP_DIR):
shutil.rmtree(self.SYNC_BACKUP_DIR)
os.mkdir(self.SYNC_BACKUP_DIR)
# backup ignored, unversioned directories
for d in self.libRepo.fullyIgnoredUnversionedDirectories:
if os.path.exists(d):
shutil.copytree(d, os.path.join(self.SYNC_BACKUP_DIR, d))
os.chdir(cwd)
def restore_ignored_files(self, base_dir: str):
"""
:param base_dir: the directory containing the lib directory, to which ignored paths are relative
"""
cwd = os.getcwd()
os.chdir(base_dir)
# remove fully ignored directories that were overwritten by the sync
for d in self.libRepo.fullyIgnoredVersionedDirectories + self.libRepo.fullyIgnoredUnversionedDirectories:
if os.path.exists(d):
print("Removing overwritten content: %s" % d)
shutil.rmtree(d)
# restore directories and files that can be restored via git
for d in self.libRepo.ignoredDirectories + self.libRepo.fullyIgnoredVersionedDirectories:
restoration_cmd = "git checkout %s" % d
print("Restoring: %s" % restoration_cmd)
os.system(restoration_cmd)
for pattern in self.libRepo.ignoredFileGlobPatterns:
for path in glob.glob(pattern, recursive=True):
print("Restoring via git: %s" % path)
os.system("git checkout %s" % path)
# restore directories that were backed up
for d in self.libRepo.fullyIgnoredUnversionedDirectories:
if os.path.exists(os.path.join(self.SYNC_BACKUP_DIR, d)):
print("Restoring from backup: %s" % d)
shutil.copytree(os.path.join(self.SYNC_BACKUP_DIR, d), d)
# remove backup dir
shutil.rmtree(self.SYNC_BACKUP_DIR)
os.chdir(cwd)
class LibRepo:
def __init__(self, name: str, libDirectory: str,
ignoredDirectories: Sequence[str] = (),
fullyIgnoredVersionedDirectories: Sequence[str] = (),
fullyIgnoredUnversionedDirectories: Sequence[str] = (),
ignoredFileGlobPatterns: Sequence[str] = ()
):
"""
:param name: name of the library being synced
:param libDirectory: relative path to the library directory within this repo
:param ignoredDirectories: ignored directories; existing files in ignored directories will be restored
via 'git checkout' on pull/push, but new files will be added.
This is useful for configuration-like files, where users may have local changes that should not
be overwritten, but new files should still be added.
:param fullyIgnoredVersionedDirectories:
fully ignored versioned directories will be restored to original state after push/pull via git checkout
:param fullyIgnoredUnversionedDirectories:
fully ignored unversioned directories will be backed up and restored to original state after push/pull
:param ignoredFileGlobPatterns: files matching ignored glob patterns will be restored via 'git checkout'
on pull/push
"""
self.name = name
self.rootPath = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
self.libDirectory = libDirectory
self.libPath = os.path.join(self.rootPath, self.libDirectory)
self.ignoredDirectories: List[str] = list(ignoredDirectories)
self.fullyIgnoredVersionedDirectories: List[str] = list(fullyIgnoredVersionedDirectories)
self.fullyIgnoredUnversionedDirectories: List[str] = list(fullyIgnoredUnversionedDirectories)
self.ignoredFileGlobPatterns: List[str] = list(ignoredFileGlobPatterns)
self.otherRepos: List[OtherRepo] = []
def add(self, repo: OtherRepo):
repo.libRepo = self
self.otherRepos.append(repo)
def runMain(self):
repos = self.otherRepos
args = sys.argv[1:]
if len(args) != 2:
print(f"usage: sync.py <{'|'.join([repo.name for repo in repos])}> <push|pull>")
else:
repo = [r for r in repos if r.name == args[0]]
if len(repo) != 1:
raise ValueError(f"Unknown repo '{args[0]}'")
repo = repo[0]
if args[1] == "push":
repo.push(self)
elif args[1] == "pull":
repo.pull(self)
else:
raise ValueError(f"Unknown command '{args[1]}'")