Загрузка данных



async function compileCurrentFile() {
    const editor = vscode.window.activeTextEditor;

    if (
        !editor ||
        path.extname(editor.document.uri.fsPath).toLowerCase() !== '.sma'
    ) {
        vscode.window.showErrorMessage('Open a .sma file to compile.');
        return;
    }

    const source = editor.document;

    // Сохраняем исходник перед компиляцией
    const saved = await source.save();
    if (!saved) {
        vscode.window.showErrorMessage('Could not save source file.');
        return;
    }

    // Находим компилятор AMXX
    const compiler = findCompiler(true);
    if (!compiler) return;

    const sourcePath = source.uri.fsPath;
    const sourceDir = path.dirname(sourcePath);

    // Корень открытого проекта
    const workspaceRoot =
        vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || sourceDir;

    // Читаем папку назначения из настроек VS Code
    const outputSetting = config().get('outputDirectory', '').trim();

    let outputDir;

    if (outputSetting) {
        // Абсолютный путь или путь относительно корня проекта
        outputDir = path.isAbsolute(outputSetting)
            ? outputSetting
            : path.resolve(workspaceRoot, outputSetting);
    } else {
        // Если настройка пустая — рядом с .sma
        outputDir = sourceDir;
    }

    // Создаём папку, если она не существует
    try {
        fs.mkdirSync(outputDir, { recursive: true });
    } catch (err) {
        vscode.window.showErrorMessage(
            `Cannot create output directory: ${err.message}`
        );
        return;
    }

    // Имя выходного файла: plugin.sma -> plugin.amxx
    const outputPath = path.join(
        outputDir,
        path.basename(sourcePath, path.extname(sourcePath)) + '.amxx'
    );

    // Панель вывода компилятора
    const output = vscode.window.createOutputChannel('AMX Mod X Compiler');
    output.clear();
    output.show(true);

    output.appendLine(`Source: ${sourcePath}`);
    output.appendLine(`Output: ${outputPath}`);
    output.appendLine('');

    // Аргументы компилятора
    const args = [
        ...config().get('compilerArgs', []),
        sourcePath,
        '-o' + outputPath
    ];

    const proc = cp.spawn(compiler, args, {
        cwd: sourceDir,
        windowsHide: true
    });

    proc.stdout.on('data', data => output.append(data.toString()));
    proc.stderr.on('data', data => output.append(data.toString()));

    proc.on('error', err => {
        output.appendLine(`Failed to start compiler: ${err.message}`);
        vscode.window.showErrorMessage(
            'Could not start AMX Mod X compiler.'
        );
    });

    proc.on('close', code => {
        output.appendLine(`\nCompiler exited with code ${code}.`);

        if (code === 0) {
            vscode.window.showInformationMessage(
                `Compiled successfully: ${outputPath}`
            );
        } else {
            vscode.window.showErrorMessage(
                'Compilation failed. Check Output → AMX Mod X Compiler.'
            );
        }
    });
}