aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/gitalias/git-sw.go
blob: f4cab21f85bc9a42e5dbecb2e565526783a7a8b4 (plain)
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
package main

import (
	"log"
	"os"
	"os/exec"
	"strings"
)

func main() {
	gitArgs := []string{"switch"}
	if requiresDetachFlag(os.Args) {
		gitArgs = append(gitArgs, "--detach")
	}
	for i, argv := range os.Args {
		if i == 0 {
			continue // argv[0] is a program name.
		}
		gitArgs = append(gitArgs, argv)
	}

	cmd := exec.Command("git", gitArgs...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if err != nil {
		switch err.(type) {
		case *exec.ExitError:
			// Do nothing here because Git has already reported the error.
		default:
			log.Fatal(err)
		}
	}

	os.Exit(cmd.ProcessState.ExitCode())
}

func requiresDetachFlag(argv []string) bool {
	argc := len(argv)
	if argc == 1 {
		return false
	}
	firstArg := argv[1]
	return strings.HasPrefix(firstArg, "origin/") || strings.HasPrefix(firstArg, "upstream/")
}