Adds the grep parsing and ticket creation

This commit is contained in:
Miguel de la Cruz 2020-02-29 13:00:40 +01:00
parent dfd8aeffa7
commit 18953f9372
3 changed files with 72 additions and 10 deletions

View file

@ -1,17 +1,24 @@
package cmd
import (
"fmt"
"os/exec"
"strconv"
"strings"
"github.com/spf13/cobra"
"git.ctrlz.es/mgdelacroix/campaigner/model"
)
const defaultGrepOpts = "-nrFI"
func AddCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: "Adds tickets to the campaign",
Args: cobra.NoArgs,
RunE: addCmdF,
Run: addCmdF,
}
cmd.Flags().StringP("dir", "d", "", "directory containing the source code")
@ -24,15 +31,69 @@ func AddCmd() *cobra.Command {
return cmd
}
func RunGrep(dir string, strs []string, caseInsensitive bool) ([]model.Ticket, error) {
// grep -nrI TEXT .
// -i as well with case insensitive
return nil, nil
func parseLine(line string) (*model.Ticket, error) {
parts := strings.Split(line, ":")
if len(parts) < 3 {
return nil, fmt.Errorf("cannot parse line: %s", line)
}
func addCmdF(cmd *cobra.Command, _ []string) error {
// either govet or grep
return nil
filename := parts[0]
lineNo, err := strconv.Atoi(parts[1])
if err != nil {
return nil, err
}
text := strings.Join(parts[2:], "")
return &model.Ticket{filename, lineNo, text}, nil
}
func RunGrep(dir, str string, caseInsensitive bool) ([]*model.Ticket, error) {
opts := defaultGrepOpts
if caseInsensitive {
opts = opts + "i"
}
out, err := exec.Command("grep", opts, str, dir).Output()
if err != nil {
return nil, err
}
tickets := []*model.Ticket{}
for _, line := range strings.Split(string(out), "\n") {
// ToDo: get and check error
ticket, _ := parseLine(line)
if ticket != nil {
tickets = append(tickets, ticket)
}
}
return tickets, nil
}
func RunGreps(dir string, strs []string, caseInsensitive bool) ([]*model.Ticket, error) {
tickets := []*model.Ticket{}
for _, str := range strs {
results, err := RunGrep(dir, str, caseInsensitive)
if err != nil {
return nil, err
}
tickets = append(tickets, results...)
}
return tickets, nil
}
func addCmdF(cmd *cobra.Command, _ []string) {
dir, _ := cmd.Flags().GetString("dir")
grepStrs, _ := cmd.Flags().GetStringSlice("grep")
caseInsensitive, _ := cmd.Flags().GetBool("case-insensitive")
tickets, err := RunGreps(dir, grepStrs, caseInsensitive)
if err != nil {
ErrorAndExit(cmd, err)
}
for _, ticket := range tickets {
fmt.Printf("%+v\n", ticket)
}
}

View file

@ -2,4 +2,5 @@ package model
type Campaign struct {
Epic string `json:"epic"`
Tickets []*Ticket `json:"tickets"`
}

View file

@ -2,6 +2,6 @@ package model
type Ticket struct {
Filename string `json:"filename"`
Line int `json:"line"`
LineNo int `json:"line_no"`
Text string `json:"text"` // needed??
}