def __init__(self, token=os.environ['CIRCLE_TOKEN']):
   APIGateway.__init__(self)
   self._username, self._project = Helper.owner_and_repo()
   self._host_url = 'https://circleci.com/api/v1'
   self._api = {
     'recent_branch_builds': {
       'path': '/project/{username}/{project}/tree/{branch}',
       'method': 'GET',
       'valid_status': [200]
     },
     'cancel_build': {
       'path': '/project/{username}/{project}/{build_num}/cancel',
       'method': 'POST'
     },
     'new_build': {
       'path': '/project/{username}/{project}/tree/{branch}',
       'method': 'POST'
     }
   }
   self._common_headers = {
     'Accept': 'application/json'
   }
   self._common_params = {
     'circle-token': token
   }
def create_pr(args):
  handler = create_handler(args)
  title = handler.get_title()
  body = handler.get_body()
  params = urllib.urlencode({'title':title,'body':body.encode("UTF-8")})
  owner, repo = Helper.owner_and_repo()
  branch = Helper.push_private()
  url = "https://github.com/{owner}/{repo}/compare/{branch}?expand=1&{params}".format(
    owner = owner,
    repo = repo,
    branch = branch,
    params = params
  )

  if args.debug == True:
    print('-- URL --')
    print(url)
    print('')
    print('-- TITLE --')
    print(title)
    print('')
    print('-- BODY --')
    print(body)
  else:
    webbrowser.open(url)
def run():
  parser = argparse.ArgumentParser(prog = get_script_name_from_python_file(__file__))
  parser.add_argument("-d", "--description")
  parser.add_argument("-n", "--nobranch", action="store_true")
  parser.add_argument("title")
  args = parser.parse_args()
  if len(args.title) < 5:
    print "The title should be 5 characters or longer"
    parser.print_usage()
    sys.exit(2)

  owner, repo = Helper.owner_and_repo()
  api = GithubAPIGateway(owner, repo, token=os.environ['GITHUB_TOKEN'])
  username = api.call('user')[0]['login']

  data = {
    'title': args.title,
    'assignee': username
  }

  if args.description is not None:
    data.update(body=args.description)

  issue = api.call('create_issue', owner=owner, repo=repo, data=data)[0]
  print issue['html_url']

  branch_name = Helper.branch_name(issue)
  if args.nobranch == False:
    Helper.create_branch(branch_name)
  else:
    print branch_name
def run():
  owner, repo = Helper.owner_and_repo()
  github_gateway = GithubAPIGateway(owner, repo)
  wrike_gateway = Wrike(data_filepath=Helper.get_data_filepath('wrike'))
  printer = StatusPrinter(70)

  merge(printer, github_gateway)
  close_wrike_task(printer, github_gateway, wrike_gateway)
  remove_remote_branch(printer, owner, repo)
def run():
  branch = Helper.current_branch()
  match = re.search('^(\d+)\-', branch)
  issue = None
  if match is not None:
    owner, repo = Helper.owner_and_repo()
    webbrowser.open('https://github.com/{0}/{1}/issues/{2}'.format(owner, repo, match.group(1)))
  else:
    print 'No issue number on branch'
 def __init__(self, args, issue_number):
   super(IssueHandler, self).__init__(args)
   self.issue_number = issue_number
   owner, repo = Helper.owner_and_repo()
   api = GithubAPIGateway(owner, repo, token=os.environ['GITHUB_TOKEN'])
   result = api.call('list_issue', owner=owner, repo=repo, number=issue_number)
   if result[1] != 200:
     raise ObjectNotFoundException('issue', issue_number)
   else:
     self.obj = result[0]
def run():
  circle_gateway = CircleCiAPIGateway()
  github_gateway = GithubAPIGateway(*Helper.owner_and_repo())
  printer = StatusPrinter()

  branch_differences_check(printer, github_gateway)
  master_differences_check(printer)
  unbrought_changes_check(printer)
  master_conflicts_check(printer)
  circleci_check(printer, circle_gateway)
  lgs_check(printer, github_gateway)
def run():
  current_branch = Repo(os.getcwd()).active_branch
  api = CircleCiAPIGateway(token=os.environ['CIRCLE_TOKEN'])
  builds_canceled = 0
  owner, repo = Helper.owner_and_repo()

  for build in api.call('recent_branch_builds', username=owner, project=repo, branch=current_branch)[0]:
    if build['status'] in ['running', 'not_running', 'queued', 'scheduled']:
      api.call('cancel_build', username=owner, project=repo, build_num=build['build_num'])
      builds_canceled += 1

  print '{0} builds canceled'.format(builds_canceled)
