summaryrefslogtreecommitdiff
path: root/internal/parser/parser.go
blob: 860baa33bf5f2b01cf609e784e8d6df76832adac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package parser

import (
	"context"
	"fmt"
	"io"
	"os"

	"epimetheus/internal/metrics"
)

// Parser defines the interface for metric parsers.
type Parser interface {
	Parse(ctx context.Context, reader io.Reader) ([]metrics.Sample, error)
}

// ParseFile parses metrics from a file.
func ParseFile(ctx context.Context, filename, format string) ([]metrics.Sample, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to open file: %w", err)
	}
	defer file.Close()

	return parseWithFormat(ctx, file, format)
}

// ParseStdin parses metrics from standard input.
func ParseStdin(ctx context.Context, format string) ([]metrics.Sample, error) {
	return parseWithFormat(ctx, os.Stdin, format)
}

// parseWithFormat parses metrics using the specified format.
func parseWithFormat(ctx context.Context, reader io.Reader, format string) ([]metrics.Sample, error) {
	var parser Parser

	switch format {
	case "csv":
		parser = NewCSVParser()
	case "json":
		parser = NewJSONParser()
	default:
		return nil, fmt.Errorf("unsupported format: %s (use csv or json)", format)
	}

	samples, err := parser.Parse(ctx, reader)
	if err != nil {
		return nil, fmt.Errorf("failed to parse metrics: %w", err)
	}

	if len(samples) == 0 {
		return nil, fmt.Errorf("no valid samples found")
	}

	return samples, nil
}