NASutils Knowledge BaseUnofficialPolski

Go · lesson 29 of 30 · Tools for the NAS · bonusBuild a notepad

load, save and run divide the work; each returns an error to its caller.

Programming on the NAS › Go in 30 lessons

29-notepad.go Download 29-notepad.go

package main

import (
	"errors"
	"fmt"
	"os"
	"slices"
	"strconv"
	"strings"
)

const file = "notes.txt"

func load() ([]string, error) {
	data, err := os.ReadFile(file)
	if errors.Is(err, os.ErrNotExist) {
		return nil, nil
	}
	text := strings.TrimRight(string(data), "\n")
	if err != nil || text == "" {
		return nil, err
	}
	return strings.Split(text, "\n"), nil
}

func save(notes []string) error {
	text := strings.Join(notes, "\n")
	if len(notes) > 0 {
		text += "\n"
	}
	return os.WriteFile(file, []byte(text), 0o644)
}

func run(args []string) error {
	notes, err := load()
	if err != nil {
		return err
	}
	switch {
	case len(args) == 2 && args[0] == "add" && args[1] != "":
		notes = append(notes, strings.ReplaceAll(args[1], "\n", " "))
		if err := save(notes); err != nil {
			return err
		}
		fmt.Println("Added note", len(notes))
		return nil
	case len(args) == 1 && args[0] == "list":
		if len(notes) == 0 {
			fmt.Println("No notes")
		}
		for i, note := range notes {
			fmt.Printf("%d. %s\n", i+1, note)
		}
		return nil
	case len(args) == 2 && args[0] == "delete":
		n, err := strconv.Atoi(args[1])
		if err != nil || n < 1 || n > len(notes) {
			return errors.New("there is no such note")
		}
		if err := save(slices.Delete(notes, n-1, n)); err != nil {
			return err
		}
		fmt.Println("Deleted note", n)
		return nil
	}
	return errors.New("usage: add TEXT | list | delete NUMBER")
}

func main() {
	if err := run(os.Args[1:]); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

Terminal

$ ./29-notepad add "Buy two disks"
Added note 1
$ ./29-notepad add "Check the backup"
Added note 2
$ ./29-notepad list
1. Buy two disks
2. Check the backup
$ ./29-notepad delete 1
Deleted note 1
$ ./29-notepad delete 9; echo "exit code $?"
there is no such note
exit code 1
$ ./29-notepad list
1. Check the backup

Exercise

Add a command find TEXT that shows matching notes.

How it works

  • load reads notes.txt into a slice. A missing file is no error here: the notepad is empty.
  • run decides what the words mean and returns an error; main prints it and ends with code 1.
  • slices.Delete takes one note out and save writes the rest.
  • add changes a line break in a note into a space, so one note stays one line.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.