How can an AWS CodeBuild job see which files have changed?
Asked Answered
C

2

4

I'm trying to set up an AWS CodeBuild project to run tests to validate PRs and commits on a GitHub repository.

Because of the nature of the repo (a monorepo combining several ML models):

  • I need to restrict down to only run tests associated with files changed in the PR/commit to keep time+cost under control, but
  • The tests will typically require reference to other un-changed files in the repo: So can't just only pull changed files through to the build container.

How can a running CodeBuild build triggered by a GitHub PR (as per the docs here) 'see' which files are changed by the PR to selectively execute tests?

Context answered 11/5, 2021 at 9:23 Comment(0)
S
3

You can use git diff --name-only $CODEBUILD_RESOLVED_SOURCE_VERSION $CODEBUILD_WEBHOOK_PREV_COMMIT

Where $CODEBUILD_WEBHOOK_PREV_COMMIT is the commit id of the previous commit. And $CODEBUILD_RESOLVED_SOURCE_VERSION is the commit id of the actual one.

Inside a build phase you can check the change with:

- |
    if [ "$(git diff --name-only $CODEBUILD_RESOLVED_SOURCE_VERSION $CODEBUILD_WEBHOOK_PREV_COMMIT | grep -e <filde_path>)" != "" ]; then
      #your code;
    fi
Scamp answered 19/10, 2022 at 15:12 Comment(3)
Belated thanks! I think I ended up finding that different repo sources (CodeCommit, GitHub, etc) and trigger types (direct, via CodePipeline, etc) could reflect differently in the various env vars CodeBuild sets? For GitHub e.g. pull requests could also refer to their compare APIContext
We use it with a GitHub repo, and works. I don't know if it works for other repos like Bitbucket.Heshvan
relevant codebuild docs: build-env-ref-env-varsWaggish
R
2

In your buildspec file you can perform shell commands, I think you can use some git commands there and echo the result, so you can see them as logs during the build.

Resistencia answered 11/5, 2021 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.