Skip to content

Commit e47e3ee

Browse files
committed
cacheSet/Get for all data types + persistent list cache
1 parent 4fff949 commit e47e3ee

File tree

5 files changed

+142
-103
lines changed

5 files changed

+142
-103
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Github Email: ketan.krishnan.xxxxx@iitbhu.ac.in
2626
```
2727

2828
## Configuration
29-
**Custom Template**: Create a file named *template.cpp, template.py, template.java, template.js* for respective languages in the **working** directory to use this feature.
29+
**Custom Template**: Create a file named *template.cpp, template.py, template.java, template.js* for respective languages in the **working** directory to use this feature.
3030
**Languages Supported**: *cpp*(C++17) \[default\], *java*, *python*(CPython3), *javascript*(Node.js)
3131
Also you can manually edit the config at ```~/.cses/config.json```
3232
```

project/helper.go

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ package main
22

33
import (
44
"bufio"
5+
"bytes"
56
"encoding/json"
67
"fmt"
8+
"io"
79
"io/ioutil"
810
"os"
911
"os/exec"
@@ -33,12 +35,6 @@ func UserHomeDir() string {
3335
return os.Getenv("HOME")
3436
}
3537

36-
func updateConfig(sess *Session) {
37-
out, err := json.MarshalIndent(sess, "", " ")
38-
check(err)
39-
cacheSet("config.json", string(out), sess.Root)
40-
}
41-
4238
func updateIfNew(scanner *bufio.Scanner, src *string, text string) {
4339
if *src == "" {
4440
fmt.Print(text + ": ")
@@ -52,31 +48,47 @@ func updateIfNew(scanner *bufio.Scanner, src *string, text string) {
5248
}
5349
}
5450

55-
func cacheSet(filename string, data string, root string) {
51+
func cacheSet(filename string, data interface{}, root string) {
52+
5653
f, err := os.Create(filepath.Join(root, filename))
54+
defer f.Close()
5755
check(err)
5856

59-
w := bufio.NewWriter(f)
60-
w.WriteString(data)
57+
b, err := json.MarshalIndent(data, "", " ")
58+
check(err)
6159

62-
w.Flush()
63-
defer f.Close()
60+
_, err = io.Copy(f, bytes.NewReader(b))
6461
}
6562

66-
func cacheGet(filename string, root string) ([]byte, bool) {
63+
func cacheGet(filename string, ret interface{}, root string) bool {
6764
path := filepath.Join(root, filename)
6865

6966
_, err := os.Stat(path)
7067
if os.IsNotExist(err) {
71-
return nil, false
68+
return false
7269
}
7370
content, err := ioutil.ReadFile(path)
7471
check(err)
75-
return content, true
72+
73+
json.Unmarshal(content, ret)
74+
return true
75+
}
76+
77+
func updateListByTask(task string, status string, root string) {
78+
var problems = []*Problem{}
79+
cacheGet("problemList.json", &problems, root)
80+
81+
for _, v := range problems {
82+
if task == v.Task {
83+
v.Solved = status
84+
break
85+
}
86+
}
87+
cacheSet("problemList.json", problems, root)
7688
}
7789

7890
func getTemplate(ext string) string {
79-
content, err := ioutil.ReadFile("template"+ext)
91+
content, err := ioutil.ReadFile("template" + ext)
8092
if err != nil {
8193
return ""
8294
}
@@ -121,21 +133,21 @@ func writeCodeFile(filename string, text string, template string) bool {
121133

122134
var extLangMap = map[string]string{
123135
".java": "Java",
124-
".js": "Node.js",
125-
".py": "Python3",
126-
".cpp": "C++",
136+
".js": "Node.js",
137+
".py": "Python3",
138+
".cpp": "C++",
127139
}
128140
var extOptionMap = map[string]string{
129141
".java": "",
130-
".js": "",
131-
".py": "CPython3",
132-
".cpp": "C++17",
142+
".js": "",
143+
".py": "CPython3",
144+
".cpp": "C++17",
133145
}
134-
var langExtMap = map[string]string {
135-
"java": ".java",
146+
var langExtMap = map[string]string{
147+
"java": ".java",
136148
"javascript": ".js",
137-
"python": ".py",
138-
"cpp": ".cpp",
149+
"python": ".py",
150+
"cpp": ".cpp",
139151
}
140152

141153
var unicodeMap = map[string]string{

project/main.go

Lines changed: 56 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,15 @@ package main
22

33
import (
44
"bufio"
5-
"encoding/json"
65
"flag"
76
"fmt"
87
"os"
98
"os/exec"
109
"path/filepath"
11-
"strconv"
1210
"strings"
11+
"sync"
1312
"time"
1413

15-
"github.com/PuerkitoBio/goquery"
1614
"github.com/briandowns/spinner"
1715
)
1816

@@ -38,29 +36,19 @@ type Session struct {
3836
Cookie string `json:"cookie"`
3937
Root string `json:"root"`
4038
Editor string `json:"editor"`
41-
Lang string `json:"lang"`
39+
Lang string `json:"lang"`
4240
Github githubConfig `json:"github"`
4341
}
4442

45-
// var cpptemplate = `
46-
// #include<bits/stdc++.h>
47-
// using namespace std;
48-
49-
// int main(){
50-
51-
// return 0;
52-
// }
53-
// `
54-
5543
func initSess(sess *Session) bool {
5644
os.MkdirAll(sess.Root, os.ModePerm)
5745

58-
out, ok := cacheGet("config.json", sess.Root)
46+
ok := cacheGet("config.json", sess, sess.Root)
5947
if !ok {
6048
return false
6149
}
6250

63-
json.Unmarshal(out, sess)
51+
// json.Unmarshal(out, sess)
6452
if sess.Csrf == "" || sess.User == "" || sess.Cookie == "" {
6553
return false
6654
}
@@ -78,64 +66,56 @@ func login(sess *Session, pass string) bool {
7866
}
7967

8068
func promtLogin(sess *Session) bool {
81-
scanner := bufio.NewScanner(os.Stdin)
8269

70+
var wg sync.WaitGroup
71+
wg.Add(1)
72+
go func() {
73+
sess.Cookie, sess.Csrf = newCookieCsrf()
74+
wg.Done()
75+
}()
76+
77+
scanner := bufio.NewScanner(os.Stdin)
8378
updateIfNew(scanner, &sess.User, "Username")
8479

8580
fmt.Print("Password: ")
8681
scanner.Scan()
8782
PASSWORD := scanner.Text()
8883

89-
sess.Cookie, sess.Csrf = newCookieCsrf()
84+
s := spinner.New(spinner.CharSets[36], 100*time.Millisecond)
85+
s.Prefix = "Logging "
86+
87+
s.Start()
88+
wg.Wait()
9089
ok := login(sess, PASSWORD)
90+
s.Stop()
9191

9292
if !ok {
9393
return false
9494
}
9595

96-
updateConfig(sess)
97-
96+
cacheSet("config.json", sess, sess.Root)
9897
return true
9998
}
10099

101-
func list(sess *Session) {
102-
103-
doc, err := goquery.NewDocumentFromReader(listRequest(sess.Cookie))
104-
check(err)
105-
106-
doc.Find(".task").Each(func(i int, s *goquery.Selection) {
107-
108-
solved := "✘"
109-
110-
a := s.Find("a")
111-
link, _ := a.Attr("href")
112-
taskNumber := link[17:]
113-
title := a.Text()
114-
115-
hitRatio := strings.Split(s.Find("span").Text(), "/")
116-
n, err := strconv.ParseFloat(strings.TrimSpace(hitRatio[0]), 64)
117-
check(err)
118-
d, err := strconv.ParseFloat(strings.TrimSpace(hitRatio[1]), 64)
119-
check(err)
120-
121-
percent := n * 100 / d
122-
123-
s.Find(".task-score").Each(func(o int, k *goquery.Selection) {
124-
st, _ := k.Attr("class")
125-
if strings.Contains(st, "full") {
126-
solved = "✔"
127-
} else if "task-score icon " == st {
128-
solved = "-"
129-
}
130-
})
100+
func updateProblemListCache(sess *Session) {
101+
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
102+
s.Prefix = "Updating Problem List "
103+
s.Start()
104+
problems := listRequest(sess.Cookie)
105+
cacheSet("problemList.json", problems, sess.Root)
106+
s.Stop()
107+
}
131108

132-
fmt.Printf("\t%s [%s] %-25s (%.1f %%)\n", solved, taskNumber, title, percent)
133-
})
109+
func list(sess *Session) {
110+
var problems = []*Problem{}
111+
cacheGet("problemList.json", &problems, sess.Root)
134112

113+
for _, v := range problems {
114+
fmt.Printf("\t%s [%s] %-25s (%.1f %%)\n", v.Solved, v.Task, v.Title, v.HitRatio)
115+
}
135116
}
136117

137118
func printResult(link string, sess *Session) bool {
138-
139119
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
140120
s.Prefix = "PENDING "
141121
s.Start()
@@ -171,17 +151,22 @@ func submit(sourceFile string, sess *Session) {
171151

172152
link := submitRequest(opts, sourceFile, sess.Cookie)
173153

174-
if verdict := printResult(link, sess); verdict && validGithubConfig(&sess.Github) {
175-
s := spinner.New(spinner.CharSets[36], 100*time.Millisecond)
176-
s.Prefix = "Committing to Github"
177-
s.Start()
178-
if ok := updateFile(sourceFile, &sess.Github); ok {
179-
s.Stop()
180-
fmt.Println("Github: "+sess.Github.SourceRepo+" ✔")
181-
} else {
182-
s.Stop()
183-
fmt.Println("Github: ✘")
154+
if verdict := printResult(link, sess); verdict {
155+
go updateListByTask(opts["task"], "✔", sess.Root)
156+
if validGithubConfig(&sess.Github) {
157+
s := spinner.New(spinner.CharSets[36], 100*time.Millisecond)
158+
s.Prefix = "Committing to Github"
159+
s.Start()
160+
if ok := updateFile(sourceFile, &sess.Github); ok {
161+
s.Stop()
162+
fmt.Println("Github: " + sess.Github.SourceRepo + " ✔")
163+
} else {
164+
s.Stop()
165+
fmt.Println("Github: ✘")
166+
}
184167
}
168+
} else {
169+
updateListByTask(opts["task"], "✘", sess.Root)
185170
}
186171
}
187172

@@ -194,16 +179,16 @@ func getTask(task string, sess *Session) (string, bool) {
194179
if os.IsNotExist(err) {
195180
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
196181
s.Prefix = "Downloading "
197-
s.Start()
198-
defer s.Stop()
199182

183+
s.Start()
200184
text := downloadTask(task)
185+
s.Stop()
186+
201187
if text == "" {
202188
return "", false
203189
}
204190
cacheSet(filename, text, sess.Root)
205191
}
206-
207192
return getTaskFromCache(task, sess.Root), true
208193
}
209194

@@ -237,7 +222,7 @@ func solve(task string, sess *Session) {
237222
fmt.Println("Editor still not configured")
238223
return
239224
}
240-
updateConfig(sess)
225+
cacheSet("config.json", sess, sess.Root)
241226
}
242227
exec.Command(sess.Editor, filename).Output()
243228
}
@@ -250,18 +235,18 @@ func configureGithub(sess *Session) {
250235
updateIfNew(scanner, &sess.Github.AuthorName, "Github Username")
251236
updateIfNew(scanner, &sess.Github.AuthorEmail, "Github Email")
252237

253-
updateConfig(sess)
238+
cacheSet("config.json", sess, sess.Root)
254239
}
255240

256-
func showHelp(){
241+
func showHelp() {
257242
fmt.Println("Usage:")
258243

259244
fmt.Println("\tcses-cli login")
260245
fmt.Println("\tcses-cli list")
261246
fmt.Println("\tcses-cli show 1068")
262247
fmt.Println("\tcses-cli solve 1068")
263248
fmt.Println("\tcses-cli submit 1068.task.cpp")
264-
249+
265250
fmt.Println("Optional:")
266251
fmt.Println("\tcses-cli github")
267252
}
@@ -292,6 +277,7 @@ func main() {
292277
fmt.Println("Login failed")
293278
} else {
294279
fmt.Println("Logged in successfully")
280+
updateProblemListCache(sess)
295281
}
296282
case "list":
297283
list(sess)

0 commit comments

Comments
 (0)