Skip to content

Commit

Permalink
Improve Command.swift (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpmartha committed May 1, 2016
1 parent 675f331 commit 72a7bcb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
29 changes: 28 additions & 1 deletion Sources/Command.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
import Darwin

func excuteCommand(argments args: [String]) {
func executeCommand(argments args: [String]) -> [String]? {
var pipe: [Int32] = [0, 0]
Darwin.pipe(&pipe)

var fileActions: posix_spawn_file_actions_t? = nil
posix_spawn_file_actions_init(&fileActions)

posix_spawn_file_actions_addopen(&fileActions, 0, "/dev/null", O_RDONLY, 0)
posix_spawn_file_actions_adddup2(&fileActions, pipe[1], 1)

posix_spawn_file_actions_addclose(&fileActions, pipe[0])
posix_spawn_file_actions_addclose(&fileActions, pipe[1])

let argv: [UnsafeMutablePointer<CChar>?] = args.map{ $0.withCString(strdup) }
var pid = pid_t()
posix_spawnp(&pid, argv[0], &fileActions, nil, argv + [nil], nil)
posix_spawn_file_actions_destroy(&fileActions)

close(pipe[1])

let N = 4096
var buf = [Int8](repeating: 0, count: N + 1)

var n: Int
var outputStrings = [String]()
repeat {
n = read(pipe[0], &buf, N)
if let output = String(validatingUTF8: buf) {
outputStrings.append(output)
}
} while n > 0

close(pipe[0])

return outputStrings
}
6 changes: 2 additions & 4 deletions Sources/Readmemd.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import Darwin

let readmeFileName = "README.md"

/// Do not overwrite an existing file.
func duplicateExistingReadme(existingReadmeDirctoryPath sourcePath: String, newReadmeDirectoryPath targetPath: String) {
excuteCommand(argments: ["cp", "-n", "\(sourcePath)/\(readmeFileName)", targetPath])
executeCommand(argments: ["cp", "-nv", "\(sourcePath)/\(readmeFileName)", targetPath])
}

func replaceStringsInReadme(source: String, target: String) {
excuteCommand(argments:["sed", "-i", "", "-e", "s/\(source)/\(target)/g", "./\(readmeFileName)"])
executeCommand(argments:["sed", "-i", "", "-e", "s/\(source)/\(target)/g", "./\(readmeFileName)"])
}

0 comments on commit 72a7bcb

Please sign in to comment.