From d01892150eed9d58210eb40b7c005d5fa8e93238 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Sat, 1 Oct 2016 21:56:29 +0200 Subject: rework program flow This commit is a complete rebuild of pkictl. Before everything was all over the place and adding new commands was kind of a hassle. Now each command has its own file and can be adjusted on a command basis. Options are still used by the same name, but can now use different descriptions. --- io.go | 62 ++++++++++++++++++++++++++++---------------------------------- 1 file changed, 28 insertions(+), 34 deletions(-) (limited to 'io.go') diff --git a/io.go b/io.go index 56cc689..0809259 100644 --- a/io.go +++ b/io.go @@ -1,45 +1,39 @@ package main -// handle all io and de/encoding of data - import ( - "encoding/pem" - "errors" - "io/ioutil" -) - -var ( - ErrBlockNotFound = errors.New("block not found") + "fmt" + "io" + "os" ) -// load a pem section from a file -func readSectionFromFile(path, btype string) ([]byte, error) { - raw, err := readFile(path) - if err != nil { - return raw, err +// Open a path for writing +func openOutput(path string) (io.WriteCloser, error) { + var ( + err error + out io.WriteCloser + ) + if path == "stdout" { + out = os.Stdout + } else { + out, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0700) + if err != nil { + return nil, err + } } - - return decodeSection(raw, btype) + return out, nil } -// read a file completely and report possible errors -func readFile(path string) ([]byte, error) { - raw, err := ioutil.ReadFile(path) - if err != nil { - return EmptyByteArray, err +// Open a path for reading the content +func openInput(path string) (io.ReadCloser, error) { + if path == "" { + return nil, fmt.Errorf("empty path is invalid") } - return raw, nil -} - -// decode a pem encoded file and search for the specified section -func decodeSection(data []byte, btype string) ([]byte, error) { - rest := data - for len(rest) > 0 { - var block *pem.Block - block, rest = pem.Decode(rest) - if block.Type == btype { - return block.Bytes, nil - } + var err error + var in io.ReadCloser + if path == "stdin" { + in = os.Stdin + } else { + in, err = os.Open(path) } - return EmptyByteArray, ErrBlockNotFound + return in, err } -- cgit v1.2.3-70-g09d2