/* * Copyright (C) 2021 Arsen Musayelyan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "os" "regexp" "strconv" ) // Attempt to match function in config to provided string func getAction(c *Config, tts *string) (*Action, bool) { // For every action in config for _, action := range c.Actions { // Attempt to compile configured regular expression regex, err := regexp.Compile(action.Phrase) if err != nil { return nil, false } // Check if string matches action matched := regex.MatchString(*tts) if matched { return &action, true } } return nil, false } // Perform action with input func performAction(a *Action, tts *string, plugins map[string]pluginFunc) (bool, error) { // Attempt to compile configured regular expression regex, err := regexp.Compile(a.Phrase) if err != nil { return false, err } // Find string submatches in string using regular expression match := regex.FindStringSubmatch(*tts) strExpanded := false // Expand instances of $var in action input retCmd := os.Expand(a.Input, func(in string) string { strExpanded = true // Attempt to convert string to integer inputInt, err := strconv.Atoi(in) // If successful if err == nil { // If index nonexistent, return empty string if len(match) <= inputInt { return "" } // Return match at index return match[inputInt] } // Get subexpression index for input string subIndex := regex.SubexpIndex(in) // If regex contains subexpression with specified name and match contains index if subIndex != -1 && len(match) >= subIndex { // Return string matched at index return match[subIndex] } // If nothing worked, put variable back return "$" + in }) // If output remained the same and string was expanded if a.Input == retCmd && strExpanded { return false, nil } // If type of action is noop, do nothing and return if a.Type == "noop" { return true, nil } // Run plugin with input plugins[a.Type](retCmd, a.Data) return true, nil }