~samwhited/query

0e3d4fc2cf856f333d2e83957ee1c94545524500 — Sam Whited 1 year, 6 months ago 03f0334 v0.0.1
Initial public release
7 files changed, 342 insertions(+), 0 deletions(-)

A CONTRIBUTING.md
A LICENSE
A README.md
A go.mod
A go.sum
A query.go
A query_test.go
A CONTRIBUTING.md => CONTRIBUTING.md +31 -0
@@ 0,0 1,31 @@
## Submitting Patches

To submit a patch, first learn to use `git send-email` by reading
[git-send-email.io], then read the SourceHut [mailing list etiquette] guide.
You can send patches to my general purpose patches [mailing list].

Please prefix the subject with `[PATCH query]`.
To configure your checkout of this repo to always use the correct prefix and
send to the correct list cd into the repo and run:

    git config sendemail.to ~samwhited/patches@lists.sr.ht
    git config format.subjectPrefix 'PATCH query'

[git-send-email.io]: https://git-send-email.io/
[mailing list etiquette]: https://man.sr.ht/lists.sr.ht/etiquette.md
[mailing list]: https://lists.sr.ht/~samwhited/patches


## License

Licensed under the BSD 2 Clause License ([LICENSE] or
https://opensource.org/licenses/BSD-2-Clause)

[LICENSE]: https://git.sr.ht/~samwhited/query/tree/master/LICENSE.md


### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you shall be licensed as above, without any
additional terms or conditions.

A LICENSE => LICENSE +23 -0
@@ 0,0 1,23 @@
Copyright © 2014 The Soquee Contributors.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

A README.md => README.md +22 -0
@@ 0,0 1,22 @@
# query

Package **`query`** parses the simple query language used for full text search
in the Soquee issue tracker.

```go
import (
	"code.soquee.net/query"
)
```


## License

The package may be used under the terms of the BSD 2-Clause License a copy of
which may be found in the [`LICENSE`] file.

Unless you explicitly state otherwise, any contribution submitted for inclusion
in the work by you shall be licensed as above, without any additional terms or
conditions.

[`LICENSE`]: ./LICENSE

A go.mod => go.mod +5 -0
@@ 0,0 1,5 @@
module code.soquee.net/query

go 1.11

require golang.org/x/text v0.3.2

A go.sum => go.sum +3 -0
@@ 0,0 1,3 @@
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

A query.go => query.go +166 -0
@@ 0,0 1,166 @@
// Package query is used to parse the simple query language used by Soquee.
package query // import "code.soquee.net/query"

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"

	"golang.org/x/text/secure/precis"
)

// IssueStatus represents the status of an issue (closed, open or any).
type IssueStatus int

// A collection of issue statuses.
// Issues may be open or closed, and, in this special case "Any" which means
// "either of those".
const (
	StatusAny IssueStatus = iota
	StatusClosed
	StatusOpen
)

// Query contains the parsed query string split into fields.
// This struct may grow over time and the field order is not part the package
// stability guarantee.
//
// TSVector is a PostgreSQL compatible full text search string.
// It is not guaranteed to be safe from SQL injection and should always be
// parameterized.
type Query struct {
	Status   IssueStatus
	TSVector string
	Assignee string
	Limit    int
	Labels   []string
}

// String parses a query from a string.
func String(q string) *Query {
	/* #nosec */
	parsed, _ := Parse(strings.NewReader(q))
	return parsed
}

// Bytes parses a query from a byte slice.
func Bytes(q []byte) *Query {
	/* #nosec */
	parsed, _ := Parse(bytes.NewReader(q))
	return parsed
}

func isSkipable(r rune) bool {
	return unicode.IsSpace(r) ||
		r == '!' ||
		r == '|' ||
		r == '&' ||
		r == '(' ||
		r == ')'
}

