Wraps a command with optional module loading. If a module was explicitly specified by the user, it will try to load it and error out if it's not found or invalid. If no module was specified, it will try the current directory as a module but provide a nil module if it's not found, not erroring out.
( fn func(context.Context, *client.Client, *dagger.Module, *cobra.Command, []string) error, presetSecretToken string, )
| 1259 | // it will try the current directory as a module but provide a nil module if it's not found, not |
| 1260 | // erroring out. |
| 1261 | func optionalModCmdWrapper( |
| 1262 | fn func(context.Context, *client.Client, *dagger.Module, *cobra.Command, []string) error, |
| 1263 | presetSecretToken string, |
| 1264 | ) func(*cobra.Command, []string) error { |
| 1265 | return func(cmd *cobra.Command, cmdArgs []string) error { |
| 1266 | _, explicitModRefSet := getExplicitModuleSourceRef() |
| 1267 | |
| 1268 | return withEngine(cmd.Context(), client.Params{ |
| 1269 | SecretToken: presetSecretToken, |
| 1270 | LoadWorkspaceModules: !moduleNoURL && !explicitModRefSet, |
| 1271 | }, func(ctx context.Context, engineClient *client.Client) (err error) { |
| 1272 | if moduleNoURL { |
| 1273 | return fn(ctx, engineClient, nil, cmd, cmdArgs) |
| 1274 | } |
| 1275 | |
| 1276 | dag := engineClient.Dagger() |
| 1277 | modRef, err := getModuleSourceRefWithDefault() |
| 1278 | if err != nil { |
| 1279 | return err |
| 1280 | } |
| 1281 | modSrc := dag.ModuleSource(modRef, dagger.ModuleSourceOpts{ |
| 1282 | AllowNotExists: true, |
| 1283 | }) |
| 1284 | configExists, err := modSrc.ConfigExists(ctx) |
| 1285 | if err != nil { |
| 1286 | return fmt.Errorf("failed to check if module exists: %w", err) |
| 1287 | } |
| 1288 | switch { |
| 1289 | case configExists: |
| 1290 | serveCtx, span := Tracer().Start(ctx, "load module: "+modRef) |
| 1291 | mod := modSrc.AsModule() |
| 1292 | serveErr := mod.Serve(serveCtx, dagger.ModuleServeOpts{IncludeDependencies: true}) |
| 1293 | telemetry.EndWithCause(span, &serveErr) |
| 1294 | if serveErr != nil { |
| 1295 | return fmt.Errorf("failed to serve module: %w", serveErr) |
| 1296 | } |
| 1297 | return fn(ctx, engineClient, mod, cmd, cmdArgs) |
| 1298 | case explicitModRefSet: |
| 1299 | // the user explicitly asked for a module but we didn't find one |
| 1300 | return fmt.Errorf("failed to get configured module: %w", err) |
| 1301 | default: |
| 1302 | // user didn't ask for a module, so just run in default mode since we didn't find one |
| 1303 | return fn(ctx, engineClient, nil, cmd, cmdArgs) |
| 1304 | } |
| 1305 | }) |
| 1306 | } |
| 1307 | } |
no test coverage detected