Skip to content

Commit

Permalink
Merge branch 'kingpin'
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikita Voloboev committed Feb 8, 2018
2 parents e6f7c7c + bfe6604 commit dbbcd41
Show file tree
Hide file tree
Showing 6 changed files with 165 additions and 109 deletions.
158 changes: 51 additions & 107 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,147 +1,91 @@
package main

import (
"encoding/csv"
"log"
"os"
"os/exec"
"strings"
"fmt"

"github.com/alecthomas/kingpin"
"github.com/deanishe/awgo"
"github.com/deanishe/awgo/update"
"github.com/docopt/docopt-go"
)

// Name of the background job that checks for updates
const updateJobName = "checkForUpdate"

var usage = `alfred-ask-create-share [search|check] [<query>]
Open web submissions from Alfred.
Usage:
alfred-ask-create-share search [<query>]
alfred-ask-create-share check
alfred-ask-create-share -h
Options:
-h, --help Show this message and exit.
`
// Defaults for Kingpin flags
const (
defaultMaxResults = "100"
)

// Icons
var (
// Icons
iconAvailable = &aw.Icon{Value: "icons/update.png"}
redditIcon = &aw.Icon{Value: "icons/reddit.png"}
githubIcon = &aw.Icon{Value: "icons/github.png"}
forumsIcon = &aw.Icon{Value: "icons/forums.png"}
stackIcon = &aw.Icon{Value: "icons/stack.png"}
docIcon = &aw.Icon{Value: "icons/doc.png"}

repo = "nikitavoloboev/alfred-ask-create-share"
wf *aw.Workflow
)

func init() {
wf = aw.New(update.GitHub(repo))
}
var (
// Kingpin and script options
app *kingpin.Application

func run() {
// Pass wf.Args() to docopt because our update logic relies on
// AwGo's magic actions.
args, _ := docopt.Parse(usage, wf.Args(), true, wf.Version(), false, true)

// Alternate action: get available releases from remote
if args["check"] != false {
wf.TextErrors = true
log.Println("Checking for updates...")
if err := wf.CheckForUpdate(); err != nil {
wf.FatalError(err)
}
return
}
// Application commands
searchCmd *kingpin.CmdClause
updateCmd *kingpin.CmdClause
testCmd *kingpin.CmdClause

// Script filter
var query string
if args["<query>"] != nil {
query = args["<query>"].(string)
}
// Script options (populated by Kingpin application)
query string

log.Printf("query=%s", query)
repo = "nikitavoloboev/alfred-ask-create-share"

// Call self with "check" command if an update is due and a
// check job isn't already running.
if wf.UpdateCheckDue() && !aw.IsRunning(updateJobName) {
log.Println("Running update check in background...")
cmd := exec.Command("./alfred-ask-create-share", "check")
if err := aw.RunInBackground(updateJobName, cmd); err != nil {
log.Printf("Error starting update check: %s", err)
}
}
// Workflow stuff
wf *aw.Workflow
)

if query == "" { // Only show update status if query is empty
// Send update status to Alfred
if wf.UpdateAvailable() {
wf.NewItem("Update Available!").
Subtitle("↩ to install").
Autocomplete("workflow:update").
Valid(false).
Icon(iconAvailable)
}
}
// Mostly sets up kingpin commands
func init() {
wf = aw.New(update.GitHub(repo), aw.HelpURL(repo+"/issues"))

links := parseCSV()

for key, value := range links {
if strings.Contains(key, "r: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(redditIcon)
} else if strings.Contains(key, "s: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(stackIcon)
} else if strings.Contains(key, "g: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(githubIcon)
} else if strings.Contains(key, "f: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(forumsIcon)
} else if strings.Contains(key, "d: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(docIcon)
} else {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key)
}
}
app = kingpin.New("ask", "Open web submissions.")

if query != "" {
wf.Filter(query)
}
// Update command
updateCmd = app.Command("update", "Check for new workflow version.").Alias("u")

// Commands using query
searchCmd = app.Command("search", "Search web submissions.").Alias("s")

wf.WarnEmpty("No matching items", "Try a different query?")
wf.SendFeedback()
// Common options
for _, cmd := range []*kingpin.CmdClause{
searchCmd,
} {
cmd.Flag("query", "Search query.").Short('q').StringVar(&query)
}
}

