Skip to content

blext.uityp

blext.uityp.blext_info

Load various data from external sources.

BLExtUI pydantic-model

Bases: BaseModel

CLI parameters-interface making it easy to create BLExtLocation and BLExtSpec.

Notes

Names are chosen to be friendly on a CLI interface.

ATTRIBUTE DESCRIPTION
path

Path to a blext project:

  • Current Directory (default): Search upwards for a pyproject.toml.
  • Project File (pyproject.toml): Configure using the [tool.blext] table.
  • Project Folder (*/pyproject.toml): Folder containing a pyproject.toml.
  • Script File (*.py): Identical configuration using "inline script metadata".

TYPE: Path | None

url

URL to a Blender extension Script File.

TYPE: str | None

git

A git repository containing pyproject.toml.

TYPE: GitLocationUI | None

platform

Blender platform(s) to target.

TYPE: tuple[BLPlatform | Literal['detect'], ...]

profile

Release profile to apply.

TYPE: StandardReleaseProfile | str | None

config

Global configuration of blext.

TYPE: StandardReleaseProfile | str | None

Fields:

bl_platforms

bl_platforms(
	global_config: GlobalConfig,
) -> frozenset[BLPlatform]

All selected Blender versions.

Source code in blext/uityp/blext_info.py
391
392
393
394
395
396
397
@lru_method()
def bl_platforms(self, global_config: GlobalConfig) -> frozenset[extyp.BLPlatform]:
	"""All selected Blender versions."""
	requested_bl_platforms = self.requested_bl_platforms(global_config)
	if not requested_bl_platforms:
		return self.blext_spec(global_config).bl_platforms
	return requested_bl_platforms

bl_versions

bl_versions(
	global_config: GlobalConfig,
) -> frozenset[BLVersion]

All selected Blender versions.

Source code in blext/uityp/blext_info.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
@lru_method()
def bl_versions(self, global_config: GlobalConfig) -> frozenset[extyp.BLVersion]:
	"""All selected Blender versions."""
	blext_spec = self.blext_spec(global_config)

	requested_bl_versions = self.requested_bl_versions(global_config)
	if not requested_bl_versions:
		return blext_spec.bl_versions
	return frozenset(
		{
			(
				bl_version
				if bl_version in blext_spec.bl_versions
				else blext_spec.bl_versions_by_granular[bl_version]
			)
			for bl_version in requested_bl_versions
		}
	)

blext_location

blext_location(
	global_config: GlobalConfig,
) -> BLExtLocation

Extension location that the user requested.

Notes
  • Essentially a convenient way of calling blext.finders.find_proj_spec.
  • The "abstract location" returned exposes a standard interface for getting ex. the path to the extension specification. To achieve this functionality, it might first ex. download a URL, clone a git repository, etc. .
PARAMETER DESCRIPTION
global_config

Global configuration.

TYPE: GlobalConfig

See Also
  • blext.location.BLExtLocation: Abstract location of a Blender extension.
  • blext.finders.find_proj_spec: Find a project by its URI, returning a location.
Source code in blext/uityp/blext_info.py
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
@lru_method()
def blext_location(self, global_config: GlobalConfig) -> extyp.BLExtLocation:
	"""Extension location that the user requested.

	Notes:
		- Essentially a convenient way of calling `blext.finders.find_proj_spec`.
		- The "abstract location" returned exposes a standard interface for getting ex. the path to the extension specification.
		To achieve this functionality, it might first ex. download a URL, clone a git repository, etc. .


	Parameters:
		global_config: Global configuration.

	See Also:
		- `blext.location.BLExtLocation`: Abstract location of a Blender extension.
		- `blext.finders.find_proj_spec`: Find a project by its URI, returning a location.
	"""
	config_paths = {
		'path_global_project_cache': global_config.path_global_project_cache,
		'path_global_download_cache': global_config.path_global_download_cache,
	}

	err_msgs: list[str] = []
	match (self.path, self.url, self.git):
		case (path, None, None):
			return extyp.BLExtLocationPath(
				path=path,
				**config_paths,  # pyright: ignore[reportArgumentType]
			)

		case (None, str() as url, None):
			return extyp.BLExtLocationHttp(
				url=url,  # pyright: ignore[reportArgumentType]
				**config_paths,  # pyright: ignore[reportArgumentType]
			)

		case (None, None, GitLocationUI() as git) if git.url is not None:
			return extyp.BLExtLocationGit(
				url=pyd.HttpUrl(git.url),
				rev=git.rev,
				tag=git.tag,
				branch=git.branch,
				entrypoint=git.entrypoint,
				**config_paths,  # pyright: ignore[reportArgumentType]
			)

		case (None, None, GitLocationUI()):
			err_msgs += [
				'**No `git` URL Given**: `--git.url` must be given.',
				'',
				*ERR_EXPLAIN_PROJ,
			]

		case (
			(None, str(), GitLocationUI())
			| (Path(), None, GitLocationUI())
			| (Path(), str(), None)
			| (Path(), str(), GitLocationUI())
		):
			err_msgs += [
				'**Multiple Locations Given**: Only one of `--path`, `--url`, or `--git` may be given.',
				'> **Given Locations**:',
				*[
					f'> - `{name}`: `{spec}`'
					for name, spec in {
						'--path': self.path,
						'--url': self.url,
						'--git': self.git,
					}.items()
				],
				'>',
				'> _Exactly one must be given._',
				'',
				*ERR_EXPLAIN_PROJ,
			]

	raise ValueError(*err_msgs)

blext_spec

blext_spec(global_config: GlobalConfig) -> BLExtSpec

Load the extension specification.

Notes
  • Uses self.blext_location internally.
  • Runs blext_spec.set_bl_platforms(self.request_bl_platforms) after loading succeeds.
PARAMETER DESCRIPTION
global_config

Global configuration.

TYPE: GlobalConfig

See Also
  • blext.location.BLExtLocation: Abstract location of a Blender extension.
  • blext.finders.find_proj_spec: Find a project by its URI, returning a location.
Source code in blext/uityp/blext_info.py
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
@lru_method()
def blext_spec(self, global_config: GlobalConfig) -> BLExtSpec:
	"""Load the extension specification.

	Notes:
		- Uses `self.blext_location` internally.
		- Runs `blext_spec.set_bl_platforms(self.request_bl_platforms)` after loading succeeds.

	Parameters:
		global_config: Global configuration.

	See Also:
		- `blext.location.BLExtLocation`: Abstract location of a Blender extension.
		- `blext.finders.find_proj_spec`: Find a project by its URI, returning a location.
	"""
	blext_location = self.blext_location(global_config=global_config)

	# Load BLExtSpec
	## Also, update project specification.
	blext_spec = BLExtSpec.from_proj_spec_path(
		blext_location.path_spec,
		path_uv_exe=global_config.path_uv_exe,
		release_profile_id=self.profile,
	)
	if self.update_proj_spec(global_config, blext_spec=blext_spec):
		pydeps.uv.update_uv_lock(
			blext_location.path_uv_lock,
			path_uv_exe=global_config.path_uv_exe,
		)
		blext_spec = BLExtSpec.from_proj_spec_path(
			blext_location.path_spec,
			path_uv_exe=global_config.path_uv_exe,
			release_profile_id=self.profile,
		)

	# Constrain BLPlatforms
	bl_platforms = self.requested_bl_platforms(global_config)
	if not bl_platforms:
		return blext_spec
	return blext_spec.replace_bl_platforms(bl_platforms)

parse_proj

parse_proj(proj: str | None) -> Self

Alter the information with information from the position argument PROJ.

PARAMETER DESCRIPTION
proj

Positional argument making it easy for users to specify a project.

TYPE: str | None

Source code in blext/uityp/blext_info.py
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
def parse_proj(self, proj: str | None) -> typ.Self:  # noqa: C901, PLR0912
	"""Alter the information with information from the position argument `PROJ`.

	Parameters:
		proj: Positional argument making it easy for users to specify a project.
	"""
	err_msgs: list[str] = []
	kwargs = self.model_dump()
	match (proj, self.path, self.url, self.git):
		case (None, _, _, _):
			return self

		####################
		# - Project String: HTTP
		####################
		case (str() as proj, None, None, None) if proj.startswith('script+http'):
			kwargs['url'] = proj.removeprefix('script+')

		case (str() as proj, None, None, None) if proj.startswith('packed+http'):
			kwargs['url'] = proj.removeprefix('packed+')

		case (str() as proj, _, str() as url, _) if proj.startswith(
			('script+http', 'packed+http', 'http')
		):
			err_msgs += [
				f"**Two URLs Given**: Both `PROJ` ('{proj}') and `--url` ('{url}') are given.",
				'> There are two ways to locate a `blext` extension by URL:',
				'> 1. Specify `PROJ` (ex. `https://example.org/ext.py`).',
				'> 2. Specify `--url` explicitly.',
				'>',
				'> _Exactly one must be given._',
				'',
			]

		####################
		# - Project String: Path
		####################
		case (str() as proj, None, None, None) if proj.startswith('script+'):
			kwargs['path'] = proj.removeprefix('script+')

		case (str() as proj, None, None, None) if proj.startswith('project+'):
			kwargs['path'] = proj.removeprefix('project+')

		case (str() as proj, None, None, None) if proj.startswith('packed+'):
			kwargs['path'] = proj.removeprefix('packed+')

		case (str() as proj, Path() as path, _, _) if proj.startswith(
			('script+', 'packed+')
		) or not proj.startswith(('script+', 'project+', 'packed+', 'git+')):
			err_msgs += [
				f"**Two Paths Given**: Both `PROJ` ('{proj}') and `--path` ('{path}') are given.",
				'> There are two ways to locate a `blext` extension by path:',
				'> 1. Specify `PROJ` (ex. `path/to/script.py`).',
				'> 2. Specify `--path` explicitly.',
				'>',
				'> _Exactly one must be given._',
				'',
			]

		####################
		# - Project String: Git
		####################
		case (str() as proj, None, None, GitLocationUI() as git) if (
			proj.startswith('git+') and git.url is None
		):
			kwargs['git']['url'] = proj.removeprefix('git+')

		case (str() as proj, None, None, None as git) if proj.startswith('git+'):
			kwargs['git'] = {'url': proj.removeprefix('git+')}

		case (str() as proj, _, _, GitLocationUI() as git) if (
			proj.startswith('git+') and git.url is not None
		):
			err_msgs += [
				f"**Two `git` URLs Given**: Both `PROJ` ('{proj}') and `--git.url` ('{git.url}') are given.",
				'> There are two ways to locate a `blext` extension by `git`:',
				'> 1. Specify `PROJ` (ex. `git+https://example.org/repo.git`).',
				'> 2. Specify `--git.url` explicitly.',
				'>',
				'> _Exactly one must be given._',
				'',
			]

		####################
		# - Project String: Unprefixed
		####################
		# URL
		case (str() as proj, None, None, None) if proj.startswith('http'):
			kwargs['url'] = proj

		# Path: Detect
		case (str() as proj, None, None, None) if Path(proj).exists():
			kwargs['path'] = proj

		####################
		# - Project String: Handle Errors
		####################
		case (str() as proj, None, None, None):
			err_msgs += [
				f'**Invalid `PROJ`**: `{proj}` does not exist, or is not specified correctly.',
				*ERR_VALID_PROJS,
			]

		case (str() as proj, _, _, _):
			err_msgs += [
				'**Invalid Location**: There is not one, unambiguous location to search for a `blext` project.',
				f'> **Implicit Location** (`PROJ`): `{proj}`',
				'>',
				'> **Explicit Locations** (`--<options>`):',
				*[
					f'> - `{name}`: `{spec}`'
					for name, spec in {
						'--path': self.path if self.path is not None else '...',
						'--url': self.url if self.url is not None else '...',
						'--git': self.git if self.git is not None else '...',
					}.items()
				],
				'>',
				'> _Only one location may be given._',
				'',
				*ERR_EXPLAIN_PROJ,
				# *ERR_VALID_PROJS,
			]

	if err_msgs:
		raise ValueError(*err_msgs)

	return self.__class__(**kwargs)  # pyright: ignore[reportAny]

path_zip_prepacks

path_zip_prepacks(
	global_config: GlobalConfig,
) -> frozendict[BLVersion, Path]

Paths of all extension pre-packed archives that should be prepared from self.blext_spec.

PARAMETER DESCRIPTION
global_config

Global configuration parameters.

TYPE: GlobalConfig

RETURNS DESCRIPTION
frozendict[BLVersion, Path]

Mapping from BLVersion to the corresponding Path to prepare pre-packed archive for that version (chunk) at.

Source code in blext/uityp/blext_info.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
@lru_method()
def path_zip_prepacks(
	self, global_config: GlobalConfig
) -> frozendict[extyp.BLVersion, Path]:
	"""Paths of all extension pre-packed archives that should be prepared from `self.blext_spec`.

	Parameters:
		global_config: Global configuration parameters.

	Returns:
		Mapping from `BLVersion` to the corresponding `Path` to prepare pre-packed archive for that version (chunk) at.
	"""
	blext_location = self.blext_location(global_config)
	blext_spec = self.blext_spec(global_config)

	extension_filenames = blext_spec.export_extension_filenames()
	return frozendict(
		{
			bl_version: (
				blext_location.path_prepack_cache / extension_filenames[bl_version]
			)
			for bl_version in blext_spec.bl_versions
		}
	)

path_zips

path_zips(
	global_config: GlobalConfig,
) -> frozendict[BLVersion, Path]

Paths of all extension .zips that should be built from self.blext_spec.

PARAMETER DESCRIPTION
global_config

Global configuration parameters.

TYPE: GlobalConfig

RETURNS DESCRIPTION
frozendict[BLVersion, Path]

Mapping from BLVersion to the corresponding Path to build the extension for that version (chunk) at.

Source code in blext/uityp/blext_info.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
@lru_method()
def path_zips(
	self, global_config: GlobalConfig
) -> frozendict[extyp.BLVersion, Path]:
	"""Paths of all extension `.zip`s that should be built from `self.blext_spec`.

	Parameters:
		global_config: Global configuration parameters.

	Returns:
		Mapping from `BLVersion` to the corresponding `Path` to build the extension for that version (chunk) at.
	"""
	blext_location = self.blext_location(global_config)
	blext_spec = self.blext_spec(global_config)

	extension_filenames = blext_spec.export_extension_filenames()
	return frozendict(
		{
			bl_version: (
				blext_location.path_build_cache / extension_filenames[bl_version]
			)
			for bl_version in blext_spec.bl_versions
		}
	)

requested_bl_platforms

requested_bl_platforms(
	global_config: GlobalConfig,
) -> frozenset[BLPlatform]

Set of BLPlatforms that the user requested.

Source code in blext/uityp/blext_info.py
225
226
227
228
229
230
231
232
233
234
235
236
237
@lru_method()
def requested_bl_platforms(
	self, global_config: GlobalConfig
) -> frozenset[extyp.BLPlatform]:
	"""Set of BLPlatforms that the user requested."""
	return frozenset(
		{
			global_config.local_bl_platform
			if bl_platform == 'detect'
			else bl_platform
			for bl_platform in self.platform
		}
	)

requested_bl_versions

requested_bl_versions(
	global_config: GlobalConfig,
) -> frozenset[BLVersion]

Set of BLPlatforms that the user requested.

Source code in blext/uityp/blext_info.py
239
240
241
242
243
244
245
246
247
248
249
250
251
@lru_method()
def requested_bl_versions(
	self, global_config: GlobalConfig
) -> frozenset[extyp.BLVersion]:
	"""Set of BLPlatforms that the user requested."""
	return frozenset(
		{
			global_config.local_default_bl_version
			if bl_release == 'detect'
			else bl_release.bl_version
			for bl_release in self.bl_version
		}
	)

update_proj_spec

update_proj_spec(
	global_config: GlobalConfig, *, blext_spec: BLExtSpec
) -> bool

Update a project specification to take vendored site-packages into account from all supported Blender versions.

