Skip to content

Commit 4e3799f

Browse files
authored
[AIRFLOW-4541] Replace os.mkdirs usage with pathlib.Path(path).mkdir (#10117)
`makedirs` is used in `airlfow.utils.file.mkdirs` - it is replaced with pathlib now with python3.5+
1 parent 1d68cd2 commit 4e3799f

File tree

7 files changed

+21
-45
lines changed

7 files changed

+21
-45
lines changed

β€Žairflow/config_templates/airflow_local_settings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@
1818
"""Airflow logging settings"""
1919

2020
import os
21+
from pathlib import Path
2122
from typing import Any, Dict, Union
2223
from urllib.parse import urlparse
2324

2425
from airflow.configuration import conf
2526
from airflow.exceptions import AirflowException
26-
from airflow.utils.file import mkdirs
2727

2828
# TODO: Logging format and level should be configured
2929
# in this file instead of from airflow.cfg. Currently
@@ -151,7 +151,7 @@
151151
processor_manager_handler_config: Dict[str, Any] = \
152152
DEFAULT_DAG_PARSING_LOGGING_CONFIG['handlers']['processor_manager']
153153
directory: str = os.path.dirname(processor_manager_handler_config['filename'])
154-
mkdirs(directory, 0o755)
154+
Path(directory).mkdir(parents=True, exist_ok=True, mode=0o755)
155155

156156
##################
157157
# Remote logging #

β€Žairflow/providers/google/cloud/hooks/cloud_sql.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import subprocess
3434
import time
3535
import uuid
36+
from pathlib import Path
3637
from subprocess import PIPE, Popen
3738
from typing import Any, Dict, List, Optional, Sequence, Union
3839
from urllib.parse import quote_plus
@@ -553,13 +554,8 @@ def start_proxy(self) -> None:
553554
else:
554555
command_to_run = [self.sql_proxy_path]
555556
command_to_run.extend(self.command_line_parameters)
556-
try:
557-
self.log.info("Creating directory %s",
558-
self.cloud_sql_proxy_socket_directory)
559-
os.makedirs(self.cloud_sql_proxy_socket_directory)
560-
except OSError:
561-
# Needed for python 2 compatibility (exists_ok missing)
562-
pass
557+
self.log.info("Creating directory %s", self.cloud_sql_proxy_socket_directory)
558+
Path(self.cloud_sql_proxy_socket_directory).mkdir(parents=True, exist_ok=True)
563559
command_to_run.extend(self._get_credential_parameters()) # pylint: disable=no-value-for-parameter
564560
self.log.info("Running the command: `%s`", " ".join(command_to_run))
565561
self.sql_proxy_process = Popen(command_to_run,

β€Žairflow/providers/sftp/operators/sftp.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
This module contains SFTP operator.
2020
"""
2121
import os
22+
from pathlib import Path
2223

2324
from airflow.exceptions import AirflowException
2425
from airflow.models import BaseOperator
@@ -130,12 +131,7 @@ def execute(self, context):
130131
if self.operation.lower() == SFTPOperation.GET:
131132
local_folder = os.path.dirname(self.local_filepath)
132133
if self.create_intermediate_dirs:
133-
# Create Intermediate Directories if it doesn't exist
134-
try:
135-
os.makedirs(local_folder)
136-
except OSError:
137-
if not os.path.isdir(local_folder):
138-
raise
134+
Path(local_folder).mkdir(parents=True, exist_ok=True)
139135
file_msg = "from {0} to {1}".format(self.remote_filepath,
140136
self.local_filepath)
141137
self.log.info("Starting to transfer %s", file_msg)

β€Žairflow/utils/file.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import os
2121
import re
2222
import zipfile
23+
from pathlib import Path
2324
from typing import Dict, Generator, List, Optional, Pattern
2425

2526
from airflow.configuration import conf
@@ -50,14 +51,12 @@ def mkdirs(path, mode):
5051
:param mode: The mode to give to the directory e.g. 0o755, ignores umask
5152
:type mode: int
5253
"""
53-
try:
54-
o_umask = os.umask(0)
55-
os.makedirs(path, mode)
56-
except OSError:
57-
if not os.path.isdir(path):
58-
raise
59-
finally:
60-
os.umask(o_umask)
54+
import warnings
55+
warnings.warn(
56+
f"This function is deprecated. Please use `pathlib.Path({path}).mkdir`",
57+
DeprecationWarning, stacklevel=2
58+
)
59+
Path(path).mkdir(mode=mode, parents=True, exist_ok=True)
6160

6261

6362
ZIP_REGEX = re.compile(r'((.*\.zip){})?(.*)'.format(re.escape(os.sep)))

β€Žairflow/utils/log/file_processor_handler.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import logging
2020
import os
2121
from datetime import datetime
22+
from pathlib import Path
2223

2324
from airflow import settings
2425
from airflow.utils.helpers import parse_template_string
@@ -43,15 +44,7 @@ def __init__(self, base_log_folder, filename_template):
4344
parse_template_string(filename_template)
4445

4546
self._cur_date = datetime.today()
46-
if not os.path.exists(self._get_log_directory()):
47-
try:
48-
os.makedirs(self._get_log_directory())
49-
except OSError:
50-
# only ignore case where the directory already exist
51-
if not os.path.isdir(self._get_log_directory()):
52-
raise
53-
54-
logging.warning("%s already exists", self._get_log_directory())
47+
Path(self._get_log_directory()).mkdir(parents=True, exist_ok=True)
5548

5649
self._symlink_latest_log_directory()
5750

@@ -137,12 +130,7 @@ def _init_file(self, filename):
137130
log_file_path = os.path.abspath(relative_log_file_path)
138131
directory = os.path.dirname(log_file_path)
139132

140-
if not os.path.exists(directory):
141-
try:
142-
os.makedirs(directory)
143-
except OSError:
144-
if not os.path.isdir(directory):
145-
raise
133+
Path(directory).mkdir(parents=True, exist_ok=True)
146134

147135
if not os.path.exists(log_file_path):
148136
open(log_file_path, "a").close()

β€Žairflow/utils/log/file_task_handler.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818
"""File logging handler for tasks."""
1919
import logging
2020
import os
21+
from pathlib import Path
2122
from typing import Optional
2223

2324
import requests
2425

2526
from airflow.configuration import AirflowConfigException, conf
2627
from airflow.models import TaskInstance
27-
from airflow.utils.file import mkdirs
2828
from airflow.utils.helpers import parse_template_string
2929

3030

@@ -223,10 +223,7 @@ def _init_file(self, ti):
223223
# operator is not compatible with impersonation (e.g. if a Celery executor is used
224224
# for a SubDag operator and the SubDag operator has a different owner than the
225225
# parent DAG)
226-
if not os.path.exists(directory):
227-
# Create the directory as globally writable using custom mkdirs
228-
# as os.makedirs doesn't set mode properly.
229-
mkdirs(directory, 0o777)
226+
Path(directory).mkdir(mode=0o777, parents=True, exist_ok=True)
230227

231228
if not os.path.exists(full_path):
232229
open(full_path, "a").close()

β€Žtests/test_utils/system_tests_class.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@
1919
import shutil
2020
import sys
2121
from datetime import datetime
22+
from pathlib import Path
2223
from unittest import TestCase
2324

2425
from airflow.configuration import AIRFLOW_HOME, AirflowConfigParser, get_airflow_config
2526
from airflow.exceptions import AirflowException
2627
from airflow.models.dagbag import DagBag
27-
from airflow.utils.file import mkdirs
2828
from airflow.utils.log.logging_mixin import LoggingMixin
2929
from airflow.utils.state import State
3030
from tests.test_utils import AIRFLOW_MAIN_FOLDER
@@ -94,7 +94,7 @@ def tearDown(self) -> None:
9494
print(f"Saving all log files to {logs_folder}/previous_runs/{date_str}")
9595
print()
9696
target_dir = os.path.join(logs_folder, "previous_runs", date_str)
97-
mkdirs(target_dir, 0o755)
97+
Path(target_dir).mkdir(parents=True, exist_ok=True, mode=0o755)
9898
files = os.listdir(logs_folder)
9999
for file in files:
100100
if file != "previous_runs":

0 commit comments

Comments
 (0)