reorganise SaveBackup code a bit (#522)

This commit is contained in:
Jesse Plamondon-Willard 2018-05-23 00:50:46 -04:00
parent b942c89dcf
commit fda2ac7485
1 changed files with 35 additions and 32 deletions

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
@ -27,16 +26,31 @@ namespace StardewModdingAPI.Mods.SaveBackup
{ {
try try
{ {
// read config
ModConfig config = this.Helper.ReadConfig<ModConfig>(); ModConfig config = this.Helper.ReadConfig<ModConfig>();
// init backup folder // init backup folder
DirectoryInfo folder = new DirectoryInfo(Path.Combine(this.Helper.DirectoryPath, "backups")); DirectoryInfo backupFolder = new DirectoryInfo(Path.Combine(this.Helper.DirectoryPath, "backups"));
folder.Create(); backupFolder.Create();
// back up saves // back up saves
this.CreateBackup(backupFolder);
this.PruneBackups(backupFolder, config.BackupsToKeep);
}
catch (Exception ex)
{ {
FileInfo file = new FileInfo(Path.Combine(folder.FullName, this.FileName)); this.Monitor.Log($"Error backing up saves: {ex}");
}
}
/*********
** Private methods
*********/
/// <summary>Back up the current saves.</summary>
/// <param name="backupFolder">The folder containing save backups.</param>
private void CreateBackup(DirectoryInfo backupFolder)
{
FileInfo file = new FileInfo(Path.Combine(backupFolder.FullName, this.FileName));
if (!file.Exists) if (!file.Exists)
{ {
this.Monitor.Log($"Adding {file.Name}...", LogLevel.Trace); this.Monitor.Log($"Adding {file.Name}...", LogLevel.Trace);
@ -44,8 +58,17 @@ namespace StardewModdingAPI.Mods.SaveBackup
} }
} }
// prune old saves /// <summary>Remove old backups if we've exceeded the limit.</summary>
foreach (FileInfo file in this.GetOldBackups(folder, config.BackupsToKeep)) /// <param name="backupFolder">The folder containing save backups.</param>
/// <param name="backupsToKeep">The number of backups to keep.</param>
private void PruneBackups(DirectoryInfo backupFolder, int backupsToKeep)
{
var oldBackups = backupFolder
.GetFiles()
.OrderByDescending(p => p.CreationTimeUtc)
.Skip(backupsToKeep);
foreach (FileInfo file in oldBackups)
{ {
try try
{ {
@ -58,25 +81,5 @@ namespace StardewModdingAPI.Mods.SaveBackup
} }
} }
} }
catch (Exception ex)
{
this.Monitor.Log($"Error backing up saves: {ex}");
}
}
/*********
** Private methods
*********/
/// <summary>Get backups ordered by creation date.</summary>
/// <param name="folder">The folder to search.</param>
/// <param name="skip">The number of backups to skip.</param>
private IEnumerable<FileInfo> GetOldBackups(DirectoryInfo folder, int skip)
{
return folder
.GetFiles()
.OrderByDescending(p => p.CreationTimeUtc)
.Skip(skip);
}
} }
} }