go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/luciexe/output_flag.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package luciexe
    16  
    17  import (
    18  	"flag"
    19  	"strings"
    20  
    21  	bbpb "go.chromium.org/luci/buildbucket/proto"
    22  )
    23  
    24  const (
    25  	// OutputCLIArg is the CLI argument to luciexe binaries to instruct them to
    26  	// dump their final Build message. The value of this flag must be an absolute
    27  	// path to a file which doesn't exist in a directory which does (and which the
    28  	// luciexe binary has access to write in). See Output*FileExt for valid
    29  	// extensions.
    30  	OutputCLIArg = "--output"
    31  )
    32  
    33  // OutputFlag can be used as a flag.Value to parse the OutputCLIArg as part of
    34  // your FlagSet.
    35  type OutputFlag struct {
    36  	Path  string
    37  	Codec BuildFileCodec
    38  }
    39  
    40  var _ flag.Value = (*OutputFlag)(nil)
    41  
    42  // Set implements flag.Value.
    43  func (o *OutputFlag) Set(value string) error {
    44  	codec, err := BuildFileCodecForPath(value)
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	o.Path = value
    50  	o.Codec = codec
    51  	return nil
    52  }
    53  
    54  func (o *OutputFlag) String() string {
    55  	if o == nil {
    56  		return ""
    57  	}
    58  	return o.Path
    59  }
    60  
    61  // Write writes the build message to this output file with the appropriate
    62  // encoding.
    63  func (o *OutputFlag) Write(build *bbpb.Build) error {
    64  	return WriteBuildFile(o.Path, build)
    65  }
    66  
    67  // AddOutputFlagToSet adds a OutputFlag to the FlagSet with OutputCLIArg and
    68  // a useful helpstring.
    69  //
    70  // Returns the added *OutputFlag. The default value has a Codec of
    71  // BuildFileNone.
    72  func AddOutputFlagToSet(fs *flag.FlagSet) *OutputFlag {
    73  	ret := &OutputFlag{Codec: buildFileCodecNoop{}}
    74  	fs.Var(ret, strings.TrimLeft(OutputCLIArg, "-"),
    75  		"a path to a `build_file` to write the final build.proto into. Valid file extensions: "+validCodecExtsStr)
    76  	return ret
    77  }