def run_app(): if len(sys.argv) != 3: raise Exception('illegal arguments') start = sys.argv[1] end = sys.argv[2] logging.info(f"started for dates: {start} - {end}") clockify = Clokify() jira = Jira() entries = clockify.list_time_entries(start, end) logging.info(f"downloaded: {entries}") entries_by_date = merge_entries_by_date(entries) entries_by_date = merge_entries(entries, entries_by_date) for d in entries_by_date: date = d.date entries = d.entries for e in entries: issue = e.get_issue() description = e.get_description() logging.info(f"processing {date} - {issue} - {description}, {e.hours}:{e.minutes}") result = jira.add_entry(issue, e.get_time_in_seconds(), date, description) if result: for id in e.ids: clockify.mark_as_processed(id, issue, description, e.ids[id])
def main(): """The main function.""" # Get runtime args cli_args = parse_runtime_args() # Parse config file with open(cli_args.config, "r") as config_file: config_dict = yaml.safe_load(config_file) # Initialize Colorama init() # Create Jira client objects for source and destination servers source_jira = Jira( server=config_dict["source-jira"]["url"], basic_auth=( config_dict["source-jira"]["auth"]["username"], config_dict["source-jira"]["auth"]["password"], ), ) destination_jira = Jira( server=config_dict["destination-jira"]["url"], basic_auth=( config_dict["destination-jira"]["auth"]["username"], config_dict["destination-jira"]["auth"]["password"], ), ) # Migrate for project in config_dict["projects-to-migrate"]: print(Style.BRIGHT + "Migrating {}".format(project) + Style.RESET_ALL) # Get tickets try: tickets = get_project_tickets(source_jira, project) except JiraError as e: print(Style.BRIGHT + "Jira call failed! Here's the error:" + Style.RESET_ALL) print(e) sys.exit(1) # Push tickets print(Style.BRIGHT + "Pushing tickets to destination" + Style.RESET_ALL) for ticket in tqdm(tickets): try: push_ticket(destination_jira, ticket) except JiraError as e: print(Style.BRIGHT + "Jira call failed! Here's the error:" + Style.RESET_ALL) print(e) sys.exit(1)
def updateTrackerGitInfo(self, branch=None, ref=None): """Updates the git info on the tracker issue""" if branch == None: branch = self.currentBranch() if branch == 'HEAD': raise Exception('Cannot update the tracker when on detached branch') # Parsing the branch parsedbranch = parseBranch(branch, C.get('wording.branchRegex')) if not parsedbranch: raise Exception('Could not extract issue number from %s' % branch) issue = 'MDL-%s' % (parsedbranch['issue']) version = parsedbranch['version'] # Get the jira config repositoryurl = C.get('repositoryUrl') diffurltemplate = C.get('diffUrlTemplate') stablebranch = self.get('stablebranch') # Get the hash of the last upstream commit headcommit = None logging.info('Searching for the head commit...') if ref: try: headcommit = self.git().hashes(ref=ref, limit=1, format='%h')[0] except GitException: logging.warning('Could not resolve a head commit using the reference: %s' % (ref)) headcommit = None # No reference was passed, or it was invalid. if not headcommit: headcommit = self.headcommit(branch) # Head commit not resolved if not headcommit: logging.error('Head commit not resolved, aborting update of tracker fields') return False logging.debug('Head commit resolved to %s' % (headcommit)) J = Jira() diffurl = diffurltemplate.replace('%branch%', branch).replace('%stablebranch%', stablebranch).replace('%headcommit%', headcommit) fieldrepositoryurl = C.get('tracker.fieldnames.repositoryurl') fieldbranch = C.get('tracker.fieldnames.%s.branch' % version) fielddiffurl = C.get('tracker.fieldnames.%s.diffurl' % version) if not fieldrepositoryurl or not fieldbranch or not fielddiffurl: logging.error('Cannot set tracker fields for this version (%s). The field names are not set in the config file.', version) else: logging.info('Setting tracker fields: \n %s: %s \n %s: %s \n %s: %s' % (fieldrepositoryurl, repositoryurl, fieldbranch, branch, fielddiffurl, diffurl)) J.setCustomFields(issue, {fieldrepositoryurl: repositoryurl, fieldbranch: branch, fielddiffurl: diffurl})
def lambda_handler(event, context): github = GitHub(event) fix_version = github.get_fix_version() ticket_numbers = github.get_ticket_numbers() assignee = get_assignee(github) for ticket in ticket_numbers: jira = Jira(ticket) jira.update_status(assignee=assignee, fix_version=fix_version) move_ticket(jira, github) return ""
def make_conn(self, svr, user, pasw): '''Connects to Jira via basic authentication. Returns: object: The Jira connection. ''' return Jira({'server': svr}, basic_auth=(user, pasw))
def updateTrackerGitInfo(self, branch=None): """Updates the git info on the tracker issue""" if branch == None: branch = self.currentBranch() if branch == "HEAD": raise Exception("Cannot update the tracker when on detached branch") # Parsing the branch parsedbranch = parseBranch(branch, C.get("wording.branchRegex")) if not parsedbranch: raise Exception("Could not extract issue number from %s" % branch) issue = "MDL-%s" % (parsedbranch["issue"]) version = parsedbranch["version"] # Get the jira config repositoryurl = C.get("repositoryUrl") diffurltemplate = C.get("diffUrlTemplate") stablebranch = self.get("stablebranch") upstreamremote = C.get("upstreamRemote") # Get the hash of the last upstream commit ref = "%s/%s" % (upstreamremote, stablebranch) headcommit = self.git().hashes(ref=ref, limit=1)[0] J = Jira() diffurl = ( diffurltemplate.replace("%branch%", branch) .replace("%stablebranch%", stablebranch) .replace("%headcommit%", headcommit) ) fieldrepositoryurl = C.get("tracker.fieldnames.repositoryurl") fieldbranch = C.get("tracker.fieldnames.%s.branch" % version) fielddiffurl = C.get("tracker.fieldnames.%s.diffurl" % version) if not (fieldrepositoryurl or fieldbranch or fielddiffurl): logging.error( "Cannot set tracker fields for this version (%s). The field names are not set in the config file.", version, ) else: logging.info( "Setting tracker fields: \n\t%s: %s \n\t%s: %s \n\t%s: %s" % (fieldrepositoryurl, repositoryurl, fieldbranch, branch, fielddiffurl, diffurl) ) J.setCustomFields(issue, {fieldrepositoryurl: repositoryurl, fieldbranch: branch, fielddiffurl: diffurl})
def get_data(self): jira = Jira(self.jira_api_url) jql = "project=%s and status in (%s) " + \ "and assignee!=null" jql = jql % (self.jira_project_key, self.jira_statuses) if self.jira_resolutions: jql += " resolutions in (%s)" % self.jira_resolutions fields = 'summary,description,assignee,created' raw_issues = jira.find_all(jql, fields, limit=int(config.general__ticket_limit)) data = [] for issue in raw_issues: fields = issue['fields'] document = Document(fields['summary'], fields['description'], fields['assignee']['name']) data.append(document) return data
def updateTrackerGitInfo(self, branch=None): """Updates the git info on the tracker issue""" if branch == None: branch = self.currentBranch() if branch == 'HEAD': raise Exception('Cannot update the tracker when on detached branch') # Parsing the branch parsedbranch = parseBranch(branch, C.get('wording.branchRegex')) if not parsedbranch: raise Exception('Could not extract issue number from %s' % branch) issue = 'MDL-%s' % (parsedbranch['issue']) version = parsedbranch['version'] # Get the jira config repositoryurl = C.get('repositoryUrl') diffurltemplate = C.get('diffUrlTemplate') stablebranch = self.get('stablebranch') upstreamremote = C.get('upstreamRemote') # Get the hash of the last upstream commit ref = '%s/%s' % (upstreamremote, stablebranch) headcommit = self.git().hashes(ref=ref, limit=1, format='%h')[0] J = Jira() diffurl = diffurltemplate.replace('%branch%', branch).replace('%stablebranch%', stablebranch).replace('%headcommit%', headcommit) fieldrepositoryurl = C.get('tracker.fieldnames.repositoryurl') fieldbranch = C.get('tracker.fieldnames.%s.branch' % version) fielddiffurl = C.get('tracker.fieldnames.%s.diffurl' % version) if not (fieldrepositoryurl or fieldbranch or fielddiffurl): logging.error('Cannot set tracker fields for this version (%s). The field names are not set in the config file.', version) else: logging.info('Setting tracker fields: \n\t%s: %s \n\t%s: %s \n\t%s: %s' % (fieldrepositoryurl, repositoryurl, fieldbranch, branch, fielddiffurl, diffurl)) J.setCustomFields(issue, {fieldrepositoryurl: repositoryurl, fieldbranch: branch, fielddiffurl: diffurl})
def pushPatch(self, branch=None): """Push a patch on the tracker, and remove the previous one""" if branch == None: branch = self.currentBranch() if branch == 'HEAD': raise Exception('Cannot create a patch from a detached branch') # Parsing the branch parsedbranch = parseBranch(branch, C.get('wording.branchRegex')) if not parsedbranch: raise Exception('Could not extract issue number from %s' % branch) issue = 'MDL-%s' % (parsedbranch['issue']) headcommit = self.headcommit(branch) # Creating a patch file. fileName = branch + '.mdk.patch' tmpPatchFile = os.path.join(gettempdir(), fileName) if self.git().createPatch('%s...%s' % (headcommit, branch), saveTo=tmpPatchFile): J = Jira() # Checking if file with same name exists. existingAttachmentId = None existingAttachments = J.getIssue(issue, fields='attachment') for existingAttachment in existingAttachments.get('fields', {}).get('attachment', {}): if existingAttachment.get('filename') == fileName: # Found an existing attachment with the same name, we keep track of it. existingAttachmentId = existingAttachment.get('id') break # Pushing patch to the tracker. try: logging.info('Uploading %s to the tracker' % (fileName)) J.upload(issue, tmpPatchFile) except JiraException: logging.error('Error while uploading the patch to the tracker') return False else: if existingAttachmentId != None: # On success, deleting file that was there before. try: logging.info('Deleting older patch...') J.deleteAttachment(existingAttachmentId) except JiraException: logging.info('Could not delete older attachment') else: logging.error('Could not create a patch file') return False return True
class JiraClient(object): def __init__(self, url, username, password): self.jira = Jira(url, username, password) def get_all_project_keys(self): projects = self.jira.get_projects().json() keys = [] for project in projects: keys.append(project['key']) return keys def get_all_project_keys_csv(self): result = '' keys = self.get_all_project_keys() for key in keys: result = result + key + ',' return result def get_all_project_keys_csv_except(self, project_keys): result = '' keys = self.get_all_project_keys() ignore_project_keys = project_keys.split(',') for key in keys: if key not in ignore_project_keys: result = result + key + ',' return result """ Delete projects with list of project keys from Jira """ def delete_projects(self, project_keys): keys = project_keys.split(',') for key in keys: print('Deleting project {0}'.format(key)) result = self.jira.delete_project(key.strip()) if result.status_code == 204: print('Successfully deleted {0}'.format(key)) else: print('Error deleting {0}. Error code {1}'.format(key, result.status_code)) """ Delete all projects except the list of project keys from Jira """ def delete_projects_except(self, project_keys): all_keys = self.get_all_project_keys() except_keys = project_keys.split(',') for key in all_keys: key = key.strip() if key not in except_keys: print('Deleting project {0}'.format(key)) result = self.jira.delete_project(key) if result.status_code == 204: print('Successfully deleted {0}'.format(key)) else: print('Error deleting {0}. Error code {1}'.format(key, result.status_code)) """ Create issue type """ def create_issue_type(self, name, description='', itype='standard'): if itype is '1': itype = 'subtask' else: itype = 'standard' result = self.jira.create_issue_type(name, description, itype) if result.status_code == 201: print('Successfully created issue type {0}'.format(name)) else: print('Error creating issue type {0}. Error code {1}'.format(name, result.status_code)) """ Create issue types from file """ def create_issue_types_from_file(self, issue_types): for issue_type in issue_types: parts = issue_type.split(',') if len(parts) < 2: print('Input file does not have the right number of columns') break else: name = parts[0].strip() description = parts[1].strip() itype = parts[2].strip() if itype is '': itype = 'standard' self.create_issue_type(name, description, itype) """ List all statuses """ def get_all_statuses(self): return self.jira.get_all_statuses() """ Get status """ def get_status(self, id): return self.jira.get_status(id) """ List statuses of project """ def get_project_statuses(self, project_key): return self.jira.get_project_statuses(project_key) """ List all resolutions """ def get_all_resolutions(self): return self.jira.get_all_resolutions() """ Get resolution """ def get_resolution(self, id): return self.jira.get_resolution(id) """ List all priorities """ def get_all_priorities(self): return self.jira.get_all_priorities() """ Get priority """ def get_priority(self, id): return self.jira.get_priority(id) """ List all custom fields """ def get_all_custom_fields(self): return self.jira.get_all_custom_fields() """ List all screen fields """ def get_screen_fields(self, screen_id): return self.jira.get_screen_fields(screen_id) """ Create custom field """ def create_custom_field(self, name, ctype, searcher_key, description=''): result = self.jira.create_custom_field(name, ctype, searcher_key, description) if result.status_code == 201: print('Successfully created custom field {0}'.format(name)) else: print('Error creating custom field {0}. Error code {1}'.format(name, result.status_code)) """ Create custom fields """ def create_custom_fields(self, custom_fields): for custom_field in custom_fields: self.create_custom_field(custom_field['name'], custom_field['type'], custom_field['searcher_key'], custom_field['description']) """ Write content to file """ def write_to_file(filepath, content): outfile = open(filepath, 'w') outfile.write(content) outfile.close()
def __init__(self, url, username, password): self.jira = Jira(url, username, password)
) driver.maximize_window() os.system('cls') # Obtém as datas automaticamente # Informa as datas manualmente: print('Dia (DD/MM): ') dia = str(input()) data = str('2020-' + str(dia)[3:5] + '-' + str(dia)[0:2]) p = Ponto(driver, str(dia)) p.abrirPagina() hrsTotal = p.calcularHorasTrabalhadas() if (p.validaPeriodo()): driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') # Tempo para alocar no Ticket JS-1 (Minutos em outras atividades) print('Minutos em JS-1 (Shared): ') tempoJS1 = int(input()) # Tempo para alocar no Ticket JS-117 (Minutos em reuniões) print('Minutos em JS-117 (Reunioes): ') tempoJS117 = int(input()) # abre a aba do jira j = Jira(driver, str(data), p.obterPrimeiraEntrada(), hrsTotal, tempoJS1, tempoJS117) j.abrirPagina() j.alocarHorasHoje() else: print('Não foi encontrado o período desejado no Meu RH')