File: symlink.go

package info (click to toggle)
golang-github-juju-utils 0.0~git20171220.f38c0b0-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,748 kB
  • sloc: makefile: 20
file content (42 lines) | stat: -rw-r--r-- 1,030 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright 2014 Cloudbase Solutions SRL
// Licensed under the LGPLv3, see LICENCE file for details.

package symlink

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/juju/utils"
)

// Replace will do an atomic replacement of a symlink to a new path
func Replace(link, newpath string) error {
	dstDir := filepath.Dir(link)
	uuid, err := utils.NewUUID()
	if err != nil {
		return err
	}
	randStr := uuid.String()
	tmpFile := filepath.Join(dstDir, "tmpfile"+randStr)
	// Create the new symlink before removing the old one. This way, if New()
	// fails, we still have a link to the old tools.
	err = New(newpath, tmpFile)
	if err != nil {
		return fmt.Errorf("cannot create symlink: %s", err)
	}
	// On Windows, symlinks may not be overwritten. We remove it first,
	// and then rename tmpFile
	if _, err := os.Stat(link); err == nil {
		err = os.RemoveAll(link)
		if err != nil {
			return err
		}
	}
	err = os.Rename(tmpFile, link)
	if err != nil {
		return fmt.Errorf("cannot update tools symlink: %v", err)
	}
	return nil
}