Skip to content

Commit 634c31c

Browse files
authored
Merge pull request #29 from hartbit/simple-persistence-state-list
Allow SimplePersistence to restore from other paths
2 parents 1b94187 + c1619b8 commit 634c31c

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

Sources/TSCUtility/SimplePersistence.swift

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ public final class SimplePersistence {
6060
/// The path at which we persist the state.
6161
private let statePath: AbsolutePath
6262

63+
/// The list of paths to search for restore if no state was found at statePath.
64+
private let otherStatePaths: [AbsolutePath]
65+
6366
/// Writes the state files with pretty print JSON.
6467
private let prettyPrint: Bool
6568

@@ -68,13 +71,15 @@ public final class SimplePersistence {
6871
schemaVersion: Int,
6972
supportedSchemaVersions: Set<Int> = [],
7073
statePath: AbsolutePath,
74+
otherStatePaths: [AbsolutePath] = [],
7175
prettyPrint: Bool = false
7276
) {
7377
assert(!supportedSchemaVersions.contains(schemaVersion), "Supported schema versions should not include the current schema")
7478
self.fileSystem = fileSystem
7579
self.schemaVersion = schemaVersion
7680
self.supportedSchemaVersions = supportedSchemaVersions
7781
self.statePath = statePath
82+
self.otherStatePaths = otherStatePaths
7883
self.prettyPrint = prettyPrint
7984
}
8085

@@ -88,12 +93,11 @@ public final class SimplePersistence {
8893
}
8994

9095
private func _restoreState(_ object: SimplePersistanceProtocol) throws -> Bool {
91-
// If the state doesn't exist, don't try to load and fail.
92-
if !fileSystem.exists(statePath) {
96+
guard let path = findStatePath() else {
9397
return false
9498
}
9599
// Load the state.
96-
let json = try JSON(bytes: try fileSystem.readFileContents(statePath))
100+
let json = try JSON(bytes: try fileSystem.readFileContents(path))
97101
// Get the schema version.
98102
let version: Int = try json.get("version")
99103

@@ -109,6 +113,11 @@ public final class SimplePersistence {
109113
throw Error.invalidSchemaVersion(version)
110114
}
111115

116+
// If we loaded an old file path, migrate to the new one.
117+
if path != statePath {
118+
try fileSystem.move(from: path, to: statePath)
119+
}
120+
112121
return true
113122
}
114123

@@ -152,6 +161,13 @@ public final class SimplePersistence {
152161

153162
/// Returns true if the state file exists on the filesystem.
154163
public func stateFileExists() -> Bool {
155-
return fileSystem.exists(statePath)
164+
return findStatePath() != nil
165+
}
166+
167+
private func findStatePath() -> AbsolutePath? {
168+
// Return the first path that exists.
169+
let allPaths = [statePath] + otherStatePaths
170+
let path = allPaths.first(where: { fileSystem.exists($0) })
171+
return path
156172
}
157173
}

0 commit comments

Comments
 (0)