-2

I am trying to execute git commands through Go code. I need to convert *byte.buffer value string to int.

cmd := exec.Command("git", "cat-file", "-s", dir+":"filename)
var outBuf bytes.Buffer
var stderr = bytes.Buffer
cmd.Stdout = &out
cmd.Stferr = &stderr
err := cmd.Run()

filesize, _ := strconv.Atoi(out.String())
fmt.Println("filesize..", filesize) //return 0
fmt.Println("filesize..", out.String()) // returns 345

I want to convert out.String() value to string which is type *byte.buffer.

Does anyone know how to do it?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
sngo
  • 1

1 Answers1

3
filesize, _ := strconv.Atoi(out.String())

You are ignoring the error return. Don't do that.

If you print the returned error, you will see that git cat-file -s <path> produced the string "345\n" (or possibly "345\r\n"). That is, there's a newline (or CRLF) at the end of the number. That is prohibited:

filesize = 0, err = strconv.Atoi: parsing "345\n": invalid syntax

Remove the newline and strconv.Atoi will be fine with the value. Consider, e.g., applying strings.TrimSpace() to the string. (See Go Playground example).

torek
  • 448,244
  • 59
  • 642
  • 775