Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions cmd/name_to_tag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package cmd

import (
"context"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/corvus-ch/bilocation/tag"
"golang.org/x/sync/errgroup"
"gopkg.in/alecthomas/kingpin.v2"
)

var test bool

// NameToTag registers the name to tag sub command to the application.
func NameToTag(app *kingpin.Application, cfg *config) {
c := app.Command("ntt", "tags files based on their names")
c.Action(func(_ *kingpin.ParseContext) error {
log := cfg.Log()
for path := range findFiles(cfg) {
tags, err := tag.NewTagSet([]byte{})
if err != nil {
return err
}
for _, rule := range cfg.Tags() {
parts := strings.SplitN(rule, "=", 2)
re, err := regexp.Compile(parts[1])
if err != nil {
return err
}
matches := re.FindStringSubmatch(path)
if len(matches) < 1 {
continue
}
tags.Add(matches[1], parts[0])
}
if test {
log.Infof("%s %v", path, tags)
} else if tags.Size() > 0 {
if err := tag.Write(path, tags); err != nil {
return err
}
}
}
return nil
})

c.Flag("path", "path to the directory containing the files to be tagged").
Short('C').
Default(".").
ExistingDirVar(&cfg.root)
c.Flag("dry-run", "print the result and does not touch the files").
Short('n').
BoolVar(&test)
c.Arg("rule", "a list of tag names and their regexp").
Required().
StringsVar(&cfg.tags)
}

func findFiles(cfg *config) chan string {
g, ctx := errgroup.WithContext(context.Background())
ch := make(chan string, 100)
g.Go(func() error {
defer close(ch)

return filepath.Walk(cfg.Root(), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}

select {
case ch <- path:
case <-ctx.Done():
return ctx.Err()
}
return nil
})

})

return ch
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func App(log logr.Logger) *kingpin.Application {
cmd.Inspect(app, cfg)
cmd.Search(app, cfg)
cmd.Summary(app, cfg)
cmd.NameToTag(app, cfg)

return app
}
Expand Down
14 changes: 14 additions & 0 deletions tag/set.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package tag

import (
"fmt"
"strings"

"github.com/corvus-ch/bilocation/tag/internal"
"github.com/golang/protobuf/proto"
)
Expand Down Expand Up @@ -104,3 +107,14 @@ func (s Set) Bytes() ([]byte, error) {
}
return proto.Marshal(set)
}

func (s Set) String() string {
var pairs []string
for value, keys := range s {
for key := range keys {
pairs = append(pairs, fmt.Sprintf("%s='%s'", key, value))
}
}

return strings.Join(pairs, " ")
}