Initial reading and writing of CSV

This commit is contained in:
Alex Yatskov 2024-03-30 20:44:24 -07:00
commit 91e6c7438a
3 changed files with 127 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.json
*.txt
*.xml
kanji-merge*

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.foosoft.net/alex/rtk-merge
go 1.21.8

120
main.go Normal file
View File

@ -0,0 +1,120 @@
package main
import (
"encoding/csv"
"flag"
"fmt"
"log"
"os"
"path/filepath"
)
type (
StoryEntry struct {
Author string `json:"author"`
Content string `json:"content"`
ModifiedDate string `json:"modifiedDate"`
StarredCount int `json:"starredCount"`
ReportedCount int `json:"reportedCount"`
}
KanjiEntry struct {
Character string `json:"character"`
Reading string `json:"reading"`
FrameNumber int `json:"frameNumber"`
StrokeCount int `json:"strokeCount"`
Story string `json:"story"`
Stories []StoryEntry `json:"stories"`
}
TableRow = []string
Table = []TableRow
)
func injectStories(table Table, path string) error {
return nil
}
func injectKanjidic(table Table, path string) error {
return nil
}
func loadTable(path string) (Table, error) {
fp, err := os.Open(path)
if err != nil {
return nil, err
}
defer fp.Close()
reader := csv.NewReader(fp)
reader.Comment = '#'
reader.Comma = '\t'
table, err := reader.ReadAll()
if err != nil {
return nil, err
}
for i := range table {
table[i] = table[i][:3]
}
return table, nil
}
func saveTable(path string, table Table) error {
fp, err := os.Create(path)
if err != nil {
return err
}
defer fp.Close()
writer := csv.NewWriter(fp)
if err := writer.WriteAll(table); err != nil {
return err
}
return nil
}
func main() {
var (
storiesPath = flag.String("stories", "", "path for stories JSON")
kanjidicPath = flag.String("kanjidic", "", "path for KANJIDIC")
)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] <notes_in.txt> <notes_out.txt>\n", filepath.Base(os.Args[0]))
fmt.Fprintln(os.Stderr, "Options:")
flag.PrintDefaults()
}
flag.Parse()
args := flag.Args()
if len(args) != 2 {
flag.Usage()
os.Exit(2)
}
table, err := loadTable(os.Args[1])
if err != nil {
log.Fatal(err)
}
if len(*storiesPath) > 0 {
if err := injectStories(table, *storiesPath); err != nil {
log.Fatal(err)
}
}
if len(*kanjidicPath) > 0 {
if err := injectKanjidic(table, *kanjidicPath); err != nil {
log.Fatal(err)
}
}
if err := saveTable(os.Args[2], table); err != nil {
log.Fatal(err)
}
}