// scanTokens is a copy of bufio.ScanWords except with the isSpace function
// replaced by one that also skips various tsquery operators.
func scanTokens(data []byte, atEOF bool) (advance int, token []byte, err error) {
	start := 0

	// Skip leading spaces.
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSkipable(r) {
			break
		}
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSkipable(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return start, nil, nil
}

const (
	prefixStatus   = "status:"
	prefixLabel    = "label:"
	prefixLimit    = "limit:"
	prefixAssignee = "assignee:"
)

// Parse parses the query string from r and returns a parsed representation.
func Parse(r io.Reader) (*Query, error) {
	parsed := &Query{}
	w := new(strings.Builder)
	s := bufio.NewScanner(r)
	s.Split(scanTokens)

	sep := ""
	no := ""
	for s.Scan() {
		tok := s.Text()
		if idx := strings.IndexByte(tok, ':'); idx > -1 {
			switch tok[:idx+1] {
			case prefixAssignee:
				/* #nosec */
				parsed.Assignee, _ = precis.UsernameCaseMapped.String(tok[len(prefixAssignee):])
				continue
			case prefixLimit:
				/* #nosec */
				parsed.Limit, _ = strconv.Atoi(tok[len(prefixLimit):])
				continue
			case prefixLabel:
				l := tok[len(prefixLabel):]
				if l == "" {
					continue
				}
				parsed.Labels = append(parsed.Labels, l)
				continue
			case prefixStatus:
				switch tok[len(prefixStatus):] {
				case "open":
					parsed.Status = StatusOpen
				case "closed":
					parsed.Status = StatusClosed
				case "any":
					parsed.Status = StatusAny
				default:
				}
				continue
			}
			continue
		}
		t := strings.TrimPrefix(tok, "-")
		if t == "" {
			continue
		}
		if tok != t {
			no = "!"
		}
		fmt.Fprintf(w, "%s%s%s", sep, no, t)
		no = ""
		sep = "&"
	}
	parsed.TSVector = w.String()
	switch {
	case parsed.Limit == 0:
		parsed.Limit = 15
	case parsed.Limit < 10:
		parsed.Limit = 10
	case parsed.Limit > 100:
		parsed.Limit = 100
	}
	return parsed, s.Err()
}

A query_test.go => query_test.go +92 -0
@@ 0,0 1,92 @@
package query_test

import (
	"strconv"
	"strings"
	"testing"

	"code.soquee.net/query"
)

var queryTests = [...]struct {
	in       string
	out      string
	status   query.IssueStatus
	limit    int
	assignee string
	labels   string
}{
	0:  {},
	1:  {in: " &| !(\t)  ", out: ""},
	2:  {in: "a  test\tstatus:a", out: "a&test", status: query.StatusAny},
	3:  {in: "-a t-est- of -time status:open", out: "!a&t-est-&of&!time", status: query.StatusOpen},
	4:  {in: "- test", out: "test"},
	5:  {in: "new - status:closed test", out: "new&test", status: query.StatusClosed},
	6:  {in: "status:any test -", out: "test"},
	7:  {in: "status:open another:bad", status: query.StatusOpen},
	8:  {in: "status:open another:bad assignee:me label:a label:b label: ", assignee: "me", status: query.StatusOpen, labels: "a,b"},
	9:  {in: "limit:80", limit: 80},
	10: {in: "limit:110", limit: 100},
	11: {in: "limit:-1", limit: 10},
	12: {in: "status:open status:bad", status: query.StatusOpen},
	13: {in: "status:open status:any", status: query.StatusAny},
}

func doTests(t *testing.T, f func(string) *query.Query) {
	for i, tc := range queryTests {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			parsed := f(tc.in)
			if parsed.TSVector != tc.out {
				t.Errorf("Unexpected output: want=%q, got=%q", tc.out, parsed.TSVector)
			}
			if parsed.Status != tc.status {
				t.Errorf("Unexpected status: want=%q, got=%q", tc.status, parsed.Status)
			}
			if labels := strings.Join(parsed.Labels, ","); labels != tc.labels {
				t.Errorf("Unexpected labels: want=%q, got=%q", tc.labels, labels)
			}
			if tc.limit == 0 {
				tc.limit = 15
			}
			if parsed.Limit != tc.limit {
				t.Errorf("Unexpected limit: want=%d, got=%d", tc.limit, parsed.Limit)
			}
			if parsed.Assignee != tc.assignee {
				t.Errorf("Unexpected assignee: want=%q, got=%q", tc.assignee, parsed.Assignee)
			}
		})
	}
}

func TestQueryString(t *testing.T) {
	doTests(t, query.String)
}

func TestQueryBytes(t *testing.T) {
	doTests(t, func(q string) *query.Query {
		return query.Bytes([]byte(q))
	})
}

const errText = "Bad err"

type errReader struct{}

func (errReader) Error() string {
	return errText
}

func (e errReader) Read([]byte) (int, error) {
	return 0, e
}

func TestBadRead(t *testing.T) {
	b := new(strings.Builder)
	_, err := query.Parse(errReader{})
	if err.Error() != errText {
		t.Errorf("Unexpected error: want=%q, got=%q", errText, err)
	}
	if s := b.String(); s != "" {
		t.Errorf("Unexpected write to buffer: %q", s)
	}
}