"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatWithPrettier = void 0;
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = require("node:fs");
const node_child_process_1 = require("node:child_process");
async function formatWithPrettier(args) {
    const cwd = findNearestPackageJsonDir(args.startSearchFrom);
    if (!cwd) {
        throw new Error(`Unable to find a package.json to run prettier from (started at: ${args.startSearchFrom})`);
    }
    const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
    await new Promise((resolve, reject) => {
        (0, node_child_process_1.execFile)(npxCmd, ['prettier', '--write', args.filePath], { cwd, env: process.env }, (error, stdout, stderr) => {
            if (error) {
                reject(new Error(`prettier failed for ${args.filePath}\n\n${stdout}\n${stderr}`));
                return;
            }
            resolve();
        });
    });
}
exports.formatWithPrettier = formatWithPrettier;
function findNearestPackageJsonDir(start) {
    let current = node_path_1.default.resolve(start);
    // If start is a file, search from its directory.
    if (node_path_1.default.extname(current)) {
        current = node_path_1.default.dirname(current);
    }
    // eslint-disable-next-line no-constant-condition
    while (true) {
        const candidate = node_path_1.default.join(current, 'package.json');
        if ((0, node_fs_1.existsSync)(candidate))
            return current;
        const parent = node_path_1.default.dirname(current);
        if (parent === current)
            return null;
        current = parent;
    }
}
