grim/convey

A host of linting fixes

2018-02-19, Gary Kramlich
f3a61cc7b59d
A host of linting fixes
// Convey
// Copyright 2016-2018 Gary Kramlich <grim@reaperworld.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package state
import (
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"github.com/aphistic/gomol"
"github.com/emirpasic/gods/stacks/arraystack"
"bitbucket.org/rw_grim/convey/logging"
)
// cleanupList is a simple structure for keeping track of functions to call
// on cleanup.
type cleanupList struct {
mutex sync.Mutex
functions *arraystack.Stack
}
// newCleanupList create and initializes a cleanupList
func newCleanupList() *cleanupList {
return &cleanupList{
functions: arraystack.New(),
}
}
// Add adds a function to the cleanup list.
func (cl *cleanupList) Add(fn func(l *gomol.LogAdapter)) {
cl.mutex.Lock()
defer cl.mutex.Unlock()
cl.functions.Push(fn)
}
// run will run all of the cleanup functions in the list
func (cl *cleanupList) run() {
cl.mutex.Lock()
defer cl.mutex.Unlock()
logger := logging.NewAdapter("cleanup")
it := cl.functions.Iterator()
for it.Next() {
fn := it.Value().(func(*gomol.LogAdapter))
fn(logger)
}
}
// cleanupOnSignal will call State.Destroy on SIGINT or SIGTERM
func (st *State) cleanupOnSignal() {
// create a channel to receive the signal
ch := make(chan os.Signal, 1)
go func() {
// block until we get a signal, we don't care what it is so we just
// throw it away
<-ch
// call the destroy method
st.Destroy()
// exit with an exit code of 1
os.Exit(1)
}()
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
}
// Cleanup registers a function to be called when the state is being torn down.
func (st *State) Cleanup(fn func(l *gomol.LogAdapter)) {
st.cleanupList.Add(fn)
}
// destroy will clean up the given state and run any registered cleanup
// functions
func (st *State) Destroy() {
// run the registered cleanup functions
st.cleanupList.run()
// finally remove the workspace if requested
if !st.KeepWorkspace {
if err := os.RemoveAll(st.Directory); err != nil {
st.logger.Warningf("error removing %s: %s\n", st.Directory, err.Error())
}
// try to remove the .convey directory. This will only succeed when
// our state is the only one and that's intentional.
os.Remove(filepath.Dir(st.Directory))
}
}