13 Commits
v0.1 ... main

Author SHA1 Message Date
amantahiliani
8da19ea968 Update goreleaser 2025-05-23 00:47:20 -04:00
amantahiliani
8038757726 Update 2025-05-23 00:36:36 -04:00
amantahiliani
39a282695d Remove Formula 2025-05-23 00:22:15 -04:00
amantahiliani
b71171d5a8 Update Binary 2025-05-23 00:00:59 -04:00
amantahiliani
3180461d94 Merge branch 'main' of https://github.com/AmanTahiliani/todo 2025-05-23 00:00:44 -04:00
amantahiliani
fcf0cb3653 Update 2025-05-23 00:00:37 -04:00
Aman Tahiliani
3dbf9a2b3d Merge pull request #3 from AmanTahiliani/productionify
Added Installation and Makefile
2025-05-23 09:22:30 +05:30
amantahiliani
91ab19fc02 Made Production Ready 2025-05-22 23:51:27 -04:00
Aman Tahiliani
40d1fa64b8 Merge pull request #2 from AmanTahiliani/shorthand-and-help
Added Short representations and Help Flag
2025-05-23 08:57:10 +05:30
amantahiliani
421090b673 Added Short representations and Help Flag 2025-05-22 23:25:53 -04:00
Aman Tahiliani
2e770df8f3 Merge pull request #1 from AmanTahiliani/sqlite-integration
Added Sqlite DB replacing JSON
2025-05-23 08:45:56 +05:30
amantahiliani
a1778d2037 Updated README 2025-05-22 23:15:24 -04:00
amantahiliani
748c8c8573 Added Sqlite DB replacing JSON 2025-05-22 23:11:03 -04:00
9 changed files with 525 additions and 128 deletions

15
.gitignore vendored
View File

@@ -1,9 +1,5 @@
# Binaries
todo
todo.exe
todo-mac
todo-linux
main
# OS files
.DS_Store
@@ -22,4 +18,11 @@ vendor/
todos.json
# Test cache
*.test
*.test
# Log files
*.log
# DB files
*.db# Added by goreleaser init:
dist/

79
.goreleaser.yaml Normal file
View File

@@ -0,0 +1,79 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
- go generate ./...
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm64
checksum:
name_template: 'checksums.txt'
algorithm: sha256
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- 'README'
- Merge pull request
- Merge branch
archives:
- formats: [tar.gz]
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
formats: [zip]
brews:
-
name: todo
homepage: https://github.com/AmanTahiliani/todo
description: "A simple CLI tool to manage your todo list."
license: "MIT"
repository:
owner: AmanTahiliani
name: homebrew-tools
commit_author:
name: AmanTahiliani
email: amantahiliani7437@gmail.com
snapshot:
name_template: '{{ .Tag }}-next'
release:
prerelease: auto
universal_binaries:
- replace: true

23
Makefile Normal file
View File

@@ -0,0 +1,23 @@
BINARY_NAME=todo
INSTALL_PATH=/usr/local/bin
.PHONY: build
build:
go build -o $(BINARY_NAME) ./cmd/todo
.PHONY: install
install: build
mkdir -p $(INSTALL_PATH)
cp $(BINARY_NAME) $(INSTALL_PATH)/$(BINARY_NAME)
.PHONY: uninstall
uninstall:
rm -f $(INSTALL_PATH)/$(BINARY_NAME)
.PHONY: clean
clean:
rm -f $(BINARY_NAME)
.PHONY: test
test:
go test -v ./...

108
README.md
View File

