code.vegaprotocol.io/vega@v0.79.0/visor/args.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package visor
    17  
    18  import (
    19  	"fmt"
    20  	"strings"
    21  )
    22  
    23  // TODO make these functions more robust.
    24  type Args []string
    25  
    26  func (a Args) indexOf(name string) int {
    27  	for i, arg := range a {
    28  		if strings.Contains(arg, name) {
    29  			return i
    30  		}
    31  	}
    32  	return -1
    33  }
    34  
    35  func (a Args) Exists(name string) bool {
    36  	return a.indexOf(name) != -1
    37  }
    38  
    39  // Set sets a new argument. Ignores if argument exists.
    40  func (a *Args) Set(name, value string) bool {
    41  	if a.Exists(name) {
    42  		return false
    43  	}
    44  
    45  	if name[0:2] != "--" {
    46  		name = fmt.Sprintf("--%s", name)
    47  	}
    48  
    49  	*a = append(*a, name, value)
    50  
    51  	return true
    52  }
    53  
    54  // ForceSet sets a new argument even if the argument currently exists.
    55  func (a *Args) ForceSet(name, value string) bool {
    56  	if name[0:2] != "--" {
    57  		name = fmt.Sprintf("--%s", name)
    58  	}
    59  
    60  	*a = append(*a, name, value)
    61  
    62  	return true
    63  }
    64  
    65  // GetFlagWithArg finds and returns a flag with it's argument.
    66  // Returns nil if not found.
    67  // Example: --home /path.
    68  func (a Args) GetFlagWithArg(name string) []string {
    69  	if name[0:2] != "--" {
    70  		name = fmt.Sprintf("--%s", name)
    71  	}
    72  
    73  	i := a.indexOf(name)
    74  	if i == -1 {
    75  		return nil
    76  	}
    77  
    78  	// Check if there is a flag's paramater available
    79  	if len(a) < i+2 {
    80  		return nil
    81  	}
    82  
    83  	return a[i : i+2]
    84  }