From 40676450c56687316a2a5d8f359b9d5d6fef018a Mon Sep 17 00:00:00 2001 From: fiplox Date: Sat, 10 Sep 2022 14:43:58 +0200 Subject: [PATCH] new line on terminal size --- cmd/ls.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/cmd/ls.go b/cmd/ls.go index 903abee..60d0a19 100644 --- a/cmd/ls.go +++ b/cmd/ls.go @@ -18,9 +18,11 @@ package cmd import ( "os" + "time" "github.com/jedib0t/go-pretty/v6/table" "github.com/spf13/cobra" + "golang.org/x/sys/unix" ) // lsCmd represents the ls command @@ -35,17 +37,40 @@ This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { todos := getAllTodos() + ws, err := unix.IoctlGetWinsize(int(os.Stdin.Fd()), unix.TIOCGWINSZ) + errPanic(err, "failed to determine terminal width") + cols := int(ws.Col) t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"#", "Description", "Due date"}) for _, todo := range todos { - t.AppendRow([]interface{}{todo.ID, todo.Desc, todo.DueDate.Format("02/01/2006 15:04")}) + date := todo.DueDate.Format("02/01/2006 15:04") + d := time.Time{} + if todo.DueDate == d { + date = "" + } + desc := todo.Desc + if len(desc) > (cols - 20) { + desc = insertNth(desc, cols-20) + } + t.AppendRow([]interface{}{todo.ID, desc, date}) // data[i] = []string{strconv.FormatUint(todo.ID, 10), todo.Desc, todo.DueDate.Format("")} } + t.SetStyle(table.StyleLight) + t.SetAllowedRowLength(cols) t.Render() }, } +// insertNth inserts new line on each nth position. +func insertNth(s string, n int) string { + for i := n - 1; i < len(s); i += n { + s = s[:i] + "\n" + s[i:] + } + + return s +} + func init() { rootCmd.AddCommand(lsCmd)