我目前正在开发一个Bitrise工作流步骤,我正在尝试允许该步骤为用户提供一种方法,为特定步骤输入提供可选的YAML键/值对列表,目前正在尝试实现为:
my_step@1:
inputs:
- uri_actions:
- button_text: Some text
uri: www.google.com
- button_text: Some text 2
uri: www.google2.com
- button_text: Some text 3
uri: www.google3.com然后尝试将Go解析为structs:
type config struct {
UriActionList []UriAction `env:"uri_actions"`
}
type UriAction struct {
ButtonText string `env:"button_text"`
Uri string `env:"uri"`
},还尝试将config结构映射为
type config struct {
UriActionList map[UriAction]string `env:"uri_actions"`
}Bitrise步骤使用stepconf自动解析用户的工作流,并将YAML映射到声明的structs
func main() {
var cfg config
if err := stepconf.Parse(&cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
stepconf.Print(cfg)
}但是这两个都不是很好..
这是我第一次尝试Go并开发我自己的Bitrise步骤,那么我做错了什么呢?或者,有没有更文明的方式来实现这一点?
发布于 2021-01-06 10:16:31
编辑:根据评论中的讨论,这个问题与go-steputils/stepconf库有关,用于解析yaml。但是该库根本不对yaml文件进行操作,而只是对环境进行一些解析以处理集合(请参阅库用法、example和test)。我的猜测是有一些管道在某个地方将yaml转换为环境变量。
如果您打算在没有管道情况下从文件中读取yaml,我建议您使用文档齐全的库- go-yaml,如下所示:
type config struct {
Inputs []Inputs `yaml:"inputs"`
}
type Inputs struct {
UriActionList []UriAction `yaml:"uri_actions"`
}
type UriAction struct {
ButtonText string `yaml:"button_text"`
Uri string `yaml:"uri"`
}
func main() {
cfg := config{}
err := yaml.Unmarshal([]byte(data), &cfg)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("---\n%v\n", cfg)
}请参阅使用工作代码here的游乐场
发布于 2021-01-09 21:00:47
步骤输入只能是字符串/文本,因为这些字符串/文本作为环境变量传递给步骤,而环境变量只能是文本。当然,您可以在字符串中包含一个yml结构,但它仍然必须是一个字符串。
所以,而不是你原来的
my_step@1:
inputs:
- uri_actions:
- button_text: Some text
uri: www.google.com
- button_text: Some text 2
uri: www.google2.com
- button_text: Some text 3
uri: www.google3.com将uri_actions的值设置为字符串(通过|):
my_step@1:
inputs:
- uri_actions: |
- button_text: Some text
uri: www.google.com
- button_text: Some text 2
uri: www.google2.com
- button_text: Some text 3
uri: www.google3.com然后,在您的步骤中,您可以读取环境变量uri_actions,它将保存值(作为字符串):
- button_text: Some text
uri: www.google.com
- button_text: Some text 2
uri: www.google2.com
- button_text: Some text 3
uri: www.google3.com如果你想把它解析成YML,你可以按照@blami提到的方式来做:
uriActionsUserInput := os.Getenv("uri_actions")
cfg := []UriAction{}
err := yaml.Unmarshal([]byte(uriActionsUserInput), &cfg)在这里看一个完整的例子:https://play.golang.org/p/qst3oVnjK0X
https://stackoverflow.com/questions/65588480
复制相似问题