This repository has been archived by the owner on Jun 27, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #46 from vapor/workdir-fix
workdir fix
- Loading branch information
Showing
1 changed file
with
30 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,33 +1,44 @@ | ||
import libc | ||
|
||
private let defaultCwd: String = { | ||
/// This function will attempt to get the current | ||
/// working directory of the application | ||
public func workingDirectory() -> String { | ||
let fileBasedWorkDir: String? | ||
|
||
#if Xcode | ||
// attempt to find working directory through #file | ||
let file = #file | ||
let directory: String? | ||
|
||
|
||
if file.contains(".build") { | ||
// most dependencies are in `./.build/` | ||
directory = file.components(separatedBy: "/.build").first | ||
fileBasedWorkDir = file.components(separatedBy: "/.build").first | ||
} else if file.contains("Packages") { | ||
// when editing a dependency, it is in `./Packages/` | ||
directory = file.components(separatedBy: "/Packages").first | ||
fileBasedWorkDir = file.components(separatedBy: "/Packages").first | ||
} else { | ||
// when dealing with current repository, file is in `./Sources/` | ||
directory = file.components(separatedBy: "/Sources").first | ||
} | ||
|
||
return directory?.finished(with: "/") ?? "./" | ||
}() | ||
|
||
/// This function will attempt to get the current | ||
/// working directory of the application | ||
public func workingDirectory() -> String { | ||
guard let cwd = getcwd(nil, Int(PATH_MAX)) else { | ||
return defaultCwd | ||
fileBasedWorkDir = file.components(separatedBy: "/Sources").first | ||
} | ||
#else | ||
fileBasedWorkDir = nil | ||
#endif | ||
|
||
defer { | ||
free(cwd) | ||
let workDir: String | ||
if let fileBasedWorkDir = fileBasedWorkDir { | ||
workDir = fileBasedWorkDir | ||
} else { | ||
// get actual working directory | ||
let cwd = getcwd(nil, Int(PATH_MAX)) | ||
defer { | ||
free(cwd) | ||
} | ||
|
||
if let cwd = cwd, let string = String(validatingUTF8: cwd) { | ||
workDir = string | ||
} else { | ||
workDir = "./" | ||
} | ||
} | ||
|
||
return String(validatingUTF8: cwd)?.finished(with: "/") ?? defaultCwd | ||
return workDir.finished(with: "/") | ||
} |