File: cmd_hook.go

package info (click to toggle)
direnv 2.37.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 872 kB
  • sloc: sh: 1,499; csh: 83; makefile: 7
file content (61 lines) | stat: -rw-r--r-- 1,077 bytes parent folder | download
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cmd

import (
	"fmt"
	"os"
	"strings"
	"text/template"
)

// HookContext are the variables available during hook template evaluation
type HookContext struct {
	// SelfPath is the unescaped absolute path to direnv
	SelfPath string
}

// CmdHook is `direnv hook $0`
var CmdHook = &Cmd{
	Name:   "hook",
	Desc:   "Used to setup the shell hook",
	Args:   []string{"SHELL"},
	Action: actionSimple(cmdHookAction),
}

func cmdHookAction(_ Env, args []string) (err error) {
	var target string

	if len(args) > 1 {
		target = args[1]
	}

	selfPath, err := os.Executable()
	if err != nil {
		return err
	}

	// Convert Windows path if needed
	selfPath = strings.ReplaceAll(selfPath, "\\", "/")
	ctx := HookContext{selfPath}

	shell := DetectShell(target)
	if shell == nil {
		return fmt.Errorf("unknown target shell '%s'", target)
	}

	hookStr, err := shell.Hook()
	if err != nil {
		return err
	}

	hookTemplate, err := template.New("hook").Parse(hookStr)
	if err != nil {
		return err
	}

	err = hookTemplate.Execute(os.Stdout, ctx)
	if err != nil {
		return err
	}

	return
}