]> Sergey Matveev's repositories - mmfileget.git/commitdiff
Do not overwrite existing file master
authorSergey Matveev <stargrave@stargrave.org>
Mon, 6 Mar 2023 11:41:57 +0000 (14:41 +0300)
committerSergey Matveev <stargrave@stargrave.org>
Mon, 6 Mar 2023 11:41:57 +0000 (14:41 +0300)
main.go

diff --git a/main.go b/main.go
index a31bb51f758acc5abd77f058c0ee46ed9d8ca35c..a54a14ba6fd54698b7e46c2a720e972bd9c977ee 100644 (file)
--- a/main.go
+++ b/main.go
@@ -5,19 +5,21 @@ import (
        "io/ioutil"
        "log"
        "os"
+       "strconv"
        "strings"
 
        "github.com/mattermost/mattermost-server/v6/model"
 )
 
 func main() {
+       log.SetFlags(0)
        url := strings.TrimPrefix(os.Args[1], "-") // -?https://MACHINE/api/v4/files/FILE
        s := strings.Split(url, "/")
        machine, fileId := s[2], s[6]
 
        login, password := findInNetrc(machine)
        if login == "" || password == "" {
-               fmt.Fprintln(os.Stderr, "No credentials found for:", machine)
+               log.Println("No credentials found for:", machine)
                os.Exit(1)
        }
 
@@ -31,24 +33,35 @@ func main() {
                log.Fatalln(err)
        }
        if info == nil {
-               fmt.Fprintln(os.Stderr, resp)
+               fmt.Println(resp)
                os.Exit(1)
        }
        filename := info.Name
        if len(os.Args) > 2 {
                filename = os.Args[2]
        } else {
-               fmt.Fprintln(os.Stderr, "Name:", info.Name)
-               fmt.Fprintln(os.Stderr, "Type:", info.MimeType)
-               fmt.Fprintln(os.Stderr, "Size:", info.Size)
-               fmt.Fprintln(os.Stderr, "Download? Ctrl-D/C")
+               log.Println("Name:", info.Name)
+               log.Println("Type:", info.MimeType)
+               log.Println("Size:", info.Size)
+               log.Println("Download? Ctrl-D/C")
                os.Stdin.Read(make([]byte, 1))
        }
        data, _, err := client.GetFile(fileId)
        if err != nil {
                log.Fatalln(err)
        }
-       if err := ioutil.WriteFile(filename, data, os.FileMode(0666)); err != nil {
-               panic(err)
+
+       dstCtr := 0
+       dst := filename
+       for {
+               if _, err = os.Stat(dst); err != nil {
+                       break
+               }
+               dst = filename + strconv.Itoa(dstCtr)
+               dstCtr++
+       }
+       if err := ioutil.WriteFile(dst, data, os.FileMode(0666)); err != nil {
+               log.Fatalln(err)
        }
+       fmt.Println(dst)
 }