mirror of https://github.com/databricks/cli.git
Transpose solution
This commit is contained in:
parent
d3e9701f27
commit
5913f03b15
|
@ -70,40 +70,24 @@ func WithStdoutWriter(dst io.Writer) execOption {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// safeMultiWriter is a thread-safe io.Writer that writes to multiple writers.
|
// safeWriter is a writer that is safe to use concurrently.
|
||||||
// It is functionality equivalent to io.MultiWriter, but is safe for concurrent use.
|
// It serializes writes to the underlying writer.
|
||||||
type safeMultiWriter struct {
|
type safeWriter struct {
|
||||||
writers []io.Writer
|
w io.Writer
|
||||||
mu sync.Mutex
|
m sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// newSafeMultiWriter creates a new safeMultiWriter that writes to the provided writers.
|
func (s *safeWriter) Write(p []byte) (n int, err error) {
|
||||||
func newSafeMultiWriter(writers ...io.Writer) *safeMultiWriter {
|
s.m.Lock()
|
||||||
return &safeMultiWriter{writers: writers}
|
defer s.m.Unlock()
|
||||||
}
|
return s.w.Write(p)
|
||||||
|
|
||||||
// Write implements the io.Writer interface for safeMultiWriter.
|
|
||||||
func (t *safeMultiWriter) Write(p []byte) (n int, err error) {
|
|
||||||
t.mu.Lock()
|
|
||||||
defer t.mu.Unlock()
|
|
||||||
|
|
||||||
for _, w := range t.writers {
|
|
||||||
n, err = w.Write(p)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if n != len(p) {
|
|
||||||
err = io.ErrShortWrite
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return len(p), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithCombinedOutput(buf *bytes.Buffer) execOption {
|
func WithCombinedOutput(buf *bytes.Buffer) execOption {
|
||||||
|
sw := &safeWriter{w: buf}
|
||||||
return func(_ context.Context, c *exec.Cmd) error {
|
return func(_ context.Context, c *exec.Cmd) error {
|
||||||
c.Stdout = newSafeMultiWriter(buf, c.Stdout)
|
c.Stdout = io.MultiWriter(sw, c.Stdout)
|
||||||
c.Stderr = newSafeMultiWriter(buf, c.Stderr)
|
c.Stderr = io.MultiWriter(sw, c.Stderr)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue