-
Notifications
You must be signed in to change notification settings - Fork 24
/
bundle.py
2025 lines (1691 loc) · 77.4 KB
/
bundle.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
"""
Manifest generation and bundling utilities
"""
import hashlib
import io
import json
import mimetypes
import os
import subprocess
import sys
import tarfile
import tempfile
import re
from pprint import pformat
from collections import defaultdict
from mimetypes import guess_type
from pathlib import Path
from copy import deepcopy
from typing import List
import click
try:
import typing
except ImportError:
typing = None
from os.path import basename, dirname, exists, isdir, join, relpath, splitext, isfile, abspath
from .log import logger
from .models import AppMode, AppModes, GlobSet
from .environment import Environment, MakeEnvironment
from .exception import RSConnectException
_module_pattern = re.compile(r"^[A-Za-z0-9_]+:[A-Za-z0-9_]+$")
# From https://github.com/rstudio/rsconnect/blob/485e05a26041ab8183a220da7a506c9d3a41f1ff/R/bundle.R#L85-L88
# noinspection SpellCheckingInspection
directories_ignore_list = [
".Rproj.user/",
".env/",
".git/",
".svn/",
".venv/",
"__pycache__/",
"env/",
"packrat/",
"renv/",
"rsconnect-python/",
"rsconnect/",
"venv/",
]
directories_to_ignore = {Path(d) for d in directories_ignore_list}
mimetypes.add_type("text/ipynb", ".ipynb")
class Manifest:
def __init__(
self,
*args,
version: int = None,
environment: Environment = None,
app_mode: AppMode = None,
entrypoint: str = None,
quarto_inspection: dict = None,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
primary_html: str = None,
metadata: dict = None,
files: dict = None,
**kwargs
) -> None:
self.data: dict = dict()
self.buffer: dict = dict()
self._deploy_dir: str = None
self.data["version"] = version if version else 1
if environment:
self.data["locale"] = environment.locale
if metadata is None:
self.data["metadata"] = {}
if app_mode is None:
self.data["metadata"]["appmode"] = AppModes.UNKNOWN
else:
self.data["metadata"]["appmode"] = app_mode.name()
else:
self.data["metadata"] = metadata
if primary_html:
self.data["metadata"]["primary_html"] = primary_html
if entrypoint:
self.data["metadata"]["entrypoint"] = entrypoint
if quarto_inspection:
self.data["quarto"] = {
"version": quarto_inspection.get("quarto", {}).get("version", "99.9.9"),
"engines": quarto_inspection.get("engines", []),
}
project_config = quarto_inspection.get("config", {}).get("project", {})
render_targets = project_config.get("render", [])
if len(render_targets):
self.data["metadata"]["primary_rmd"] = render_targets[0]
project_type = project_config.get("type", None)
if project_type or len(render_targets) > 1:
self.data["metadata"]["content_category"] = "site"
if environment:
package_manager = environment.package_manager
self.data["python"] = {
"version": environment.python,
"package_manager": {
"name": package_manager,
"version": getattr(environment, package_manager),
"package_file": environment.filename,
},
}
if image or env_management_py is not None or env_management_r is not None:
self.data["environment"] = {}
if image:
self.data["environment"]["image"] = image
if env_management_py is not None or env_management_r is not None:
self.data["environment"]["environment_management"] = {}
if env_management_py is not None:
self.data["environment"]["environment_management"]["python"] = env_management_py
if env_management_r is not None:
self.data["environment"]["environment_management"]["r"] = env_management_r
self.data["files"] = {}
if files:
self.data["files"] = files
@property
def deploy_dir(self):
return self._deploy_dir
@deploy_dir.setter
def deploy_dir(self, value):
self._deploy_dir = value
@classmethod
def from_json(cls, json_str):
return cls(**json.loads(json_str))
@classmethod
def from_json_file(cls, json_path):
with open(json_path) as json_file:
return cls(**json.load(json_file))
@property
def json(self):
return json.dumps(self.data, indent=2)
@property
def entrypoint(self):
if "metadata" not in self.data:
return None
if "entrypoint" in self.data["metadata"]:
return self.data["metadata"]["entrypoint"]
return None
@entrypoint.setter
def entrypoint(self, value):
self.data["metadata"]["entrypoint"] = value
@property
def primary_html(self):
if "metadata" not in self.data:
return None
if "primary_html" in self.data["metadata"]:
return self.data["metadata"]["primary_html"]
return None
@primary_html.setter
def primary_html(self, value):
self.data["metadata"]["primary_html"] = value
def add_file(self, path):
manifestPath = Path(path).as_posix()
self.data["files"][manifestPath] = {"checksum": file_checksum(path)}
return self
def discard_file(self, path):
if path in self.data["files"]:
del self.data["files"][path]
return self
def add_to_buffer(self, key, value):
self.buffer[key] = value
self.data["files"][key] = {"checksum": buffer_checksum(value)}
return self
def discard_from_buffer(self, key):
if key in self.buffer:
del self.buffer[key]
del self.data["files"][key]
return self
def raise_on_empty_entrypoint(self):
if self.entrypoint is None:
raise RSConnectException("A valid entrypoint must be provided.")
return self
@property
def flattened_data(self):
self.raise_on_empty_entrypoint()
new_data_files = {}
deploy_dir = dirname(self.entrypoint) if isfile(self.entrypoint) else self.entrypoint
deploy_dir = self.deploy_dir or deploy_dir
for path in self.data["files"]:
rel_path = relpath(path, deploy_dir)
manifestPath = Path(rel_path).as_posix()
new_data_files[manifestPath] = self.data["files"][path]
return new_data_files
@property
def flattened_buffer(self):
self.raise_on_empty_entrypoint()
new_buffer = {}
deploy_dir = dirname(self.entrypoint) if isfile(self.entrypoint) else self.entrypoint
deploy_dir = self.deploy_dir or deploy_dir
for k, v in self.buffer.items():
rel_path = relpath(k, deploy_dir)
manifestPath = Path(rel_path).as_posix()
new_buffer[manifestPath] = v
return new_buffer
@property
def flattened_entrypoint(self):
self.raise_on_empty_entrypoint()
return relpath(self.entrypoint, dirname(self.entrypoint))
@property
def flattened_primary_html(self):
if self.primary_html is None:
raise RSConnectException("A valid primary_html must be provided.")
return relpath(self.primary_html, dirname(self.primary_html))
@property
def flattened_copy(self):
self.raise_on_empty_entrypoint()
new_manifest = deepcopy(self)
new_manifest.data["files"] = self.flattened_data
new_manifest.buffer = self.flattened_buffer
new_manifest.entrypoint = self.flattened_entrypoint
if self.primary_html:
new_manifest.primary_html = self.flattened_primary_html
return new_manifest
class Bundle:
def __init__(self, *args, **kwargs) -> None:
self.file_paths: set = set()
self.buffer: dict = {}
self._deploy_dir = None
@property
def deploy_dir(self):
return self._deploy_dir
@deploy_dir.setter
def deploy_dir(self, value):
self._deploy_dir = value
def add_file(self, filepath):
self.file_paths.add(filepath)
def discard_file(self, filepath):
self.file_paths.discard(filepath)
def to_file(self, flatten_to_deploy_dir=True):
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
for fp in self.file_paths:
if Path(fp).name in self.buffer:
continue
rel_path = Path(fp).relative_to(self.deploy_dir) if flatten_to_deploy_dir else None
bundle.add(fp, arcname=rel_path)
for k, v in self.buffer.items():
buf = io.BytesIO(to_bytes(v))
file_info = tarfile.TarInfo(k)
file_info.size = len(buf.getvalue())
bundle.addfile(file_info, buf)
bundle_file.seek(0)
return bundle_file
def add_to_buffer(self, key, value):
self.buffer[key] = value
return self
def discard_from_buffer(self, key):
if key in self.buffer:
del self.buffer[key]
return self
# noinspection SpellCheckingInspection
def make_source_manifest(
app_mode: AppMode,
environment: Environment,
entrypoint: str,
quarto_inspection: typing.Dict[str, typing.Any],
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.Dict[str, typing.Any]:
manifest = {
"version": 1,
} # type: typing.Dict[str, typing.Any]
# When adding locale, add it early so it is ordered immediately after
# version.
if environment:
manifest["locale"] = environment.locale
manifest["metadata"] = {
"appmode": app_mode.name(),
}
if entrypoint:
manifest["metadata"]["entrypoint"] = entrypoint
if quarto_inspection:
manifest["quarto"] = {
"version": quarto_inspection.get("quarto", {}).get("version", "99.9.9"),
"engines": quarto_inspection.get("engines", []),
}
project_config = quarto_inspection.get("config", {}).get("project", {})
render_targets = project_config.get("render", [])
if len(render_targets):
manifest["metadata"]["primary_rmd"] = render_targets[0]
project_type = project_config.get("type", None)
if project_type or len(render_targets) > 1:
manifest["metadata"]["content_category"] = "site"
if environment:
package_manager = environment.package_manager
manifest["python"] = {
"version": environment.python,
"package_manager": {
"name": package_manager,
"version": getattr(environment, package_manager),
"package_file": environment.filename,
},
}
if image or env_management_py is not None or env_management_r is not None:
manifest["environment"] = {}
if image:
manifest["environment"]["image"] = image
if env_management_py is not None or env_management_r is not None:
manifest["environment"]["environment_management"] = {}
if env_management_py is not None:
manifest["environment"]["environment_management"]["python"] = env_management_py
if env_management_r is not None:
manifest["environment"]["environment_management"]["r"] = env_management_r
manifest["files"] = {}
return manifest
def manifest_add_file(manifest, rel_path, base_dir):
"""Add the specified file to the manifest files section
The file must be specified as a pathname relative to the notebook directory.
"""
path = join(base_dir, rel_path) if os.path.isdir(base_dir) else rel_path
if "files" not in manifest:
manifest["files"] = {}
manifestPath = Path(rel_path).as_posix()
manifest["files"][manifestPath] = {"checksum": file_checksum(path)}
def manifest_add_buffer(manifest, filename, buf):
"""Add the specified in-memory buffer to the manifest files section"""
manifest["files"][filename] = {"checksum": buffer_checksum(buf)}
def make_hasher():
try:
return hashlib.md5()
except Exception:
# md5 is not available in FIPS mode, see if the usedforsecurity option is available
# (it was added in python 3.9). We set usedforsecurity=False since we are only
# using this for a file upload integrity check.
return hashlib.md5(usedforsecurity=False)
def file_checksum(path):
"""Calculate the md5 hex digest of the specified file"""
with open(path, "rb") as f:
m = make_hasher()
chunk_size = 64 * 1024
chunk = f.read(chunk_size)
while chunk:
m.update(chunk)
chunk = f.read(chunk_size)
return m.hexdigest()
def buffer_checksum(buf):
"""Calculate the md5 hex digest of a buffer (str or bytes)"""
m = make_hasher()
m.update(to_bytes(buf))
return m.hexdigest()
def to_bytes(s):
if isinstance(s, bytes):
return s
elif hasattr(s, "encode"):
return s.encode("utf-8")
logger.warning("can't encode to bytes: %s" % type(s).__name__)
return s
def bundle_add_file(bundle, rel_path, base_dir):
"""Add the specified file to the tarball.
The file path is relative to the notebook directory.
"""
path = join(base_dir, rel_path) if os.path.isdir(base_dir) else rel_path
logger.debug("adding file: %s", path)
bundle.add(path, arcname=rel_path)
def bundle_add_buffer(bundle, filename, contents):
"""Add an in-memory buffer to the tarball.
`contents` may be a string or bytes object
"""
logger.debug("adding file: %s", filename)
buf = io.BytesIO(to_bytes(contents))
file_info = tarfile.TarInfo(filename)
file_info.size = len(buf.getvalue())
bundle.addfile(file_info, buf)
def write_manifest(
relative_dir: str,
nb_name: str,
environment: Environment,
output_dir: str,
hide_all_input: bool = False,
hide_tagged_input: bool = False,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.Tuple[list, list]:
"""Create a manifest for source publishing the specified notebook.
The manifest will be written to `manifest.json` in the output directory..
A requirements.txt file will be created if one does not exist.
Returns the list of filenames written.
"""
manifest_filename = "manifest.json"
manifest = make_source_manifest(AppModes.JUPYTER_NOTEBOOK, environment, nb_name, None,
image, env_management_py, env_management_r)
if hide_all_input:
if "jupyter" not in manifest:
manifest["jupyter"] = {}
manifest["jupyter"].update({"hide_all_input": hide_all_input})
if hide_tagged_input:
if "jupyter" not in manifest:
manifest["jupyter"] = {}
manifest["jupyter"].update({"hide_tagged_input": hide_tagged_input})
manifest_file = join(output_dir, manifest_filename)
created = []
skipped = []
manifest_relative_path = join(relative_dir, manifest_filename)
if exists(manifest_file):
skipped.append(manifest_relative_path)
else:
with open(manifest_file, "w") as f:
f.write(json.dumps(manifest, indent=2))
created.append(manifest_relative_path)
logger.debug("wrote manifest file: %s", manifest_file)
environment_filename = environment.filename
environment_file = join(output_dir, environment_filename)
environment_relative_path = join(relative_dir, environment_filename)
if environment.source == "file":
skipped.append(environment_relative_path)
else:
with open(environment_file, "w") as f:
f.write(environment.contents)
created.append(environment_relative_path)
logger.debug("wrote environment file: %s", environment_file)
return created, skipped
def list_files(base_dir, include_sub_dirs, walk=os.walk):
"""List the files in the directory at path.
If include_sub_dirs is True, recursively list
files in subdirectories.
Returns an iterable of file paths relative to base_dir.
"""
skip_dirs = [".ipynb_checkpoints", ".git"]
def iter_files():
for root, sub_dirs, files in walk(base_dir):
if include_sub_dirs:
for skip in skip_dirs:
if skip in sub_dirs:
sub_dirs.remove(skip)
else:
# tell walk not to traverse any subdirectories
sub_dirs[:] = []
for filename in files:
yield relpath(join(root, filename), base_dir)
return list(iter_files())
def make_notebook_source_bundle(
file: str,
environment: Environment,
extra_files: typing.List[str],
hide_all_input: bool,
hide_tagged_input: bool,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.IO[bytes]:
"""Create a bundle containing the specified notebook and python environment.
Returns a file-like object containing the bundle tarball.
"""
if extra_files is None:
extra_files = []
base_dir = dirname(file)
nb_name = basename(file)
manifest = make_source_manifest(AppModes.JUPYTER_NOTEBOOK, environment, nb_name, None,
image, env_management_py, env_management_r)
if hide_all_input:
if "jupyter" not in manifest:
manifest["jupyter"] = {}
manifest["jupyter"].update({"hide_all_input": hide_all_input})
if hide_tagged_input:
if "jupyter" not in manifest:
manifest["jupyter"] = {}
manifest["jupyter"].update({"hide_tagged_input": hide_tagged_input})
manifest_add_file(manifest, nb_name, base_dir)
manifest_add_buffer(manifest, environment.filename, environment.contents)
if extra_files:
skip = [nb_name, environment.filename, "manifest.json"]
extra_files = sorted(list(set(extra_files) - set(skip)))
for rel_path in extra_files:
manifest_add_file(manifest, rel_path, base_dir)
logger.debug("manifest: %r", manifest)
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
# add the manifest first in case we want to partially untar the bundle for inspection
bundle_add_buffer(bundle, "manifest.json", json.dumps(manifest, indent=2))
bundle_add_buffer(bundle, environment.filename, environment.contents)
bundle_add_file(bundle, nb_name, base_dir)
for rel_path in extra_files:
bundle_add_file(bundle, rel_path, base_dir)
bundle_file.seek(0)
return bundle_file
def make_quarto_source_bundle(
file_or_directory: str,
inspect: typing.Dict[str, typing.Any],
app_mode: AppMode,
environment: Environment,
extra_files: typing.List[str],
excludes: typing.List[str],
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.IO[bytes]:
"""
Create a bundle containing the specified Quarto content and (optional)
python environment.
Returns a file-like object containing the bundle tarball.
"""
manifest, relevant_files = make_quarto_manifest(
file_or_directory, inspect, app_mode, environment, extra_files, excludes,
image, env_management_py, env_management_r,
)
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
base_dir = file_or_directory
if not isdir(file_or_directory):
base_dir = dirname(file_or_directory)
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
bundle_add_buffer(bundle, "manifest.json", json.dumps(manifest, indent=2))
if environment:
bundle_add_buffer(bundle, environment.filename, environment.contents)
for rel_path in relevant_files:
bundle_add_file(bundle, rel_path, base_dir)
# rewind file pointer
bundle_file.seek(0)
return bundle_file
def make_html_manifest(
filename: str,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.Dict[str, typing.Any]:
# noinspection SpellCheckingInspection
manifest = {
"version": 1,
"metadata": {
"appmode": "static",
"primary_html": filename,
},
} # type: typing.Dict[str, typing.Any]
if image or env_management_py is not None or env_management_r is not None:
manifest["environment"] = {}
if image:
manifest["environment"]["image"] = image
if env_management_py is not None or env_management_r is not None:
manifest["environment"]["environment_management"] = {}
if env_management_py is not None:
manifest["environment"]["environment_management"]["python"] = env_management_py
if env_management_r is not None:
manifest["environment"]["environment_management"]["r"] = env_management_r
return manifest
def make_notebook_html_bundle(
filename: str,
python: str,
hide_all_input: bool,
hide_tagged_input: bool,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
check_output: typing.Callable = subprocess.check_output,
) -> typing.IO[bytes]:
# noinspection SpellCheckingInspection
cmd = [
python,
"-m",
"nbconvert",
"--execute",
"--stdout",
"--log-level=ERROR",
"--to=html",
filename,
]
if hide_all_input and hide_tagged_input or hide_all_input:
cmd.append("--no-input")
elif hide_tagged_input:
version = check_output([python, "--version"]).decode("utf-8")
if version >= "Python 3":
cmd.append("--TagRemovePreprocessor.remove_input_tags=hide_input")
else:
cmd.append("--TagRemovePreprocessor.remove_input_tags=['hide_input']")
try:
output = check_output(cmd)
except subprocess.CalledProcessError:
raise
nb_name = basename(filename)
filename = splitext(nb_name)[0] + ".html"
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
bundle_add_buffer(bundle, filename, output)
# manifest
manifest = make_html_manifest(filename, image, env_management_py, env_management_r)
bundle_add_buffer(bundle, "manifest.json", json.dumps(manifest, indent=2))
# rewind file pointer
bundle_file.seek(0)
return bundle_file
def keep_manifest_specified_file(relative_path, ignore_path_set=directories_to_ignore):
"""
A helper to see if the relative path given, which is assumed to have come
from a manifest.json file, should be kept or ignored.
:param relative_path: the relative path name to check.
:return: True, if the path should kept or False, if it should be ignored.
"""
p = Path(relative_path)
for parent in p.parents:
if parent in ignore_path_set:
return False
if p in ignore_path_set:
return False
return True
def _default_title_from_manifest(the_manifest, manifest_file):
"""
Produce a default content title from the contents of a manifest.
"""
filename = None
metadata = the_manifest.get("metadata")
if metadata:
# noinspection SpellCheckingInspection
filename = metadata.get("entrypoint") or metadata.get("primary_rmd") or metadata.get("primary_html")
# If the manifest is for an API, revert to using the parent directory.
if filename and _module_pattern.match(filename):
filename = None
return _default_title(filename or dirname(manifest_file))
def read_manifest_app_mode(file):
source_manifest, _ = read_manifest_file(file)
# noinspection SpellCheckingInspection
app_mode = AppModes.get_by_name(source_manifest["metadata"]["appmode"])
return app_mode
def default_title_from_manifest(file):
source_manifest, _ = read_manifest_file(file)
title = _default_title_from_manifest(source_manifest, file)
return title
def read_manifest_file(manifest_path):
"""
Read a manifest's content from its file. The content is provided as both a
raw string and a parsed dictionary.
:param manifest_path: the path to the file to read.
:return: the parsed manifest data and the raw file content as a string.
"""
with open(manifest_path, "rb") as f:
raw_manifest = f.read().decode("utf-8")
manifest = json.loads(raw_manifest)
return manifest, raw_manifest
def make_manifest_bundle(manifest_path):
"""Create a bundle, given a manifest.
:return: a file-like object containing the bundle tarball.
"""
manifest, raw_manifest = read_manifest_file(manifest_path)
base_dir = dirname(manifest_path)
files = list(filter(keep_manifest_specified_file, manifest.get("files", {}).keys()))
if "manifest.json" in files:
# this will be created
files.remove("manifest.json")
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
# add the manifest first in case we want to partially untar the bundle for inspection
bundle_add_buffer(bundle, "manifest.json", raw_manifest)
for rel_path in files:
bundle_add_file(bundle, rel_path, base_dir)
# rewind file pointer
bundle_file.seek(0)
return bundle_file
def create_glob_set(directory, excludes):
"""
Takes a list of glob strings and produces a GlobSet for path matching.
**Note:** we don't use Python's glob support because it takes way too
long to run when large file trees are involved in conjunction with the
'**' pattern.
:param directory: the directory the globs are relative to.
:param excludes: the list of globs to expand.
:return: a GlobSet ready for path matching.
"""
work = []
if excludes:
for pattern in excludes:
file_pattern = join(directory, pattern)
# Special handling, if they gave us just a dir then "do the right thing".
if isdir(file_pattern):
file_pattern = join(file_pattern, "**/*")
work.append(file_pattern)
return GlobSet(work)
def is_environment_dir(directory):
python_path = join(directory, "bin", "python")
return exists(python_path)
def list_environment_dirs(directory):
# type: (...) -> typing.List[str]
"""Returns a list of subdirectories in `directory` that appear to contain virtual environments."""
envs = []
for name in os.listdir(directory):
path = join(directory, name)
if is_environment_dir(path):
envs.append(name)
return envs
def make_api_manifest(
directory: str,
entry_point: str,
app_mode: AppMode,
environment: Environment,
extra_files: typing.List[str],
excludes: typing.List[str],
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[str]]:
"""
Makes a manifest for an API.
:param directory: the directory containing the files to deploy.
:param entry_point: the main entry point for the API.
:param app_mode: the app mode to use.
:param environment: the Python environment information.
:param extra_files: a sequence of any extra files to include in the bundle.
:param excludes: a sequence of glob patterns that will exclude matched files.
:param image: the optional docker image to be specified for off-host execution. Default = None.
:param env_management_py: False prevents Connect from managing the Python environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:param env_management_r: False prevents Connect from managing the R environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:return: the manifest and a list of the files involved.
"""
if is_environment_dir(directory):
excludes = list(excludes or []) + ["bin/", "lib/"]
extra_files = extra_files or []
skip = [environment.filename, "manifest.json"]
extra_files = sorted(list(set(extra_files) - set(skip)))
# Don't include these top-level files.
excludes = list(excludes) if excludes else []
excludes.append("manifest.json")
excludes.append(environment.filename)
excludes.extend(list_environment_dirs(directory))
relevant_files = create_file_list(directory, extra_files, excludes)
manifest = make_source_manifest(app_mode, environment, entry_point, None,
image, env_management_py, env_management_r)
manifest_add_buffer(manifest, environment.filename, environment.contents)
for rel_path in relevant_files:
manifest_add_file(manifest, rel_path, directory)
return manifest, relevant_files
def create_html_manifest(
path: str,
entrypoint: str,
extra_files: typing.List[str] = None,
excludes: typing.List[str] = None,
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
**kwargs
) -> Manifest:
"""
Creates and writes a manifest.json file for the given path.
:param path: the file, or the directory containing the files to deploy.
:param entrypoint: the main entry point for the API.
:param environment: the Python environment to start with. This should be what's
returned by the inspect_environment() function.
:param app_mode: the application mode to assume. If this is None, the extension
portion of the entry point file name will be used to derive one. Previous default = None.
:param extra_files: any extra files that should be included in the manifest. Previous default = None.
:param excludes: a sequence of glob patterns that will exclude matched files.
:param force_generate: bool indicating whether to force generate manifest and related environment files.
:param image: the optional docker image to be specified for off-host execution. Default = None.
:param env_management_py: False prevents Connect from managing the Python environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:param env_management_r: False prevents Connect from managing the R environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:return: the manifest data structure.
"""
if not path:
raise RSConnectException("A valid path must be provided.")
extra_files = list(extra_files) if extra_files else []
entrypoint_candidates = infer_entrypoint_candidates(path=abspath(path), mimetype="text/html")
deploy_dir = guess_deploy_dir(path, entrypoint)
if len(entrypoint_candidates) <= 0:
if entrypoint is None:
raise RSConnectException("No valid entrypoint found.")
entrypoint = abs_entrypoint(path, entrypoint)
elif len(entrypoint_candidates) == 1:
if entrypoint:
entrypoint = abs_entrypoint(path, entrypoint)
else:
entrypoint = entrypoint_candidates[0]
else: # len(entrypoint_candidates) > 1:
if entrypoint is None:
raise RSConnectException("No valid entrypoint found.")
entrypoint = abs_entrypoint(path, entrypoint)
extra_files = validate_extra_files(deploy_dir, extra_files, use_abspath=True)
excludes = list(excludes) if excludes else []
excludes.extend(["manifest.json"])
excludes.extend(list_environment_dirs(deploy_dir))
manifest = Manifest(app_mode=AppModes.STATIC, entrypoint=entrypoint, primary_html=entrypoint,
image=image, env_management_py=env_management_py, env_management_r=env_management_r)
manifest.deploy_dir = deploy_dir
file_list = create_file_list(path, extra_files, excludes, use_abspath=True)
for abs_path in file_list:
manifest.add_file(abs_path)
return manifest
def make_html_bundle(
path: str,
entrypoint: str,
extra_files: typing.List[str],
excludes: typing.List[str],
image: str = None,
env_management_py: bool = None,
env_management_r: bool = None,
) -> typing.IO[bytes]:
"""
Create an html bundle, given a path and/or entrypoint.
The bundle contains a manifest.json file created for the given notebook entrypoint file.
:param path: the file, or the directory containing the files to deploy.
:param entrypoint: the main entry point.
:param extra_files: a sequence of any extra files to include in the bundle.
:param excludes: a sequence of glob patterns that will exclude matched files.
:param image: the optional docker image to be specified for off-host execution. Default = None.
:param env_management_py: False prevents Connect from managing the Python environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:param env_management_r: False prevents Connect from managing the R environment for this bundle.
The server administrator is responsible for installing packages in the runtime environment. Default = None.
:return: a file-like object containing the bundle tarball.
"""
manifest = create_html_manifest(**locals())
if manifest.data.get("files") is None:
raise RSConnectException("No valid files were found for the manifest.")
bundle = Bundle()
for f in manifest.data["files"]:
if f in manifest.buffer:
continue
bundle.add_file(f)
for k, v in manifest.flattened_buffer.items():
bundle.add_to_buffer(k, v)
manifest_flattened_copy_data = manifest.flattened_copy.data
bundle.add_to_buffer("manifest.json", json.dumps(manifest_flattened_copy_data, indent=2))
bundle.deploy_dir = manifest.deploy_dir
return bundle.to_file()
def create_file_list(
path: str,
extra_files: typing.List[str] = None,
excludes: typing.List[str] = None,
use_abspath: bool = False,