-
I believe the question in hand is not addressed in the Mage docs, so please consider the following simple target function which I hope is self-explanatory even w/o providing its domain context: func (Environment) Init(environmentName string) error {
mg.Deps(Environment.Config)
env, exist := envsConfig.Environments[environmentName]
if !exist {
return say.error("Environment '%s' not found", environmentName)
}
for _, stack := range env.Stacks {
mg.SerialDeps(mg.F(Stack.Init, stack.Path, environmentName))
}
return nil
} Question: is the line If it is a hack, then what is the right way to do it? I consciously wamt to avoid extracting definition of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
So, you can just call Init like a regular old function. Mage targets are just go functions. Putting it inside a call to mg.SerialDeps will mean that if the function has already been called previously with those arguments using mg.Deps or mg.SerialDeps, then it won't get executed again. I'm not sure if that's the effect you're going for or not. If you don't care if the function gets executed a second time (or if you know that it won't because of how the code is structured) then you can just call Init(environmentName) like it's a normal go function (because it is). It's a little hard to follow your example because I think you have some copy and paste errors from editing out the extraneous information, but this might be close? func (Environment) Init(environmentName string) error {
mg.Deps(Environment.Config)
env, exist := envsConfig.Environments[environmentName]
if !exist {
return say.error("Environment '%s' not found", environmentName)
}
for _, stack := range env.Stacks {
err := stack.Init(stack.Path)
if err != nil {
return fmt.Errorf("failed to run init on stack %q under environment %q: %w", stack.Path, environmentName, err)
}
}
return nil
} |
Beta Was this translation helpful? Give feedback.
Mage code is just go code. The examples sometimes ignore the receiver variable in mg.Namespace methods, but you can put it back. Then you can just call stack.Clean like you would in any other struct.