Commit b354c1c2 authored by Boris Mühmer's avatar Boris Mühmer
Browse files

use regexp for match pattern

parent eb8c20f8
Loading
Loading
Loading
Loading
+24 −7
Original line number Diff line number Diff line
@@ -3,7 +3,7 @@ package get
import (
	"fmt"
	"io"
	"strings"
	"regexp"
	"sync"

	"repositories.muehmer.net/bsmrgo/get/mb"
@@ -18,6 +18,19 @@ const (
	Err
)

func (c Channel) String() string {
	switch c {
	case In:
		return "In"
	case Out:
		return "Out"
	case Err:
		return "Err"
	default:
		return fmt.Sprintf("unknown channel %d", uint(c))
	}
}

type Expect struct {
	stdin           io.Reader
	stdout          io.Writer
@@ -28,8 +41,8 @@ type Expect struct {
}

type PatternValue struct {
	p string
	v string
	pattern *regexp.Regexp
	value   string
}

type ChannelPatternValue struct {
@@ -75,10 +88,14 @@ func (x *Expect) Stderr() io.Writer {
	return x.stderr
}

func (x *Expect) Match(c Channel, match, text string) error {
func (x *Expect) Match(c Channel, pattern, text string) error {
	match, err := regexp.Compile(pattern)
	if err != nil {
		return err
	}
	x.matchStream <- ChannelPatternValue{
		c: c,
		m: PatternValue{p: match, v: text},
		m: PatternValue{pattern: match, value: text},
	}
	return nil
}
@@ -232,12 +249,12 @@ func process(
			}
			for _, m := range matches {
				s := string(bytes)
				if !strings.Contains(s, m.p) {
				if !m.pattern.MatchString(s) {
					continue
				}
				go func(s string) {
					stringStream <- s
				}(m.v)
				}(m.value)
				break
			}
		}
+13 −3
Original line number Diff line number Diff line
@@ -22,9 +22,19 @@ func TestPasswdChange(t *testing.T) {
	}
	defer x.Close()

	x.Match(Err, "Current password", lp2Pass)
	x.Match(Err, "New password", lpNPass)
	x.Match(Err, "Retype new password", lpNPass)
	for _, cpv := range []struct {
		c Channel
		p string
		v string
	}{
		{c: Err, p: `^[cC]urrent password`, v: lp2Pass},
		{c: Err, p: `^[nN]ew password`, v: lpNPass},
		{c: Err, p: `^[rR]etype new password`, v: lpNPass},
	} {
		if err := x.Match(cpv.c, cpv.p, cpv.v); err != nil {
			t.Errorf("x.Match(%s,%q,%q) failed with: %s", cpv.c, cpv.p, cpv.v, err)
		}
	}

	p, err := passwd.New(x.Stdin(), x.Stdout(), x.Stderr(), lp2User)
	if err != nil {