xref: /expo/tools/src/vendoring/devmenu/steps/Task.ts (revision 7e58fb75)
1import logger from '../../../Logger';
2import { toRepoPath } from '../utils';
3
4/**
5 * An base class for all task.
6 * It provides a simple task luncher, log utils and path to working directory.
7 */
8export abstract class Task {
9  private workingDirectory?: string;
10
11  /**
12   * Tasks can contain multiple steps. This function provides a consistent way to log information about each step.
13   * @param message
14   */
15  protected logSubStep(message: string) {
16    logger.info(`> ${message}`);
17  }
18
19  /**
20   * A function which provides a consistent way of printing debug information inside a task.
21   * @param message which will be printed using debug log level.
22   */
23  protected logDebugInfo(message: string | string[]) {
24    if (typeof message === 'string') {
25      logger.debug(`  ${message}`);
26    } else {
27      logger.debug(`  ${message.join('\n    ')}`);
28    }
29  }
30
31  /**
32   * We want to have a way to change working directory using task's settings.
33   * For example, we could run pipe in the temp directory but one task from it in the repo.
34   * It's ignored if undefined was returned.
35   * @returns the override working directory for task.
36   */
37  protected overrideWorkingDirectory(): string | undefined {
38    return;
39  }
40
41  /**
42   * @returns the absolute path to working directory for task based on overrideWorkDirectory().
43   */
44  protected getWorkingDirectory(): string {
45    const overrideValue = this.overrideWorkingDirectory();
46    if (overrideValue) {
47      return toRepoPath(overrideValue);
48    }
49
50    return toRepoPath(this.workingDirectory!);
51  }
52
53  /**
54   * Sets the working directory for the task.
55   * @param workingDirectory
56   */
57  public setWorkingDirectory(workingDirectory: string) {
58    this.workingDirectory = workingDirectory;
59  }
60
61  /**
62   * A function which will be call in start method. The body of the task.
63   */
64  protected abstract async execute();
65
66  /**
67   * A method that starts the task. It provides error handling.
68   */
69  public async start() {
70    try {
71      await this.execute();
72    } catch (e) {
73      logger.error(e);
74      return;
75    }
76  }
77}
78