framework-py 0.1.0.dev14__py3-none-any.whl → 0.1.0.dev15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
framework/__main__.py CHANGED
@@ -37,8 +37,20 @@ def _parser() -> argparse.ArgumentParser:
37
37
  create.add_argument("--path", required=True, help="the project folder to create")
38
38
  create.add_argument(
39
39
  "--type",
40
- choices=["project", "project_sensitive", "course", "presentation", "bare"],
41
- help="project type, with --name (default: project, or asked with --interactive)",
40
+ choices=[
41
+ "project",
42
+ "project_sensitive",
43
+ "course",
44
+ "presentation",
45
+ "bare",
46
+ "shiny",
47
+ "shiny_python",
48
+ "fastapi",
49
+ ],
50
+ help=(
51
+ "project type, with --name (default: project, or asked with --interactive); "
52
+ "shiny and fastapi need a Framework Cloud login"
53
+ ),
42
54
  )
43
55
  create.add_argument(
44
56
  "--workflow",
framework/cloud.py CHANGED
@@ -40,6 +40,7 @@ from dataclasses import dataclass
40
40
  from datetime import UTC, datetime
41
41
  from pathlib import Path
42
42
  from typing import Any
43
+ from urllib.parse import unquote
43
44
 
44
45
  import httpx
45
46
  import pandas as pd
@@ -1617,9 +1618,28 @@ def cloud_register(
1617
1618
 
1618
1619
  def fetch_layers(key: str, url: str | None = None) -> tuple[dict[str, Any], str]:
1619
1620
  """A project's layers file from the cloud, by its project token."""
1621
+ envelope, server, _ = pull_project(key, url)
1622
+ return envelope, server
1623
+
1624
+
1625
+ def pull_project(key: str, url: str | None = None) -> tuple[dict[str, Any], str, str | None]:
1626
+ """A project's layers file, its server, and the owner's Projects folder, by project token.
1627
+
1628
+ The Projects folder is the ``Framework-Projects-Dir`` header, percent-encoded
1629
+ UTF-8, or None when the server doesn't send it.
1630
+ """
1620
1631
  server = cloud_server(url).url
1621
1632
  inform(f"Fetching this project's definition from {server} (what is shared: {server}/privacy)")
1622
- envelope = api("/api/v1/projects/pull", key, server)
1633
+ response = _request("/api/v1/projects/pull", key, server)
1634
+ envelope = response.json()
1623
1635
  if not isinstance(envelope, dict):
1624
1636
  raise CloudError("The server returned an unexpected project definition.")
1625
- return envelope, server
1637
+ return envelope, server, header_projects_dir(response.headers.get("Framework-Projects-Dir"))
1638
+
1639
+
1640
+ def header_projects_dir(value: str | None) -> str | None:
1641
+ """A Framework-Projects-Dir header value, decoded, or None when absent or blank."""
1642
+ if not value:
1643
+ return None
1644
+ decoded = unquote(value, encoding="utf-8", errors="replace").strip()
1645
+ return decoded or None
framework/create.py CHANGED
@@ -648,6 +648,38 @@ def catalog_layer(type: str) -> dict[str, Any]:
648
648
  return _defaults_layer(catalog, type) if isinstance(catalog, dict) else {}
649
649
 
650
650
 
651
+ # App project types: Framework Cloud blueprints, so they need a login. In Python,
652
+ # shiny is Shiny for Python.
653
+ APP_TYPES = {
654
+ "shiny": "framework/shiny_python",
655
+ "shiny_python": "framework/shiny_python",
656
+ "fastapi": "framework/fastapi",
657
+ }
658
+ # R's app types, with the Python type to use instead.
659
+ R_APP_TYPES = {"plumber": ("Plumber", "fastapi")}
660
+
661
+
662
+ def _invalid_type() -> FrameworkError:
663
+ return FrameworkError(
664
+ f"Invalid project type. Must be one of: {', '.join(TYPES)}, "
665
+ f"or, with Framework Cloud, {', '.join(APP_TYPES)}"
666
+ )
667
+
668
+
669
+ def _app_blueprint(type: str) -> str:
670
+ """The blueprint for an app type. It needs a Framework Cloud login, checked first."""
671
+ from framework.cloud import CloudError, cloud_server, cloud_token, host, login_hint
672
+
673
+ blueprint = APP_TYPES[type]
674
+ server = cloud_server().url
675
+ if cloud_token(server) is None:
676
+ raise CloudError(
677
+ f'type="{type}" builds the Framework Cloud blueprint {blueprint}. '
678
+ f"No cloud token found for {host(server)}. {login_hint(server)}"
679
+ )
680
+ return blueprint
681
+
682
+
651
683
  def new_project(
652
684
  name: str | None = None,
653
685
  location: str | Path | None = None,
@@ -672,8 +704,20 @@ def new_project(
672
704
 
673
705
  Args:
674
706
  name: Project name. Asked for when interactive.
675
- location: The project folder to create. Asked for when interactive.
676
- type: project, project_sensitive, course, presentation, or bare. When
707
+ location: The project folder to create. ``~`` is expanded and a relative path is
708
+ taken from the current directory. With no location, an interactive session
709
+ shows ``<current directory>/<project-name>`` and asks
710
+ ``Create the project here (<path>)? [y/n]``. With a Projects folder set in
711
+ Framework Cloud Settings, it offers ``<Projects folder>/<project-name>``
712
+ instead and asks ``Create the project in <path>? [y/n]``, creating the
713
+ Projects folder if needed. Answering n asks for the folder to put the
714
+ project in; leaving it blank uses the current directory. A
715
+ non-interactive session raises an error asking for ``location``.
716
+ type: project, project_sensitive, course, presentation, or bare. App types
717
+ ``"shiny"`` (Shiny for Python; ``"shiny_python"`` is the same) and
718
+ ``"fastapi"`` are Framework Cloud blueprints: ``type="fastapi"`` is
719
+ ``blueprint="framework/fastapi"``, and needs
720
+ [`cloud_login()`](ref:cloud_login). ``"plumber"`` is R only. When
677
721
  you are logged in to Framework Cloud, every choice is resolved there:
678
722
  a type is its system blueprint (``framework/<type>``), and with no
679
723
  choices at all the project starts from your defaults. When not logged
@@ -734,6 +778,14 @@ def new_project(
734
778
  cloud_choices = blueprint is not None or structure is not None
735
779
  if cloud_choices and type is not None:
736
780
  raise FrameworkError("Pass type, or blueprint and structure, not both")
781
+ if type in R_APP_TYPES:
782
+ label, instead = R_APP_TYPES[type]
783
+ raise FrameworkError(
784
+ f'{label} is an R project type. For a Python API, use type="{instead}".'
785
+ )
786
+ if type in APP_TYPES:
787
+ # Exactly blueprint="framework/<app>"
788
+ blueprint, type, cloud_choices = _app_blueprint(type), None, True
737
789
  if not cloud_choices:
738
790
  needs_cloud = [
739
791
  name
@@ -756,11 +808,144 @@ def new_project(
756
808
  name = input("Project name: ").strip()
757
809
  if not name:
758
810
  raise FrameworkError("Project name cannot be empty")
811
+ location = _project_location(location, kebab_case(name), interactive)
812
+ root = _new_build(
813
+ name,
814
+ location,
815
+ type,
816
+ workflow,
817
+ tools,
818
+ package_sets,
819
+ skill_sets,
820
+ blueprint,
821
+ structure,
822
+ skills,
823
+ sensitive,
824
+ ai,
825
+ git,
826
+ interactive,
827
+ offline,
828
+ cloud_choices,
829
+ )
830
+ inform(f"Project ready at {root}")
831
+ return root
832
+
833
+
834
+ def _readline(prompt: str) -> str:
835
+ """Read an answer from the user. A seam for tests."""
836
+ return input(prompt)
837
+
838
+
839
+ def _abs_location(location: str | Path) -> Path:
840
+ """A location as an absolute path: ``~`` expanded, a relative path taken from here."""
841
+ path = Path(str(location).strip()).expanduser()
842
+ return path if path.is_absolute() else Path.cwd() / path
843
+
844
+
845
+ def _projects_dir() -> str | None:
846
+ """The Projects folder set in Framework Cloud Settings, or None when unset.
847
+
848
+ It is ``defaults.projects_dir`` in the person's settings document. Signed in,
849
+ it comes from the cloud, or from the mirror ``cloud_sync()`` keeps when the
850
+ cloud can't be reached. Signed out, it comes from the mirror alone.
851
+ """
852
+ from framework.cloud import _sync_paths, api, cloud_server, cloud_token
853
+
854
+ def from_document(document: Any) -> str | None:
855
+ defaults = document.get("defaults") if isinstance(document, dict) else None
856
+ value = defaults.get("projects_dir") if isinstance(defaults, dict) else None
857
+ return value.strip() if isinstance(value, str) and value.strip() else None
858
+
859
+ try:
860
+ server = cloud_server().url
861
+ token = cloud_token(server)
862
+ except FrameworkError:
863
+ token = None
864
+ if token:
865
+ try:
866
+ response = api("/api/v1/settings", token, server)
867
+ except FrameworkError:
868
+ response = None
869
+ if isinstance(response, dict) and "document" in response:
870
+ return from_document(response["document"])
871
+
872
+ mirror = _sync_paths()[0]
873
+ if not mirror.is_file():
874
+ return None
875
+ try:
876
+ return from_document(_yaml.read(mirror))
877
+ except Exception: # an unreadable mirror counts as unset
878
+ return None
879
+
880
+
881
+ def _ask_location(slug: str, interactive: bool, projects_dir: str | None = None) -> Path:
882
+ """Where a new project goes when no location was given, as in R.
883
+
884
+ An interactive session confirms a folder named for the project in the
885
+ Projects folder (``projects_dir``, else the one in Framework Cloud Settings),
886
+ or in the current directory when neither is set, or takes the folder to put
887
+ it in. There is never a
888
+ default elsewhere: the location is always explicit.
889
+ """
890
+ here = Path.cwd()
891
+ suggested = here / slug
892
+ if not interactive:
893
+ raise FrameworkError(
894
+ "No project location given. Pass `location=`, the folder to create, "
895
+ f'such as location="{suggested}".'
896
+ )
897
+ projects_dir = projects_dir or _projects_dir()
898
+ if projects_dir is None:
899
+ question = f"Create the project here ({suggested})? [y/n] "
900
+ else:
901
+ suggested = _abs_location(projects_dir) / slug
902
+ question = f"Create the project in {suggested}? [y/n] "
903
+ while True:
904
+ answer = _readline(question).strip().lower()
905
+ if answer in ("", "y", "yes"):
906
+ return suggested
907
+ if answer in ("n", "no"):
908
+ break
909
+ inform("Answer y or n.")
910
+ typed = _readline(
911
+ f"Where should the project go? Leave blank to use the current directory ({here}): "
912
+ ).strip()
913
+ parent = _abs_location(typed) if typed else here
914
+ # A typed path that already names the project folder is used as is
915
+ return parent if parent.name == slug else parent / slug
916
+
917
+
918
+ def _project_location(
919
+ location: str | Path | None, slug: str, interactive: bool, projects_dir: str | None = None
920
+ ) -> Path:
921
+ """The absolute project folder, asked for when not given, announced before creation."""
759
922
  if location is None:
760
- if not interactive:
761
- raise FrameworkError("Project location is required in non-interactive mode")
762
- suggested = Path("~") / "projects" / kebab_case(name)
763
- location = input(f"Project location [{suggested}]: ").strip() or suggested
923
+ root = _ask_location(slug, interactive, projects_dir)
924
+ else:
925
+ root = _abs_location(location)
926
+ inform(f"Creating the project at {root}")
927
+ return root
928
+
929
+
930
+ def _new_build(
931
+ name: str,
932
+ location: Path,
933
+ type: str | None,
934
+ workflow: str | None,
935
+ tools: Mapping[str, bool] | Sequence[str] | None,
936
+ package_sets: Sequence[str],
937
+ skill_sets: Sequence[str],
938
+ blueprint: str | None,
939
+ structure: str | None,
940
+ skills: Sequence[str],
941
+ sensitive: bool | None,
942
+ ai: bool | Mapping[str, Any] | None,
943
+ git: bool | None,
944
+ interactive: bool,
945
+ offline: bool,
946
+ cloud_choices: bool,
947
+ ) -> Path:
948
+ """Build the project at its resolved location: from the cloud, or locally."""
764
949
 
765
950
  def local(register: bool = True) -> Path:
766
951
  return _new_local(
@@ -789,7 +974,7 @@ def new_project(
789
974
  return local()
790
975
  # Logged in: the cloud resolves every choice. A Framework type is its system blueprint.
791
976
  if type is not None and type not in TYPES:
792
- raise FrameworkError(f"Invalid project type. Must be one of: {', '.join(TYPES)}")
977
+ raise _invalid_type()
793
978
  body = _choices_body(
794
979
  name,
795
980
  f"framework/{type}" if type else None,
@@ -825,7 +1010,7 @@ def _new_local(
825
1010
  else:
826
1011
  type = "project"
827
1012
  if type not in TYPES:
828
- raise FrameworkError(f"Invalid project type. Must be one of: {', '.join(TYPES)}")
1013
+ raise _invalid_type()
829
1014
 
830
1015
  from framework.features import definition_layers, workflow_layers
831
1016
 
@@ -1045,16 +1230,15 @@ def _replace_default_skills(spec: dict[str, Any], type: str, layers: Sequence[An
1045
1230
  def _new_from_cloud(
1046
1231
  key: str, location: str | Path | None, interactive: bool, url: str | None = None
1047
1232
  ) -> Path:
1048
- from framework.cloud import fetch_layers, write_project_token
1233
+ from framework.cloud import pull_project, write_project_token
1049
1234
 
1050
- envelope, server = fetch_layers(key, url)
1235
+ envelope, server, owner_projects_dir = pull_project(key, url)
1051
1236
  name = envelope.get("name")
1052
1237
  if not name:
1053
1238
  raise FrameworkError("The cloud project has no name")
1054
- if location is None:
1055
- suggested = Path("~") / "projects" / kebab_case(str(name))
1056
- answer = input(f"Location [{suggested}]: ").strip() if interactive else ""
1057
- location = answer or suggested
1239
+ location = _project_location(
1240
+ location, _envelope_slug(envelope, str(name)), interactive, owner_projects_dir
1241
+ )
1058
1242
  resolved = spec_resolve(envelope.get("layers") or [], str(name), envelope.get("author"))
1059
1243
  spec = resolved.spec
1060
1244
  spec["source"] = envelope.get("source") or {"origin": "cloud"}
@@ -1065,6 +1249,16 @@ def _new_from_cloud(
1065
1249
  return root
1066
1250
 
1067
1251
 
1252
+ def _envelope_slug(envelope: Mapping[str, Any], name: str) -> str:
1253
+ """The cloud project's slug, the key of its project layer, or one made from its name."""
1254
+ for entry in reversed(envelope.get("layers") or []):
1255
+ if isinstance(entry, dict) and entry.get("kind") == "project":
1256
+ key = entry.get("key")
1257
+ if isinstance(key, str) and key:
1258
+ return key
1259
+ return kebab_case(name)
1260
+
1261
+
1068
1262
  def project_add_directory(project_path: str | Path, key: str, label: str, path: str) -> Path:
1069
1263
  """Create a folder in a project and record it under ``extra_directories``.
1070
1264
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: framework-py
3
- Version: 0.1.0.dev14
3
+ Version: 0.1.0.dev15
4
4
  Summary: Structured data science projects: a data catalog, integrity tracking, caching, outputs, and AI guardrails
5
5
  Project-URL: Homepage, https://framework.pub
6
6
  Project-URL: Source, https://github.com/frameworktools/framework-py
@@ -1,5 +1,5 @@
1
1
  framework/__init__.py,sha256=o0XJpG81cf3D_3scUvP1jHHMke0-LH47_9DyQr61Ghg,6395
2
- framework/__main__.py,sha256=2ckCsWoKuWPRcAYZFhtHvwG2eK2ngPM2NpHjEvn2Ex0,8863
2
+ framework/__main__.py,sha256=S0ChmRQnNa9W5_MPXhHnH61Kjr_pNthkeS41eJU1w0U,9093
3
3
  framework/_agents_md.py,sha256=mfFH73aGY5RF60YWQMB4zF3C40EqOD7ptgdSqgdEGNc,9830
4
4
  framework/_artifacts.py,sha256=cOk2XLqctoqLaQSkksmc7cP4W0_AgqSxYNCTJxyZyik,36068
5
5
  framework/_backups.py,sha256=ra1DhGcIbIXB0zqDFVFJ3yPEjmXpYKFX-fjV01b9Rtg,1958
@@ -25,11 +25,11 @@ framework/ai.py,sha256=1yhagWueOJrqpOWPnksekFt7QlnzGVWW5mxanF2Pi0g,10994
25
25
  framework/bootstrap.py,sha256=mYlD1BG9KaG9PAIHlw3l6677fJYwQdtih95W9Rqmnho,9687
26
26
  framework/cache.py,sha256=jJxWIs6kQ7naMenC96pCPtqDCYiCe9c1KSITufV75q4,17160
27
27
  framework/catalog.py,sha256=sl4V1judSCVoa2LYLXeQdDhWdsONTC_5s2_fpyPylto,13202
28
- framework/cloud.py,sha256=6uZKBgFuTvAAEneJ2QXiLP-IVCAN_5gF1gj4yR_wSok,62607
28
+ framework/cloud.py,sha256=A3HmRiMP8RSK0MIG5WL5Y_T5yRwX-qBvKNE9dX2UCL4,63442
29
29
  framework/config_home.py,sha256=iSb0VuENgNOSnsZ_v53xFqjRiGgrB7OzZbHbyDOqKzs,8265
30
30
  framework/connections.py,sha256=EUkWtuQKW7X-BLJOKXzSbVTSNE6raxjV_GuIELjAOSY,32439
31
31
  framework/console.py,sha256=zQ0LuFDcxe1W1kuc5E1bJ03h8d3cvwFoqDT8dAJQyN0,1267
32
- framework/create.py,sha256=9hG-FyjXuU8rzRunhhTaQ55u4sIxJxED20y82SvwEHk,45408
32
+ framework/create.py,sha256=3cR7swrNyIz0fN-x2J_AcFs4zWpR5wjj_UvOZWK88UY,52432
33
33
  framework/data.py,sha256=5EwVKFwXABIhbEuf2MsvS8v_yJJ27upG0itSYA6N5mo,31557
34
34
  framework/db.py,sha256=Wruez2V352xA3gjk5RcUi_0zncFsDwTs9Gwa2hXBY3Y,8099
35
35
  framework/display.py,sha256=0FuKUt67uf5h1WjD4bwzoruc2XAN4y_j3mz_f5FskhE,5334
@@ -124,7 +124,7 @@ framework/templates/stubs/notebook-default.qmd,sha256=8Js1S2BcHYeQWmJS-kt31gBvIj
124
124
  framework/templates/stubs/notebook-minimal.qmd,sha256=2U2k8judffhrh_6m6r6OAbQBCYEtViAjeKRBqBYCJTM,178
125
125
  framework/templates/stubs/notebook-revealjs.qmd,sha256=_ztT_gHoudpB5DIjlbvtB5zQ8163DeV8xbWcT-HgJrI,409
126
126
  framework/templates/stubs/script-default.py,sha256=vbWqgW0_rHot17mQC3tYb92g_9L-cbTOeL3y99BRrSk,216
127
- framework_py-0.1.0.dev14.dist-info/METADATA,sha256=J76tG5URU-7unX0qBod-v_VA3zSOT2fwdwYSZZns3gk,4281
128
- framework_py-0.1.0.dev14.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
129
- framework_py-0.1.0.dev14.dist-info/licenses/LICENSE,sha256=giOOgSwALkZimC7uhLZQK8Untez641bLW1-2-Cjvmq0,1072
130
- framework_py-0.1.0.dev14.dist-info/RECORD,,
127
+ framework_py-0.1.0.dev15.dist-info/METADATA,sha256=qxJG-pNutvPhGjHXBMuYNblfoqLwGnrJ4nyou-qNfCk,4281
128
+ framework_py-0.1.0.dev15.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
129
+ framework_py-0.1.0.dev15.dist-info/licenses/LICENSE,sha256=giOOgSwALkZimC7uhLZQK8Untez641bLW1-2-Cjvmq0,1072
130
+ framework_py-0.1.0.dev15.dist-info/RECORD,,