Git:获取分支最新推送中所有提交的列表

5

我正试图在 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 钩子将接收到参考列表、它们的旧位置和新位置。您可以使用这些来生成提交列表。 - Noufal Ibrahim
1个回答

0

我通过使用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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接