remove the old logging

This commit is contained in:
Rick Olson 2014-06-05 12:48:23 -06:00
parent f83d26fa39
commit 92cf6ea31a
15 changed files with 88 additions and 185 deletions

@ -12,7 +12,7 @@ type CleanCommand struct {
} }
func (c *CleanCommand) Run() { func (c *CleanCommand) Run() {
gitmedia.InstallHooks(false) gitmedia.InstallHooks()
var filename string var filename string
if len(c.Args) > 1 { if len(c.Args) > 1 {
@ -23,7 +23,7 @@ func (c *CleanCommand) Run() {
cleaned, err := filters.Clean(os.Stdin) cleaned, err := filters.Clean(os.Stdin)
if err != nil { if err != nil {
gitmedia.Panic(err, "Error cleaning asset") Panic(err, "Error cleaning asset")
} }
defer cleaned.Close() defer cleaned.Close()
@ -36,10 +36,12 @@ func (c *CleanCommand) Run() {
Debug("%s exists", mediafile) Debug("%s exists", mediafile)
} else { } else {
if err := os.Rename(tmpfile, mediafile); err != nil { if err := os.Rename(tmpfile, mediafile); err != nil {
gitmedia.Panic(err, "Unable to move %s to %s\n", tmpfile, mediafile) Panic(err, "Unable to move %s to %s\n", tmpfile, mediafile)
} }
gitmedia.QueueUpload(cleaned.Sha, filename) if err = gitmedia.QueueUpload(cleaned.Sha, filename); err != nil {
Panic(err, "Unable to add %s to queue", cleaned.Sha)
}
Debug("Writing %s", mediafile) Debug("Writing %s", mediafile)
} }

@ -16,10 +16,7 @@ func (c *InitCommand) Run() {
switch sub { switch sub {
case "hooks": case "hooks":
if err := c.hookInit(); err != nil { c.hookInit()
Print("%s", err)
return
}
default: default:
c.runInit() c.runInit()
} }
@ -35,11 +32,15 @@ func (c *InitCommand) runInit() {
} }
func (c *InitCommand) globalInit() { func (c *InitCommand) globalInit() {
gitmedia.InstallFilters() if err := gitmedia.InstallFilters(); err != nil {
Error(err.Error())
}
} }
func (c *InitCommand) hookInit() error { func (c *InitCommand) hookInit() {
return gitmedia.InstallHooks(true) if err := gitmedia.InstallHooks(); err != nil {
Error(err.Error())
}
} }
func init() { func init() {

@ -69,7 +69,7 @@ func (c *LogsCommand) showLog(name string) {
func (c *LogsCommand) clear() { func (c *LogsCommand) clear() {
err := os.RemoveAll(gitmedia.LocalLogDir) err := os.RemoveAll(gitmedia.LocalLogDir)
if err != nil { if err != nil {
gitmedia.Panic(err, "Error clearing %s", gitmedia.LocalLogDir) Panic(err, "Error clearing %s", gitmedia.LocalLogDir)
} }
fmt.Println("Cleared", gitmedia.LocalLogDir) fmt.Println("Cleared", gitmedia.LocalLogDir)
@ -78,7 +78,7 @@ func (c *LogsCommand) clear() {
func (c *LogsCommand) boomtown() { func (c *LogsCommand) boomtown() {
Debug("Debug message") Debug("Debug message")
err := errors.New("Error!") err := errors.New("Error!")
gitmedia.Panic(err, "Welcome to Boomtown") Panic(err, "Welcome to Boomtown")
Debug("Never seen") Debug("Never seen")
} }

@ -15,7 +15,7 @@ type PathCommand struct {
} }
func (c *PathCommand) Run() { func (c *PathCommand) Run() {
gitmedia.InstallHooks(false) gitmedia.InstallHooks()
var sub string var sub string
if len(c.SubCommands) > 0 { if len(c.SubCommands) > 0 {

@ -11,7 +11,11 @@ type PushCommand struct {
} }
func (c *PushCommand) Run() { func (c *PushCommand) Run() {
q := gitmedia.UploadQueue() q, err := gitmedia.UploadQueue()
if err != nil {
Panic(err, "Error setting up the queue")
}
q.Walk(func(id string, body []byte) error { q.Walk(func(id string, body []byte) error {
fileInfo := string(body) fileInfo := string(body)
parts := strings.Split(fileInfo, ":") parts := strings.Split(fileInfo, ":")
@ -26,16 +30,16 @@ func (c *PushCommand) Run() {
err := gitmediaclient.Options(path) err := gitmediaclient.Options(path)
if err != nil { if err != nil {
gitmedia.Panic(err, "error uploading file %s", filename) Panic(err, "error uploading file %s", filename)
} }
err = gitmediaclient.Put(path, filename) err = gitmediaclient.Put(path, filename)
if err != nil { if err != nil {
gitmedia.Panic(err, "error uploading file %s", sha) Panic(err, "error uploading file %s", sha)
} }
if err := q.Del(id); err != nil { if err := q.Del(id); err != nil {
gitmedia.Panic(err, "error removing %s from queue", sha) Panic(err, "error removing %s from queue", sha)
} }
return nil return nil
}) })

@ -30,7 +30,7 @@ func (c *QueuesCommand) Run() {
}) })
if err != nil { if err != nil {
gitmedia.Panic(err, "Error walking queues") Panic(err, "Error walking queues")
} }
} }

@ -12,17 +12,17 @@ type SmudgeCommand struct {
} }
func (c *SmudgeCommand) Run() { func (c *SmudgeCommand) Run() {
gitmedia.InstallHooks(false) gitmedia.InstallHooks()
sha, err := metafile.Decode(os.Stdin) sha, err := metafile.Decode(os.Stdin)
if err != nil { if err != nil {
gitmedia.Panic(err, "Error reading git-media meta data from stdin:") Panic(err, "Error reading git-media meta data from stdin:")
} }
err = filters.Smudge(os.Stdout, sha) err = filters.Smudge(os.Stdout, sha)
if err != nil { if err != nil {
smudgerr := err.(*filters.SmudgeError) smudgerr := err.(*filters.SmudgeError)
gitmedia.Panic(err, "Error reading file from local media dir: %s", smudgerr.Filename) Panic(err, "Error reading file from local media dir: %s", smudgerr.Filename)
} }
} }

@ -106,7 +106,7 @@ func NewCommand(name, subname string) *Command {
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
setupDebugging(fs) setupDebugging(fs)
fs.SetOutput(gitmedia.ErrorWriter) fs.SetOutput(ErrorWriter)
return &Command{name, subname, fs, args, args} return &Command{name, subname, fs, args, args}
} }
@ -139,7 +139,7 @@ type Command struct {
} }
func (c *Command) Usage() { func (c *Command) Usage() {
gitmedia.Print("usage: %s %s", c.Name, c.SubCommand) Print("usage: %s %s", c.Name, c.SubCommand)
c.FlagSet.PrintDefaults() c.FlagSet.PrintDefaults()
} }
@ -156,7 +156,7 @@ func registerCommand(name string, cmdcb func(*Command) RunnableCommand) {
} }
func missingCommand(cmd *Command, subname string) { func missingCommand(cmd *Command, subname string) {
gitmedia.Error("%s: '%s' is not a %s command. See %s help.", Error("%s: '%s' is not a %s command. See %s help.",
cmd.Name, subname, cmd.Name, cmd.Name) cmd.Name, subname, cmd.Name, cmd.Name)
} }

@ -149,7 +149,7 @@ func (c *TestCommand) Run() {
cmd := exec.Command(Bin, c.Args...) cmd := exec.Command(Bin, c.Args...)
cmd.Stdin = c.Input cmd.Stdin = c.Input
outputBytes, err := cmd.Output() outputBytes, err := cmd.CombinedOutput()
c.e(err) c.e(err)
if len(c.Output) > 0 { if len(c.Output) > 0 {

@ -17,9 +17,7 @@ func TestInit(t *testing.T) {
repo.AddPath(repo.Path, "subdir") repo.AddPath(repo.Path, "subdir")
cmd := repo.Command("init") cmd := repo.Command("init")
cmd.Output = "Installing clean filter\n" + cmd.Output = "git media initialized"
"Installing smudge filter\n" +
"git media initialized"
prePushHookFile := filepath.Join(repo.Path, ".git", "hooks", "pre-push") prePushHookFile := filepath.Join(repo.Path, ".git", "hooks", "pre-push")
@ -44,11 +42,7 @@ func TestInit(t *testing.T) {
}) })
cmd = repo.Command("init") cmd = repo.Command("init")
cmd.Output = "Installing clean filter\n" + cmd.Output = "Hook already exists: pre-push\ngit media initialized"
"Installing smudge filter\n" +
"Hook already exists: " +
filepath.Join(repo.Path, ".git", "hooks", "pre-push") +
"\ngit media initialized"
customHook := []byte("echo 'yo'") customHook := []byte("echo 'yo'")
cmd.Before(func() { cmd.Before(func() {

@ -91,12 +91,12 @@ func (c *Configuration) loadGitConfig() {
var output string var output string
listOutput, err := gitconfig.List() listOutput, err := gitconfig.List()
if err != nil { if err != nil {
Panic(err, listOutput) panic(fmt.Errorf("Error listing git config: %s", err))
} }
fileOutput, err := gitconfig.ListFromFile() fileOutput, err := gitconfig.ListFromFile()
if err != nil { if err != nil {
Panic(err, fileOutput) panic(fmt.Errorf("Error listing git config from file: %s", err))
} }
output = listOutput + "\n" + fileOutput output = listOutput + "\n" + fileOutput

@ -26,7 +26,7 @@ func TempFile() (*os.File, error) {
func LocalMediaPath(sha string) string { func LocalMediaPath(sha string) string {
path := filepath.Join(LocalMediaDir, sha[0:2], sha[2:4]) path := filepath.Join(LocalMediaDir, sha[0:2], sha[2:4])
if err := os.MkdirAll(path, 0744); err != nil { if err := os.MkdirAll(path, 0744); err != nil {
Panic(err, "Error trying to create local media directory: %s", path) panic(fmt.Errorf("Error trying to create local media directory in '%s': %s", path, err))
} }
return filepath.Join(path, sha) return filepath.Join(path, sha)
@ -63,7 +63,7 @@ func init() {
queueDir = setupQueueDir() queueDir = setupQueueDir()
if err := os.MkdirAll(TempDir, 0744); err != nil { if err := os.MkdirAll(TempDir, 0744); err != nil {
Panic(err, "Error trying to create temp directory: %s", TempDir) panic(fmt.Errorf("Error trying to create temp directory in '%s': %s", TempDir, err))
} }
} }
} }
@ -71,7 +71,7 @@ func init() {
func resolveGitDir() (string, string, error) { func resolveGitDir() (string, string, error) {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
Panic(err, "Error reading working directory") panic(fmt.Errorf("Error reading working directory: %s", err))
} }
return recursiveResolveGitDir(wd) return recursiveResolveGitDir(wd)

@ -1,121 +0,0 @@
package gitmedia
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
)
var (
Debugging = false
ErrorBuffer = &bytes.Buffer{}
ErrorWriter = io.MultiWriter(os.Stderr, ErrorBuffer)
OutputWriter = io.MultiWriter(os.Stdout, ErrorBuffer)
)
// Error prints a formatted message to Stderr. It also gets printed to the
// panic log if one is created for this command.
func Error(format string, args ...interface{}) {
line := fmt.Sprintf(format, args...)
fmt.Fprintln(ErrorWriter, line)
}
// Print prints a formatted message to Stdout. It also gets printed to the
// panic log if one is created for this command.
func Print(format string, args ...interface{}) {
line := fmt.Sprintf(format, args...)
fmt.Fprintln(OutputWriter, line)
}
// Exit prints a formatted message and exits.
func Exit(format string, args ...interface{}) {
Error(format, args...)
os.Exit(2)
}
// Panic prints a formatted message, and writes a stack trace for the error to
// a log file before exiting.
func Panic(err error, format string, args ...interface{}) {
Error(format, args...)
file := handlePanic(err)
if len(file) > 0 {
fmt.Fprintf(os.Stderr, "\nErrors logged to %s.\nUse `git media logs last` to view the log.\n", file)
}
os.Exit(2)
}
// Debug prints a formatted message if debugging is enabled. The formatted
// message also shows up in the panic log, if created.
func Debug(format string, args ...interface{}) {
if !Debugging {
return
}
log.Printf(format, args...)
}
func handlePanic(err error) string {
if err == nil {
return ""
}
Debug(err.Error())
logFile, logErr := logPanic(err)
if logErr != nil {
fmt.Fprintf(os.Stderr, "Unable to log panic to %s\n", LocalLogDir)
logEnv(os.Stderr)
panic(logErr)
}
return logFile
}
func logEnv(w io.Writer) {
for _, env := range Environ() {
fmt.Fprintln(w, env)
}
}
func logPanic(loggedError error) (string, error) {
if err := os.MkdirAll(LocalLogDir, 0744); err != nil {
return "", err
}
now := time.Now()
name := now.Format("2006-01-02T15:04:05.999999999")
full := filepath.Join(LocalLogDir, name+".log")
file, err := os.Create(full)
if err != nil {
return "", err
}
defer file.Close()
fmt.Fprintf(file, "> %s", filepath.Base(os.Args[0]))
if len(os.Args) > 0 {
fmt.Fprintf(file, " %s", strings.Join(os.Args[1:], " "))
}
fmt.Fprint(file, "\n")
logEnv(file)
fmt.Fprint(file, "\n")
file.Write(ErrorBuffer.Bytes())
fmt.Fprint(file, "\n")
fmt.Fprintln(file, loggedError.Error())
file.Write(debug.Stack())
return full, nil
}
func init() {
log.SetOutput(ErrorWriter)
}

@ -11,48 +11,63 @@ import (
) )
var ( var (
valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media") valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
prePushHook = []byte("#!/bin/sh\ngit media push\n") prePushHook = []byte("#!/bin/sh\ngit media push\n")
NotInARepositoryError = errors.New("Not in a repository")
) )
func InstallHooks(verbose bool) error { type HookExists struct {
Name string
Path string
}
func (e *HookExists) Error() string {
return fmt.Sprintf("Hook already exists: %s", e.Name)
}
func InstallHooks() error {
if !InRepo() { if !InRepo() {
return errors.New("Not in a repository") return NotInARepositoryError
} }
hookPath := filepath.Join(LocalGitDir, "hooks", "pre-push") hookPath := filepath.Join(LocalGitDir, "hooks", "pre-push")
if _, err := os.Stat(hookPath); err == nil { if _, err := os.Stat(hookPath); err == nil {
if verbose { return &HookExists{"pre-push", hookPath}
Print("Hook already exists: %s", hookPath)
}
} else { } else {
ioutil.WriteFile(hookPath, prePushHook, 0755) return ioutil.WriteFile(hookPath, prePushHook, 0755)
} }
return nil return nil
} }
func InstallFilters() { func InstallFilters() error {
setFilter("clean") var err error
setFilter("smudge") err = setFilter("clean")
requireFilters() if err == nil {
err = setFilter("smudge")
}
if err == nil {
err = requireFilters()
}
return err
} }
func setFilter(filterName string) { func setFilter(filterName string) error {
key := fmt.Sprintf("filter.media.%s", filterName) key := fmt.Sprintf("filter.media.%s", filterName)
value := fmt.Sprintf("git media %s %%f", filterName) value := fmt.Sprintf("git media %s %%f", filterName)
existing := gitconfig.Find(key) existing := gitconfig.Find(key)
if shouldReset(existing) { if shouldReset(existing) {
Print("Installing %s filter", filterName)
gitconfig.UnsetGlobal(key) gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, value) gitconfig.SetGlobal(key, value)
} else if existing != value { } else if existing != value {
Print("The %s filter should be \"%s\" but is \"%s\"", filterName, value, existing) return fmt.Errorf("The %s filter should be \"%s\" but is \"%s\"", filterName, value, existing)
} }
return nil
} }
func requireFilters() { func requireFilters() error {
key := "filter.media.required" key := "filter.media.required"
value := "true" value := "true"
@ -61,8 +76,10 @@ func requireFilters() {
gitconfig.UnsetGlobal(key) gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, value) gitconfig.SetGlobal(key, value)
} else if existing != value { } else if existing != value {
Print("Media filters should be required but are not.") return errors.New("Media filters should be required but are not.")
} }
return nil
} }
func shouldReset(value string) bool { func shouldReset(value string) bool {

@ -5,23 +5,29 @@ import (
"path/filepath" "path/filepath"
) )
func QueueUpload(sha, filename string) { func QueueUpload(sha, filename string) error {
fileBody := sha fileBody := sha
if filename != "" { if filename != "" {
fileBody += ":" + filename fileBody += ":" + filename
} }
_, err := UploadQueue().AddString(fileBody) q, err := UploadQueue()
if err != nil { if err != nil {
Panic(err, "Unable to add %s to queue", sha) return err
} }
_, err = q.AddString(fileBody)
return err
} }
func WalkQueues(cb func(name string, queue *queuedir.Queue) error) error { func WalkQueues(cb func(name string, queue *queuedir.Queue) error) error {
var err error var err error
for name, queuefunc := range queues { for name, queuefunc := range queues {
err = cb(name, queuefunc()) q, err := queuefunc()
if err == nil {
err = cb(name, q)
}
if err != nil { if err != nil {
return err return err
} }
@ -29,16 +35,16 @@ func WalkQueues(cb func(name string, queue *queuedir.Queue) error) error {
return err return err
} }
func UploadQueue() *queuedir.Queue { func UploadQueue() (*queuedir.Queue, error) {
if uploadQueue == nil { if uploadQueue == nil {
q, err := queueDir.Queue("upload") q, err := queueDir.Queue("upload")
if err != nil { if err != nil {
Panic(err, "Error setting up queue") return nil, err
} }
uploadQueue = q uploadQueue = q
} }
return uploadQueue return uploadQueue, nil
} }
func setupQueueDir() *queuedir.QueueDir { func setupQueueDir() *queuedir.QueueDir {
@ -46,7 +52,7 @@ func setupQueueDir() *queuedir.QueueDir {
} }
var ( var (
queues = map[string]func() *queuedir.Queue{ queues = map[string]func() (*queuedir.Queue, error){
"upload": UploadQueue, "upload": UploadQueue,
} }
queueDir *queuedir.QueueDir queueDir *queuedir.QueueDir