I'm not sure whether TeamCity knows about the pull request ID. Its unlikely because the build is done on a commit, not a pull request, and it doesn't need the pull request to post the result back to Bitbucket Server. There are certainly ways to get the information you need though.
The first option I can think of is by using Bitbucket Server's Pull Request REST API (documentation here). You'd need http credentials to do the request. I'm not sure whether TeamCity has some available for you to use, but if it doesn't then you'll want to generate a personal access token so that this script is restricted with its access.
curl -u username:password https://url.to.bitbucket/rest/api/latest/projects/<project_name>/repos/<repo_name>/pull-requests?state=OPEN&at=refs/heads/<branchname>&direction=OUTGOING
You'll then have to parse the json to get the pull request out of the response (maybe doing it in something like Python would be easier than bash). Another limitation with this is that it won't get you PRs that are from a fork.
If doing it via the REST API is too difficult (because of credentials and json parsing) you may be able to do it with just git by using git name-rev
to find the closest pull request ref. This is less conventional and I haven't actually tried doing this, so I think that there are likely going to be more edge cases to take care of, where as the REST API gives you a very straightforward answer.
Something like this:
> git fetch origin refs/pull-requests/*:refs/pull-requests/* # fetch all the pull-request refs
> git name-rev --name-only --refs="refs/pull-requests/*/from" HEAD # Find the pull request 'from' ref that is closest to the latest commit
pull-requests/11732/from~4^2
You'd have to strip out the 'number of commits' part if it is present (everything after the ~
), and work out what to do if there were multiple pull requests at that commit (name-rev will only ever give you one ref) but you won't need to set up your credentials, and it does work for PRs from forks.
Another scenario that you'll have to consider with either option is that there may not be a pull request created yet.
Hope this helps!