serval-dna/swift-daemon-api/Sources/CliContextFile.swift
Andrew Bettison a79156c4d0 Add Swift daemon API, use in 'servaldswift'
The daemon API is built as a Swift module called ServalDNA.

The new CliContext class allows easy implementation of CLI output using
Swift code.  The new CliContextFile subclass is the obvious first
implementation, equivalent to cli_stdio.c.  The 'servaldswift'
executable now uses CliContextFile to print its CLI output to standard
output.

The new delegated log output support constructs each log line in a
buffer and prints it by calling the delegate's 'print' function at
end-of-line.  The 'servaldswift' executable now provides a log output
delegate in Swift that simply prints to standard error, replacing
log_output_console.o, which is omitted from its link.
2018-03-06 15:29:17 +10:30

55 lines
1.7 KiB
Swift

/*
Serval DNA Swift CLI output to stdio stream
Copyright 2017 Flinders University
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import Foundation
/* An instance of struct cli_vtable that prints all fields to a stdio stream
* via a buffer. This is the Swift equivalent of cli_stdio.c. It is used by
* the 'servaldswift' daemon to produce its output.
*/
open class CliContextFile: CliContext {
private var fileHandle: FileHandle
private var buffer: Data
private let bufsize: Int? = nil
public init(_ file: FileHandle) {
self.fileHandle = file
self.buffer = Data()
}
public override func delim(_ opt: String?) {
self.puts(ProcessInfo.processInfo.environment["SERVALD_OUTPUT_DELIMITER"] ?? opt ?? "\n")
}
public override func write(_ data: Data) {
self.buffer.append(data)
if self.bufsize != nil && self.buffer.count >= self.bufsize! {
self.flush()
}
}
public override func flush() {
if !self.buffer.isEmpty {
self.fileHandle.write(self.buffer)
self.buffer.removeAll()
}
}
}