File: main.go

package info (click to toggle)
golang-github-kisom-goutils 0.0~git20161101.0.858c9cb-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 384 kB
  • ctags: 331
  • sloc: makefile: 6
file content (91 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download | duplicates (3)
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
package main

import (
	"bytes"
	"encoding/pem"
	"flag"
	"fmt"
	"io"
	"os"

	"github.com/kisom/goutils/assert"
	"github.com/kisom/goutils/die"
	"github.com/kisom/goutils/lib"
)

func usage(w io.Writer) {
	fmt.Fprintf(w, `Usage: %s [-h] -t type sources

	Flags:
		-h	Display this help message.
		-t type	Set the PEM type. This is required.

	Sources may be a list of files or a single '-'. A single dash
	(or no arguments) will cause %s to use standard input.
`, lib.ProgName(), lib.ProgName())
}

func init() {
	flag.Usage = func() { usage(os.Stderr) }
}

func copyFile(path string, buf *bytes.Buffer) error {
	assert.Bool(buf != nil, "buffer should not be nil")
	file, err := os.Open(path)
	if err != nil {
		return err
	}

	_, err = io.Copy(buf, file)
	file.Close()
	return err
}

func main() {
	var pemType string
	flag.StringVar(&pemType, "t", "", "Specify the `PEM type`.")
	flag.Parse()

	die.When(len(pemType) == 0, "no PEM type specified.")

	buf := &bytes.Buffer{}
	argc := flag.NArg()
	var err error

	switch {
	case argc == 0:
		_, err = io.Copy(buf, os.Stdin)
		if err != nil {
			lib.Err(lib.ExitFailure, err, "failed to read input")
		}
	case argc == 1:
		path := flag.Arg(0)
		if path == "-" {
			_, err = io.Copy(buf, os.Stdin)
		} else {
			err = copyFile(path, buf)
		}

		if err != nil {
			lib.Err(lib.ExitFailure, err, "failed to read input")
		}
	case argc > 1:
		for i := 0; i < argc; i++ {
			path := flag.Arg(i)
			err = copyFile(path, buf)
			if err != nil {
				lib.Err(lib.ExitFailure, err, "reading file failed")
			}
		}
	default:
		panic("shouldn't be here")
	}

	p := &pem.Block{
		Type:  pemType,
		Bytes: buf.Bytes(),
	}

	encoded := string(pem.EncodeToMemory(p))
	fmt.Print(encoded)
}