A project: a backup tool
Copy a folder into a zip file named by date, keep only the newest few, and restore the latest. Folders, zip, sorting and cleanup in one small program.
What you will learn#
- zipping and unzipping folders,
- names that sort in time order,
- keeping the newest N files (retention),
- restoring and verifying,
- the shape of a program that is safe to run again and again.
The design#
| Need | Decision |
|---|---|
| a backup must not overwrite the previous one | every backup has its own file: backup-<date and time>.zip |
| the files should be easy to find and to sort | the stamp is year-month-day_hourminute: sorting the names sorts by time |
| disk space is limited | keep only the newest N (here 3) and delete the older ones |
| a backup that was never restored is not a backup | the program restores the newest one and checks it |
The program#
# a project - a backup tool (zip a folder, name by date, keep the newest few, restore)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.IO.Compression"
}
func main
oPath = new Path()
oDirectory = new Directory()
oFile = new File()
cWork = oPath.Combine([oPath.GetTempPath(),"ringdotnet_backup"])
if oDirectory.Exists(cWork)
oDirectory.Delete([ :path = cWork, :recursive = True ])
ok
cSource = oPath.Combine([cWork,"documents"])
cBackups = oPath.Combine([cWork,"backups"])
oDirectory.CreateDirectory(oPath.Combine([cSource,"notes"]))
oDirectory.CreateDirectory(cBackups)
oFile.WriteAllText([ :path = oPath.Combine([cSource,"report.txt"]), :contents = "Annual report" + nl + copies("lorem ipsum ",50) ])
oFile.WriteAllText([ :path = oPath.Combine([cSource,"notes/todo.txt"]), :contents = "buy milk" ])
? "The folder to protect has " + len(oDirectory.GetFiles([ :path = cSource, :searchPattern = "*", :searchOption = "AllDirectories" ]).toList()) + " files"
# STEP 1. A backup is a zip file named with the date and time, so that the names sort in time order
aStamps = ["2024-05-01_0900","2024-05-02_0900","2024-05-03_0900","2024-05-04_0900","2024-05-05_0900"]
for cStamp in aStamps
oFile.WriteAllText([ :path = oPath.Combine([cSource,"report.txt"]), :contents = "Annual report, version of " + cStamp + nl + copies("lorem ipsum ",50) ])
makeBackup(cSource,cBackups,cStamp)
next
? nl + "STEP 1: five backups made:"
showBackups(cBackups)
# STEP 2. Keep only the newest 3: the names sort by time, so delete from the front of the sorted list
nDeleted = keepNewest(cBackups,3)
? nl + "STEP 2: removed " + nDeleted + " old backups, left:"
showBackups(cBackups)
# STEP 3. Restore the newest backup into a new folder and check that it has our latest report
cRestore = oPath.Combine([cWork,"restored"])
cLatest = restoreLatest(cBackups,cRestore)
? nl + "STEP 3: restored " + oPath.GetFileName(cLatest)
? " the restored report says: " + left(oFile.ReadAllText(oPath.Combine([cRestore,"report.txt"])),38)
? " restored files: " + len(oDirectory.GetFiles([ :path = cRestore, :searchPattern = "*", :searchOption = "AllDirectories" ]).toList())
oDirectory.Delete([ :path = cWork, :recursive = True ])
# STEP 1: zip the source folder to backups/backup-<stamp>.zip
func makeBackup cSource, cBackups, cStamp
cZip = new Path().Combine([cBackups,"backup-" + cStamp + ".zip"])
new ZipFile().CreateFromDirectory([ :sourceDirectoryName = cSource, :destinationArchiveFileName = cZip ])
return cZip
# the backups, oldest first (the names sort the same way as the dates)
func listBackups cBackups
return sort(new Directory().GetFiles([ :path = cBackups, :searchPattern = "backup-*.zip" ]).toList())
func showBackups cBackups
aFiles = listBackups(cBackups)
for cFile in aFiles
? " " + new Path().GetFileName(cFile)
next
# STEP 2: delete the oldest backups until only nKeep are left
func keepNewest cBackups, nKeep
aList = listBackups(cBackups)
nDeleted = 0
for nIndex = 1 to len(aList) - nKeep
new File().Delete(aList[nIndex])
nDeleted++
next
return nDeleted
# STEP 3: unzip the newest backup into a folder
func restoreLatest cBackups, cFolder
aList = listBackups(cBackups)
cLatest = aList[len(aList)]
new ZipFile().ExtractToDirectory([ :sourceArchiveFileName = cLatest, :destinationDirectoryName = cFolder ])
return cLatest
func copies cText, nTimes
cResult = ""
for nIndex = 1 to nTimes
cResult += cText
next
return cResultThe folder to protect has 2 files
STEP 1: five backups made:
backup-2024-05-01_0900.zip
backup-2024-05-02_0900.zip
backup-2024-05-03_0900.zip
backup-2024-05-04_0900.zip
backup-2024-05-05_0900.zip
STEP 2: removed 2 old backups, left:
backup-2024-05-03_0900.zip
backup-2024-05-04_0900.zip
backup-2024-05-05_0900.zip
STEP 3: restored backup-2024-05-05_0900.zip
the restored report says: Annual report, version of 2024-05-05_0
restored files: 2How it works#
Names that sort#
2024-05-03_0900 sorts correctly as text because the biggest unit comes first and every part has a fixed width (05, not 5). That is why sort(list of names) puts the oldest backup first. A stamp like 3-5-2024 would sort wrongly. A real program makes the stamp from the clock: new DateTime().Now.Format("yyyy-MM-dd_HHmm"); the tutorial passes fixed stamps so that the output is repeatable.
Making a backup#
ZipFile.CreateFromDirectory([ :sourceDirectoryName = folder, :destinationArchiveFileName = zipFile ]) compresses the folder, with its subfolders, into a zip. It raises an error if the zip file already exists: another reason for a unique name.
Retention#
keepNewest(folder, 3) lists the backups oldest first and deletes all but the last three: the loop for nIndex = 1 to len(aList) - nKeep visits only the surplus ones. It returns how many it removed, so the caller can report it. Always list first, then delete: a bug here deletes data, so keep the logic small and test it on a demo folder, as this program does.
Restoring#
ZipFile.ExtractToDirectory([ :sourceArchiveFileName = zip, :destinationDirectoryName = folder ]) unzips into a folder (which must not exist yet). The program restores the newest backup and checks two facts: the report file has the latest text, and the number of files is the same as in the original. A real backup tool should do this check after every backup.
A program that is safe to repeat#
Run it twice and nothing breaks: new backups get new names, old ones are trimmed, the restore folder is new. Programs that run on a schedule must behave like this.
What you learned#
- zip with
ZipFile, - fixed-width date stamps sort as text,
- retention by deleting from the front of a sorted list,
- restore and verify.
Exercises#
- Use the real clock for the stamp and run the program twice.
- Skip a backup when no file changed since the last one (compare file dates or hashes: the tutorial A project: find duplicate files).
- Put the list of folders to back up in a settings file (the tutorial Settings).
- Add a window with a Back up now button and a list of the backups.