Skip to content

Commit

Permalink
fix folder prefix filter using library
Browse files Browse the repository at this point in the history
  • Loading branch information
konoui committed Jun 8, 2021
1 parent 64068fc commit eb17760
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 120 deletions.
2 changes: 1 addition & 1 deletion assets/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
</dict>
</dict>
<key>version</key>
<string>v0.3.1</string>
<string>v0.4.0</string>
<key>webaddress</key>
<string>https://github.com/konoui/alfred-bookmarks</string>
</dict>
Expand Down
71 changes: 51 additions & 20 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ func init() {
}

type runtime struct {
cfg *Config
query string
folderPrefix string
clear bool
cfg *Config
query string
folderPrefixF func(subtitle string) bool
clear bool
}

// Execute runs cmd
Expand All @@ -57,6 +57,11 @@ func Execute(args ...string) {
fatal(err)
}

err = awf.OnInitialize()
if err != nil {
fatal(err)
}

r, err := parse(cfg, args...)
if err != nil {
awf.Clear().Append(
Expand Down Expand Up @@ -87,19 +92,15 @@ func parse(cfg *Config, args ...string) (*runtime, error) {
return nil, err
}
r := &runtime{
cfg: cfg,
query: alfred.Normalize(strings.Join(fs.Args(), " ")),
folderPrefix: alfred.Normalize(folderPrefix),
clear: clear,
cfg: cfg,
query: strings.Join(fs.Args(), " "),
folderPrefixF: filterBySubtitle(folderPrefix),
clear: clear,
}
return r, nil
}

func (r *runtime) run() error {
if err := awf.OnInitialize(); err != nil {
return err
}

c, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if !alfred.HasUpdateArg() && awf.Updater().NewerVersionAvailable(c) {
Expand All @@ -125,7 +126,8 @@ func (r *runtime) run() error {
ttl := convertDefaultTTL(r.cfg.MaxCacheAge)
if awf.Cache(cacheKey).LoadItems(ttl).Err() == nil {
awf.Logger().Infoln("loading from cache file")
awf.Filter(r.query).Output()
awf.FilterByItemProperty(r.folderPrefixF, alfred.FilterSubtitle).
Filter(r.query).Output()
return nil
}

Expand All @@ -144,12 +146,6 @@ func (r *runtime) run() error {
opts = append(opts, bookmarker.OptionRemoveDuplicates())
}

if r.folderPrefix != "" {
// Note set empty key as to disable saving data into cache
cacheKey = ""
opts = append(opts, bookmarker.OptionFilterByFolder(r.folderPrefix))
}

manager, err := bookmarker.New(opts...)
if err != nil {
return err
Expand Down Expand Up @@ -185,11 +181,46 @@ func (r *runtime) run() error {
}

defer func() {
awf.Filter(r.query).Output()
awf.FilterByItemProperty(r.folderPrefixF, alfred.FilterSubtitle).
Filter(r.query).Output()
}()
return awf.Cache(cacheKey).StoreItems().Err()
}

func fatal(err error) {
awf.Fatal("a fatal error occurred", err.Error())
}

func filterBySubtitle(prefixQuery string) func(subtitle string) bool {
f := func(subtitle string) bool {
// Note: if input is empty return true
if prefixQuery == "" {
return true
}

leftTrimedSubtitle := strings.TrimLeft(subtitle, "[")
idx := strings.LastIndex(leftTrimedSubtitle, "]")
if idx < 0 {
return false
}
folder := leftTrimedSubtitle[:idx]
return hasFolderPrefix(folder, prefixQuery)
}
return f
}

func hasFolderPrefix(folder, prefix string) bool {
folder = strings.ToLower(folder)
folder = strings.ReplaceAll(folder, " ", "")
prefix = strings.ToLower(prefix)
prefix = strings.ReplaceAll(prefix, " ", "")
if !strings.HasPrefix(prefix, "/") {
prefix = "/" + prefix
}

if strings.HasPrefix(folder, prefix) {
return true
}

return strings.HasPrefix(folder+"/", prefix)
}
12 changes: 6 additions & 6 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ func TestRun(t *testing.T) {
filepath: filepath.Join(testdataPath, "empty-results.json"),
},
{
name: "fildter by folder name. return firefox when RemoveDuplicate is true",
name: "filter by folder name from all bookmarks. return firefox",
args: args{
query: "",
folder: "Bookmark Menu",
},
config: &Config{
RemoveDuplicates: true,
RemoveDuplicates: false,
MaxCacheAge: -1,
Firefox: Firefox{
Enable: true,
Expand Down Expand Up @@ -129,9 +129,9 @@ func TestRun(t *testing.T) {
awf.SetEmptyWarning(emptyTitle, emptySubtitle)

r := &runtime{
cfg: tt.config,
query: tt.args.query,
folderPrefix: tt.args.folder,
cfg: tt.config,
query: tt.args.query,
folderPrefixF: filterBySubtitle(tt.args.folder),
}
if err != nil {
t.Fatal(err)
Expand All @@ -147,7 +147,7 @@ func TestRun(t *testing.T) {

got := outBuf.Bytes()
if diff := alfred.DiffOutput(want, got); diff != "" {
t.Errorf("+want -got\n%+v", diff)
t.Errorf("-want +got\n%+v", diff)
}

// automatically update test data
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.16
require (
github.com/frioux/leatherman v0.0.0-20200721002700-06899856e483
github.com/google/go-cmp v0.5.2
github.com/konoui/go-alfred v0.10.0
github.com/konoui/go-alfred v0.11.0
github.com/pierrec/lz4 v2.5.2+incompatible
github.com/spf13/pflag v1.0.3
github.com/spf13/viper v1.7.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konoui/go-alfred v0.10.0 h1:F7k1kfDiQ23Pnr+6TOBLrOkNnCl7PauwnLtVr+lptB4=
github.com/konoui/go-alfred v0.10.0/go.mod h1:S2ZhSnr3TIWBOvi3NeDhFrT0WV4867t6GSYklWznmtA=
github.com/konoui/go-alfred v0.11.0 h1:jmePQ1uwrgLGeTKRvxmwSsEzZcbOl3A6TCzPeBbqju0=
github.com/konoui/go-alfred v0.11.0/go.mod h1:S2ZhSnr3TIWBOvi3NeDhFrT0WV4867t6GSYklWznmtA=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
Expand Down
31 changes: 0 additions & 31 deletions pkg/bookmarker/bookmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package bookmarker

import (
"sort"
"strings"
)

// bookmarkerName is a type of supported browser name
Expand Down Expand Up @@ -60,33 +59,3 @@ func (b Bookmarks) uniqByURI() (uniq Bookmarks) {

return
}

func (b Bookmarks) filterByFolderPrefix(query string) (fb Bookmarks) {
if query == "" {
return b
}

for _, e := range b {
if hasFolderPrefix(e.Folder, query) {
fb = append(fb, e)
}
}

return
}

func hasFolderPrefix(folder, prefix string) bool {
folder = strings.ToLower(folder)
folder = strings.ReplaceAll(folder, " ", "")
prefix = strings.ToLower(prefix)
prefix = strings.ReplaceAll(prefix, " ", "")
if !strings.HasPrefix(prefix, "/") {
prefix = "/" + prefix
}

if strings.HasPrefix(folder, prefix) {
return true
}

return strings.HasPrefix(folder+"/", prefix)
}
44 changes: 0 additions & 44 deletions pkg/bookmarker/bookmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,50 +44,6 @@ func TestBookmarks_UniqByURI(t *testing.T) {
}
}

func TestBookmarks_FilterByFolderPrefix(t *testing.T) {
type args struct {
query string
}
tests := []struct {
name string
args args
options []Option
want Bookmarks
}{
{
name: "if empty string, return all bookmarks",
want: testChromeBookmarks,
options: []Option{
OptionChrome(defaultChromeProfilePath, testProfile),
},
args: args{
query: "",
},
},
{
name: "filter by folder prefix with chrome folder name",
want: testChromeBookmarks,
options: []Option{
OptionFirefox(defaultFirefoxProfilePath, testProfile),
OptionChrome(defaultChromeProfilePath, testProfile),
OptionSafari(),
},
args: args{
query: "Bookmarks bar",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := getTestBookmarks(t, tt.options...)
got := b.filterByFolderPrefix(tt.args.query)
if diff := DiffBookmark(got, tt.want); diff != "" {
t.Errorf("+want/-got: %s", diff)
}
})
}
}

func getTestBookmarks(t *testing.T, opts ...Option) Bookmarks {
bookmarer, err := New(opts...)
if err != nil {
Expand Down
15 changes: 0 additions & 15 deletions pkg/bookmarker/maneger.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import "fmt"
type Manager struct {
bookmarkers map[bookmarkerName]Bookmarker
removeDuplicates bool
folderQuery string
}

// Option is the type to replace default parameters.
Expand Down Expand Up @@ -59,14 +58,6 @@ func OptionRemoveDuplicates() Option {
}
}

// OptionFilterByFolder filter by bookmark folder name
func OptionFilterByFolder(folderQuery string) Option {
return func(m *Manager) error {
m.folderQuery = folderQuery
return nil
}
}

// New is a managed bookmarker to get each bookmarks
func New(opts ...Option) (Bookmarker, error) {
m := &Manager{
Expand Down Expand Up @@ -103,12 +94,6 @@ func (m *Manager) Bookmarks() (Bookmarks, error) {
bookmarks = append(bookmarks, b...)
}

// TODO folder filter should implement in each bookmark for performance
// But there are caching problem. the workflow uses alfred library caching
if q := m.folderQuery; q != "" {
bookmarks = bookmarks.filterByFolderPrefix(q)
}

// Note: execute uniq after folder filter
if m.removeDuplicates {
bookmarks = bookmarks.uniqByURI()
Expand Down

0 comments on commit eb17760

Please sign in to comment.