github.com/kcmerrill/alfred@v0.0.0-20180727171036-06445dcb5e3d/pkg/alfred/taskgroup.go (about)

     1  package alfred
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  	"sync"
     7  )
     8  
     9  // TaskGroup contains a task name and it's arguments
    10  type TaskGroup struct {
    11  	Name string
    12  	Args []string
    13  }
    14  
    15  // ParseTaskGroup takes in a string, and parses it into a TaskGroup
    16  func (t *Task) ParseTaskGroup(group string) []TaskGroup {
    17  	tg := make([]TaskGroup, 0)
    18  	group = strings.TrimSpace(group)
    19  
    20  	if group == "" {
    21  		return tg
    22  	}
    23  
    24  	// TODO: This is pretty terrible ... but until I get something better it stays
    25  	// I need to research tokenizers
    26  	if strings.Index(group, "\n") == -1 && !strings.Contains(group, "(") {
    27  		// This means we have a regular space delimited list, probably
    28  		if strings.HasPrefix(group, "!") {
    29  			tg = append(tg, TaskGroup{Name: group, Args: []string{}})
    30  		} else {
    31  			tasks := strings.Split(group, " ")
    32  			for _, task := range tasks {
    33  				tg = append(tg, TaskGroup{Name: task, Args: []string{}})
    34  			}
    35  		}
    36  	} else {
    37  		// mix and match here
    38  		tasks := strings.Split(group, "\n")
    39  		for _, task := range tasks {
    40  			re := regexp.MustCompile(`(.*?)\((.*?)\)`)
    41  			results := re.FindStringSubmatch(task)
    42  			if len(results) == 0 || strings.HasPrefix(task, "!") {
    43  				tg = append(tg, TaskGroup{Name: strings.TrimSpace(task), Args: []string{}})
    44  			} else {
    45  				args := strings.Split(results[2], ",")
    46  				for idx, a := range args {
    47  					// trim the extra whitespace
    48  					args[idx] = strings.TrimSpace(a)
    49  				}
    50  				tg = append(tg, TaskGroup{Name: strings.TrimSpace(results[1]), Args: args})
    51  			}
    52  		}
    53  	}
    54  	return tg
    55  }
    56  
    57  func execTaskGroup(taskGroups []TaskGroup, task Task, context *Context, tasks map[string]Task) {
    58  	for _, tg := range taskGroups {
    59  		c := copyContex(context, translateArgs(tg.Args, context))
    60  		NewTask(tg.Name, &c, tasks)
    61  	}
    62  }
    63  
    64  func goExecTaskGroup(taskGroups []TaskGroup, task Task, context *Context, tasks map[string]Task) {
    65  	c := copyContex(context, []string{})
    66  	var wg sync.WaitGroup
    67  	for _, tg := range taskGroups {
    68  		wg.Add(1)
    69  		go func(theTG TaskGroup, stableContext Context, tasks map[string]Task) {
    70  			copyOfContext := copyContex(&stableContext, translateArgs(theTG.Args, &stableContext))
    71  			NewTask(theTG.Name, &copyOfContext, tasks)
    72  			wg.Done()
    73  		}(tg, c, tasks)
    74  	}
    75  	wg.Wait()
    76  }