stampzilla-go icon indicating copy to clipboard operation
stampzilla-go copied to clipboard

fix progressbars for self-update and installs etc (fetching from http)

Open jonaz opened this issue 3 years ago • 1 comments

jonaz avatar Feb 12 '22 11:02 jonaz

Ive impelemented this somewhere else and then i did it like this:

........
........
	file, err := os.OpenFile(binPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) // #nosec
	if err != nil {
		return err
	}

	counter := &ProgressCounter{Total: float64(resp.ContentLength)}
	_, err = io.Copy(file, io.TeeReader(resp.Body, counter))
	if err != nil {
		renameErr := os.Rename(binPath+".backup", binPath)
		if renameErr != nil {
			return fmt.Errorf("Failed to restore backup: %s", err.Error())
		}
		return err
	}

	err = os.Remove(binPath + ".backup")
	if err != nil {
		return err
	}

	logrus.Infof("Update to version %s successful", version)
	return nil
}

type ProgressCounter struct {
	Total     float64
	Counter   float64
	LastPrint int64
}

func (wc *ProgressCounter) Write(p []byte) (int, error) {
	n := len(p)
	wc.Counter += float64(n)
	wc.PrintProgress()
	return n, nil
}

func (wc *ProgressCounter) PrintProgress() {
	val := int64(math.RoundToEven((wc.Counter / wc.Total) * 100.0))
	if val == wc.LastPrint {
		return
	}

	wc.LastPrint = val

	fmt.Printf("\r%s", strings.Repeat(" ", 35))
	fmt.Printf("\rDownloading... %d%% complete", val)

	if val == 100 {
		fmt.Println()
	}
}

jonaz avatar Mar 09 '22 10:03 jonaz