github.com/echohead/hub@v2.2.1+incompatible/commands/alias.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/github/hub/ui"
    10  	"github.com/github/hub/utils"
    11  )
    12  
    13  var cmdAlias = &Command{
    14  	Run:   alias,
    15  	Usage: "alias [-s] [SHELL]",
    16  	Short: "Show shell instructions for wrapping git",
    17  	Long: `Shows shell instructions for wrapping git. If given, SHELL specifies the
    18  type of shell; otherwise defaults to the value of SHELL environment
    19  variable. With -s, outputs shell script suitable for eval.
    20  `,
    21  }
    22  
    23  var flagAliasScript bool
    24  
    25  func init() {
    26  	cmdAlias.Flag.BoolVarP(&flagAliasScript, "script", "s", false, "SCRIPT")
    27  	CmdRunner.Use(cmdAlias)
    28  }
    29  
    30  func alias(command *Command, args *Args) {
    31  	var shell string
    32  	if args.ParamsSize() > 0 {
    33  		shell = args.FirstParam()
    34  	} else {
    35  		shell = os.Getenv("SHELL")
    36  	}
    37  
    38  	if shell == "" {
    39  		utils.Check(fmt.Errorf("Unknown shell"))
    40  	}
    41  
    42  	shells := []string{"bash", "zsh", "sh", "ksh", "csh", "tcsh", "fish"}
    43  	shell = filepath.Base(shell)
    44  	var validShell bool
    45  	for _, s := range shells {
    46  		if s == shell {
    47  			validShell = true
    48  			break
    49  		}
    50  	}
    51  
    52  	if !validShell {
    53  		err := fmt.Errorf("hub alias: unsupported shell\nsupported shells: %s", strings.Join(shells, " "))
    54  		utils.Check(err)
    55  	}
    56  
    57  	if flagAliasScript {
    58  		var alias string
    59  		switch shell {
    60  		case "csh", "tcsh":
    61  			alias = "alias git hub"
    62  		default:
    63  			alias = "alias git=hub"
    64  		}
    65  
    66  		ui.Println(alias)
    67  	} else {
    68  		var profile string
    69  		switch shell {
    70  		case "bash":
    71  			profile = "~/.bash_profile"
    72  		case "zsh":
    73  			profile = "~/.zshrc"
    74  		case "ksh":
    75  			profile = "~/.profile"
    76  		case "fish":
    77  			profile = "~/.config/fish/config.fish"
    78  		case "csh":
    79  			profile = "~/.cshrc"
    80  		case "tcsh":
    81  			profile = "~/.tcshrc"
    82  		default:
    83  			profile = "your profile"
    84  		}
    85  
    86  		msg := fmt.Sprintf("# Wrap git automatically by adding the following to %s:\n", profile)
    87  		ui.Println(msg)
    88  
    89  		var eval string
    90  		switch shell {
    91  		case "fish":
    92  			eval = `eval (hub alias -s)`
    93  		case "csh", "tcsh":
    94  			eval = "eval \"`hub alias -s`\""
    95  		default:
    96  			eval = `eval "$(hub alias -s)"`
    97  		}
    98  		ui.Println(eval)
    99  	}
   100  
   101  	os.Exit(0)
   102  }