src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

save.go (1472B)


      1 package buffer
      2 
      3 import (
      4 	"bytes"
      5 	"fmt"
      6 	"os"
      7 	"time"
      8 )
      9 
     10 // TODO: save to temporary file, then move over current file.
     11 // TODO: autosave; track dirty buffer.
     12 func (b *Buffer) Save() error {
     13 	var buf bytes.Buffer
     14 	switch len(b.lines) {
     15 	case 1:
     16 		if l := b.lines[0]; l.Length() != 0 {
     17 			if _, err := buf.WriteString(l.String()); err != nil {
     18 				return fmt.Errorf(
     19 					"failed to write to buffer: %v", err,
     20 				)
     21 			}
     22 			if _, err := buf.WriteRune('\n'); err != nil {
     23 				return fmt.Errorf(
     24 					"failed to write to buffer: %v", err,
     25 				)
     26 			}
     27 		}
     28 	default:
     29 		for _, l := range b.lines {
     30 			if _, err := buf.WriteString(l.String()); err != nil {
     31 				return fmt.Errorf(
     32 					"failed to write to buffer: %v", err,
     33 				)
     34 			}
     35 			if _, err := buf.WriteRune('\n'); err != nil {
     36 				return fmt.Errorf(
     37 					"failed to write to buffer: %v", err,
     38 				)
     39 			}
     40 		}
     41 	}
     42 
     43 	if err := os.WriteFile(
     44 		b.name,
     45 		buf.Bytes(),
     46 		os.ModePerm,
     47 	); err != nil {
     48 		return fmt.Errorf("failed to write file: %v", err)
     49 	}
     50 
     51 	b.saved = time.Now()
     52 
     53 	return nil
     54 }
     55 
     56 func (b *Buffer) SaveAs(name string) error {
     57 	f, err := os.Create(name)
     58 	if err != nil {
     59 		return fmt.Errorf("failed to create file: %w", err)
     60 	}
     61 
     62 	// Close the previous file.
     63 	if err := b.file.Close(); err != nil {
     64 		b.log.Error.Printf("failed close file: %v", err)
     65 	}
     66 
     67 	// Set the new file and name.
     68 	b.file = f
     69 	b.name = name
     70 
     71 	if err := b.Save(); err != nil {
     72 		return fmt.Errorf("failed to save file: %w", err)
     73 	}
     74 
     75 	return nil
     76 }