github.com/microsoft/fabrikate@v1.0.0-alpha.1.0.20210115014322-dc09194d0885/internal/cmd/find.go (about) 1 package cmd 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "strings" 8 9 "github.com/google/go-github/v28/github" 10 "github.com/spf13/cobra" 11 12 log "github.com/sirupsen/logrus" 13 ) 14 15 // FindComponent finds fabrikate components in the fabrikate-definitions repository that are related to the given keyword. 16 func FindComponent(keyword string) error { 17 18 client := github.NewClient(nil) 19 ctx := context.Background() 20 query := keyword + "+repo:microsoft/fabrikate-definitions" 21 22 results, _, err := client.Search.Code(ctx, query, nil) 23 24 if err != nil || results.CodeResults == nil { 25 return err 26 } 27 28 components := GetFabrikateComponents(results.CodeResults) 29 30 fmt.Printf("Search results for '%s':\n", keyword) 31 if len(components) == 0 { 32 log.Info(fmt.Sprintf("No components were found for '%s'", keyword)) 33 } else { 34 for _, component := range components { 35 fmt.Println(component) 36 } 37 } 38 39 return nil 40 } 41 42 // GetFabrikateComponents returns a unique list of fabrikate components from a github search result 43 func GetFabrikateComponents(codeResults []github.CodeResult) []string { 44 45 if codeResults == nil { 46 return []string{} 47 } 48 49 components := []string{} 50 uniqueComponents := map[string]bool{} 51 52 for _, result := range codeResults { 53 54 path := *result.Path 55 if !strings.HasPrefix(path, "definitions") { 56 continue 57 } 58 59 pathComponents := strings.Split(path, "/") 60 componentName := pathComponents[1] 61 62 if _, ok := uniqueComponents[componentName]; !ok { 63 uniqueComponents[componentName] = true 64 components = append(components, componentName) 65 } 66 } 67 68 return components 69 } 70 71 var findCmd = &cobra.Command{ 72 Use: "find <keyword>", 73 Short: "Find fabrikate components related to the given keyword", 74 Long: `Find fabrikate components related to the given keyword 75 Eg. 76 $ fab find prometheus 77 Finds fabrikate components that are related to 'prometheus'. 78 `, 79 RunE: func(cmd *cobra.Command, args []string) (err error) { 80 81 if len(args) != 1 { 82 return errors.New("'find' takes one argument") 83 } 84 85 return FindComponent(args[0]) 86 }, 87 } 88 89 func init() { 90 rootCmd.AddCommand(findCmd) 91 }