File: lazy_file.go

package info (click to toggle)
golang-github-cheekybits-genny 1.0.0-8
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 336 kB
  • sloc: makefile: 17; sh: 3
file content (38 lines) | stat: -rw-r--r-- 908 bytes parent folder | download
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
package out

import (
	"os"
	"path"
)

// LazyFile is an io.WriteCloser which defers creation of the file it is supposed to write in
// till the first call to its write function in order to prevent creation of file, if no write
// is supposed to happen.
type LazyFile struct {
	// FileName is path to the file to which genny will write.
	FileName string
	file     *os.File
}

// Close closes the file if it is created. Returns nil if no file is created.
func (lw *LazyFile) Close() error {
	if lw.file != nil {
		return lw.file.Close()
	}
	return nil
}

// Write writes to the specified file and creates the file first time it is called.
func (lw *LazyFile) Write(p []byte) (int, error) {
	if lw.file == nil {
		err := os.MkdirAll(path.Dir(lw.FileName), 0755)
		if err != nil {
			return 0, err
		}
		lw.file, err = os.Create(lw.FileName)
		if err != nil {
			return 0, err
		}
	}
	return lw.file.Write(p)
}