NewAPI returns a new API with the given options applied.
(logger slog.Logger, options ...Option)
| 322 | |
| 323 | // NewAPI returns a new API with the given options applied. |
| 324 | func NewAPI(logger slog.Logger, options ...Option) *API { |
| 325 | ctx, cancel := context.WithCancel(context.Background()) |
| 326 | api := &API{ |
| 327 | ctx: ctx, |
| 328 | cancel: cancel, |
| 329 | initialUpdateDone: make(chan struct{}), |
| 330 | updateTrigger: make(chan chan error), |
| 331 | updateInterval: defaultUpdateInterval, |
| 332 | logger: logger, |
| 333 | clock: quartz.NewReal(), |
| 334 | execer: agentexec.DefaultExecer, |
| 335 | containerLabelIncludeFilter: make(map[string]string), |
| 336 | devcontainerNames: make(map[string]bool), |
| 337 | knownDevcontainers: make(map[string]codersdk.WorkspaceAgentDevcontainer), |
| 338 | configFileModifiedTimes: make(map[string]time.Time), |
| 339 | ignoredDevcontainers: make(map[string]bool), |
| 340 | recreateSuccessTimes: make(map[string]time.Time), |
| 341 | recreateErrorTimes: make(map[string]time.Time), |
| 342 | scriptLogger: func(uuid.UUID) ScriptLogger { return noopScriptLogger{} }, |
| 343 | injectedSubAgentProcs: make(map[string]subAgentProcess), |
| 344 | usingWorkspaceFolderName: make(map[string]bool), |
| 345 | } |
| 346 | // The ctx and logger must be set before applying options to avoid |
| 347 | // nil pointer dereference. |
| 348 | for _, opt := range options { |
| 349 | opt(api) |
| 350 | } |
| 351 | if api.commandEnv != nil { |
| 352 | api.execer = newCommandEnvExecer( |
| 353 | api.logger, |
| 354 | api.commandEnv, |
| 355 | api.execer, |
| 356 | ) |
| 357 | } |
| 358 | if api.ccli == nil { |
| 359 | api.ccli = NewDockerCLI(api.execer) |
| 360 | } |
| 361 | if api.dccli == nil { |
| 362 | api.dccli = NewDevcontainerCLI(logger.Named("devcontainer-cli"), api.execer) |
| 363 | } |
| 364 | if api.watcher == nil { |
| 365 | var err error |
| 366 | api.watcher, err = watcher.NewFSNotify() |
| 367 | if err != nil { |
| 368 | logger.Error(ctx, "create file watcher service failed", slog.Error(err)) |
| 369 | api.watcher = watcher.NewNoop() |
| 370 | } |
| 371 | } |
| 372 | if api.fs == nil { |
| 373 | api.fs = afero.NewOsFs() |
| 374 | } |
| 375 | if api.subAgentClient.Load() == nil { |
| 376 | var c SubAgentClient = noopSubAgentClient{} |
| 377 | api.subAgentClient.Store(&c) |
| 378 | } |
| 379 | |
| 380 | return api |
| 381 | } |