github.com/itscaro/cli@v0.0.0-20190705081621-c9db0fe93829/cli/command/task/print.go (about) 1 package task 2 3 import ( 4 "context" 5 "fmt" 6 "sort" 7 8 "github.com/docker/cli/cli/command" 9 "github.com/docker/cli/cli/command/formatter" 10 "github.com/docker/cli/cli/command/idresolver" 11 "github.com/docker/cli/cli/config/configfile" 12 "github.com/docker/docker/api/types/swarm" 13 ) 14 15 type tasksBySlot []swarm.Task 16 17 func (t tasksBySlot) Len() int { 18 return len(t) 19 } 20 21 func (t tasksBySlot) Swap(i, j int) { 22 t[i], t[j] = t[j], t[i] 23 } 24 25 func (t tasksBySlot) Less(i, j int) bool { 26 // Sort by slot. 27 if t[i].Slot != t[j].Slot { 28 return t[i].Slot < t[j].Slot 29 } 30 31 // If same slot, sort by most recent. 32 return t[j].Meta.CreatedAt.Before(t[i].CreatedAt) 33 } 34 35 // Print task information in a format. 36 // Besides this, command `docker node ps <node>` 37 // and `docker stack ps` will call this, too. 38 func Print(ctx context.Context, dockerCli command.Cli, tasks []swarm.Task, resolver *idresolver.IDResolver, trunc, quiet bool, format string) error { 39 sort.Stable(tasksBySlot(tasks)) 40 41 names := map[string]string{} 42 nodes := map[string]string{} 43 44 tasksCtx := formatter.Context{ 45 Output: dockerCli.Out(), 46 Format: NewTaskFormat(format, quiet), 47 Trunc: trunc, 48 } 49 50 prevName := "" 51 for _, task := range tasks { 52 serviceName, err := resolver.Resolve(ctx, swarm.Service{}, task.ServiceID) 53 if err != nil { 54 return err 55 } 56 57 nodeValue, err := resolver.Resolve(ctx, swarm.Node{}, task.NodeID) 58 if err != nil { 59 return err 60 } 61 62 var name string 63 if task.Slot != 0 { 64 name = fmt.Sprintf("%v.%v", serviceName, task.Slot) 65 } else { 66 name = fmt.Sprintf("%v.%v", serviceName, task.NodeID) 67 } 68 69 // Indent the name if necessary 70 indentedName := name 71 if name == prevName { 72 indentedName = fmt.Sprintf(" \\_ %s", indentedName) 73 } 74 prevName = name 75 76 names[task.ID] = name 77 if tasksCtx.Format.IsTable() { 78 names[task.ID] = indentedName 79 } 80 nodes[task.ID] = nodeValue 81 } 82 83 return FormatWrite(tasksCtx, tasks, names, nodes) 84 } 85 86 // DefaultFormat returns the default format from the config file, or table 87 // format if nothing is set in the config. 88 func DefaultFormat(configFile *configfile.ConfigFile, quiet bool) string { 89 if len(configFile.TasksFormat) > 0 && !quiet { 90 return configFile.TasksFormat 91 } 92 return formatter.TableFormatKey 93 }