diff --git a/src/NuGetMirror/MirrorUtility.cs b/src/NuGetMirror/MirrorUtility.cs index 4c876d9..94aa729 100644 --- a/src/NuGetMirror/MirrorUtility.cs +++ b/src/NuGetMirror/MirrorUtility.cs @@ -9,34 +9,32 @@ namespace NuGetMirror { - /// - /// Mirror a feed to disk as a folder of nupkgs. - /// public static class MirrorUtility { private const string CursorFile = "cursor.json"; - /// - /// cursor.json path - /// public static FileInfo GetCursorFile(DirectoryInfo root) { + ArgumentNullException.ThrowIfNull(root); return new FileInfo(Path.Combine(root.FullName, CursorFile)); } - /// - /// Load cursor.json if it exists. - /// If it doesn't exist MinTime is returned. - /// public static DateTimeOffset LoadCursor(DirectoryInfo root) { + ArgumentNullException.ThrowIfNull(root); + var file = GetCursorFile(root); if (file.Exists) { - var json = LoadJson(file.OpenRead()); + using var stream = file.OpenRead(); + var json = LoadJson(stream); + var cursorValue = json["cursor"]?.ToObject(); - return DateTimeOffset.Parse(json["cursor"]!.ToObject()!, CultureInfo.InvariantCulture); + if (!string.IsNullOrEmpty(cursorValue)) + { + return DateTimeOffset.Parse(cursorValue, CultureInfo.InvariantCulture); + } } return DateTimeOffset.MinValue; @@ -44,28 +42,25 @@ public static DateTimeOffset LoadCursor(DirectoryInfo root) internal static JObject LoadJson(Stream stream) { - using (var reader = new StreamReader(stream)) - using (var jsonReader = new JsonTextReader(reader)) + using var reader = new StreamReader(stream); + using var jsonReader = new JsonTextReader(reader) { - // Avoid error prone json.net date handling - jsonReader.DateParseHandling = DateParseHandling.None; + DateParseHandling = DateParseHandling.None + }; - return JObject.Load(jsonReader); - } + return JObject.Load(jsonReader); } - /// - /// Write cursor.json to disk. - /// public static void SaveCursor(DirectoryInfo root, DateTimeOffset time) { - var file = GetCursorFile(root); + ArgumentNullException.ThrowIfNull(root); + var file = GetCursorFile(root); FileUtility.Delete(file.FullName); - var json = new JObject() + var json = new JObject { - { "cursor", time.ToString("o") } + ["cursor"] = time.ToString("o") }; File.WriteAllText(file.FullName, json.ToString()); @@ -73,10 +68,15 @@ public static void SaveCursor(DirectoryInfo root, DateTimeOffset time) internal static void SetTempRoot(this SourceCacheContext context, string path) { + ArgumentNullException.ThrowIfNull(context); + ArgumentException.ThrowIfNullOrWhiteSpace(path); + var folderProp = typeof(SourceCacheContext) - .GetField("_generatedTempFolder", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + .GetField("_generatedTempFolder", + BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("Field _generatedTempFolder not found"); - folderProp!.SetValue(context, path); + folderProp.SetValue(context, path); } } }