-
Notifications
You must be signed in to change notification settings - Fork 4
/
Shell.swift
66 lines (46 loc) · 1.76 KB
/
Shell.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Shell.swift
// App
//
// Created by Nathan Tannar on 2018-08-22.
//
import Vapor
final class Shell: Service {
private var worker: Container
// MARK: - Initialization
public init(worker: Container) throws{
self.worker = worker
}
// MARK: - Public
func execute(commandName: String, arguments: [String] = []) throws -> Future<Data> {
return try bash(commandName: commandName, arguments:arguments)
}
// MARK: - Private
private func bash(commandName: String, arguments: [String]) throws -> Future<Data> {
return executeShell(command: "/bin/bash" , arguments:[ "-l", "-c", "which \(commandName)" ])
.map(to: String.self) { data in
guard let commandPath = String(data: data, encoding: .utf8) else {
throw Abort(.internalServerError)
}
return commandPath.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}.flatMap(to: Data.self) { path in
return self.executeShell(command: path, arguments: arguments)
}
}
private func executeShell(command: String, arguments: [String] = []) -> Future<Data> {
return Future.map(on: worker) {
let process = Process()
process.launchPath = command
process.arguments = arguments
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
return pipe.fileHandleForReading.readDataToEndOfFile()
}
}
}
extension Shell: ServiceType {
public static func makeService(for worker: Container) throws -> Shell {
return try Shell(worker: worker)
}
}