Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XToolSupport / Console.swift

Console.swift144 lines · 4.6 KiBRaw
1import Foundation
2import XKit
3import XUtils
4import NIOPosix
5import NIOCore
6
7enum Console {
8 private static func withStdio<T>(
9 _ body: (
10 _ stdin: NIOAsyncChannelInboundStream<ByteBuffer>,
11 _ stdout: NIOAsyncChannelOutboundWriter<ByteBuffer>
12 ) async throws -> T
13 ) async throws -> T {
14 try await NIOPipeBootstrap(group: .singletonMultiThreadedEventLoopGroup)
15 .takingOwnershipOfDescriptors(
16 input: FileDescriptor.standardInput.duplicate().rawValue,
17 output: FileDescriptor.standardOutput.duplicate().rawValue
18 )
19 .flatMapThrowing { try NIOAsyncChannel(wrappingChannelSynchronously: $0) }
20 .get()
21 .executeThenClose { try await body($0, $1) }
22 }
23
24 static func prompt(_ message: String) async throws -> String {
25 try await withStdio { stdin, stdout in
26 try await stdout.write(ByteBuffer(bytes: message.utf8))
27
28 fflush(stdoutSafe)
29
30 var data = Data()
31 for try await chunk in stdin {
32 let view = chunk.readableBytesView
33 if let endIndex = view.firstIndex(of: UInt8(ascii: "\n")) {
34 data += view[..<endIndex]
35 break
36 } else {
37 data += view
38 }
39 }
40 let str = String(decoding: data, as: UTF8.self)
41 return str.hasSuffix("\r") ? String(str.dropLast()) : str
42 }
43 }
44
45 static func promptRequired(_ message: String, existing: String?) async throws -> String {
46 let value: String
47 if let existing {
48 value = existing
49 } else {
50 value = try await Console.prompt(message)
51 }
52 guard !value.isEmpty else {
53 throw Console.Error("Input cannot be empty.")
54 }
55 return value
56 }
57
58 static func getPassword(_ message: String) async throws -> String {
59 if !message.isEmpty {
60 print(message, terminator: "")
61 }
62 let password = try await withoutEcho { try await prompt("") }
63 print()
64 return password
65 }
66
67 private static func withoutEcho<T>(_ action: () async throws -> T) async rethrows -> T {
68 #if os(Windows)
69 // based on https://stackoverflow.com/a/4497117/3769927
70 // TODO: Confirm that this works (or even compiles)
71
72 let hConsole = CreateFileA("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)
73 var dwOldMode: DWORD = 0
74 GetConsoleMode(hConsole, &dwOldMode)
75
76 let dwNewMode = dwOldMode & ~ENABLE_ECHO_INPUT
77 SetConsoleMode(hConsole, dwNewMode)
78 defer { SetConsoleMode(hConsole, dwOldMode) }
79
80 return try action()
81 #else
82 var origAttr = termios()
83 tcgetattr(STDIN_FILENO, &origAttr)
84
85 var newAttr = origAttr
86 newAttr.c_lflag = newAttr.c_lflag & ~tcflag_t(ECHO)
87 tcsetattr(STDIN_FILENO, TCSANOW, &newAttr)
88 defer { tcsetattr(STDIN_FILENO, TCSANOW, &origAttr) }
89
90 return try await action()
91 #endif
92 }
93
94 static func chooseNumber(in range: Range<Int>) async throws -> Int {
95 let message = "Choice (\(range.lowerBound)-\(range.upperBound - 1)): "
96 while true {
97 if let choice = try await Int(prompt(message)), range.contains(choice) {
98 return choice
99 }
100 }
101 }
102
103 static func choose<T>(
104 from elements: [T],
105 onNoElement: () throws -> T,
106 multiPrompt: @autoclosure () -> String,
107 formatter: (T) throws -> String
108 ) async throws -> T {
109 switch elements.count {
110 case 0:
111 return try onNoElement()
112 case 1:
113 return elements[0]
114 default:
115 print(multiPrompt())
116 try elements.enumerated().forEach { index, element in
117 try print("\(index): \(formatter(element))")
118 }
119 let choice = try await chooseNumber(in: elements.indices)
120 return elements[choice]
121 }
122 }
123
124 private static let yesSet: Set<String> = ["yes", "y"]
125 private static let noSet: Set<String> = ["no", "n"]
126
127 static func confirm(_ message: String) async throws -> Bool {
128 while true {
129 let resp = try await prompt("\(message) (yes/no): ").lowercased()
130 if yesSet.contains(resp) {
131 return true
132 } else if noSet.contains(resp) {
133 return false
134 }
135 }
136 }
137
138 struct Error: Swift.Error, CustomStringConvertible {
139 let description: String
140 init(_ description: String) {
141 self.description = description
142 }
143 }
144}