Start work on a command to self update kitty-tool

This commit is contained in:
Kovid Goyal
2022-11-15 21:29:11 +05:30
parent 36dd5b2d00
commit d54fe3c16a
4 changed files with 289 additions and 16 deletions

View File

@@ -3,6 +3,7 @@
package utils
import (
"bytes"
"fmt"
"io"
"net/http"
@@ -32,27 +33,15 @@ func (self *write_counter) Write(p []byte) (int, error) {
return n, nil
}
func DownloadFile(destpath, url string, progress_callback ReportFunc) error {
func DownloadToWriter(url string, dest io.Writer, progress_callback ReportFunc) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
destpath, err = filepath.EvalSymlinks(destpath)
if err != nil {
return err
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("The server responded with the HTTP error %d (%s)", resp.StatusCode, resp.Status)
}
dest, err := os.CreateTemp(filepath.Dir(destpath), filepath.Base(destpath)+".partial-download.")
if err != nil {
return err
}
dest_removed := false
defer func() {
dest.Close()
if !dest_removed {
os.Remove(dest.Name())
}
}()
wc := write_counter{report: progress_callback}
cl, err := strconv.Atoi(resp.Header.Get("Content-Length"))
if err == nil {
@@ -62,7 +51,53 @@ func DownloadFile(destpath, url string, progress_callback ReportFunc) error {
if err != nil {
return err
}
return nil
}
func DownloadAsSlice(url string, progress_callback ReportFunc) (data []byte, err error) {
b := bytes.Buffer{}
b.Grow(4096)
err = DownloadToWriter(url, &b, progress_callback)
if err == nil {
return b.Bytes(), nil
}
return nil, err
}
func DownloadToFile(destpath, url string, progress_callback ReportFunc, temp_file_path_callback func(string)) error {
destpath, err := filepath.EvalSymlinks(destpath)
if err != nil {
return err
}
dest, err := os.CreateTemp(filepath.Dir(destpath), filepath.Base(destpath)+".partial-download.")
if err != nil {
return err
}
if temp_file_path_callback != nil {
temp_file_path_callback(dest.Name())
}
dest_removed := false
defer func() {
dest.Close()
if !dest_removed {
os.Remove(dest.Name())
}
}()
err = DownloadToWriter(url, dest, progress_callback)
if err != nil {
return err
}
dest.Close()
fi, err := os.Stat(destpath)
if err == nil {
err = os.Chmod(dest.Name(), fi.Mode().Perm())
if err != nil {
return err
}
}
if err != nil {
return err
}
err = os.Rename(dest.Name(), destpath)
if err != nil {
return err