/
ShellHistory.go
98 lines (88 loc) · 2.33 KB
/
ShellHistory.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
98
package models
import (
"fmt"
"github.com/bharatkalluri/harmony/config"
"io/ioutil"
"sort"
)
type ShellHistory struct {
History []HistoryItem
}
func (s ShellHistory) ConvertToString(shell Shell) string {
var shellHistoryStr string
for _, el := range s.History {
if len(el.Command) > 0 {
shellHistoryStr = shellHistoryStr + fmt.Sprintf("%s\n", shell.EncodeHistoryItem(el))
}
}
return shellHistoryStr
}
func GetShellHistoryInBytes() ([]byte, error) {
var err error
appConfig, err := config.ReadAppConfig()
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile(appConfig.ShellHistoryPath)
return data, err
}
func (s ShellHistory) GetLatestUpdatedTime() int {
var max int
for i, el := range s.History {
if i == 0 || el.TimeStamp > max {
max = el.TimeStamp
}
}
return max
}
func GetShellHistory(shell Shell) (ShellHistory, error) {
data, err := GetShellHistoryInBytes()
if err != nil {
return ShellHistory{}, err
}
shellHistory, err := shell.GetShellHistoryFromBytes(data)
if err != nil {
return ShellHistory{}, err
}
return shellHistory, nil
}
func WriteLocalShellHistory(shellHistory ShellHistory, shell Shell) error {
shellHistoryStr := shellHistory.ConvertToString(shell)
appConfig, err := config.ReadAppConfig()
if err != nil {
return err
}
err = ioutil.WriteFile(appConfig.ShellHistoryPath, []byte(shellHistoryStr), 0644)
return err
}
func addMap(a map[int]string, b map[int]string) {
for k, v := range b {
a[k] = v
}
}
func MergeShellHistories(shellHistoryOne ShellHistory, shellHistoryTwo ShellHistory) ShellHistory {
shellHistoryOneMap := make(map[int]string)
if shellHistoryOne.History != nil {
for _, el := range shellHistoryOne.History {
shellHistoryOneMap[el.TimeStamp] = el.Command
}
}
shellHistoryTwoMap := make(map[int]string)
if shellHistoryTwo.History != nil {
for _, el := range shellHistoryTwo.History {
shellHistoryTwoMap[el.TimeStamp] = el.Command
}
}
addMap(shellHistoryOneMap, shellHistoryTwoMap)
var mergedShellHistory []HistoryItem
for k, v := range shellHistoryOneMap {
mergedShellHistory = append(mergedShellHistory, HistoryItem{
Command: v,
TimeStamp: k,
})
}
sort.Slice(mergedShellHistory[:], func(i, j int) bool {
return mergedShellHistory[i].TimeStamp < mergedShellHistory[j].TimeStamp
})
return ShellHistory{History: mergedShellHistory}
}