@@ -60,6 +60,9 @@ public final class SimplePersistence {
60
60
/// The path at which we persist the state.
61
61
private let statePath : AbsolutePath
62
62
63
+ /// The list of paths to search for restore if no state was found at statePath.
64
+ private let otherStatePaths : [ AbsolutePath ]
65
+
63
66
/// Writes the state files with pretty print JSON.
64
67
private let prettyPrint : Bool
65
68
@@ -68,13 +71,15 @@ public final class SimplePersistence {
68
71
schemaVersion: Int ,
69
72
supportedSchemaVersions: Set < Int > = [ ] ,
70
73
statePath: AbsolutePath ,
74
+ otherStatePaths: [ AbsolutePath ] = [ ] ,
71
75
prettyPrint: Bool = false
72
76
) {
73
77
assert ( !supportedSchemaVersions. contains ( schemaVersion) , " Supported schema versions should not include the current schema " )
74
78
self . fileSystem = fileSystem
75
79
self . schemaVersion = schemaVersion
76
80
self . supportedSchemaVersions = supportedSchemaVersions
77
81
self . statePath = statePath
82
+ self . otherStatePaths = otherStatePaths
78
83
self . prettyPrint = prettyPrint
79
84
}
80
85
@@ -88,12 +93,11 @@ public final class SimplePersistence {
88
93
}
89
94
90
95
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 {
93
97
return false
94
98
}
95
99
// Load the state.
96
- let json = try JSON ( bytes: try fileSystem. readFileContents ( statePath ) )
100
+ let json = try JSON ( bytes: try fileSystem. readFileContents ( path ) )
97
101
// Get the schema version.
98
102
let version : Int = try json. get ( " version " )
99
103
@@ -109,6 +113,11 @@ public final class SimplePersistence {
109
113
throw Error . invalidSchemaVersion ( version)
110
114
}
111
115
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
+
112
121
return true
113
122
}
114
123
@@ -152,6 +161,13 @@ public final class SimplePersistence {
152
161
153
162
/// Returns true if the state file exists on the filesystem.
154
163
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
156
172
}
157
173
}
0 commit comments