Skip to content

Instantly share code, notes, and snippets.

@sybrex
Last active June 26, 2022 12:52
Show Gist options
  • Save sybrex/ade297aeae4724735df5c5c674f028ab to your computer and use it in GitHub Desktop.
Save sybrex/ade297aeae4724735df5c5c674f028ab to your computer and use it in GitHub Desktop.
Bitbucket repositories list and clone
import argparse
import json
import os
import requests
import sys
import subprocess
from requests.auth import HTTPBasicAuth
def get_reps(login: str, password: str, workspace: str) -> list:
reps = []
page = 1
pagelen = 100
url = f'https://api.bitbucket.org/2.0/repositories/{workspace}?page={page}&pagelen={pagelen}'
while url:
request = requests.get(url, auth=HTTPBasicAuth(login, password))
data = json.loads(request.content.decode('utf-8'))
for rep in data['values']:
reps.append(rep['slug'])
url = data.get('next')
return reps
def clone_reps(login: str, password: str, workspace: str, path: str) -> list:
reps = get_reps(login, password, workspace)
for rep in reps:
if os.path.exists(f'{path}/{rep}'):
print(f'Skipping repository {rep}')
else:
command = f'git clone git@bitbucket.org:{workspace}/{rep}.git {path}/{rep}'
print('-' * 100, '\n')
print(f'Clone: {rep}\n{command}')
print('-' * 100, '\n')
subprocess.run(command.split(' '))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action', action='store', choices=['list', 'clone'], help='Operation')
parser.add_argument('workspace', help='Workspace')
parser.add_argument('--login', required=True, help='Account login')
parser.add_argument('--password', required=True, help='Application password')
parser.add_argument('--path', required=False, help='Path to folder to save reps')
args = parser.parse_args()
action = args.action
login = args.login
password = args.password
workspace = args.workspace
path = args.path
if action == 'list':
reps = get_reps(login, password, workspace)
print(reps)
elif action == 'clone':
clone_reps(login, password, workspace, path)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment