How to create the pull request in Bitbucket from command line - command-line

what is the command to create a new pull request in Bitbucket.
I am automating the check-in the code to Bitbucket and create pull request.
I referred many documents and found the curl command. but it is also not working and I don't know the what is the use of each module in that command.
see the below command that I have tried.
curl -u username:Password -H "Content-Type: application/jso https://bitbucket.server.com/rest/api/1.0/projects/myProject/repos/myRepo/pull-requests -X POST --data #req.json
created the req.json file, copied the content to file
see the below content that I copied.
{"title":"test","description":"test","fromRef":{"id":"refs/heads/del","repository":{"slug":"BB_repo","name":null}},"toRef":{"id":"refs/heads/master","repository":{"slug":"BB_repo","name":null}}}
can anyone suggest me the better way to create pull request? I need some explanation as I'm new to Bitbucket

Using a bitbucket personal access token, you could create an alias or adapt these to a script.
Global Config
[bitbucket]
url = https://bitbucket.<domain>/rest/api/latest/projects/<proj>/repos/<repo>/pull-requests
token = <Enter PAT Here>
[alias "pr"]
m = "!f() { B=$(git branch-name);D=$(git pr.data $B master);U=$(git config --get bitbucket.url);J=$(git pr.json);T=$(git pr.token);C=$(echo curl -X POST $U -H $T -H $J -d $D;); eval $C; }; f"
d = "!f() { B=$(git branch-name);D=$(git pr.data $B develop);U=$(git config --get bitbucket.url);J=$(git pr.json);T=$(git pr.token);C=$(echo curl -X POST $U -H $T -H $J -d $D;); eval $C; }; f"
json = "!echo '\"Content-Type: application/json\"'"
token = "!echo '\"Authorization: Bearer '$(git config --get bitbucket.token)'\"'"
data = !sh -c 'echo -e \"\\x27{\\\"title\\\":\\\"$1 - $2\\\",\\\"fromRef\\\":{\\\"id\\\":\\\"refs/heads/$1\\\"},\\\"toRef\\\":{\\\"id\\\":\\\"refs/heads/$2\\\"""}}\\x27\"' -
[alias]
branch-name = !git rev-parse --abbrev-ref HEAD
Usage:
git pr.m
git pr.d

Related

Saving a list of a public Github repo contributors using curl

I'm trying to get a list of contributors to a public GitHub repo, saved as a text file.
curl -H "Authorization: token mytoken" https://api.github.com/repos/v2fly/v2ray-core/contributors&per_page=100 >> output.txt
I get the output in the terminal, but not to the file. Also, the request doesn't seem to close. What am I doing wrong?
I guess the API URL is incorrect. That per_page querystring needs to be passed after putting "?" after URL, You can try this
curl -H "Authorization: token mytoken" https://api.github.com/repos/v2fly/v2ray-core/contributors?per_page=100 >> output.txt

Using new github tokens to list and create comments on pull requests

After I switched to the new Github Token format, I am not able anymore to perform a call for this github API:
https://docs.github.com/en/rest/issues/comments#list-issue-comments
My script does the following:
[[ -z "$GITHUB_REPO_SLUG" ]] && export GITHUB_REPO_SLUG="$TRAVIS_REPO_SLUG"
GITHUB_API_BASE_URL="https://api.github.com/repos/${GITHUB_REPO_SLUG}"
GITHUB_AUTH_HEADER="Authorization: token $GITHUB_TOKEN"
comment_ids=$(curl -s -H "$GITHUB_AUTH_HEADER" "$GITHUB_API_BASE_URL/issues/$pull_request_id/comments" \
| jq --arg USER "$GITHUB_USER" -r '. | map(select(.user.login==$USER)) | map(.id) | .[]')
for comment_id in $(echo $comment_ids); do
jq -n -r --arg message "$message" '{ body: $message }' \
| curl -s -H "$GITHUB_AUTH_HEADER" "$GITHUB_API_BASE_URL/issues/comments/$comment_id" -X PATCH --data #- > /dev/null
echo "Edited comment with id $comment_id of PR $pull_request_id"
done
The api call that list comments ids responds:
{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest/reference/issues#list-issue-comments"
}
This still works using tokens in the old format, but doesn't with tokens in the new format.
Is there any way to use the GHP to call that api?
The github user associated with the github token must be provided writing access to the repository.
Since this was missing API responded 404 (default behaviour set for Github APIs).

Check scopes of GitHub token

I want to passively check the permissions (scopes) of a GitHub security token passively (without pushing something into a repository). I tried the following command. I replaced your_username: your access token and the URL of my repo. But it shows an error.
curl: (3) URL using bad/illegal format or missing URL
curl -u your_username:your_access_token \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/octocat/hello-world/collaborators/USERNAME/permission
If the goal is to determine which scopes a token has access to, check the response header with prefix x-oauth-scopes (using curl with -I):
$ GITHUB_TOKEN=ghp_DefineYourOwnToken
$ curl -sS -f -I -H "Authorization: token ${GITHUB_TOKEN}" https://api.github.com | grep ^x-oauth-scopes: | cut -d' ' -f2- | tr -d "[:space:]" | tr ',' '\n'
Note that tr -d "[:space:]" above is essential for removing some unusual whitespace, failing which a matching command such as grep -x doesn't subsequently work correctly.
Sample output 1:
gist
repo
workflow
Sample output 2:
delete:packages
public_repo
read:packages
repo:invite
repo:status
Credit: answer by VK

How do you create a project in a specific group via GitLab API?

I tried to use GitLab API to create a new project. This worked, but this is in my user space:
curl \
--header "Authorization: Bearer ${GITLAB_API_TOKEN}" \
--request POST \
"https://gitlab.com/api/v4/projects/?name=$test-proj"
But I wanted to do it under a specific group with group_id <group_id> (I blanked it here). The most sensible approach that occured to me was:
curl \
--header "Authorization: Bearer ${GITLAB_API_TOKEN}" \
--request POST \
"https://gitlab.com/api/v4/groups/<group_id>/projects/?name=test-proj
But this did not work. Are there any suggestions on how I could achieve this?
I consulted the following references
https://forum.gitlab.com/t/create-a-new-project-in-a-group-using-api/1552
https://docs.gitlab.com/ee/api/projects.html#create-project
The GitLab documentation mentions the path or namespace_id attribute (although I would actually be in search of a group_id attribute). I am not sure about path and how to specify that. I tried - without success - to retrieve the namespace_id via
curl --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" "https://gitlab.example.com/api/v4/namespaces"
It is well possible that I might not have the rights to do the required operation. Therefore a reference to an official (GitLab) documentation together with a test curl command that works would be very helpful to me - thank you!
For anyone looking for the direct command:
STEP 1:
Navigate as below and identify the group ID from GUI:
Admin Area -> Groups -> GroupName
STEP 2:
Construct the command with two parameters viz., name, namespace_id
curl --header "PRIVATE-TOKEN: <myprivatetoken>" -X POST "https://gitlab.com/api/v4/projects?name=myexpectedrepo&namespace_id=38"
Both users and groups are considered "namespaces" as far as the Gitlab API is concerned, so you can use either a group ID or a username in the namespace_id field. You can see this in use by getting a single namespace with either a Group ID (that you can see in the /groups API call, or from a Group's "profile" page) or a username:
# this will show the namespace details of the Group with ID 54
curl --header "PRIVATE-TOKEN: ${TOKEN}" "https://gitlab.com/api/v4/namespaces/54
# this will show the namespace details of the User with username my-username
curl --header "PRIVATE-TOKEN: ${TOKEN}" "https://gitlab.com/api/v4/namespace/my-username
If you have the appropriate access level, you can assign a git remote to your local repository that includes your group name. Then, the push event will trigger GitLab to create the remote repository.
$ mkdir project_name && cd $_
$ echo "# project_name" > README.md
$ git init; git add .; git commit -m initial
$ GITLAB_HOST="gitlab.com"
$ git remote add origin git#${GITLAB_HOST}:group_name/project_name.git
$ git push origin HEAD
Then, point your browser to ${GITLAB_HOST}/group_name/project_name
https://docs.gitlab.com/ee/user/group/#specify-who-can-add-projects-to-a-group

AzureDevops Api call for pull-request doesn't work

I'm referring to this page, to create a pull request during the build process in Azure DevOps via API call. I'm using authorization as Bearer using $(System.AccessToken) instead of PAT credentials. In my previous steps, I used Bearer with $(System.AccessToken) to get the buildNumber via API call which worked seamlessly. However, if I use the same in my below task for the POST mechanism to create a pull request it doesn't work and gives me 400 error code.
Can anyone suggest to me, how can I make this work?
- task: Bash#3
inputs:
targetType: 'inline'
script: |
echo 'Started createing pull-request'
url="https://dev.azure.com/{Organization name}/{Project name}/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
echo $url
ret=$(curl -d '{"sourceRefName": $(BUILD.SOURCEBRANCH), "targetRefName": "refs/heads/devlopment", "title": "test", "description": "test" }' -X POST -H "Authorization:Bearer $(System.AccessToken)" -H "Content-Type:application/json" ${url} --write-out "%{http_code}" --output response.json)
echo $ret
cat response.json
The error was in JSON. Fixed and reformatted JSON all working now. This is the task now looks like with some extra addition:
Title and Description are parameterized.
- task: Bash#3
displayName: Creating Pull request
inputs:
targetType: 'inline'
script: |
url="$(System.TeamFoundationCollectionUri)/$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
ret=$(curl -X POST \
--silent \
-H "Authorization:Bearer $(System.AccessToken)" \
-H "Content-Type:application/json" \
${url} \
--write-out "%{http_code}" \
--output response.json \
-d'{
"sourceRefName":"$(BUILD.SOURCEBRANCH)",
"targetRefName":"refs/heads/<branch-name>",
"title":"$(Title)",
"description":"$(Description)"
}' )
if [[ $ret -ne 201 ]];
then
message=$(cat response.json | jq '.message' --raw-output)
echo "##vso[task.logissue type=error;] ERROR MESSAGE: ${message}"
exit 1
fi
continueOnError: false
Did you check your URL?
In your example:
url="https://dev.azure.com/{Organization name}/{Project name}/_apis/git/REPOSITORIE/$(Build.Repository.ID)/pullrequests?api-version=6.0"
should be
url="https://dev.azure.com/{Organization name}/{Project name}/_apis/git/REPOSITORIES/$(Build.Repository.ID)/pullrequests?api-version=6.0"
GIT Pullrequest
I was trying to use your code, yet I had a problem
MESSAGE: TF401027: You need the Git 'PullRequestContribute' permission to perform this action. Details: identity 'Build\c5f6a8a4-de0a-4081-bff4-928a38d232c4', scope 'repository'.
The solution comes from
https://developercommunity.visualstudio.com/t/tf401027-you-need-the-git-pullrequestcontribute-pe/1441618
Navigate to Project Settings >> Repositories >> select Security tab >> Type Project Collection Build Service (organizationName) in the search box >> check if the Contribute to pull requests permission is set to Allow.
You need to search for this 'Project Collection Build Service' and only then it would appear on your list. There is no add button, only 'search'.
https://dev.azure.com/{owner}/{project}/_settings/repositories?_a=permissions
(example) https://dev.azure.com/jmusz/iospoc/_settings/repositories?_a=permissions
My code was based on yours, an example of a plain curl without an error handling is
- task: Bash#3
displayName: Creating Pull request
inputs:
targetType: 'inline'
script: |
url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
echo $url
curl -X POST \
-v \
-H "Authorization: Bearer $(System.AccessToken)" \
-H "Content-Type: application/json" \
${url} \
--write-out "%{http_code}" \
--output response.json \
-d'{
"sourceRefName": "$(BUILD.SOURCEBRANCH)",
"targetRefName": "refs/heads/dest",
"title": "Title",
"description": "Description"
}'
cat response.json
As you might guess, when I could not find PullRequestContribute (took me a while), I had a 'Plan B' that was to use a Personal Access Token...
Turns out, there is a difference with Authorization header:
$(System.AccessToken) - you can use it directly, with -H "Authorization: Bearer $(System.AccessToken)"
while PAT must be extended with a (username:PAT) that is encoded with BASE64, and Basic not Bearer so you use -H "Authorization: Basic ${b64pat}" \
The code for PAT is:
- task: Bash#3
displayName: Creating Pull request
inputs:
targetType: 'inline'
script: |
url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
echo $url
#works
b64pat=`echo -n 'jmusz:ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk' | base64`
#works (empty username)
b64pat=`echo -n ':ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk' | base64`
#not working (missing `:` )
#b64pat=`echo -n 'ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk' | base64`
#echo $b64pat
#-H "Authorization: Bearer $(System.AccessToken)" \ #require PullRequestContribute
#-H "Authorization: Basic ${b64pat}" \ # user:PAT | base64
ret=$(curl -X POST \
-v \
-H "Authorization: Basic ${b64pat}" \
-H "Content-Type: application/json" \
${url} \
--write-out "%{http_code}" \
--output response.json \
-d'{
"sourceRefName": "$(BUILD.SOURCEBRANCH)",
"targetRefName": "refs/heads/dest",
"title": "Title",
"description": "Description"
}' )
if [[ $ret -ne 201 ]];
then
message=$(cat response.json | jq '.message' --raw-output)
echo "##vso[task.logissue type=error;] ERROR MESSAGE: ${message}"
#cat response.json
exit 1
fi
PAT with powershell
- task: PowerShell#2
displayName: Creating Pull request - PS
inputs:
targetType: 'inline'
script: |
$url = "https://dev.azure.com/jmusz/iospoc/_apis/git/repositories/iospoc/pullrequests?api-version=6.0"
$sourceBranch = "refs/heads/source"
$targetBranch = "refs/heads/dest"
$title = "title"
$description = "description"
$MyPat = 'ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk'
$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(":$MyPat")) #Note : !!!!
$B64Pat
$header = #{ Authorization = "Basic $B64Pat" }
$body = #{
sourceRefName = "$sourceBranch"
targetRefName = "$targetBranch"
title = "$title"
description = "$description"
}
$jsonBody = ConvertTo-Json $body
try {
$response = Invoke-RestMethod -Uri $url -Method Post -Headers $header -Body $jsonBody -ContentType "application/json;charset=UTF-8"
}
catch {
Write-Error $_
Write-Error $_.Exception.Message
}
$response
GIT repo clone with Token
I had to pass credentials to repo to a task in pipeline, I decided the best would be to use $(System.AccessToken) (plan B was with PAT).
I faced the same problem as above - Bearer $(System.AccessToken) vs Basic ${b64pat}
Please note that username is optional when used with PAT (for git clone) while it is not optional when used for API interaction
- stage: Lint
jobs:
- job: SwiftLint
steps:
- bash: |
b64pat=`echo -n jmusz:ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk |base64`
echo 1 not working
git clone $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.ID) ||true
#rm -rf libraries ||true
echo 2 not working
#not working
git -c http.extraHeader="Authorization: Basic $(System.AccessToken)" clone $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.Name) ||true
rm -rf iospoc ||true
echo 2.1 working
#working
git -c http.extraHeader="Authorization: Bearer $(System.AccessToken)" clone $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.Name) ||true
rm -rf iospoc ||true
echo 3 working
git -c http.extraHeader="Authorization: Basic ${b64pat}" clone $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.Name) ||true
#git -c http.extraHeader="Authorization: Basic $(System.AccessToken)" clone https://dev.azure.com/jmusz/iospoc/_git/libraries/ ||true
rm -rf libraries ||true
echo 4 not working
git clone "https://jmusz:$(System.AccessToken)#dev.azure.com/jmusz/iospoc/_git/libraries" ||true
rm -rf libraries ||true
echo 4.01 not working
git clone "https://$(System.AccessToken)#dev.azure.com/jmusz/iospoc/_git/libraries" ||true
rm -rf libraries ||true
echo 4.1 working
git clone "https://jmusz:ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk#dev.azure.com/jmusz/iospoc/_git/libraries" ||true
rm -rf libraries ||true
echo 4.2 working
git clone "https://ljfcuww24sa7ywmgvlvuwrn3v7znmuvbnfymfh4xtnt3tbo6bk#dev.azure.com/jmusz/iospoc/_git/libraries" ||true
rm -rf libraries ||true
#not working
echo 5 not working
git clone https://${b64pat}#dev.azure.com/jmusz/iospoc/_git/libraries ||true
rm -rf libraries ||true
#not working
echo 6 not working
git clone https://$(System.AccessToken)#dev.azure.com/jmusz/iospoc/_git/libraries ||true
rm -rf libraries ||true
#working
echo 7 working
git config --global --add http.https://dev.azure.com/jmusz/iospoc/_git/libraries.extraHeader "AUTHORIZATION: Basic ${b64pat}"
git clone https://dev.azure.com/jmusz/iospoc/_git/libraries/ ||true
rm -rf libraries ||true
#not working?
echo 8 not working
git config --global --add http.https://dev.azure.com/jmusz/iospoc/_git/libraries.extraHeader "AUTHORIZATION: Bearer $(System.AccessToken)"
git clone https://dev.azure.com/jmusz/iospoc/_git/libraries/ ||true
rm -rf libraries ||true
Interesting that 2.1 works while 8 does not