Debian Codegraph @

internal/buffer/serialize.go

raw
1 package buffer
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "errors"
7 "os"
8 "path/filepath"
9 "time"
10
11 "github.com/zyedidia/micro/v2/internal/config"
12 "github.com/zyedidia/micro/v2/internal/util"
13 )
14
15 // The SerializedBuffer holds the types that get serialized when a buffer is saved
16 // These are used for the savecursor and saveundo options
17 type SerializedBuffer struct {
18 EventHandler *EventHandler
19 Cursor Loc
20 ModTime time.Time
21 }
22
23 // Serialize serializes the buffer to config.ConfigDir/buffers
24 func (b *Buffer) Serialize() error {
25 if !b.Settings["savecursor"].(bool) && !b.Settings["saveundo"].(bool) {
26 return nil
27 }
28 if b.Path == "" {
29 return nil
30 }
31
32 var buf bytes.Buffer
33 err := gob.NewEncoder(&buf).Encode(SerializedBuffer{
34 b.EventHandler,
35 b.GetActiveCursor().Loc,
36 b.ModTime,
37 })
38 if err != nil {
39 return err
40 }
41
42 name, resolveName := util.DetermineEscapePath(filepath.Join(config.ConfigDir, "buffers"), b.AbsPath)
43 err = util.SafeWrite(name, buf.Bytes(), true)
44 if err != nil {
45 return err
46 }
47
48 if resolveName != "" {
49 err = util.SafeWrite(resolveName, []byte(b.AbsPath), true)
50 if err != nil {
51 return err
52 }
53 }
54
55 return nil
56 }
57
58 // Unserialize loads the buffer info from config.ConfigDir/buffers
59 func (b *Buffer) Unserialize() error {
60 // If either savecursor or saveundo is turned on, we need to load the serialized information
61 // from ~/.config/micro/buffers
62 if b.Path == "" {
63 return nil
64 }
65 name, _ := util.DetermineEscapePath(filepath.Join(config.ConfigDir, "buffers"), b.AbsPath)
66 file, err := os.Open(name)
67 if err == nil {
68 defer file.Close()
69 var buffer SerializedBuffer
70 decoder := gob.NewDecoder(file)
71 err = decoder.Decode(&buffer)
72 if err != nil {
73 return errors.New(err.Error() + "\nYou may want to remove the files in ~/.config/micro/buffers (these files\nstore the information for the 'saveundo' and 'savecursor' options) if\nthis problem persists.\nThis may be caused by upgrading to version 2.0, and removing the 'buffers'\ndirectory will reset the cursor and undo history and solve the problem.")
74 }
75 if b.Settings["savecursor"].(bool) {
76 b.StartCursor = buffer.Cursor
77 }
78
79 if b.Settings["saveundo"].(bool) {
80 // We should only use last time's eventhandler if the file wasn't modified by someone else in the meantime
81 if b.ModTime == buffer.ModTime {
82 b.EventHandler = buffer.EventHandler
83 b.EventHandler.cursors = b.cursors
84 b.EventHandler.buf = b.SharedBuffer
85 }
86 }
87 }
88 return nil
89 }