Go Cobra - CLI 명령어 관리

하설·2023년 8월 16일

Cobra 란


커맨드를 관리해주는 CLI 어플리케이션 개발 라이브러리
ex) ./a.out version

레포지토리 : https://github.com/spf13/cobra

예시

코드

package main

import (
	"fmt"
	"github.com/spf13/cobra"
)

func main() {
	// 기본 베이스 커맨드
	rootCmd := &cobra.Command{
		// 실행 파일명
		Use:   "cobraexample",
		// 짧은 설명
		Short: "Short description of application",
		// 긴 설명
		Long:  "Long description of application",
	}
	// 기본적으로 completion 이라는 커맨드가 내장되어있는데 이는 CLI 커맨드 자동완성(tab을 쳤을 때) 기능을 내장해주는 shell script 를 반환
	rootCmd.CompletionOptions.DisableDefaultCmd = true
	subCmd := &cobra.Command{
		// 하위 커맨드
		Use:   "version",
		// 짧은 설명
		Short: "Show Version",
		// 긴 설명
		Long:  "Show version of application",
		// 해당 커맨드 실행 시 실행될 함수
		// 만일 subCmd 하위에 subCmd가 있다면 하위의 subCmd의 Use 값과 일치하는 경우 하위 커맨드가 실행되고 그 외에는 해당 커맨드가 실행되며 args로 값이 전달됨
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("application version : v1.0.0")
		},
	}
	// rooCmd 하위 커맨드로 subCmd 등록
    // 해당 코드의 경우 `./<실행파일명> version` 커맨드 옵션을 추가한다는 의미
	rootCmd.AddCommand(subCmd)
	if err := rootCmd.Execute(); err != nil {
		fmt.Println("Error Occured")
		fmt.Println(err)
		return
	}
	return
}

참고하면 좋을 레퍼런스

https://github.com/kubernetes/kubernetes/blob/7b1b8012954bad71b4383efeca2ad256fbd27bf7/staging/src/k8s.io/kubectl/pkg/cmd/cmd.go#L267

profile
리자몽이 되고픈 파이리 데이터 엔지니어

0개의 댓글