3

I have to develop a functionality wherein I have to pull the files from bitbucket repository using python code on linux server. Files are located in bitbucket repository itself

Can you suggest me how to do that and best way of doing that. I tried with APIs- http:///rest/api/1.0/projects//repos//browse - It gave me components level data i.e only the files name, but not the actual files content

Thanks

phd
  • 82,685
  • 13
  • 120
  • 165
anonymous
  • 31
  • 1
  • 2

1 Answers1

0

There is a python library which wraps around the rest api:

https://github.com/cosmin/stashy

Or you can use urllib2:

#!/usr/bin/python

import os
import tempfile
import sys
import urllib2
import json
import base64
import logging
import re
import pprint
import requests
import subprocess

projectKey= "FW"
repoKey = "fw"
branch = "master"
pathToVersionProperties = "core/CruiseControl/CI_version.properties"
localVersionProperties = "CI_version.properties"
bitbucketBaseUrl = "https://bitbucket.company.com/rest/api/latest"
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

def checkPersonalAccessToken():
      try:
         os.environ["PAT"]
         logging.info("Detected Personal Access Token")
      except KeyError: 
         logging.error("Personal Access Token: $PAT env variable not set, update Jenkins master with correct environment variable")
         sys.exit(1)

def getJenkinsPropertiesFile():
    restEndpoint = "{}/projects/{}/repos/{}/raw/{}".format(bitbucketBaseUrl, projectKey, repoKey, pathToVersionProperties)
    logging.info("REST endpoint : {}".format(restEndpoint))
    request = urllib2.Request(restEndpoint)
    request.add_header("Authorization", "Bearer %s" % os.environ["PAT"])
    result = urllib2.urlopen(request).read()
    return result

checkPersonalAccessToken()
propertiesString = getJenkinsPropertiesFile()

This example retrieves a properties file from bitbucket. I am not sure what version of Bitbucket you are using. The example above uses Personal Access Tokens for authentication (added in Bitbucket 5.5). You could also use standard username/password.

eeijlar
  • 1,232
  • 3
  • 20
  • 53
  • its giving me components level data like this - { "path": { }, "revision": "refs/heads/master", "children": { "values": [ { "path": { "components": [ "test.robot" ], "parent": "", "name": "test.robot", "extension": "robot", "toString": "test.robot" }},]}} but I need data under the file as well. I mean I need file name as well data inside the file which is not fetched by this API – anonymous Oct 19 '18 at 18:24