import { stat } from 'fs/promises';
import { createReadStream } from 'fs';
import { transform } from 'p-transform';
import { isBinaryFile } from 'isbinaryfile';
import { normalizeLineEndings } from '../../base/support/index.mjs';
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 = (git) => transform(async (file) => {
    if (!file.contents) {
        return file;
    }
    if (await isBinaryFile(file.contents)) {
        return file;
    }
    const fstat = await stat(file.path);
    if (!fstat.isFile()) {
        return file;
    }
    const attributes = Object.fromEntries((await git.raw('check-attr', 'binary', 'eol', '--', file.path))
        .split(/\r\n|\r|\n/)
        .map(attr => attr.split(':'))
        .map(([_file, attr, value]) => [attr, value]));
    if (attributes.binary === 'set' || attributes.eol === 'lf') {
        return file;
    }
    if (attributes.eol === 'crlf' || (await detectCrLf(file.path))) {
        file.contents = Buffer.from(normalizeLineEndings(file.contents.toString(), '\r\n'));
    }
    return file;
});
export default autoCrlfTransform;
