Skip to content

Commit 166e88e

Browse files
committed
Add Unit to create_text and parse_text
Signed-off-by: Arianna Vespri <[email protected]>
1 parent 90aaa11 commit 166e88e

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

expfmt/text_create.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,33 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
148148
if err != nil {
149149
return
150150
}
151+
if in.Unit != nil {
152+
n, err = w.WriteString("# UNIT ")
153+
written += n
154+
if err != nil {
155+
return
156+
}
157+
n, err = w.WriteString(name)
158+
written += n
159+
if err != nil {
160+
return
161+
}
162+
err = w.WriteByte(' ')
163+
written++
164+
if err != nil {
165+
return
166+
}
167+
n, err = writeEscapedString(w, *in.Unit, false)
168+
written += n
169+
if err != nil {
170+
return
171+
}
172+
err = w.WriteByte('\n')
173+
written++
174+
if err != nil {
175+
return
176+
}
177+
}
151178

152179
// Finally the samples, one line for each.
153180
for _, metric := range in.Metric {

expfmt/text_parse.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ func (p *TextParser) startComment() stateFn {
178178
return p.startOfLine
179179
}
180180
keyword := p.currentToken.String()
181-
if keyword != "HELP" && keyword != "TYPE" {
181+
if keyword != "HELP" && keyword != "TYPE" && keyword != "UNIT" {
182182
// Generic comment, ignore by fast forwarding to end of line.
183183
for p.currentByte != '\n' {
184184
if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
@@ -217,6 +217,8 @@ func (p *TextParser) startComment() stateFn {
217217
return p.readingHelp
218218
case "TYPE":
219219
return p.readingType
220+
case "UNIT":
221+
return p.readingUnit
220222
}
221223
panic(fmt.Sprintf("code error: unexpected keyword %q", keyword))
222224
}
@@ -528,6 +530,21 @@ func (p *TextParser) readingType() stateFn {
528530
return p.startOfLine
529531
}
530532

533+
// readingUnit represents the state where the last byte read (now in
534+
// p.currentByte) is the first byte of the docstring after 'UNIT'.
535+
func (p *TextParser) readingUnit() stateFn {
536+
if p.currentMF.Unit != nil {
537+
p.parseError(fmt.Sprintf("second UNIT line for metric name %q", p.currentMF.GetName()))
538+
return nil
539+
}
540+
// Rest of line is the docstring.
541+
if p.readTokenUntilNewline(true); p.err != nil {
542+
return nil // Unexpected end of input.
543+
}
544+
p.currentMF.Unit = proto.String(p.currentToken.String())
545+
return p.startOfLine
546+
}
547+
531548
// parseError sets p.err to a ParseError at the current line with the given
532549
// message.
533550
func (p *TextParser) parseError(msg string) {

0 commit comments

Comments
 (0)