Skip to content

Commit

Permalink
accept io.Reader instead of os.File to make it more flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
elliot40404 committed Jan 12, 2025
1 parent 57e0c81 commit c27fe6f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 16 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# MODO
<img src="./images/modo.gif" alt="modo.gif"></img>

> Modo is a simple cli app that lets you interact any text file that contains checkboxes in the markdown format.
> Modo is a simple cross platform cli app that lets you interact any text file that contains checkboxes in the markdown format.
## Why

Expand Down
7 changes: 6 additions & 1 deletion cmd/modo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ func main() {
return
}
defer f.Close()
todos, err := parser.ParseTodos(f)
lineEndingLen, err := parser.GetLineEndingLen(f)
if err != nil {
slog.Error("something went wrong", "error", err)
return
}
todos, err := parser.ParseTodos(f, lineEndingLen)
if err != nil {
slog.Error("something went wrong", "error", err)
}
Expand Down
33 changes: 19 additions & 14 deletions internal/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package parser

import (
"bufio"
"io"
"log/slog"
"os"
"strings"
Expand Down Expand Up @@ -33,28 +34,16 @@ func (t *Todo) ToggleChecked(f *os.File) {
}
}

func ParseTodos(f *os.File) ([]Todo, error) {
func ParseTodos(f io.Reader, lineEndingLen int) ([]Todo, error) {
todos := make([]Todo, 0)
scanner := bufio.NewScanner(f)
offset := int64(0)
lineEnding := 1
crlf, err := isCRLF(f)
if err != nil {
return todos, err
}
if crlf {
lineEnding = 2
}
_, err = f.Seek(0, 0)
if err != nil {
return todos, err
}
for scanner.Scan() {
line := scanner.Text()
if todo, ok := ParseTodo(line, offset); ok {
todos = append(todos, todo)
}
offset += int64(len(line) + lineEnding)
offset += int64(len(line) + lineEndingLen)
}
return todos, nil
}
Expand All @@ -68,6 +57,22 @@ func isCRLF(f *os.File) (bool, error) {
return len(line) > 1 && line[len(line)-2] == '\r' && line[len(line)-1] == '\n', nil
}

func GetLineEndingLen(f *os.File) (int, error) {
lineEndingLen := 1
crlf, err := isCRLF(f)
if err != nil {
return 0, err
}
if crlf {
lineEndingLen = 2
}
_, err = f.Seek(0, 0)
if err != nil {
return 0, err
}
return lineEndingLen, nil
}

func ParseTodo(line string, offset int64) (Todo, bool) {
ogLine := line
line = strings.Trim(line, " ")
Expand Down

0 comments on commit c27fe6f

Please sign in to comment.