@@ -169,6 +169,39 @@ func AppendToTextFile(filePath string, text string) error {
169
169
return nil
170
170
}
171
171
172
+ func RotateFiles (baseFilePath string , count int ) error {
173
+ // Check if the base file exists
174
+ if _ , err := os .Stat (baseFilePath ); os .IsNotExist (err ) {
175
+ // Base file doesn't exist, nothing to rotate
176
+ return nil
177
+ }
178
+
179
+ // Remove the oldest rotation file if it exists
180
+ oldestFile := fmt .Sprintf ("%s.%d" , baseFilePath , count - 1 )
181
+ _ = os .Remove (oldestFile ) // Ignore error if file doesn't exist
182
+
183
+ // Shift all existing rotation files by one position
184
+ for i := count - 2 ; i >= 0 ; i -- {
185
+ oldFile := fmt .Sprintf ("%s.%d" , baseFilePath , i )
186
+ newFile := fmt .Sprintf ("%s.%d" , baseFilePath , i + 1 )
187
+
188
+ // Check if the old file exists before attempting to rename
189
+ if _ , err := os .Stat (oldFile ); err == nil {
190
+ if err := os .Rename (oldFile , newFile ); err != nil {
191
+ return fmt .Errorf ("failed to rename %s to %s: %w" , oldFile , newFile , err )
192
+ }
193
+ }
194
+ }
195
+
196
+ // Rename the base file to .0
197
+ newFile := fmt .Sprintf ("%s.0" , baseFilePath )
198
+ if err := os .Rename (baseFilePath , newFile ); err != nil {
199
+ return fmt .Errorf ("failed to rename %s to %s: %w" , baseFilePath , newFile , err )
200
+ }
201
+
202
+ return nil
203
+ }
204
+
172
205
func SaveJsonFile (filePath string , v any ) error {
173
206
var writer bytes.Buffer
174
207
encoder := json .NewEncoder (& writer )
0 commit comments