Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated config to work without Foundation #147

Merged
merged 5 commits into from
Mar 23, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 15 additions & 31 deletions Sources/Vapor/Config/Config.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
#if swift(>=3.0)
import Foundation

extension NSData: SequenceType {
public func generate() -> UnsafeBufferPointer<UInt8>.Generator {
return UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(self.bytes), count: self.length).generate()
}
}

public class Config {
public static let configDir = Application.workDir + "Config"
private let fileManager = NSFileManager.defaultManager()
private var repository: [String: Json]

public init(repository: [String: Json] = [:], application: Application? = nil) {
Expand Down Expand Up @@ -77,7 +67,7 @@ public class Config {

/* Convenience call to conditionally populate config if it exists */
public func populate(application: Application) -> Bool {
if fileManager.fileExistsAtPath(self.dynamicType.configDir) {
if FileManager.fileAtPath(self.dynamicType.configDir).exists {
do {
try populate(self.dynamicType.configDir, application: application)
return true
Expand All @@ -91,21 +81,17 @@ public class Config {
}

public func populate(path: String, application: Application) throws {
var url = NSURL(fileURLWithPath: path)
var files = [String: [NSURL]]()
var path = path.finish("/")
var files = [String: [String]]()

// Populate config files by environment
try populateConfigFiles(&files, in: url)
try populateConfigFiles(&files, in: path)

for env in application.environment.description.keys {
#if os(Linux)
url = url.URLByAppendingPathComponent(env)!
#else
url = url.URLByAppendingPathComponent(env)
#endif

if url.path.flatMap(fileManager.fileExistsAtPath) == true {
try populateConfigFiles(&files, in: url)
path += env + "/"

if FileManager.fileAtPath(path).exists {
try populateConfigFiles(&files, in: path)
}
}

Expand All @@ -118,7 +104,7 @@ public class Config {
}

for file in files {
let data = try NSData(contentsOfURL: file, options: [])
let data = try FileManager.readBytesFromFile(file)
let json = try Json.deserialize(data)

if repository[group] == nil {
Expand All @@ -133,7 +119,7 @@ public class Config {
// containing multiple groups
if let env = files[".env"] {
for file in env {
let data = try NSData(contentsOfURL: file, options: [])
let data = try FileManager.readBytesFromFile(file)
let json = try Json.deserialize(data)

guard case let .ObjectValue(object) = json else {
Expand All @@ -151,17 +137,16 @@ public class Config {
}
}

private func populateConfigFiles(files: inout [String: [NSURL]], in url: NSURL) throws {
let contents = try fileManager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: [ ])
private func populateConfigFiles(files: inout [String: [String]], in path: String) throws {
let contents = try FileManager.contentsOfDirectory(path)
let suffix = ".json"

for file in contents {
guard file.pathExtension == "json" else {
guard let fileName = file.split("/").last, suffixRange = fileName.rangeOfString(suffix) where suffixRange.endIndex == fileName.characters.endIndex else {
continue
}

guard let name = file.URLByDeletingPathExtension?.lastPathComponent else {
continue
}
let name = fileName.substringToIndex(suffixRange.startIndex)

if files[name] == nil {
files[name] = []
Expand Down Expand Up @@ -209,4 +194,3 @@ extension String {
}

}
#endif
53 changes: 52 additions & 1 deletion Sources/Vapor/Fixes/FileManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,55 @@ class FileManager {
}
return (true, isDirectory)
}
}

static func expandPath(path: String) throws -> String {
let result = realpath(path, nil)

guard result != nil else {
throw Error.Unreadable
}

defer { free(result) }

if let expanded = String.fromCString(result) {
return expanded
} else {
throw Error.Unreadable
}
}

static func contentsOfDirectory(path: String) throws -> [String] {
var gt = glob_t()
defer { globfree(&gt) }

let path = try self.expandPath(path).finish("/")
let pattern = strdup(path + "*")

switch glob(pattern, GLOB_MARK | GLOB_NOSORT, nil, &gt) {
case GLOB_NOMATCH:
return [ ]
case GLOB_ABORTED:
throw Error.Unreadable
default:
break
}

var contents = [String]()
let count: Int

#if os(Linux)
count = Int(gt.gl_pathc)
#else
count = Int(gt.gl_matchc)
#endif

for i in 0..<count {
if let path = String.fromCString(gt.gl_pathv[i]) {
contents.append(path)
}
}

return contents
}

}
12 changes: 10 additions & 2 deletions Sources/Vapor/Fixes/StringExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import libc
extension String {

}
#else
#else
extension String {
func hasPrefix(str: String) -> Bool {
let strGen = str.characters.generate()
Expand Down Expand Up @@ -107,7 +107,15 @@ extension String {
func split(maxSplit: Int = Int.max, separator: Character) -> [String] {
return self.characters.split(maxSplit) { $0 == separator }.map(String.init)
}


public func finish(ending: String) -> String {
if hasSuffix(ending) {
return self
} else {
return self + ending
}
}

func replace(old: Character, new: Character) -> String {
var buffer = [Character]()
self.characters.forEach { buffer.append($0 == old ? new : $0) }
Expand Down
2 changes: 1 addition & 1 deletion Tests/Vapor/ConfigTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class ConfigTests: XCTestCase {
do {
try app.config.populate("./Sources/VaporDev/Config", application: app)
} catch {
XCTAssert(false, "Failed to load config: \(config)")
XCTAssert(false, "Failed to load config: \(error)")
}

return app.config
Expand Down
42 changes: 0 additions & 42 deletions Tests/Vapor/UtilityTests.swift

This file was deleted.