Skip to content

Instantly share code, notes, and snippets.

@squaremo
Created May 23, 2019 15:05
Show Gist options
  • Save squaremo/68f75a34768195e79333eb338b329f8d to your computer and use it in GitHub Desktop.
Save squaremo/68f75a34768195e79333eb338b329f8d to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"sync"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := execGitCmd(ctx, os.Stdout, []string{"notes", "--ref", "flux", "list"}); err != nil {
println(err.Error())
return
}
println("OK!")
}
type threadSafeBuffer struct {
bytes.Buffer
sync.Mutex
}
func (b *threadSafeBuffer) Write(p []byte) (n int, err error) {
b.Lock()
defer b.Unlock()
return b.Buffer.Write(p)
}
func (b *threadSafeBuffer) ReadFrom(r io.Reader) (n int64, err error) {
b.Lock()
defer b.Unlock()
return b.Buffer.ReadFrom(r)
}
// execGitCmd runs a `git` command with the supplied arguments.
func execGitCmd(ctx context.Context, out io.Writer, args []string) error {
c := exec.CommandContext(ctx, "git", args...)
stdOutAndStdErr := &threadSafeBuffer{}
c.Stdout = stdOutAndStdErr
c.Stderr = stdOutAndStdErr
if out != nil {
c.Stdout = io.MultiWriter(c.Stdout, out)
}
err := c.Run()
if err != nil {
if len(stdOutAndStdErr.Bytes()) > 0 {
err = fmt.Errorf(stdOutAndStdErr.String())
}
}
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("running git command: %s %v: %s", "git", args, ctx.Err().Error())
} else if ctx.Err() == context.Canceled {
return fmt.Errorf("context was unexpectedly cancelled when running git command: %s %v", "git", args)
}
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment