10 "github.com/zyedidia/micro/internal/config"
11 "github.com/zyedidia/micro/internal/screen"
12 "github.com/zyedidia/micro/internal/util"
13 "golang.org/x/text/encoding"
16 const backupMsg = `A backup was detected for this file. This likely means that micro
17 crashed while editing this file, or another instance of micro is currently
20 The backup was created on %s, and the file is
24 * 'recover' will apply the backup as unsaved changes to the current buffer.
25 When the buffer is closed, the backup will be removed.
26 * 'ignore' will ignore the backup, discarding its changes. The backup file
29 Options: [r]ecover, [i]gnore: `
31 // Backup saves the current buffer to ConfigDir/backups
32 func (b *Buffer) Backup(checkTime bool) error {
33 if !b.Settings["backup"].(bool) || b.Path == "" {
38 sub := time.Now().Sub(b.lastbackup)
39 if sub < time.Duration(backupTime)*time.Millisecond {
40 log.Println("Backup event but not enough time has passed", sub)
45 b.lastbackup = time.Now()
47 backupdir := config.ConfigDir + "/backups/"
48 if _, err := os.Stat(backupdir); os.IsNotExist(err) {
49 os.Mkdir(backupdir, os.ModePerm)
50 log.Println("Creating backup dir")
53 name := backupdir + util.EscapePath(b.AbsPath)
55 log.Println("Backing up to", name)
57 err := overwriteFile(name, encoding.Nop, func(file io.Writer) (e error) {
58 if len(b.lines) == 0 {
66 if _, e = file.Write(b.lines[0].data); e != nil {
70 for _, l := range b.lines[1:] {
71 if _, e = file.Write(eol); e != nil {
74 if _, e = file.Write(l.data); e != nil {
84 // RemoveBackup removes any backup file associated with this buffer
85 func (b *Buffer) RemoveBackup() {
86 if !b.Settings["backup"].(bool) || b.Path == "" {
89 f := config.ConfigDir + "/backups/" + util.EscapePath(b.AbsPath)
93 // ApplyBackup applies the corresponding backup file to this buffer (if one exists)
94 // Returns true if a backup was applied
95 func (b *Buffer) ApplyBackup(fsize int64) bool {
96 if b.Settings["backup"].(bool) && len(b.Path) > 0 {
97 backupfile := config.ConfigDir + "/backups/" + util.EscapePath(b.AbsPath)
98 if info, err := os.Stat(backupfile); err == nil {
99 backup, err := os.Open(backupfile)
103 msg := fmt.Sprintf(backupMsg, t.Format("Mon Jan _2 at 15:04, 2006"), util.EscapePath(b.AbsPath))
104 choice := screen.TermPrompt(msg, []string{"r", "i", "recover", "ignore"}, true)
108 b.LineArray = NewLineArray(uint64(fsize), FFAuto, backup)
111 } else if choice%2 == 1 {
113 os.Remove(backupfile)