Skip to content

Commit 735c3a2

Browse files
authored
feat: accept pathlib in the API (microsoft#110)
1 parent f81221c commit 735c3a2

20 files changed

+117
-94
lines changed

build_driver.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
import re
1818
import shutil
1919
import subprocess
20-
from pathlib import Path
2120

22-
_dirname = Path(os.path.dirname(os.path.abspath(__file__)))
21+
from playwright.path_utils import get_file_dirname
22+
23+
_dirname = get_file_dirname()
2324

2425
driver_path = _dirname / "driver"
2526
package_path = _dirname / "playwright"

build_package.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,20 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import os
1615
import shutil
1716
import subprocess
1817

19-
folder = os.path.dirname(os.path.abspath(__file__))
20-
if os.path.exists(os.path.join(folder, "build")):
21-
shutil.rmtree(os.path.join(folder, "build"))
22-
if os.path.exists(os.path.join(folder, "dist")):
23-
shutil.rmtree(os.path.join(folder, "dist"))
24-
if os.path.exists(os.path.join(folder, "playwright.egg-info")):
25-
shutil.rmtree(os.path.join(folder, "playwright.egg-info"))
18+
from playwright.path_utils import get_file_dirname
19+
20+
_dirname = get_file_dirname()
21+
_build_dir = _dirname / "build"
22+
if _build_dir.exists():
23+
shutil.rmtree(_build_dir)
24+
_dist_dir = _dirname / "dist"
25+
if _dist_dir.exists():
26+
shutil.rmtree(_dist_dir)
27+
_egg_dir = _dirname / "playwright.egg-info"
28+
if _egg_dir.exists():
29+
shutil.rmtree(_egg_dir)
2630

2731
subprocess.run("python setup.py sdist bdist_wheel", shell=True)

playwright/async_api.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515

16+
import pathlib
1617
import sys
1718
import typing
1819

@@ -870,7 +871,12 @@ async def selectText(self, timeout: int = None) -> NoneType:
870871
async def setInputFiles(
871872
self,
872873
files: typing.Union[
873-
str, FilePayload, typing.List[str], typing.List[FilePayload]
874+
str,
875+
pathlib.Path,
876+
FilePayload,
877+
typing.List[str],
878+
typing.List[pathlib.Path],
879+
typing.List[FilePayload],
874880
],
875881
timeout: int = None,
876882
noWaitAfter: bool = None,
@@ -1877,7 +1883,12 @@ async def setInputFiles(
18771883
self,
18781884
selector: str,
18791885
files: typing.Union[
1880-
str, FilePayload, typing.List[str], typing.List[FilePayload]
1886+
str,
1887+
pathlib.Path,
1888+
FilePayload,
1889+
typing.List[str],
1890+
typing.List[pathlib.Path],
1891+
typing.List[FilePayload],
18811892
],
18821893
timeout: int = None,
18831894
noWaitAfter: bool = None,

playwright/element_handle.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import mimetypes
1717
import os
1818
import sys
19+
from pathlib import Path
1920
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union, cast
2021

2122
from playwright.connection import ChannelOwner, from_nullable_channel
@@ -123,7 +124,7 @@ async def selectText(self, timeout: int = None) -> None:
123124

124125
async def setInputFiles(
125126
self,
126-
files: Union[str, FilePayload, List[str], List[FilePayload]],
127+
files: Union[str, Path, FilePayload, List[str], List[Path], List[FilePayload]],
127128
timeout: int = None,
128129
noWaitAfter: bool = None,
129130
) -> None:
@@ -242,16 +243,16 @@ def convert_select_option_values(arg: ValuesToSelect) -> Any:
242243

243244

244245
def normalize_file_payloads(
245-
files: Union[str, FilePayload, List[str], List[FilePayload]]
246+
files: Union[str, Path, FilePayload, List[str], List[Path], List[FilePayload]]
246247
) -> List[FilePayload]:
247248
file_list = files if isinstance(files, list) else [files]
248249
file_payloads: List[FilePayload] = []
249250
for item in file_list:
250-
if isinstance(item, str):
251+
if isinstance(item, str) or isinstance(item, Path):
251252
with open(item, mode="rb") as fd:
252253
file: FilePayload = {
253254
"name": os.path.basename(item),
254-
"mimeType": mimetypes.guess_type(item)[0]
255+
"mimeType": mimetypes.guess_type(str(Path(item)))[0]
255256
or "application/octet-stream",
256257
"buffer": base64.b64encode(fd.read()).decode(),
257258
}

playwright/frame.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import asyncio
1616
import sys
17+
from pathlib import Path
1718
from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Optional, Set, Union, cast
1819

1920
from pyee import BaseEventEmitter
@@ -280,7 +281,7 @@ async def addScriptTag(
280281
params = locals_to_params(locals())
281282
if path:
282283
with open(path, "r") as file:
283-
params["content"] = file.read() + "\n//# sourceURL=" + path
284+
params["content"] = file.read() + "\n//# sourceURL=" + str(Path(path))
284285
del params["path"]
285286
return from_channel(await self._channel.send("addScriptTag", params))
286287

@@ -290,7 +291,9 @@ async def addStyleTag(
290291
params = locals_to_params(locals())
291292
if path:
292293
with open(path, "r") as file:
293-
params["content"] = file.read() + "\n/*# sourceURL=" + path + "*/"
294+
params["content"] = (
295+
file.read() + "\n/*# sourceURL=" + str(Path(path)) + "*/"
296+
)
294297
del params["path"]
295298
return from_channel(await self._channel.send("addStyleTag", params))
296299

@@ -366,7 +369,7 @@ async def selectOption(
366369
async def setInputFiles(
367370
self,
368371
selector: str,
369-
files: Union[str, FilePayload, List[str], List[FilePayload]],
372+
files: Union[str, Path, FilePayload, List[str], List[Path], List[FilePayload]],
370373
timeout: int = None,
371374
noWaitAfter: bool = None,
372375
) -> None:

playwright/main.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from playwright.connection import Connection
2828
from playwright.helper import Error, not_installed_error
2929
from playwright.object_factory import create_remote_object
30+
from playwright.path_utils import get_file_dirname
3031
from playwright.playwright import Playwright
3132
from playwright.sync_api import Playwright as SyncPlaywright
3233
from playwright.sync_base import dispatcher_fiber, set_dispatcher_fiber
@@ -44,20 +45,20 @@ def compute_driver_name() -> str:
4445

4546

4647
async def run_driver_async() -> Connection:
47-
package_path = os.path.dirname(os.path.abspath(__file__))
48+
package_path = get_file_dirname()
4849
driver_name = compute_driver_name()
49-
driver_executable = os.path.join(package_path, driver_name)
50-
archive_name = os.path.join(package_path, "drivers", driver_name + ".gz")
50+
driver_executable = package_path / driver_name
51+
archive_name = package_path / "drivers" / (driver_name + ".gz")
5152

52-
if not os.path.exists(driver_executable) or os.path.getmtime(
53+
if not driver_executable.exists() or os.path.getmtime(
5354
driver_executable
5455
) < os.path.getmtime(archive_name):
5556
raise not_installed_error(
5657
"Playwright requires additional post-installation step to be made."
5758
)
5859

5960
proc = await asyncio.create_subprocess_exec(
60-
driver_executable,
61+
str(driver_executable),
6162
stdin=asyncio.subprocess.PIPE,
6263
stdout=asyncio.subprocess.PIPE,
6364
stderr=asyncio.subprocess.PIPE,
@@ -124,12 +125,12 @@ def main() -> None:
124125
if "install" not in sys.argv:
125126
print('Run "python -m playwright install" to complete installation')
126127
return
127-
package_path = os.path.dirname(os.path.abspath(__file__))
128+
package_path = get_file_dirname()
128129
driver_name = compute_driver_name()
129-
driver_executable = os.path.join(package_path, driver_name)
130-
archive_name = os.path.join(package_path, "drivers", driver_name + ".gz")
130+
driver_executable = package_path / driver_name
131+
archive_name = package_path / "drivers" / (driver_name + ".gz")
131132

132-
if not os.path.exists(driver_executable) or os.path.getmtime(
133+
if not driver_executable.exists() or os.path.getmtime(
133134
driver_executable
134135
) < os.path.getmtime(archive_name):
135136
print(f"Extracting {archive_name} into {driver_executable}...")

playwright/path_utils.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import inspect
2+
from pathlib import Path
3+
4+
5+
def get_file_dirname() -> Path:
6+
"""Returns the callee (`__file__`) directory name"""
7+
frame = inspect.stack()[1]
8+
module = inspect.getmodule(frame[0])
9+
assert module
10+
return Path(module.__file__).parent.absolute()

playwright/sync_api.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515

16+
import pathlib
1617
import sys
1718
import typing
1819

@@ -906,7 +907,12 @@ def selectText(self, timeout: int = None) -> NoneType:
906907
def setInputFiles(
907908
self,
908909
files: typing.Union[
909-
str, FilePayload, typing.List[str], typing.List[FilePayload]
910+
str,
911+
pathlib.Path,
912+
FilePayload,
913+
typing.List[str],
914+
typing.List[pathlib.Path],
915+
typing.List[FilePayload],
910916
],
911917
timeout: int = None,
912918
noWaitAfter: bool = None,
@@ -1968,7 +1974,12 @@ def setInputFiles(
19681974
self,
19691975
selector: str,
19701976
files: typing.Union[
1971-
str, FilePayload, typing.List[str], typing.List[FilePayload]
1977+
str,
1978+
pathlib.Path,
1979+
FilePayload,
1980+
typing.List[str],
1981+
typing.List[pathlib.Path],
1982+
typing.List[FilePayload],
19721983
],
19731984
timeout: int = None,
19741985
noWaitAfter: bool = None,

scripts/documentation_provider.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import os
1615
import re
1716
import sys
18-
from pathlib import Path
1917
from typing import Any, Dict, List, cast
2018

21-
_dirname = Path(os.path.dirname(os.path.abspath(__file__)))
19+
from playwright.path_utils import get_file_dirname
20+
21+
_dirname = get_file_dirname()
2222

2323

2424
class DocumentationProvider:

scripts/generate_api.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ def return_value(value: Any) -> List[str]:
153153
154154
import typing
155155
import sys
156+
import pathlib
156157
157158
if sys.version_info >= (3, 8): # pragma: no cover
158159
from typing import Literal

0 commit comments

Comments
 (0)