Skip to content

Commit

Permalink
Added strategy support, sources are now enabled per instance
Browse files Browse the repository at this point in the history
  • Loading branch information
spy16 committed Sep 23, 2018
1 parent 333b753 commit 2868c06
Show file tree
Hide file tree
Showing 20 changed files with 414 additions and 108 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ Currently following implementations are available:

## TODO:

- [ ] Make sources configurable
- sources to be used should be configurable per instance
- [x] Make sources configurable
- [x] sources to be used should be configurable per instance
- [ ] a configurable caching mechanism to enable offline usage
- [ ] Add more sources (hackernews?, wikipedia?)
- [ ] Enable markdown to console colored output ?
Expand Down
2 changes: 1 addition & 1 deletion clipmon.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (cbm *ClipboardMonitor) Run(ctx context.Context) error {
query.Text = strings.TrimSpace(currentContent)

cbm.Instance.Infof("running query for '%s'..", query.Text)
rs, err := cbm.Instance.Search(ctx, query)
rs, err := cbm.Instance.Search(ctx, query, Strategy1st)
if err == nil && rs != nil {
if len(rs) > 0 {
cbm.Instance.Infof("recieved result. pasting back..")
Expand Down
33 changes: 9 additions & 24 deletions cmd/radium/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,19 @@ package main

import (
"fmt"
"log"
"reflect"
"strings"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func newCLI() *cobra.Command {
cfg := &config{}
rootCmd := newRootCmd(cfg)

initConfig := func() {
viper.SetConfigName("radium")
viper.SetConfigType("yaml")

viper.AddConfigPath("./")
if hd, err := homedir.Dir(); err == nil {
viper.AddConfigPath(hd)
}
viper.AutomaticEnv()
viper.BindPFlags(rootCmd.PersistentFlags())

viper.ReadInConfig()
if err := viper.Unmarshal(cfg); err != nil {
log.Fatalf("config err: %s\n", err)
}
}

cobra.OnInitialize(initConfig)
cobra.OnInitialize(func() {
initConfig(cfg, rootCmd)
})
return rootCmd
}

Expand All @@ -51,6 +34,7 @@ and replace queries with solutions as they come in!

rootCmd.PersistentFlags().BoolP("ugly", "u", false, "Print raw output as yaml or json")
rootCmd.PersistentFlags().Bool("json", false, "Print output as JSON")
rootCmd.PersistentFlags().StringSlice("sources", nil, "Enable sources")

rootCmd.AddCommand(newServeCmd(cfg))
rootCmd.AddCommand(newQueryCmd(cfg))
Expand All @@ -67,14 +51,15 @@ func newListSources(cfg *config) *cobra.Command {
}

cmd.Run = func(_ *cobra.Command, args []string) {
ins := getNewRadiumInstance()
ins := getNewRadiumInstance(*cfg)
srcs := ins.GetSources()

if L := len(srcs); L > 0 {
fmt.Printf("%d source(s) available:\n", L)
for name, src := range srcs {
fmt.Printf("%s\n", strings.Repeat("-", 20))
for order, src := range srcs {
ty := reflect.TypeOf(src)
fmt.Printf("* %s (Type: %s)\n", name, ty.String())
fmt.Printf("%d. %s (Type: %s)\n", order+1, src.Name, ty.String())
}
} else {
fmt.Println("No sources configured")
Expand Down
26 changes: 26 additions & 0 deletions cmd/radium/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
package main

import (
"log"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func initConfig(cfg *config, rootCmd *cobra.Command) {
viper.SetDefault("sources", "cheatsh,learnxiny,tldr")

viper.SetConfigName("radium")
viper.AddConfigPath("./")
if hd, err := homedir.Dir(); err == nil {
viper.AddConfigPath(hd)
}
viper.AutomaticEnv()
viper.BindPFlags(rootCmd.PersistentFlags())

viper.ReadInConfig()
if err := viper.Unmarshal(cfg); err != nil {
log.Fatalf("config err: %s\n", err)
}
}

// config struct is used to store CLI configurations. configuration
// values are read into this struct using viper
type config struct {
Sources []string `json:"sources"`
}
26 changes: 13 additions & 13 deletions cmd/radium/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"context"
"fmt"
"errors"
"os"
"strings"

Expand All @@ -19,7 +19,9 @@ func newQueryCmd(cfg *config) *cobra.Command {
}

var attribs []string
var strategy string
cmd.Flags().StringSliceVarP(&attribs, "attr", "a", []string{}, "Attributes to narrow the search scope")
cmd.Flags().StringVarP(&strategy, "strategy", "s", "concurrent", "Strategy to use for executing sources")

cmd.Run = func(_ *cobra.Command, args []string) {
query := radium.Query{}
Expand All @@ -31,26 +33,24 @@ func newQueryCmd(cfg *config) *cobra.Command {
if len(parts) == 2 {
query.Attribs[parts[0]] = parts[1]
} else {
fmt.Println("Err: invalid attrib format. must be <name>:<value>")
writeOut(cmd, errors.New("invalid attrib format. must be <name>:<value>"))
os.Exit(1)
}
}

ctx := context.Background()
ins := getNewRadiumInstance()
rs, err := ins.Search(ctx, query)
ins := getNewRadiumInstance(*cfg)
rs, err := ins.Search(ctx, query, strategy)
if err != nil {
writeOut(cmd, map[string]interface{}{
"error": err.Error(),
})
} else {
if len(rs) == 1 {
writeOut(cmd, rs[0])
} else {
writeOut(cmd, rs)
}
writeOut(cmd, err)
os.Exit(1)
}

if len(rs) == 1 {
writeOut(cmd, rs[0])
} else {
writeOut(cmd, rs)
}
}

return cmd
Expand Down
2 changes: 1 addition & 1 deletion cmd/radium/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ by passing '--clipboard' or '-C' option and setting '--addr' blank.

var wg sync.WaitGroup

ins := getNewRadiumInstance()
ins := getNewRadiumInstance(*cfg)

if addr != "" {
srv := radium.NewServer(ins)
Expand Down
21 changes: 17 additions & 4 deletions cmd/radium/setup.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package main

import (
"strings"

"github.com/shivylp/radium"
"github.com/shivylp/radium/sources"
)

func getNewRadiumInstance() *radium.Instance {
func getNewRadiumInstance(cfg config) *radium.Instance {
ins := radium.New(nil, nil)

ins.RegisterSource("cheat.sh", sources.NewCheatSh())
ins.RegisterSource("tldr", sources.NewTLDR())
ins.RegisterSource("learnxinyminutes", sources.NewLearnXInYMins())
for _, src := range cfg.Sources {
switch strings.ToLower(strings.TrimSpace(src)) {
case "cheatsh", "cheat.sh":
ins.RegisterSource("cheat.sh", sources.NewCheatSh())
case "learnxiny", "lxy", "learnxinyminutes":
ins.RegisterSource("learnxinyminutes", sources.NewLearnXInYMins())
case "tldr":
ins.RegisterSource("tldr", sources.NewTLDR())
case "wiki", "wikipedia":
ins.RegisterSource("wikipedia", sources.NewWikipedia())
default:
ins.Fatalf("unknown source type: %s", src)
}
}

return ins
}
9 changes: 6 additions & 3 deletions cmd/radium/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ func writeOut(cmd *cobra.Command, v interface{}) {
}

func tryPrettyPrint(v interface{}) {
if article, ok := v.(radium.Article); ok {
fmt.Println(article.Content)
} else {
switch v.(type) {
case radium.Article:
fmt.Println((v.(radium.Article)).Content)
case error:
fmt.Printf("error: %s\n", v)
default:
rawDump(v, true)
}
}
Expand Down
18 changes: 16 additions & 2 deletions interfaces.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
package radium

import (
"context"
"fmt"
"log"
"os"
)

// Source implementation is responsible for providing
// external data source to query for results.
type Source interface {
Search(q Query) ([]Article, error)
Search(ctx context.Context, q Query) ([]Article, error)
}

// RegisteredSource embeds given Source along with the registered name.
type RegisteredSource struct {
Name string
Source
}

// Logger implementation should provide logging
Expand All @@ -18,6 +26,7 @@ type Logger interface {
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
}

// Cache implementation is responsible for caching
Expand Down Expand Up @@ -45,5 +54,10 @@ func (dl defaultLogger) Warnf(format string, args ...interface{}) {
}

func (dl defaultLogger) Errorf(format string, args ...interface{}) {
log.Printf("ERR : %s", fmt.Sprintf(format, args...))
log.Printf("ERROR: %s", fmt.Sprintf(format, args...))
}

func (dl defaultLogger) Fatalf(format string, args ...interface{}) {
log.Printf("FATAL: %s", fmt.Sprintf(format, args...))
os.Exit(1)
}
Loading

0 comments on commit 2868c06

Please sign in to comment.