| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/pem" |
| 6 |
"flag" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"os" |
| 10 |
|
| 11 |
"github.com/kisom/goutils/assert" |
| 12 |
"github.com/kisom/goutils/die" |
| 13 |
"github.com/kisom/goutils/lib" |
| 14 |
) |
| 15 |
|
| 16 |
func usage(w io.Writer) { |
| 17 |
fmt.Fprintf(w, `Usage: %s [-h] -t type sources |
| 18 |
|
| 19 |
Flags: |
| 20 |
-h Display this help message. |
| 21 |
-t type Set the PEM type. This is required. |
| 22 |
|
| 23 |
Sources may be a list of files or a single '-'. A single dash |
| 24 |
(or no arguments) will cause %s to use standard input. |
| 25 |
`, lib.ProgName(), lib.ProgName()) |
| 26 |
} |
| 27 |
|
| 28 |
func init() { |
| 29 |
flag.Usage = func() { usage(os.Stderr) } |
| 30 |
} |
| 31 |
|
| 32 |
func copyFile(path string, buf *bytes.Buffer) error { |
| 33 |
assert.Bool(buf != nil, "buffer should not be nil") |
| 34 |
file, err := os.Open(path) |
| 35 |
if err != nil { |
| 36 |
return err |
| 37 |
} |
| 38 |
|
| 39 |
_, err = io.Copy(buf, file) |
| 40 |
file.Close() |
| 41 |
return err |
| 42 |
} |
| 43 |
|
| 44 |
func main() { |
| 45 |
var pemType string |
| 46 |
flag.StringVar(&pemType, "t", "", "Specify the `PEM type`.") |
| 47 |
flag.Parse() |
| 48 |
|
| 49 |
die.When(len(pemType) == 0, "no PEM type specified.") |
| 50 |
|
| 51 |
buf := &bytes.Buffer{} |
| 52 |
argc := flag.NArg() |
| 53 |
var err error |
| 54 |
|
| 55 |
switch { |
| 56 |
case argc == 0: |
| 57 |
_, err = io.Copy(buf, os.Stdin) |
| 58 |
if err != nil { |
| 59 |
lib.Err(lib.ExitFailure, err, "failed to read input") |
| 60 |
} |
| 61 |
case argc == 1: |
| 62 |
path := flag.Arg(0) |
| 63 |
if path == "-" { |
| 64 |
_, err = io.Copy(buf, os.Stdin) |
| 65 |
} else { |
| 66 |
err = copyFile(path, buf) |
| 67 |
} |
| 68 |
|
| 69 |
if err != nil { |
| 70 |
lib.Err(lib.ExitFailure, err, "failed to read input") |
| 71 |
} |
| 72 |
case argc > 1: |
| 73 |
for i := 0; i < argc; i++ { |
| 74 |
path := flag.Arg(i) |
| 75 |
err = copyFile(path, buf) |
| 76 |
if err != nil { |
| 77 |
lib.Err(lib.ExitFailure, err, "reading file failed") |
| 78 |
} |
| 79 |
} |
| 80 |
default: |
| 81 |
panic("shouldn't be here") |
| 82 |
} |
| 83 |
|
| 84 |
p := &pem.Block{ |
| 85 |
Type: pemType, |
| 86 |
Bytes: buf.Bytes(), |
| 87 |
} |
| 88 |
|
| 89 |
encoded := string(pem.EncodeToMemory(p)) |
| 90 |
fmt.Print(encoded) |
| 91 |
} |