/
cli.py
executable file
·1689 lines (1505 loc) · 62.9 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import print_function
from builtins import bytes
from builtins import object
from builtins import next
from builtins import str
import click
import json
import locale
import os
import time
import zipfile
import requests
from jinja2 import Environment, PackageLoader
from transcriptic.english import AutoprotocolParser
from transcriptic.config import Connection
from transcriptic.util import iter_json, flatmap, ascii_encode, makedirs
from transcriptic import routes
from os.path import isfile
from collections import OrderedDict
from contextlib import contextmanager
import sys
if sys.version_info[0] < 3:
input = raw_input
PermissionError = RuntimeError
# not exactly identical, but similar enough for this case
FileNotFoundError= IOError
class FeatureGroup(click.Group):
"""Custom group to handle hiding of commands based on the `feature` tag
TODO: Deprecate once Click 7 lands and use `hidden` parameter in commands
"""
def __init__(self, **attrs):
click.Group.__init__(self, **attrs)
def format_commands(self, ctx, formatter):
"""Custom formatter to control whether a command is displayed
Note: This is only called when formatting the help message.
"""
ctx.obj = ContextObject()
try:
ctx.obj.api = Connection.from_file('~/.transcriptic')
except (FileNotFoundError, OSError):
# This defaults to feature_groups = []
ctx.obj.api = Connection()
rows = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
if cmd is None:
continue
try:
if cmd.feature is not None and \
cmd.feature in ctx.obj.api.feature_groups:
help = cmd.short_help or ''
rows.append((subcommand, help))
else:
continue
except AttributeError:
help = cmd.short_help or ''
rows.append((subcommand, help))
if rows:
with formatter.section('Commands'):
formatter.write_dl(rows)
class FeatureCommand(click.Command):
"""Extend off Command to add `feature` attribute
TODO: Deprecate once Click 7 lands and use `hidden` parameter in commands
"""
def __init__(self, feature=None, **attrs):
click.Command.__init__(self, **attrs)
self.feature = feature
class HiddenOption(click.Option):
"""Monkey patch of click Option to enable hidden options
TODO: Deprecate once Click 7 lands and use `hidden` option instead
"""
def __init__(self, *param_decls, **attrs):
__hidden__ = attrs.pop('hidden', True)
click.Option.__init__(self, *param_decls, **attrs)
self.__hidden__ = __hidden__
def get_help_record(self, ctx):
"""This hijacks the help record so that a hidden option does not show
up in the help text
"""
if self.__hidden__:
return
click.Option.get_help_record(self, ctx)
class ContextObject(object):
"""Object passed along Click context
Note: `ctx` is passed along whenever the @click.pass_context decorator is
present. This object is referenced using `ctx.obj`
"""
def __init__(self):
self._api = None
@property
def api(self):
return self._api
@api.setter
def api(self, value):
self._api = value
_CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=_CONTEXT_SETTINGS, cls=FeatureGroup)
@click.option('--api-root', default=None, hidden=True, cls=HiddenOption)
@click.option('--email', default=None, hidden=True, cls=HiddenOption)
@click.option('--token', default=None, hidden=True, cls=HiddenOption)
@click.option('--organization', '-o', default=None, hidden=True, cls=HiddenOption)
@click.option(
'--config',
envvar='TRANSCRIPTIC_CONFIG',
default='~/.transcriptic',
help='Specify a configuration file.'
)
@click.version_option(prog_name="Transcriptic Python Library (TxPy)")
@click.pass_context
def cli(ctx, api_root, email, token, organization, config):
"""A command line tool for working with Transcriptic.
Note: This is the main entry point of the CLI. If specifying credentials,
note that the order of preference is: --flag, environment then config file.
Example: `transcriptic --organization "my_org" projects` >>
`export USER_ORGANIZATION="my_org"` >> `"organization_id": "my_org" in
~/.transcriptic
"""
# Initialize ContextObject to be used for storing api object
ctx.obj = ContextObject()
if ctx.invoked_subcommand in ['compile', 'preview', 'summarize', 'init']:
# For local commands, initialize empty connection
ctx.obj.api = Connection()
elif ctx.invoked_subcommand == 'login':
# Load analytics option from existing dotfile if present, else prompt
try:
api = Connection.from_file(config)
api.api_root = (
api_root or os.environ.get('BASE_URL', None) or api.api_root
)
ctx.obj.api = api
except (OSError, IOError):
ctx.obj.api = Connection()
# Echo a warning if other options are defined for login
if organization or email or token:
click.echo("Only the `--api-root` option is applicable for the "
"`login` command. All other options are ignored.")
else:
try:
api = Connection.from_file(config)
api.api_root = (
api_root or os.environ.get('BASE_URL', None) or api.api_root
)
api.organization_id = (
organization or os.environ.get('USER_ORGANIZATION', None) or
api.organization_id
)
api.email = (
email or os.environ.get('USER_EMAIL', None) or api.email
)
api.token = (
token or os.environ.get('USER_TOKEN', None) or api.token
)
ctx.obj.api = api
except (OSError, IOError):
click.echo("Welcome to TxPy! It seems like your `.transcriptic` "
"config file is missing or out of date")
analytics = click.confirm("Send TxPy CLI usage information to "
"improve the CLI user "
"experience?", default=True)
ctx.obj.api = Connection() # Initialize empty connection
ctx.invoke(login, api_root=api_root, analytics=analytics)
if ctx.obj.api.analytics:
try:
ctx.obj.api._post_analytics(event_action=ctx.invoked_subcommand,
event_category="cli")
except requests.exceptions.RequestException:
pass
@cli.command(cls=FeatureCommand, feature='can_submit_autoprotocol')
@click.argument('file', default='-')
@click.option(
'--project', '-p',
metavar='PROJECT_ID',
required=True,
help=('Project id or name to submit the run to. '
'Use `transcriptic projects` command to list existing projects.')
)
@click.option('--title', '-t', help='Optional title of your run')
@click.option('--test', help='Submit this run in test mode', is_flag=True)
@click.option('--pm',
metavar='PAYMENT_METHOD_ID',
required=False,
help='Payment id to be used for run submission. '
'Use `transcriptic payments` command to list existing '
'payment methods.')
@click.pass_context
def submit(ctx, file, project, title=None, test=None, pm=None):
"""Submit your run to the project specified."""
if pm is not None and not is_valid_payment_method(pm):
print_stderr("Payment method is invalid. Please specify a payment "
"method from `transcriptic payments` or not specify the "
"`--payment` flag to use the default payment method.")
return
project = get_project_id(project)
if not project:
return
with click.open_file(file, 'r') as f:
try:
protocol = json.loads(f.read())
except ValueError:
click.echo("Error: Could not submit since your manifest.json "
"file is improperly formatted.")
return
try:
req_json = ctx.obj.api.submit_run(
protocol, project_id=project, title=title, test_mode=test,
payment_method_id=pm
)
run_id = req_json['id']
click.echo("Run created: %s" %
ctx.obj.api.url("%s/runs/%s" % (project, run_id)))
except Exception as err:
click.echo("\n" + str(err))
@cli.command('build-release', cls=FeatureCommand, feature='can_upload_packages')
@click.argument('package', required=False, metavar="PACKAGE")
@click.option('--name', '-n', help="Optional name for your zip file")
@click.pass_context
def release(ctx, name=None, package=None):
"""
Compress the contents of the current directory to upload as a release.
"""
deflated = zipfile.ZIP_DEFLATED
if name:
filename = 'release_%s' % name
else:
filename = 'release'
if os.path.isfile(filename + ".zip"):
new = click.prompt("You already have a release named %s "
"in this directory, make "
"another one? [y/n]" % filename, default="y")
if new == "y":
num_existing = sum([1 for x in os.listdir('.') if filename in x])
filename = filename + "_" + str(num_existing)
else:
return
click.echo("Compressing all files in this directory...")
zf = zipfile.ZipFile(filename + ".zip", 'w', deflated)
for (path, dirs, files) in os.walk('.'):
for f in files:
if ".zip" not in f:
zf.write(os.path.join(path, f))
zf.close()
click.echo("Archive %s created." % (filename + ".zip"))
if package:
package_id = get_package_id(package) or get_package_name(package)
ctx.invoke(
upload_release, archive=(filename + ".zip"), package=package_id)
@cli.command('upload-release', cls=FeatureCommand,
feature='can_upload_packages')
@click.argument('archive', required=True, type=click.Path(exists=True),
metavar="ARCHIVE")
@click.argument('package', required=True, metavar="PACKAGE")
@click.pass_context
def upload_release(ctx, archive, package):
"""Upload a release archive to a package."""
try:
package_id = get_package_id(
package.lower()) or get_package_name(package.lower())
click.echo("Uploading %s to %s" %
(archive,
(get_package_name(package_id.lower()) or
get_package_id(package_id.lower()))
)
)
except AttributeError:
click.echo("Error: Invalid package id or name.")
return
with click.progressbar(None, 100, "Upload Progress",
show_eta=False, width=70,
fill_char="|", empty_char="-") as bar:
bar.update(40)
file = open(os.path.basename(archive), 'rb')
upload_id = ctx.obj.api.upload_to_uri(
file, 'application/zip, application/octet-stream', archive, archive
)
bar.update(20)
try:
up = ctx.obj.api.post_release(
data=json.dumps({"release":
{"upload_id": upload_id}}
),
package_id=package_id
)
re = up['id']
except (ValueError, PermissionError) as err:
if type(err) == ValueError:
click.echo("\nError: There was a problem uploading your release."
"\nVerify that your manifest.json file is properly "
"formatted and that all previews in your manifest "
"produce valid Autoprotocol by using the "
"`transcriptic preview` and/or `transcriptic analyze` "
"commands.")
elif type(err) == PermissionError:
click.echo("\n" + str(err))
return
bar.update(20)
time.sleep(10)
status = ctx.obj.api.get_release_status(package_id=package_id, release_id=re,
timestamp=int(time.time()))
published = status['published']
errors = status['validation_errors']
bar.update(30)
if errors:
click.echo("\nPackage upload to %s unsuccessful. "
"The following error(s) was returned: \n%s" %
(get_package_name(package_id),
('\n').join(e.get('message', '[Unknown]') for
e in errors))
)
else:
click.echo("\nPackage uploaded successfully! \n"
"Visit %s to publish." % ctx.obj.api.url('packages/%s' %
package_id))
@cli.command('upload-dataset')
@click.argument('file_path', type=click.Path(exists=True),
metavar="FILE")
@click.argument('title', metavar="TITLE")
@click.argument('run_id', metavar="RUN-ID")
@click.option('--tool', '-t', required=True,
help="Name of analysis tool used for generating the dataset")
@click.option('--version', '-v', required=True,
help="Version of analysis tool used for generating the dataset")
@click.pass_context
def upload_dataset(ctx, file_path, title, run_id, tool, version):
"""Uploads specified file as an analysis dataset to the specified run."""
resp = ctx.obj.api.upload_dataset_from_filepath(
file_path=file_path,
title=title,
run_id=run_id,
analysis_tool=tool,
analysis_tool_version=version
)
try:
data_id = resp['data']['id']
run_route = ctx.obj.api.url(
"/api/runs/{}?fields[runs]=project_id".format(run_id)
)
run_resp = ctx.obj.api.get(run_route)
project = run_resp['data']['attributes']['project_id']
data_url = "{}/analysis/{}".format(
ctx.obj.api.get_route(
'datasets',
project_id=project,
run_id=run_id
),
data_id
)
click.echo("Dataset uploaded to {}".format(data_url))
except KeyError:
click.echo("An unexpected response was returned from the server. ")
@cli.command()
@click.pass_context
@click.option(
'--local',
is_flag=True,
required=False,
default=False,
help='Shows available local protocols instead of remote protocols'
)
@click.option("--json", "json_flag", help="print JSON response", is_flag=True)
def protocols(ctx, local, json_flag):
"""List protocols within your manifest or organization."""
if not local:
protocol_objs = ctx.obj.api.get_protocols()
else:
manifest = load_manifest()
if 'protocols' not in list(manifest.keys()) or not manifest['protocols']:
click.echo("Your manifest.json file doesn't contain any protocols or"
" is improperly formatted.")
return
protocol_objs = manifest['protocols']
if json_flag:
click.echo(json.dumps(protocol_objs))
else:
click.echo('\n{:^60}'.format("Protocols within this {}:".format("organization" if not local else "manifest")))
click.echo('{:-^60}'.format(''))
for p in protocol_objs:
if p.get('display_name'):
display_str = u"{} ({})".format(p[u'name'], p.get(u'display_name'))
else:
display_str = p[u'name']
click.echo(u"{}\n{}".format(display_str, u'{:-^60}'.format("")))
@cli.command()
@click.pass_context
@click.option("-i")
def packages(ctx, i):
"""List packages in your organization."""
response = ctx.obj.api.packages()
# there's probably a better way to do this
package_names = OrderedDict(
sorted(list({"yours": {}, "theirs": {}}.items()),
key=lambda t: len(t[0]))
)
for pack in response:
n = str(pack['name']).lower().replace(
"com.%s." % ctx.obj.api.organization_id, "")
latest = str(pack['latest_version']) if pack[
'latest_version'] else "-"
if pack.get('owner') and pack['owner']['email'] == ctx.obj.api.email:
package_names['yours'][n] = {}
package_names['yours'][n]['id'] = str(pack['id'])
package_names['yours'][n]['latest'] = latest
else:
package_names['theirs'][n] = {}
package_names['theirs'][n]['id'] = str(pack['id'])
package_names['theirs'][n]['latest'] = latest
if i:
return dict(list(package_names['yours'].items()) +
list(package_names['theirs'].items()))
else:
for category, packages in list(package_names.items()):
if category == "yours":
click.echo('\n{:^90}'.format("YOUR PACKAGES:\n"))
click.echo('{:^30}'.format("PACKAGE NAME") + "|" +
'{:^30}'.format("PACKAGE ID") +
"|" + '{:^30}'.format("LATEST PUBLISHED RELEASE"))
click.echo('{:-^90}'.format(''))
elif category == "theirs" and list(packages.values()):
click.echo('\n{:^90}'.format("OTHER PACKAGES IN YOUR ORG:\n"))
click.echo('{:^30}'.format("PACKAGE NAME") + "|" +
'{:^30}'.format("PACKAGE ID") + "|" +
'{:^30}'.format("LATEST PUBLISHED RELEASE"))
click.echo('{:-^90}'.format(''))
for name, p in list(packages.items()):
click.echo('{:<30}'.format(name) + "|" +
'{:^30}'.format(p['id']) + "|" +
'{:^30}'.format(p['latest']))
click.echo('{:-^90}'.format(''))
@cli.command('create-package', cls=FeatureCommand,
feature='can_upload_packages')
@click.argument('name')
@click.argument('description')
@click.pass_context
def create_package(ctx, description, name):
"""Create a new empty protocol package"""
existing = ctx.obj.api.packages()
for p in existing:
if name == p['name'].split('.')[-1]:
click.echo("You already have an existing package with the name "
"\"%s\". Please choose a different package name." %
name)
return
try:
new_pack = ctx.obj.api.create_package(name, description)
if new_pack:
click.echo(
"New package '%s' created with id %s \n"
"View it at %s" % (
name, new_pack['id'],
ctx.obj.api.url('packages/%s' % new_pack['id'])
)
)
else:
click.echo("There was an error creating this package.")
except Exception as err:
click.echo("\n" + str(err))
@cli.command('delete-package', cls=FeatureCommand,
feature='can_upload_packages')
@click.argument('name')
@click.option('--force', '-f', help="force delete a package without being \
prompted if you're sure", is_flag=True)
@click.pass_context
def delete_package(ctx, name, force):
"""Delete an existing protocol package"""
package_id = get_package_id(name)
if package_id:
try:
if not force:
click.confirm(
"Are you sure you want to permanently delete the package "
"'%s'? All releases within will be lost." %
get_package_name(package_id), default=False, abort=True
)
click.confirm("Are you really really sure?", default=True)
del_pack = ctx.obj.api.delete_package(package_id=package_id)
if del_pack:
click.echo("Package deleted.")
else:
click.echo("There was a problem deleting this package.")
except Exception as err:
click.echo("\n" + str(err))
@cli.command()
@click.pass_context
@click.argument('name')
def generate_protocol(ctx, name):
"""Generate a python protocol scaffold"""
# TODO we should update click to be like rails
# transcriptic generate protocol FOO
# transcriptic generate other_type FOO
env = Environment(loader=PackageLoader('transcriptic', 'templates'))
template_infos = [
{"template_name": 'manifest.json.jinja', "file_name": "manifest.json"},
{"template_name": 'protocol.py.jinja', "file_name": "{}.py".format(name)},
{"template_name": 'requirements.txt.jinja', "file_name": "requirements.txt"}
]
# make directory for protocol
dirname = name
makedirs(dirname, exist_ok=True)
# write __init__ package file
open('{}/{}'.format(dirname, '__init__.py'), 'w').write('')
for template_info in template_infos:
template_name = template_info["template_name"]
file_name = template_info["file_name"]
template = env.get_template(template_name)
file = open('{}/{}'.format(dirname, file_name), 'w')
output = template.render(name=name)
file.write(output)
click.echo("Successfully generated protocol '{}'!".format(name))
click.echo("Testing the protocol is as easy as:")
click.echo("")
click.echo("\tcd {}".format(name))
click.echo("\tpip install -r requirements.txt")
click.echo("\ttranscriptic preview {}".format(name))
click.echo("\ttranscriptic launch --local {} -p SOME_PROJECT_ID".format(name))
@cli.command()
@click.pass_context
@click.option("-i")
@click.option("--json", "json_flag", help="print JSON response", is_flag=True)
def projects(ctx, i, json_flag):
"""List the projects in your organization"""
try:
projects = ctx.obj.api.projects()
proj_id_names = {}
all_proj = {}
for proj in projects:
status = " (archived)" if proj['archived_at'] else ""
proj_id_names[proj["id"]] = proj["name"]
all_proj[proj["id"]] = proj["name"] + status
if i:
return proj_id_names
elif json_flag:
return click.echo(json.dumps(projects))
else:
click.echo('\n{:^80}'.format("PROJECTS:\n"))
click.echo('{:^40}'.format("PROJECT NAME") + "|" +
'{:^40}'.format("PROJECT ID"))
click.echo('{:-^80}'.format(''))
for proj_id, name in list(all_proj.items()):
click.echo('{:<40}'.format(name) + "|" +
'{:^40}'.format(proj_id))
click.echo('{:-^80}'.format(''))
except RuntimeError:
click.echo("There was an error listing the projects in your "
"organization. Make sure your login details are correct.")
@cli.command()
@click.pass_context
@click.argument('project_name')
@click.option("--json", "json_flag", help="print JSON response", is_flag=True)
def runs(ctx, project_name, json_flag):
"""List the runs that exist in a project"""
project_id = get_project_id(project_name)
run_list = []
if project_id:
req = ctx.obj.api.runs(project_id=project_id)
if not req:
click.echo("Project '%s' is empty." % project_name)
return
for r in req:
run_list.append([r['title'] or "(Untitled)",
r['id'],
r['completed_at'].split("T")[0] if r['completed_at']
else r['created_at'].split("T")[0],
r['status'].replace("_", " ")])
if json_flag:
return click.echo(json.dumps(map(lambda x: {
'title': x['title'] or "(Untitled)",
'id': x['id'],
'completed_at': x['completed_at']
if x['completed_at'] else None,
'created_at': x['created_at'],
'status': x['status']}, req)))
else:
click.echo(
'\n{:^120}'.format("Runs in Project '%s':\n" %
get_project_name(project_id))
)
click.echo('{:^30}'.format("RUN TITLE") + "|" +
'{:^30}'.format("RUN ID") + "|" +
'{:^30}'.format("RUN DATE") + "|" +
'{:^30}'.format('RUN STATUS'))
click.echo('{:-^120}'.format(''))
for run in run_list:
click.echo(u'{:^30}'.format(run[0]) + "|" +
u'{:^30}'.format(run[1]) + "|" +
u'{:^30}'.format(run[2]) + "|" +
u'{:^30}'.format(run[3]))
click.echo(u'{:-^120}'.format(''))
@cli.command("create-project")
@click.argument('name', metavar="PROJECT_NAME")
@click.option('--dev', '-d', '-pilot', help="Create a pilot project",
is_flag=True)
@click.pass_context
def create_project(ctx, name, dev):
"""Create a new empty project."""
existing = ctx.obj.api.projects()
for p in existing:
if name == p['name'].split('.')[-1]:
click.confirm(
"You already have an existing project with the name '{}'. "
"Are you sure you want to create another one?".format(name),
default=False,
abort=True
)
break
try:
new_proj = ctx.obj.api.create_project(name)
click.echo(
"New%s project '%s' created with id %s \nView it at %s" % (
" pilot" if dev else "", name, new_proj[
'id'], ctx.obj.api.url('%s' % (new_proj['id']))
)
)
except RuntimeError:
click.echo("There was an error creating this project.")
@cli.command("delete-project")
@click.argument('name', metavar="PROJECT_NAME")
@click.option('--force', '-f', help="force delete a project without being \
prompted if you're sure", is_flag=True)
@click.pass_context
def delete_project(ctx, name, force):
"""Delete an existing project."""
project_id = get_project_id(name)
if project_id:
if not force:
click.confirm(
"Are you sure you want to permanently delete '%s'?" %
get_project_name(project_id),
default=False,
abort=True
)
if ctx.obj.api.delete_project(project_id=str(project_id)):
click.echo("Project deleted.")
else:
click.confirm(
"Could not delete project. This may be because it contains \
runs. Try archiving it instead?",
default=False,
abort=True
)
if ctx.obj.api.archive_project(project_id=str(project_id)):
click.echo("Project archived.")
else:
click.echo("Could not archive project!")
@cli.command()
@click.argument('query', default='*')
@click.pass_context
def resources(ctx, query):
"""Search catalog of provisionable resources"""
resource_req = ctx.obj.api.resources(query)
if resource_req["results"]:
kit_req = ctx.obj.api.kits(query)
if not kit_req["results"]:
common_name = resource_req["results"][0]["name"]
kit_req = ctx.obj.api.kits(common_name)
flat_items = list(flatmap(lambda x: [{"name": y["resource"]["name"],
"id": y["resource"]["id"],
"vendor": x["vendor"]["name"] if "vendor" in list(x.keys()) else ''}
for y in x["kit_items"] if
(y["provisionable"] and not y["reservable"])],
kit_req["results"]))
rs_id_list = [rs["id"] for rs in resource_req["results"]]
matched_resources = []
for item in flat_items:
if item["id"] in rs_id_list and item not in matched_resources:
matched_resources.append(item)
if matched_resources:
click.echo("Results for '%s':" % query)
click.echo('{:^40}'.format("Resource Name") + '|' +
'{:^40}'.format("Vendor") + '|' +
'{:^40}'.format("Resource ID"))
click.echo('{:-^120}'.format(''))
for resource in matched_resources:
click.echo('{:^40}'.format(ascii_encode(resource["name"])) + '|' +
'{:^40}'.format(ascii_encode(resource["vendor"])) + '|' +
'{:^40}'.format(ascii_encode(resource["id"])))
click.echo('{:-^120}'.format(''))
else:
click.echo("No usable resource for '{}'.".format(query))
else:
click.echo("No results for '{}'.".format(query))
@cli.command()
@click.argument('query', default='*')
@click.option('--include_aliquots', help='include containers with matching aliquots', is_flag=True)
@click.option('--show_status', help='show container status', is_flag=True)
@click.option('--retrieve_all', help='retrieve all samples, this may take a while', is_flag=True)
@click.pass_context
def inventory(ctx, include_aliquots, show_status, retrieve_all, query):
"""Search organization for inventory"""
inventory_req = ctx.obj.api.inventory(query)
num_pages = inventory_req["num_pages"]
per_page = inventory_req["per_page"]
results = inventory_req["results"]
max_results_bound = num_pages * per_page
num_prefiltered = len(results)
if retrieve_all:
for i in range(1, num_pages):
click.echo("Retrieved {} records"
" out of {} total for '{}'...\r".
format(i * per_page,
max_results_bound, query), nl=False)
inventory_req = ctx.obj.api.inventory(query, page=i)
results.extend(inventory_req["results"])
click.echo()
if include_aliquots:
results = [c if "label" in c else c["container"] for c in results]
else:
results = [c for c in results if "label" in c]
results = [i for n, i in enumerate(results) if i not in results[n + 1:]]
if results:
def truncate_time(d, k):
old_time = d[k]
d[k] = old_time.split("T")[0]
return d
results = [truncate_time(c, "created_at") for c in results]
barcode_present = any(c["barcode"] for c in results)
keys = ["label", "id", "container_type_id", "storage_condition", "created_at"]
if barcode_present:
keys.insert(2, "barcode")
if show_status:
keys.append("status")
friendly_keys = {k: k.split("_")[0] for k in keys}
spacing = {k: max(len(friendly_keys[k]),
max([len(str(c[k])) for c in results])) for k in keys}
spacing = {k: (v // 2 + 1) * 2 + 1 for k, v in spacing.items()}
sum_spacing = sum(spacing.values()) + (len(keys) - 1) * 3 + 1
spacing = {k: "{:^%s}" % v for k, v in spacing.items()}
sum_spacing = "{:-^%s}" % sum_spacing
click.echo("Results for '%s':" % query)
click.echo(' | '.join([spacing[k].
format(friendly_keys[k]) for k in keys]))
click.echo(sum_spacing.format(''))
for c in results:
click.echo(' | '.join([spacing[k].
format(ascii_encode(c[k])) for k in keys]))
click.echo(sum_spacing.format(''))
if not retrieve_all:
if num_pages > 1:
click.echo("Retrieved {} records out of "
"{} total (use the --retrieve_all flag "
"to request all records).".
format(num_prefiltered, max_results_bound))
else:
if retrieve_all:
click.echo("No results for '{}'.".format(query))
else:
if num_pages > 1:
click.echo("Retrieved {} records out of "
"{} total but all were filtered out. "
"Use the --retrieve_all flag "
"to request all records.".
format(num_prefiltered, max_results_bound))
else:
click.echo("All records were filtered out. "
"Use flags to modify your search")
@cli.command()
@click.pass_context
def payments(ctx):
"""Lists available payment methods"""
methods = ctx.obj.api.payment_methods()
click.echo('{:^50}'.format("Method") + '|' +
'{:^20}'.format("Expiry") + '|' +
'{:^20}'.format("Id"))
click.echo('{:-^90}'.format(''))
if len(methods) == 0:
print_stderr("No payment methods found.")
return
for method in methods:
if method['type'] == "CreditCard":
description = "{} ending with {}".format(
method["credit_card_type"], method["credit_card_last_4"]
)
elif method['type'] == "PurchaseOrder":
description = "Purchase Order \"{}\"".format(
method["description"]
)
else:
description = method["description"]
if method['is_default?']:
description += " (Default)"
if not method['is_valid']:
description += " (Invalid)"
click.echo('{:^50}'.format(ascii_encode(description)) + '|' +
'{:^20}'.format(ascii_encode(method['expiry'])) + '|' +
'{:^20}'.format(ascii_encode(method['id'])))
@click.pass_context
def is_valid_payment_method(ctx, id):
"""Determines if payment is valid"""
methods = ctx.obj.api.payment_methods()
return any([id == method['id'] and method['is_valid'] for method in methods])
@cli.command(cls=FeatureCommand, feature='can_upload_packages')
@click.argument('path', default='.')
def init(path):
"""Initialize a directory with a manifest.json file."""
manifest_data = OrderedDict(
format="python",
license="MIT",
protocols=[{
"name": "SampleProtocol",
"version": "0.0.1",
"display_name": "Sample Protocol",
"description": "This is a protocol.",
"command_string": "python sample_protocol.py",
"inputs": {},
"preview": {"refs": {}, "parameters": {}},
}]
)
try:
os.makedirs(path)
except OSError:
click.echo("Specified directory already exists.")
if isfile('%s/manifest.json' % path):
click.confirm("This directory already contains a manifest.json file, "
"would you like to overwrite it with an empty one? ",
default=False,
abort=True)
with open('%s/manifest.json' % path, 'w+') as f:
click.echo('Creating empty manifest.json...')
f.write(json.dumps(dict(manifest_data), indent=2))
click.echo("manifest.json created")
@cli.command()
@click.argument('file', default='-')
@click.option('--test', help='Analyze this run in test mode', is_flag=True)
@click.pass_context
def analyze(ctx, file, test):
"""Analyze a block of Autoprotocol JSON."""
with click.open_file(file, 'r') as f:
try:
protocol = json.loads(f.read())
except ValueError:
click.echo("Error: The Autoprotocol you're trying to analyze is "
"not properly formatted. \n"
"Check that your manifest.json file is "
"valid JSON and/or your script "
"doesn't print anything other than pure Autoprotocol "
"to standard out.")
return
try:
analysis = ctx.obj.api.analyze_run(protocol, test_mode=test)
click.echo(u"\u2713 Protocol analyzed")
format_analysis(analysis)
except Exception as err:
click.echo("\n" + str(err))
def format_analysis(response):
def count(thing, things, num):
click.echo(" %s %s" % (num, thing if num == 1 else things))
count("instruction", "instructions", len(response['instructions']))
count("container", "containers", len(response['refs']))
price(response)
for w in response['warnings']:
message = w['message']
if 'instruction' in w['context']:
context = "instruction %s" % w['context']['instruction']
else:
context = json.dumps(w['context'])
click.echo("WARNING (%s): %s" % (context, message))
def price(response):
"""Prints out price based on response"""
# quote won't appear in response if user is missing permissions.
if "quote" not in response or "items" not in response["quote"]:
return
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
separator_len = 24
for quote_item in response['quote']['items']:
quote_str = " %s: %s" % (
quote_item["title"],
locale.currency(float(quote_item["cost"]), grouping=True))
click.echo(quote_str)
separator_len = max(separator_len, len(quote_str))
click.echo('-' * separator_len)
click.echo(" Total Cost: %s" %
locale.currency(float(response['total_cost']),
grouping=True))
@cli.command(cls=FeatureCommand, feature='can_upload_packages')
@click.argument('protocol_name', metavar="PROTOCOL_NAME")
@click.option('--view', is_flag=True)
@click.option('--dye_test', is_flag=True)
@click.pass_context
def preview(ctx, protocol_name, view, dye_test):
"""Preview the Autoprotocol output of protocol in the current package."""
manifest, protocol = load_manifest_and_protocol(protocol_name)
try:
inputs = protocol['preview']
except KeyError:
click.echo("Error: The manifest.json you're trying to preview doesn't "
"contain a \"preview\" section")
return
run_protocol(manifest, protocol, inputs, view, dye_test)
@cli.command()
@click.argument('file', default='-')
@click.pass_context
@click.option('--html', '-x', is_flag=True, help='Generates an html view of the autoprotocol')
@click.option('--tree', '-t', is_flag=True, help='Prints a job tree with instructions as leaf nodes')
@click.option('--lookup', '-l', is_flag=True, help='Queries Transcriptic to convert resourceID to string')
# time allowance is on order of seconds
@click.option('--runtime', type=click.INT, default=5)
def summarize(ctx, file, html, tree, lookup, runtime):
"""Summarize Autoprotocol as a list of plain English steps, as well as a
visualized Job Tree contingent upon desired runtime allowance (in seconds).
A Job Tree refers to a structure of protocol based on container dependency,
where each node, and its corresponding number, represents an instruction of
the protocol. More specifically, the tree structure contains process branches,
in which the x-axis refers to the dependency depth in a given branch, while
the y-axis refers to the traversal of branches themselves.
Example usage is as follows: