Skip to content

Commit

Permalink
Merge pull request #19 from zvercodebender/master
Browse files Browse the repository at this point in the history
Create Bitbucket Tiles and refactor Stash Tiles
  • Loading branch information
Rick Broker authored Sep 30, 2019
2 parents 158fed5 + 2d1f631 commit 390a8fc
Show file tree
Hide file tree
Showing 33 changed files with 876 additions and 176 deletions.
25 changes: 15 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ This plugin offers an interface from XL Release to Atlassian Stash(Now Bitbucket
+ `stash.DeclinePullRequest` : This task can be used to Decline a pull request
+ `stash.WaitForMerge` : This task waits and polls stash to check the status of a Pull request Merge Status
+ `stash.DownloadCode` : This task allows to export a code zip file that can be downloaded to a specified folder on XL Release server locally for a provided branch in repository. Requires [Bitbucket Server Archive plugin](https://marketplace.atlassian.com/plugins/com.atlassian.stash.plugin.stash-archive/server/overview)
+ `stash.searchFileContent` : This task allows to search a file's content in a repository/branch using a provided pattern and return group0 and group1 as results. eg.
+ `stash.searchFileContent` : This task allows to search a file's content in a repository/branch using a provided pattern and return group0 and group1 as results. eg.

```
version[ ]*=[ ]*(\d+)
Expand All @@ -68,19 +68,19 @@ This plugin offers an interface from XL Release to Atlassian Stash(Now Bitbucket
+ `stash.TagRelease` : This task adds a tag to a branch



# Commit Trigger Usage #

* Stash commit trigger configuration
![](images/stash/stashcommittrigger1.png)
![](images/stash/stashcommittrigger2.png)

# Bitbucket Tasks Usage #

* Setup the server configuration
![](images/bitbucket/config.png)

* Create pull request
* Create pull request
![](images/bitbucket/createpullrequest.png)

* Merge pull request
Expand All @@ -90,17 +90,17 @@ This plugin offers an interface from XL Release to Atlassian Stash(Now Bitbucket
![](images/bitbucket/waitformerge.png)


* Download Code
* Download Code
![](images/bitbucket/downloadcodezip.png)


# Stash Tasks Usage #


* Setup the server configuration
![](images/stash/config.png)

* Create pull request
* Create pull request
![](images/stash/createpullrequest.png)

* Merge pull request
Expand All @@ -112,13 +112,13 @@ This plugin offers an interface from XL Release to Atlassian Stash(Now Bitbucket
* Decline pull request
![](images/stash/declinepullrequest.png)

* Delete branch
* Delete branch
![](images/stash/deletebranch.png)

* Search file content
![](images/stash/searchfilecontent.png)

* Download Code
* Download Code
![](images/stash/downloadcodezip.png)

* Get Pull Request
Expand All @@ -127,8 +127,13 @@ This plugin offers an interface from XL Release to Atlassian Stash(Now Bitbucket
* Tag Release
![](images/stash/tagrelease.png)

* Query Commits
![](images/stash/querycommits.png)

* Stash Dashboard
![](images/stash/stash-dashboard.png)

# References #

[Stash/Bitbucket Server REST API](https://developer.atlassian.com/stash/docs/latest/reference/rest-api.html)
[Bitbucket Cloud REST API](https://confluence.atlassian.com/bitbucket/use-the-bitbucket-cloud-rest-apis-222724129.html)

2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ xlDocker {
compileVersion = '9.0'
runImage = 'xebialabsunsupported/xlr_dev_run'
runVersion = '9.0'
runPortMapping = '15516:5516'
runPortMapping = '5516:5516'
}


Expand Down
Binary file added images/stash/querycommits.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/stash/stash-dashboard.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 46 additions & 10 deletions src/main/resources/bitbucket/Bitbucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
from com.xebialabs.overthere.local import LocalConnection
from com.xebialabs.overthere.OperatingSystemFamily import UNIX
from java.lang import String

import org.slf4j.Logger as Logger
import org.slf4j.LoggerFactory as LoggerFactory

class BitbucketClient(object):
def __init__(self, server, username, password):
self.logger = LoggerFactory.getLogger("com.xebialabs.bitbucket-plugin")
creds = CredentialsFallback(server, username, password).getCredentials()
self.http_request = HttpRequest(server, creds['username'], creds['password'])

Expand Down Expand Up @@ -66,10 +68,10 @@ def bitbucket_createpullrequest(self, variables):
str(variables['source']),
str(variables['target']),
str(variables['closebranch']).lower())
print "Submitting Pull Request %s using endpoint %s" % (content, endpoint)
self.logger.warn( "Submitting Pull Request %s using endpoint %s" % (content, endpoint) )
response = self.api_call('POST',endpoint, body = content, contentType="application/json")
data = json.loads(response.getResponse())
print "Pull Request created with ID %s " % data['id']
self.logger.warn( "Pull Request created with ID %s " % data['id'] )
return {'output' : data, 'prid' : data['id']}

def bitbucket_mergepullrequest(self, variables):
Expand All @@ -79,24 +81,24 @@ def bitbucket_mergepullrequest(self, variables):
"close_source_branch": %s
}''' % (str(variables['message']),
str(variables['closebranch']).lower())
print "Merging Pull Request %s using endpoint %s" % (content, endpoint)
self.logger.warn( "Merging Pull Request %s using endpoint %s" % (content, endpoint) )
response = self.api_call('POST',endpoint, body = content, contentType="application/json")
data = json.loads(response.getResponse())
print "Pull Request %s merged sucessfully with STATE : %s" % ( data['id'], data['state'])
self.logger.warn( "Pull Request %s merged sucessfully with STATE : %s" % ( data['id'], data['state']) )
return {'output' : data}

def bitbucket_waitformerge(self, variables):
endpoint = "/2.0/repositories/%s/pullrequests/%s" % (str(variables['repo_full_name']), str(variables['prid']))
print "Waiting for Merge Pull Request %s using endpoint %s" % (str(variables['prid']), endpoint)
self.logger.warn( "Waiting for Merge Pull Request %s using endpoint %s" % (str(variables['prid']), endpoint) )
isClear = False
while (not isClear):
response = self.api_call('GET',endpoint, contentType="application/json")
data = json.loads(response.getResponse())
if data['state'] == "MERGED" :
isClear = True
print "Pull Request %s merged sucessfully with STATE : %s" % (data['id'], data['state'])
self.logger.warn( "Pull Request %s merged sucessfully with STATE : %s" % (data['id'], data['state']) )
else:
print "Pull Request %s : current STATE :[ %s ], retrying after %s seconds\n" % (data['id'], data['state'], str(variables['pollInterval']) )
self.logger.warn( "Pull Request %s : current STATE :[ %s ], retrying after %s seconds\n" % (data['id'], data['state'], str(variables['pollInterval']) ) )
time.sleep(variables['pollInterval'])
return {'output' : data}

Expand All @@ -106,7 +108,7 @@ def bitbucket_downloadcode(self, variables):

capturedOutput = ""

print "Cleaning up download folder : %s" % variables['downloadPath']
self.logger.warn( "Cleaning up download folder : %s" % variables['downloadPath'] )
command = CmdLine()
command.addArgument("rm")
command.addArgument("-rf")
Expand All @@ -116,7 +118,7 @@ def bitbucket_downloadcode(self, variables):
exit_code = connection.execute(output_handler, error_handler, command)
capturedOutput = self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

print " Now downloading code in download folder : %s" % variables['downloadPath']
self.logger.warn( " Now downloading code in download folder : %s" % variables['downloadPath'] )
command = CmdLine()
script = '''
cd %s
Expand Down Expand Up @@ -146,3 +148,37 @@ def bitbucket_downloadcode(self, variables):
capturedOutput += self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

return {'output': capturedOutput}

def bitbucket_commitsquery(self, variables):
self.logger.warn("bitbucket_commitsquery-> START")
data = self.bitbucket_querycommits(variables)
commits = data
#self.logger.warn( "Build commitList\n %s" % json.dumps(commits, indent=4, sort_keys=True) )
commitList = []
self.logger.warn("bitbucket_commitsquery-> Loop over commits")
for commit in commits:
self.logger.warn( "message ~%s~" % commit['message'] )
commitList.append( commit['message'] )
results = { "output": data, "commitList": commitList }
self.logger.warn( "results\n %s" % json.dumps(results, indent=4, sort_keys=True) )
return results

def bitbucket_querycommits(self, variables):
endpoint_get = "/2.0/repositories/%s/commits/%s" % (variables['repo_full_name'], variables['branch'] )
endpoint_get = "%s?limit=%s" % (endpoint_get, variables['results_limit'])
if ( variables['tag'] is not None ):
endpoint_get = "%s&at=refs/tags/%s" % (endpoint_get, variables['tag'])
self.logger.warn( "endpoint = %s" % endpoint_get )
response = self.api_call('GET', endpoint_get, contentType="application/json", Origin = variables['server']['url'])
data = response.getResponse()
data = json.loads(data)['values']
self.logger.warn( "DATA2 = %s" % json.dumps(data, indent=4, sort_keys=True) )
return data

def bitbucket_querymergerequests(self, variables):
endpoint = "2.0/repositories/%s/pullrequests?state=%s" % (variables['repo_full_name'], variables['state'])
self.logger.warn( "URL = %s" % endpoint )
response = self.api_call('GET', endpoint, contentType="application/json", Origin = variables['server']['url'])
data = json.loads( response.getResponse() )['values']
self.logger.warn( "merge_requests = %s" % json.dumps(data, indent=4, sort_keys=True) )
return data
24 changes: 24 additions & 0 deletions src/main/resources/bitbucket/CommitsTile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from bitbucket.Bitbucket import BitbucketClient
import json

if ( server == "" or repo_full_name == "" ):
values = []
data = {"commits": values }
exit(0)

def getCommits( variables ):
bitbucket = BitbucketClient.get_client(server, username, password)
results = bitbucket.bitbucket_querycommits( variables )
return {"commits": {"parents": results } }

data = getCommits( locals() )
45 changes: 45 additions & 0 deletions src/main/resources/bitbucket/ContributionsTile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from bitbucket.Bitbucket import BitbucketClient
import json

if ( server == "" or repo_full_name == "" ):
values = []
data = {"commits": values }
else:
bitbucket = BitbucketClient.get_client(server, username, password)
data = bitbucket.bitbucket_querycommits( locals() )
commits = data

authors = {}
committers = {}
people = []
for commit in commits:
print "commit: %s" % json.dumps(commit, indent=4, sort_keys=True)
if commit['author']['user']['nickname'] in authors.keys():
authors[commit['author']['user']['nickname']] += 1
else:
authors[commit['author']['user']['nickname']] = 1
if commit['author']['user']['nickname'] not in people:
people.append(commit['author']['user']['nickname'])

if commit['author']['user']['nickname'] in committers.keys():
committers[commit['author']['user']['nickname']] += 1
else:
committers[commit['author']['user']['nickname']] = 1
if commit['author']['user']['nickname'] not in people:
people.append(commit['author']['user']['nickname'])

data = {
"commits": commits,
"authors": [{"name":author,"value":authors[author]} for author in authors.keys()],
"committers": [{"name":committer,"value":committers[committer]} for committer in committers.keys()],
"people": people
}
19 changes: 19 additions & 0 deletions src/main/resources/bitbucket/MergeRequestsTile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from bitbucket.Bitbucket import BitbucketClient
import json

if ( server == "" or repo_full_name == "" ):
values = []
data = {"merge_requests": values }
else:
bitbucket = BitbucketClient.get_client(server, username, password)
data = bitbucket.bitbucket_querymergerequests( locals() )
data = {"merge_requests": data}
55 changes: 55 additions & 0 deletions src/main/resources/bitbucket/TimelineTile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from bitbucket.Bitbucket import BitbucketClient
import json
import time
from java.time import LocalDate, ZonedDateTime
import org.slf4j.Logger as Logger
import org.slf4j.LoggerFactory as LoggerFactory

logger = LoggerFactory.getLogger("com.xebialabs.bitbucket-plugin")
def convertRFC3339ToDate(timestamp):
zonedDateTime = ZonedDateTime.parse(timestamp)
return zonedDateTime.toLocalDate()

bitbucket = BitbucketClient.get_client(server, username, password)
commits = bitbucket.bitbucket_querycommits(locals())

# Compile data for summary view
commitsByDay = {}
for commit in commits:
logger.warn("commit date %s" % commit['date'])
commitDate = convertRFC3339ToDate(commit["date"])
if commitDate in commitsByDay.keys():
commitsByDay[commitDate] += 1
else:
commitsByDay[commitDate] = 1

dates = [date for date in commitsByDay.keys()]
dates.sort()
startDate = dates[0]
endDate = dates[-1]
days = []
commitsEachDay = []
daysWithCommits = [dayCommits.toString() for dayCommits in commitsByDay.keys()]
while startDate.isBefore(endDate.plusDays(1)):
days.append(startDate.toString())
if startDate.toString() in daysWithCommits:
commitsEachDay.append(commitsByDay[startDate])
else:
commitsEachDay.append(0)
startDate = startDate.plusDays(1)

data = {
"dates": days,
"commitsEachDay": commitsEachDay,
"commits": commits
}
Loading

0 comments on commit 390a8fc

Please sign in to comment.