Source code in blext/uityp/blext_info.py
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
def update_proj_spec(  # noqa: C901, PLR0912, PLR0915
	self, global_config: GlobalConfig, *, blext_spec: BLExtSpec
) -> bool:
	"""Update a project specification to take vendored `site-packages` into account from all supported Blender versions."""
	altered_spec = False

	blext_location = self.blext_location(global_config=global_config)
	all_extras = {
		(
			pymarker_extra.replace(
				'-', '_'
			),  ## '-'/'_' differ between uv.lock/pyproject.toml
			bl_version.vendored_site_packages,
		)
		for bl_version in sorted(
			blext_spec.bl_versions,
			key=lambda el: tuple(
				int(v) for v in el.source.blender_version_min.split('.')
			),
		)
		for pymarker_extra in bl_version.pymarker_extras
	}
	if len({extra[0] for extra in all_extras}) < len(all_extras):
		msg = 'In BLReleaseOfficial, two entries with identical `pymarker_extra`s have differing `vendored_site_packages`. Please report this as a bug in `blext`.'
		raise RuntimeError(msg)

	if blext_location.path_spec.name == 'pyproject.toml':
		####################
		# - Stage 0: Handle Blender Versions in [projects.optional-dependencies]
		####################
		with blext_location.path_spec.open('r') as f:
			doc = tomlkit.parse(f.read())

		original_doc = tomlkit.dumps(doc)  # pyright: ignore[reportUnknownMemberType]

		# The user must already have defined a `[project]` table.
		## If it's not a table, then that's an error.
		## Otherwise, `pyproject.toml` isn't valid.
		if 'project' not in doc:
			msgs = [
				'In `pyproject.toml`, `[project]` does not exists.',
				'> Please define the `[project]` table.',
			]
			raise ValueError(*msgs)
		if not isinstance(doc['project'], tomlkit.items.Table):
			msgs = [
				"In `pyproject.toml`, `[project]` exists, but isn't a table.",
				'> Please define `[project]` as a table.',
			]
			raise ValueError(*msgs)

		# The user need not have defined optional-dependencies - otherwise we do it for them.
		## If it isn't a table, then that's an error.
		if 'optional-dependencies' not in doc['project']:  # pyright: ignore[reportOperatorIssue]
			doc['project']['optional-dependencies'] = tomlkit.table()  # pyright: ignore[reportIndexIssue]
		elif not isinstance(
			doc['project']['optional-dependencies'],  # pyright: ignore[reportIndexIssue]
			tomlkit.items.Table,
		):
			msg = "In `pyproject.toml`, `[project.optional-dependencies]` exists, but isn't a table."
			raise ValueError(msg)

		# Now we iterate over all the extras aka. Blender versions with vendored pydep versions.
		for extra in sorted(all_extras, key=lambda el: el[0]):
			extra_name = extra[0]
			vendored_site_packages = [
				f'{pkg_name}=={pkg_version}'
				for pkg_name, pkg_version in extra[1].items()
			]  ## Use explicit `==` to precisely match what Blender ships with

			# If 'extra_name' is already there, we need to be very precise.
			## Since pyproject.toml is user-authored, we must be careful to preserve styling.
			if extra_name not in doc['project']['optional-dependencies']:  # pyright: ignore[reportOperatorIssue, reportIndexIssue]
				doc['project'][  # pyright: ignore[reportIndexIssue, reportUnknownMemberType, reportUnusedCallResult]
					'optional-dependencies'
				].append(  # pyright: ignore[reportAttributeAccessIssue]
					extra_name,
					tomlkit.array(),
				)

			# The 'extras' dependency group must be an array.
			if not isinstance(
				doc['project']['optional-dependencies'][extra_name],  # pyright: ignore[reportIndexIssue]
				tomlkit.items.Array,
			):
				msgs = [
					f"In `pyproject.toml`, `project.optional-dependencies.{extra_name}` exists, but isn't an array.",
					f'> **Value**: `{doc["project"]["optional-dependencies"][extra_name]}`',  # pyright: ignore[reportIndexIssue]
				]
				raise TypeError(*msgs)

			# All elements of that array must be strings.
			if not all(
				isinstance(el, str)
				for el in doc['project']['optional-dependencies'][extra_name]  # pyright: ignore[reportIndexIssue, reportGeneralTypeIssues, reportUnknownVariableType]
			):
				msgs = [
					f"In `pyproject.toml`, `project.optional-dependencies.{extra_name}` exists, but isn't an array.",
					f'> **Value**: `{doc["project"]["optional-dependencies"][extra_name]}`',  # pyright: ignore[reportIndexIssue]
				]
				raise ValueError(*msgs)

			# We must delete those retained strings that conflict with vendored_site_packages.
			## Why not error? If the user sets an incompatible version, they're wrong.
			## By considering it "managed", we don't have to bug the user for a rote fix.
			## This also naturally allows non-conflicting user deps to "float to the top".
			## Be good to the user, for they are benevolent.
			pydep_strs_to_delete: set[str] = {
				current_pydep_str
				for current_pydep_str in doc['project']['optional-dependencies'][  # pyright: ignore[reportIndexIssue, reportGeneralTypeIssues, reportUnknownVariableType]
					extra_name
				]
				if any(
					current_pydep_str.startswith(pkg_name)  # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
					for pkg_name in extra[1]
				)
			}
			for pydep_str_to_delete in pydep_strs_to_delete:
				_ = doc['project']['optional-dependencies'][extra_name].remove(  # pyright: ignore[reportIndexIssue, reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType]
					pydep_str_to_delete
				)

			# Finally, all vendored site-packages are dumped to the TOML
			## Why not error? If the user sets an incompatible version, they're wrong.
			for i, pydep_str in enumerate(vendored_site_packages):
				if i == 0:
					comment = TOML_MANAGED_COMMENTS[0]
				elif i == len(vendored_site_packages) - 1:
					comment = TOML_MANAGED_COMMENTS[1]
				else:
					comment = None

				doc['project']['optional-dependencies'][extra_name].add_line(  # pyright: ignore[reportIndexIssue, reportAttributeAccessIssue, reportUnknownMemberType]
					pydep_str,
					comment=comment,
					indent=' ' * 4,
				)

			doc['project']['optional-dependencies'][extra_name].multiline(True)  # pyright: ignore[reportIndexIssue, reportAttributeAccessIssue, reportUnknownMemberType]

		####################
		# - Stage 1: Handle Extra Conflicts in [tool.uv]
		####################
		# The extras are not supplementary - they are mutually exclusive.
		## We can tell 'uv' about this situation by setting tool.uv.conflicts correctly.
		if 'tool' not in doc and 'uv' not in doc['tool']:  # pyright: ignore[reportOperatorIssue]
			msgs = [
				'In `pyproject.toml`, `[tool.uv]` does not exists.',
				'> Please define the `[tool.uv]` table.',
			]
			raise ValueError(*msgs)

		# Make sure tool.uv.package is False.
		## As far as uv is concerned, extensions are virtual packages.
		if doc['tool']['uv'].get('package', True):  # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportIndexIssue]
			msgs = [
				'In `pyproject.toml`, `tool.uv.package` is either undefined or `true`.',
				'> `blext` projects must define `tool.uv.package = false`.',
				'>',
				'> **See**: <https://docs.astral.sh/uv/reference/settings/#package>',
			]
			raise ValueError(*msgs)

		# Create tool.uv.conflicts if it doesn't exist.
		if 'conflicts' not in doc['tool']['uv']:  # pyright: ignore[reportIndexIssue, reportOperatorIssue]
			doc['tool']['uv']['conflicts'] = tomlkit.array()  # pyright: ignore[reportIndexIssue]

		# Ensure tool.uv.conflicts is an array.
		if not isinstance(doc['tool']['uv']['conflicts'], tomlkit.items.Array):  # pyright: ignore[reportIndexIssue]
			msgs = [
				"In `pyproject.toml`, `tool.uv.conflicts` exists, but isn't an array.",
				'> Please define `tool.uv.conflicts` as an array.',
			]
			raise ValueError(*msgs)

		# Scan conflicts array for those with only { extra = <extra in all_extras> }
		## These should be removed, as they are redundant together with what we're adding.
		all_extra_names = {extra[0] for extra in all_extras}
		conflict_idxs_to_remove = {
			i
			for i, conflict_spec_arr in enumerate(doc['tool']['uv']['conflicts'])  # pyright: ignore[reportUnknownVariableType, reportIndexIssue, reportArgumentType]
			if all(
				# There exactly one key specifying the conflicting element.
				len(conflict_spec_table) == 1  # pyright: ignore[reportUnknownArgumentType]
				# That one key is 'extra'.
				and conflict_spec_table.get('extra') is not None  # pyright: ignore[reportUnknownMemberType]
				# The output of that key is one of the extra names.
				and conflict_spec_table['extra'] in all_extra_names
				for conflict_spec_table in conflict_spec_arr  # pyright: ignore[reportUnknownVariableType]
			)
		}
		for idx_to_remove in sorted(conflict_idxs_to_remove, reverse=True):
			_ = doc['tool']['uv']['conflicts'].pop(idx_to_remove)  # pyright: ignore[reportIndexIssue, reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType]

		# Add the conflicts entry line by line.
		## These should be removed, as they are redundant together with what we're adding.
		if len(all_extras) > 1:
			conflict_spec_arr_to_add = tomlkit.array()
			for i, extra in enumerate(sorted(all_extras, key=lambda el: el[0])):
				extra_name = extra[0]

				extra_conflict_table = tomlkit.inline_table()
				extra_conflict_table['extra'] = extra_name

				if i == 0:
					comment = TOML_MANAGED_COMMENTS[0]
				elif i == len(all_extras) - 1:
					comment = TOML_MANAGED_COMMENTS[1]
				else:
					comment = None

				conflict_spec_arr_to_add.add_line(
					extra_conflict_table,
					indent=' ' * 8,
					comment=comment,  # pyright: ignore[reportArgumentType]
				)
			_ = conflict_spec_arr_to_add.multiline(True)
			conflict_spec_arr_to_add._trivia.indent = ' ' * 4  # pyright: ignore[reportPrivateUsage] # noqa: SLF001

			doc['tool']['uv']['conflicts'].add_line(  # pyright: ignore[reportAttributeAccessIssue, reportIndexIssue, reportUnknownMemberType]
				conflict_spec_arr_to_add,
				indent=' ' * 4,
			)
			doc['tool']['uv']['conflicts'].multiline(True)  # pyright: ignore[reportAttributeAccessIssue, reportIndexIssue, reportUnknownMemberType]

		if original_doc != tomlkit.dumps(doc):  # pyright: ignore[reportUnknownMemberType]
			with blext_location.path_spec.open('w') as f:
				_ = f.write(tomlkit.dumps(doc))  # pyright: ignore[reportUnknownMemberType]

			altered_spec = True

	elif blext_location.path_spec.name.endswith('.py'):
		# Check for single smooshed version
		if len(all_extras) != 1:
			msgs = [
				'Script extensions may not support more than one "smooshable" version of Blender.'
			]
			raise ValueError(*msgs)

		vendored_site_packages = next(iter(extra[1] for extra in all_extras))

		# Load the inline script metadata
		with blext_location.path_spec.open('r') as f:
			py_source_code = f.read()
			doc_str = parse_inline_script_metadata_str(
				py_source_code=py_source_code
			)

		# Ensure there's inline script metadata actually available
		if doc_str is None:
			msg = f'No inline script metadata found in script extension: {blext_location.path_spec}'
			raise ValueError(msg)

		# Load the document.
		doc = tomlkit.parse(doc_str)

		####################
		# - Stage 0: Handle Vendored site-package in 'dependencies'
		####################
		if 'dependencies' not in doc:
			msg = f'No `dependencies` field found in inline script metadata: {blext_location.path_spec}'
			raise ValueError(msg)
		pydep_strs_to_delete_from_script: set[str] = {
			current_pydep_str
			for current_pydep_str in doc['dependencies']  # pyright: ignore[reportGeneralTypeIssues, reportUnknownVariableType]
			if any(
				current_pydep_str.startswith(pkg_name)  # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
				for pkg_name in vendored_site_packages
			)
		}
		for pydep_str_to_delete in pydep_strs_to_delete_from_script:
			_ = doc['dependencies'].remove(  # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType]
				pydep_str_to_delete
			)

		# All vendored site-packages are dumped to the TOML
		## Why not error? If the user sets an incompatible version, they're wrong.
		for i, pydep_str in enumerate(
			[
				f'{pkg_name}=={pkg_version}'
				for pkg_name, pkg_version in vendored_site_packages.items()
			]
		):
			if i == 0:
				comment = TOML_MANAGED_COMMENTS[0]
			elif i == len(vendored_site_packages) - 1:
				comment = TOML_MANAGED_COMMENTS[1]
			else:
				comment = None

			doc['dependencies'].add_line(  # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
				pydep_str,
				comment=comment,
				indent=' ' * 4,
			)

		doc['dependencies'].multiline(True)  # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
		if doc_str != tomlkit.dumps(doc):  # pyright: ignore[reportUnknownMemberType]
			new_py_source_code = replace_inline_script_metadata_str(
				py_source_code=py_source_code,
				metadata_str=tomlkit.dumps(doc),  # pyright: ignore[reportUnknownMemberType]
			)
			with blext_location.path_spec.open('w') as f:
				_ = f.write(new_py_source_code)

			altered_spec = True

	return altered_spec

