forked from davidjturnbull/cocktails
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pretty-print-cocktails.go
101 lines (90 loc) · 2.34 KB
/
pretty-print-cocktails.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
// Pretty-printing cocktail recipes in JSON format
//
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2020, Gianluca Fiore
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
////////////////////////////////////////////////////////////////////////////////
import (
"encoding/json"
"fmt"
"os"
"io/ioutil"
"log"
"strings"
)
type Recipe struct {
Id string `json: "id"`
Name string `json: "name"`
Description string `json: "description"`
Method string `json: "method"`
Variations string `json: "variations"`
Ingredients []struct {
Parts string `json: "parts"`
Amount string `json: "amount"`
AmountUnits string `json: "amountUnits"`
IngredientName string `json: "ingredientName"`
} `json: "ingredients"`
Glass string `json: "glass"`
Garnish string `json: "garnish"`
}
func bold(t string) string {
return "\033[1m" + t + "\033[0m"
}
func prettyPrintJSON(r Recipe) {
fmt.Println(bold(r.Name))
if r.Description != "" {
fmt.Println(r.Description)
}
fmt.Println(r.Method)
fmt.Println(r.Glass)
if r.Garnish != "" {
fmt.Println(r.Garnish)
}
if r.Variations != "" {
fmt.Println("Variations: ")
fmt.Println("\t", r.Variations)
}
fmt.Println("Ingredients: ")
for _, v := range r.Ingredients {
if v.Parts != "" {
fmt.Println("\t", bold(v.Parts), " part(s) /", bold(v.Amount), v.AmountUnits, v.IngredientName)
} else {
if v.AmountUnits != "" {
fmt.Println("\t", bold(v.Amount), v.AmountUnits, v.IngredientName)
} else {
fmt.Println("\t", bold(v.Amount), v.IngredientName)
}
}
}
}
func main() {
if len(os.Args) <= 1 {
fmt.Println("Please insert the desired cocktail's recipe")
os.Exit(1)
}
var recipe Recipe
var recipeName string
// check if a full path is being given or not
if !(strings.HasSuffix(os.Args[1], ".json")) {
recipeName = "json/" + os.Args[1] + ".json"
} else {
recipeName = os.Args[1]
}
f, err := ioutil.ReadFile(recipeName)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
unmarshal_err := json.Unmarshal(f, &recipe)
if unmarshal_err != nil {
fmt.Println(unmarshal_err)
os.Exit(1)
}
prettyPrintJSON(recipe)
}