From fb8165fa805d3b459bf2e9f3ce01390a9afff520 Mon Sep 17 00:00:00 2001 From: Ian Adam Naval Date: Tue, 16 Sep 2014 21:43:43 -0400 Subject: [PATCH] Make ps follow new standard --- common.go | 29 ++++++++++++++++++++++++++--- free/main.go | 6 +++--- ps/main.go | 11 ++++++++--- 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/common.go b/common.go index 54482de..964addb 100644 --- a/common.go +++ b/common.go @@ -4,9 +4,10 @@ package jsh import ( "encoding/json" + "fmt" ) -type JshOutput struct { +type JshFrame struct { StdOut interface{} StdErr interface{} } @@ -22,8 +23,8 @@ const ( TB Unit = 2 ^ 40 ) -// Converts a Jshoutput into a JSON string -func (j JshOutput) ToJson() *string { +// Converts a JshFrame into a JSON string +func (j JshFrame) ToJson() *string { jsonOut, err := json.Marshal(j) if err != nil { panic(err) @@ -31,3 +32,25 @@ func (j JshOutput) ToJson() *string { jsonString := string(jsonOut) return &jsonString } + +// goroutine for outputing frames. Pass it a channel of pointers to JshFrames, +// and it will send "true" to the done channel once you close the queue channel. +func OutputFrames(queue chan *JshFrame, done chan bool) { + fmt.Printf("[") + isFirst := true + for { + frame, more := <-queue + if more { + if !isFirst { + fmt.Printf(",") + } else { + isFirst = false + } + fmt.Printf(*frame.ToJson()) + } else { + fmt.Printf("]\n") + done <- true + return + } + } +} diff --git a/free/main.go b/free/main.go index 313310c..add8c89 100644 --- a/free/main.go +++ b/free/main.go @@ -53,10 +53,10 @@ func parseLine(line string) (string, jsh.MemStat, error) { return key, jsh.MemStat{val, unit}, nil } -func parseMemInfo() jsh.JshOutput { +func parseMemInfo() jsh.JshFrame { file, err := os.Open("/proc/meminfo") if err != nil { - return jsh.JshOutput{[]string{}, []error{err}} + return jsh.JshFrame{[]string{}, []error{err}} } defer file.Close() @@ -72,7 +72,7 @@ func parseMemInfo() jsh.JshOutput { memInfo[key] = val } - finalOut := jsh.JshOutput{memInfo, errors} + finalOut := jsh.JshFrame{memInfo, errors} return finalOut } diff --git a/ps/main.go b/ps/main.go index fd047c7..9df6a7b 100644 --- a/ps/main.go +++ b/ps/main.go @@ -26,10 +26,15 @@ func PsOutputToProcesses(out string) *[]jsh.Process { func runJsonMode() { // Run procps-ng "ps" with full output psOut := string(*jsh.FallbackWithArgs("/usr/bin/ps", []string{"auxww"})) - processesPtr := PsOutputToProcesses(psOut) - finalOut := jsh.JshOutput{*processesPtr, []string{}} - fmt.Printf("%s", *finalOut.ToJson()) + frame := jsh.JshFrame{*processesPtr, []string{}} + + queue := make(chan *jsh.JshFrame) + done := make(chan bool) + go jsh.OutputFrames(queue, done) + queue <- &frame + close(queue) + <-done } func main() {