All files / backend/helpers/gitcommit bitbucketCommit.mjs

92.71% Statements 229/247
91.37% Branches 53/58
51.61% Functions 16/31
98.68% Lines 226/229

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533                                                    36x       36x 25x 25x 4x   25x 25x 25x 25x                   36x 6x             36x 17x         17x 17x 17x   17x       17x 17x         15x   2x 2x 2x   17x       36x 23x   23x   23x 23x 23x 23x 23x   23x   23x               23x 23x             6x 5x         36x 2x   2x   2x 2x 2x 2x 2x   2x   2x               36x 25x           25x 2x   25x     25x     36x 23x 23x 23x 23x 18x 18x   5x 5x 3x 3x 3x 3x         2x 2x 2x 2x 1x 1x   1x 1x       1x 1x 1x       36x 15x   15x             15x 23x 23x 23x 23x 23x             19x   4x 4x 4x 4x   4x 2x             1x 1x     22x 8x       15x     36x 11x 11x           11x   11x                       11x 11x         11x 11x 11x   11x 3x       3x     8x 8x 8x   3x 3x 3x 3x       36x   8x         8x   8x   8x       8x 8x         7x 7x   1x 1x 1x   8x     36x 20x         20x 20x 20x 20x 3x     17x   17x 17x 17x 17x 17x 2x 2x     15x           15x 15x 4x       4x 4x     11x         11x 11x 3x 3x     8x   8x         8x 8x 1x 1x   8x   3x 3x 3x 3x 3x   11x     36x 3x             3x   3x   3x 3x   3x 6x     3x 3x         2x   1x 1x 1x 1x 1x 1x   3x     36x 7x     7x 7x           7x 6x 6x   1x 1x 1x       6x 6x 1x     5x 5x   5x 5x 5x   5x                       5x 1x 1x     4x   2x 2x 2x 2x 2x     6x                                       36x 33x 33x       33x   20x   3x   7x   3x      
/*
  Copyright (C) 2023 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import axios from 'axios';
import FormData from 'form-data';
import crypto from 'crypto';
import bitbucket from '@back/helpers/bitbucket.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {parseBitbucketV1ApiError} from '@back/helpers/bitbucketErrorParser.mjs';
import { v4 as uuidv4 } from 'uuid';
import {BB_V1_DELAY_BETWEEN_COMMIT_FILE, BB_V1_FAST_FAIL_COMMIT_FILE} from '@back/helpers/env.mjs';
import {buildZipArchive, sendArchiveToAdapter} from '@back/helpers/gitcommit/utils.mjs';
 
const logger = getLoggerWithTag('bb-commit');
 
let ADAPTER_BITBUCKET_URL_SAVE;
 
const getRepositoryOptions = (bbPath) => {
    let rootPath = bbPath;
    if (!rootPath) {
        rootPath = process.env.VUE_APP_DOCHUB_ROOT_MANIFEST;
    }
    const [protocol, projectID, repositoryID, source] = rootPath.split(':');
    const [branch] = source.split('@');
    const baseURL = process.env.VUE_APP_DOCHUB_BITBUCKET_URL;
    return {
        protocol,
        projectID,
        repositoryID,
        source,
        branch,
        baseURL: baseURL.endsWith('/') ? baseURL : `${baseURL}/`
    };
};
 
const checkItWasRequestWithoutChanges = (err) => {
    return (
        err?.response?.status === 409 &&
        err?.response?.data?.errors[0]?.message ===
        'The content provided is the same as what already exists. No change was committed.'
    );
};
 
const createBranch = async({newBranchName, repositoryOptions}) => {
    const result = {
        id: 0,
        stageName: 'Создание ветки',
        success: false
    };
    const {baseURL, projectID, repositoryID, branch} = repositoryOptions;
    result.message = `Создана ветка: ${newBranchName} от ветки ${branch} в репозитории ${repositoryID} в проекте ${projectID}`;
    const url = `${baseURL}rest/api/1.0/projects/${projectID}/repos/${repositoryID}/branches`;
 
    const body = {
        name: newBranchName,
        startPoint: `refs/heads/${branch}`
    };
    try {
        await axios({
            method: 'POST',
            url,
            data: body
        });
        result.success = true;
    } catch (err) {
        const axiosError = parseBitbucketV1ApiError(err);
        result.message = `Ошибка при создании ветки: ${newBranchName}`;
        result.error = `${axiosError.status}: ${axiosError.statusText}: ${axiosError.message}`;
    }
    return result;
 
};
 
const updateFile = async({branch, fileName, content, repositoryOptions, commitMessage}) => {
    const {baseURL, projectID, repositoryID} = repositoryOptions;
 
    const url = `${baseURL}rest/api/1.0/projects/${projectID}/repos/${repositoryID}/browse/${fileName}`;
 
    const body = new FormData();
    body.append('branch', branch);
    body.append('sourceCommitId', 'HEAD');
    body.append('content', content);
    body.append('message', commitMessage);
 
    const headers = body.getHeaders();
 
    logger.debug(() => [
        `send request to bb [PUT] ${url}`,
        {title: 'branch', obj: branch},
        {title: 'sourceCommitId', obj: 'HEAD'},
        {title: 'message', obj: commitMessage},
        {title: 'content', obj: content}
    ]);
 
    try {
        return await axios({
            method: 'PUT',
            headers,
            url,
            data: body
        });
    } catch (err) {
        if (!checkItWasRequestWithoutChanges(err)) {
            throw err;
        }
    }
};
 
const createNewFile = async({branch, fileName, content, repositoryOptions, commitMessage}) => {
    const {baseURL, projectID, repositoryID} = repositoryOptions;
 
    const url = `${baseURL}rest/api/1.0/projects/${projectID}/repos/${repositoryID}/browse/${fileName}`;
 
    const body = new FormData();
    body.append('branch', branch);
    body.append('type', 'file');
    body.append('message', commitMessage);
    body.append('content', content);
 
    const headers = body.getHeaders();
 
    return await axios({
        method: 'PUT',
        headers,
        url,
        data: body
    });
};
 
const createFileResult = ({path, branch, mode = null, success = false, message = undefined, error = undefined}) => {
    const result = {
        success: success,
        path: path,
        mode: mode,
        writeToBranch: branch
    };
    if (message !== undefined) {
        result.message = message;
    }
    Iif (error !== undefined) {
        result.error = error;
    }
    return result;
};
 
const writeFile = async({branch, fileName, content, repositoryOptions, commitMessage}) => {
    const result = createFileResult({path: fileName, branch: branch, mode: 'update', success: false});
    logger.debug(() => `try update file ${fileName} in branch ${branch}, with content [${JSON.stringify(content)}]`);
    try {
        await updateFile({branch, fileName, content, repositoryOptions, commitMessage});
        result.success = true;
        return result;
    } catch (err) {
        logger.debug(() => `updateFile ${fileName} get error`, err);
        if (err?.response?.status !== 404) {
            const axiosError = parseBitbucketV1ApiError(err);
            result.message = `Ошибка при обновлении файла "${fileName}" в ветке "${branch}"`;
            result.error = `${axiosError.status}: ${axiosError.statusText}: ${axiosError.message}`;
            throw result;
        }
        // если статус 404, то ничего не делаем, попробуем создать файл
    }
 
    result.mode = 'create';
    logger.debug(() => `${fileName} not found in branch ${branch}, create new`);
    try {
        await createNewFile({branch, fileName, content, repositoryOptions, commitMessage});
        result.success = true;
        return result;
    } catch (err) {
        const axiosError = parseBitbucketV1ApiError(err);
        logger.debug(() => [
            `createNewFile ${fileName} get error`,
            {title: 'axiosError', obj: axiosError}
        ]);
        result.message = `Ошибка при создании файла "${fileName}" в ветке "${branch}"`;
        result.error = `${axiosError.status}: ${axiosError.statusText}: ${axiosError.message}`;
        throw result;
    }
};
 
const writeFileListWidthDelay = async({branchName, contentObject, repositoryOptions, commitMessageSuffix}) => {
    const dataList = Object.entries(contentObject);
 
    const result = {
        id: 1,
        stageName: 'Запись файлов',
        files: [],
        success: true
    };
 
    for (let i = 0; i < dataList.length; i++) {
        const [path, data] = dataList[i];
        logger.debug(() => `write file ${path}, data [${JSON.stringify(data)}]`);
        try {
            const commitMessage = `seaf: Сохранение файла ${path} ${commitMessageSuffix}`;
            const fileResult = await writeFile({
                branch: branchName,
                fileName: path,
                content: data,
                repositoryOptions: repositoryOptions,
                commitMessage: commitMessage
            });
            result.files.push(fileResult);
        } catch (errorObject) {
            result.files.push(errorObject);
            result.success = false; // если хоть один файл не удалось загрузить - считаем шаг с ошибкой
            result.error = errorObject.error;
            result.message = errorObject.message;
 
            if (BB_V1_FAST_FAIL_COMMIT_FILE) {
                const skippedFiles = dataList.slice(i + 1).map(([skippedPath]) => createFileResult({
                    path: skippedPath,
                    branch: branchName,
                    mode: 'skipped',
                    success: false,
                    message: `Запись файла "${skippedPath}" пропущена: остановлено после ошибки в файле "${path}"`
                }));
                result.files.push(...skippedFiles);
                break;
            }
        }
        if (i < dataList.length - 1) { // для последнего элемента пауза не нужна
            await new Promise(resolve => setTimeout(resolve, BB_V1_DELAY_BETWEEN_COMMIT_FILE));
        }
    }
 
    return result;
};
 
const createPR = async({fromBranch, repositoryOptions, commitMessageSuffix}) => {
    const {baseURL, projectID, repositoryID, branch} = repositoryOptions;
    const result = {
        id: 2,
        stageName: `Создание pull request из ветки ${fromBranch} в ветку ${branch}`,
        success: false
    };
 
    const url = `${baseURL}rest/api/1.0/projects/${projectID}/repos/${repositoryID}/pull-requests`;
 
    const body = {
        title: `SEAF put content ${commitMessageSuffix}`,
        // description: 'Описание для PR',
        closeSourceBranch: true,
        fromRef: {
            id: `refs/heads/${fromBranch}`
        },
        toRef: {
            id: `refs/heads/${branch}`
        }
    };
 
    try {
        const axiosResponse = await axios({
            method: 'POST',
            url,
            data: body
        });
        const data = axiosResponse.data;
        result.prId = data?.id;
        result.prVersion = data?.version;
 
        if (result.prId == null || result.prVersion == null) {
            logger.error(() => [
                'incorrect bitbucket answer for create pr',
                {title: 'answer.data', obj: data}
            ]);
            throw new Error('Bitbucket return incorrect answer');
        }
 
        result.message = `Создан PR #${result.prId}`;
        result.success = true;
        return result;
    } catch (err) {
        const axiosError = parseBitbucketV1ApiError(err);
        result.message = `Ошибка при создании pull-request ("${fromBranch}" ~> "${branch}")`;
        result.error = `${axiosError.status}: ${axiosError.statusText}: ${axiosError.message}`;
        return result;
    }
};
 
const mergePR = async({prId, version, repositoryOptions}) => {
 
    const result = {
        id: 3,
        stageName: `Слияние pull request #${prId}`,
        success: false
    };
    const {baseURL, projectID, repositoryID} = repositoryOptions;
 
    const url = `${baseURL}rest/api/1.0/projects/${projectID}/repos/${repositoryID}/pull-requests/${prId}/merge`;
 
    const body = {
        version
    };
 
    try {
        await axios({
            method: 'POST',
            url,
            data: body
        });
        result.message = 'PR успешно влит';
        result.success = true;
    } catch (err) {
        const axiosError = parseBitbucketV1ApiError(err);
        result.message = `Merge-request #${prId} завершился с ошибкой`;
        result.error = `${axiosError.status}: ${axiosError.statusText}: ${axiosError.message}`;
    }
    return result;
};
 
const commitToBitbucketApiV1 = async({content, rootPath, userInfo}) => {
    const result = {
        success: false,
        stack: []
    };
 
    try {
        logger.debug(() => `Объект userInfo перед попыткой коммита в bitbucket: ${JSON.stringify(userInfo)}`);
        const {sub, name, surname} = userInfo || {};
        if (!sub || !name || !surname) {
            throw new Error('Недостаточно данных пользователя из JWT-токена для отправки в bitbucket (sub/name/surname)');
        }
 
        const commitMessageAuthorSuffix = `от ${name} ${surname} (${sub})`;
 
        const newBranchName = `commit/${Date.now()}`;
        const repositoryOptions = getRepositoryOptions(rootPath);
        const createBranchResult = await createBranch({newBranchName: newBranchName, repositoryOptions: repositoryOptions});
        result.stack.push(createBranchResult);
        if (!createBranchResult.success) {
            const {message, error} = createBranchResult;
            return Object.assign(result, {message, error});
        }
 
        const writeFilesResult = await writeFileListWidthDelay({
            branchName: newBranchName,
            contentObject: content,
            repositoryOptions: repositoryOptions,
            commitMessageSuffix: commitMessageAuthorSuffix
        });
        result.stack.push(writeFilesResult);
        if (!writeFilesResult.success) {
            logger.debug(() => [
                'error when save file in bb',
                {title: 'result.writeFiles', obj: writeFilesResult}
            ]);
            const {message, error} = writeFilesResult;
            return Object.assign(result, {message, error});
        }
 
        const pullRequestResult = await createPR({
            fromBranch: newBranchName,
            repositoryOptions: repositoryOptions,
            commitMessageSuffix: commitMessageAuthorSuffix
        });
        result.stack.push(pullRequestResult);
        if (!pullRequestResult.success) {
            const {message, error} = pullRequestResult;
            return Object.assign(result, {message, error});
        }
 
        const { prId, prVersion } =  pullRequestResult;
 
        const mergeRequestResult = await mergePR({
            prId: prId,
            version: prVersion,
            repositoryOptions: repositoryOptions
        });
        result.stack.push(mergeRequestResult);
        if (!mergeRequestResult.success) {
            const {message, error} = mergeRequestResult;
            Object.assign(result, {message, error});
        }
        result.success = mergeRequestResult.success; // процесс успешно завершен, если последний шаг успешный
    } catch (err) {
        const traceId = uuidv4();
        logger.error(() => `${traceId}: Error when put-content, state = ${result}`, err);
        result.success = false;
        result.message = `Непредвиденная ошибка: ${traceId}`;
        result.error = err.message;
    }
    return result;
};
 
const commitToBitbucketApiV2 = async({content}) => {
    const result = {
        success: false,
        createBranch: null,
        writeFiles: null,
        createPR: null,
        mergePR: null
    };
    const {projectID, repositoryID, branch} = getRepositoryOptions();
 
    const requestUri = bitbucket.makeSourceURI(projectID, repositoryID);
 
    const data = new URLSearchParams();
    data.append('branch', branch);
 
    for (let url in content) {
        data.append(url, content[url]);
    }
 
    try {
        await axios({
            method: 'POST',
            url: requestUri.toString(),
            data
        });
        result.success = true;
    } catch (err) {
        const traceId = uuidv4();
        logger.error(() => `${traceId}: error when put content with bb v2`, err);
        const axiosError = parseBitbucketV1ApiError(err);
        result.message = `Непредвиденная ошибка: ${traceId}`;
        result.error = axiosError.message;
        result.success = false;
    }
    return result;
};
 
const commitToBitbucketApiAdapter = async({content, rootPath, userInfo}) => {
    const result = {
        success: false
    };
    try {
        Iif (!process.env.VUE_APP_DOCHUB_BITBUCKET_ADAPTER_URL) {
            logger.error(() => 'env VUE_APP_DOCHUB_BITBUCKET_ADAPTER_URL, not exist or empty, it\'s required for save by adapter');
            throw new Error('Сохранение данных невозможно (1)');
        }
 
 
        if (!ADAPTER_BITBUCKET_URL_SAVE) {
            try {
                ADAPTER_BITBUCKET_URL_SAVE = new URL('/api/v1/send-files', process.env.VUE_APP_DOCHUB_BITBUCKET_ADAPTER_URL).toString();
            } catch (e) {
                logger.error(() => `Incorrect value in env VUE_APP_DOCHUB_BITBUCKET_ADAPTER_URL, can't create URL to gas ${process.env.VUE_APP_DOCHUB_BITBUCKET_ADAPTER_URL}`);
                result.success = false;
                throw new Error('Сохранение данных невозможно');
            }
        }
 
        const {sub, name, surname, email} = userInfo || {};
        if (!sub || !name || !surname) {
            throw new Error('Недостаточно данных пользователя из JWT-токена для отправки в bitbucket-адаптер (sub/name/surname)');
        }
 
        const {protocol, projectID, repositoryID, branch} = getRepositoryOptions(rootPath);
        const repoUrl = `${protocol}:${projectID}:${repositoryID}`;
 
        const archiveBuffer = buildZipArchive(content);
        const checksum = crypto.createHash('sha256').update(archiveBuffer).digest('hex');
        const processId = uuidv4();
 
        const sendResult = await sendArchiveToAdapter({
            adapterUrl: ADAPTER_BITBUCKET_URL_SAVE,
            archiveBuffer: archiveBuffer,
            checksum: checksum,
            repoUrl: repoUrl,
            branch: branch,
            processId: processId,
            sub: sub,
            name: name,
            surname: surname,
            email: email
        });
        if (!sendResult.success) {
            const {message, error} = sendResult;
            return Object.assign(result, {message, error});
        }
 
        result.success = true;
    } catch (err) {
        const traceId = uuidv4();
        logger.error(() => `${traceId}: Error when put-content with bb adapter`, err);
        result.success = false;
        result.message = `Непредвиденная ошибка: ${traceId}`;
        result.error = err.message;
    }
 
    return result;
};
 
/**
 * @typedef {{
 *     content: object,
 *     rootPath: string,
 *     userInfo?: {
 *       sub?: string,
 *       name?: string,
 *       surname?: string,
 *       email?: string
 *     }
 * }} CommitData
 */
 
/**
 *
 * @param {CommitData} data
 */
export const commitToBitbucket = (data) => {
    const mode = process.env.VUE_APP_DOCHUB_BITBUCKET_MODE;
    logger.debug(() => [
        `Write files to bb with mode ${mode}`,
        {title: 'fileNames', obj: Object.keys(data?.content)}
    ]);
    switch (mode) {
        case 'v1':
            return commitToBitbucketApiV1(data);
        case 'v2':
            return commitToBitbucketApiV2(data);
        case 'adapter':
            return commitToBitbucketApiAdapter(data);
        default:
            throw Error('Некорректно указано значение VUE_APP_DOCHUB_BITBUCKET_MODE');
    }
};