GitLocationUI pydantic-model

Bases: BaseModel

Information about an extension project in a git repository.

ATTRIBUTE DESCRIPTION
url

URL of a git repository.

TYPE: str | None

rev

Reference to a particular commit.

TYPE: str | None

tag

Reference to a particular tag.

TYPE: str | None

branch

Reference to the head of a particular branch.

TYPE: str | None

entrypoint

Path to an extension specification file, relative to the repo root.

TYPE: Path | None

Fields:

  • url (str | None)
  • rev (str | None)
  • tag (str | None)
  • branch (str | None)
  • entrypoint (Path | None)

blext.uityp.global_config

Implements global configuration of blext.

GlobalConfig pydantic-model

Bases: BaseModel

Static configuration impacting the runtime behavior of blext.

Notes

path_global_cache can only be overridden in the user's global configuration file.

ATTRIBUTE DESCRIPTION
path_global_cache

Path to global cache directory used by blext.

TYPE: Path

local_bl_platform

The current system's BLPlatform.

TYPE: BLPlatform

path_default_blender_exe

Path to the default blender executable.

TYPE: Path

path_uv_exe

Path to the uv executable to use.

TYPE: Path

Fields:

  • path_global_cache (Path)
  • local_bl_platform (BLPlatform)
  • path_default_blender_exe (Path)
  • path_uv_exe (Path)

