Home > Back-end >  GitHub Actions - copy git `user.name` and `user.email` from last commit
GitHub Actions - copy git `user.name` and `user.email` from last commit

Time:11-08

I have a GitHub Action which runs on any push to my repo. Basically, it compiles the repo files, commits the compiled files, squashes that commit into the previous one, then force pushes to the repo.

Essentially, the idea is that it seamlessly creates a build and adds it to the repo, to make it look like this was part of the original push.

The only problem I'm having is with git config. I want to be able to copy the user.name and user.email from the last commit, so that when my action performs its commit, it looks like it was done by the user who pushed. I know I can use the GITHUB_ACTOR environment variable to get the username, but there doesn't seem to be an env variable which gives the email. And GitHub works out that they're not the same:

enter image description here

So, how can I set git config to use the user.name and user.email from the last commit?


Here is the action's .yaml file for completeness:

on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Set up Git repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 2
      - (... step that creates build files ...)
      - name: Upload build files to repo
        run: |
          # Configure git
          git config user.name "$GITHUB_ACTOR"
          git config user.email "<>"
          # Roll back git history to before last commit
          # This also adds all changes in the last commit to the working tree
          git reset --soft HEAD~1
          # Add build files to working tree
          git add (build files)
          # Commit changes and build files using same commit info as before 
          git commit -C HEAD@{1}
          # Force push to overwrite git history
          git push --force

CodePudding user response:

From the git manual, you can get the username and email of the user who made the last commit by running:

git log -n 1 --pretty=format:%an    # username
git log -n 1 --pretty=format:           
  • Related