File: once_writer.go

package info (click to toggle)
lazygit 0.50.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,808 kB
  • sloc: sh: 128; makefile: 76
file content (31 lines) | stat: -rw-r--r-- 509 bytes parent folder | download | duplicates (3)
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
package utils

import (
	"io"
	"sync"
)

// This wraps a writer and ensures that before we actually write anything we call a given function first

type OnceWriter struct {
	writer io.Writer
	once   sync.Once
	f      func()
}

var _ io.Writer = &OnceWriter{}

func NewOnceWriter(writer io.Writer, f func()) *OnceWriter {
	return &OnceWriter{
		writer: writer,
		f:      f,
	}
}

func (self *OnceWriter) Write(p []byte) (n int, err error) {
	self.once.Do(func() {
		self.f()
	})

	return self.writer.Write(p)
}