def _def(ctx,word,limit,dictionary,config): """ Dictionary. Support Urban Dict / M-W Dict. """ if config: run_config() ctx.exit() if not word: click.echo(ctx.get_help()) word = click.prompt('Please enter a word', type=str) else: word = " ".join(word) bkcolor = ColorText(mapping={"[]":"fC",("<g","g>") : "fG",("<alert>","</alert>"):"bR","{}":"bB"}) if dictionary == "urban": result = lookupUrban(word,limit) else: result = lookupMW(word,limit) if isinstance(result,list) and result: td=TableDisplay(bkcolor) click.echo("") title = " DEFINITION : <g"+f">>> {word.capitalize()} <<<g>" click.echo(td.format(title=title,text=result)) click.echo("") else: click.echo("") click.echo(bkcolor(f'<alert>!Unable to find online definition. \n <{result}> </alert>')) click.echo("")
def print_settings(ctx, param, value): if not value or ctx.resilient_parsing: return data = Config('sync_settings').readData() td = TableDisplay(({"[]": "fG"})) click.echo( td(title=">>> [Sync Settings] <<<", text=json.dumps(data, indent=2).strip('{}'))) ctx.exit()
def write_gist(data, auth, gist, settings): """ write a data dict to gist. settings = 'plugin' or 'config' """ if not gist: url = "https://api.github.com/gists" else: url = f"https://api.github.com/gists/{gist}" headers = { 'Authorization': f'token {auth}', 'Content-Type': 'applicaiton/json' } payload = { "description": f"OK tools settings configuration and plugins", "public": True, "files": { f"{settings}.json": { "content": json.dumps(data, indent=2), }, "OK_config_lastupdate": { "content": f'UPDATE ON: {datetime.now().strftime("%c")}, FROM: {socket.gethostname()}' } } } try: if gist: res = requests.patch(url, headers=headers, data=json.dumps(payload)) if res.status_code == 200: click.echo( td(text= f"<g>Successfully synced</g> <y>{settings}</y> <g>settings!</g>\nGist @ [https://gist.github.com/{gist}]" )) else: res = requests.post(url, headers=headers, data=json.dumps(payload)) if res.status_code == 201: gist = res.json()['id'] update_Sync_settings(gist=gist) click.echo( td(text= f"<g>Successfully CREATED NEW</g> <y>{settings}</y> <g>settings!</g>\nGist @ [https://gist.github.com/{gist}]" )) if res.status_code not in [200, 201]: jsontd = TableDisplay(({"[]": "fR"})) click.echo( jsontd(title=">>> [Sync failed with following response] <<<", text=json.dumps(res.json(), indent=2).strip("{}"))) except Exception as e: click.echo(td(title=">>> <r> ! Sync Failed </r><<<", text=f"{e}"))
def export_config(ctx, param, path): if path is None or ctx.resilient_parsing: return result = extract_settings('conf') if path.endswith('-'): newtd = TableDisplay({"[]": "fC"}) click.echo( newtd(title=">>>[ Config Parameters ]<<<", text=json.dumps(result, indent=2).strip('{}'))) else: mkdirs(path) filepath = os.path.join(path, 'OK_config.json') with open(filepath, 'wt') as f: json.dump(result, f, indent=2) click.echo( td(text=f' Config data Saved! \n File saved to:\n [{filepath}]')) ctx.exit()
def cli(inputs,precision): """ A big calculator. """ # precision handing: precision = precision.strip('. ') formula = "".join(inputs) # replace log and ln formula = re.sub( "log\s*(?P<num>\d+)" , "math.log10(\g<num>)" , formula) formula = re.sub( "log\s*\((?P<num>.*)\)" , "math.log10(\g<num>)" , formula) formula = re.sub( "ln\s*(?P<num>\d+)" , "math.log(\g<num>)" , formula) formula = re.sub( "ln\s*\((?P<num>.*)\)" , "math.log(\g<num>)" , formula) # replace constant e and pi formula = re.sub( "eu" , "math.e" , formula) formula = re.sub( "pi" , "math.pi" , formula) # replace ^ by ** formula = re.sub( "\^" , "**" , formula) formula = re.sub( "sqrt" , "math.sqrt" , formula) formula = re.sub( "sin" , "math.sin" , formula) formula = re.sub( "cos" , "math.cos" , formula) formula = re.sub( "tan" , "math.tan" , formula) formula = re.sub( "asin" , "math.asin" , formula) formula = re.sub( "acos" , "math.acos" , formula) formula = re.sub( "atan" , "math.atan" , formula) formula = re.sub( "abs" , "math.fabs" , formula) # replace factorial inside parenthesis formula = re.sub("\((?P<num>.*)\)!","math.factorial(\g<num>)",formula,) # replace factorial of numbers formula = re.sub("(?P<num>\s*\d+\s*)!","math.factorial(\g<num>)",formula) try: result = eval(formula) result = [(f' [结果] = {{:.{precision}}}').format(result)] except Exception as e: result = [f"Formula : {formula}" , '<alert>Error {} </alert>'.format(e)] line1 = f' [计算] <f>{"".join(inputs)}</f>' tf = TableDisplay({"[]":"fGsB",("<f>","</f>"):"fMsB","{}":"bB",("<alert>","</alert>"):"bR"}) data = tf(title='{>>>计算器<<<}',text=[[line1],result]) click.echo('') click.echo(data) click.echo('')
def cli(folder, pattern, reverse): """ Clean files from a folder using regex pattern search.\n Default using icloud sync duplicate pattern / [2-9]$/ . """ td = TableDisplay() op = 'reverse' if reverse else 'clean' folder = folder or click.prompt( td(text=f"Enter [path/to/folder] you want to {op}:") + '\n', default=os.getcwd()) if reverse: try: click.echo(td(text=f'Reverse cleaning on folder [{folder}] ...')) reverse_deletion(folder) click.echo( td(title=">>> <g>SUCCESS</g> <<<", text=f'Reversed cleaning on folder [{folder}]')) except Exception as e: click.echo( td(title=">>> <r>ERROR</r> <<<", text=f"Error: <r>{e}</r>")) return pattern = pattern or click.prompt(td(text="Enter regex pattern:") + '\n', default=" [2-9]$") try: pattern = re.compile(pattern) except re.error as e: click.echo( td(title=">>> <r>ERROR</r> <<<", text=f"Regex compile error: <r>{e}</r>")) return if os.path.isdir(folder): click.echo(td(text=f'Cleaning folder [{folder}] ...')) save, fileCount, folderCount = delete_by_pattern(folder, pattern) click.echo( td(title=">>> <g>Result</g> <<<", text= f'Cleaning Done.\n{{{fileCount}}} files\n{{{folderCount}}} folders\nMoved to [{save}].' )) else: click.echo(td(text=f"Path <r>{folder}</r> is invalid."))
import click import subprocess as sub from cli.utils import TableDisplay, Config import os config = Config('folders') td = TableDisplay() def displayMenu(data): data = data.get('favorites', {}) dis = [] for k in sorted(data.keys()): dis.append(f" >><g> [ {k} ] </g><< {data[k]} ") click.echo(td(title="[>> Favorite Folders <<]", text=[dis])) def mark_fav(ctx, param, value): if not value or ctx.resilient_parsing: return cwd = os.getcwd() key = click.prompt( td(text=f'Enter name for favorite folder\n@ [{cwd}]') + '\n') data = config.readData() if data.get('favorites', None) is None: data['favorites'] = {} todis = [] for k in key.split():
def cli(ctx, v): """ git pull add commit push 4 step in one. """ if ctx._depth == 2: if v: versionfile = [] packagejson = [] for root, folder, files in os.walk(os.getcwd()): for file in files: fullpath = os.path.join(root, file) if file.split('.')[0] == '_version_': versionfile.append(fullpath) elif file.strip() == 'package.json': if not ('node_modules' in root): packagejson.append(fullpath) trueVersion = [] for f in versionfile: try: data = open(f, 'rt').read() if '__version__' in data: trueVersion.append((f, data)) except: pass count = len(trueVersion) + len(packagejson) if count > 1 or count == 0: if count > 1: click.echo(f"Found these __version__ files:") for f, d in trueVersion: click.echo(f) for f in packagejson: click.echo(f) if not click.confirm( f'{"More" if count>1 else "Less"} than one _version_.* file was found, ignore version and continue?', default=True, ): return else: foundVersion = False if trueVersion: file, data = trueVersion[0] data = data.split('\n') for k, line in enumerate(data): p = re.compile('\d+\.\d+\.\d+') if '__version__' in line: m = p.search(line) if m: foundVersion = True ver = m.group() verl = ver.split('.') verl[-1] = str(int(verl[-1]) + 1) newver = '.'.join(verl) data[k] = line.replace(ver, newver) else: file = packagejson[0] with open(file, 'rt') as f: data = json.load(f) ver = data.get('version', None) if ver: ov = ver.split('.') ov[-1] = str(int(ov[-1]) + 1) newver = '.'.join(ov) data['version'] = newver foundVersion = True if foundVersion: if not click.confirm( f"Update __version__ in {file} from <{ver}> to <{newver}> ?", default=True): return with open(file, 'wt') as f: if trueVersion: f.write('\n'.join(data)) else: json.dump(data, f, indent=2) else: click.echo(f'No __version__ can be found in <{file}>.') click.echo('\nGit pull') sub.run( 'git pull', shell=True, ) click.echo('\nCommit to Git') msg = click.prompt( "Enter a comment", show_default=True, default= f"ON: {date.now().strftime('%c')}, FROM: {socket.gethostname()}") sub.run('git add .', shell=True) sub.run(f'git commit -m "{msg}"', shell=True) sub.run('git push', shell=True) # sub.run(f'git add . \n git commit -m "{msg}" \n git push',shell=True) result = sub.run('git config --get remote.origin.url', stdout=sub.PIPE, encoding='utf-8', shell=True).stdout td = TableDisplay() click.echo( td(title='>>> <g>! Success</g> <<<', text=f"Commited to [{result.strip()}]"))