def jql_search(self, *args): """Submit a JQL search query to the server""" jql = None if args and args != ('', ): jql = ' '.join(args) SAVED_QUERIES.add(jql=jql) else: entry_type = ih.make_selections( ['Select a saved query', 'Type a JQL query'], prompt='Choose one', unbuffered=True) if 'Select a saved query' in entry_type: selected_query = ih.make_selections( SAVED_QUERIES.find(get_fields='name,jql'), prompt='Choose one', item_format='({name}) {jql}', unbuffered=True) if selected_query: jql = selected_query[0]['jql'] name = selected_query[0]['name'] _id = selected_query[0]['_id'] update_kwargs = {'chosen_on': dh.utc_now_float_string()} if name is None: name = ih.user_input('Enter a name for this selection') if name: update_kwargs.update(name=name) SAVED_QUERIES.update(_id, **update_kwargs) else: jql = ih.user_input('Enter your JQL query') if not jql: return SAVED_QUERIES.add(jql=jql) else: jql = ih.user_input('Enter your JQL query') if not jql: return SAVED_QUERIES.add(jql=jql) self._info['last_jql'] = jql if not 'order by' in jql.lower() and self._info['orderby_fields']: jql += ' ORDER BY ' + ', '.join(self._info['orderby_fields']) results = jql_search(jql, session=self._session, count=self._info['count_only'], fields=self._info['return_fields'], return_raw=self._info['raw_json']) pprint(results) print('\njql:', jql)
def get_last_or_make_selection(field_type, force_new=False): """Fetch most recent selections for field type from SELECTED_FIELDS - field_type: one of the keys in ALLOWED_FIELD_TYPE_INFO dict - force_new: if True, prompt user to select fields for field_type """ assert field_type in ALLOWED_FIELD_TYPE_INFO, ( 'field_type {} is not one of {}'.format( repr(field_type), repr(sorted(ALLOWED_FIELD_TYPE_INFO.keys())))) last = None selections = None if not force_new: last = SELECTED_FIELDS.find('type:{}'.format(field_type), limit=1, get_fields='selected') if last: selections = last[0]['selected'] if not selections or force_new: selections = ih.make_selections( ALLOWED_FIELD_TYPE_INFO[field_type]['fields'], prompt=ALLOWED_FIELD_TYPE_INFO[field_type]['prompt']) if selections: SELECTED_FIELDS.add(type=field_type, selected=selections) return selections
def select_commit_to_tag(n=10): """Select a commit hash from recent commits - n: number of recent commits to choose from """ SOURCE_BRANCH = _get_repo_settings('SOURCE_BRANCH') branch = get_branch_name() assert branch == SOURCE_BRANCH, ( 'Must be on {} branch to select commit, not {}'.format( SOURCE_BRANCH, branch)) last_tag = get_last_tag() cmd_part = 'git log --find-renames --no-merges --oneline' if last_tag: cmd = cmd_part + ' {}..'.format(last_tag) else: cmd = cmd_part + ' -{}'.format(n) output = bh.run_output(cmd) if not output: return items = re.split('\r?\n', output)[:n] selected = ih.make_selections(items, wrap=False, prompt='Select commit to tag') if selected: return selected[0].split(' ', 1)[0]
def select_qa(empty_only=False, full_only=False, multi=False): """Select QA branch(es) - empty_only: if True, only show empty qa environments in generated menu - full_only: if True, only show non-empty qa environments in generated menu - multi: if True, allow selecting multiple qa branches """ assert not empty_only or not full_only, 'Cannot select both empty_only and full_only' if empty_only: items = sorted(list(get_empty_qa())) elif full_only: items = sorted(list(get_non_empty_qa())) else: items = sorted(_get_repo_settings('QA_BRANCHES')) if len(items) == 1: print('Selected: {}'.format(repr(items[0]))) return items[0] elif len(items) == 0: print('No items to select') return prompt = 'Select QA branch' one = not multi if multi: prompt = 'Select QA branches' selected = ih.make_selections(items, prompt=prompt, one=one) return selected
def most_commented_files_play_select(limit=62): """Select files that have been most commented and play""" selected = ih.make_selections( COMMENTS.top_values_for_index('basename', limit=limit), prompt='Select basenames to play', item_format='{} ({})', wrap=False ) if selected: play_basenames(*[s[0] for s in selected])
def recent_files_play_select(limit=62): """Select files that were most recently added and play""" selected = ih.make_selections( FILES.find('audio:True', get_fields='basename', admin_fmt=True, limit=limit), item_format='{basename} .::. {_ts}', prompt='Select basenames to play', wrap=False ) if selected: play_basenames(*[x['basename'] for x in selected])
def main(): """Select from current trending on youtube""" selected = ih.make_selections( ph.youtube_trending(), wrap=False, item_format='{duration} .::. {title} .::. {user} .::. {uploaded}', ) if selected: ph.logger.info('Selected {}'.format(' '.join( [x['link'] for x in selected]))) with open(ph.LOGFILE, 'a') as fp: pprint(selected, fp)
def choose_old_selection_or_make_new_selection(field_type): """Choose from old groups of selections for field_type or make a new selection - field_type: one of the keys in ALLOWED_FIELD_TYPE_INFO dict """ assert field_type in ALLOWED_FIELD_TYPE_INFO, ( 'field_type {} is not one of {}'.format( repr(field_type), repr(sorted(ALLOWED_FIELD_TYPE_INFO.keys())))) selections = None choice = ih.make_selections( ['Choose from old selections', 'Make a new selection'], prompt='Choose one for {} fields in search results'.format(field_type), unbuffered=True) if 'Choose from old selections' in choice: found = SELECTED_FIELDS.find('type:{}'.format(field_type), get_fields='selected,name') selected = ih.make_selections(found, item_format='({name}): {selected}', prompt='Choose one', wrap=False, unbuffered=True) if selected: selections = selected[0]['selected'] name = selected[0]['name'] _id = selected[0]['_id'] update_kwargs = {'chosen_on': dh.utc_now_float_string()} if name is None: name = ih.user_input('Enter a name for this selection') if name: update_kwargs.update(name=name) SELECTED_FIELDS.update(_id, **update_kwargs) else: selections = get_last_or_make_selection(field_type, force_new=True) return selections
def select_branches(grep='', all_branches=False, one=False): """Select remote branch(es); return a list of strings - grep: grep pattern to filter branches by (case-insensitive) - all_branches: if True, don't filter out non-selectable branches or branches prefixed by a qa branch - one: if True, only select one branch """ prompt = 'Select remote branch(es)' if one: prompt = 'Select remote branch' selected = ih.make_selections(sorted( get_remote_branches(grep, all_branches=all_branches)), prompt=prompt, one=one) return selected
def main(query): """Pass a search query to duckduckgo api""" query = query or ih.user_input('duckduckgo query') if not query: return selected = ih.make_selections( ph.duckduckgo_api(query), wrap=True, item_format='{text}', ) if selected: ph.logger.info('Selected {}'.format(' '.join( [x['link'] for x in selected]))) with open(ph.LOGFILE, 'a') as fp: pprint(selected, fp)
def main(query): """Pass a search query to youtube""" query = query or ih.user_input('youtube query') if not query: return selected = ih.make_selections( ph.youtube_serp(query), wrap=False, item_format='{duration} .::. {title} .::. {user} .::. {uploaded}', ) if selected: ph.logger.info('Selected {}'.format(' '.join( [x['link'] for x in selected]))) with open(ph.LOGFILE, 'a') as fp: pprint(selected, fp)
def select_branches_with_times(grep='', all_branches=False, one=False): """Select remote branch(es); return a list of dicts - grep: grep pattern to filter branches by (case-insensitive) - all_branches: if True, don't filter out non-selectable branches or branches prefixed by a qa branch - one: if True, only select one branch """ prompt = 'Select remote branch(es)' if one: prompt = 'Select remote branch' selected = ih.make_selections(get_remote_branches_with_times( grep, all_branches=all_branches), item_format='{branch} ({time})', wrap=False, prompt=prompt, one=one) return selected
def build_jql_query(): """Select items from various menus to build a JQL query string""" menus = [ 'projects', 'issue types', 'status types', 'query fields', 'date fields', 'order by fields', 'return fields' ] selected_menus = ih.make_selections( menus, prompt= 'Select the JQL elements you are interested in (separate by space)') if not selected_menus: return s = StringIO() # s.write('') # # # - if orderby is used, ask if asc or desc # - if multiple selected, separate by comma return s.getvalue()
def jumploop(choose_all=False): """Loop an unbuffered input session, jumping between selected marks (up to 62)""" num_comments = get_comments(count=True) if choose_all: selected = get_comments( post_fetch_sort_key='timestamp', sort_key_default_val=0 ) else: selected = select_comments( prompt='Select up to 62 comments for jumploop (or type "all")', unbuffered=False, get_fields='text,timestamp', include_meta=False ) if selected: basename = get_current_basename() selected = selected[:62] while True: print('\n{}\n'.format(basename)) try: idx = ih.make_selections( selected, item_format='{timestamp} -> {text}', prompt='Select mark/comment or ctrl+c to break loop', wrap=False, unbuffered=True, raise_interrupt=True, raise_exception_chars=[' '] ) if idx: if basename not in moc.info_string(): play_basenames(basename) moc.go(idx[0]['timestamp']) else: moc.go(idx[0]['timestamp']) except KeyboardInterrupt: print() break except Exception: moc.toggle_pause()
def find_select_and_play(*paths): """Find all audio files at the given paths, select interactively, and play - paths: filename and dirname globs that either are audio files, or contain audio files """ results = find_audio(*paths) if results: selected = ih.make_selections( results, wrap=False ) if selected: start_server() output = bh.run_output( 'mocp --playit {}'.format(' '.join(selected)), timeout=10 ) if output: print(output) else: print('No files found matching {}'.format(repr(paths)))
def main(query, **kwargs): """Pass a search query to google""" query = query or ih.user_input('google query') if not query: return session = ph.new_requests_session() selected = ih.make_selections( ph.google_serp(query, session=session, **kwargs), wrap=False, item_format='{title} .::. {link}', ) for item in selected: remote_basename = os.path.basename(item['link']) ext = remote_basename.split('.')[-1] localfile = '' if ext != remote_basename: localfile = lazy_filename(item['title']) + '.' + ext else: localfile = lazy_filename( item['link'].split('://')[-1].strip('/').replace('/', '--') ) + '.html' ph.download_file(item['link'], localfile, session=session)
def select_comments(item_format='{timestamp} -> {text}', prompt='Select mark/comment', unbuffered=None, **kwargs): """Select comments for current file playing - item_format: passed along to ih.make_selections func - prompt: passed along to ih.make_selections func - unbuffered: if False is explicitly passed in, don't use unbuffered when number of comments is less than 62 - kwargs: passed along to `COMMENTS.find` via `get_comments` func - if no 'post_fetch_sort_key' passed in, use `post_fetch_sort_key='timestamp', sort_key_default_val=0` - if no 'limit' pass in, use 75 by default """ if 'post_fetch_sort_key' not in kwargs: kwargs.update({ 'post_fetch_sort_key': 'timestamp', 'sort_key_default_val': 0 }) if 'limit' not in kwargs: kwargs.update({'limit': 75}) comments = get_comments(**kwargs) if unbuffered is None: if len(comments) > 62: unbuffered = False else: unbuffered = True return ih.make_selections( comments, item_format=item_format, prompt=prompt, wrap=False, unbuffered=unbuffered )
def main(**kwargs): """For matching instances, issue a command on the instance via SSH""" ec2 = ah.EC2(kwargs['profile']) find = kwargs['find'] command = kwargs['command'] use_private_ip = kwargs['private_ip'] matched_instances = [] local_pems = ah.find_all_pems() if not command: if kwargs['non_interactive']: print('No command specified') return else: command = ih.user_input('Enter remote command') if not command: print('No command specified') resp = ih.user_input( 'Do you want interactive SSH session(s)? (y/n)') if resp.lower().startswith('y') is False: return if ah.AWS_EC2 is not None: ec2.update_collection() running_instances = ah.AWS_EC2.find( 'status:running', get_fields='name, status, pem, id, ip, ip_private, sshuser', include_meta=False, limit=ah.AWS_EC2.size) else: instances = ec2.get_all_instances_filtered_data() running_instances = [ ih.rename_keys( ih.filter_keys( instance, 'Tags__Value, State__Name, KeyName, InstanceId, PublicIpAddress, PrivateIpAddress' ), **INSTANCE_KEY_NAME_MAPPING) for instance in ih.find_items(instances, 'State__Name:running') ] for term in ih.string_to_list(find): for item in ih.find_items(running_instances, 'name:${}'.format(term)): if item not in matched_instances: matched_instances.append(item) for item in ih.find_items(running_instances, 'id:${}'.format(term)): if item not in matched_instances: matched_instances.append(item) for item in ih.find_items(running_instances, 'ip:${}'.format(term)): if item not in matched_instances: matched_instances.append(item) for item in ih.find_items(running_instances, 'ip_private:${}'.format(term)): if item not in matched_instances: matched_instances.append(item) if not find: matched_instances = running_instances ih.sort_by_keys(matched_instances, 'name, ip') # # Uncomment and modify if you ever need to use a .pem file that # # is different than what AWS thinks it should be # for i, instance in enumerate(matched_instances): # if instance.get('pem', '') == 'old-pem': # matched_instances[i]['pem'] = 'new-pem' if kwargs['non_interactive'] is False: matched_instances = ih.make_selections( matched_instances, prompt='Select instances', item_format='{id} ({name}) at {ip} ({ip_private}) using {pem}', wrap=False) for instance in matched_instances: pem_name = instance['pem'] ip = instance['ip'] if not use_private_ip else instance['ip_private'] if not ip: continue pem_file = local_pems.get(pem_name) if not pem_file: print('Could not find {} pem in ~/.ssh for {}.'.format( repr(pem_name), repr(instance))) continue sshuser = instance.get('sshuser') if not sshuser: sshuser = ah.determine_ssh_user(ip, pem_file) if not sshuser and kwargs['verbose']: print('--------------------------------------------------') print('\nCould not determine SSH user for {}'.format( repr(instance))) continue else: if ah.AWS_EC2: hash_id = ah.AWS_EC2.get_hash_id_for_unique_value( instance['id']) ah.AWS_EC2.update(hash_id, sshuser=sshuser) if kwargs['verbose']: print('--------------------------------------------------') print('\nInstance {} ({}) at {} with pem {} and user {}\n'.format( instance['id'], instance['name'], ip, pem_name, sshuser)) ah.do_ssh(ip, pem_file, sshuser, command, kwargs['timeout'], kwargs['verbose'])