Skip to content

Commit

Permalink
Respect symlinks when reading static mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Vasily Fedorov committed Dec 21, 2021
1 parent e6e3776 commit 8844acf
Showing 1 changed file with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import CatbirdAPI
import Vapor
import NIO
import Foundation

final class FileResponseStore: ResponseStore {
/// Path to the response body folder.
Expand All @@ -21,7 +22,13 @@ final class FileResponseStore: ResponseStore {
guard fileExists(atPath: path) else {
return request.eventLoop.makeFailedFuture(Abort(.notFound))
}
let response = request.fileio.streamFile(at: path)
let realFilePath: String
if fileIsSymlink(atPath: path) {
realFilePath = destinationOfSymlink(atPath: path)
} else {
realFilePath = path
}
let response = request.fileio.streamFile(at: realFilePath)
return request.eventLoop.makeSucceededFuture(response)
}

Expand Down Expand Up @@ -51,6 +58,31 @@ final class FileResponseStore: ResponseStore {
return fileManger.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue
}

private func fileIsSymlink(atPath path: String) -> Bool {
guard let fileAttributes = try? fileManger.attributesOfItem(atPath: path) else {
return false
}
guard fileAttributes[.type] as? FileAttributeType == .typeSymbolicLink else {
return false
}
return true
}

private func destinationOfSymlink(atPath path: String) -> String {
guard let symLinkDestination = try? fileManger.destinationOfSymbolicLink(atPath: path) else {
return path
}
if fileExists(atPath: symLinkDestination) {
return symLinkDestination
}
let basePath = (path as NSString).deletingLastPathComponent as NSString
let symlinkFullPath = basePath.appendingPathComponent(symLinkDestination)
guard fileExists(atPath: symlinkFullPath) else {
return path
}
return symlinkFullPath
}

private func createDirectories(for filePath: String) throws {
let url = URL(fileURLWithPath: filePath, isDirectory: false)
// Remove file name
Expand Down

0 comments on commit 8844acf

Please sign in to comment.