Merge branch 'feature/standards-compliant' into 'master'

Feature/standards compliant

See merge request !1
This commit is contained in:
Fredric Silberberg 2014-09-18 12:09:30 -04:00
commit 5122c83609
7 changed files with 211 additions and 174 deletions

View File

@ -11,7 +11,7 @@ COVER_DIR=cover
# Package lists # Package lists
TOPLEVEL_PKG := jsh TOPLEVEL_PKG := jsh
CMD_LIST := jsh/ps CMD_LIST := jsh/ps jsh/free jsh/ls
# List building # List building
ALL_LIST = $(TOPLEVEL_PKG) $(CMD_LIST) ALL_LIST = $(TOPLEVEL_PKG) $(CMD_LIST)

View File

@ -4,25 +4,27 @@ package jsh
import ( import (
"encoding/json" "encoding/json"
"fmt"
) )
type JshOutput struct { type JshFrame struct {
StdOut interface{} StdOut interface{}
StdErr interface{} StdErr interface{}
} }
// Size prefixes as integers, using binary representation // Size prefixes as integers, using binary representation
type Unit int type Unit int
const ( const (
B Unit = 2 ^ 0 B Unit = 2 ^ 0
KB Unit = 2 ^ 10 KB Unit = 2 ^ 10
MB Unit = 2 ^ 20 MB Unit = 2 ^ 20
GB Unit = 2 ^ 30 GB Unit = 2 ^ 30
TB Unit = 2 ^ 40 TB Unit = 2 ^ 40
) )
// Converts a Jshoutput into a JSON string // Converts a JshFrame into a JSON string
func (j JshOutput) ToJson() *string { func (j JshFrame) ToJson() *string {
jsonOut, err := json.Marshal(j) jsonOut, err := json.Marshal(j)
if err != nil { if err != nil {
panic(err) panic(err)
@ -30,3 +32,25 @@ func (j JshOutput) ToJson() *string {
jsonString := string(jsonOut) jsonString := string(jsonOut)
return &jsonString 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
}
}
}

16
free.go
View File

@ -1,8 +1,8 @@
/* File for free-related structs and methods */ /* File for free-related structs and methods */
package jsh package jsh
type MemStat struct { type MemStat struct {
Stat int Stat int
Units Unit Units Unit
} }

View File

@ -1,93 +1,102 @@
package main package main
import ( import (
"bufio" "bufio"
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"jsh" "jsh"
"regexp" "os"
"os" "regexp"
"strconv" "strconv"
) )
func convertUnit(stringUnit string) (jsh.Unit, error) { func convertUnit(stringUnit string) (jsh.Unit, error) {
switch stringUnit { switch stringUnit {
case "B": case "B":
return jsh.B, nil return jsh.B, nil
case "kB": case "kB":
return jsh.KB, nil return jsh.KB, nil
case "mB": case "mB":
return jsh.MB, nil return jsh.MB, nil
case "gB": case "gB":
return jsh.GB, nil return jsh.GB, nil
case "tB": case "tB":
return jsh.TB, nil return jsh.TB, nil
default: case "":
return 0, errors.New(fmt.Sprintln("Unknown unit %s", stringUnit)) return jsh.B, nil
} default:
} return 0, errors.New(fmt.Sprintf("Unknown unit: %s\n", stringUnit))
}
func parseLine(line string) (string, jsh.MemStat, error) { }
// Recognizes a alphanumeric or () word, the : character, whitespace, the number we're looking for,
// more whitespace, and possibly the unit func parseLine(line string) (string, jsh.MemStat, error) {
lineRegex := regexp.MustCompile("(?P<key>^[\\w()]+):\\s+(?P<val>\\d+)(\\s+)?(?P<unit>\\w+)?") // Recognizes a alphanumeric or () word, the : character, whitespace, the number we're looking for,
// more whitespace, and possibly the unit
// Parse the line, and construct a map of the valid matches lineRegex := regexp.MustCompile("(?P<key>^[\\w()]+):\\s+(?P<val>\\d+)(\\s+)?(?P<unit>\\w+)?")
parsedLine := lineRegex.FindStringSubmatch(line)
names := lineRegex.SubexpNames() // Parse the line, and construct a map of the valid matches
matchedVals := map[string]string{} parsedLine := lineRegex.FindStringSubmatch(line)
for i, n := range parsedLine { names := lineRegex.SubexpNames()
matchedVals[names[i]] = n matchedVals := map[string]string{}
} for i, n := range parsedLine {
matchedVals[names[i]] = n
key := matchedVals["key"] }
val, err := strconv.Atoi(matchedVals["val"])
if err != nil { key := matchedVals["key"]
return "", jsh.MemStat{}, err val, err := strconv.Atoi(matchedVals["val"])
} if err != nil {
unit, err := convertUnit(matchedVals["unit"]) return "", jsh.MemStat{}, err
if err != nil { }
return "", jsh.MemStat{}, err unit, err := convertUnit(matchedVals["unit"])
} if err != nil {
return key, jsh.MemStat{val, unit}, nil return "", jsh.MemStat{}, err
} }
return key, jsh.MemStat{val, unit}, nil
func parseMemInfo() jsh.JshOutput { }
file, err := os.Open("/proc/meminfo")
if err != nil { func parseMemInfo() jsh.JshFrame {
return jsh.JshOutput{[]string{}, []error{err}} file, err := os.Open("/proc/meminfo")
} if err != nil {
defer file.Close() return jsh.JshFrame{[]string{}, []error{err}}
}
scanner := bufio.NewScanner(file) defer file.Close()
memInfo := make(map[string]jsh.MemStat)
errors := []error{} scanner := bufio.NewScanner(file)
// Read in each line of the meminfo file, and place it in the map memInfo := make(map[string]jsh.MemStat)
for scanner.Scan() { errors := []error{}
key, val, err := parseLine(scanner.Text()) // Read in each line of the meminfo file, and place it in the map
if err != nil { for scanner.Scan() {
errors = append(errors, err) key, val, err := parseLine(scanner.Text())
} if err != nil {
memInfo[key] = val errors = append(errors, err)
} }
memInfo[key] = val
finalOut := jsh.JshOutput{memInfo, errors} }
return finalOut
} // Wrap with array
stdOut := []map[string]jsh.MemStat{memInfo}
func runJsonMode() { finalOut := jsh.JshFrame{stdOut, errors}
output := parseMemInfo() return finalOut
fmt.Println("%s", *output.ToJson()) }
}
func runJsonMode() {
func main() { output := parseMemInfo()
jsonModePtr := flag.Bool("json", false, "whether to use json mode for output") queue := make(chan *jsh.JshFrame)
flag.Parse() done := make(chan bool)
go jsh.OutputFrames(queue, done)
if !*jsonModePtr { queue <- &output
fmt.Printf("%s", jsh.Fallback("/usr/bin/free")) close(queue)
} else { <-done
runJsonMode() }
}
} func main() {
jsonModePtr := flag.Bool("json", false, "whether to use json mode for output")
flag.Parse()
if !*jsonModePtr {
fmt.Printf("%s", jsh.Fallback("/usr/bin/free"))
} else {
runJsonMode()
}
}

View File

@ -1,76 +1,75 @@
package main package main
import ( import (
"io/ioutil" "flag"
"fmt" "fmt"
"flag" "io/ioutil"
"log" "log"
"syscall" "strconv"
"strconv" "syscall"
) )
func get_fileinfo(f string, size bool, mode bool, inode bool) string {
func get_fileinfo(f string, size bool, mode bool, inode bool) string{ var stat syscall.Stat_t
var stat syscall.Stat_t var ret string
var ret string ret = "{\"files\": [{\"name\":\"" + f + "\""
ret = "{\"name\":\"" + f + "\"" if err := syscall.Stat(f, &stat); err != nil {
if err := syscall.Stat(f, &stat); err != nil { log.Fatal(err)
log.Fatal(err) }
} if size {
if(size){ ret = ret + ", \"size\":" + strconv.FormatInt(stat.Size, 10)
ret = ret + ", \"size\":" + strconv.FormatInt(stat.Size,10) }
} if mode {
if(mode){ ret = ret + ", \"mode\":" + strconv.Itoa(int(stat.Mode))
ret = ret + ", \"mode\":" + strconv.Itoa(int(stat.Mode)) }
} if inode {
if(inode){ ret = ret + ", \"inode\":" + strconv.FormatUint(stat.Ino, 10)
ret = ret + ", \"inode\":" + strconv.FormatUint(stat.Ino,10) }
} ret = ret + "}]}"
ret = ret + "}" return ret
return ret
} }
func main() { func main() {
// here be the ls flags // here be the ls flags
var a_flag bool // all files, even ones starting with . var a_flag bool // all files, even ones starting with .
var mode_flag bool // flags var mode_flag bool // flags
var inode_flag bool // inode var inode_flag bool // inode
var size_flag bool // size var size_flag bool // size
var first = true var first = true
flag.BoolVar(&a_flag, "a", false, "lists all files in directory, even hidden ones") flag.BoolVar(&a_flag, "a", false, "lists all files in directory, even hidden ones")
flag.BoolVar(&mode_flag, "f", false, "include flags for file") flag.BoolVar(&mode_flag, "f", false, "include flags for file")
flag.BoolVar(&inode_flag, "i", false, "include flags for file") flag.BoolVar(&inode_flag, "i", false, "include flags for file")
flag.BoolVar(&size_flag, "s", false, "include flags for file") flag.BoolVar(&size_flag, "s", false, "include flags for file")
// end ls flag // end ls flag
flag.Parse() flag.Parse()
root := "."//flag.Arg(0) root := "." //flag.Arg(0)
dir,_ := ioutil.ReadDir(root) dir, _ := ioutil.ReadDir(root)
fmt.Printf("[\n") fmt.Printf("[{\"StdOut\": [\n")
if(!a_flag){ if !a_flag {
for _,entry := range dir{ for _, entry := range dir {
if(entry.Name()[0]!='.'){ if entry.Name()[0] != '.' {
if(!first){ if !first {
fmt.Printf(",") fmt.Printf(",")
}else{ } else {
first = false first = false
}
fmt.Printf("%s\n", get_fileinfo(entry.Name(), size_flag, mode_flag, inode_flag))
}
}
} else {
for _, entry := range dir {
if !first {
fmt.Printf(",")
} else {
first = false
}
fmt.Printf("%s\n", get_fileinfo(entry.Name(), size_flag, mode_flag, inode_flag))
}
} }
fmt.Printf("%s\n", get_fileinfo(entry.Name(), size_flag, mode_flag, inode_flag)) fmt.Printf("], \"StdErr\": []}]\n")
}
}
}else{
for _,entry := range dir{
if(!first){
fmt.Printf(",")
}else{
first = false
}
fmt.Printf("%s\n", get_fileinfo(entry.Name(), size_flag, mode_flag, inode_flag))
}
}
fmt.Printf("]\n")
} }

View File

@ -25,11 +25,16 @@ func PsOutputToProcesses(out string) *[]jsh.Process {
func runJsonMode() { func runJsonMode() {
// Run procps-ng "ps" with full output // Run procps-ng "ps" with full output
psOut := string(*jsh.FallbackWithArgs("/usr/bin/ps", []string{"auxww"})) psOut := string(*jsh.FallbackWithArgs("/usr/bin/ps", []string{"auxww"}))
processesPtr := PsOutputToProcesses(psOut) processesPtr := PsOutputToProcesses(psOut)
finalOut := jsh.JshOutput{*processesPtr, []string{}} frame := jsh.JshFrame{*processesPtr, []string{}}
fmt.Printf("%s", *finalOut.ToJson())
queue := make(chan *jsh.JshFrame)
done := make(chan bool)
go jsh.OutputFrames(queue, done)
queue <- &frame
close(queue)
<-done
} }
func main() { func main() {

View File

@ -2,9 +2,9 @@ package jsh
import ( import (
"math" "math"
"unicode"
"os" "os"
"os/exec" "os/exec"
"unicode"
) )
// FieldsN slices s into substrings after each instance of a whitespace // FieldsN slices s into substrings after each instance of a whitespace
@ -56,7 +56,7 @@ func FallbackWithArgs(program string, args []string) *[]byte {
if err != nil { if err != nil {
panic(err) panic(err)
} }
return &out return &out
} }
func Fallback(program string) *[]byte { func Fallback(program string) *[]byte {