Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting env vars #337

Merged
merged 4 commits into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/full_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,21 @@ source_dir: ".lefthook"
source_dir_local: ".lefthook-local"
```

## Custom preset ENV variables

Lefthook allows you to set ENV variables for the commands and scripts. This is helpful when you use lefthook on different OSes and need to pass ENV vars to your executables.

```yml
# lefthook.yml

pre-commit:
commands:
test:
run: bundle exec rspec
env:
RAILS_ENV: test
```

## Manage verbosity

You can manage the verbosity using the `skip_output` config.
Expand Down
9 changes: 5 additions & 4 deletions internal/config/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ var errFilesIncompatible = errors.New("One of your runners contains incompatible
type Command struct {
Run string `mapstructure:"run"`

Skip interface{} `mapstructure:"skip"`
Tags []string `mapstructure:"tags"`
Glob string `mapstructure:"glob"`
Files string `mapstructure:"files"`
Skip interface{} `mapstructure:"skip"`
Tags []string `mapstructure:"tags"`
Glob string `mapstructure:"glob"`
Files string `mapstructure:"files"`
Env map[string]string `mapstructure:"env"`

Root string `mapstructure:"root"`
Exclude string `mapstructure:"exclude"`
Expand Down
5 changes: 3 additions & 2 deletions internal/config/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import (
type Script struct {
Runner string `mapstructure:"runner"`

Skip interface{} `mapstructure:"skip"`
Tags []string `mapstructure:"tags"`
Skip interface{} `mapstructure:"skip"`
Tags []string `mapstructure:"tags"`
Env map[string]string `mapstructure:"env"`

FailText string `mapstructure:"fail_text"`
Interactive bool `mapstructure:"interactive"`
Expand Down
16 changes: 12 additions & 4 deletions internal/lefthook/runner/execute_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package runner

import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
Expand All @@ -19,9 +20,9 @@ import (

type CommandExecutor struct{}

func (e CommandExecutor) Execute(root string, args []string, interactive bool) (*bytes.Buffer, error) {
func (e CommandExecutor) Execute(opts ExecuteOptions) (*bytes.Buffer, error) {
stdin := os.Stdin
if interactive && !isatty.IsTerminal(os.Stdin.Fd()) {
if opts.interactive && !isatty.IsTerminal(os.Stdin.Fd()) {
tty, err := os.Open("/dev/tty")
if err == nil {
defer tty.Close()
Expand All @@ -30,10 +31,17 @@ func (e CommandExecutor) Execute(root string, args []string, interactive bool) (
log.Errorf("Couldn't enable TTY input: %s\n", err)
}
}
command := exec.Command("sh", "-c", strings.Join(args, " "))
rootDir, _ := filepath.Abs(root)
command := exec.Command("sh", "-c", strings.Join(opts.args, " "))
rootDir, _ := filepath.Abs(opts.root)
command.Dir = rootDir

envList := make([]string, len(opts.env))
for name, value := range opts.env {
envList = append(envList, fmt.Sprintf("%s=%s", strings.ToUpper(name), value))
}

command.Env = append(os.Environ(), envList...)

p, err := pty.Start(command)
if err != nil {
return nil, err
Expand Down
16 changes: 12 additions & 4 deletions internal/lefthook/runner/execute_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package runner

import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand All @@ -11,13 +12,20 @@ import (

type CommandExecutor struct{}

func (e CommandExecutor) Execute(root string, args []string, _ bool) (*bytes.Buffer, error) {
command := exec.Command(args[0])
func (e CommandExecutor) Execute(opts ExecuteOptions) (*bytes.Buffer, error) {
command := exec.Command(opts.args[0])
command.SysProcAttr = &syscall.SysProcAttr{
CmdLine: strings.Join(args, " "),
CmdLine: strings.Join(opts.args, " "),
}

rootDir, _ := filepath.Abs(root)
envList := make([]string, len(opts.env))
for name, value := range opts.env {
envList = append(envList, fmt.Sprintf("%s=%s", strings.ToUpper(name), value))
}

command.Env = append(os.Environ(), envList...)

rootDir, _ := filepath.Abs(opts.root)
command.Dir = rootDir

var out bytes.Buffer
Expand Down
10 changes: 9 additions & 1 deletion internal/lefthook/runner/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@ import (
"bytes"
)

// ExecutorOptions contains the options that control the execution.
type ExecuteOptions struct {
name, root, failText string
args []string
interactive bool
env map[string]string
}

// Executor provides an interface for command execution.
// It is used here for testing purpose mostly.
type Executor interface {
Execute(root string, args []string, interactive bool) (*bytes.Buffer, error)
Execute(opts ExecuteOptions) (*bytes.Buffer, error)
RawExecute(command string, args ...string) error
}
17 changes: 6 additions & 11 deletions internal/lefthook/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@ const (

var surroundingQuotesRegexp = regexp.MustCompile(`^'(.*)'$`)

// RunOptions contains the options that control the execution.
type RunOptions struct {
name, root, failText string
args []string
interactive bool
}

// Runner responds for actual execution and handling the results.
type Runner struct {
fs afero.Fs
Expand Down Expand Up @@ -212,12 +205,13 @@ func (r *Runner) runScript(script *config.Script, unquotedPath string, file os.F
args = append(args, quotedScriptPath)
args = append(args, r.args[:]...)

r.run(RunOptions{
r.run(ExecuteOptions{
name: file.Name(),
root: r.repo.RootPath,
args: args,
failText: script.FailText,
interactive: script.Interactive,
env: script.Env,
})
}

Expand Down Expand Up @@ -282,12 +276,13 @@ func (r *Runner) runCommand(name string, command *config.Command) {
return
}

r.run(RunOptions{
r.run(ExecuteOptions{
name: name,
root: filepath.Join(r.repo.RootPath, command.Root),
args: args,
failText: command.FailText,
interactive: command.Interactive,
env: command.Env,
})
}

Expand Down Expand Up @@ -396,11 +391,11 @@ func replaceQuoted(source, substitution string, files []string) string {
return source
}

func (r *Runner) run(opts RunOptions) {
func (r *Runner) run(opts ExecuteOptions) {
log.SetName(opts.name)
defer log.UnsetName(opts.name)

out, err := r.exec.Execute(opts.root, opts.args, opts.interactive)
out, err := r.exec.Execute(opts)

var execName string
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions internal/lefthook/runner/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ import (

type TestExecutor struct{}

func (e TestExecutor) Execute(root string, args []string, interactive bool) (out *bytes.Buffer, err error) {
func (e TestExecutor) Execute(opts ExecuteOptions) (out *bytes.Buffer, err error) {
out = bytes.NewBuffer(make([]byte, 0))

if args[0] == "success" {
if opts.args[0] == "success" {
err = nil
} else {
err = errors.New(args[0])
err = errors.New(opts.args[0])
}

return
Expand Down