-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathstate.go
58 lines (49 loc) · 1.1 KB
/
state.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
package main
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
var dataFolder = ".hget/"
var stateFileName = "state.json"
type State struct {
Url string
Parts []Part
}
type Part struct {
Url string
Path string
RangeFrom int64
RangeTo int64
}
func (s *State) Save() error {
//make temp folder
//only working in unix with env HOME
folder := FolderOf(s.Url)
Printf("Saving current download data in %s\n", folder)
if err := MkdirIfNotExist(folder); err != nil {
return err
}
//move current downloading file to data folder
for _, part := range s.Parts {
os.Rename(part.Path, filepath.Join(folder, filepath.Base(part.Path)))
}
//save state file
j, err := json.Marshal(s)
if err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(folder, stateFileName), j, 0644)
}
func Read(task string) (*State, error) {
file := filepath.Join(os.Getenv("HOME"), dataFolder, task, stateFileName)
Printf("Getting data from %s\n", file)
bytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
s := new(State)
err = json.Unmarshal(bytes, s)
return s, err
}