Validators:

local_default_bl_version cached property

local_default_bl_version: BLVersion

Blender version derived from running self.path_default_blender_exe with --version.

path_global_download_cache cached property

path_global_download_cache: Path

Path containing root folders for downloaded extensions, identified uniquely.

Notes

Each subfolder should be named by the hash of the URL that was downloaded.

path_global_project_cache cached property

path_global_project_cache: Path

Path containing root folders for script extensions.

Notes

Each subfolder should be named by the hash of the path to the script it serves.

export_config

export_config(fmt: Literal['json', 'toml']) -> str

Global configuration of blext as a string.

PARAMETER DESCRIPTION
fmt

String format to export global configuration to.

TYPE: Literal['json', 'toml']

RETURNS DESCRIPTION
str

Global configuration

Source code in blext/uityp/global_config.py
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
def export_config(self, fmt: typ.Literal['json', 'toml']) -> str:
	"""Global configuration of `blext` as a string.

	Parameters:
		fmt: String format to export global configuration to.

	Returns:
		Global configuration
	"""
	# Parse Model to JSON
	## - JSON is used like a Rosetta Stone, since it is best supported by pydantic.
	json_str = self.model_dump_json(
		include={
			'path_global_cache',
			'path_default_blender_exe',
			'path_uv_exe',
			'local_bl_platform',
		},
		by_alias=True,
	)

	# Return String as Format
	json_dict: dict[str, typ.Any] = json.loads(json_str)
	cfg_dict = {'cfg': json_dict}
	if fmt == 'json':
		return json.dumps(cfg_dict)
	if fmt == 'toml':
		return tomli_w.dumps(cfg_dict)

	msg = f'Cannot export init settings to the given unknown format: {fmt}'  # pyright: ignore[reportUnreachable]
	raise ValueError(msg)

