github.com/tommi2day/tnscli@v0.0.0-20240401211958-338fc0647b73/cmd/list.go (about) 1 // Package cmd commands 2 package cmd 3 4 import ( 5 "fmt" 6 "os" 7 "regexp" 8 "sort" 9 "strings" 10 11 "github.com/tommi2day/gomodules/dblib" 12 13 log "github.com/sirupsen/logrus" 14 15 "github.com/spf13/cobra" 16 ) 17 18 var ( 19 // check represents the list command 20 listCmd = &cobra.Command{ 21 Use: "list", 22 Short: "list TNS Entries", 23 Long: `list all TNS Entries`, 24 RunE: listTns, 25 SilenceUsage: true, 26 } 27 ) 28 var search = "" 29 var complete = false 30 31 func init() { 32 // don't have variables populated here 33 listCmd.Flags().StringVarP(&search, "search", "s", "", "search for tns name") 34 listCmd.Flags().BoolVarP(&complete, "complete", "C", false, "print complete entry") 35 RootCmd.AddCommand(listCmd) 36 } 37 38 // search or list tns entries 39 func listTns(_ *cobra.Command, _ []string) error { 40 // load available tns entries 41 tnsEntries, _, err := dblib.GetTnsnames(filename, true) 42 l := len(tnsEntries) 43 if err != nil || l == 0 { 44 log.Info("No Entries found") 45 return err 46 } 47 log.Infof("list %d entries", l) 48 err = outputTNS(tnsEntries, nil, complete) 49 return err 50 } 51 52 func outputTNS(tnsEntries dblib.TNSEntries, fo *os.File, full bool) (err error) { 53 l := len(tnsEntries) 54 if search == "" { 55 log.Debugf("list %d entries", l) 56 } else { 57 log.Debugf("search for %s in %d entries", search, l) 58 } 59 keys := make([]string, 0, len(tnsEntries)) 60 for k := range tnsEntries { 61 keys = append(keys, k) 62 } 63 if fo == nil { 64 fo = os.Stdout 65 } 66 sort.Strings(keys) 67 f := 0 68 var re *regexp.Regexp 69 if search != "" { 70 re = regexp.MustCompile("(?i)" + search) 71 } 72 for _, k := range keys { 73 out := formatEntry(tnsEntries, k, full) 74 if search == "" { 75 _, err = fmt.Fprintln(fo, out) 76 } else if re.Match([]byte(k)) { 77 log.Debugf("alias %s matches search string %s", k, search) 78 f++ 79 _, err = fmt.Fprintln(fo, out) 80 } 81 if err != nil { 82 log.Errorf("Error while writing:%v", err) 83 return 84 } 85 } 86 if search != "" { 87 log.Infof("found %d entries\n", f) 88 if f == 0 { 89 err = fmt.Errorf("no alias with '%s' found", search) 90 } 91 } 92 return 93 } 94 95 // format one tns entry 96 func formatEntry(entries dblib.TNSEntries, key string, full bool) (out string) { 97 if full { 98 entry := entries[key] 99 desc := entry.Desc 100 loc := entry.Location 101 tnsAlias := entry.Name 102 desc = strings.ReplaceAll(desc, "\r", " ") 103 desc = strings.ReplaceAll(desc, "\n", "\n ") 104 desc = strings.ReplaceAll(desc, "(ADDRESS_LIST", " (ADDRESS_LIST") 105 desc = strings.ReplaceAll(desc, "(CONNECT_DATA", " (CONNECT_DATA") 106 out = fmt.Sprintf("# Location: %s \n%s= %s", loc, tnsAlias, desc) 107 } else { 108 out = fmt.Sprintf("%s\n", key) 109 } 110 return 111 }