Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jonaz opened this issue Feb 12, 2022 · 1 comment
Open
Assignees

Comments

@jonaz
Copy link
Member

jonaz commented Feb 12, 2022

No description provided.

@jonaz jonaz self-assigned this Feb 12, 2022
@jonaz
Copy link
Member Author

jonaz commented Mar 9, 2022

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()
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant