2020-01-12 15:39:24 +00:00
|
|
|
//
|
|
|
|
// MongoEvaluator.swift
|
|
|
|
// MongoView
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 1/12/20.
|
|
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import MongoSwift
|
|
|
|
|
|
|
|
struct MongoEvaluator {
|
|
|
|
|
2020-01-28 03:20:02 +00:00
|
|
|
static let decoder = BSONDecoder()
|
2020-01-12 15:39:24 +00:00
|
|
|
|
2020-01-28 03:20:02 +00:00
|
|
|
static func parse(extendedJSON: String) -> BSON? {
|
|
|
|
guard !extendedJSON.isEmpty else {
|
|
|
|
return nil
|
2020-01-12 15:39:24 +00:00
|
|
|
}
|
|
|
|
do {
|
2020-01-28 03:20:02 +00:00
|
|
|
return try decoder.decode(BSON.self, from: extendedJSON)
|
2020-01-12 15:39:24 +00:00
|
|
|
} catch {
|
2020-01-28 03:20:02 +00:00
|
|
|
print("Unable to parse BSON: \(error)")
|
2020-01-12 15:39:24 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-28 03:20:02 +00:00
|
|
|
static func eval(command: String, connectingTo connStr: String) -> [BSON] {
|
|
|
|
let realCommand = """
|
|
|
|
Object.prototype.printExtJSON = function() { print(JSON.stringify(this)); };
|
|
|
|
Array.prototype.printExtJSON = function() { this.map(JSON.stringify).forEach(it => print(it)); };
|
|
|
|
\(command).printExtJSON()
|
|
|
|
"""
|
2020-01-12 15:39:24 +00:00
|
|
|
print("Running command \"\(command)\" against \(connStr)")
|
|
|
|
|
|
|
|
let mongoOutputPipe = Pipe()
|
|
|
|
|
|
|
|
let mongoProcess = Process()
|
|
|
|
mongoProcess.launchPath = "/usr/local/bin/mongo"
|
2020-01-28 03:20:02 +00:00
|
|
|
mongoProcess.arguments = [connStr, "--quiet", "--norc", "--eval", realCommand]
|
2020-01-12 15:39:24 +00:00
|
|
|
mongoProcess.standardOutput = mongoOutputPipe
|
|
|
|
mongoProcess.launch()
|
|
|
|
|
|
|
|
let mongoOutputHandle = mongoOutputPipe.fileHandleForReading
|
|
|
|
|
|
|
|
var strs = [String]()
|
|
|
|
var data: Data!
|
|
|
|
repeat {
|
|
|
|
data = mongoOutputHandle.availableData
|
|
|
|
strs.append(String(data: data, encoding: .utf8)!)
|
|
|
|
} while (data.count > 0)
|
|
|
|
mongoOutputHandle.closeFile()
|
|
|
|
|
|
|
|
let lines = strs.joined(separator: "").components(separatedBy: "\n")
|
2020-01-28 03:20:02 +00:00
|
|
|
return lines.compactMap(parse(extendedJSON:))
|
2020-01-12 15:39:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|