>  기사  >  웹 프론트엔드  >  쉘 스크립트에서 \"Bun 스크립트\"로 마이그레이션하는 중

쉘 스크립트에서 \"Bun 스크립트\"로 마이그레이션하는 중

Barbara Streisand
Barbara Streisand원래의
2024-09-28 06:18:29608검색

Migrating from shell script to

zCloud에서 프로세스 자동화 및 인프라에 초점을 맞춘 프로젝트를 진행하다 보면 검증 및 공통 프로세스를 수행하기 위해 여러 기능을 생성해야 하는 경우가 자주 발생합니다. 하나의 운영 체제만 사용하면 모든 것이 잘 작동하지만, 둘 이상의 시스템이 관련되면 상황이 복잡해집니다.

우리의 경우 대부분의 개발이 Linux에서 이루어지지만 macOS와의 호환성도 보장해야 합니다. 이로 인해 코드 비호환성이 발생하는 경우가 많습니다.

이 문제를 해결하기 위해 Bun을 인터프리터로 사용하여 쉘 스크립트 기능을 JavaScript 파일로 마이그레이션하고 있습니다. Bun은 Shell API 기능을 통해 쉘처럼 명령을 실행하는 간단한 방법을 제공하기 때문에 선택했습니다.

아래는 인프라 수정을 적용하기 전에 코드 변경 사항을 확인하는 데 사용하는 기능의 예입니다.

쉘 스크립트 코드:

function zc_check_pristine_git() {
    if [ "$ZC_CURRENT_ENV" = "staging" ] || [ "$ZC_CURRENT_ENV" = "dev" ]; then
      return 0
    fi

    local not_pristine=0
    local modified_files=""

    # Check for staged but uncommitted changes
    staged_changes=$(git diff --name-only --cached)
    if [ -n "$staged_changes" ]; then
        not_pristine=1
        modified_files+="Staged changes:\n$staged_changes"
    fi

    # Check for unstaged changes
    unstaged_changes=$(git diff --name-only)
    if [ -n "$unstaged_changes" ]; then
        not_pristine=1
        modified_files+="Unstaged changes:\n$unstaged_changes"
    fi

    # Check for untracked files
    untracked_files=$(git ls-files --others --exclude-standard)
    if [ -n "$untracked_files" ]; then
        not_pristine=1
        modified_files+="Untracked files:\n$untracked_files"
    fi

    # Check if the current branch is ahead of the remote
    ahead_commits=$(git log @{u}.. --oneline)
    if [ -n "$ahead_commits" ]; then
        not_pristine=1
        modified_files+="Commits ahead of the remote:\n$ahead_commits\n\n"
    fi

    if [ $not_pristine -eq 1 ]; then
        echo -e "$modified_files"
        return 1
    fi

    return 0
}

이 코드를 JavaScript로 변환하기 위해 프로젝트의 bin 디렉토리(이미 PATH에 있음)에 다음 내용이 포함된 zc_check_pristine_git이라는 파일을 생성했습니다.

#!/usr/bin/env bun
// @language JavaScript

import { checkPristineGit } from '../js/helpers/helpers.js';

await checkPristineGit({ currentEnv: process.env.ZC_CURRENT_ENV });

우리는 Bun을 인터프리터로 사용하고 있음을 나타내기 위해 shebang #!/usr/bin/env bun을 사용했습니다.

IDE에서 해당 파일을 JavaScript로 인식할 수 있도록 //@언어 JavaScript 주석을 추가했습니다(저희는 주로 Jetbrains 도구를 사용합니다).

그런 다음 실제로 실행될 함수를 가져왔습니다.

쉘에서 JavaScript로 변환된 함수 구현:

export const checkPristineGit = async ({ currentEnv }) => {
  exitOnError(() => {
    notEmpty(currentEnv, 'currentEnv is required');
  });
  if (['staging', 'dev'].includes(currentEnv)) {
    return;
  }

  let notPristine = 0;
  let modifiedFiles = '';

  // Check for staged but uncommitted changes
  const stagedChanges = await $`git diff --name-only --cached`.text();
  if (stagedChanges !== '') {
    notPristine = 1;
    modifiedFiles += `Staged changes:\n${stagedChanges}`;
  }

  // Check for unstaged changes
  const unstagedChanges = await $`git diff --name-only`.text();
  if (unstagedChanges !== '') {
    notPristine = 1;
    modifiedFiles += `Unstaged changes:\n${unstagedChanges}`;
  }

  // Check for untracked files
  const untrackedFiles = await $`git ls-files --others --exclude-standard`.text();
  if (untrackedFiles !== '') {
    notPristine = 1;
    modifiedFiles += `Untracked files:\n${untrackedFiles}`;
  }

  // Check if the current branch is ahead of the remote
  const aheadCommits = await $`git log @{u}.. --oneline`.text();
  if (aheadCommits !== '') {
    notPristine = 1;
    modifiedFiles += `Commits ahead of the remote:\n${aheadCommits}`;
  }

  if (notPristine) {
    console.warn('Error: You can only apply changes in production environments if the repository is in a pristine state.');
    console.warn(modifiedFiles);
    process.exit(1);
  }
};

이런 방식으로 우리는 쉘 스크립트처럼 실행될 표준화된 JavaScript 코드를 갖게 되었습니다.


제공된 예제에 구현되지 않은 함수 호출(exitOnError, notEmpty)이 있습니다.

위 내용은 쉘 스크립트에서 \"Bun 스크립트\"로 마이그레이션하는 중의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.