|
| 1 | +import {resolve} from "path"; |
| 2 | +import {mapFn} from "@softwareventures/array"; |
| 3 | +import {ProjectSource} from "../project/project"; |
| 4 | +import {readProjectJson} from "../project/read-json"; |
| 5 | +import {combineAsyncResults, mapFailureFn, Result, success} from "../result/result"; |
| 6 | +import {yarn} from "../yarn/yarn"; |
| 7 | + |
| 8 | +export type PrettierFixResult = Result<PrettierFixFailureReason>; |
| 9 | + |
| 10 | +export interface PrettierFixFailureReason { |
| 11 | + readonly type: "prettier-fix-failed"; |
| 12 | + readonly path: string; |
| 13 | +} |
| 14 | + |
| 15 | +export async function prettierFixFiles( |
| 16 | + project: ProjectSource, |
| 17 | + relativePaths: readonly string[] |
| 18 | +): Promise<PrettierFixResult> { |
| 19 | + return Promise.resolve(relativePaths) |
| 20 | + .then( |
| 21 | + mapFn(async path => |
| 22 | + yarn(project.path, "prettier", "--write", path).then( |
| 23 | + mapFailureFn( |
| 24 | + (): PrettierFixFailureReason => ({ |
| 25 | + type: "prettier-fix-failed", |
| 26 | + path: resolve(project.path, path) |
| 27 | + }) |
| 28 | + ) |
| 29 | + ) |
| 30 | + ) |
| 31 | + ) |
| 32 | + .then(combineAsyncResults); |
| 33 | +} |
| 34 | + |
| 35 | +export async function prettierFixFilesIfAvailable( |
| 36 | + project: ProjectSource, |
| 37 | + relativePaths: readonly string[] |
| 38 | +): Promise<PrettierFixResult> { |
| 39 | + return isPrettierAvailable(project).then(async available => |
| 40 | + available ? prettierFixFiles(project, relativePaths) : success() |
| 41 | + ); |
| 42 | +} |
| 43 | + |
| 44 | +export async function isPrettierAvailable(project: ProjectSource): Promise<boolean> { |
| 45 | + return readProjectJson(project, "package.json") |
| 46 | + .catch(reason => { |
| 47 | + if (reason instanceof SyntaxError || reason.code === "ENOENT") { |
| 48 | + return false; |
| 49 | + } else { |
| 50 | + throw reason; |
| 51 | + } |
| 52 | + }) |
| 53 | + .then( |
| 54 | + packageJson => |
| 55 | + packageJsonDependsOnPrettier(packageJson) && yarnPrettierCanRun(packageJson) |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +function packageJsonDependsOnPrettier(packageJson: any): boolean { |
| 60 | + return ( |
| 61 | + typeof packageJson === "object" && |
| 62 | + ((typeof packageJson?.dependencies === "object" && |
| 63 | + typeof packageJson?.dependencies?.prettier === "string") || |
| 64 | + (typeof packageJson?.devDependencies === "object" && |
| 65 | + typeof packageJson?.devDependencies?.prettier === "string")) |
| 66 | + ); |
| 67 | +} |
| 68 | + |
| 69 | +function yarnPrettierCanRun(packageJson: any): boolean { |
| 70 | + return ( |
| 71 | + typeof packageJson === "object" && |
| 72 | + (typeof packageJson?.scripts !== "object" || |
| 73 | + packageJson?.scripts?.prettier == null || |
| 74 | + String(packageJson?.scripts?.prettier).trim() === "prettier") |
| 75 | + ); |
| 76 | +} |
0 commit comments