Go CLI 기반 Todo 앱

PHPz
풀어 주다: 2024-09-10 06:39:32
원래의
1111명이 탐색했습니다.

Go CLI based Todo app

Go CLI based Todo app

사용된 외부 라이브러리 설치


github.com/aquasecurity/table을 방문하세요

디렉토리 구조

Go CLI based Todo app

main.go

package main

func main() {
    todos := Todos{}

    storage := NewStorage[Todos]("todos.json")
    storage.Load(&todos)

    CmdFlags := NewCmdflags()
    CmdFlags.Execute(&todos)

    storage.Save(todos)
}
로그인 후 복사
  1. 구조 이름 Todos의 조각 만들기
  2. 이전에 Storage.Save로 생성한 "todo.json" 파일에 로컬로 시스템의 기존 할 일에 대한 동적 메모리를 생성합니다.
  3. 그렇지 않으면 비어 있는 상태로 로드됩니다
  4. 사용자가 제공한 명령 플래그를 구문 분석하고 검증합니다
  5. 제공된 플래그에 따라 실행

기능 구현

package main

import (
    "errors"
    "fmt"
    "os"
    "strconv"
    "time"

    "github.com/aquasecurity/table"
)

type Todo struct {
    Title     string
    Completed bool
    CreatedAt time.Time
    // this field here is a pointer reference because it can be null
    CompletedAt *time.Time
}

// a slice(array) of Todo
type Todos []Todo

// Passing Todo slice here as a reference
// declares a parameter named todos that is a pointer to a Todos slice.
// the function receives a copy of the slice under the name todos
func (todos *Todos) add(title string) {
    todo := Todo{
        Title:       title,
        Completed:   false,
        CompletedAt: nil,
        CreatedAt:   time.Now(),
    }
    *todos = append(*todos, todo)

}

func (todos *Todos) validateIndex(index int) error {
    if index < 0 || index >= len(*todos) {
        err := errors.New("invalid index")
        fmt.Println(err)
    }
    return nil
}

func (todos *Todos) delete(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    *todos = append(t[:index], t[index+1:]...)

    return nil
}

func (todos *Todos) toggle(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    isCompleted := t[index].Completed

    if !isCompleted {
        completionTime := time.Now()
        t[index].CompletedAt = &completionTime
    }

    t[index].Completed = !isCompleted

    return nil
}

func (todos *Todos) edit(index int, title string) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    t[index].Title = title

    return nil
}

func (todos *Todos) print() {
    table := table.New(os.Stdout)
    table.SetRowLines(false)
    table.SetHeaders("#", "Title", "Status", "Created", "Completed")

    for index, t := range *todos {
        mark := "❌"
        completedAt := ""

        if t.Completed {
            mark = "✅"
            if t.CompletedAt != nil {
                completedAt = t.CompletedAt.Format(time.RFC1123)
            }
        }
        table.AddRow(strconv.Itoa(index), t.Title, mark, t.CreatedAt.Format(time.RFC1123), completedAt)
    }

    table.Render()
}

로그인 후 복사

스토리지 구현

package main

import (
    "encoding/json"
    "os"
)

type Storage[T any] struct {
    FileName string
}

func NewStorage[T any](filename string) *Storage[T] {
    return &Storage[T]{FileName: filename}
}

func (s *Storage[T]) Save(data T) error {
    fileData, err := json.MarshalIndent(data, "", "\t")

    if err != nil {
        return err
    }

    return os.WriteFile(s.FileName, fileData, 0644)

}

func (s *Storage[T]) Load(data *T) error {
    fileData, err := os.ReadFile(s.FileName)

    if err != nil {
        return err
    }

    return json.Unmarshal(fileData, data)
}
로그인 후 복사

명령줄 플래그 유효성 검사 및 실행

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
    "strings"
)

type CmdFlags struct {
    Help   bool
    Add    string
    Del    int
    Edit   string
    Update int
    List   bool
}

func NewCmdflags() *CmdFlags {
    cf := CmdFlags{}

    flag.BoolVar(&cf.Help, "help", false, "List existing commands")
    flag.StringVar(&cf.Add, "add", "", "Add a new todo specify title")
    flag.StringVar(&cf.Edit, "edit", "", "Edit an existing todo, enter #index and specify a new title. \"id:new title\"")
    flag.IntVar(&cf.Del, "del", -1, "Specify a todo by #index to delete")
    flag.IntVar(&cf.Update, "update", -1, "Specify a todo #index to update")
    flag.BoolVar(&cf.List, "list", false, "List all todos")

    for _, arg := range os.Args[1:] {
        if strings.HasPrefix(arg, "-") && !isValidFlag(arg) {
            fmt.Printf("Unknown flag: %s\n", arg)
            fmt.Println("try --help to know more")

            os.Exit(0)
        }
    }

    flag.Parse()
    return &cf
}

func isValidFlag(flag string) bool {

    validFlags := []string{
        "-help", "--help",
        "-add", "--add",
        "-edit", "--edit",
        "-del", "--del",
        "-update", "--update",
        "-list", "--list",
    }

    if idx := strings.Index(flag, "="); idx != -1 {
        flag = flag[:idx]
    }

    for _, validFlag := range validFlags {
        if flag == validFlag {
            return true
        }
    }

    return false
}

func (cf *CmdFlags) Execute(todos *Todos) {
    switch {
    case cf.List:
        todos.print()

    case cf.Add != "":
        todos.add(cf.Add)

    case cf.Edit != "":
        parts := strings.SplitN(cf.Edit, ":", 2)
        if len(parts) != 2 {
            fmt.Printf("Error, invalid format for edit.\nCorrect Format: \"id:new title\" ")
            os.Exit(1)
        }

        index, err := strconv.Atoi(parts[0])

        if err != nil {
            fmt.Printf("Error, Invalid index for edit")
            os.Exit(1)
        }

        todos.edit(index, parts[1])

    case cf.Update != -1:
        todos.toggle(cf.Update)

    case cf.Del != -1:
        todos.delete(cf.Del)

    case cf.Help:
        fmt.Println("usage:")
        fmt.Println("--help\t\t| List existing commands")
        fmt.Println("--add\t\t| Add new task")
        fmt.Println("--del\t\t| Delete an existing task")
        fmt.Println("--update\t| Check/Uncheck existing task")
        fmt.Println("--edit\t\t| Edit an existing task")
    }
}
로그인 후 복사

Github 레포: CLI Todo 앱

위 내용은 Go CLI 기반 Todo 앱의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!