options.go 1.32 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
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
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package flags

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// Options stores options for the config commands
type Options struct {
	Config  string
	Output  string
	InPlace bool
}

// Validate checks whether the options are valid.
func (o Options) Validate() error {
	if o.InPlace && o.Output != "" {
		return fmt.Errorf("cannot specify both --in-place and --output")
	}

	return nil
}

// GetOutput returns the effective output
func (o Options) GetOutput() string {
	if o.InPlace {
		return o.Config
	}

	return o.Output
}

// EnsureOutputFolder creates the output folder if it does not exist.
// If the output folder is not specified (i.e. output to STDOUT), it is ignored.
func (o Options) EnsureOutputFolder() error {
	output := o.GetOutput()
	if output == "" {
		return nil
	}
	if dir := filepath.Dir(output); dir != "" {
		return os.MkdirAll(dir, 0755)
	}
	return nil
}

// CreateOutput creates the writer for the output.
func (o Options) CreateOutput() (io.WriteCloser, error) {
	output := o.GetOutput()
	if output == "" {
		return nullCloser{os.Stdout}, nil
	}

	return os.Create(output)
}

// nullCloser is a writer that does nothing on Close.
type nullCloser struct {
	io.Writer
}

// Close is a no-op for a nullCloser.
func (d nullCloser) Close() error {
	return nil
}