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() {
gitmedia.InstallHooks(false)
gitmedia.InstallHooks()
var filename string
if len(c.Args) > 1 {
@ -23,7 +23,7 @@ func (c *CleanCommand) Run() {
cleaned, err := filters.Clean(os.Stdin)
if err != nil {
gitmedia.Panic(err, "Error cleaning asset")
Panic(err, "Error cleaning asset")
}
defer cleaned.Close()
@ -36,10 +36,12 @@ func (c *CleanCommand) Run() {
Debug("%s exists", mediafile)
} else {
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)
}

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

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

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

@ -11,7 +11,11 @@ type PushCommand struct {
}
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 {
fileInfo := string(body)
parts := strings.Split(fileInfo, ":")
@ -26,16 +30,16 @@ func (c *PushCommand) Run() {
err := gitmediaclient.Options(path)
if err != nil {
gitmedia.Panic(err, "error uploading file %s", filename)
Panic(err, "error uploading file %s", filename)
}
err = gitmediaclient.Put(path, filename)
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 {
gitmedia.Panic(err, "error removing %s from queue", sha)
Panic(err, "error removing %s from queue", sha)
}
return nil
})

@ -30,7 +30,7 @@ func (c *QueuesCommand) Run() {
})
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() {
gitmedia.InstallHooks(false)
gitmedia.InstallHooks()
sha, err := metafile.Decode(os.Stdin)
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)
if err != nil {
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)
setupDebugging(fs)
fs.SetOutput(gitmedia.ErrorWriter)
fs.SetOutput(ErrorWriter)
return &Command{name, subname, fs, args, args}
}
@ -139,7 +139,7 @@ type Command struct {
}
func (c *Command) Usage() {
gitmedia.Print("usage: %s %s", c.Name, c.SubCommand)
Print("usage: %s %s", c.Name, c.SubCommand)
c.FlagSet.PrintDefaults()
}
@ -156,7 +156,7 @@ func registerCommand(name string, cmdcb func(*Command) RunnableCommand) {
}
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)
}

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

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

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

@ -26,7 +26,7 @@ func TempFile() (*os.File, error) {
func LocalMediaPath(sha string) string {
path := filepath.Join(LocalMediaDir, sha[0:2], sha[2:4])
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)
@ -63,7 +63,7 @@ func init() {
queueDir = setupQueueDir()
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) {
wd, err := os.Getwd()
if err != nil {
Panic(err, "Error reading working directory")
panic(fmt.Errorf("Error reading working directory: %s", err))
}
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 (
valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
prePushHook = []byte("#!/bin/sh\ngit media push\n")
valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
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() {
return errors.New("Not in a repository")
return NotInARepositoryError
}
hookPath := filepath.Join(LocalGitDir, "hooks", "pre-push")
if _, err := os.Stat(hookPath); err == nil {
if verbose {
Print("Hook already exists: %s", hookPath)
}
return &HookExists{"pre-push", hookPath}
} else {
ioutil.WriteFile(hookPath, prePushHook, 0755)
return ioutil.WriteFile(hookPath, prePushHook, 0755)
}
return nil
}
func InstallFilters() {
setFilter("clean")
setFilter("smudge")
requireFilters()
func InstallFilters() error {
var err error
err = setFilter("clean")
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)
value := fmt.Sprintf("git media %s %%f", filterName)
existing := gitconfig.Find(key)
if shouldReset(existing) {
Print("Installing %s filter", filterName)
gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, 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"
value := "true"
@ -61,8 +76,10 @@ func requireFilters() {
gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, 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 {

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