Skip to content

Commit

Permalink
cmd: copy file if minify fails, fixes #560
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed Mar 14, 2023
1 parent d1e3c2f commit 0956551
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 45 deletions.
30 changes: 0 additions & 30 deletions cmd/minify/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,6 @@ import (
"io"
)

type countingReader struct {
io.Reader
N uint64
}

func newCountingReader(r io.Reader) *countingReader {
return &countingReader{r, 0}
}

func (r *countingReader) Read(p []byte) (int, error) {
n, err := r.Reader.Read(p)
r.N += uint64(n)
return n, err
}

type countingWriter struct {
io.Writer
N uint64
}

func newCountingWriter(w io.Writer) *countingWriter {
return &countingWriter{w, 0}
}

func (w *countingWriter) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
w.N += uint64(n)
return n, err
}

type eofReader struct{}

func (r eofReader) Read(p []byte) (int, error) {
Expand Down
32 changes: 17 additions & 15 deletions cmd/minify/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -788,38 +788,40 @@ func minify(t Task) bool {
return true
}

r := newCountingReader(fr)
w := newCountingWriter(fw)
bw := bufio.NewWriter(w)
b, err := ioutil.ReadAll(fr)
if err != nil {
fr.Close()
fw.Close()
Error.Println("cannot minify "+srcName+":", err)
return false
}
w := bytes.NewBuffer(make([]byte, 0, len(b)))

success := true
startTime := time.Now()
if err = m.Minify(fileMimetype, bw, r); err != nil {
bw.Flush()
if t.dst == "" && 0 < w.N {
fmt.Fprintf(os.Stdout, "\n\n")
}
if err = m.Minify(fileMimetype, w, bytes.NewReader(b)); err != nil {
w = bytes.NewBuffer(b) // copy original
Error.Println("cannot minify "+srcName+":", err)
success = false
} else {
bw.Flush()
}

rLen, wLen := len(b), w.Len()
_, err = io.Copy(fw, w)
fr.Close()
fw.Close()

if verbose {
dur := time.Since(startTime)
speed := "Inf MB"
if 0 < dur {
speed = humanize.Bytes(uint64(float64(r.N) / dur.Seconds()))
speed = humanize.Bytes(uint64(float64(rLen) / dur.Seconds()))
}
ratio := 1.0
if 0 < r.N {
ratio = float64(w.N) / float64(r.N)
if 0 < rLen {
ratio = float64(wLen) / float64(rLen)
}

stats := fmt.Sprintf("(%9v, %6v, %6v, %5.1f%%, %6v/s)", dur, humanize.Bytes(r.N), humanize.Bytes(w.N), ratio*100, speed)
stats := fmt.Sprintf("(%9v, %6v, %6v, %5.1f%%, %6v/s)", dur, humanize.Bytes(uint64(rLen)), humanize.Bytes(uint64(wLen)), ratio*100, speed)
if srcName != dstName {
Info.Println(stats, "-", srcName, "to", dstName)
} else {
Expand Down

0 comments on commit 0956551

Please sign in to comment.