1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| package df
import ( "fmt" "reflect" "strings" )
type commandOutputdrowIdx int
const ( command_output_row_idx_file_system commandOutputdrowIdx = iota command_output_row_idx_size command_output_row_idx_used command_output_row_idx_available command_output_row_idx_used_percent command_output_row_idx_mounted_on )
var headers = []string{ "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted", "on", }
func Parse(output string) ([]Row, error) { lines := strings.Split(output, "\n") rows := make([]Row, 0, len(lines)) headerFound := false for _, line := range lines { if len(line) == 0 { continue }
ds := strings.Fields(strings.TrimSpace(line)) if ds[0] == headers[0] { if !reflect.DeepEqual(ds, headers) { return nil, fmt.Errorf(`unexpected 'df -h' command header order (%v, expected %v, output: %q)`, ds, headers, output) } headerFound = true continue }
if !headerFound { continue }
row, err := parseRow(ds) if err != nil { return nil, err }
rows = append(rows, row) }
return rows, nil }
func parseRow(row []string) (Row, error) { if len(row) != len(headers)-1 { return Row{}, fmt.Errorf(`unexpected row column number %v (expected %v)`, row, headers) }
return Row{ Filesystem: strings.TrimSpace(row[command_output_row_idx_file_system]), Size: strings.TrimSpace(row[command_output_row_idx_size]), Used: strings.TrimSpace(row[command_output_row_idx_used]), Avail: strings.TrimSpace(row[command_output_row_idx_available]), UsePercent: strings.TrimSpace(strings.Replace(row[command_output_row_idx_used_percent], "%", " %", -1)), MountedOn: strings.TrimSpace(row[command_output_row_idx_mounted_on]), }, nil }
|