Skip to content

Instantly share code, notes, and snippets.

@syossan27
Created December 22, 2018 15:21
Show Gist options
  • Save syossan27/0f134c595bce5b9ba0ca6311d908507e to your computer and use it in GitHub Desktop.
Save syossan27/0f134c595bce5b9ba0ca6311d908507e to your computer and use it in GitHub Desktop.
const (
completionDir = "/etc/bash_completion.d"
completionFile = "en"
completionFileContent = `
_cli_bash_autocomplete() {
local cur opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete en
`
loadConfigFileContent = "if [ -f '/etc/bash_completion.d/en' ]; then source '/etc/bash_completion.d/en'; fi"
)
func BashCompletionAction(ctx *cli.Context) {
// sudo en bash-completeと実行しているかチェック
if !validation.CheckSudo() {
foundation.PrintError("Please run 'sudo en bash-complete'")
return
}
// 引数チェック
args := ctx.Args()
validation.ValidateArgs(args)
path := args[0]
// /etc/bash_complete.d/にbash_autocompletionファイルを設置
completion.CreateConfigFile()
// ファイルを読み込むように指定されたシェルの設定ファイルに書き込み
completion.WriteLoadConfig(path)
foundation.PrintSuccess(
fmt.Sprintf("Configure bash_complete Successful\nPlease run `source %v`", path),
)
}
func CheckSudo() bool {
// sudoのuidである0かどうかで判断
if os.Getuid() != 0 {
return false
}
return true
}
func CreateConfigFile() {
// /etc/bash_completion.dディレクトリの存在確認
if _, err := os.Stat(completionDir); err != nil {
PrintError("Not found bash_completion.d directory\nPlease make /etc/bash_completion.d directory")
return
}
// completionファイルの作成
f, err := os.Create(filepath.Join(completionDir, completionFile))
if err != nil {
PrintError("Failed to create bash_completion file")
return
}
defer f.Close()
// completionファイルにurfave/cliで提供されているbash_autocompleteの内容を書き込み
_, err = f.Write([]byte(completionFileContent))
if err != nil {
PrintError("Failed to write to bash_completion file")
return
}
}
func WriteLoadConfig(path string) {
if _, err := os.Stat(path); err != nil {
PrintError(fmt.Sprintf("Not found %v", path))
return
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
PrintError("Failed to write to ssh config file")
return
}
defer f.Close()
fmt.Fprintln(f, loadConfigFileContent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment