Each command messages now implement

- String() for colorized output
  - JSON() for json marshalled output

All messages should adhere to this interface unless its
explicitly not necessary in some cases.
This commit is contained in:
Harshavardhana
2015-09-13 02:20:43 -07:00
parent 3014a25bf4
commit 36e2c1813d
15 changed files with 210 additions and 142 deletions
+14 -9
View File
@@ -67,15 +67,20 @@ type AccessMessage struct {
Perms bucketPerms `json:"permission"`
}
// String colorized access message
func (s AccessMessage) String() string {
if !globalJSONFlag {
if s.Operation == "set" {
return console.Colorize("Access", "Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
}
if s.Operation == "get" {
return console.Colorize("Access", "Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
}
if s.Operation == "set" {
return console.Colorize("Access", "Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
}
if s.Operation == "get" {
return console.Colorize("Access", "Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
}
// nothing to print
return ""
}
// JSON jsonified access message
func (s AccessMessage) JSON() string {
accessJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
@@ -128,7 +133,7 @@ func mainAccess(ctx *cli.Context) {
fatalIf(doSetAccess(targetURL, perms).Trace(targetURL, string(perms)), "Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
console.Println(AccessMessage{
Prints("%s\n", AccessMessage{
Operation: "set",
Status: "success",
Bucket: targetURL,
@@ -141,7 +146,7 @@ func mainAccess(ctx *cli.Context) {
perms, err := doGetAccess(targetURL)
fatalIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
console.Println(AccessMessage{
Prints("%s\n", AccessMessage{
Operation: "get",
Status: "success",
Bucket: targetURL,
+20 -16
View File
@@ -63,21 +63,25 @@ type AliasMessage struct {
URL string `json:"url,omitempty"`
}
// String string printer for Content metadata
// String colorized alias message
func (a AliasMessage) String() string {
if !globalJSONFlag {
if a.op == "list" {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
if a.op == "remove" {
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "list" {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
if a.op == "remove" {
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
}
// should never come here
return ""
}
// JSON jsonified alias message
func (a AliasMessage) JSON() string {
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -145,7 +149,7 @@ func listAliases() {
// convert interface{} back to its original struct
newConf := config.Data().(*configV3)
for k, v := range newConf.Aliases {
console.Println(AliasMessage{
Prints("%s\n", AliasMessage{
op: "list",
Alias: k,
URL: v,
@@ -180,7 +184,7 @@ func removeAlias(alias string) {
err = writeConfig(newConfig)
fatalIf(err.Trace(alias), "Unable to save alias ‘"+alias+"’.")
console.Println(AliasMessage{
Prints("%s\n", AliasMessage{
op: "remove",
Alias: alias,
})
@@ -216,7 +220,7 @@ func addAlias(alias, url string) {
err = writeConfig(newConfig)
fatalIf(err.Trace(alias, url), "Unable to save alias ‘"+alias+"’.")
console.Println(AliasMessage{
Prints("%s\n", AliasMessage{
op: "add",
Alias: alias,
URL: url,
+22 -18
View File
@@ -48,24 +48,28 @@ type HostMessage struct {
SecretAccessKey string `json:"secretAccessKey,omitempty"`
}
// String string printer for Content metadata
// String colorized host message
func (a HostMessage) String() string {
if !globalJSONFlag {
if a.op == "list" {
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s", a.SecretAccessKey))
}
return message
}
if a.op == "remove" {
return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.")
if a.op == "list" {
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s", a.SecretAccessKey))
}
return message
}
if a.op == "remove" {
return console.Colorize("HostMessage", "Removed host ‘"+a.Host+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("HostMessage", "Added host ‘"+a.Host+"’ successfully.")
}
// should never reach here
return ""
}
// JSON jsonified host message
func (a HostMessage) JSON() string {
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -133,7 +137,7 @@ func listHosts() {
// convert interface{} back to its original struct
newConf := config.Data().(*configV3)
for k, v := range newConf.Hosts {
console.Println(HostMessage{
Prints("%s\n", HostMessage{
op: "list",
Host: k,
AccessKeyID: v.AccessKeyID,
@@ -169,7 +173,7 @@ func removeHost(hostGlob string) {
err = writeConfig(newConfig)
fatalIf(err.Trace(hostGlob), "Unable to save host glob ‘"+hostGlob+"’.")
console.Println(HostMessage{
Prints("%s\n", HostMessage{
op: "remove",
Host: hostGlob,
})
@@ -227,7 +231,7 @@ func addHost(hostGlob, accessKeyID, secretAccessKey string) {
err = writeConfig(newConfig)
fatalIf(err.Trace(hostGlob), "Unable to save host glob ‘"+hostGlob+"’.")
console.Println(HostMessage{
Prints("%s\n", HostMessage{
op: "add",
Host: hostGlob,
AccessKeyID: accessKeyID,
-1
View File
@@ -55,7 +55,6 @@ func mainConfigVersion(ctx *cli.Context) {
type Version struct {
Value string `json:"value"`
}
if globalJSONFlag {
tB, e := json.Marshal(
struct {
+8 -6
View File
@@ -71,11 +71,13 @@ type CopyMessage struct {
Length int64 `json:"length"`
}
// String string printer for copy message
// String colorized copy message
func (c CopyMessage) String() string {
if !globalJSONFlag {
return console.Colorize("Copy", fmt.Sprintf("‘%s’ -> ‘%s’", c.Source, c.Target))
}
return console.Colorize("Copy", fmt.Sprintf("‘%s’ -> ‘%s’", c.Source, c.Target))
}
// JSON jsonified copy message
func (c CopyMessage) JSON() string {
copyMessageBytes, err := json.Marshal(c)
fatalIf(probe.NewError(err), "Failed to marshal copy message.")
@@ -111,11 +113,11 @@ func doCopy(cpURLs copyURLs, bar *barSend, cpQueue <-chan bool, wg *sync.WaitGro
var newReader io.ReadCloser
if globalQuietFlag || globalJSONFlag {
console.Println(CopyMessage{
Prints("%s\n", CopyMessage{
Source: cpURLs.SourceContent.Name,
Target: cpURLs.TargetContent.Name,
Length: cpURLs.SourceContent.Size,
}.String())
})
newReader = reader
} else {
// set up progress
+2 -1
View File
@@ -80,7 +80,8 @@ func mainDiff(ctx *cli.Context) {
newFirstURL := stripRecursiveURL(firstURL)
for diff := range doDiffCmd(newFirstURL, secondURL, isURLRecursive(firstURL)) {
fatalIf(diff.Error.Trace(newFirstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.")
console.Println(diff.String())
Prints("%s\n", diff)
}
}
+17 -13
View File
@@ -52,21 +52,25 @@ type DiffMessage struct {
Error *probe.Error `json:"error,omitempty"`
}
// String colorized diff message
func (d DiffMessage) String() string {
if !globalJSONFlag {
msg := ""
switch d.Diff {
case "only-in-first":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case "type":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
case "size":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
default:
fatalIf(errDummy().Trace(), "Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
}
return msg
msg := ""
switch d.Diff {
case "only-in-first":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
case "type":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
case "size":
msg = console.Colorize("DiffMessage", "‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
default:
fatalIf(errDummy().Trace(), "Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
}
return msg
}
// JSON jsonified diff message
func (d DiffMessage) JSON() string {
diffJSONBytes, err := json.Marshal(d)
fatalIf(probe.NewError(err), "Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
+15 -13
View File
@@ -44,19 +44,21 @@ type ContentMessage struct {
Name string `json:"name"`
}
// String string printer for Content metadata.
// String colorized string message
func (c ContentMessage) String() string {
if !globalJSONFlag {
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
message = func() string {
if c.Filetype == "folder" {
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name))
}
return message + console.Colorize("File", fmt.Sprintf("%s", c.Name))
}()
return message
}
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
message = func() string {
if c.Filetype == "folder" {
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name))
}
return message + console.Colorize("File", fmt.Sprintf("%s", c.Name))
}()
return message
}
// JSON jsonified content message
func (c ContentMessage) JSON() string {
jsonMessageBytes, e := json.Marshal(c)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -123,7 +125,7 @@ func doList(clnt client.Client, recursive bool) *probe.Error {
err = contentCh.Err.Trace()
break
}
console.Println(parseContent(contentCh.Content))
Prints("%s\n", parseContent(contentCh.Content))
}
if err != nil {
return err.Trace()
+7 -4
View File
@@ -55,10 +55,13 @@ type MakeBucketMessage struct {
Bucket string `json:"bucket"`
}
// String colorized make bucket message
func (s MakeBucketMessage) String() string {
if !globalJSONFlag {
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’")
}
return console.Colorize("MakeBucket", "Bucket created successfully ‘"+s.Bucket+"’")
}
// JSON jsonified make bucket message
func (s MakeBucketMessage) JSON() string {
makeBucketJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
@@ -89,7 +92,7 @@ func mainMakeBucket(ctx *cli.Context) {
targetURL := getAliasURL(arg, config.Aliases)
fatalIf(doMakeBucketCmd(targetURL).Trace(targetURL), "Unable to make bucket ‘"+targetURL+"’.")
console.Println(MakeBucketMessage{
Prints("%s\n", MakeBucketMessage{
Status: "success",
Bucket: targetURL,
})
+10 -8
View File
@@ -67,12 +67,14 @@ type MirrorMessage struct {
Targets []string `json:"targets"`
}
// String string printer for mirror message
func (s MirrorMessage) String() string {
if !globalJSONFlag {
return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", s.Source, s.Targets))
}
mirrorMessageBytes, e := json.Marshal(s)
// String colorized mirror message
func (m MirrorMessage) String() string {
return console.Colorize("Mirror", fmt.Sprintf("‘%s’ -> ‘%s’", m.Source, m.Targets))
}
// JSON jsonified mirror message
func (m MirrorMessage) JSON() string {
mirrorMessageBytes, e := json.Marshal(m)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(mirrorMessageBytes)
@@ -112,10 +114,10 @@ func doMirror(sURLs mirrorURLs, bar *barSend, mirrorQueueCh <-chan bool, wg *syn
var newReader io.ReadCloser
if globalQuietFlag || globalJSONFlag {
console.Println(MirrorMessage{
Prints("%s\n", MirrorMessage{
Source: sURLs.SourceContent.Name,
Targets: targetURLs,
}.String())
})
newReader = reader
} else {
// set up progress
+34
View File
@@ -0,0 +1,34 @@
/*
* Minio Client (C) 2014, 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import "github.com/minio/mc/pkg/console"
// Message interface for all structured messages implementing JSON(), String() methods
type Message interface {
JSON() string
String() string
}
// Prints print wrapper for Message interface, implementing both JSON() and String() methods
func Prints(format string, message Message) {
if !globalJSONFlag {
console.Printf(format, message.String())
return
}
console.Printf(format, message.JSON())
}
+10 -6
View File
@@ -75,7 +75,7 @@ func listSessions() *probe.Error {
// sort sessions based on time
sort.Sort(bySessionWhen(bySessions))
for _, session := range bySessions {
console.Println(session)
Prints("%s\n", session)
}
return nil
}
@@ -86,10 +86,13 @@ type ClearSessionMessage struct {
SessionID string `json:"sessionId"`
}
// String colorized clear session message
func (c ClearSessionMessage) String() string {
if !globalJSONFlag {
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully")
}
return console.Colorize("ClearSession", "Session ‘"+c.SessionID+"’ cleared successfully")
}
// JSON jsonified clear session message
func (c ClearSessionMessage) JSON() string {
clearSessionJSONBytes, err := json.Marshal(c)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
@@ -103,7 +106,8 @@ func clearSession(sid string) {
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
console.Println(ClearSessionMessage{
Prints("%s\n", ClearSessionMessage{
Status: "success",
SessionID: sid,
})
@@ -120,7 +124,7 @@ func clearSession(sid string) {
if session != nil {
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
console.Println(ClearSessionMessage{
Prints("%s\n", ClearSessionMessage{
Status: "success",
SessionID: sid,
})
+9 -6
View File
@@ -73,13 +73,16 @@ type sessionV2 struct {
sigCh bool
}
// String colorized session message
func (s sessionV2) String() string {
if !globalJSONFlag {
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
return message
}
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
return message
}
// JSON jsonified session message
func (s sessionV2) JSON() string {
sessionMesage := SessionMessage{
SessionID: s.SessionID,
Time: s.Header.When.Local(),
+7 -4
View File
@@ -70,10 +70,13 @@ type ShareMessage struct {
URL string
}
// String - regular colorized message
func (s ShareMessage) String() string {
if !globalJSONFlag {
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s", humanizeDuration(s.Expiry), s.URL))
}
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s", humanizeDuration(s.Expiry), s.URL))
}
// JSON json message for share command
func (s ShareMessage) JSON() string {
shareMessageBytes, err := json.Marshal(struct {
Expiry time.Duration `json:"expireSeconds"`
SharedURL string `json:"sharedURL"`
@@ -239,7 +242,7 @@ func doShareURL(targetURL string, recursive bool, expires time.Duration) *probe.
Date: shareDate,
Message: shareMessage,
}
console.Println(shareMessage)
Prints("%s\n", shareMessage)
}
saveSharedURLsV1(sURLs)
return nil
+35 -37
View File
@@ -63,21 +63,24 @@ type UpdateMessage struct {
Version time.Time `json:"version"`
}
// String colorized update message
func (u UpdateMessage) String() string {
if !globalJSONFlag {
if u.Update {
var msg string
if runtime.GOOS == "windows" {
msg = "mc.exe cp " + u.Download + " .\\mc.exe"
} else {
msg = "mc cp " + u.Download + " ./mc.new; chmod 755 ./mc.new"
}
msg, err := colorizeUpdateMessage(msg)
fatalIf(err.Trace(msg), "Unable to colorize experimental update notification string ‘"+msg+"’.")
return msg
if u.Update {
var msg string
if runtime.GOOS == "windows" {
msg = "mc.exe cp " + u.Download + " .\\mc.exe"
} else {
msg = "mc cp " + u.Download + " ./mc.new; chmod 755 ./mc.new"
}
return console.Colorize("UpdateMessage", "You are already running the most recent version of ‘mc’.")
msg, err := colorizeUpdateMessage(msg)
fatalIf(err.Trace(msg), "Unable to colorize experimental update notification string ‘"+msg+"’.")
return msg
}
return console.Colorize("UpdateMessage", "You are already running the most recent version of ‘mc’.")
}
// JSON jsonified update message
func (u UpdateMessage) JSON() string {
updateMessageJSONBytes, err := json.Marshal(u)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
@@ -143,19 +146,19 @@ func getExperimentalUpdate() {
}
mcExperimentalURLParse := clnt.URL()
if latest.After(current) {
console.Println(UpdateMessage{
Update: true,
Download: mcExperimentalURLParse.Scheme + "://" + mcExperimentalURLParse.Host + string(mcExperimentalURLParse.Separator) + experimentals.Platforms[runtime.GOOS],
Version: latest,
})
return
}
console.Println(UpdateMessage{
Update: false,
Download: mcExperimentalURLParse.Scheme + "://" + mcExperimentalURLParse.Host + string(mcExperimentalURLParse.Separator) + experimentals.Platforms[runtime.GOOS],
downloadURL := (mcExperimentalURLParse.Scheme + "://" +
mcExperimentalURLParse.Host +
string(mcExperimentalURLParse.Separator) +
experimentals.Platforms[runtime.GOOS])
updateMessage := UpdateMessage{
Download: downloadURL,
Version: latest,
})
}
if latest.After(current) {
updateMessage.Update = true
}
Prints("%s\n", updateMessage)
}
func getReleaseUpdate() {
@@ -185,18 +188,13 @@ func getReleaseUpdate() {
}
mcUpdateURLParse := clnt.URL()
if latest.After(current) {
console.Println(UpdateMessage{
Update: true,
Download: mcUpdateURLParse.Scheme + "://" + mcUpdateURLParse.Host + string(mcUpdateURLParse.Separator) + updates.Platforms[runtime.GOOS],
Version: latest,
})
return
}
console.Println(UpdateMessage{
Update: false,
Download: mcUpdateURLParse.Scheme + "://" + mcUpdateURLParse.Host + string(mcUpdateURLParse.Separator) + updates.Platforms[runtime.GOOS],
downloadURL := mcUpdateURLParse.Scheme + "://" + mcUpdateURLParse.Host + string(mcUpdateURLParse.Separator) + updates.Platforms[runtime.GOOS]
updateMessage := UpdateMessage{
Download: downloadURL,
Version: latest,
})
return
}
if latest.After(current) {
updateMessage.Update = true
}
Prints("%s\n", updateMessage)
}