Skip to content

Commit

Permalink
Code style tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Mar 13, 2021
1 parent 84a25c7 commit a27a4fa
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 44 deletions.
59 changes: 35 additions & 24 deletions Sources/ApertureCLI/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,37 @@ enum InEvent: String, CaseIterable, ExpressibleByArgument {
}

extension CaseIterable {
static func toStringArray() -> String {
return allCases.map { "\($0)" }.joined(separator: ", ")
static var asCommaSeparatedList: String {
allCases.map { "\($0)" }.joined(separator: ", ")
}
}

struct ApertureCLI: ParsableCommand {
static var configuration = CommandConfiguration(
static let configuration = CommandConfiguration(
commandName: "aperture",
subcommands: [List.self, Record.self, Events.self]
subcommands: [
List.self,
Record.self,
Events.self
]
)
}

extension ApertureCLI {
struct List: ParsableCommand {
static var configuration = CommandConfiguration(
subcommands: [Screens.self, AudioDevices.self]
static let configuration = CommandConfiguration(
subcommands: [
Screens.self,
AudioDevices.self
]
)
}

struct Record: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Start a recording with the given options.")
static let configuration = CommandConfiguration(abstract: "Start a recording with the given options.")

@Option(name: .shortAndLong, help: "The ID to use for this process")
var processId: String = "main"
var processId = "main"

@Argument(help: "Stringified JSON object with options passed to Aperture")
var options: String
Expand All @@ -52,43 +59,47 @@ extension ApertureCLI {
}

struct Events: ParsableCommand {
static var configuration = CommandConfiguration(
subcommands: [Send.self, Listen.self, ListenAll.self]
static let configuration = CommandConfiguration(
subcommands: [
Send.self,
Listen.self,
ListenAll.self
]
)
}
}

extension ApertureCLI.List {
struct Screens: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "List available screens.")
static let configuration = CommandConfiguration(abstract: "List available screens.")

mutating func run() throws {
// Uses stderr because of unrelated stuff being outputted on stdout
// Uses stderr because of unrelated stuff being outputted on stdout.
print(try toJson(Aperture.Devices.screen().map { ["id": $0.id, "name": $0.name] }), to: .standardError)
}
}

struct AudioDevices: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "List available audio devices.")
static let configuration = CommandConfiguration(abstract: "List available audio devices.")

mutating func run() throws {
// Uses stderr because of unrelated stuff being outputted on stdout
// Uses stderr because of unrelated stuff being outputted on stdout.
print(try toJson(Aperture.Devices.audio().map { ["id": $0.id, "name": $0.name] }), to: .standardError)
}
}
}

