Skip to content

Commit af272ae

Browse files
committed
feat: set the __file__ variable for scripts loaded from files
1 parent a9e4b1a commit af272ae

3 files changed

Lines changed: 39 additions & 1 deletion

File tree

src/cq_cli/main.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,11 @@ def get_script_from_infile(infile, outfile, errfile):
123123
script_str = infile
124124
else:
125125
with open(infile, "r") as file:
126-
script_str = file.read()
126+
# prepend an assignment for the __file__ variable so the model
127+
# script knows its path and can potentially load resources relative
128+
# to that path.
129+
script_str = f"__file__ = '{os.path.abspath(infile)}'\n"
130+
script_str += file.read()
127131

128132
return script_str
129133

tests/test_cli.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,3 +544,26 @@ def test_multiple_outfiles():
544544
]
545545
out, err, exitcode = helpers.cli_call(command)
546546
assert exitcode == 0
547+
548+
def test_file_variable_is_set():
549+
"""
550+
Tests that cq-cli sets the __file__ variable for the model script.
551+
"""
552+
test_file = helpers.get_test_file_location("file_var.py")
553+
554+
temp_dir = tempfile.gettempdir()
555+
out_path = os.path.join(temp_dir, "temp_test_file_variable.stl")
556+
557+
command = [
558+
"python",
559+
"src/cq_cli/main.py",
560+
"--codec",
561+
"stl",
562+
"--infile",
563+
test_file,
564+
"--outfile",
565+
out_path,
566+
]
567+
out, err, exitcode = helpers.cli_call(command)
568+
assert exitcode == 0
569+
assert("__file__=" in out.decode())

tests/testdata/file_var.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import cadquery as cq
2+
3+
# print info about the __file__ variable to stdout so the test can check it
4+
if '__file__' in locals():
5+
print(f"__file__={__file__}")
6+
else:
7+
print("__FILE__ not set")
8+
9+
# render a simple shape so the cq-cli invocation succeeds
10+
b = cq.Workplane("XY").rect(10, 10).extrude(10)
11+
show_object(b)

0 commit comments

Comments
 (0)