Skip to content

Commit 3bc82aa

Browse files
committed
use Path from pathlib everywhere. drop path dep
1 parent dadf151 commit 3bc82aa

22 files changed

+320
-276
lines changed

cadquery/assembly.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from typish import instance_of
1616
from uuid import uuid1 as uuid
1717
from warnings import warn
18+
from pathlib import Path
1819

1920
from .cq import Workplane
2021
from .occ_impl.shapes import Shape, Compound, isSubshape
@@ -47,6 +48,7 @@
4748

4849
PATH_DELIM = "/"
4950

51+
5052
# entity selector grammar definition
5153
def _define_grammar():
5254

@@ -507,7 +509,7 @@ def solve(self, verbosity: int = 0) -> Self:
507509
@deprecate()
508510
def save(
509511
self,
510-
path: str,
512+
path: Path,
511513
exportType: Optional[ExportLiterals] = None,
512514
mode: STEPExportModeLiterals = "default",
513515
tolerance: float = 0.1,
@@ -534,7 +536,7 @@ def save(
534536

535537
def export(
536538
self,
537-
path: str,
539+
path: Path,
538540
exportType: Optional[ExportLiterals] = None,
539541
mode: STEPExportModeLiterals = "default",
540542
tolerance: float = 0.1,
@@ -560,7 +562,7 @@ def export(
560562
raise ValueError(f"Unknown assembly export mode {mode} for STEP")
561563

562564
if exportType is None:
563-
t = path.split(".")[-1].upper()
565+
t = path.suffix.upper().lstrip(".")
564566
if t in ("STEP", "XML", "XBF", "VRML", "VTKJS", "GLTF", "GLB", "STL"):
565567
exportType = cast(ExportLiterals, t)
566568
else:
@@ -591,7 +593,7 @@ def export(
591593
return self
592594

593595
@classmethod
594-
def importStep(cls, path: str) -> Self:
596+
def importStep(cls, path: Path) -> Self:
595597
"""
596598
Reads an assembly from a STEP file.
597599
@@ -602,13 +604,13 @@ def importStep(cls, path: str) -> Self:
602604
return cls.load(path, importType="STEP")
603605

604606
@classmethod
605-
def load(cls, path: str, importType: Optional[ImportLiterals] = None,) -> Self:
607+
def load(cls, path: Path, importType: Optional[ImportLiterals] = None,) -> Self:
606608
"""
607609
Load step, xbf or xml.
608610
"""
609611

610612
if importType is None:
611-
t = path.split(".")[-1].upper()
613+
t = path.suffix.upper().lstrip(".")
612614
if t in ("STEP", "XML", "XBF"):
613615
importType = cast(ImportLiterals, t)
614616
else:
@@ -680,8 +682,12 @@ def __iter__(
680682
color = self.color if self.color else color
681683

682684
if self.obj:
683-
yield self.obj if isinstance(self.obj, Shape) else Compound.makeCompound(
684-
s for s in self.obj.vals() if isinstance(s, Shape)
685+
yield (
686+
self.obj
687+
if isinstance(self.obj, Shape)
688+
else Compound.makeCompound(
689+
s for s in self.obj.vals() if isinstance(s, Shape)
690+
)
685691
), name, loc, color
686692

687693
for ch in self.children:

cadquery/cq.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
)
2222
from typing_extensions import Literal
2323
from inspect import Parameter, Signature
24+
from pathlib import Path
2425

2526

2627
from .occ_impl.geom import Vector, Plane, Location
@@ -4582,7 +4583,7 @@ def invoke(
45824583

45834584
def export(
45844585
self: T,
4585-
fname: str,
4586+
fname: Path,
45864587
tolerance: float = 0.1,
45874588
angularTolerance: float = 0.1,
45884589
opt: Optional[Dict[str, Any]] = None,

cadquery/occ_impl/exporters/__init__.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import tempfile
22
import os
33
import io as StringIO
4+
from pathlib import Path
45

56
from typing import IO, Optional, Union, cast, Dict, Any, Iterable
67
from typing_extensions import Literal
@@ -39,13 +40,12 @@ class ExportTypes:
3940

4041
def export(
4142
w: Union[Shape, Iterable[Shape]],
42-
fname: str,
43+
fname: Path,
4344
exportType: Optional[ExportLiterals] = None,
4445
tolerance: float = 0.1,
4546
angularTolerance: float = 0.1,
4647
opt: Optional[Dict[str, Any]] = None,
4748
):
48-
4949
"""
5050
Export Workplane or Shape to file. Multiple entities are converted to compound.
5151
@@ -69,7 +69,7 @@ def export(
6969
shape = compound(*w)
7070

7171
if exportType is None:
72-
t = fname.split(".")[-1].upper()
72+
t = fname.suffix.upper().lstrip(".")
7373
if t in ExportTypes.__dict__.values():
7474
exportType = cast(ExportLiterals, t)
7575
else:
@@ -121,7 +121,7 @@ def export(
121121

122122
elif exportType == ExportTypes.VRML:
123123
shape.mesh(tolerance, angularTolerance)
124-
VrmlAPI.Write_s(shape.wrapped, fname)
124+
VrmlAPI.Write_s(shape.wrapped, str(fname))
125125

126126
elif exportType == ExportTypes.VTP:
127127
exportVTP(shape, fname, tolerance, angularTolerance)
@@ -205,9 +205,9 @@ def tessellate(shape, angularTolerance):
205205
os.close(h)
206206

207207
if exportType == ExportTypes.STEP:
208-
shape.exportStep(outFileName)
208+
shape.exportStep(Path(outFileName))
209209
elif exportType == ExportTypes.STL:
210-
shape.exportStl(outFileName, tolerance, angularTolerance, True)
210+
shape.exportStl(Path(outFileName), tolerance, angularTolerance, True)
211211
else:
212212
raise ValueError("No idea how i got here")
213213

cadquery/occ_impl/exporters/assembly.py

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import os.path
21
import uuid
32

43
from tempfile import TemporaryDirectory
54
from shutil import make_archive
65
from typing import Optional
76
from typing_extensions import Literal
7+
from pathlib import Path
88

99
from vtkmodules.vtkIOExport import vtkJSONSceneExporter, vtkVRMLExporter
1010
from vtkmodules.vtkRenderingCore import vtkRenderWindow
@@ -50,7 +50,7 @@ class ExportModes:
5050

5151
def exportAssembly(
5252
assy: AssemblyProtocol,
53-
path: str,
53+
path: Path,
5454
mode: STEPExportModeLiterals = "default",
5555
**kwargs,
5656
) -> bool:
@@ -102,14 +102,14 @@ def exportAssembly(
102102
Interface_Static.SetIVal_s("write.stepcaf.subshapes.name", 1)
103103
writer.Transfer(doc, STEPControl_StepModelType.STEPControl_AsIs)
104104

105-
status = writer.Write(path)
105+
status = writer.Write(str(path))
106106

107107
return status == IFSelect_ReturnStatus.IFSelect_RetDone
108108

109109

110110
def exportStepMeta(
111111
assy: AssemblyProtocol,
112-
path: str,
112+
path: Path,
113113
write_pcurves: bool = True,
114114
precision_mode: int = 0,
115115
) -> bool:
@@ -161,10 +161,12 @@ def _process_child(child: AssemblyProtocol, assy_label: TDF_Label):
161161
# Collect all of the shapes in the child object
162162
if child.obj:
163163
child_items = (
164-
child.obj
165-
if isinstance(child.obj, Shape)
166-
else Compound.makeCompound(
167-
s for s in child.obj.vals() if isinstance(s, Shape)
164+
(
165+
child.obj
166+
if isinstance(child.obj, Shape)
167+
else Compound.makeCompound(
168+
s for s in child.obj.vals() if isinstance(s, Shape)
169+
)
168170
),
169171
child.name,
170172
child.loc,
@@ -268,19 +270,20 @@ def _process_assembly(
268270
Interface_Static.SetIVal_s("write.precision.mode", precision_mode)
269271
writer.Transfer(doc, STEPControl_StepModelType.STEPControl_AsIs)
270272

271-
status = writer.Write(path)
273+
status = writer.Write(str(path))
272274

273275
return status == IFSelect_ReturnStatus.IFSelect_RetDone
274276

275277

276-
def exportCAF(assy: AssemblyProtocol, path: str, binary: bool = False) -> bool:
278+
def exportCAF(assy: AssemblyProtocol, path: Path, binary: bool = False) -> bool:
277279
"""
278280
Export an assembly to an XCAF xml or xbf file (internal OCCT formats).
279281
"""
280282

281-
folder, fname = os.path.split(path)
282-
name, ext = os.path.splitext(fname)
283-
ext = ext[1:] if ext[0] == "." else ext
283+
folder = path.parent
284+
fname = path.name
285+
name = path.stem
286+
ext = path.suffix.lstrip(".")
284287

285288
_, doc = toCAF(assy, binary=binary)
286289
app = XCAFApp_Application.GetApplication_s()
@@ -308,10 +311,10 @@ def exportCAF(assy: AssemblyProtocol, path: str, binary: bool = False) -> bool:
308311
format_name, format_desc, TCollection_AsciiString(ext), ret, store,
309312
)
310313

311-
doc.SetRequestedFolder(TCollection_ExtendedString(folder))
314+
doc.SetRequestedFolder(TCollection_ExtendedString(str(folder)))
312315
doc.SetRequestedName(TCollection_ExtendedString(name))
313316

314-
status = app.SaveAs(doc, TCollection_ExtendedString(path))
317+
status = app.SaveAs(doc, TCollection_ExtendedString(str(path)))
315318

316319
app.Close(doc)
317320

@@ -335,7 +338,7 @@ def _vtkRenderWindow(
335338
return renderWindow
336339

337340

338-
def exportVTKJS(assy: AssemblyProtocol, path: str):
341+
def exportVTKJS(assy: AssemblyProtocol, path: Path):
339342
"""
340343
Export an assembly to a zipped vtkjs. NB: .zip extensions is added to path.
341344
"""
@@ -348,12 +351,12 @@ def exportVTKJS(assy: AssemblyProtocol, path: str):
348351
exporter.SetFileName(tmpdir)
349352
exporter.SetRenderWindow(renderWindow)
350353
exporter.Write()
351-
make_archive(path, "zip", tmpdir)
354+
make_archive(str(path), "zip", tmpdir)
352355

353356

354357
def exportVRML(
355358
assy: AssemblyProtocol,
356-
path: str,
359+
path: Path,
357360
tolerance: float = 1e-3,
358361
angularTolerance: float = 0.1,
359362
):
@@ -362,14 +365,14 @@ def exportVRML(
362365
"""
363366

364367
exporter = vtkVRMLExporter()
365-
exporter.SetFileName(path)
368+
exporter.SetFileName(str(path))
366369
exporter.SetRenderWindow(_vtkRenderWindow(assy, tolerance, angularTolerance))
367370
exporter.Write()
368371

369372

370373
def exportGLTF(
371374
assy: AssemblyProtocol,
372-
path: str,
375+
path: Path,
373376
binary: Optional[bool] = None,
374377
tolerance: float = 1e-3,
375378
angularTolerance: float = 0.1,
@@ -382,10 +385,10 @@ def exportGLTF(
382385
if binary is None:
383386
# Handle the binary option for GLTF export based on file extension
384387
binary = True
385-
path_parts = path.split(".")
388+
sfx = path.suffix.lstrip(".").lower()
386389

387390
# Binary will be the default if the user specified a non-standard file extension
388-
if len(path_parts) > 0 and path_parts[-1] == "gltf":
391+
if sfx == "gltf":
389392
binary = False
390393

391394
# map from CadQuery's right-handed +Z up coordinate system to glTF's right-handed +Y up coordinate system
@@ -395,7 +398,7 @@ def exportGLTF(
395398

396399
_, doc = toCAF(assy, True, True, tolerance, angularTolerance)
397400

398-
writer = RWGltf_CafWriter(TCollection_AsciiString(path), binary)
401+
writer = RWGltf_CafWriter(TCollection_AsciiString(str(path)), binary)
399402
result = writer.Perform(
400403
doc, TColStd_IndexedDataMapOfStringString(), Message_ProgressRange()
401404
)

cadquery/occ_impl/exporters/dxf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from OCP.gp import gp_Dir
2121
from OCP.GC import GC_MakeArcOfEllipse
2222
from typing_extensions import Self
23+
from pathlib import Path
2324

2425
from ...units import RAD2DEG
2526
from ..shapes import Face, Edge, Shape, Compound, compound
@@ -366,7 +367,7 @@ def _dxf_spline(cls, edge: Edge, plane: Plane) -> DxfEntityAttributes:
366367

367368
def exportDXF(
368369
w: Union[WorkplaneLike, Shape, Iterable[Shape]],
369-
fname: str,
370+
fname: Path,
370371
approx: Optional[ApproxOptions] = None,
371372
tolerance: float = 1e-3,
372373
*,

cadquery/occ_impl/exporters/vtk.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from vtkmodules.vtkIOXML import vtkXMLPolyDataWriter
22
from ..shapes import Shape
3+
from pathlib import Path
34

45

56
def exportVTP(
6-
shape: Shape, fname: str, tolerance: float = 0.1, angularTolerance: float = 0.1
7+
shape: Shape, fname: Path, tolerance: float = 0.1, angularTolerance: float = 0.1
78
):
89

910
writer = vtkXMLPolyDataWriter()
10-
writer.SetFileName(fname)
11+
writer.SetFileName(str(fname))
1112
writer.SetInputData(shape.toVtkPolyData(tolerance, angularTolerance))
1213
writer.Write()
1314

0 commit comments

Comments
 (0)