// parseCSV parses CSV for links and arguments
func parseCSV() map[string]string {
func run() {
var err error

// Load values from file to a hash map
f, err := os.Open("ask-create-share.csv")
cmd, err := app.Parse(wf.Args())
if err != nil {
panic(err)
wf.FatalError(err)
}
defer f.Close()

r := csv.NewReader(f)

records, err := r.ReadAll()
if err != nil {
log.Fatal(err)
switch cmd {
case searchCmd.FullCommand():
err = doSearch()
case updateCmd.FullCommand():
err = doUpdate()
default:
err = fmt.Errorf("Uknown command: %s", cmd)
}

// Holds user's search arguments and an appropriate search URL
links := make(map[string]string)

for _, record := range records {
links[record[0]] = record[1]
// Check for update
if err == nil && cmd != updateCmd.FullCommand() {
err = checkForUpdate()
}

return links

if err != nil {
wf.FatalError(err)
}
}

func main() {
Expand Down
70 changes: 70 additions & 0 deletions search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import (
"encoding/csv"
"log"
"os"
"strings"
)

// doSearch makes a search for web submissions and returns results to Alfred.
func doSearch() error {
showUpdateStatus()

log.Printf("query=%s", query)

links := parseCSV()

for key, value := range links {
if strings.Contains(key, "r: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(redditIcon)
} else if strings.Contains(key, "s: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(stackIcon)
} else if strings.Contains(key, "g: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(githubIcon)
} else if strings.Contains(key, "f: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(forumsIcon)
} else if strings.Contains(key, "d: ") {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key).Icon(docIcon)
} else {
wf.NewItem(key).Valid(true).UID(key).Var("URL", value).Var("ARG", key)
}
}

if query != "" {
wf.Filter(query)
}

wf.WarnEmpty("No matching items", "Try a different query?")
wf.SendFeedback()
return nil
}

// parseCSV parses CSV for links and arguments.
func parseCSV() map[string]string {
var err error

// Load values from file to a hash map
f, err := os.Open("ask-create-share.csv")
if err != nil {
panic(err)
}
defer f.Close()

r := csv.NewReader(f)

records, err := r.ReadAll()
if err != nil {
log.Fatal(err)
}

// Holds user's search arguments and an appropriate search URL
links := make(map[string]string)

for _, record := range records {
links[record[0]] = record[1]
}

return links

}
42 changes: 42 additions & 0 deletions update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"log"
"os"
"os/exec"

aw "github.com/deanishe/awgo"
)

// doUpdate checks for a newer version of the workflow.
func doUpdate() error {
log.Println("Checking for update...")
return wf.CheckForUpdate()
}

// checkForUpdate runs "./alsf update" in the background if an update check is due.
func checkForUpdate() error {
if !wf.UpdateCheckDue() || aw.IsRunning("update") {
return nil
}
cmd := exec.Command(os.Args[0], "update")
return aw.RunInBackground("update", cmd)
}

// showUpdateStatus adds an "update available!" message to Script Filters if an update is available
// and query is empty.
func showUpdateStatus() {
if query != "" {
return
}

if wf.UpdateAvailable() {
wf.Configure(aw.SuppressUIDs(true))
log.Println("Update available!")
wf.NewItem("An update is available!").
Subtitle("⇥ or ↩ to install update").
Valid(false).
Autocomplete("workflow:update").
Icon(&aw.Icon{Value: "icons/update-available.png"})
}
}
Binary file modified workflow/alfred-ask-create-share
Binary file not shown.
Binary file added workflow/icons/update-available.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions workflow/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
<key>runningsubtext</key>
<string>Loading...</string>
<key>script</key>
<string>./alfred-ask-create-share search "$1"</string>
<string>./alfred-ask-create-share search -q "$1"</string>
<key>scriptargtype</key>
<integer>1</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -225,7 +225,7 @@ Post any issues and feature requests you have there. 💜</string>
</dict>
</dict>
<key>version</key>
<string>2.6.3</string>
<string>2.6.4</string>
<key>webaddress</key>
<string>https://github.com/nikitavoloboev/alfred-ask-create-share</string>
</dict>
Expand Down

0 comments on commit dbbcd41

Please sign in to comment.