Skip to content

Commit

Permalink
Added file opener
Browse files Browse the repository at this point in the history
  • Loading branch information
cgxeiji committed Oct 30, 2018
1 parent 97e4ad1 commit 617c8ba
Show file tree
Hide file tree
Showing 3 changed files with 245 additions and 9 deletions.
96 changes: 92 additions & 4 deletions app/cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ package cmd
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
Expand Down Expand Up @@ -56,6 +58,8 @@ You can TODO`,
if _, err := os.Stat(file); os.IsNotExist(err) {
if doi := query(search); doi != "" {
entry = addDOI(doi)
commit(entry)
edit(entry)
}
} else {
fmt.Println("file:", file)
Expand Down Expand Up @@ -84,11 +88,16 @@ You can TODO`,
entry = add(t)
}

} else {
fmt.Println("Getting metadata from doi")
entry = addDOI(doi)
}

commit(entry)
attach(entry, file)
}

commit(entry)
edit(entry)
pretty.Println(entry.Bib())

},
Expand Down Expand Up @@ -141,7 +150,6 @@ func requestSearch() string {
}

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

Expand All @@ -163,20 +171,41 @@ func commit(entry *scholar.Entry) {

file := filepath.Join(saveTo, "entry.yaml")
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)
err := editor(file)
if err != nil {
panic(err)
}

d, err = ioutil.ReadFile(file)
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
Expand All @@ -197,6 +226,22 @@ func editor(file string) error {
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 @@ -357,3 +402,46 @@ 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)

src, err := os.Open(file)
if err != nil {
panic(err)
}
defer src.Close()

filename := fmt.Sprintf("%s_%.40s%s", key, clean(entry.Required["title"]), filepath.Ext(file))

path := filepath.Join(saveTo, filename)

dst, err := os.Create(path)
if err != nil {
panic(err)
}
defer dst.Close()

b, err := io.Copy(dst, src)
if err != nil {
panic(err)
}
fmt.Println("Copied", b, "bytes to", path)
// horrible placeholder
entry.File = path

update(entry)
}
153 changes: 153 additions & 0 deletions app/cmd/open.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

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

// openCmd represents the open command
var openCmd = &cobra.Command{
Use: "open",
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:
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.`,
Run: func(cmd *cobra.Command, args []string) {
// TODO: Make a entry search menu
open(findQuery("").File)
},
}

func init() {
rootCmd.AddCommand(openCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// openCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// openCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

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

for _, dir := range dirs {
if dir.IsDir() && dir.Name() == strings.TrimSpace(key) {
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)
}

return &e
}
}

return &scholar.Entry{}
}

func findQuery(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 type: {{ 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: "-------------------------- Types --------------------------",
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]

}
5 changes: 0 additions & 5 deletions app/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,6 @@ func initConfig() {

viper.Set("deflib", dlex)

// TODO: delete this
fmt.Println(viper.GetString("deflib"))

et := viper.New()
et.SetConfigName("types")
et.SetConfigType("yaml")
Expand All @@ -134,8 +131,6 @@ func initConfig() {
panic("no types.yaml found")
}

// TODO: delete this
fmt.Println(et.ConfigFileUsed())
err = scholar.LoadTypes(et.ConfigFileUsed())
if err != nil {
panic(err)
Expand Down

0 comments on commit 617c8ba

Please sign in to comment.