Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Commit

Permalink
Merge pull request #46 from vapor/workdir-fix
Browse files Browse the repository at this point in the history
workdir fix
  • Loading branch information
tanner0101 authored Apr 27, 2017
2 parents 1689d7d + 4c6b31a commit ebd75b2
Showing 1 changed file with 30 additions and 19 deletions.
49 changes: 30 additions & 19 deletions Sources/Core/WorkingDirectory.swift
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: "/")
}

0 comments on commit ebd75b2

Please sign in to comment.