github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/worker/uniter/runner/jujuc/tools.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuc
     5  
     6  import (
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils/symlink"
    12  
    13  	"github.com/juju/juju/juju/names"
    14  )
    15  
    16  // EnsureSymlinks creates a symbolic link to jujuc within dir for each
    17  // hook command. If the commands already exist, this operation does nothing.
    18  // If dir is a symbolic link, it will be dereferenced first.
    19  func EnsureSymlinks(dir string) (err error) {
    20  	logger.Infof("ensure jujuc symlinks in %s", dir)
    21  	defer func() {
    22  		if err != nil {
    23  			err = errors.Annotatef(err, "cannot initialize hook commands in %q", dir)
    24  		}
    25  	}()
    26  	st, err := os.Lstat(dir)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	// NOTE: need to work out how to do this on windows.
    31  	if st.Mode()&os.ModeSymlink != 0 {
    32  		link, err := symlink.Read(dir)
    33  		if err != nil {
    34  			return err
    35  		}
    36  		if !filepath.IsAbs(link) {
    37  			logger.Infof("%s is relative", link)
    38  			link = filepath.Join(filepath.Dir(dir), link)
    39  		}
    40  		dir = link
    41  		logger.Infof("was a symlink, now looking at %s", dir)
    42  	}
    43  
    44  	jujudPath := filepath.Join(dir, names.Jujud)
    45  	logger.Debugf("jujud path %s", jujudPath)
    46  	for _, name := range CommandNames() {
    47  		// The link operation fails when the target already exists,
    48  		// so this is a no-op when the command names already
    49  		// exist.
    50  		err := symlink.New(jujudPath, filepath.Join(dir, name))
    51  		if err != nil && !os.IsExist(err) {
    52  			return err
    53  		}
    54  	}
    55  	return nil
    56  }