2014-11-16 20:13:20 +00:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
2014-10-21 07:10:19 +00:00
|
|
|
//
|
2015-03-07 20:36:35 +00:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 06:52:18 +00:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2014-10-21 07:10:19 +00:00
|
|
|
|
|
|
|
package osutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io"
|
2022-07-28 17:36:39 +00:00
|
|
|
|
|
|
|
"github.com/syncthing/syncthing/lib/build"
|
2014-10-21 07:10:19 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type ReplacingWriter struct {
|
|
|
|
Writer io.Writer
|
|
|
|
From byte
|
|
|
|
To []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w ReplacingWriter) Write(bs []byte) (int, error) {
|
|
|
|
var n, written int
|
|
|
|
var err error
|
|
|
|
|
|
|
|
newlineIdx := bytes.IndexByte(bs, w.From)
|
|
|
|
for newlineIdx >= 0 {
|
|
|
|
n, err = w.Writer.Write(bs[:newlineIdx])
|
|
|
|
written += n
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if len(w.To) > 0 {
|
|
|
|
n, err := w.Writer.Write(w.To)
|
|
|
|
if n == len(w.To) {
|
|
|
|
written++
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
bs = bs[newlineIdx+1:]
|
|
|
|
newlineIdx = bytes.IndexByte(bs, w.From)
|
|
|
|
}
|
|
|
|
|
|
|
|
n, err = w.Writer.Write(bs)
|
|
|
|
written += n
|
|
|
|
|
|
|
|
return written, err
|
|
|
|
}
|
2021-11-22 08:38:24 +00:00
|
|
|
|
|
|
|
// LineEndingsWriter returns a writer that writes platform-appropriate line
|
|
|
|
// endings. (This is a no-op on non-Windows platforms.)
|
|
|
|
func LineEndingsWriter(w io.Writer) io.Writer {
|
2022-07-28 17:36:39 +00:00
|
|
|
if !build.IsWindows {
|
2021-11-22 08:38:24 +00:00
|
|
|
return w
|
|
|
|
}
|
|
|
|
return &ReplacingWriter{
|
|
|
|
Writer: w,
|
|
|
|
From: '\n',
|
|
|
|
To: []byte{'\r', '\n'},
|
|
|
|
}
|
|
|
|
}
|