-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmain.py
More file actions
2323 lines (2101 loc) · 73.6 KB
/
Copy pathmain.py
File metadata and controls
2323 lines (2101 loc) · 73.6 KB
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
import functools
import json
import os
import sys
import traceback
import typing
import textwrap
import click
from os.path import abspath, dirname, exists, isdir, join
from functools import wraps
from rsconnect.certificates import read_certificate_file
from .environment import EnvironmentException
from .exception import RSConnectException
from .actions import (
cli_feedback,
create_quarto_deployment_bundle,
describe_manifest,
quarto_inspect,
set_verbosity,
test_api_key,
test_server,
validate_quarto_engines,
which_quarto,
test_rstudio_server,
)
from .actions_content import (
download_bundle,
build_add_content,
build_remove_content,
build_list_content,
build_history,
build_start,
search_content,
get_content,
emit_build_log,
)
from . import api, VERSION, validation
from .api import RSConnectExecutor, RSConnectServer, RSConnectClient, filter_out_server_info
from .bundle import (
create_python_environment,
default_title_from_manifest,
is_environment_dir,
make_manifest_bundle,
make_html_bundle,
make_api_bundle,
make_notebook_html_bundle,
make_notebook_source_bundle,
make_voila_bundle,
read_manifest_app_mode,
write_notebook_manifest_json,
write_api_manifest_json,
write_environment_file,
write_quarto_manifest_json,
write_voila_manifest_json,
validate_entry_point,
validate_extra_files,
validate_file_is_notebook,
validate_manifest_file,
fake_module_file_from_directory,
get_python_env_info,
)
from .log import logger, LogOutputFormat
from .metadata import ServerStore, AppStore
from .models import (
AppModes,
BuildStatus,
ContentGuidWithBundleParamType,
StrippedStringParamType,
VersionSearchFilterParamType,
)
from .json_web_token import (
read_secret_key,
validate_hs256_secret_key,
TokenGenerator,
produce_bootstrap_output,
parse_client_response,
)
server_store = ServerStore()
future_enabled = False
def cli_exception_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
def failed(err):
click.secho(str(err), fg="bright_red", err=False)
sys.exit(1)
try:
result = func(*args, **kwargs)
except RSConnectException as exc:
failed("Error: " + exc.message)
except EnvironmentException as exc:
failed("Error: " + str(exc))
except Exception as exc:
if click.get_current_context("verbose"):
traceback.print_exc()
failed("Internal error: " + str(exc))
finally:
logger.set_in_feedback(False)
return result
return wrapper
def server_args(func):
@click.option("--name", "-n", help="The nickname of the Posit Connect server to deploy to.")
@click.option(
"--server",
"-s",
envvar="CONNECT_SERVER",
help="The URL for the Posit Connect server to deploy to.",
)
@click.option(
"--api-key",
"-k",
envvar="CONNECT_API_KEY",
help="The API key to use to authenticate with Posit Connect.",
)
@click.option(
"--insecure",
"-i",
envvar="CONNECT_INSECURE",
is_flag=True,
help="Disable TLS certification/host validation.",
)
@click.option(
"--cacert",
"-c",
envvar="CONNECT_CA_CERTIFICATE",
type=click.Path(exists=True, file_okay=True, dir_okay=False),
help="The path to trusted TLS CA certificates.",
)
@click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.")
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def cloud_shinyapps_args(func):
@click.option(
"--account",
"-A",
envvar=["SHINYAPPS_ACCOUNT"],
help="The shinyapps.io/Posit Cloud account name.",
)
@click.option(
"--token",
"-T",
envvar=["SHINYAPPS_TOKEN", "RSCLOUD_TOKEN"],
help="The shinyapps.io/Posit Cloud token.",
)
@click.option(
"--secret",
"-S",
envvar=["SHINYAPPS_SECRET", "RSCLOUD_SECRET"],
help="The shinyapps.io/Posit Cloud token secret.",
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def shinyapps_deploy_args(func):
@click.option(
"--visibility",
"-V",
type=click.Choice(["public", "private"]),
help="The visibility of the resource being deployed. (shinyapps.io only; must be public (default) or private)",
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def _passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def validate_env_vars(ctx, param, all_values):
vars = {}
for s in all_values:
if not isinstance(s, str):
raise click.BadParameter("environment variable must be a string: '{}'".format(s))
if "=" in s:
name, value = s.split("=", 1)
vars[name] = value
else:
# inherited value from the environment
value = os.environ.get(s)
if value is None:
raise click.BadParameter("'{}' not found in the environment".format(s))
vars[s] = value
return vars
def content_args(func):
@click.option(
"--new",
"-N",
is_flag=True,
help=(
"Force a new deployment, even if there is saved metadata from a "
"previous deployment. Cannot be used with --app-id."
),
)
@click.option(
"--app-id",
"-a",
help="Existing app ID or GUID to replace. Cannot be used with --new.",
)
@click.option("--title", "-t", help="Title of the content (default is the same as the filename).")
@click.option(
"--environment",
"-E",
"env_vars",
multiple=True,
callback=validate_env_vars,
help="Set an environment variable. Specify a value with NAME=VALUE, "
"or just NAME to use the value from the local environment. "
"May be specified multiple times. [v1.8.6+]",
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
# This callback handles the "shorthand" --disable-env-management option.
# If the shorthand flag is provided, then it takes precendence over the R and Python flags.
# This callback also inverts the --disable-env-management-r and
# --disable-env-management-py boolean flags if they are provided,
# otherwise returns None. This is so that we can pass the
# non-negative (env_management_r, env_management_py) args to our API functions,
# which is more consistent when writing these values to the manifest.
def env_management_callback(ctx, param, value) -> typing.Optional[bool]:
# eval the shorthand flag if it was provided
disable_env_management = ctx.params.get("disable_env_management")
if disable_env_management is not None:
value = disable_env_management
# invert value if it is defined.
if value is not None:
return not value
return value
def runtime_environment_args(func):
@click.option(
"--image",
"-I",
help="Target image to be used during content build and execution. "
"This option is only applicable if the Connect server is configured to use off-host execution.",
)
@click.option(
"--disable-env-management",
is_flag=True,
is_eager=True,
default=None,
help="Shorthand to disable environment management for both Python and R.",
)
@click.option(
"--disable-env-management-py",
"env_management_py",
is_flag=True,
default=None,
help="Disable Python environment management for this bundle. "
"Connect will not create an environment or install packages. An administrator must install the "
"required packages in the correct Python environment on the Connect server.",
callback=env_management_callback,
)
@click.option(
"--disable-env-management-r",
"env_management_r",
is_flag=True,
default=None,
help="Disable R environment management for this bundle. "
"Connect will not create an environment or install packages. An administrator must install the "
"required packages in the correct R environment on the Connect server.",
callback=env_management_callback,
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@click.group(no_args_is_help=True)
@click.option("--future", "-u", is_flag=True, hidden=True, help="Enables future functionality.")
def cli(future):
"""
This command line tool may be used to deploy various types of content to Posit
Connect, Posit Cloud, and shinyapps.io.
The tool supports the notion of a simple nickname that represents the
information needed to interact with a deployment target. Use the add, list and
remove commands to manage these nicknames.
The information about an instance of Posit Connect includes its URL, the
API key needed to authenticate against that instance, a flag that notes whether
TLS certificate/host verification should be disabled and a path to a trusted CA
certificate file to use for TLS. The last two items are only relevant if the
URL specifies the "https" protocol.
For Posit Cloud, the information needed to connect includes the auth token, auth
secret, and server ('posit.cloud'). For shinyapps.io, the auth token, auth secret,
server ('shinyapps.io'), and account are needed.
"""
global future_enabled
future_enabled = future
@cli.command(help="Show the version of the rsconnect-python package.")
def version():
click.echo(VERSION)
def _test_server_and_api(server, api_key, insecure, ca_cert):
"""
Test the specified server information to make sure it works. If so, a
ConnectServer object is returned with the potentially expanded URL.
:param server: the server URL, which is allowed to be missing its scheme.
:param api_key: an optional API key to validate.
:param insecure: a flag noting whether TLS host/validation should be skipped.
:param ca_cert: the name of a CA certs file containing certificates to use.
:return: a tuple containing an appropriate ConnectServer object and the username
of the user the API key represents (or None, if no key was provided).
"""
ca_data = None
if ca_cert:
ca_data = read_certificate_file(ca_cert)
me = None
with cli_feedback("Checking %s" % server):
real_server, _ = test_server(api.RSConnectServer(server, api_key, insecure, ca_data))
real_server.api_key = api_key
if api_key:
with cli_feedback("Checking API key"):
me = test_api_key(real_server)
return real_server, me
def _test_rstudio_creds(server: api.PositServer):
with cli_feedback("Checking {} credential".format(server.remote_name)):
test_rstudio_server(server)
@cli.command(
short_help="Create an initial admin user to bootstrap a Connect instance.",
help="Creates an initial admin user to bootstrap a Connect instance. Returns the provisionend API key.",
no_args_is_help=True,
)
@click.option(
"--server",
"-s",
envvar="CONNECT_SERVER",
required=True,
help="The URL for the RStudio Connect server.",
)
@click.option(
"--insecure",
"-i",
envvar="CONNECT_INSECURE",
is_flag=True,
help="Disable TLS certification/host validation.",
)
@click.option(
"--cacert",
"-c",
envvar="CONNECT_CA_CERTIFICATE",
type=click.Path(exists=True, file_okay=True, dir_okay=False),
help="The path to trusted TLS CA certificates.",
)
@click.option(
"--jwt-keypath",
"-j",
help="The path to the file containing the private key used to sign the JWT.",
)
@click.option("--raw", "-r", is_flag=True, help="Return the API key as raw output rather than a JSON object")
@click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.")
@cli_exception_handler
def bootstrap(
server,
insecure,
cacert,
jwt_keypath,
raw,
verbose,
):
set_verbosity(verbose)
if not server.startswith("http"):
raise RSConnectException("Server URL expected to begin with transfer protocol (ex. http/https).")
secret_key = read_secret_key(jwt_keypath)
validate_hs256_secret_key(secret_key)
token_generator = TokenGenerator(secret_key)
bootstrap_token = token_generator.bootstrap()
logger.debug("Generated JWT:\n" + bootstrap_token)
logger.debug("Insecure: " + str(insecure))
ca_data = None
if cacert:
ca_data = read_certificate_file(cacert)
with cli_feedback("", stderr=True):
connect_server = RSConnectServer(
server, None, insecure=insecure, ca_data=ca_data, bootstrap_jwt=bootstrap_token
)
connect_client = RSConnectClient(connect_server)
response = connect_client.bootstrap()
# post-processing on response data
status, json_data = parse_client_response(response)
output = produce_bootstrap_output(status, json_data)
if raw:
click.echo(output["api_key"])
else:
json.dump(output, sys.stdout, indent=2)
sys.stdout.write("\n")
# noinspection SpellCheckingInspection
@cli.command(
short_help="Define a nickname for a Posit Connect, Posit Cloud, or shinyapps.io server and credential.",
help=(
"Associate a simple nickname with the information needed to interact with a deployment target. "
"Specifying an existing nickname will cause its stored information to be replaced by what is given "
"on the command line."
),
no_args_is_help=True,
)
@click.option("--name", "-n", required=True, help="The nickname of the Posit Connect server to deploy to.")
@click.option(
"--server",
"-s",
envvar="CONNECT_SERVER",
help="The URL for the Posit Connect server to deploy to, OR rstudio.cloud OR shinyapps.io.",
)
@click.option(
"--api-key",
"-k",
envvar="CONNECT_API_KEY",
help="The API key to use to authenticate with Posit Connect.",
)
@click.option(
"--insecure",
"-i",
envvar="CONNECT_INSECURE",
is_flag=True,
help="Disable TLS certification/host validation.",
)
@click.option(
"--cacert",
"-c",
envvar="CONNECT_CA_CERTIFICATE",
type=click.Path(exists=True, file_okay=True, dir_okay=False),
help="The path to trusted TLS CA certificates.",
)
@click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.")
@cloud_shinyapps_args
@click.pass_context
def add(ctx, name, server, api_key, insecure, cacert, account, token, secret, verbose):
set_verbosity(verbose)
if click.__version__ >= "8.0.0" and sys.version_info >= (3, 7):
click.echo("Detected the following inputs:")
for k, v in locals().items():
if k in {"ctx", "verbose"}:
continue
if v is not None:
click.echo(" {}: {}".format(k, ctx.get_parameter_source(k).name))
validation.validate_connection_options(
url=server,
api_key=api_key,
insecure=insecure,
cacert=cacert,
account_name=account,
token=token,
secret=secret,
)
old_server = server_store.get_by_name(name)
if token:
if server and ("rstudio.cloud" in server or "posit.cloud" in server):
real_server = api.CloudServer(server, account, token, secret)
else:
real_server = api.ShinyappsServer(server, account, token, secret)
_test_rstudio_creds(real_server)
server_store.set(
name,
real_server.url,
account_name=real_server.account_name,
token=real_server.token,
secret=real_server.secret,
)
if old_server:
click.echo('Updated {} credential "{}".'.format(real_server.remote_name, name))
else:
click.echo('Added {} credential "{}".'.format(real_server.remote_name, name))
else:
# Server must be pingable and the API key must work to be added.
real_server, _ = _test_server_and_api(server, api_key, insecure, cacert)
server_store.set(
name,
real_server.url,
real_server.api_key,
real_server.insecure,
real_server.ca_data,
)
if old_server:
click.echo('Updated Connect server "%s" with URL %s' % (name, real_server.url))
else:
click.echo('Added Connect server "%s" with URL %s' % (name, real_server.url))
@cli.command(
"list",
short_help="List the known Posit Connect servers.",
help="Show the stored information about each known server nickname.",
)
@click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.")
def list_servers(verbose):
set_verbosity(verbose)
with cli_feedback(""):
servers = server_store.get_all_servers()
click.echo("Server information from %s" % server_store.get_path())
if not servers:
click.echo("No servers are saved. To add a server, see `rsconnect add --help`.")
else:
click.echo()
for server in servers:
click.echo('Nickname: "%s"' % server["name"])
click.echo(" URL: %s" % server["url"])
if server.get("api_key"):
click.echo(" API key is saved")
if server.get("insecure"):
click.echo(" Insecure mode (TLS host/certificate validation disabled)")
if server.get("ca_cert"):
click.echo(" Client TLS certificate data provided")
click.echo()
# noinspection SpellCheckingInspection
@cli.command(
short_help="Show details about a Posit Connect server.",
help=(
"Show details about a Posit Connect server and installed Python information. "
"Use this command to verify that a URL refers to a Posit Connect server, optionally, that an "
"API key is valid for authentication for that server. It may also be used to verify that the "
"information stored as a nickname is still valid."
),
no_args_is_help=True,
)
@server_args
@cli_exception_handler
def details(name, server, api_key, insecure, cacert, verbose):
set_verbosity(verbose)
ce = RSConnectExecutor(name, server, api_key, insecure, cacert).validate_server()
click.echo(" Posit Connect URL: %s" % ce.remote_server.url)
if not ce.remote_server.api_key:
return
with cli_feedback("Gathering details"):
server_details = ce.server_details
connect_version = server_details["connect"]
apis_allowed = server_details["python"]["api_enabled"]
python_versions = server_details["python"]["versions"]
click.echo(" Posit Connect version: %s" % ("<redacted>" if len(connect_version) == 0 else connect_version))
if len(python_versions) == 0:
click.echo(" No versions of Python are installed.")
else:
click.echo(" Installed versions of Python:")
for python_version in python_versions:
click.echo(" %s" % python_version)
click.echo(" APIs: %sallowed" % ("" if apis_allowed else "not "))
@cli.command(
short_help="Remove the information about a Posit Connect server.",
help=(
"Remove the information about a Posit Connect server by nickname or URL. "
"One of --name or --server is required."
),
no_args_is_help=True,
)
@click.option("--name", "-n", help="The nickname of the Posit Connect server to remove.")
@click.option("--server", "-s", help="The URL of the Posit Connect server to remove.")
@click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.")
def remove(name, server, verbose):
set_verbosity(verbose)
message = None
with cli_feedback("Checking arguments"):
if name and server:
raise RSConnectException("You must specify only one of -n/--name or -s/--server.")
if not (name or server):
raise RSConnectException("You must specify one of -n/--name or -s/--server.")
if name:
if server_store.remove_by_name(name):
message = 'Removed nickname "%s".' % name
else:
raise RSConnectException('Nickname "%s" was not found.' % name)
else: # the user specified -s/--server
if server_store.remove_by_url(server):
message = 'Removed URL "%s".' % server
else:
raise RSConnectException('URL "%s" was not found.' % server)
if message:
click.echo(message)
def _get_names_to_check(file_or_directory):
"""
A function to determine a set files to look for in getting information about a
deployment.
:param file_or_directory: the file or directory to start with.
:return: a sequence of file names to try.
"""
result = [file_or_directory]
if isdir(file_or_directory):
result.append(fake_module_file_from_directory(file_or_directory))
result.append(join(file_or_directory, "manifest.json"))
return result
@cli.command(
short_help="Show saved information about the specified deployment.",
help=(
"Display information about a deployment. For any given file, "
"information about it"
"s deployments are saved on a per-server basis."
),
no_args_is_help=True,
)
@click.argument("file", type=click.Path(exists=True, dir_okay=True, file_okay=True))
def info(file):
with cli_feedback(""):
for file_name in _get_names_to_check(file):
app_store = AppStore(file_name)
deployments = app_store.get_all()
if len(deployments) > 0:
break
if len(deployments) > 0:
click.echo("Loaded deployment information from %s" % abspath(app_store.get_path()))
for deployment in deployments:
# If this deployment was via a manifest, this will get us extra stuff about that.
file_name = deployment.get("filename")
entry_point, primary_document = describe_manifest(file_name)
label = "Directory:" if isdir(file_name) else "Filename: "
click.echo()
click.echo("Server URL: %s" % click.style(deployment.get("server_url")))
click.echo(" App URL: %s" % deployment.get("app_url"))
click.echo(" App ID: %s" % deployment.get("app_id"))
click.echo(" App GUID: %s" % deployment.get("app_guid"))
click.echo(' Title: "%s"' % deployment.get("title"))
click.echo(" %s %s" % (label, file_name))
if entry_point:
click.echo(" Entry point: %s" % entry_point)
if primary_document:
click.echo(" Primary doc: %s" % primary_document)
click.echo(" Type: %s" % AppModes.get_by_name(deployment.get("app_mode"), True).desc())
else:
click.echo("No saved deployment information was found for %s." % file)
@cli.group(no_args_is_help=True, help="Deploy content to Posit Connect, Posit Cloud, or shinyapps.io.")
def deploy():
pass
def _warn_on_ignored_manifest(directory):
"""
Checks for the existence of a file called manifest.json in the given directory.
If it's there, a warning noting that it will be ignored will be printed.
:param directory: the directory to check in.
"""
if exists(join(directory, "manifest.json")):
click.secho(
" Warning: the existing manifest.json file will not be used or considered.",
fg="yellow",
)
def _warn_if_no_requirements_file(directory):
"""
Checks for the existence of a file called requirements.txt in the given directory.
If it's not there, a warning will be printed.
:param directory: the directory to check in.
"""
if not exists(join(directory, "requirements.txt")):
click.secho(
" Warning: Capturing the environment using 'pip freeze'.\n"
" Consider creating a requirements.txt file instead.",
fg="yellow",
)
def _warn_if_environment_directory(directory):
"""
Issue a warning if the deployment directory is itself a virtualenv (yikes!).
:param directory: the directory to check in.
"""
if is_environment_dir(directory):
click.secho(
" Warning: The deployment directory appears to be a python virtual environment.\n"
" Python libraries and binaries will be excluded from the deployment.",
fg="yellow",
)
def _warn_on_ignored_requirements(directory, requirements_file_name):
"""
Checks for the existence of a file called manifest.json in the given directory.
If it's there, a warning noting that it will be ignored will be printed.
:param directory: the directory to check in.
:param requirements_file_name: the name of the requirements file.
"""
if exists(join(directory, requirements_file_name)):
click.secho(
" Warning: the existing %s file will not be used or considered." % requirements_file_name,
fg="yellow",
)
# noinspection SpellCheckingInspection,DuplicatedCode
@deploy.command(
name="notebook",
short_help="Deploy Jupyter notebook to Posit Connect [v1.7.0+].",
help=(
"Deploy a Jupyter notebook to Posit Connect. This may be done by source or as a static HTML "
"page. If the notebook is deployed as a static HTML page (--static), it cannot be scheduled or "
"rerun on the Connect server."
),
no_args_is_help=True,
)
@server_args
@content_args
@runtime_environment_args
@click.option(
"--static",
"-S",
is_flag=True,
help=(
"Render the notebook locally and deploy the result as a static "
"document. Will not include the notebook source. Static notebooks "
"cannot be re-run on the server."
),
)
@click.option(
"--python",
"-p",
type=click.Path(exists=True),
help=(
"Path to Python interpreter whose environment should be used. "
"The Python environment must have the rsconnect package installed."
),
)
@click.option(
"--force-generate",
"-g",
is_flag=True,
help='Force generating "requirements.txt", even if it already exists.',
)
@click.option("--hide-all-input", is_flag=True, default=False, help="Hide all input cells when rendering output")
@click.option(
"--hide-tagged-input", is_flag=True, default=False, help="Hide input code cells with the 'hide_input' tag"
)
@click.argument("file", type=click.Path(exists=True, dir_okay=False, file_okay=True))
@click.argument(
"extra_files",
nargs=-1,
type=click.Path(exists=True, dir_okay=False, file_okay=True),
)
@cli_exception_handler
def deploy_notebook(
name: str,
server: str,
api_key: str,
insecure: bool,
cacert: typing.IO,
static: bool,
new: bool,
app_id: str,
title: str,
python,
force_generate,
verbose: int,
file: str,
extra_files,
hide_all_input: bool,
hide_tagged_input: bool,
env_vars: typing.Dict[str, str],
image: str,
disable_env_management: bool,
env_management_py: bool,
env_management_r: bool,
):
kwargs = locals()
set_verbosity(verbose)
kwargs["extra_files"] = extra_files = validate_extra_files(dirname(file), extra_files)
app_mode = AppModes.JUPYTER_NOTEBOOK if not static else AppModes.STATIC
base_dir = dirname(file)
_warn_on_ignored_manifest(base_dir)
_warn_if_no_requirements_file(base_dir)
_warn_if_environment_directory(base_dir)
python, environment = get_python_env_info(file, python, force_generate)
if force_generate:
_warn_on_ignored_requirements(base_dir, environment.filename)
ce = RSConnectExecutor(**kwargs)
ce.validate_server().validate_app_mode(app_mode=app_mode)
if app_mode == AppModes.STATIC:
ce.make_bundle(
make_notebook_html_bundle,
file,
python,
hide_all_input,
hide_tagged_input,
image=image,
env_management_py=env_management_py,
env_management_r=env_management_r,
)
else:
ce.make_bundle(
make_notebook_source_bundle,
file,
environment,
extra_files,
hide_all_input,
hide_tagged_input,
image=image,
env_management_py=env_management_py,
env_management_r=env_management_r,
)
ce.deploy_bundle().save_deployed_info().emit_task_log()
# noinspection SpellCheckingInspection,DuplicatedCode
@deploy.command(
name="voila",
short_help="Deploy Jupyter notebook in Voila mode to Posit Connect [v2023.03.0+].",
help=("Deploy a Jupyter notebook in Voila mode to Posit Connect."),
no_args_is_help=True,
)
@server_args
@content_args
@runtime_environment_args
@click.option(
"--entrypoint",
"-e",
help=("The module and executable object which serves as the entry point."),
)
@click.option(
"--multi-notebook",
"-m",
is_flag=True,
help=("Deploy in multi-notebook mode."),
)
@click.option(
"--exclude",
"-x",
multiple=True,
help=(
"Specify a glob pattern for ignoring files when building the bundle. Note that your shell may try "
"to expand this which will not do what you expect. Generally, it's safest to quote the pattern. "
"This option may be repeated."
),
)
@click.option(
"--python",
"-p",
type=click.Path(exists=True),
help=(
"Path to Python interpreter whose environment should be used. "
"The Python environment must have the rsconnect package installed."
),
)
@click.option(
"--force-generate",
"-g",
is_flag=True,
help='Force generating "requirements.txt", even if it already exists.',
)
@click.argument("path", type=click.Path(exists=True, dir_okay=True, file_okay=True))
@click.argument(
"extra_files",
nargs=-1,
type=click.Path(exists=True, dir_okay=False, file_okay=True),
)
@cli_exception_handler
def deploy_voila(
path: str = None,
entrypoint: str = None,
python=None,
force_generate=False,
extra_files=None,
exclude=None,
image: str = "",
disable_env_management: bool = None,
env_management_py: bool = None,
env_management_r: bool = None,
title: str = None,
env_vars: typing.Dict[str, str] = None,
verbose: int = 0,
new: bool = False,
app_id: str = None,
name: str = None,
server: str = None,
api_key: str = None,
insecure: bool = False,
cacert: typing.IO = None,
connect_server: api.RSConnectServer = None,
multi_notebook: bool = False,
):
kwargs = locals()
set_verbosity(verbose)
app_mode = AppModes.JUPYTER_VOILA
environment = create_python_environment(
path if isdir(path) else dirname(path),
force_generate,
python,
)
ce = RSConnectExecutor(**kwargs).validate_server().validate_app_mode(app_mode=app_mode)
ce.make_bundle(
make_voila_bundle,
path,
entrypoint,
extra_files,
exclude,
force_generate,
environment,
image=image,
env_management_py=env_management_py,
env_management_r=env_management_r,
multi_notebook=multi_notebook,
).deploy_bundle().save_deployed_info().emit_task_log()
# noinspection SpellCheckingInspection,DuplicatedCode
@deploy.command(
name="manifest",
short_help="Deploy content to Posit Connect, Posit Cloud, or shinyapps.io by manifest.",