File: lazy.go

package info (click to toggle)
gitlab-shell 14.35.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,652 kB
  • sloc: ruby: 1,129; makefile: 583; sql: 391; sh: 384
file content (42 lines) | stat: -rw-r--r-- 960 bytes parent folder | download | duplicates (2)
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
package backup

import (
	"io"
)

// LazyWriter is a WriteCloser that will call Create when on the first call to
// Write. This means it will only create a file if there will be data written
// to it.
type LazyWriter struct {
	create func() (io.WriteCloser, error)
	w      io.WriteCloser
}

// NewLazyWriter initializes a new LazyWriter. create is called on the first
// call of Write, any errors will be returned by this call.
func NewLazyWriter(create func() (io.WriteCloser, error)) *LazyWriter {
	return &LazyWriter{
		create: create,
	}
}

func (w *LazyWriter) Write(p []byte) (int, error) {
	if w.w == nil {
		var err error
		w.w, err = w.create()
		if err != nil {
			return 0, err
		}
	}

	return w.w.Write(p)
}

// Close calls Close on the WriteCloser returned by Create, passing on any
// returned error. Close must be called to properly clean up resources.
func (w *LazyWriter) Close() error {
	if w.w == nil {
		return nil
	}
	return w.w.Close()
}