aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 2231f97c2a1f8599a0fccba5350a0b8c76bf2a8a (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main

import (
	"archive/tar"
	"bufio"
	"compress/gzip"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"

	flag "github.com/spf13/pflag"
)

func main() {
	var (
		url          = flag.StringP("url", "u", "", "Url to the APKINDEX.tar.gz")
		output       = flag.StringP("output", "o", "index.md", "Output path")
		templateType = flag.StringP("template-type", "t", "text", "Template system to be used, options: html, text")
		templateFile = flag.StringP("template-file", "f", "text", "Template file to be used")
	)
	flag.Parse()

	err := run(
		*url,
		*output,
		*templateType,
		*templateFile,
	)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func run(
	url string,
	output string,
	templateType string,
	templateFile string,
) error {

	tarStream, err := fechIndex(url)
	if err != nil {
		return fmt.Errorf("Error fecthing index file: %w", err)
	}

	defer tarStream.Close()

	archive, err := gzip.NewReader(tarStream)
	if err != nil {
		return fmt.Errorf("Error creating gzip reader: %w", err)
	}

	tr := tar.NewReader(archive)

	for {
		h, err := tr.Next()
		if err != nil {
			return fmt.Errorf("Error reading next tar entry: %w", err)
		}

		if h.FileInfo().Name() == "APKINDEX" {
			break
		}
	}

	var (
		s       = bufio.NewScanner(tr)
		entries = make([]*Entry, 0)
		lines   = make([]string, 0)
	)

	for s.Scan() {
		l := s.Text()
		if l == "" {
			entry := Parse(lines)
			entries = append(entries, entry)
			lines = make([]string, 0)
		} else {
			lines = append(lines, l)
		}
	}

	outputFile, err := getOutputFile(output)
	if err != nil {
		return fmt.Errorf("Error openning output file: %w", err)
	}

	tmpl, err := GetTemplate(templateType, templateFile)
	if err != nil {
		return fmt.Errorf("Error loading template file: %w", err)
	}

	err = tmpl.Execute(outputFile, entries)
	if err != nil {
		return fmt.Errorf("Error executing template: %w", err)
	}
	return nil
}

func getOutputFile(output string) (*os.File, error) {
	if output != "" {
		outputFile, err := os.Create(output)
		if err != nil {
			return nil, err
		}
		return outputFile, nil
	} else {
		return os.Stdout, nil
	}
}

func fechIndex(url string) (io.ReadCloser, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, errors.New("Http error " + strconv.Itoa(resp.StatusCode))
	}

	return resp.Body, nil
}