oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package pi
2
3import (
4 "encoding/json"
5 "strings"
6)
7
8// Redacted stands where a launch's key was.
9const Redacted = "[redacted]"
10
11// Redactor takes a launch's key out of what the harness says (a step can
12// read the key, connectors spec §2.1, so it can echo it): every string
13// the runner logs or reports from Pi passes through it. Stream handles
14// text that arrives in pieces, holding back an end that could be the
15// start of the key.
16type Redactor struct {
17 forms []string
18 pending string
19}
20
21// NewRedactor redacts key, as itself and as it appears inside JSON.
22func NewRedactor(key string) *Redactor {
23 r := &Redactor{}
24 if key == "" {
25 return r
26 }
27 r.forms = []string{key}
28 if raw, err := json.Marshal(key); err == nil {
29 if quoted := string(raw[1 : len(raw)-1]); quoted != key {
30 r.forms = append(r.forms, quoted)
31 }
32 }
33 return r
34}
35
36// Redact replaces every whole occurrence.
37func (r *Redactor) Redact(s string) string {
38 for _, f := range r.forms {
39 s = strings.ReplaceAll(s, f, Redacted)
40 }
41 return s
42}
43
44// RedactJSON redacts a JSON document's text (the key inside a string
45// value keeps it valid JSON).
46func (r *Redactor) RedactJSON(raw json.RawMessage) json.RawMessage {
47 return json.RawMessage(r.Redact(string(raw)))
48}
49
50// Stream takes the next piece of a text and returns what can be shown
51// now: everything but an end that could still become the key.
52func (r *Redactor) Stream(piece string) string {
53 if len(r.forms) == 0 {
54 return piece
55 }
56 s := r.Redact(r.pending + piece)
57 hold := 0
58 for _, f := range r.forms {
59 for k := min(len(f)-1, len(s)); k > hold; k-- {
60 if strings.HasSuffix(s, f[:k]) {
61 hold = k
62 break
63 }
64 }
65 }
66 r.pending = s[len(s)-hold:]
67 return s[:len(s)-hold]
68}
69
70// Flush returns what Stream held back, once the text has ended.
71func (r *Redactor) Flush() string {
72 s := r.pending
73 r.pending = ""
74 return s
75}
76