extension ApertureCLI.Events {
struct Send: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Send an event to the given process.")
static let configuration = CommandConfiguration(abstract: "Send an event to the given process.")

@Flag(inversion: .prefixedNo, help: "Wait for event to be received")
var wait: Bool = true
var wait = true

@Option(name: .shortAndLong, help: "The ID of the target process")
var processId: String = "main"
var processId = "main"

@Argument(help: "Name of the event to send. Can be one of:\n\(InEvent.toStringArray())")
@Argument(help: "Name of the event to send. Can be one of:\n\(InEvent.asCommaSeparatedList)")
var event: InEvent

@Argument(help: "Data to pass to the event")
Expand All @@ -110,15 +121,15 @@ extension ApertureCLI.Events {
}

struct Listen: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Listen to an outcoming event for the given process.")
static let configuration = CommandConfiguration(abstract: "Listen to an outcoming event for the given process.")

@Flag(help: "Exit after receiving the event once")
var exit = false

@Option(name: .shortAndLong, help: "The ID of the target process")
var processId: String = "main"
var processId = "main"

@Argument(help: "Name of the event to listen for. Can be one of:\n\(OutEvent.toStringArray())")
@Argument(help: "Name of the event to listen for. Can be one of:\n\(OutEvent.asCommaSeparatedList)")
var event: OutEvent

func run() {
Expand All @@ -127,7 +138,7 @@ extension ApertureCLI.Events {
print(data)
}

if self.exit {
if exit {
notification.answer()
Foundation.exit(0)
}
Expand All @@ -138,10 +149,10 @@ extension ApertureCLI.Events {
}

struct ListenAll: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Listen to all outcoming events for the given process.")
static let configuration = CommandConfiguration(abstract: "Listen to all outcoming events for the given process.")

@Option(name: .shortAndLong, help: "The ID of the target process")
var processId: String = "main"
var processId = "main"

func run() {
for event in OutEvent.allCases {
Expand Down
45 changes: 30 additions & 15 deletions Sources/ApertureCLI/notifications.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation

final class ApertureNotification {
static func notificationName(forEvent event: String, processId: String) -> String {
return "aperture.\(processId).\(event)"
"aperture.\(processId).\(event)"
}

private var notification: Notification
Expand All @@ -13,19 +13,17 @@ final class ApertureNotification {
}

func getField<T>(_ name: String) -> T? {
return notification.userInfo?[name] as? T
notification.userInfo?[name] as? T
}

var data: String? {
return getField("data")
}
var data: String? { getField("data") }

func answer(_ data: Any? = nil) {
isAnswered = true

let responseIdentifier: String? = getField("responseIdentifier")

guard responseIdentifier != nil else {
guard
let responseIdentifier: String = getField("responseIdentifier")
else {
return
}

Expand All @@ -36,7 +34,7 @@ final class ApertureNotification {
}

DistributedNotificationCenter.default().postNotificationName(
.init(responseIdentifier!),
.init(responseIdentifier),
object: nil,
userInfo: payload,
deliverImmediately: true
Expand All @@ -50,7 +48,7 @@ enum ApertureEvents {
event: String,
using handler: @escaping (ApertureNotification) -> Void
) -> NSObjectProtocol {
return DistributedNotificationCenter.default().addObserver(
DistributedNotificationCenter.default().addObserver(
forName: .init(ApertureNotification.notificationName(forEvent: event, processId: processId)),
object: nil,
queue: nil
Expand All @@ -61,7 +59,7 @@ enum ApertureEvents {
if !apertureNotification.isAnswered {
apertureNotification.answer()
}
}
}
}

static func sendEvent(
Expand Down Expand Up @@ -100,11 +98,28 @@ enum ApertureEvents {
)
}

static func sendEvent(processId: String, event: String, using callback: @escaping (ApertureNotification) -> Void) {
sendEvent(processId: processId, event: event, data: nil, using: callback)
static func sendEvent(
processId: String,
event: String,
using callback: @escaping (ApertureNotification) -> Void
) {
sendEvent(
processId: processId,
event: event,
data: nil,
using: callback
)
}

static func sendEvent(processId: String, event: String, data: Any? = nil) {
sendEvent(processId: processId, event: event, data: data) { _ in }
static func sendEvent(
processId: String,
event: String,
data: Any? = nil
) {
sendEvent(
processId: processId,
event: event,
data: data
) { _ in }
}
}
6 changes: 4 additions & 2 deletions Sources/ApertureCLI/record.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,17 @@ func record(_ optionsString: String, processId: String) throws {
}

recorder.onFinish = { error in
guard error == nil else {
print(error!, to: .standardError)
if let error = error {
print(error, to: .standardError)
exit(1)
}

ApertureEvents.sendEvent(processId: processId, event: OutEvent.onFinish.rawValue)

for observer in observers {
DistributedNotificationCenter.default().removeObserver(observer)
}

exit(0)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ extension FileHandle: TextOutputStream {
}
}

struct CLI {
enum CLI {
static var standardInput = FileHandle.standardInput
static var standardOutput = FileHandle.standardOutput
static var standardError = FileHandle.standardError
Expand Down Expand Up @@ -221,13 +221,13 @@ final class Once {

extension Data {
func jsonDecoded<T: Decodable>() throws -> T {
return try JSONDecoder().decode(T.self, from: self)
try JSONDecoder().decode(T.self, from: self)
}
}

extension String {
func jsonDecoded<T: Decodable>() throws -> T {
return try data(using: .utf8)!.jsonDecoded()
try data(using: .utf8)!.jsonDecoded()
}
}

Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class Aperture {
videoCodec = undefined
} = {}) {
this.processId = getRandomId();

return new Promise((resolve, reject) => {
if (this.recorder !== undefined) {
reject(new Error('Call `.stopRecording()` first'));
Expand Down Expand Up @@ -199,6 +200,7 @@ class Aperture {
this.throwIfNotStarted();

await this.sendEvent('resume');

// It takes about 1s after the promise resolves for the recording to actually start
await delay(1000);
}
Expand Down

0 comments on commit a27a4fa

Please sign in to comment.