@@ -1,6 +1,6 @@
# Go Todo CLI App
# Todo CLI
A simple command-line Todo application written in Go. Todos are stored in a local JSON file.
A powerful command-line todo application written in Go. Manage your tasks efficiently with a simple, intuitive interface. All data is automatically stored in a SQLite database in your home directory.
## Features
@@ -8,61 +8,87 @@ A simple command-line Todo application written in Go. Todos are stored in a loca
- List all todos, grouped by incomplete and completed
- Mark todos as completed
- Remove todos by ID
- Data is persisted in `todos.json`
- Automatic SQLite database management
- User-friendly command-line interface with intuitive commands
- Data stored securely in user's home directory
## Installation
### Using Go
```bash
go install github.com/AmanTahiliani/todo/cmd/todo@latest
```
### Using Make
```bash
git clone https://github.com/AmanTahiliani/todo.git
cd todo
make install
```
### Using Homebrew (macOS)
```bash
brew tap AmanTahiliani/todo
brew install todo
```
## Usage
Build the app:
```sh
go build -o todo
### Add a new todo
```bash
todo add -t "Meeting" -d "Team standup at 10AM"
```
### Add a Todo
```sh
./todo -action=add -title="Buy milk" -description="Get 2 liters of milk"
### List all todos
```bash
todo list
```
### List Todos
```sh
./todo -action=list
### Mark a todo as completed
```bash
todo complete -i 1
```
### Complete a Todo
```sh
./todo -action=complete -id=1
### Remove a todo
```bash
todo remove -i 1
```
### Remove a Todo
```sh
./todo -action=remove -id=1
### Get help
```bash
todo --help
```
## Flags
## Data Storage
- `-action` (add, remove, list, complete) — What you want to do
- `-title` — Title for the todo (required for add)
- `-description` — Description for the todo (required for add)
- `-id` — ID of the todo (required for remove and complete)
Todos are automatically stored in a SQLite database located at `~/.todo/todos.db`. The application handles all database operations transparently, so you don't need to worry about database management.
## Example
## Development
```sh
./todo -action=add -title="Read Go book" -description="Finish chapter 3"
./todo -action=list
./todo -action=complete -id=1
./todo -action=remove -id=1
### Prerequisites
- Go 1.21 or later
- Make (optional, for easier building)
### Building from source
```bash
make build
```
## Next Improvements
### Running tests
- Use a CLI library like [cobra](https://github.com/spf13/cobra) for better UX
- Add edit and search features
- Add unit tests
- Improve error handling
- Use a database instead of a JSON file for storage
- Add binary release for different platforms and make it available through Homebrew, Winget and Apt.
```bash
make test
```
## License
MIT License
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.

227
cmd/todo/main.go Normal file
View File

@@ -0,0 +1,227 @@
package main
import (
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
)
type Todo struct {
Id int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Completed bool `json:"completed"`
}
var (
dbPath string
rootCmd = &cobra.Command{
Use: "todo",
Short: "A simple CLI todo application",
Long: `Todo is a CLI application for managing your tasks.
It provides simple commands to add, list, complete, and remove todos.
All data is stored locally in a SQLite database.`,
}
addCmd = &cobra.Command{
Use: "add",
Short: "Add a new todo",
Run: handleAdd,
}
listCmd = &cobra.Command{
Use: "list",
Short: "List all todos",
Run: handleList,
}
completeCmd = &cobra.Command{
Use: "complete",
Short: "Mark a todo as completed",
Run: handleComplete,
}
removeCmd = &cobra.Command{
Use: "remove",
Short: "Remove a todo",
Run: handleRemove,
}
title string
description string
id int
)
func init() {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
// Create .todo directory if it doesn't exist
todoDir := filepath.Join(homeDir, ".todo")
if err := os.MkdirAll(todoDir, 0755); err != nil {
log.Fatal(err)
}
// Set database path
dbPath = filepath.Join(todoDir, "todos.db")
// Add commands
rootCmd.AddCommand(addCmd, listCmd, completeCmd, removeCmd)
// Add flags
addCmd.Flags().StringVarP(&title, "title", "t", "", "Title of the todo")
addCmd.Flags().StringVarP(&description, "description", "d", "", "Description of the todo")
addCmd.MarkFlagRequired("title")
addCmd.MarkFlagRequired("description")
completeCmd.Flags().IntVarP(&id, "id", "i", 0, "ID of the todo to complete")
completeCmd.MarkFlagRequired("id")
removeCmd.Flags().IntVarP(&id, "id", "i", 0, "ID of the todo to remove")
removeCmd.MarkFlagRequired("id")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func getDB() *sql.DB {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
// Create table if it doesn't exist
sqlStmt := `CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
completed BOOLEAN DEFAULT 0
);`
_, err = db.Exec(sqlStmt)
if err != nil {
log.Fatal(err)
}
return db
}
func handleAdd(_ *cobra.Command, _ []string) {
db := getDB()
defer db.Close()
_, err := db.Exec("INSERT INTO todos (title, description) VALUES (?, ?)", title, description)
if err != nil {
log.Fatal(err)
}
fmt.Println("Todo added successfully!")
}
func handleList(_ *cobra.Command, _ []string) {
db := getDB()
defer db.Close()
rows, err := db.Query("SELECT id, title, description, completed FROM todos ORDER BY completed, id")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
fmt.Println("\nPending Todos:")
fmt.Println("-------------")
pendingFound := false
for rows.Next() {
var todo Todo
if err := rows.Scan(&todo.Id, &todo.Title, &todo.Description, &todo.Completed); err != nil {
log.Fatal(err)
}
if !todo.Completed {
pendingFound = true
fmt.Printf("[%d] %s\n %s\n\n", todo.Id, todo.Title, todo.Description)
}
}
if !pendingFound {
fmt.Println("No pending todos!\n")
}
// Reset the rows for completed todos
rows, err = db.Query("SELECT id, title, description, completed FROM todos WHERE completed = 1 ORDER BY id")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
fmt.Println("Completed Todos:")
fmt.Println("---------------")
completedFound := false
for rows.Next() {
var todo Todo
if err := rows.Scan(&todo.Id, &todo.Title, &todo.Description, &todo.Completed); err != nil {
log.Fatal(err)
}
completedFound = true
fmt.Printf("[%d] %s\n %s\n\n", todo.Id, todo.Title, todo.Description)
}
if !completedFound {
fmt.Println("No completed todos!")
}
}
func handleComplete(_ *cobra.Command, _ []string) {
db := getDB()
defer db.Close()
result, err := db.Exec("UPDATE todos SET completed = 1 WHERE id = ?", id)
if err != nil {
log.Fatal(err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
if rowsAffected == 0 {
fmt.Printf("No todo found with ID %d\n", id)
return
}
fmt.Printf("Todo %d marked as completed!\n", id)
}
func handleRemove(_ *cobra.Command, _ []string) {
db := getDB()
defer db.Close()
result, err := db.Exec("DELETE FROM todos WHERE id = ?", id)
if err != nil {
log.Fatal(err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
if rowsAffected == 0 {
fmt.Printf("No todo found with ID %d\n", id)
return
}
fmt.Printf("Todo %d removed successfully!\n", id)
}

12
go.mod
View File

@@ -1,3 +1,13 @@
module github.com/AmanTahiliani/todo
go 1.24.0
go 1.21.4
require (
github.com/mattn/go-sqlite3 v1.14.28
github.com/spf13/cobra v1.9.1
)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
)

12
go.sum Normal file
View File

@@ -0,0 +1,12 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

177
main.go
View File

@@ -1,11 +1,13 @@
package main
import (
"encoding/json"
"database/sql"
"flag"
"fmt"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
)
var fileName = "todos.json"
@@ -37,145 +39,160 @@ func listTodos(todos []Todo) {
}
}
func ensureFile() error {
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
return f.Close()
}
func loadTodos() ([]Todo, error) {
if err := ensureFile(); err != nil {
return nil, err
}
data, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
if len(data) == 0 {
return []Todo{}, nil
}
func loadTodos(db *sql.DB) ([]Todo, error) {
var todos []Todo
if err := json.Unmarshal(data, &todos); err != nil {
return []Todo{}, nil // Reset on corrupt file
rows, err := db.Query("SELECT id, title, description, completed FROM todos")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var todo Todo
err := rows.Scan(&todo.Id, &todo.Title, &todo.Description, &todo.Completed)
if err != nil {
return nil, err
}
todos = append(todos, todo)
}
return todos, nil
}
func saveTodos(todos []Todo) error {
data, err := json.MarshalIndent(todos, "", " ")
func getNextId(db *sql.DB) int {
var id int
err := db.QueryRow("SELECT MAX(id) FROM todos").Scan(&id)
if err != nil {
return err
return 0
}
return os.WriteFile(fileName, data, 0666)
return id + 1
}
func getNextId(todos []Todo) int {
maxId := 0
for _, todo := range todos {
if todo.Id > maxId {
maxId = todo.Id
}
}
return maxId + 1
}
func addTodo(title, description string) error {
todos, err := loadTodos()
if err != nil {
return err
}
func addTodo(db *sql.DB, title, description string) error {
todo := Todo{
Id: getNextId(todos),
Id: getNextId(db),
Title: title,
Description: description,
Completed: false,
}
todos = append(todos, todo)
return saveTodos(todos)
}
func completeTodo(id int) error {
todos, err := loadTodos()
_, err := db.Exec("INSERT INTO todos (id, title, description, completed) VALUES (?, ?, ?, ?)", todo.Id, todo.Title, todo.Description, todo.Completed)
if err != nil {
return err
}
for i := range todos {
if todos[i].Id == id {
todos[i].Completed = true
break
}
}
return saveTodos(todos)
return nil
}
func removeTodo(id int) error {
todos, err := loadTodos()
func completeTodo(db *sql.DB, id int) error {
_, err := db.Exec("UPDATE todos SET completed=true WHERE id=?", id)
if err != nil {
return err
}
for i, todo := range todos {
if todo.Id == id {
todos = append(todos[:i], todos[i+1:]...)
break
}
return nil
}
func removeTodo(db *sql.DB, id int) error {
_, err := db.Exec("DELETE FROM todos WHERE id=?", id)
if err != nil {
return err
}
return saveTodos(todos)
return nil
}
var (
action = flag.String("action", "add", "action (add, remove, list, complete)")
title = flag.String("title", "", "title of the todo")
description = flag.String("description", "", "description of the todo")
id = flag.Int("id", 0, "ID of the todo to be actioned upon. Used for remove and complete")
title = flag.String("title", "", "Title of the todo item")
description = flag.String("description", "", "Description of the todo item")
id = flag.Int("id", 0, "ID of the todo item to remove or mark as complete")
)
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Todo CLI - A simple todo list manager\n\n")
fmt.Fprintf(os.Stderr, "Usage:\n %s [action] [flags]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Actions:\n")
fmt.Fprintf(os.Stderr, " add Add a new todo item\n")
fmt.Fprintf(os.Stderr, " remove Remove a todo item\n")
fmt.Fprintf(os.Stderr, " complete Mark a todo item as completed\n")
fmt.Fprintf(os.Stderr, " list List all todo items\n\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\nExamples:\n")
fmt.Fprintf(os.Stderr, " %s add -t \"Meeting\" -d \"Team standup at 10AM\"\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s complete -i 1\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s remove -i 2\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s list\n", os.Args[0])
}
flag.StringVar(title, "t", "", "shorthand for --title")
flag.StringVar(description, "d", "", "shorthand for --description")
flag.IntVar(id, "i", 0, "shorthand for --id")
}
func main() {
// Check for help flag before any other operations
if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
flag.Usage()
os.Exit(0)
}
db, err := sql.Open("sqlite3", "./todos.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
sqlStmt := `CREATE TABLE if not exists todos ( id INT not null primary key, title varchar not null, description text, completed boolean);`
_, err = db.Exec(sqlStmt)
if err != nil {
log.Fatal(err)
}
if len(os.Args) < 2 {
flag.Usage()
os.Exit(1)
}
action := os.Args[1]
os.Args = os.Args[1:]
flag.Parse()
switch *action {
switch action {
case "add":
handleAdd()
handleAdd(db)
case "remove":
handleRemove()
handleRemove(db)
case "complete":
handleComplete()
handleComplete(db)
case "list":
handleList()
handleList(db)
default:
log.Fatal("Please input a valid action.")
}
}
func handleAdd() {
func handleAdd(db *sql.DB) {
if *title == "" || *description == "" {
log.Fatal("Title and Description must be provided for adding a new TODO")
}
if err := addTodo(*title, *description); err != nil {
if err := addTodo(db, *title, *description); err != nil {
log.Fatal(err)
}
}
func handleRemove() {
func handleRemove(db *sql.DB) {
if *id == 0 {
log.Fatal("ID must be provided for removing a TODO")
}
if err := removeTodo(*id); err != nil {
if err := removeTodo(db, *id); err != nil {
log.Fatal(err)
}
}
func handleComplete() {
func handleComplete(db *sql.DB) {
if *id == 0 {
log.Fatal("ID must be provided for marking a Todo as complete")
}
if err := completeTodo(*id); err != nil {
if err := completeTodo(db, *id); err != nil {
log.Fatal(err)
}
}
func handleList() {
todos, err := loadTodos()
func handleList(db *sql.DB) {
todos, err := loadTodos(db)
if err != nil {
log.Fatal(err)
}

BIN
todo

Binary file not shown.