forked from invzhi/ankit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
97 lines (80 loc) · 1.84 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"flag"
// "go/format"
// "go/parser"
// "go/token"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"io/ioutil"
"github.com/invzhi/ankit"
"github.com/invzhi/ankit/leetcode"
)
var (
cfg leetcode.Config
spec string
)
func init() {
flag.StringVar(&cfg.Path, "path", ".", "leetcode repo path")
flag.StringVar(&cfg.Source, "db", "leetcode.db", "sqlite3 filename")
flag.StringVar(&cfg.Lang, "lang", "python3", "programming language")
flag.StringVar(&spec, "spec", "", "optional: the relative path of leetcode question that should be exported only")
}
func code(path string, _ leetcode.Lang) (string, error) {
b, err := ioutil.ReadFile(path)
return string(b), err
}
func question(path string, info os.FileInfo) (leetcode.Key, error) {
if path == "." {
return nil, nil
}
// skip directory in repository
if info.IsDir() {
return nil, filepath.SkipDir
}
filename := filepath.Base(path)
ext := filepath.Ext(filename)
// only handle python file
if ext != ".py" {
return nil, nil
}
// identify leetcode question by title slug: filename
slug := strings.TrimSuffix(filename, ext)
id_s := strings.SplitN(slug, "-", 2)[0]
id, err := strconv.Atoi(id_s)
if err != nil {
return nil, filepath.SkipDir
}
return leetcode.KeyID(id), nil
}
func main() {
flag.Parse()
if err := cfg.Valid(); err != nil {
log.Fatal(err)
}
repo := leetcode.NewRepo(cfg, code, question)
defer repo.Close()
var r ankit.Reader = repo
if spec != "" {
path := filepath.Join(cfg.Path, spec)
info, err := os.Lstat(path)
if err != nil {
log.Fatal(err)
}
key, err := repo.KeyFn(spec, info)
if err != nil && err != filepath.SkipDir {
log.Fatal(err)
}
q, err := repo.Question(key, path)
if err != nil {
log.Fatal(err)
}
r = ankit.OneNoteReader(q)
}
if err := ankit.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}
}