github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/resource/context/internal/util.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package internal
     5  
     6  import (
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"github.com/juju/errors"
    12  )
    13  
    14  // Logger exposes the logger functionality needed by CloseAndLog.
    15  type Logger interface {
    16  	// Errorf formats the provided log message and writes it to the log.
    17  	Errorf(string, ...interface{})
    18  }
    19  
    20  // CloseAndLog calls the closer's Close() and logs any error returned therefrom.
    21  func CloseAndLog(closer io.Closer, label string, logger Logger) {
    22  	if closer == nil {
    23  		return
    24  	}
    25  	if err := closer.Close(); err != nil {
    26  		logger.Errorf("while closing %s: %v", label, err)
    27  	}
    28  }
    29  
    30  // ReplaceDirectory replaces the target directory with the source. This
    31  // involves removing the target if it exists and then moving the source
    32  // into place.
    33  func ReplaceDirectory(targetDir, sourceDir string, deps ReplaceDirectoryDeps) error {
    34  	// TODO(ericsnow) Move it out of the way and remove it after the rename.
    35  	if err := deps.RemoveDir(targetDir); err != nil {
    36  		return errors.Trace(err)
    37  	}
    38  
    39  	if err := os.MkdirAll(filepath.Dir(targetDir), 0755); err != nil {
    40  		return errors.Trace(err)
    41  	}
    42  
    43  	if err := deps.Move(targetDir, sourceDir); err != nil {
    44  		return errors.Trace(err)
    45  	}
    46  	return nil
    47  }
    48  
    49  // ReplaceDirectoryDeps exposes the functionality needed by ReplaceDirectory.
    50  type ReplaceDirectoryDeps interface {
    51  	// RemoveDir deletes the directory at the given path.
    52  	RemoveDir(dirname string) error
    53  
    54  	// Move moves the directory at the source path to the target path.
    55  	Move(target, source string) error
    56  }