|
|
|
@ -3,8 +3,19 @@ package main |
|
|
|
|
import ( |
|
|
|
|
"errors" |
|
|
|
|
"fmt" |
|
|
|
|
"os" |
|
|
|
|
"strconv" |
|
|
|
|
"strings" |
|
|
|
|
|
|
|
|
|
"github.com/fatih/color" |
|
|
|
|
) |
|
|
|
|
|
|
|
|
|
func check(err error) { |
|
|
|
|
if err != nil { |
|
|
|
|
fmt.Fprintf(os.Stderr, "[ERR] %s", err) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
type Todo struct { |
|
|
|
|
Title string |
|
|
|
|
Content string |
|
|
|
@ -32,12 +43,56 @@ func (todo *Todos) RemoveTodo(index int) (err error) { |
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
func (todo *Todos) ListTodo() int { |
|
|
|
|
func (todo *Todos) ListTodo() (err error) { |
|
|
|
|
// Create a custom print function for convenience
|
|
|
|
|
id := color.New(color.Bold, color.FgGreen).PrintfFunc() |
|
|
|
|
title := color.New(color.Bold, color.FgBlue).PrintfFunc() |
|
|
|
|
content := color.New(color.Bold, color.FgWhite).PrintfFunc() |
|
|
|
|
|
|
|
|
|
if len(todo.Items) == 0 { |
|
|
|
|
return 0 |
|
|
|
|
return errors.New("[ERR] Todo list is empty!\n") |
|
|
|
|
} |
|
|
|
|
for k, v := range todo.Items { |
|
|
|
|
id("[%d]", k) |
|
|
|
|
title("%s", v.Title) |
|
|
|
|
content("%s\n", v.Content) |
|
|
|
|
} |
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
func (todo *Todos) SaveToFile(filename string) error { |
|
|
|
|
var sb strings.Builder |
|
|
|
|
var FILE *os.File |
|
|
|
|
|
|
|
|
|
filename = filename + ".txt" |
|
|
|
|
for k, v := range todo.Items { |
|
|
|
|
fmt.Printf("%d:%s\n", k, v) |
|
|
|
|
fmt.Printf("#%d,%s,%s;\n", k, strings.ReplaceAll(v.Title, "\n", ""), strings.ReplaceAll(v.Content, "\n", "")) |
|
|
|
|
sb.WriteString(strconv.Itoa(k)) |
|
|
|
|
sb.WriteString(",") |
|
|
|
|
sb.WriteString(strings.ReplaceAll(v.Title, "\n", "")) |
|
|
|
|
sb.WriteString(",") |
|
|
|
|
sb.WriteString(strings.ReplaceAll(v.Content, "\n", "")) |
|
|
|
|
sb.WriteString(";\n") |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
content := sb.String() |
|
|
|
|
|
|
|
|
|
fmt.Println(content) |
|
|
|
|
|
|
|
|
|
if _, err := os.Stat(filename); err != nil { |
|
|
|
|
if FILE, err = os.Create(filename); err != nil { |
|
|
|
|
return errors.New("[ERR] could not create file \n") |
|
|
|
|
} |
|
|
|
|
return errors.New("[ERR] file does not exist, creating one...\n") |
|
|
|
|
} |
|
|
|
|
FILE, _ = os.Create(filename) //errors already handled
|
|
|
|
|
|
|
|
|
|
if _, err := FILE.WriteString(content); err != nil { |
|
|
|
|
return err |
|
|
|
|
//return errors.New("[ERR] could not write to file\n")
|
|
|
|
|
} |
|
|
|
|
return 1 |
|
|
|
|
|
|
|
|
|
sb.Reset() //reset the string builder
|
|
|
|
|
FILE.Close() //close the file
|
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|