def run():
  current_branch = Repo(os.getcwd()).active_branch
  api = CircleCiAPIGateway(token=os.environ['CIRCLE_TOKEN'])
  owner, repo = Helper.owner_and_repo()
  result = api.call('new_build', username=owner, project=repo, branch=current_branch)[0]
  if result.get('build_url') is not None:
    print result['build_url']
  else:
    if result.get('message') is not None:
      print result['message']
    else:
      print result
def run():
  parser = argparse.ArgumentParser(prog = get_script_name_from_python_file(__file__))
  parser.add_argument("item_counter")
  args = parser.parse_args()

  owner, repo = Helper.owner_and_repo()
  api = PyRollbarAPI(repo)
  item = api.get_item_from_counter(args.item_counter)
  branch_name = Helper.branch_name_from_item(item['id'], item['title'])

  result = Helper2().create_branch(branch_name)
  if result[0] != 0:
    print(result[1])
    sys.exit(result[0])
def remove_label_from_issue(args):
  results, status = GithubAPIGateway(*Helper.owner_and_repo()).remove_label_from_issue(args.issue_number, args.label, args.all_labels)

  if status in [200, 204]:
    print "Issue {0} labels:".format(args.issue_number)
    if results:
      for label in results:
        color = rgb2short(label['color'])[1]
        label_color = fg('black') + bg('#' + color)
        reset_color = attr('reset')
        print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color)
    else:
      print "No labels found."
  else:
    print results['message']
def list_labels(args):
  results, status = GithubAPIGateway(*Helper.owner_and_repo()).get_labels(issue_number=args.issue_number)

  if status == 200:
    if args.issue_number:
      print "Issue {0} labels:".format(args.issue_number)

    if results:
      for label in results:
        color = rgb2short(label['color'])[1]
        label_color = fg('black') + bg('#' + color)
        reset_color = attr('reset')
        print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color)
    else:
      print "No labels found."
  else:
    print results['message']
def issue_from_wrike(args):
  # GET TASKS
  tasks = []
  wrike_gateway = Wrike(data_filepath=Helper.get_data_filepath('wrike'), wait_for_redirect=True)
  github_gateway = GithubAPIGateway(*Helper.owner_and_repo())
  for taskid in args.taskids:
    task = wrike_gateway.get_task(taskid)
    if task is None:
      print "'{0}' is not a valid taskid or it cannot be found".format(taskid)
      sys.exit(-1)
    tasks.append(task)

  # BODY OF ISSUE
  body = ''
  for task in tasks:
    body += '### {0}\n___\n\n{1}\n'.format(task['permalink'].encode('utf-8'), task['description'].encode('utf-8'))

  # TITLE OF ISSUE
  title = tasks[0]['title']
  if len(tasks) > 1:
    title += ' (+{0} Wrike tasks)'.format(len(tasks) - 1)

  # CREATE ISSUE
  issue = github_gateway.create_issue(title, True, {'body': body})
  print issue['html_url']
  branch_name = Helper.branch_name(issue)
  if args.nobranch == False:
    Helper.create_branch(branch_name)
  else:
    print branch_name

  # WRITE LINK TO ISSUE ON EVERY TASK AND SET ASIGNEE
  wrike_gateway.redirect(issue['html_url'])
  contact = wrike_gateway.get_current_contact()
  for task in tasks:
    wrike_gateway.create_task_comment(task['id'], issue['html_url'])
    if contact['id'] not in task['responsibleIds']:
      wrike_gateway.change_task(task['id'], {
        'addResponsibles': "['{0}']".format(contact['id'])
      })
 def __init__(self, **gateways):
   self._github_gateway = GithubAPIGateway(*Helper.owner_and_repo()) if gateways.get('github') is None else gateways['github']
from githubgateway import GithubAPIGateway
from misc import Helper
import argparse
from colored import fg, bg, attr
from misc.color_translations import rgb2short
from misc.helper2 import get_script_name_from_python_file

parser = argparse.ArgumentParser(prog = get_script_name_from_python_file(__file__))
parser.add_argument("-i", "--issue_number", required=True)
parser.add_argument("-l", "--labels", nargs='+', required=True)
parser.add_argument("-f", "--force-label-creation", dest='force_label_creation', action='store_true')
parser.set_defaults(force_label_creation=False)

args = parser.parse_args()
results, status = GithubAPIGateway(*Helper.owner_and_repo()).add_labels_to_issue(args.issue_number, args.labels, args.force_label_creation)

if status == 200:
  print "Issue {0} labels:".format(args.issue_number)
  for label in results:
    color = rgb2short(label['color'])[1]
    label_color = fg('black') + bg('#' + color)
    reset_color = attr('reset')
    print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color)
else:
  print results['message']