【问题标题】:Git: Get list if all commits in the latest push in a branchGit:如果分支中最新推送中的所有提交,则获取列表
【发布时间】:2021-05-21 02:32:52
【问题描述】:

我正在尝试在 gitlab-runner 中创建一个自动管道,它将应用最新 git push 中的所有更改。它正在获取推送中的最新提交(使用 gitlab-runner 中的 $CI_COMMIT_SHA 变量)。但是,如果推送有多个提交,它会忽略较旧的提交。因此,所有更改都不会应用到应用程序中。

我有以下疑问:

  1. 是否为每个 git push 分配了任何 ID?基本上给定一个 git push Id,有没有办法找到所有底层提交?
  2. gitlab-runner 有没有办法找到最新的 git push 中提交的所有文件?此外,我更愿意保持它们提交的顺序。
  3. 我看到git cherry 可以给我未推送的提交列表。有没有办法,我可以通过变量将信息传递给 gitlab-runner?

提前致谢

【问题讨论】:

  • 你可以访问 git 钩子吗?如果是这样,update 挂钩将接收引用列表、它们的旧位置和新位置。您可以使用这些来生成提交列表。

标签: git gitlab-ci-runner git-push runner git-cherry


【解决方案1】:

我通过 GitLab API 获取最新推送事件,通过在本地生成 git CLI 工具获取最新提交,然后交叉检查它们来解决这个问题。

推送事件将具有push_data 属性,它将告诉您推送中的提交范围。 https://docs.gitlab.com/ee/api/events.html#list-a-projects-visible-events

我缩短的 node.js 代码:

require('isomorphic-fetch');
const exec = require('util').promisify(require('child_process').exec);

const lastPush = await getLastPushEvent();
const commits = await listLatestCommits();

const commitsInLatestPush = [];
for (const commit of commits) {
  if (lastPush.push_data.commit_from === commit.commit) {
    break;
  }
  commitsInLatestPush.push(commit);
}

console.log(commitsInLatestPush);

async function getLastPushEvent() {
  const events = await fetch(`https://gitlab.example.com/api/v4/projects/${process.env.CI_PROJECT_ID}/events?action=pushed`, {
    headers: {
      'PRIVATE-TOKEN': process.env.PRIVATE_GITLAB_TOKEN,
    },
  });
  return events[0] || null;
}

async function listLatestCommits(count = 10) {
  const { stdout, stderr } = await exec(`git log --pretty=format:'{%n  ^^^^commit^^^^: ^^^^%H^^^^,%n  ^^^^abbreviated_commit^^^^: ^^^^%h^^^^,%n  ^^^^tree^^^^: ^^^^%T^^^^,%n  ^^^^abbreviated_tree^^^^: ^^^^%t^^^^,%n  ^^^^parent^^^^: ^^^^%P^^^^,%n  ^^^^abbreviated_parent^^^^: ^^^^%p^^^^,%n  ^^^^refs^^^^: ^^^^%D^^^^,%n  ^^^^encoding^^^^: ^^^^%e^^^^,%n  ^^^^subject^^^^: ^^^^%s^^^^,%n  ^^^^sanitized_subject_line^^^^: ^^^^%f^^^^,%n  ^^^^commit_notes^^^^: ^^^^%N^^^^,%n  ^^^^verification_flag^^^^: ^^^^%G?^^^^,%n  ^^^^signer^^^^: ^^^^%GS^^^^,%n  ^^^^signer_key^^^^: ^^^^%GK^^^^,%n  ^^^^author^^^^: {%n    ^^^^name^^^^: ^^^^%aN^^^^,%n    ^^^^email^^^^: ^^^^%aE^^^^,%n    ^^^^date^^^^: ^^^^%aD^^^^%n  },%n  ^^^^committer^^^^: {%n    ^^^^name^^^^: ^^^^%cN^^^^,%n    ^^^^email^^^^: ^^^^%cE^^^^,%n    ^^^^date^^^^: ^^^^%cD^^^^%n  }%n},' -n ${count} | sed 's/"/\\\\"/g' | sed 's/\\^^^^/"/g' | sed "$ s/,$//" | sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n/ /g'  | awk 'BEGIN { print("[") } { print($0) } END { print("]") }'`);
  if (stderr) {
    throw new Error(`Git command failed: ${stderr}`);
  }
  const data = JSON.parse(stdout);
  return data;
}

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2016-09-08
    • 2020-10-08
    • 2016-10-24
    • 2013-10-05
    • 2012-02-06
    • 2021-09-28
    • 2021-07-07
    相关资源
    最近更新 更多