|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "flag" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "math" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/CodeYourFuture/immersive-go-course/projects/file-parsing/parsers" |
| 11 | + "github.com/CodeYourFuture/immersive-go-course/projects/file-parsing/parsers/binary" |
| 12 | + "github.com/CodeYourFuture/immersive-go-course/projects/file-parsing/parsers/csv" |
| 13 | + "github.com/CodeYourFuture/immersive-go-course/projects/file-parsing/parsers/json" |
| 14 | + "github.com/CodeYourFuture/immersive-go-course/projects/file-parsing/parsers/repeated_json" |
| 15 | +) |
| 16 | + |
| 17 | +func main() { |
| 18 | + format := flag.String("format", "", "Format the file is serialised in. Accepted values: json,repeated-json,csv,binary") |
| 19 | + file := flag.String("file", "", "Path to the file to read data from") |
| 20 | + flag.Parse() |
| 21 | + |
| 22 | + var parser parsers.Parser |
| 23 | + switch *format { |
| 24 | + case "json": |
| 25 | + parser = &json.Parser{} |
| 26 | + case "repeated-json": |
| 27 | + parser = &repeated_json.Parser{} |
| 28 | + case "csv": |
| 29 | + parser = &csv.Parser{} |
| 30 | + case "bin": |
| 31 | + parser = &binary.Parser{} |
| 32 | + case "": |
| 33 | + log.Fatal("format is a required argument") |
| 34 | + default: |
| 35 | + log.Fatalf("Didn't know how to parse format %q", *format) |
| 36 | + } |
| 37 | + |
| 38 | + if *file == "" { |
| 39 | + log.Fatal("file is a required argument") |
| 40 | + } |
| 41 | + f, err := os.Open(*file) |
| 42 | + if err != nil { |
| 43 | + log.Fatalf("Failed to open file %s: %v", *file, err) |
| 44 | + } |
| 45 | + defer f.Close() |
| 46 | + |
| 47 | + records, err := parser.Parse(f) |
| 48 | + if err != nil { |
| 49 | + log.Fatalf("Failed to parse file %s as %s: %v", *file, *format, err) |
| 50 | + } |
| 51 | + |
| 52 | + if len(records) == 0 { |
| 53 | + log.Fatal("No scores were found") |
| 54 | + } |
| 55 | + |
| 56 | + lowScore := parsers.ScoreRecord{ |
| 57 | + HighScore: math.MaxInt32, |
| 58 | + } |
| 59 | + highScore := parsers.ScoreRecord{ |
| 60 | + HighScore: math.MinInt32, |
| 61 | + } |
| 62 | + |
| 63 | + for _, record := range records { |
| 64 | + if record.HighScore > highScore.HighScore { |
| 65 | + highScore = record |
| 66 | + } |
| 67 | + if lowScore.HighScore < lowScore.HighScore { |
| 68 | + lowScore = record |
| 69 | + } |
| 70 | + } |
| 71 | + fmt.Printf("High score: %d from %s - congratulations!\n", highScore.HighScore, highScore.Name) |
| 72 | + fmt.Printf("Low score: %d from %s - commiserations!\n", lowScore.HighScore, lowScore.Name) |
| 73 | +} |
0 commit comments