Skip to content

Commit 7f8470c

Browse files
committed
refactor(api): Add type hints and improve documentation for clarity
Signed-off-by: longhao <[email protected]>
1 parent 3b608f4 commit 7f8470c

File tree

127 files changed

+8316
-7998
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

127 files changed

+8316
-7998
lines changed

.github/workflows/code-check.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ jobs:
2929
runs-on: windows-latest
3030
strategy:
3131
matrix:
32-
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]
32+
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
3333
steps:
3434
- uses: actions/checkout@v4
3535
with:

docs/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Documentation generation module."""
2+
3+
from __future__ import annotations

docs/gen_api_nav.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
"""Plugin for generate API docs."""
22

33
# Import built-in modules
4+
from __future__ import annotations
5+
46
from pathlib import Path
57

68
# Import third-party modules
79
import mkdocs_gen_files
810

911

10-
def main():
12+
def main() -> None:
1113
nav = mkdocs_gen_files.Nav()
1214
root = Path(__file__).parent.parent
1315
api_root = root.joinpath("photoshop")
@@ -16,11 +18,7 @@ def main():
1618
doc_path = path.relative_to(root).with_suffix(".md")
1719
full_doc_path = Path("reference", doc_path)
1820
parts = list(module_path.parts)
19-
if parts[-1] == "__init__":
20-
continue
21-
elif parts[-1] == "__main__":
22-
continue
23-
elif parts[-1] == "__version__":
21+
if parts[-1] == "__init__" or parts[-1] == "__main__" or parts[-1] == "__version__":
2422
continue
2523
nav_parts = list(parts)
2624
if nav_parts[-1].startswith("_"):
@@ -29,7 +27,7 @@ def main():
2927
full_doc_path = full_doc_path.as_posix().replace("\\", "/")
3028
with mkdocs_gen_files.open(full_doc_path, "w") as fd:
3129
ident = ".".join(parts)
32-
print(f"::: " + ident, file=fd)
30+
print("::: " + ident, file=fd)
3331

3432
mkdocs_gen_files.set_edit_path(full_doc_path, path.as_posix().replace("\\", "/"))
3533

docs/gen_examples.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
"""Plugin for generate API docs."""
22

33
# Import built-in modules
4+
from __future__ import annotations
5+
46
import os
57
from pathlib import Path
68

7-
# Import third-party modules
8-
from jinja2 import Template
99
import mkdocs_gen_files
1010
import stringcase
1111

12+
# Import third-party modules
13+
from jinja2 import Template
1214

1315
template = Template(
1416
r"""
@@ -22,44 +24,43 @@
2224
```
2325
{% endfor %}
2426
25-
"""
27+
""",
2628
)
2729

2830

29-
class Examples(object):
30-
def __init__(self, root: Path):
31+
class Examples:
32+
def __init__(self, root: Path) -> None:
3133
self._root = root
3234

33-
def get_examples(self):
34-
files = [file_ for file_ in self._root.glob("*.py") if "_psd_files.py" not in file_.as_posix()]
35-
return files
35+
def get_examples(self) -> list[Path]:
36+
return [file_ for file_ in self._root.glob("*.py") if "_psd_files.py" not in file_.as_posix()]
3637

3738
@staticmethod
38-
def convert_relative_path(file):
39+
def convert_relative_path(file: str) -> str:
3940
path = file.split("examples")[1]
4041
return "../examples{}".format(path.replace("\\", "/"))
4142

4243
@staticmethod
43-
def get_name(file):
44-
name = os.path.basename(file).split(".py")[0]
44+
def get_name(file: str) -> str:
45+
name = Path(file).name.split(".py")[0]
4546
return stringcase.titlecase(name)
4647

4748
@staticmethod
48-
def get_line(name):
49+
def get_line(name: str) -> str:
4950
return "-" * len(name)
5051

5152
@staticmethod
52-
def get_content(file_):
53-
with open(file_, "r") as f:
53+
def get_content(file_: str) -> str:
54+
with Path(file_).open() as f:
5455
return "".join(f.readlines())
5556

5657

57-
def main():
58+
def main() -> None:
5859
root = Path(__file__).parent.parent
5960
with mkdocs_gen_files.open("examples.md", "w") as nav_file:
6061
examples_data = Examples(root.joinpath("examples"))
6162
nav_file.write(template.render(Examples=examples_data))
6263

6364

64-
if __name__ == "<run_path>":
65+
if __name__ == "__main__":
6566
main()

examples/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Example scripts for photoshop-python-api."""
2+
3+
from __future__ import annotations

examples/_psd_files.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# Import built-in modules
2+
from __future__ import annotations
3+
from pathlib import Path
24
import os
35

46

5-
def get_psd_files():
7+
def get_psd_files() -> dict[str, str]:
68
files = {}
7-
this_root = os.path.dirname(__file__)
8-
file_root = os.path.join(this_root, "files")
9+
this_root = Path(__file__).parent
10+
file_root = this_root / "files"
911
for file_name in os.listdir(file_root):
10-
files[file_name] = os.path.join(file_root, file_name)
12+
files[file_name] = str(file_root / file_name)
1113
return files

examples/active_layer.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1-
# Set the active layer to the last art layer of the active document, or the
2-
# first if the last is already active.
3-
4-
# Import local modules
5-
from photoshop import Session
6-
7-
8-
with Session() as ps:
9-
if len(ps.app.documents) < 1:
10-
docRef = ps.app.documents.add()
11-
else:
12-
docRef = ps.app.activeDocument
13-
14-
if len(docRef.layers) < 2:
15-
docRef.artLayers.add()
16-
17-
ps.echo(docRef.activeLayer.name)
18-
new_layer = docRef.artLayers.add()
19-
ps.echo(new_layer.name)
20-
new_layer.name = "test"
1+
# Set the active layer to the last art layer of the active document, or the
2+
# first if the last is already active.
3+
4+
# Import local modules
5+
from __future__ import annotations
6+
7+
from photoshop import Session
8+
9+
with Session() as ps:
10+
if len(ps.app.documents) < 1:
11+
docRef = ps.app.documents.add()
12+
else:
13+
docRef = ps.app.activeDocument
14+
15+
if len(docRef.layers) < 2:
16+
docRef.artLayers.add()
17+
18+
ps.echo(docRef.activeLayer.name)
19+
new_layer = docRef.artLayers.add()
20+
ps.echo(new_layer.name)
21+
new_layer.name = "test"

examples/add_metadata.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
"""Add metadata to current active document."""
22

33
# Import built-in modules
4+
from __future__ import annotations
5+
46
import os
57

68
# Import local modules
79
from photoshop import Session
810

9-
1011
with Session(action="new_document") as ps:
1112
doc = ps.active_document
1213
doc.info.author = os.getenv("USERNAME")
1314
doc.info.provinceState = "Beijing"
1415
doc.info.title = "My Demo"
15-
print("Print all metadata of current active document.")
16+
ps.echo("Metadata of current active document:")
1617
ps.echo(doc.info)

examples/add_slate.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,35 @@
88
"""
99

1010
# Import built-in modules
11-
from datetime import datetime
11+
from __future__ import annotations
12+
1213
import os
14+
from datetime import datetime
1315
from tempfile import mkdtemp
16+
from pathlib import Path
17+
from datetime import timezone
1418

1519
# Import third-party modules
1620
import examples._psd_files as psd # Import from examples.
1721

1822
# Import local modules
1923
from photoshop import Session
2024

21-
2225
PSD_FILE = psd.get_psd_files()
2326
slate_template = PSD_FILE["slate_template.psd"]
2427
with Session(slate_template, action="open", auto_close=True) as ps:
2528
layer_set = ps.active_document.layerSets.getByName("template")
2629

2730
data = {
2831
"project name": "test_project",
29-
"datetime": datetime.today().strftime("%Y-%m-%d"),
32+
"datetime": datetime.now(tz=timezone.utc).strftime("%Y-%m-%d"),
3033
}
3134
for layer in layer_set.layers:
3235
if layer.kind == ps.LayerKind.TextLayer:
3336
layer.textItem.contents = data[layer.textItem.contents.strip()]
3437

35-
jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "slate.jpg")
36-
ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions())
37-
print(f"Save jpg to {jpg_file}")
38-
os.startfile(jpg_file)
38+
jpg_file = Path(mkdtemp("photoshop-python-api")) / "slate.jpg"
39+
ps.active_document.saveAs(str(jpg_file), ps.JPEGSaveOptions())
40+
ps.echo(f"Save jpg to {jpg_file}")
41+
# Note: os.startfile is Windows-specific, consider using a cross-platform solution
42+
os.startfile(str(jpg_file))

examples/add_start_application_event.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,18 @@
88
"""
99

1010
# Import built-in modules
11+
from __future__ import annotations
12+
1113
import os
1214
from tempfile import mkdtemp
15+
from pathlib import Path
1316

1417
# Import local modules
1518
from photoshop import Session
1619

17-
1820
with Session() as ps:
19-
root = mkdtemp()
20-
jsx_file = os.path.join(root, "event.jsx")
21-
with open(jsx_file, "w") as f:
22-
f.write('alert("Start Application event.")')
23-
ps.app.notifiers.add(ps.EventID.Notify, jsx_file)
24-
print("Add event done.")
21+
root = Path(mkdtemp())
22+
jsx_file = root / "event.jsx"
23+
jsx_file.write_text('alert("Start Application event.")')
24+
ps.app.notifiers.add(ps.EventID.Notify, str(jsx_file))
25+
ps.echo("Add event done.")

0 commit comments

Comments
 (0)