Browse code

Rework docker cli history

The implementation of `history` is a little redundant espacially
when user set the `--human` and/or `--no-trunc` options.

There are too many conditionals for `human`, `no-trunc` and `quiet` which
I think is useless and complicated.

Since `quiet` will only display the container IDs so it could be not
nested with the other options.

Signed-off-by: Hu Keping <hukeping@huawei.com>

Hu Keping authored on 2015/10/20 17:23:32
Showing 1 changed files
... ...
@@ -3,6 +3,7 @@ package client
3 3
 import (
4 4
 	"encoding/json"
5 5
 	"fmt"
6
+	"strconv"
6 7
 	"strings"
7 8
 	"text/tabwriter"
8 9
 	"time"
... ...
@@ -40,38 +41,36 @@ func (cli *DockerCli) CmdHistory(args ...string) error {
40 40
 	}
41 41
 
42 42
 	w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
43
-	if !*quiet {
44
-		fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE\tCOMMENT")
45
-	}
46
-
47
-	for _, entry := range history {
48
-		if *noTrunc {
49
-			fmt.Fprintf(w, entry.ID)
50
-		} else {
51
-			fmt.Fprintf(w, stringid.TruncateID(entry.ID))
52
-		}
53
-		if !*quiet {
54
-			if *human {
55
-				fmt.Fprintf(w, "\t%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(entry.Created, 0))))
56
-			} else {
57
-				fmt.Fprintf(w, "\t%s\t", time.Unix(entry.Created, 0).Format(time.RFC3339))
58
-			}
59 43
 
44
+	if *quiet {
45
+		for _, entry := range history {
60 46
 			if *noTrunc {
61
-				fmt.Fprintf(w, "%s\t", strings.Replace(entry.CreatedBy, "\t", " ", -1))
47
+				fmt.Fprintf(w, "%s\n", entry.ID)
62 48
 			} else {
63
-				fmt.Fprintf(w, "%s\t", stringutils.Truncate(strings.Replace(entry.CreatedBy, "\t", " ", -1), 45))
49
+				fmt.Fprintf(w, "%s\n", stringid.TruncateID(entry.ID))
64 50
 			}
51
+		}
52
+		w.Flush()
53
+		return nil
54
+	}
65 55
 
66
-			if *human {
67
-				fmt.Fprintf(w, "%s\t", units.HumanSize(float64(entry.Size)))
68
-			} else {
69
-				fmt.Fprintf(w, "%d\t", entry.Size)
70
-			}
56
+	fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE\tCOMMENT")
57
+	for _, entry := range history {
58
+		imageID := entry.ID
59
+		createdBy := strings.Replace(entry.CreatedBy, "\t", " ", -1)
60
+		if *noTrunc == false {
61
+			createdBy = stringutils.Truncate(createdBy, 45)
62
+			imageID = stringid.TruncateID(entry.ID)
63
+		}
71 64
 
72
-			fmt.Fprintf(w, "%s", entry.Comment)
65
+		created := units.HumanDuration(time.Now().UTC().Sub(time.Unix(entry.Created, 0))) + " ago"
66
+		size := units.HumanSize(float64(entry.Size))
67
+		if *human == false {
68
+			created = time.Unix(entry.Created, 0).Format(time.RFC3339)
69
+			size = strconv.FormatInt(entry.Size, 10)
73 70
 		}
74
-		fmt.Fprintf(w, "\n")
71
+
72
+		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", imageID, created, createdBy, size, entry.Comment)
75 73
 	}
76 74
 	w.Flush()
77 75
 	return nil