No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* Common structures and methods used across all coreutils */
  2. package jsh
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. )
  8. type JshFrame struct {
  9. StdOut interface{}
  10. StdErr interface{}
  11. }
  12. // Converts a JshFrame into a JSON string
  13. func (j JshFrame) ToJson() *string {
  14. jsonOut, err := json.Marshal(j)
  15. if err != nil {
  16. panic(err)
  17. }
  18. jsonString := string(jsonOut)
  19. return &jsonString
  20. }
  21. func (j JshFrame) StdOutToJson() *string {
  22. jsonOut, err := json.Marshal(j.StdOut)
  23. if err != nil {
  24. panic(err)
  25. }
  26. jsonString := string(jsonOut)
  27. return &jsonString
  28. }
  29. func (j JshFrame) StdErrToJson() *string {
  30. jsonOut, err := json.Marshal(j.StdErr)
  31. if err != nil {
  32. panic(err)
  33. }
  34. jsonString := string(jsonOut)
  35. return &jsonString
  36. }
  37. // goroutine for outputing frames. Pass it a channel of pointers to JshFrames,
  38. // and it will send "true" to the done channel once you close the queue channel.
  39. func OutputFrames(queue chan *JshFrame, done chan bool) {
  40. fmt.Printf("[")
  41. fmt.Fprintf(os.Stderr, "[")
  42. isFirst := true
  43. for {
  44. frame, more := <-queue
  45. if more {
  46. if !isFirst {
  47. fmt.Printf(",")
  48. fmt.Fprintf(os.Stderr, ",")
  49. } else {
  50. isFirst = false
  51. }
  52. fmt.Printf(*frame.StdOutToJson())
  53. fmt.Fprintf(os.Stderr, *frame.StdErrToJson())
  54. } else {
  55. fmt.Printf("]\n")
  56. fmt.Fprintf(os.Stderr, "]\n")
  57. done <- true
  58. return
  59. }
  60. }
  61. }
  62. // Size prefixes as integers, using binary representation
  63. type Unit int
  64. const (
  65. B Unit = 2 ^ 0
  66. KB Unit = 2 ^ 10
  67. MB Unit = 2 ^ 20
  68. GB Unit = 2 ^ 30
  69. TB Unit = 2 ^ 40
  70. )
  71. func (u Unit) ToString() string {
  72. if u == B {
  73. return "B"
  74. } else if u == KB {
  75. return "kB"
  76. } else if u == MB {
  77. return "mB"
  78. } else if u == GB {
  79. return "gB"
  80. } else if u == TB {
  81. return "tB"
  82. } else {
  83. return fmt.Sprintf("Unknown type, values is %d", u)
  84. }
  85. }