Skip to content

Commit

Permalink
Clean up and moved general function to a separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
cgxeiji committed Oct 31, 2018
1 parent 74b64c2 commit ece4bfc
Show file tree
Hide file tree
Showing 6 changed files with 280 additions and 182 deletions.
109 changes: 21 additions & 88 deletions app/cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@ import (
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"

Expand All @@ -56,7 +53,24 @@ You can TODO`,
search := strings.Join(args, " ")
file, _ := homedir.Expand(search)
if _, err := os.Stat(file); os.IsNotExist(err) {
if doi := query(search); doi != "" {
if search == "" {
doi := addDoi
if !requestManual("Would you like to search the web for metadata?") {
doi = query(requestSearch())
}
if doi != "" {
fmt.Println("Getting metadata from doi")
entry = addDOI(doi)
} else {
fmt.Println()
fmt.Println("Adding the entry manually...")
fmt.Println("What kind of entry is it?")
t := selectType()
fmt.Println()
fmt.Println("Please, add the required fields:")
entry = add(t)
}
} else if doi := query(search); doi != "" {
entry = addDOI(doi)
commit(entry)
edit(entry)
Expand All @@ -72,7 +86,7 @@ You can TODO`,

if doi == "" {
fmt.Println()
if !requestManual() {
if !requestManual("I could not find anything, can you give me a better search variable?") {
doi = query(requestSearch())
}
if doi != "" {
Expand Down Expand Up @@ -123,9 +137,9 @@ func init() {
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func requestManual() bool {
func requestManual(question string) bool {
prompt := promptui.Prompt{
Label: "I could not find anything, can you give me a better search variable?",
Label: question,
IsConfirm: true,
}

Expand Down Expand Up @@ -173,75 +187,6 @@ func commit(entry *scholar.Entry) {
ioutil.WriteFile(file, d, 0644)
}

func edit(entry *scholar.Entry) {
key := entry.GetKey()
saveTo := filepath.Join(viper.GetString("deflib"), key)

file := filepath.Join(saveTo, "entry.yaml")

err := editor(file)
if err != nil {
panic(err)
}

d, err := ioutil.ReadFile(file)
if err != nil {
panic(err)
}

yaml.Unmarshal(d, &entry)
}

func update(entry *scholar.Entry) {
key := entry.GetKey()
saveTo := filepath.Join(viper.GetString("deflib"), key)

file := filepath.Join(saveTo, "entry.yaml")

d, err := yaml.Marshal(entry)
if err != nil {
panic(err)
}

ioutil.WriteFile(file, d, 0644)
}

func editor(file string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
default:
cmd = viper.GetString("GENERAL.editor")
}
args = append(args, file)
c := exec.Command(cmd, args...)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr

return c.Run()
}

func open(file string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
default:
cmd = "xdg-open"
}
args = append(args, file)

return exec.Command(cmd, args...).Start()
}

func query(search string) string {
fmt.Println("Searching metadata for:", search)

Expand Down Expand Up @@ -403,18 +348,6 @@ func add(entryType string) *scholar.Entry {
return entry
}

func clean(filename string) string {
rx, err := regexp.Compile("[^[:alnum:][:space:]]+")
if err != nil {
return filename
}

filename = rx.ReplaceAllString(filename, " ")
filename = strings.Replace(filename, " ", "_", -1)

return strings.ToLower(filename)
}

func attach(entry *scholar.Entry, file string) {
key := entry.GetKey()
saveTo := filepath.Join(viper.GetString("deflib"), key)
Expand Down
16 changes: 9 additions & 7 deletions app/cmd/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ import (
// editCmd represents the edit command
var editCmd = &cobra.Command{
Use: "edit",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Short: "Edits an entry",
Long: `Scholar: a CLI Reference Manager
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Edit an entry's metadata using the default's text editor.
--------------------------------------------------------------------------------
TODO:
--------------------------------------------------------------------------------
`,
Run: func(cmd *cobra.Command, args []string) {
entry := findQuery("")
entry := entryQuery("")
edit(entry)
update(entry)
},
Expand Down
19 changes: 13 additions & 6 deletions app/cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,20 @@ import (
// exportCmd represents the export command
var exportCmd = &cobra.Command{
Use: "export",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Short: "Exports entries",
Long: `Scholar: a CLI Reference Manager
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Print all entries to stdout using biblatex format.
To save to a file run:
scholar export > references.bib
--------------------------------------------------------------------------------
TODO: add different export formats
TODO: add flag to specify which library to export
--------------------------------------------------------------------------------
`,
Run: func(cmd *cobra.Command, args []string) {
export()
},
Expand Down
166 changes: 166 additions & 0 deletions app/cmd/general.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package cmd

import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"

"github.com/cgxeiji/scholar"
"github.com/manifoldco/promptui"
"github.com/spf13/viper"
yaml "gopkg.in/yaml.v2"
)

func edit(entry *scholar.Entry) {
key := entry.GetKey()
saveTo := filepath.Join(viper.GetString("deflib"), key)

file := filepath.Join(saveTo, "entry.yaml")

err := editor(file)
if err != nil {
panic(err)
}

d, err := ioutil.ReadFile(file)
if err != nil {
panic(err)
}

yaml.Unmarshal(d, &entry)
}

func update(entry *scholar.Entry) {
key := entry.GetKey()
saveTo := filepath.Join(viper.GetString("deflib"), key)

file := filepath.Join(saveTo, "entry.yaml")

d, err := yaml.Marshal(entry)
if err != nil {
panic(err)
}

ioutil.WriteFile(file, d, 0644)
}

func editor(file string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
default:
cmd = viper.GetString("GENERAL.editor")
}
args = append(args, file)
c := exec.Command(cmd, args...)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr

return c.Run()
}

func open(file string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
default:
cmd = "xdg-open"
}
args = append(args, file)

return exec.Command(cmd, args...).Start()
}

func clean(filename string) string {
rx, err := regexp.Compile("[^[:alnum:][:space:]]+")
if err != nil {
return filename
}

filename = rx.ReplaceAllString(filename, " ")
filename = strings.Replace(filename, " ", "_", -1)

return strings.ToLower(filename)
}

func entryQuery(search string) *scholar.Entry {
dirs, err := ioutil.ReadDir(viper.GetString("deflib"))
if err != nil {
panic(err)
}

var entries []*scholar.Entry

for _, dir := range dirs {
if dir.IsDir() {
d, err := ioutil.ReadFile(filepath.Join(viper.GetString("deflib"), dir.Name(), "entry.yaml"))
if err != nil {
panic(err)
}

var e scholar.Entry
err = yaml.Unmarshal(d, &e)
if err != nil {
panic(err)
}

entries = append(entries, &e)
}
}

template := &promptui.SelectTemplates{
Label: "{{ . }}",
Active: `> {{ index .Required "title" | cyan | bold | underline }} ({{ index .Required "date" | yellow | bold | underline }}) {{ index .Required "author" | red | bold | underline }}`,
Inactive: ` {{ index .Required "title" | cyan }} ({{ index .Required "date" | yellow }}) {{ index .Required "author" | red }}`,
Selected: `Entry selected: {{ index .Required "title" | cyan | bold }}`,
Details: `
------------------------- Details -------------------------
{{ "Title:" | faint }} {{ index .Required "title" | cyan | bold}}
{{ "Author(s):" | faint }} {{ index .Required "author" | red | bold}}
{{ "Date:" | faint }} {{ index .Required "date" | yellow | bold}}`,
}

searcher := func(input string, index int) bool {
entry := entries[index]
title := strings.Replace(strings.ToLower(entry.Required["title"]), " ", "", -1)
aus := strings.Replace(strings.ToLower(entry.Required["author"]), " ", "", -1)
file := strings.Replace(strings.ToLower(filepath.Base(entry.File)), "_", "", -1)
s := fmt.Sprintf("%s%s%s", title, aus, file)
input = strings.Replace(strings.ToLower(input), " ", "", -1)

return strings.Contains(s, input)
}

prompt := promptui.Select{
Label: "-------------------------- Entries --------------------------",
Items: entries,
Templates: template,
Size: 5,
Searcher: searcher,
StartInSearchMode: true,
}

i, _, err := prompt.Run()

if err != nil {
fmt.Println("Aborting")
os.Exit(1)
}

return entries[i]

}
Loading

0 comments on commit ece4bfc

Please sign in to comment.