From cc27626d016f8e13cfc86291ae9ddfc1a6e9d09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20=27Necoro=27=20Neumann?= Date: Sun, 23 Jan 2022 23:52:53 +0100 Subject: Factor out `encodedWriter` --- encoding.go | 10 ++++++++-- main.go | 2 +- template.go | 6 +----- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/encoding.go b/encoding.go index d77cd65..b7511c5 100644 --- a/encoding.go +++ b/encoding.go @@ -5,12 +5,13 @@ import ( "io" "github.com/gogs/chardet" + "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/ianaindex" ) -// getEncodedReader tries to determine the encoding of the content of `r`. +// encodedReader tries to determine the encoding of the content of `r`. // It returns a new reader that returns UTF-8 content. -func getEncodedReader(r io.Reader) (io.Reader, error) { +func encodedReader(r io.Reader) (io.Reader, error) { buf := make([]byte, 128) n, err := io.ReadFull(r, buf) @@ -38,3 +39,8 @@ func getEncodedReader(r io.Reader) (io.Reader, error) { return enc.NewDecoder().Reader(r), nil } + +// encodedWriter returns a wrapper around the passed in writer that encodes into the expected charset. +func encodedWriter(w io.Writer) io.Writer { + return charmap.ISO8859_1.NewEncoder().Writer(w) +} diff --git a/main.go b/main.go index e2da4cd..b671b15 100644 --- a/main.go +++ b/main.go @@ -86,7 +86,7 @@ func parseOphardtInput(fileName string) ([]participant, error) { return nil, fmt.Errorf("opening input file '%s': %w", fileName, err) } - encReader, err := getEncodedReader(f) + encReader, err := encodedReader(f) if err != nil { return nil, fmt.Errorf("cannot determine encoding of file '%s': %w", fileName, err) } diff --git a/template.go b/template.go index 67cd565..ce1127a 100644 --- a/template.go +++ b/template.go @@ -7,8 +7,6 @@ import ( "io/fs" "os" "path" - - "golang.org/x/text/encoding/charmap" ) const verbatimPath = "templates/verbatim" @@ -33,9 +31,7 @@ func writeVerbatimFile(outputDir string, entry fs.DirEntry) error { } defer output.Close() - encodedOutput := charmap.ISO8859_1.NewEncoder().Writer(output) - - if _, err = io.Copy(encodedOutput, input); err != nil { + if _, err = io.Copy(encodedWriter(output), input); err != nil { return fmt.Errorf("writing to '%s': %w", outName, err) } -- cgit v1.2.3