import { stat } from 'fs/promises';
import { createReadStream } from 'fs';
import { relative } from 'path';
import { transform } from 'p-transform';
import { isBinaryFile } from 'isbinaryfile';
import { simpleGit } from 'simple-git';
import { isFileStateModified } from 'mem-fs-editor/state';
import { normalizeLineEndings } from '../../base/support/index.js';
export function detectCrLf(filePath) {
    return new Promise((resolve, reject) => {
        let isCrlf;
        const rs = createReadStream(filePath, { encoding: 'utf8' });
        rs.on('data', function (chunk) {
            const n = chunk.indexOf('\n');
            const r = chunk.indexOf('\r');
            if (n !== -1 || r !== -1) {
                isCrlf = n === -1 || (r !== -1 && r < n);
                rs.close();
            }
        })
            .on('close', function () {
            resolve(isCrlf);
        })
            .on('error', function (err) {
            reject(err);
        });
    });
}
const autoCrlfTransform = async ({ baseDir }) => {
    const git = simpleGit({ baseDir }).env({
        ...process.env,
        LANG: 'en',
    });
    if (!(await git.checkIsRepo())) {
        throw new Error(`${baseDir} is not inside a git repository`);
    }
    return transform(async (file) => {
        if (!isFileStateModified(file) || !file.path.startsWith(baseDir)) {
            return file;
        }
        try {
            const fstat = await stat(file.path);
            if (fstat.isFile()) {
                if (await isBinaryFile(file.contents)) {
                    return file;
                }
                const attrs = Object.fromEntries((await git.raw('check-attr', 'binary', 'eol', '--', relative(baseDir, file.path)))
                    .split(/\r\n|\r|\n/)
                    .map(attr => attr.split(':'))
                    .map(([_file, attr, value]) => [attr, value]));
                if (attrs.eol === 'crlf' || (attrs.binary !== 'set' && attrs.eol !== 'lf' && (await detectCrLf(file.path)))) {
                    file.contents = Buffer.from(normalizeLineEndings(file.contents.toString(), '\r\n'));
                }
            }
        }
        catch {
        }
        return file;
    });
};
export default autoCrlfTransform;
