Last active
July 9, 2017 23:07
-
-
Save barkovv/bfe839642b8e08f50c07100313f49681 to your computer and use it in GitHub Desktop.
Syncs files which have been changed since last sync with dir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! python | |
import sys | |
import os | |
import logging | |
from shutil import copy | |
from pathlib import Path | |
from datetime import datetime | |
defaultTimestampName = ".syncstamp" | |
patternsForSync = ["*.c", "*.h"] | |
def getTimestampPath(folder): | |
return os.path.join(folder, defaultTimestampName) | |
def createTimestamp(folder, timestamp=datetime.now().timestamp()): | |
filename = getTimestampPath(folder) | |
logging.debug("createTimestamp: writing {0} to {1}" | |
.format(timestamp, filename)) | |
file = open(filename, "w") | |
file.write(str(timestamp)) | |
file.close() | |
def getLastSyncTimestamp(folder): | |
try: | |
path = getTimestampPath(folder) | |
with open(path, "r") as file: | |
return float(file.read()) | |
except(FileNotFoundError, ValueError) as e: | |
logging.debug("getLastSyncTimestamp: " + str(e)) | |
return 0.0 | |
def getFilesForSync(pathFrom, lastSyncTimestamp=0): | |
folderFrom = Path(pathFrom) | |
candidates = [] | |
for pattern in patternsForSync: | |
candidates += list(folderFrom.rglob(pattern)) | |
result = [] | |
for candidate in candidates: | |
try: | |
mtime = os.path.getmtime(str(candidate)) | |
if(mtime > lastSyncTimestamp): | |
result.append(str(candidate)) | |
except OSError as e: | |
logging.debug("getFilesForSync: " + str(e)) | |
continue | |
return result | |
def sync(files, pathFrom, pathTo): | |
for file in files: | |
relativePath = os.path.relpath(file, pathFrom) | |
destination = os.path.join(pathTo, relativePath) | |
print("{0} -> {1}".format(file, destination)) | |
copy(file, destination) | |
def printHelp(programName): | |
print("Usage: " + programName + " <from> <to>") | |
def main(arguments=[]): | |
if(len(arguments) < 3): | |
printHelp(arguments[0]) | |
return 0 | |
pathFrom = arguments[1] | |
pathTo = arguments[2] | |
try: | |
lastSyncTime = getLastSyncTimestamp(pathFrom) | |
files = getFilesForSync(pathFrom, lastSyncTime) | |
sync(files, pathFrom, pathTo) | |
createTimestamp(pathFrom) | |
print("DONE.") | |
except OSError as e: | |
logging.error("main: " + str(e)) | |
return -1 | |
if __name__ == "__main__": | |
code = main(sys.argv) | |
sys.exit(code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment