Last active
March 16, 2019 23:28
-
-
Save vahnilah/0c3b3bb5eb934b9565eb34df0f67006c to your computer and use it in GitHub Desktop.
Python script to open your IDE and scan for changes in your working directory to make backup files in a different directory whenever a save or new file is created.
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
# Script to open programs, make backups, and push to git every 1hr when ever changes are made | |
# Setup git & backup folder to push to remote or self-hosted network to secure backups outside of local to protect if hardware failure occurs | |
# Created 03.14.2019 | |
# Updated 03.16.2019 | |
""" Example of txt file | |
--- Program to open --- | |
C:\Program Files\...\SomeIDEProg.exe | |
--- Location to scan for periodic backups --- | |
D:\Projects\...\SomeFolder | |
--- Location to place the backups --- | |
E:\Backup | |
""" | |
fileName = "directoryToScan.txt" | |
fileExtToIgnore = ["~", ".TMP"] | |
# fiesExtToSave = [".cs"] | |
# Set max file size to backup | |
maxFileSize = 1000000 | |
import errno | |
import shutil | |
import os | |
import sys | |
import sched | |
import time, datetime | |
import git | |
import subprocess | |
import threading | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
def opentext(name, parameter): | |
content2 = [] | |
file = open(name, parameter) | |
content = file.readlines() | |
file.close() | |
for file in content: | |
file = file.split("\n") | |
content2.append(file[0]) | |
return content2 | |
def openProgram(file): | |
subprocess.Popen([file]) | |
def scanForChanges(scanFolder, saveFolder): | |
class Watcher: | |
DIRECTORY_TO_WATCH = scanFolder | |
def __init__(self): | |
self.observer = Observer() | |
def run(self, startingScan = True): | |
event_handler = Handler() | |
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True) | |
self.observer.start() | |
if (startingScan == True): | |
print("Scanning for file changes at: " + str(scanFolder)) | |
startingScan = False | |
try: | |
while True: | |
time.sleep(1) | |
except: | |
self.observer.stop() | |
print("Error") | |
self.observer.join() | |
class Handler(FileSystemEventHandler): | |
@staticmethod | |
def on_any_event(event): | |
if event.is_directory: | |
return None | |
elif event.event_type == 'created': | |
# Take any action here when a file is first created. | |
# print("Received created event - " + str(event.src_path)) | |
file = str(event.src_path) | |
try: | |
copyfile(scanFolder, saveFolder, file) | |
except: | |
print("Could not backup: " + file) | |
elif event.event_type == 'modified': | |
# Taken any action here when a file is modified. | |
# print("Received modified event - " + str(event.src_path)) | |
file = str(event.src_path) | |
try: | |
copyfile(scanFolder, saveFolder, file) | |
except: | |
print("Could not backup: " + file) | |
def copyfile(scanFolder, saveFolder, file): | |
skipfile = False | |
t = datetime.datetime.now() | |
file = str(file) | |
fileName = file.replace(scanFolder,'') | |
root, ext = os.path.splitext(fileName) | |
# Checek if file is in the list of extentions to be ignored | |
for ignore in fileExtToIgnore: | |
c1 = ignore | |
c2 = ext[-1:] | |
if (str(c1).endswith(str(ext))) or (str(c1) == str(c2)): | |
skipfile = True | |
# print("File skipped: " + str(fileName)) | |
break | |
# Check file size if it isn't ignored | |
if (skipfile == False): | |
fileSize = os.path.getsize(scanFolder + fileName) | |
if (maxFileSize < fileSize): | |
print("File size is too large: " + str(file)) | |
skipfile = True | |
# Backup file | |
if (skipfile == False): | |
timeStamp = " (" + str(t.year) + "-" + str(t.month) + "-" + str(t.day) + " " + str(t.hour) + "hr" + str(t.minute) + "m)" | |
dst = saveFolder + str(root) + timeStamp + str(ext) | |
folder = os.path.dirname(os.path.realpath(dst)) | |
if not os.path.exists(folder): | |
os.makedirs(folder) | |
shutil.copy2(file, dst) | |
print("Created backup file: " + dst) | |
# Run git every 1hr | |
def runProc1(): | |
s = sched.scheduler(time.time, time.sleep) | |
def runGit(sched): | |
try: | |
repo = git.Repo(saveFolder) | |
repo.git.add(".") | |
t = datetime.datetime.today() | |
commitMsg = str(datetime.date.today()) + " @ " + str(t.hour) + ":" + str(t.minute) | |
repo.git.commit('-m', commitMsg) | |
repo.git.push() | |
print("\nSuccessfully backed up - backup files\n") | |
# 60 sec * 60 min = 3600 | |
s.enter(3600, 1, runGit, (sched,)) | |
except Exception as e: | |
print("\nCould not backed up - backup files\n\n" + str(e) + "\n") | |
s.enter(3600, 1, runGit, (sched,)) | |
s.enter(1, 1, runGit, (s,)) | |
s.run() | |
# Scan for changes to backup | |
def runProc2(): | |
w = Watcher() | |
w.run() | |
if __name__ == '__main__': | |
p1 = threading.Thread(target=runProc1) | |
p2 = threading.Thread(target=runProc2) | |
p1.start() | |
p2.start() | |
def main(): | |
location = opentext(fileName, "r") | |
print("Opening: " + location[1]) | |
openProgram(location[1]) | |
scanForChanges(location[3], location[5]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment