* Generate a file using a stub template * * @param stubsRoot - Root directory containing stub files * @param stubPath - Path to the specific stub file * @param stubState - Template variables for stub generation * * @example * ```ts * const result = await codemods.makeUsingStu
(
stubsRoot: string,
stubPath: string,
stubState: Record<string, any>,
options?: {
contentsFromFile?: string
}
)
| 561 | * ``` |
| 562 | */ |
| 563 | async makeUsingStub( |
| 564 | stubsRoot: string, |
| 565 | stubPath: string, |
| 566 | stubState: Record<string, any>, |
| 567 | options?: { |
| 568 | contentsFromFile?: string |
| 569 | } |
| 570 | ): Promise<GeneratedStub> { |
| 571 | const stubs = await this.#app.stubs.create() |
| 572 | const stub = await stubs.build(stubPath, { source: stubsRoot }) |
| 573 | |
| 574 | /** |
| 575 | * Overwrite the contents of the stub output with the contents |
| 576 | * of the provided file. |
| 577 | */ |
| 578 | if (options?.contentsFromFile) { |
| 579 | const source = isAbsolute(options.contentsFromFile) |
| 580 | ? options.contentsFromFile |
| 581 | : this.#app.makePath(options.contentsFromFile) |
| 582 | |
| 583 | try { |
| 584 | debug('overwriting stub output with contents from file %s', source) |
| 585 | stub.replaceWith(await readFile(source, 'utf-8')) |
| 586 | } catch (error: any) { |
| 587 | if (error.code === 'ENOENT') { |
| 588 | throw new Error( |
| 589 | `Cannot replace stub output with "${options.contentsFromFile}" file contents as the file is missing`, |
| 590 | { cause: error } |
| 591 | ) |
| 592 | } |
| 593 | throw error |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | const output = await stub.generate({ force: this.overwriteExisting, ...stubState }) |
| 598 | debug('generating file %O', output) |
| 599 | |
| 600 | const entityFileName = stringHelpers.toUnixSlash(this.#app.relativePath(output.destination)) |
| 601 | const result = { ...output, relativeFileName: entityFileName } |
| 602 | |
| 603 | if (output.status === 'skipped') { |
| 604 | this.#cliLogger.action(`create ${entityFileName}`).skipped(output.skipReason) |
| 605 | return result |
| 606 | } |
| 607 | |
| 608 | this.#cliLogger.action(`create ${entityFileName}`).succeeded() |
| 609 | return result |
| 610 | } |
| 611 | |
| 612 | /** |
| 613 | * Install packages using the detected or specified package manager. |