from_config classmethod

from_config(
	path_config: Path,
	*,
	environ: dict[str, str] | None = None,
) -> Self

Load from config file and given environment variables.

Source code in blext/uityp/global_config.py
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
@classmethod
def from_config(
	cls, path_config: Path, *, environ: dict[str, str] | None = None
) -> typ.Self:
	"""Load from config file and given environment variables."""
	# Load Environment Dictionary
	environ = {} if environ is None else environ

	# Load Config File
	try:
		with path_config.open('rb') as f:
			config = tomllib.load(f)
	except FileNotFoundError:
		config = {}

	# Extract Attribute Values
	attr_dict = {}
	for attr in [
		'path_global_cache',
		'local_bl_platform',
		'path_default_blender_exe',
		'path_uv_exe',
	]:
		attr_env_var = 'BLEXT_' + attr.upper()
		if attr_env_var in environ:
			attr_dict[attr] = environ[attr_env_var]
		elif attr in config:
			attr_dict[attr] = config[attr]

	# pydantic Handles the Rest
	return cls(**attr_dict)  # pyright: ignore[reportUnknownArgumentType]

mkdir_path_global_cache pydantic-validator

mkdir_path_global_cache(value: Path) -> Path

Ensure the global cache path exists.

Source code in blext/uityp/global_config.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
@pyd.field_validator('path_global_cache', mode='after')
@classmethod
def mkdir_path_global_cache(cls, value: Path) -> Path:
	"""Ensure the global cache path exists."""
	# Doesn't Exist: Create Folder
	if not value.exists():
		value.mkdir(parents=True, exist_ok=True)

	# Exists, Not Folder: Error
	elif not value.is_dir():
		msg = f"The global cache path {value} is not a folder, yet it exists. Please remove this path, or adjust blext's global cache path."
		raise ValueError(msg)

	# Exists, Is Folder: Check Read/Write Permissions
	## - I know, I know, "forgiveness vs permission" and all that.
	## - I raise you "explicit is better than implicit".
	## - Why are you reading this? Because you care. Let's get a coffee or something.
	if os.access(value, os.R_OK):
		if os.access(value, os.W_OK):
			return value
		msg = f'The global cache path {value} exists, but is not writable. Please grant `blext` permission to write to this folder.'
		raise ValueError(msg)
	msg = f'The global cache path {value} exists, but is not readable. Please grant `blext` permission to read this folder.'
	raise ValueError(msg)