git-remote-dropbox 2.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- git_remote_dropbox/__init__.py +21 -0
- git_remote_dropbox/cli/__init__.py +0 -0
- git_remote_dropbox/cli/common.py +96 -0
- git_remote_dropbox/cli/helper.py +31 -0
- git_remote_dropbox/cli/manage.py +164 -0
- git_remote_dropbox/constants.py +9 -0
- git_remote_dropbox/git.py +184 -0
- git_remote_dropbox/helper.py +562 -0
- git_remote_dropbox/util.py +279 -0
- git_remote_dropbox-2.0.1.dist-info/LICENSE.md +22 -0
- git_remote_dropbox-2.0.1.dist-info/METADATA +199 -0
- git_remote_dropbox-2.0.1.dist-info/RECORD +15 -0
- git_remote_dropbox-2.0.1.dist-info/WHEEL +5 -0
- git_remote_dropbox-2.0.1.dist-info/entry_points.txt +4 -0
- git_remote_dropbox-2.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
from git_remote_dropbox.constants import (
|
|
2
|
+
PROCESSES,
|
|
3
|
+
CHUNK_SIZE,
|
|
4
|
+
MAX_RETRIES,
|
|
5
|
+
)
|
|
6
|
+
from git_remote_dropbox.util import (
|
|
7
|
+
readline,
|
|
8
|
+
Level,
|
|
9
|
+
stdout,
|
|
10
|
+
stderr,
|
|
11
|
+
Binder,
|
|
12
|
+
Poison,
|
|
13
|
+
Token,
|
|
14
|
+
)
|
|
15
|
+
from git_remote_dropbox import git
|
|
16
|
+
|
|
17
|
+
import dropbox # type: ignore
|
|
18
|
+
|
|
19
|
+
import multiprocessing
|
|
20
|
+
import multiprocessing.dummy
|
|
21
|
+
import multiprocessing.pool
|
|
22
|
+
import posixpath
|
|
23
|
+
import sys
|
|
24
|
+
import threading
|
|
25
|
+
from typing import Optional, Union, NoReturn, Tuple, Dict, List, Set
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
# Importing synchronize is to detect platforms where
|
|
29
|
+
# multiprocessing does not work (python issue 3770)
|
|
30
|
+
# and cause an ImportError. Otherwise it will happen
|
|
31
|
+
# later when trying to use Queue().
|
|
32
|
+
from multiprocessing import synchronize as _
|
|
33
|
+
from multiprocessing import Queue
|
|
34
|
+
except ImportError:
|
|
35
|
+
from queue import Queue # type: ignore
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Helper:
|
|
39
|
+
"""
|
|
40
|
+
A git remote helper to communicate with Dropbox.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, token: Token, path: str, processes: int = PROCESSES) -> None:
|
|
44
|
+
self._token = token
|
|
45
|
+
self._per_thread = threading.local()
|
|
46
|
+
self._path = path
|
|
47
|
+
self._processes = processes
|
|
48
|
+
self._verbosity = Level.INFO # default verbosity
|
|
49
|
+
self._refs: Dict[str, Tuple[str, str]] = {} # map from remote ref name => (rev number, sha)
|
|
50
|
+
self._pushed: Dict[str, str] = {} # map from remote ref name => sha
|
|
51
|
+
self._first_push = False
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def verbosity(self) -> Level:
|
|
55
|
+
return self._verbosity
|
|
56
|
+
|
|
57
|
+
def _trace(self, message: str, level: Level = Level.DEBUG, exact: bool = False) -> None:
|
|
58
|
+
"""
|
|
59
|
+
Log a message with a given severity level.
|
|
60
|
+
"""
|
|
61
|
+
if level > self._verbosity:
|
|
62
|
+
return
|
|
63
|
+
if exact:
|
|
64
|
+
if level == self._verbosity:
|
|
65
|
+
stderr(message)
|
|
66
|
+
return
|
|
67
|
+
if level <= Level.ERROR:
|
|
68
|
+
stderr("error: %s\n" % message)
|
|
69
|
+
elif level == Level.INFO:
|
|
70
|
+
stderr("info: %s\n" % message)
|
|
71
|
+
elif level >= Level.DEBUG:
|
|
72
|
+
stderr("debug: %s\n" % message)
|
|
73
|
+
|
|
74
|
+
def _fatal(self, message: str) -> NoReturn:
|
|
75
|
+
"""
|
|
76
|
+
Log a fatal error and exit.
|
|
77
|
+
"""
|
|
78
|
+
self._trace(message, Level.ERROR)
|
|
79
|
+
sys.exit(1)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def _connection(self) -> dropbox.Dropbox:
|
|
83
|
+
"""
|
|
84
|
+
Return a Dropbox connection object private to this thread.
|
|
85
|
+
|
|
86
|
+
Lazily initialized per-thread.
|
|
87
|
+
"""
|
|
88
|
+
if not hasattr(self._per_thread, "connection"):
|
|
89
|
+
self._per_thread.connection = self._token.connect()
|
|
90
|
+
return self._per_thread.connection
|
|
91
|
+
|
|
92
|
+
def run(self) -> None:
|
|
93
|
+
"""
|
|
94
|
+
Run the helper following the git remote helper communication protocol.
|
|
95
|
+
"""
|
|
96
|
+
while True:
|
|
97
|
+
line = readline()
|
|
98
|
+
if line == "capabilities":
|
|
99
|
+
_write("option")
|
|
100
|
+
_write("push")
|
|
101
|
+
_write("fetch")
|
|
102
|
+
_write()
|
|
103
|
+
elif line.startswith("option"):
|
|
104
|
+
self._do_option(line)
|
|
105
|
+
elif line.startswith("list"):
|
|
106
|
+
self._do_list(line)
|
|
107
|
+
elif line.startswith("push"):
|
|
108
|
+
self._do_push(line)
|
|
109
|
+
elif line.startswith("fetch"):
|
|
110
|
+
self._do_fetch(line)
|
|
111
|
+
elif line == "":
|
|
112
|
+
break
|
|
113
|
+
else:
|
|
114
|
+
self._fatal("unsupported operation: %s" % line)
|
|
115
|
+
|
|
116
|
+
def _do_option(self, line: str) -> None:
|
|
117
|
+
"""
|
|
118
|
+
Handle the option command.
|
|
119
|
+
"""
|
|
120
|
+
if line.startswith("option verbosity"):
|
|
121
|
+
self._verbosity = Level(int(line[len("option verbosity ") :]))
|
|
122
|
+
_write("ok")
|
|
123
|
+
else:
|
|
124
|
+
_write("unsupported")
|
|
125
|
+
|
|
126
|
+
def _do_list(self, line: str) -> None:
|
|
127
|
+
"""
|
|
128
|
+
Handle the list command.
|
|
129
|
+
"""
|
|
130
|
+
for_push = "for-push" in line
|
|
131
|
+
refs = self.get_refs(for_push=for_push)
|
|
132
|
+
for sha, ref in refs:
|
|
133
|
+
_write("%s %s" % (sha, ref))
|
|
134
|
+
if not for_push:
|
|
135
|
+
head = self.read_symbolic_ref("HEAD")
|
|
136
|
+
if head:
|
|
137
|
+
_write("@%s HEAD" % head[1])
|
|
138
|
+
else:
|
|
139
|
+
self._trace("no default branch on remote", Level.INFO)
|
|
140
|
+
_write()
|
|
141
|
+
|
|
142
|
+
def _do_push(self, line: str) -> None:
|
|
143
|
+
"""
|
|
144
|
+
Handle the push command.
|
|
145
|
+
"""
|
|
146
|
+
remote_head = None
|
|
147
|
+
while True:
|
|
148
|
+
src, dst = line.split(" ")[1].split(":")
|
|
149
|
+
if src == "":
|
|
150
|
+
self._delete(dst)
|
|
151
|
+
else:
|
|
152
|
+
self._push(src, dst)
|
|
153
|
+
if self._first_push:
|
|
154
|
+
if not remote_head or src == git.symbolic_ref("HEAD"):
|
|
155
|
+
remote_head = dst
|
|
156
|
+
line = readline()
|
|
157
|
+
if line == "":
|
|
158
|
+
if self._first_push:
|
|
159
|
+
self._first_push = False
|
|
160
|
+
if remote_head:
|
|
161
|
+
if not self.write_symbolic_ref("HEAD", remote_head):
|
|
162
|
+
self._trace("failed to set default branch on remote", Level.INFO)
|
|
163
|
+
else:
|
|
164
|
+
self._trace("first push but no branch to set remote HEAD")
|
|
165
|
+
break
|
|
166
|
+
_write()
|
|
167
|
+
|
|
168
|
+
def _do_fetch(self, line: str) -> None:
|
|
169
|
+
"""
|
|
170
|
+
Handle the fetch command.
|
|
171
|
+
"""
|
|
172
|
+
while True:
|
|
173
|
+
_, sha, value = line.split(" ")
|
|
174
|
+
self._fetch(sha)
|
|
175
|
+
line = readline()
|
|
176
|
+
if line == "":
|
|
177
|
+
break
|
|
178
|
+
_write()
|
|
179
|
+
|
|
180
|
+
def _delete(self, ref: str) -> None:
|
|
181
|
+
"""
|
|
182
|
+
Delete the ref from the remote.
|
|
183
|
+
"""
|
|
184
|
+
self._trace("deleting ref %s" % ref)
|
|
185
|
+
head = self.read_symbolic_ref("HEAD")
|
|
186
|
+
if head and ref == head[1]:
|
|
187
|
+
_write("error %s refusing to delete the current branch: %s" % (ref, head))
|
|
188
|
+
return
|
|
189
|
+
try:
|
|
190
|
+
self._connection.files_delete(self._ref_path(ref))
|
|
191
|
+
except dropbox.exceptions.ApiError as e:
|
|
192
|
+
if not isinstance(e.error, dropbox.files.DeleteError):
|
|
193
|
+
raise
|
|
194
|
+
# someone else might have deleted it first, that's fine
|
|
195
|
+
self._refs.pop(ref, None) # discard
|
|
196
|
+
self._pushed.pop(ref, None) # discard
|
|
197
|
+
_write("ok %s" % ref)
|
|
198
|
+
|
|
199
|
+
def _push(self, src: str, dst: str) -> None:
|
|
200
|
+
"""
|
|
201
|
+
Push src to dst on the remote.
|
|
202
|
+
"""
|
|
203
|
+
force = False
|
|
204
|
+
if src.startswith("+"):
|
|
205
|
+
src = src[1:]
|
|
206
|
+
force = True
|
|
207
|
+
present = [self._refs[name][1] for name in self._refs]
|
|
208
|
+
present.extend(self._pushed.values())
|
|
209
|
+
# before updating the ref, write all objects that are referenced
|
|
210
|
+
objects = git.list_objects(src, present)
|
|
211
|
+
try:
|
|
212
|
+
# upload objects in parallel
|
|
213
|
+
pool = multiprocessing.pool.ThreadPool(processes=self._processes)
|
|
214
|
+
res = pool.imap_unordered(Binder(self, "_put_object"), objects)
|
|
215
|
+
# show progress
|
|
216
|
+
total = len(objects)
|
|
217
|
+
self._trace("", level=Level.INFO, exact=True)
|
|
218
|
+
for done, _ in enumerate(res, 1):
|
|
219
|
+
pct = int(float(done) / total * 100)
|
|
220
|
+
message = "\rWriting objects: {:3.0f}% ({}/{})".format(pct, done, total)
|
|
221
|
+
if done == total:
|
|
222
|
+
message = "%s, done.\n" % message
|
|
223
|
+
self._trace(message, level=Level.INFO, exact=True)
|
|
224
|
+
except Exception:
|
|
225
|
+
if self.verbosity >= Level.DEBUG:
|
|
226
|
+
raise # re-raise exception so it prints out a stack trace
|
|
227
|
+
else:
|
|
228
|
+
self._fatal("exception while writing objects (run with -v for details)\n")
|
|
229
|
+
sha = git.ref_value(src)
|
|
230
|
+
error = self._write_ref(sha, dst, force)
|
|
231
|
+
if error is None:
|
|
232
|
+
_write("ok %s" % dst)
|
|
233
|
+
self._pushed[dst] = sha
|
|
234
|
+
else:
|
|
235
|
+
_write("error %s %s" % (dst, error))
|
|
236
|
+
|
|
237
|
+
def _ref_path(self, name: str) -> str:
|
|
238
|
+
"""
|
|
239
|
+
Return the path to the given ref on the remote.
|
|
240
|
+
"""
|
|
241
|
+
assert name.startswith("refs/")
|
|
242
|
+
return posixpath.join(self._path, name)
|
|
243
|
+
|
|
244
|
+
def _ref_name_from_path(self, path: str) -> str:
|
|
245
|
+
"""
|
|
246
|
+
Return the ref name given the full path of the remote ref.
|
|
247
|
+
"""
|
|
248
|
+
prefix = "%s/" % self._path
|
|
249
|
+
assert path.startswith(prefix)
|
|
250
|
+
return path[len(prefix) :]
|
|
251
|
+
|
|
252
|
+
def _object_path(self, name: str) -> str:
|
|
253
|
+
"""
|
|
254
|
+
Return the path to the given object on the remote.
|
|
255
|
+
"""
|
|
256
|
+
prefix = name[:2]
|
|
257
|
+
suffix = name[2:]
|
|
258
|
+
return posixpath.join(self._path, "objects", prefix, suffix)
|
|
259
|
+
|
|
260
|
+
def _get_file(self, path: str) -> Tuple[str, bytes]:
|
|
261
|
+
"""
|
|
262
|
+
Return the revision number and content of a given file on the remote.
|
|
263
|
+
|
|
264
|
+
Return a tuple (revision, content).
|
|
265
|
+
"""
|
|
266
|
+
self._trace("fetching: %s" % path)
|
|
267
|
+
meta, resp = self._connection.files_download(path)
|
|
268
|
+
return (meta.rev, resp.content)
|
|
269
|
+
|
|
270
|
+
def _get_files(self, paths: List[str]) -> List[Tuple[str, bytes]]:
|
|
271
|
+
"""
|
|
272
|
+
Return a list of (revision number, content) for a given list of files.
|
|
273
|
+
"""
|
|
274
|
+
pool = multiprocessing.dummy.Pool(self._processes)
|
|
275
|
+
return pool.map(self._get_file, paths) # type: ignore
|
|
276
|
+
|
|
277
|
+
def _put_object(self, sha: str) -> None:
|
|
278
|
+
"""
|
|
279
|
+
Upload an object to the remote.
|
|
280
|
+
"""
|
|
281
|
+
data = git.encode_object(sha)
|
|
282
|
+
path = self._object_path(sha)
|
|
283
|
+
self._trace("writing: %s" % path)
|
|
284
|
+
retries = 0
|
|
285
|
+
mode = dropbox.files.WriteMode.overwrite
|
|
286
|
+
|
|
287
|
+
if len(data) <= CHUNK_SIZE:
|
|
288
|
+
while True:
|
|
289
|
+
try:
|
|
290
|
+
self._connection.files_upload(data, path, mode, strict_conflict=True, mute=True)
|
|
291
|
+
except dropbox.exceptions.InternalServerError:
|
|
292
|
+
self._trace("internal server error writing %s, retrying" % sha)
|
|
293
|
+
if retries < MAX_RETRIES:
|
|
294
|
+
retries += 1
|
|
295
|
+
else:
|
|
296
|
+
raise
|
|
297
|
+
else:
|
|
298
|
+
break
|
|
299
|
+
else:
|
|
300
|
+
cursor = dropbox.files.UploadSessionCursor(offset=0)
|
|
301
|
+
done_uploading = False
|
|
302
|
+
|
|
303
|
+
while not done_uploading:
|
|
304
|
+
try:
|
|
305
|
+
end = cursor.offset + CHUNK_SIZE
|
|
306
|
+
chunk = data[(cursor.offset) : end]
|
|
307
|
+
|
|
308
|
+
if cursor.offset == 0:
|
|
309
|
+
# upload first chunk
|
|
310
|
+
result = self._connection.files_upload_session_start(chunk)
|
|
311
|
+
cursor.session_id = result.session_id
|
|
312
|
+
elif end < len(data):
|
|
313
|
+
# upload intermediate chunks
|
|
314
|
+
self._connection.files_upload_session_append_v2(chunk, cursor)
|
|
315
|
+
else:
|
|
316
|
+
# upload the last chunk
|
|
317
|
+
commit_info = dropbox.files.CommitInfo(
|
|
318
|
+
path, mode, strict_conflict=True, mute=True
|
|
319
|
+
)
|
|
320
|
+
self._connection.files_upload_session_finish(chunk, cursor, commit_info)
|
|
321
|
+
done_uploading = True
|
|
322
|
+
|
|
323
|
+
# advance cursor to next chunk
|
|
324
|
+
cursor.offset = end
|
|
325
|
+
|
|
326
|
+
except dropbox.files.UploadSessionOffsetError as offset_error:
|
|
327
|
+
self._trace("offset error writing %s, retrying" % sha)
|
|
328
|
+
cursor.offset = offset_error.correct_offset
|
|
329
|
+
if retries < MAX_RETRIES:
|
|
330
|
+
retries += 1
|
|
331
|
+
else:
|
|
332
|
+
raise
|
|
333
|
+
except dropbox.exceptions.InternalServerError:
|
|
334
|
+
self._trace("internal server error writing %s, retrying" % sha)
|
|
335
|
+
if retries < MAX_RETRIES:
|
|
336
|
+
retries += 1
|
|
337
|
+
else:
|
|
338
|
+
raise
|
|
339
|
+
|
|
340
|
+
def _download(
|
|
341
|
+
self, input_queue: "Queue[Union[str, Poison]]", output_queue: "Queue[Union[str, Poison]]"
|
|
342
|
+
) -> None:
|
|
343
|
+
"""
|
|
344
|
+
Download files given in input_queue and push results to output_queue.
|
|
345
|
+
"""
|
|
346
|
+
while True:
|
|
347
|
+
try:
|
|
348
|
+
obj = input_queue.get()
|
|
349
|
+
if isinstance(obj, Poison):
|
|
350
|
+
return
|
|
351
|
+
_, data = self._get_file(self._object_path(obj))
|
|
352
|
+
computed_sha = git.decode_object(data)
|
|
353
|
+
if computed_sha != obj:
|
|
354
|
+
output_queue.put(Poison("hash mismatch %s != %s" % (computed_sha, obj)))
|
|
355
|
+
output_queue.put(obj)
|
|
356
|
+
except Exception as e:
|
|
357
|
+
output_queue.put(Poison("exception while downloading: %s" % e))
|
|
358
|
+
|
|
359
|
+
def _fetch(self, sha: str) -> None:
|
|
360
|
+
"""
|
|
361
|
+
Recursively fetch the given object and the objects it references.
|
|
362
|
+
"""
|
|
363
|
+
# have multiple threads downloading in parallel
|
|
364
|
+
queue = [sha]
|
|
365
|
+
pending: Set[str] = set()
|
|
366
|
+
downloaded: Set[str] = set()
|
|
367
|
+
input_queue: "Queue[Union[str, Poison]]" = Queue() # requesting downloads
|
|
368
|
+
output_queue: "Queue[Union[str, Poison]]" = Queue() # completed downloads
|
|
369
|
+
procs = []
|
|
370
|
+
for _ in range(self._processes):
|
|
371
|
+
target = Binder(self, "_download")
|
|
372
|
+
args = (input_queue, output_queue)
|
|
373
|
+
# use multiprocessing.dummy to use threads instead of processes
|
|
374
|
+
proc = multiprocessing.dummy.Process(target=target, args=args)
|
|
375
|
+
proc.daemon = True
|
|
376
|
+
proc.start()
|
|
377
|
+
procs.append(proc)
|
|
378
|
+
self._trace("", level=Level.INFO, exact=True) # for showing progress
|
|
379
|
+
done = total = 0
|
|
380
|
+
while queue or pending:
|
|
381
|
+
if queue:
|
|
382
|
+
# if possible, queue up download
|
|
383
|
+
sha = queue.pop()
|
|
384
|
+
if sha in downloaded or sha in pending:
|
|
385
|
+
continue
|
|
386
|
+
if git.object_exists(sha):
|
|
387
|
+
if sha == git.EMPTY_TREE_HASH:
|
|
388
|
+
# git.object_exists() returns True for the empty
|
|
389
|
+
# tree hash even if it's not present in the object
|
|
390
|
+
# store. Everything will work fine in this situation,
|
|
391
|
+
# but `git fsck` will complain if it's not present, so
|
|
392
|
+
# we explicitly add it to avoid that.
|
|
393
|
+
git.write_object("tree", b"")
|
|
394
|
+
if not git.history_exists(sha):
|
|
395
|
+
# this can only happen in the case of aborted fetches
|
|
396
|
+
# that are resumed later
|
|
397
|
+
self._trace("missing part of history from %s" % sha)
|
|
398
|
+
queue.extend(git.referenced_objects(sha))
|
|
399
|
+
else:
|
|
400
|
+
self._trace("%s already downloaded" % sha)
|
|
401
|
+
else:
|
|
402
|
+
pending.add(sha)
|
|
403
|
+
input_queue.put(sha)
|
|
404
|
+
else:
|
|
405
|
+
# process completed download
|
|
406
|
+
res = output_queue.get()
|
|
407
|
+
if isinstance(res, Poison):
|
|
408
|
+
# _download never puts Poison with an empty message in the output_queue
|
|
409
|
+
assert res.message is not None
|
|
410
|
+
self._fatal(res.message)
|
|
411
|
+
pending.remove(res)
|
|
412
|
+
downloaded.add(res)
|
|
413
|
+
queue.extend(git.referenced_objects(res))
|
|
414
|
+
# show progress
|
|
415
|
+
done = len(downloaded)
|
|
416
|
+
total = done + len(pending)
|
|
417
|
+
pct = int(float(done) / total * 100)
|
|
418
|
+
message = "\rReceiving objects: {:3.0f}% ({}/{})".format(pct, done, total)
|
|
419
|
+
self._trace(message, level=Level.INFO, exact=True)
|
|
420
|
+
if total:
|
|
421
|
+
self._trace(
|
|
422
|
+
"\rReceiving objects: 100% ({}/{}), done.\n".format(done, total),
|
|
423
|
+
level=Level.INFO,
|
|
424
|
+
exact=True,
|
|
425
|
+
)
|
|
426
|
+
for proc in procs:
|
|
427
|
+
input_queue.put(Poison())
|
|
428
|
+
for proc in procs:
|
|
429
|
+
proc.join()
|
|
430
|
+
|
|
431
|
+
def _write_ref(self, new_sha: str, dst: str, force: bool = False) -> Optional[str]:
|
|
432
|
+
"""
|
|
433
|
+
Atomically update the given reference to point to the given object.
|
|
434
|
+
|
|
435
|
+
Return None if there is no error, otherwise return a description of the
|
|
436
|
+
error.
|
|
437
|
+
"""
|
|
438
|
+
path = self._ref_path(dst)
|
|
439
|
+
if force:
|
|
440
|
+
# overwrite regardless of what is there before
|
|
441
|
+
mode = dropbox.files.WriteMode.overwrite
|
|
442
|
+
else:
|
|
443
|
+
info = self._refs.get(dst, None)
|
|
444
|
+
if info:
|
|
445
|
+
rev, sha = info
|
|
446
|
+
if not git.object_exists(sha):
|
|
447
|
+
return "fetch first"
|
|
448
|
+
is_fast_forward = git.is_ancestor(sha, new_sha)
|
|
449
|
+
if not is_fast_forward and not force:
|
|
450
|
+
return "non-fast forward"
|
|
451
|
+
# perform an atomic compare-and-swap
|
|
452
|
+
mode = dropbox.files.WriteMode.update(rev)
|
|
453
|
+
else:
|
|
454
|
+
# perform an atomic add, which fails if a concurrent writer
|
|
455
|
+
# writes before this does
|
|
456
|
+
mode = dropbox.files.WriteMode.add
|
|
457
|
+
self._trace("writing ref %s with mode %s" % (dst, mode))
|
|
458
|
+
data = ("%s\n" % new_sha).encode("utf8")
|
|
459
|
+
try:
|
|
460
|
+
self._connection.files_upload(data, path, mode, strict_conflict=True, mute=True)
|
|
461
|
+
except dropbox.exceptions.ApiError as e:
|
|
462
|
+
if not isinstance(e.error, dropbox.files.UploadError):
|
|
463
|
+
raise
|
|
464
|
+
return "fetch first"
|
|
465
|
+
else:
|
|
466
|
+
return None
|
|
467
|
+
|
|
468
|
+
def get_refs(self, for_push: bool) -> List[Tuple[str, str]]:
|
|
469
|
+
"""
|
|
470
|
+
Return the refs present on the remote.
|
|
471
|
+
|
|
472
|
+
Return a list of tuples of (sha, name).
|
|
473
|
+
"""
|
|
474
|
+
try:
|
|
475
|
+
loc = posixpath.join(self._path, "refs")
|
|
476
|
+
res = self._connection.files_list_folder(loc, recursive=True)
|
|
477
|
+
files = res.entries
|
|
478
|
+
while res.has_more:
|
|
479
|
+
res = self._connection.files_list_folder_continue(res.cursor)
|
|
480
|
+
files.extend(res.entries)
|
|
481
|
+
except dropbox.exceptions.ApiError as e:
|
|
482
|
+
if not isinstance(e.error, dropbox.files.ListFolderError):
|
|
483
|
+
raise
|
|
484
|
+
if not for_push:
|
|
485
|
+
# if we're pushing, it's okay if nothing exists beforehand,
|
|
486
|
+
# but it's good to notify the user just in case
|
|
487
|
+
self._trace("repository is empty", Level.INFO)
|
|
488
|
+
else:
|
|
489
|
+
self._first_push = True
|
|
490
|
+
return []
|
|
491
|
+
files = [i for i in files if isinstance(i, dropbox.files.FileMetadata)]
|
|
492
|
+
paths = [i.path_lower for i in files]
|
|
493
|
+
if not paths:
|
|
494
|
+
return []
|
|
495
|
+
revs: List[str] = []
|
|
496
|
+
data: List[bytes] = []
|
|
497
|
+
for rev, datum in self._get_files(paths):
|
|
498
|
+
revs.append(rev)
|
|
499
|
+
data.append(datum)
|
|
500
|
+
refs = []
|
|
501
|
+
for path, rev, datum in zip(paths, revs, data):
|
|
502
|
+
name = self._ref_name_from_path(path)
|
|
503
|
+
sha = datum.decode("utf8").strip()
|
|
504
|
+
self._refs[name] = (rev, sha)
|
|
505
|
+
refs.append((sha, name))
|
|
506
|
+
return refs
|
|
507
|
+
|
|
508
|
+
def write_symbolic_ref(self, path: str, ref: str, rev: Optional[str] = None) -> bool:
|
|
509
|
+
"""
|
|
510
|
+
Write the given symbolic ref to the remote.
|
|
511
|
+
|
|
512
|
+
Perform a compare-and-swap (using previous revision rev) if specified,
|
|
513
|
+
otherwise perform a regular write.
|
|
514
|
+
|
|
515
|
+
Return a boolean indicating whether the write was successful.
|
|
516
|
+
"""
|
|
517
|
+
path = posixpath.join(self._path, path)
|
|
518
|
+
if rev:
|
|
519
|
+
# atomic compare-and-swap
|
|
520
|
+
mode = dropbox.files.WriteMode.update(rev)
|
|
521
|
+
else:
|
|
522
|
+
# atomic add
|
|
523
|
+
mode = dropbox.files.WriteMode.add
|
|
524
|
+
data = ("ref: %s\n" % ref).encode("utf8")
|
|
525
|
+
self._trace("writing symbolic ref %s with mode %s" % (path, mode))
|
|
526
|
+
try:
|
|
527
|
+
self._connection.files_upload(data, path, mode, strict_conflict=True, mute=True)
|
|
528
|
+
return True
|
|
529
|
+
except dropbox.exceptions.ApiError as e:
|
|
530
|
+
if not isinstance(e.error, dropbox.files.UploadError):
|
|
531
|
+
raise
|
|
532
|
+
return False
|
|
533
|
+
return True
|
|
534
|
+
|
|
535
|
+
def read_symbolic_ref(self, path: str) -> Optional[Tuple[str, str]]:
|
|
536
|
+
"""
|
|
537
|
+
Return the revision number and content of a given symbolic ref on the remote.
|
|
538
|
+
|
|
539
|
+
Return a tuple (revision, content), or None if the symbolic ref does not exist.
|
|
540
|
+
"""
|
|
541
|
+
path = posixpath.join(self._path, path)
|
|
542
|
+
self._trace("fetching symbolic ref: %s" % path)
|
|
543
|
+
try:
|
|
544
|
+
meta, resp = self._connection.files_download(path)
|
|
545
|
+
ref = resp.content.decode("utf8")
|
|
546
|
+
ref = ref[len("ref: ") :].rstrip()
|
|
547
|
+
rev = meta.rev
|
|
548
|
+
return (rev, ref)
|
|
549
|
+
except dropbox.exceptions.ApiError as e:
|
|
550
|
+
if not isinstance(e.error, dropbox.files.DownloadError):
|
|
551
|
+
raise
|
|
552
|
+
return None
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _write(message: Optional[str] = None) -> None:
|
|
556
|
+
"""
|
|
557
|
+
Write a message to standard output.
|
|
558
|
+
"""
|
|
559
|
+
if message is not None:
|
|
560
|
+
stdout("%s\n" % message)
|
|
561
|
+
else:
|
|
562
|
+
stdout("\n")
|