11 "github.com/zyedidia/micro/v2/internal/config"
12 "github.com/zyedidia/micro/v2/internal/screen"
13 "github.com/zyedidia/micro/v2/internal/util"
14 "golang.org/x/text/encoding"
17 const backupMsg = `A backup was detected for this file. This likely means that micro
18 crashed while editing this file, or another instance of micro is currently
21 The backup was created on %s, and the file is
25 * 'recover' will apply the backup as unsaved changes to the current buffer.
26 When the buffer is closed, the backup will be removed.
27 * 'ignore' will ignore the backup, discarding its changes. The backup file
30 Options: [r]ecover, [i]gnore: `
32 var backupRequestChan chan *Buffer
36 time.Sleep(time.Second * 8)
38 for len(backupRequestChan) > 0 {
39 b := <-backupRequestChan
40 bfini := atomic.LoadInt32(&(b.fini)) != 0
49 backupRequestChan = make(chan *Buffer, 10)
54 func (b *Buffer) RequestBackup() {
55 if !b.requestedBackup {
57 case backupRequestChan <- b:
61 b.requestedBackup = true
65 // Backup saves the current buffer to ConfigDir/backups
66 func (b *Buffer) Backup() error {
67 if !b.Settings["backup"].(bool) || b.Path == "" || b.Type != BTDefault {
71 backupdir, err := util.ReplaceHome(b.Settings["backupdir"].(string))
72 if backupdir == "" || err != nil {
73 backupdir = filepath.Join(config.ConfigDir, "backups")
75 if _, err := os.Stat(backupdir); os.IsNotExist(err) {
76 os.Mkdir(backupdir, os.ModePerm)
79 name := filepath.Join(backupdir, util.EscapePath(b.AbsPath))
81 err = overwriteFile(name, encoding.Nop, func(file io.Writer) (e error) {
82 if len(b.lines) == 0 {
90 if _, e = file.Write(b.lines[0].data); e != nil {
94 for _, l := range b.lines[1:] {
95 if _, e = file.Write(eol); e != nil {
98 if _, e = file.Write(l.data); e != nil {
105 b.requestedBackup = false
110 // RemoveBackup removes any backup file associated with this buffer
111 func (b *Buffer) RemoveBackup() {
112 if !b.Settings["backup"].(bool) || b.Settings["permbackup"].(bool) || b.Path == "" || b.Type != BTDefault {
115 f := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
119 // ApplyBackup applies the corresponding backup file to this buffer (if one exists)
120 // Returns true if a backup was applied
121 func (b *Buffer) ApplyBackup(fsize int64) bool {
122 if b.Settings["backup"].(bool) && !b.Settings["permbackup"].(bool) && len(b.Path) > 0 && b.Type == BTDefault {
123 backupfile := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
124 if info, err := os.Stat(backupfile); err == nil {
125 backup, err := os.Open(backupfile)
129 msg := fmt.Sprintf(backupMsg, t.Format("Mon Jan _2 at 15:04, 2006"), util.EscapePath(b.AbsPath))
130 choice := screen.TermPrompt(msg, []string{"r", "i", "recover", "ignore"}, true)
134 b.LineArray = NewLineArray(uint64(fsize), FFAuto, backup)
137 } else if choice%2 == 1 {
139 os.Remove(backupfile)