Add a tracer that honors GIT_TRACE

This commit is contained in:
rubyist 2014-10-03 10:56:58 -04:00
parent 494a547831
commit d669f77a39
3 changed files with 60 additions and 0 deletions

@ -5,6 +5,7 @@ import (
"github.com/github/git-media/gitmedia"
"github.com/github/git-media/gitmediaclient"
"github.com/github/git-media/pointer"
"github.com/github/git-media/trace"
"github.com/spf13/cobra"
"io/ioutil"
"os"
@ -122,6 +123,7 @@ func pushCommand(cmd *cobra.Command, args []string) {
// git media endpoint already has a git media object for that oid. The object will
// not be pushed again.
func pushAsset(oid, filename string, index, totalFiles int) *gitmedia.WrappedError {
trace.Trace("push_asset: %s %s %d/%d", oid, filename, index, totalFiles)
path, err := gitmedia.LocalMediaPath(oid)
if err != nil {
return gitmedia.Errorf(err, "Error uploading file %s (%s)", filename, oid)

@ -6,6 +6,7 @@ import (
"bytes"
"errors"
"fmt"
"github.com/github/git-media/trace"
"io"
"os/exec"
"regexp"
@ -149,6 +150,7 @@ func (c *gitConfig) Version() (string, error) {
// simpleExec is a small wrapper around os/exec.Command. If the passed stdin
// is not nil it will be hooked up to the subprocess stdin.
func simpleExec(stdin io.Reader, name string, arg ...string) (string, error) {
trace.Trace("run_command: '%s' %s", name, strings.Join(arg, " "))
cmd := exec.Command(name, arg...)
if stdin != nil {
cmd.Stdin = stdin

56
trace/trace.go Normal file

@ -0,0 +1,56 @@
package trace
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
var tracerOut io.Writer
// Trace prints tracing output following the semantics of the GIT_TRACE environment
// variable. If GIT_TRACE is set to "1", "2", or "true", messages will be printed
// on stderr. If the variable is set to an integer value greater than 1 and lower than
// 10 it will be interpreted as an open file descriptor and will try to write messages
// into this file descriptor. Alternatively, if this variable is set to an absolute
// path, messages will be logged to that file.
func Trace(format string, args ...interface{}) {
if tracerOut != nil {
fmt.Fprintf(tracerOut, "trace media: "+format+"\n", args...)
}
}
func init() {
trace := os.Getenv("GIT_TRACE")
if trace == "" || strings.ToLower(trace) == "false" {
return
}
fd, err := strconv.Atoi(trace)
if err != nil {
if filepath.IsAbs(trace) {
tracerOut, err = os.OpenFile(trace, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not open '%s' for tracing: %s\nDefaulting to tracing on stderr...\n", trace, err)
tracerOut = os.Stderr
}
} else if strings.ToLower(trace) == "true" {
tracerOut = os.Stderr
} else {
return
}
} else {
switch fd {
case 0:
return
case 1, 2:
tracerOut = os.Stderr
default:
tracerOut = os.NewFile(uintptr(fd), "trace")
}
}
}