Moved repeated logic into function

This commit is contained in:
sloumdrone 2019-11-02 22:14:10 -07:00
parent b998fa9e7c
commit 3a96792cf3
1 changed files with 26 additions and 20 deletions

View File

@ -528,18 +528,12 @@ func (c *client) saveFile(u Url, name string) {
return
}
savePath := filepath.Join(c.Options["savelocation"], name)
suffix := 1
_, fileErr := os.Stat(savePath)
for fileErr == nil {
fn := fmt.Sprintf("%s.%d", name, suffix)
savePath = filepath.Join(c.Options["savelocation"], fn)
_, fileErr = os.Stat(savePath)
suffix++
}
// We are ignoring the error here since WriteFile will
// generate the same error, and will handle the messaging
savePath, _ := findAvailableFileName(c.Options["savelocation"], name)
err = ioutil.WriteFile(savePath, file, 0644)
if err != nil {
c.SetMessage("Error writing file: "+err.Error(), true)
c.SetMessage("Error writing file: "+err.Error()+savePath, true)
c.DrawMessage()
return
}
@ -553,18 +547,12 @@ func (c *client) saveFileFromData(d, name string) {
c.SetMessage(fmt.Sprintf("Saving %s ...", name), false)
c.DrawMessage()
savePath := filepath.Join(c.Options["savelocation"], name)
suffix := 1
_, fileErr := os.Stat(savePath)
for fileErr == nil {
fn := fmt.Sprintf("%s.%d", name, suffix)
savePath = filepath.Join(c.Options["savelocation"], fn)
_, fileErr = os.Stat(savePath)
suffix++
}
// We are ignoring the error here since WriteFile will
// generate the same error, and will handle the messaging
savePath, _ := findAvailableFileName(c.Options["savelocation"], name)
err := ioutil.WriteFile(savePath, data, 0644)
if err != nil {
c.SetMessage("Error writing file: "+err.Error(), true)
c.SetMessage("Error writing file: "+err.Error()+savePath, true)
c.DrawMessage()
return
}
@ -1081,3 +1069,21 @@ func MakeClient(name string) *client {
c := client{0, 0, defaultOptions, "", false, MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar(), gemini.MakeTofuDigest()}
return &c
}
func findAvailableFileName(fpath, fname string) (string, error) {
savePath := filepath.Join(fpath, fname)
_, fileErr := os.Stat(savePath)
for suffix := 1; fileErr == nil; suffix++ {
fn := fmt.Sprintf("%s.%d", fname, suffix)
savePath = filepath.Join(fpath, fn)
_, fileErr = os.Stat(savePath)
if !os.IsNotExist(fileErr) && fileErr != nil {
return savePath, fileErr
}
}
return savePath, nil
}