| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
import argparse |
| 23 |
import enum |
| 24 |
import hashlib |
| 25 |
import os |
| 26 |
import re |
| 27 |
import shutil |
| 28 |
import ssl |
| 29 |
import sys |
| 30 |
import time |
| 31 |
import urllib |
| 32 |
|
| 33 |
from urllib.parse import urlparse, urljoin |
| 34 |
from http.client import HTTPConnection, HTTPSConnection, HTTPException |
| 35 |
from os import listdir |
| 36 |
from os.path import isfile, isdir, join |
| 37 |
from base64 import b64encode |
| 38 |
|
| 39 |
from . import dirindex |
| 40 |
from .exceptions import UserError, NetworkError, RepoDataError, \ |
| 41 |
InvalidDirIndexFile, UnsupportedURLScheme |
| 42 |
from .virtual_path import VirtualPath |
| 43 |
|
| 44 |
|
| 45 |
PROGNAME = os.path.basename(sys.argv[0]) |
| 46 |
|
| 47 |
class ExitStatus(enum.Enum): |
| 48 |
SUCCESS = 0 |
| 49 |
|
| 50 |
ERROR = 1 |
| 51 |
CHECK_MODE_FOUND_MISMATCH = 2 |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
exp”). |
| 60 |
_removeDirectoryTree_dangerous_cre = re.compile( |
| 61 |
r"""^(/ (home (/ [^/]*)? )? /* | # for Unix-like systems |
| 62 |
[a-zA-Z]: [\/]* # for Windows |
| 63 |
)$""", re.VERBOSE) |
| 64 |
|
| 65 |
def removeDirectoryTree(base, whatToRemove): |
| 66 |
"""Recursively remove directory 'whatToRemove', with safety checks. |
| 67 |
|
| 68 |
This function ensures that 'whatToRemove' does not resolve to a |
| 69 |
directory such as /, /home, /home/foobar, C:\, d:\, etc. It is also |
| 70 |
an error if 'whatToRemove' does not literally start with the value |
| 71 |
of 'base' (IOW, this function refuses to erase anything that is not |
| 72 |
under 'base'). |
| 73 |
|
| 74 |
'whatToRemove' is *not* interpreted relatively to 'base' (this would |
| 75 |
be doable, just a different API). |
| 76 |
|
| 77 |
""" |
| 78 |
assert os.path.isdir(base), "Not a directory: {!r}".format(base) |
| 79 |
assert (base and |
| 80 |
whatToRemove.startswith(base) and |
| 81 |
whatToRemove[len(base):].startswith(os.sep)), \ |
| 82 |
"Unexpected base path for removeDirectoryTree(): {!r}".format(base) |
| 83 |
absPath = os.path.abspath(whatToRemove) |
| 84 |
|
| 85 |
if not os.path.isfile(join(absPath, ".dirindex")): |
| 86 |
raise UserError("refusing to recursively delete '{}' because " |
| 87 |
"it does not contain a .dirindex file".format(absPath)) |
| 88 |
elif _removeDirectoryTree_dangerous_cre.match(absPath): |
| 89 |
raise UserError("in order to protect your data, refusing to " |
| 90 |
"recursively delete '{}'".format(absPath)) |
| 91 |
else: |
| 92 |
shutil.rmtree(absPath) |
| 93 |
|
| 94 |
|
| 95 |
def computeHash(fileLike): |
| 96 |
hash = hashlib.sha1() |
| 97 |
|
| 98 |
for chunk in iter(lambda: fileLike.read(4096), b""): |
| 99 |
hash.update(chunk) |
| 100 |
|
| 101 |
return hash.hexdigest() |
| 102 |
|
| 103 |
|
| 104 |
def hashForFile(fname): |
| 105 |
with open(fname, "rb") as f: |
| 106 |
return computeHash(f) |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
class HTTPGetCallback: |
| 114 |
def __init__(self, src, callback): |
| 115 |
"""Initialize an HTTPGetCallback instance. |
| 116 |
|
| 117 |
src -- a VirtualPath instance (corresponding to the path on |
| 118 |
the server for which a GET request is to be issued) |
| 119 |
callback -- a function taking two parameters: the URL (string) |
| 120 |
and an http.client.HTTPResponse instance. When |
| 121 |
invoked, the callback return value will be returned |
| 122 |
by HTTPGetter.get(). |
| 123 |
|
| 124 |
""" |
| 125 |
if callback is not None: |
| 126 |
self.callback = callback |
| 127 |
self.src = src |
| 128 |
|
| 129 |
class HTTPGetter: |
| 130 |
def __init__(self, baseUrl, maxPending=10, auth=""): |
| 131 |
self.baseUrl = baseUrl |
| 132 |
self.parsedBaseUrl = urlparse(baseUrl) |
| 133 |
self.maxPending = maxPending |
| 134 |
self.requests = [] |
| 135 |
self.pendingRequests = [] |
| 136 |
|
| 137 |
if self.parsedBaseUrl.scheme == "http": |
| 138 |
self.httpConnection = HTTPConnection(self.parsedBaseUrl.netloc) |
| 139 |
elif self.parsedBaseUrl.scheme == "https": |
| 140 |
context = ssl.create_default_context() |
| 141 |
self.httpConnection = HTTPSConnection(self.parsedBaseUrl.netloc, |
| 142 |
context=context) |
| 143 |
else: |
| 144 |
raise UnsupportedURLScheme(self.parsedBaseUrl.scheme) |
| 145 |
|
| 146 |
self.httpRequestHeaders = headers = {'Host':self.parsedBaseUrl.netloc,'Content-Length':0,'Connection':'Keep-Alive','User-Agent':'FlightGear terrasync.py'} |
| 147 |
if( auth and not auth.isspace() ): |
| 148 |
self.httpRequestHeaders['Authorization'] = 'Basic %s' % b64encode(auth.encode("utf-8")).decode("ascii") |
| 149 |
|
| 150 |
def assemblePath(self, httpGetCallback): |
| 151 |
"""Return the path-on-server for the file to download. |
| 152 |
|
| 153 |
Example: '/scenery/Airports/N/E/4/.dirindex' |
| 154 |
|
| 155 |
""" |
| 156 |
assert not self.parsedBaseUrl.path.endswith('/'), \ |
| 157 |
repr(self.parsedBaseUrl) |
| 158 |
return self.parsedBaseUrl.path + str(httpGetCallback.src) |
| 159 |
|
| 160 |
def assembleUrl(self, httpGetCallback): |
| 161 |
"""Return the URL of the file to download.""" |
| 162 |
baseUrl = self.parsedBaseUrl.geturl() |
| 163 |
assert not baseUrl.endswith('/'), repr(baseUrl) |
| 164 |
|
| 165 |
return urljoin(baseUrl + '/', httpGetCallback.src.asRelative()) |
| 166 |
|
| 167 |
def doGet(self, httpGetCallback): |
| 168 |
time.sleep(1.25) |
| 169 |
|
| 170 |
pathOnServer = self.assemblePath(httpGetCallback) |
| 171 |
self.httpConnection.request("GET", pathOnServer, None, |
| 172 |
self.httpRequestHeaders) |
| 173 |
httpResponse = self.httpConnection.getresponse() |
| 174 |
|
| 175 |
|
| 176 |
return httpGetCallback.callback(self.assembleUrl(httpGetCallback), |
| 177 |
httpResponse) |
| 178 |
|
| 179 |
def get(self, httpGetCallback): |
| 180 |
nbRetries = nbRetriesLeft = 5 |
| 181 |
|
| 182 |
while True: |
| 183 |
try: |
| 184 |
return self.doGet(httpGetCallback) |
| 185 |
except HTTPException as exc: |
| 186 |
if nbRetriesLeft == 0: |
| 187 |
raise NetworkError( |
| 188 |
"after {nbRetries} retries for URL {url}: {errMsg}" |
| 189 |
.format(nbRetries=nbRetries, |
| 190 |
url=self.assembleUrl(httpGetCallback), |
| 191 |
errMsg=exc)) from exc |
| 192 |
|
| 193 |
|
| 194 |
self.httpConnection.close() |
| 195 |
time.sleep(1) |
| 196 |
self.httpConnection.connect() |
| 197 |
nbRetriesLeft -= 1 |
| 198 |
|
| 199 |
|
| 200 |
class HTTPDownloadRequest(HTTPGetCallback): |
| 201 |
def __init__(self, src, dst, callback=None): |
| 202 |
"""Initialize an HTTPDownloadRequest instance. |
| 203 |
|
| 204 |
src -- a VirtualPath instance (corresponding to the path |
| 205 |
on the server for which a GET request is to be |
| 206 |
issued) |
| 207 |
dst -- file path (or whatever open() accepts) where the |
| 208 |
downloaded data is to be stored |
| 209 |
callback -- a function that will be called if the download is |
| 210 |
successful, or None if no such callback is desired. |
| 211 |
The function must take one parameter: when invoked, |
| 212 |
it will be passed this HTTPDownloadRequest |
| 213 |
instance. Its return value is ignored. |
| 214 |
|
| 215 |
""" |
| 216 |
HTTPGetCallback.__init__(self, src, None) |
| 217 |
self.dst = dst |
| 218 |
self.mycallback = callback |
| 219 |
|
| 220 |
|
| 221 |
def callback(self, url, httpResponse): |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
if httpResponse.status != 200: |
| 227 |
raise NetworkError("HTTP callback got status {status} for URL {url}" |
| 228 |
.format(status=httpResponse.status, url=url)) |
| 229 |
|
| 230 |
try: |
| 231 |
with open(self.dst, 'wb') as f: |
| 232 |
f.write(httpResponse.read()) |
| 233 |
except HTTPException as exc: |
| 234 |
raise NetworkError("for URL {url}: {error}" |
| 235 |
.format(url=url, error=exc)) from exc |
| 236 |
|
| 237 |
if self.mycallback is not None: |
| 238 |
self.mycallback(self) |
| 239 |
|
| 240 |
|
| 241 |
class HTTPSocketRequest(HTTPGetCallback): |
| 242 |
"""HTTPGetCallback class whose callback returns a file-like object. |
| 243 |
|
| 244 |
The file-like object returned by the callback, and thus by |
| 245 |
HTTPGetter.get(), is a socket or similar. This allows one to read |
| 246 |
the data obtained from the network without necessarily storing it |
| 247 |
to a file. |
| 248 |
|
| 249 |
""" |
| 250 |
def __init__(self, src): |
| 251 |
"""Initialize an HTTPSocketRequest object. |
| 252 |
|
| 253 |
src -- VirtualPath instance for the resource on the server |
| 254 |
(presumably a file) |
| 255 |
|
| 256 |
""" |
| 257 |
HTTPGetCallback.__init__(self, src, None) |
| 258 |
|
| 259 |
def callback(self, url, httpResponse): |
| 260 |
|
| 261 |
if httpResponse.status != 200: |
| 262 |
raise NetworkError("HTTP callback got status {status} for URL {url}" |
| 263 |
.format(status=httpResponse.status, url=url)) |
| 264 |
|
| 265 |
return httpResponse |
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
class Coordinate: |
| 270 |
def __init__(self, lat, lon): |
| 271 |
self.lat = lat |
| 272 |
self.lon = lon |
| 273 |
|
| 274 |
class DownloadBoundaries: |
| 275 |
def __init__(self, top, left, bottom, right): |
| 276 |
if top < bottom: |
| 277 |
raise ValueError("top cannot be less than bottom") |
| 278 |
if right < left: |
| 279 |
|
| 280 |
if not (left >= 0 and right < 0): |
| 281 |
raise ValueError("right cannot be less than left") |
| 282 |
|
| 283 |
if top > 90 or bottom < -90: |
| 284 |
raise ValueError("top and bottom must be a valid latitude") |
| 285 |
if left < -180 or right >= 180: |
| 286 |
raise ValueError("left and right must be a valid longitude") |
| 287 |
self.top = top |
| 288 |
self.left = left |
| 289 |
self.bottom = bottom |
| 290 |
self.right = right |
| 291 |
|
| 292 |
def is_coordinate_inside_boundaries(self, coordinate, isOuterBucket): |
| 293 |
bigTileBottom = coordinate.lat |
| 294 |
bigTileTop = bigTileBottom + (10 if isOuterBucket else 1) |
| 295 |
bigTileLeft = coordinate.lon |
| 296 |
bigTileRight = bigTileLeft + (10 if isOuterBucket else 1) |
| 297 |
|
| 298 |
|
| 299 |
if bigTileTop <= self.bottom or bigTileBottom > self.top: |
| 300 |
return False |
| 301 |
if bigTileRight <= self.left or bigTileLeft > self.right: |
| 302 |
|
| 303 |
if self.left >= 0 and self.right < 0: |
| 304 |
|
| 305 |
if bigTileLeft >= 0: |
| 306 |
if bigTileRight <= self.left: |
| 307 |
return False |
| 308 |
elif bigTileLeft > self.right: |
| 309 |
return False |
| 310 |
else: |
| 311 |
return False |
| 312 |
|
| 313 |
|
| 314 |
return True |
| 315 |
|
| 316 |
|
| 317 |
def parse_terrasync_coordinate(coordinate): |
| 318 |
matches = re.match("(w|e)(\d{3})(n|s)(\d{2})", coordinate) |
| 319 |
if not matches: |
| 320 |
return None |
| 321 |
|
| 322 |
lon = int(matches.group(2)) |
| 323 |
if matches.group(1) == "w": |
| 324 |
lon *= -1 |
| 325 |
lat = int(matches.group(4)) |
| 326 |
if matches.group(3) == "s": |
| 327 |
lat *= -1 |
| 328 |
|
| 329 |
return Coordinate(lat, lon) |
| 330 |
|
| 331 |
|
| 332 |
class Report: |
| 333 |
"""Gather and format data about the state of a TerraSync mirror.""" |
| 334 |
|
| 335 |
def __init__(self, targetDir): |
| 336 |
self.targetDir = targetDir |
| 337 |
|
| 338 |
self.dirsWithMissingIndex = set() |
| 339 |
self.dirsWithMismatchingDirIndexHash = set() |
| 340 |
self.missingFiles = set() |
| 341 |
self.filesWithMismatchingHash = set() |
| 342 |
self.dirsSkippedDueToBoundaries = set() |
| 343 |
|
| 344 |
self.orphanFiles = set() |
| 345 |
self.orphanDirs = set() |
| 346 |
|
| 347 |
def addMissingDirIndex(self, directoryVirtualPath): |
| 348 |
self.dirsWithMissingIndex.add(directoryVirtualPath) |
| 349 |
|
| 350 |
def addDirIndexWithMismatchingHash(self, directoryVirtualPath): |
| 351 |
self.dirsWithMismatchingDirIndexHash.add(directoryVirtualPath) |
| 352 |
|
| 353 |
def addMissingFile(self, virtualPath): |
| 354 |
self.missingFiles.add(virtualPath) |
| 355 |
|
| 356 |
def addFileWithMismatchingHash(self, virtualPath): |
| 357 |
self.filesWithMismatchingHash.add(virtualPath) |
| 358 |
|
| 359 |
def addSkippedDueToBoundaries(self, virtualPath): |
| 360 |
self.dirsSkippedDueToBoundaries.add(virtualPath) |
| 361 |
|
| 362 |
def addOrphanFile(self, virtualPath): |
| 363 |
self.orphanFiles.add(virtualPath) |
| 364 |
|
| 365 |
def addOrphanDir(self, virtualPath): |
| 366 |
self.orphanDirs.add(virtualPath) |
| 367 |
|
| 368 |
def summaryString(self): |
| 369 |
reportElements = [ |
| 370 |
("Directories with missing index", self.dirsWithMissingIndex), |
| 371 |
("Directories whose .dirindex file had a mismatching hash", |
| 372 |
self.dirsWithMismatchingDirIndexHash), |
| 373 |
("Missing files", self.missingFiles), |
| 374 |
("Files with a mismatching hash", self.filesWithMismatchingHash), |
| 375 |
("Directories skipped because of the specified boundaries", |
| 376 |
self.dirsSkippedDueToBoundaries), |
| 377 |
("Orphan files", self.orphanFiles), |
| 378 |
("Orphan directories", self.orphanDirs)] |
| 379 |
|
| 380 |
l = [] |
| 381 |
for heading, setOfFilesOrDirs in reportElements: |
| 382 |
if setOfFilesOrDirs: |
| 383 |
l.append(heading + ":\n") |
| 384 |
l.extend( (" " + str(f) for f in sorted(setOfFilesOrDirs)) ) |
| 385 |
l.append('') |
| 386 |
else: |
| 387 |
l.append(heading + ": none") |
| 388 |
|
| 389 |
return '\n'.join(l) |
| 390 |
|
| 391 |
def printReport(self): |
| 392 |
title = "{prg} report".format(prg=PROGNAME) |
| 393 |
print("\n" + title + '\n' + len(title)*"=", end="\n\n") |
| 394 |
print(self.summaryString()) |
| 395 |
|
| 396 |
|
| 397 |
@enum.unique |
| 398 |
class FailedCheckReason(enum.Enum): |
| 399 |
"""Reasons that can cause 'check' mode to report a mismatch. |
| 400 |
|
| 401 |
Note that network errors and things like that do *not* belong here. |
| 402 |
|
| 403 |
""" |
| 404 |
|
| 405 |
missingDirIndexFile, mismatchingHashForDirIndexFile, \ |
| 406 |
missingNormalFile, mismatchingHashForNormalFile, \ |
| 407 |
orphanFile, orphanDirectory = range(6) |
| 408 |
|
| 409 |
|
| 410 |
def explain(self, path): |
| 411 |
if self is FailedCheckReason.missingDirIndexFile: |
| 412 |
res = ".dirindex file '{}' is missing locally".format(path) |
| 413 |
elif self is FailedCheckReason.mismatchingHashForDirIndexFile: |
| 414 |
res = ".dirindex file '{}' doesn't have the hash it " \ |
| 415 |
"should have according to the server".format(path) |
| 416 |
elif self is FailedCheckReason.missingNormalFile: |
| 417 |
res = "file '{}' is present on the server but missing locally" \ |
| 418 |
.format(path) |
| 419 |
elif self is FailedCheckReason.mismatchingHashForNormalFile: |
| 420 |
res = "file '{}' doesn't have the hash given in the " \ |
| 421 |
".dirindex file of its containing directory".format(path) |
| 422 |
elif self is FailedCheckReason.orphanFile: |
| 423 |
res = "file '{}' was found locally but is not present on the " \ |
| 424 |
"server".format(path) |
| 425 |
elif self is FailedCheckReason.orphanDirectory: |
| 426 |
res = "directory '{}' was found locally but is not present " \ |
| 427 |
"on the server".format(path) |
| 428 |
else: |
| 429 |
assert False, "Unhandled enum value: {!r}".format(self) |
| 430 |
|
| 431 |
return res |
| 432 |
|
| 433 |
|
| 434 |
class TerraSync: |
| 435 |
|
| 436 |
@enum.unique |
| 437 |
class Mode(enum.Enum): |
| 438 |
"""Main modes of operation for the TerraSync class.""" |
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
check, sync = range(2) |
| 444 |
|
| 445 |
def __init__(self, mode, doReport, url, target, quick, removeOrphan, |
| 446 |
downloadBoundaries, auth): |
| 447 |
self.mode = self.Mode[mode] |
| 448 |
self.doReport = doReport |
| 449 |
self.setUrl(url).setTarget(target) |
| 450 |
self.auth = auth |
| 451 |
self.quick = quick |
| 452 |
self.removeOrphan = removeOrphan |
| 453 |
self.httpGetter = None |
| 454 |
self.downloadBoundaries = downloadBoundaries |
| 455 |
|
| 456 |
|
| 457 |
self.report = Report(self.target) |
| 458 |
|
| 459 |
def inSyncMode(self): |
| 460 |
return self.mode == self.Mode.sync |
| 461 |
|
| 462 |
def setUrl(self, url): |
| 463 |
self.url = url.rstrip('/').strip() |
| 464 |
return self |
| 465 |
|
| 466 |
def setTarget(self, target): |
| 467 |
|
| 468 |
|
| 469 |
self.target = os.path.abspath(target) |
| 470 |
return self |
| 471 |
|
| 472 |
def start(self, virtualSubdir=VirtualPath('/')): |
| 473 |
"""Start the 'sync' or 'check' process. |
| 474 |
|
| 475 |
The 'virtualSubdir' argument must be a VirtualPath instance and |
| 476 |
allows one to start the 'sync' or 'check' process in a chosen |
| 477 |
subdirectory of the TerraSync repository, instead of at its |
| 478 |
root. |
| 479 |
|
| 480 |
""" |
| 481 |
|
| 482 |
|
| 483 |
localSubdir = os.path.normpath(virtualSubdir.asRelative()) |
| 484 |
if localSubdir == ".": |
| 485 |
localSubdir = "" |
| 486 |
|
| 487 |
assert not os.path.isabs(localSubdir), repr(localSubdir) |
| 488 |
self.httpGetter = HTTPGetter(baseUrl=self.url,auth=self.auth) |
| 489 |
|
| 490 |
|
| 491 |
try: |
| 492 |
request = HTTPSocketRequest(virtualSubdir / ".dirindex") |
| 493 |
with self.httpGetter.get(request) as fileLike: |
| 494 |
dirIndexHash = computeHash(fileLike) |
| 495 |
except HTTPException as exc: |
| 496 |
raise NetworkError("for the root .dirindex file: {errMsg}" |
| 497 |
.format(errMsg=exc)) from exc |
| 498 |
|
| 499 |
|
| 500 |
self.processDirectoryEntry(virtualSubdir, localSubdir, dirIndexHash) |
| 501 |
|
| 502 |
return self.report |
| 503 |
|
| 504 |
def processFileEntry(self, virtualPath, localPath, fileHash): |
| 505 |
"""Process a file entry from a .dirindex file.""" |
| 506 |
localFullPath = join(self.target, localPath) |
| 507 |
failedCheckReason = None |
| 508 |
|
| 509 |
if not os.path.isfile(localFullPath): |
| 510 |
self.report.addMissingFile(virtualPath) |
| 511 |
failedCheckReason = FailedCheckReason.missingNormalFile |
| 512 |
elif hashForFile(localFullPath) != fileHash: |
| 513 |
self.report.addFileWithMismatchingHash(virtualPath) |
| 514 |
failedCheckReason = FailedCheckReason.mismatchingHashForNormalFile |
| 515 |
else: |
| 516 |
|
| 517 |
return |
| 518 |
|
| 519 |
assert failedCheckReason is not None |
| 520 |
|
| 521 |
if self.inSyncMode(): |
| 522 |
if os.path.isdir(localFullPath): |
| 523 |
|
| 524 |
|
| 525 |
removeDirectoryTree(self.target, localFullPath) |
| 526 |
|
| 527 |
print("Downloading '{}'".format(virtualPath)) |
| 528 |
request = HTTPDownloadRequest(virtualPath, localFullPath) |
| 529 |
self.httpGetter.get(request) |
| 530 |
else: |
| 531 |
self.abortCheckMode(failedCheckReason, virtualPath) |
| 532 |
|
| 533 |
def processDirectoryEntry(self, virtualPath, localPath, dirIndexHash): |
| 534 |
"""Process a directory entry from a .dirindex file.""" |
| 535 |
print("Processing '{}'...".format(virtualPath)) |
| 536 |
isOuterBucket = True if len(virtualPath.parts) <= 3 else False |
| 537 |
|
| 538 |
coord = parse_terrasync_coordinate(virtualPath.name) |
| 539 |
|
| 540 |
if (coord and |
| 541 |
not self.downloadBoundaries.is_coordinate_inside_boundaries(coord, isOuterBucket)): |
| 542 |
self.report.addSkippedDueToBoundaries(virtualPath) |
| 543 |
return |
| 544 |
|
| 545 |
localFullPath = join(self.target, localPath) |
| 546 |
localDirIndex = join(localFullPath, ".dirindex") |
| 547 |
failedCheckReason = None |
| 548 |
|
| 549 |
if not os.path.isfile(localDirIndex): |
| 550 |
failedCheckReason = FailedCheckReason.missingDirIndexFile |
| 551 |
self.report.addMissingDirIndex(virtualPath) |
| 552 |
elif hashForFile(localDirIndex) != dirIndexHash: |
| 553 |
failedCheckReason = FailedCheckReason.mismatchingHashForDirIndexFile |
| 554 |
self.report.addDirIndexWithMismatchingHash(virtualPath) |
| 555 |
|
| 556 |
if failedCheckReason is None: |
| 557 |
if not self.quick: |
| 558 |
self.handleDirindexFile(localDirIndex) |
| 559 |
elif self.inSyncMode(): |
| 560 |
if os.path.isfile(localFullPath): |
| 561 |
os.unlink(localFullPath) |
| 562 |
if not os.path.exists(localFullPath): |
| 563 |
os.makedirs(localFullPath) |
| 564 |
|
| 565 |
request = HTTPDownloadRequest(virtualPath / ".dirindex", |
| 566 |
localDirIndex, |
| 567 |
self.handleDirindexRequest) |
| 568 |
self.httpGetter.get(request) |
| 569 |
else: |
| 570 |
self.abortCheckMode(failedCheckReason, virtualPath / ".dirindex") |
| 571 |
|
| 572 |
def handleDirindexRequest(self, dirindexRequest): |
| 573 |
self.handleDirindexFile(dirindexRequest.dst) |
| 574 |
|
| 575 |
def handleDirindexFile(self, dirindexFile): |
| 576 |
dirIndex = dirindex.DirIndex(dirindexFile) |
| 577 |
virtualBase = dirIndex.path |
| 578 |
relativeBase = virtualBase.asRelative() |
| 579 |
serverFiles = [] |
| 580 |
serverDirs = [] |
| 581 |
|
| 582 |
for file in dirIndex.files: |
| 583 |
f = file['name'] |
| 584 |
self.processFileEntry(virtualBase / f, |
| 585 |
join(relativeBase, f), |
| 586 |
file['hash']) |
| 587 |
serverFiles.append(f) |
| 588 |
|
| 589 |
for subdir in dirIndex.directories: |
| 590 |
d = subdir['name'] |
| 591 |
self.processDirectoryEntry(virtualBase / d, |
| 592 |
join(relativeBase, d), |
| 593 |
subdir['hash']) |
| 594 |
serverDirs.append(d) |
| 595 |
|
| 596 |
for tarball in dirIndex.tarballs: |
| 597 |
|
| 598 |
f = tarball['name'] |
| 599 |
self.processFileEntry(virtualBase / f, |
| 600 |
join(relativeBase, f), |
| 601 |
tarball['hash']) |
| 602 |
serverFiles.append(f) |
| 603 |
|
| 604 |
localFullPath = join(self.target, relativeBase) |
| 605 |
localFiles = [ f for f in listdir(localFullPath) |
| 606 |
if isfile(join(localFullPath, f)) ] |
| 607 |
|
| 608 |
for f in localFiles: |
| 609 |
if f != ".dirindex" and f not in serverFiles: |
| 610 |
virtualPath = virtualBase / f |
| 611 |
self.report.addOrphanFile(virtualPath) |
| 612 |
|
| 613 |
if self.inSyncMode(): |
| 614 |
if self.removeOrphan: |
| 615 |
os.remove(join(self.target, virtualPath.asRelative())) |
| 616 |
else: |
| 617 |
self.abortCheckMode(FailedCheckReason.orphanFile, |
| 618 |
virtualPath) |
| 619 |
|
| 620 |
localDirs = [ f for f in listdir(localFullPath) |
| 621 |
if isdir(join(localFullPath, f)) ] |
| 622 |
|
| 623 |
for d in localDirs: |
| 624 |
if d not in serverDirs: |
| 625 |
virtualPath = virtualBase / d |
| 626 |
self.report.addOrphanDir(virtualPath) |
| 627 |
|
| 628 |
if self.inSyncMode(): |
| 629 |
if self.removeOrphan: |
| 630 |
removeDirectoryTree(self.target, |
| 631 |
join(self.target, |
| 632 |
virtualPath.asRelative())) |
| 633 |
else: |
| 634 |
self.abortCheckMode(FailedCheckReason.orphanDirectory, |
| 635 |
virtualPath) |
| 636 |
|
| 637 |
|
| 638 |
def abortCheckMode(self, reason, fileOrDirVirtualPath): |
| 639 |
assert self.mode == self.Mode.check, repr(self.mode) |
| 640 |
|
| 641 |
print("{prg}: exiting from 'check' mode because {explanation}." |
| 642 |
.format(prg=PROGNAME, |
| 643 |
explanation=reason.explain(fileOrDirVirtualPath))) |
| 644 |
|
| 645 |
if self.doReport: |
| 646 |
self.report.printReport() |
| 647 |
|
| 648 |
sys.exit(ExitStatus.CHECK_MODE_FOUND_MISMATCH.value) |
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
def parseCommandLine(): |
| 653 |
parser = argparse.ArgumentParser() |
| 654 |
|
| 655 |
parser.add_argument("-u", "--url", dest="url", metavar="URL", |
| 656 |
default="http://flightgear.sourceforge.net/scenery", |
| 657 |
help="server URL [default: %(default)s]") |
| 658 |
|
| 659 |
parser.add_argument("-a", "--auth", dest="auth", metavar="user:password", |
| 660 |
default="", help="""\ |
| 661 |
authentication credentials for basic auth [default: empty, no authentication]""") |
| 662 |
|
| 663 |
parser.add_argument("-t", "--target", dest="target", metavar="DIR", |
| 664 |
default=".", help="""\ |
| 665 |
directory where to store the files [default: the current directory]""") |
| 666 |
|
| 667 |
parser.add_argument("--only-subdir", dest="onlySubdir", metavar="SUBDIR", |
| 668 |
default="", help="""\ |
| 669 |
restrict processing to this subdirectory of the TerraSync repository. Use |
| 670 |
a path relative to the repository root, for instance 'Models/Residential' |
| 671 |
[default: process the whole repository]""") |
| 672 |
|
| 673 |
parser.add_argument("-q", "--quick", dest="quick", action="store_true", |
| 674 |
default=False, help="enable quick mode") |
| 675 |
|
| 676 |
parser.add_argument("-r", "--remove-orphan", dest="removeOrphan", |
| 677 |
action="store_true", |
| 678 |
default=False, help="remove old scenery files") |
| 679 |
|
| 680 |
parser.add_argument("--mode", default="sync", choices=("check", "sync"), |
| 681 |
help="""\ |
| 682 |
main mode of operation (default: '%(default)s'). In 'sync' mode, contents |
| 683 |
is downloaded from the server to the target directory. On the other hand, |
| 684 |
in 'check' mode, {progname} compares the contents of the target directory |
| 685 |
with the remote repository without writing nor deleting anything on |
| 686 |
disk.""".format(progname=PROGNAME)) |
| 687 |
|
| 688 |
parser.add_argument("--report", dest="report", action="store_true", |
| 689 |
default=False, |
| 690 |
help="""\ |
| 691 |
before normal exit, print a report of what was found""") |
| 692 |
|
| 693 |
parser.add_argument("--top", dest="top", type=int, default=90, help="""\ |
| 694 |
maximum latitude to include in download [default: %(default)d]""") |
| 695 |
|
| 696 |
parser.add_argument("--bottom", dest="bottom", type=int, default=-90, |
| 697 |
help="""\ |
| 698 |
minimum latitude to include in download [default: %(default)d]""") |
| 699 |
|
| 700 |
parser.add_argument("--left", dest="left", type=int, default=-180, help="""\ |
| 701 |
minimum longitude to include in download [default: %(default)d]""") |
| 702 |
parser.add_argument("--right", dest="right", type=int, default=179, |
| 703 |
help="""\ |
| 704 |
maximum longitude to include in download [default: %(default)d]""") |
| 705 |
|
| 706 |
args = parser.parse_args() |
| 707 |
|
| 708 |
|
| 709 |
if args.mode == "check" and args.removeOrphan: |
| 710 |
print("{prg}: 'check' mode is read-only and thus doesn't make sense " |
| 711 |
"with\noption --remove-orphan (-r)".format(prg=PROGNAME), |
| 712 |
file=sys.stderr) |
| 713 |
sys.exit(ExitStatus.ERROR.value) |
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
args.virtualSubdir = VirtualPath(args.onlySubdir.replace('\\', '/')) |
| 721 |
|
| 722 |
|
| 723 |
if os.path.isabs(args.virtualSubdir.asRelative()): |
| 724 |
print("{prg}: option --only-subdir expects a *relative* path, but got " |
| 725 |
"'{subdir}'".format(prg=PROGNAME, subdir=args.onlySubdir), |
| 726 |
file=sys.stderr) |
| 727 |
sys.exit(ExitStatus.ERROR.value) |
| 728 |
|
| 729 |
return args |
| 730 |
|
| 731 |
|
| 732 |
def main(): |
| 733 |
args = parseCommandLine() |
| 734 |
terraSync = TerraSync(args.mode, args.report, args.url, args.target, |
| 735 |
args.quick, args.removeOrphan, |
| 736 |
DownloadBoundaries(args.top, args.left, args.bottom, |
| 737 |
args.right),args.auth) |
| 738 |
report = terraSync.start(args.virtualSubdir) |
| 739 |
|
| 740 |
if args.report: |
| 741 |
report.printReport() |
| 742 |
|
| 743 |
sys.exit(ExitStatus.SUCCESS.value) |