Skip to content

Commit 8c25e1f

Browse files
committed
Use pathlib instead of os
1 parent fc52778 commit 8c25e1f

File tree

6 files changed

+55
-53
lines changed

6 files changed

+55
-53
lines changed

describe.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import argparse
2929
import collections
3030
import json
31-
import os
3231
import pathlib
3332
import re
3433
import string
@@ -43,8 +42,9 @@
4342

4443
import uritemplate
4544

46-
DISCOVERY_DOC_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
47-
'googleapiclient/discovery_cache/documents')
45+
DISCOVERY_DOC_DIR = (
46+
pathlib.Path(__file__).parent.resolve() / "googleapiclient" / "discovery_cache" / "documents"
47+
)
4848

4949
CSS = """<style>
5050
@@ -136,8 +136,7 @@
136136
<code><a href="#$name">$name($params)</a></code></p>
137137
<p class="firstline">$firstline</p>"""
138138

139-
BASE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
140-
"docs/dyn")
139+
BASE = pathlib.Path(__file__).parent.resolve() / "docs" / "dyn"
141140

142141
DIRECTORY_URI = "https://www.googleapis.com/discovery/v1/apis"
143142

@@ -361,7 +360,7 @@ def document_collection(resource, path, root_discovery, discovery, css=CSS):
361360
def document_collection_recursive(resource, path, root_discovery, discovery, doc_destination_dir):
362361
html = document_collection(resource, path, root_discovery, discovery)
363362

364-
f = open(os.path.join(doc_destination_dir, path + "html"), "w")
363+
f = open(pathlib.Path(doc_destination_dir).joinpath(path + "html"), "w")
365364

366365
f.write(html)
367366
f.close()
@@ -407,7 +406,7 @@ def document_api(name, version, uri, doc_destination_dir):
407406
version = safe_version(version)
408407
doc_name = "{}.{}.json".format(name, version.replace("_", ""))
409408

410-
discovery_file_path = os.path.join(DISCOVERY_DOC_DIR, doc_name)
409+
discovery_file_path = DISCOVERY_DOC_DIR / doc_name
411410
revision = None
412411

413412
pathlib.Path(discovery_file_path).touch(exist_ok=True)
@@ -495,7 +494,7 @@ def generate_all_api_documents(directory_uri=DIRECTORY_URI, doc_destination_dir=
495494
)
496495
markdown.append("\n")
497496

498-
with open(os.path.join(BASE, "index.md"), "w") as f:
497+
with open(BASE / "index.md", "w") as f:
499498
markdown = "\n".join(markdown)
500499
f.write(markdown)
501500

noxfile.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ def unit(session, oauth2client):
9595
@nox.session(python=["3.9"])
9696
def scripts(session):
9797
session.install(*test_dependencies)
98-
session.install(".")
99-
session.install("-r", os.path.join("scripts", "requirements.txt"))
98+
session.install("-e", ".")
99+
session.install("-r", "scripts/requirements.txt")
100100

101101
# Run py.test against the unit tests.
102102
session.run(

scripts/buildprbody.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@
1414

1515
from enum import IntEnum
1616
import numpy as np
17-
import os
1817
import pandas as pd
19-
18+
import pathlib
2019

2120
class ChangeType(IntEnum):
2221
UNKNOWN = 0
@@ -36,8 +35,8 @@ def get_commit_link(name):
3635
sha = None
3736
api_link = ""
3837

39-
file_path = os.path.join(directory, "{0}.sha".format(name))
40-
if os.path.exists(file_path):
38+
file_path = pathlib.Path(directory).joinpath("{0}.sha".format(name))
39+
if file_path.is_file():
4140
with open(file_path, "r") as f:
4241
sha = f.readline().rstrip()
4342
if sha:
@@ -47,7 +46,7 @@ def get_commit_link(name):
4746

4847

4948
if __name__ == "__main__":
50-
directory = "temp"
49+
directory = pathlib.Path("temp")
5150
dataframe = pd.read_csv("temp/allapis.dataframe")
5251
dataframe["Version"] = dataframe["Version"].astype(str)
5352

@@ -80,7 +79,7 @@ def get_commit_link(name):
8079
.values
8180
)
8281

83-
with open(os.path.join(directory, "allapis.summary"), "w") as f:
82+
with open(directory / "allapis.summary", "w") as f:
8483
if len(stable_and_breaking) > 0:
8584
f.writelines(
8685
[

scripts/changesummary.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@
1515
from enum import IntEnum
1616
import json
1717
from multiprocessing import Pool
18-
import os
1918
import pandas as pd
19+
import pathlib
2020
import numpy as np
2121

22-
BRANCH_ARTIFACTS_DIR = "googleapiclient/discovery_cache/documents/"
23-
MAIN_ARTIFACTS_DIR = "../main/googleapiclient/discovery_cache/documents/"
22+
BRANCH_ARTIFACTS_DIR = (
23+
pathlib.Path(__file__).parent.resolve() / "googleapiclient" / "discovery_cache" / "documents"
24+
)
25+
MAIN_ARTIFACTS_DIR = (
26+
pathlib.Path(__file__).parent.resolve() / ".." / "main" / "googleapiclient" / "discovery_cache" / "documents"
27+
)
28+
2429
MULTIPROCESSING_NUM_PER_BATCH = 5
2530
MULTIPROCESSING_NUM_AGENTS = 10
2631

@@ -57,9 +62,9 @@ def __init__(self, new_artifacts_dir, current_artifacts_dir, temp_dir, file_list
5762
"""
5863

5964
self._file_list = file_list
60-
self._new_artifacts_dir = new_artifacts_dir
61-
self._current_artifacts_dir = current_artifacts_dir
62-
self._temp_dir = temp_dir
65+
self._new_artifacts_dir = pathlib.Path(new_artifacts_dir)
66+
self._current_artifacts_dir = pathlib.Path(current_artifacts_dir)
67+
self._temp_dir = pathlib.Path(temp_dir)
6368

6469
# Sanity checks to ensure directories exist
6570
self._raise_if_directory_not_found(self._new_artifacts_dir)
@@ -73,7 +78,7 @@ def _raise_if_directory_not_found(self, directory):
7378
directory (str): The relative path to the `directory`
7479
"""
7580

76-
if not os.path.exists(directory):
81+
if not pathlib.Path(directory).exists():
7782
raise DirectoryDoesNotExist(
7883
"Directory does not exist : {0}".format(directory)
7984
)
@@ -90,7 +95,7 @@ def _load_json_to_dataframe(self, file_path):
9095
# doesn't exist
9196
dataframe_doc = pd.DataFrame()
9297

93-
if os.path.exists(file_path):
98+
if pathlib.Path(file_path).is_file():
9499
with open(file_path, "r") as f:
95100
# Now load the json file into a pandas dataframe as a flat table
96101
dataframe_doc = pd.json_normalize(json.load(f))
@@ -105,8 +110,8 @@ def _get_discovery_differences(self, filename):
105110
filename (str): The name of the discovery artifact to parse.
106111
"""
107112
# The paths of the 2 discovery artifacts to compare
108-
current_artifact_path = os.path.join(self._current_artifacts_dir, filename)
109-
new_artifact_path = os.path.join(self._new_artifacts_dir, filename)
113+
current_artifact_path = self._current_artifacts_dir / filename
114+
new_artifact_path = self._new_artifacts_dir / filename
110115

111116
# Use a helper functions to load the discovery artifacts into pandas
112117
# dataframes
@@ -375,7 +380,7 @@ def _get_summary_and_write_to_disk(self, dataframe, directory):
375380

376381
# Write the final dataframe to disk as it will be used in the
377382
# buildprbody.py script
378-
dataframe.to_csv(os.path.join(directory, "allapis.dataframe"))
383+
dataframe.to_csv(directory / "allapis.dataframe")
379384
return dataframe
380385

381386
def _write_verbose_changes_to_disk(self, dataframe, directory, summary_df):
@@ -432,7 +437,7 @@ def _write_verbose_changes_to_disk(self, dataframe, directory, summary_df):
432437
# Create a file which contains verbose changes for the current
433438
# API being processed
434439
filename = "{0}.verbose".format(currentApi)
435-
f = open(os.path.join(directory, filename), "a")
440+
f = open(pathlib.Path(directory / filename), "a")
436441
lastApi = currentApi
437442

438443
# Create a filter with only the rows for the current API
@@ -507,7 +512,7 @@ def detect_discovery_changes(self):
507512

508513
# Create a folder which be used by the `createcommits.sh` and
509514
# `buildprbody.py` scripts.
510-
os.makedirs(os.path.dirname(self._temp_dir), exist_ok=True)
515+
pathlib.Path(self._temp_dir).mkdir(exist_ok=True)
511516

512517
# Create a summary which contains a conventional commit message
513518
# for each API and write it to disk.

scripts/changesummary_test.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
__author__ = "[email protected] (Anthonios Partheniou)"
1818

19-
import os
19+
import pathlib
2020
import shutil
2121
import unittest
2222

@@ -26,21 +26,18 @@
2626
from changesummary import ChangeType
2727
from changesummary import DirectoryDoesNotExist
2828

29-
30-
SCRIPTS_DIR = os.path.dirname(os.path.realpath(__file__))
31-
NEW_ARTIFACTS_DIR = os.path.join(SCRIPTS_DIR, "test_resources", "new_artifacts_dir")
32-
CURRENT_ARTIFACTS_DIR = os.path.join(
33-
SCRIPTS_DIR, "test_resources", "current_artifacts_dir"
34-
)
35-
TEMP_DIR = os.path.join(SCRIPTS_DIR, "test_resources", "temp")
29+
SCRIPTS_DIR = pathlib.Path(__file__).parent.resolve()
30+
NEW_ARTIFACTS_DIR = SCRIPTS_DIR / "test_resources" / "new_artifacts_dir"
31+
CURRENT_ARTIFACTS_DIR = SCRIPTS_DIR / "test_resources" / "current_artifacts_dir"
32+
TEMP_DIR = SCRIPTS_DIR / "test_resources" / "temp"
3633

3734

3835
class TestChangeSummary(unittest.TestCase):
3936
def setUp(self):
4037
# Clear temporary directory
4138
shutil.rmtree(TEMP_DIR, ignore_errors=True)
4239
# Create temporary directory
43-
os.mkdir(TEMP_DIR)
40+
pathlib.Path(TEMP_DIR).mkdir()
4441

4542
self.cs = ChangeSummary(NEW_ARTIFACTS_DIR, CURRENT_ARTIFACTS_DIR, TEMP_DIR, [])
4643

@@ -66,7 +63,7 @@ def test_raises_on_directory_not_found_temp_dir(self):
6663
).detect_discovery_changes()
6764

6865
# Create temporary directory
69-
os.mkdir(TEMP_DIR)
66+
pathlib.Path(TEMP_DIR).mkdir()
7067

7168
ChangeSummary(
7269
NEW_ARTIFACTS_DIR, CURRENT_ARTIFACTS_DIR, TEMP_DIR, []
@@ -81,7 +78,7 @@ def test_load_json_to_dataframe_returns_empty_df_if_file_path_invalid(self):
8178
self.assertTrue(df.empty)
8279

8380
def test_load_json_to_dataframe_returns_expected_data(self):
84-
doc_path = os.path.join(NEW_ARTIFACTS_DIR, "drive.v3.json")
81+
doc_path = NEW_ARTIFACTS_DIR / "drive.v3.json"
8582
df = self.cs._load_json_to_dataframe(file_path=doc_path)
8683
self.assertEqual(df["name"].iloc[0], "drive")
8784
self.assertEqual(df["version"].iloc[0], "v3")
@@ -184,7 +181,7 @@ def test_detect_discovery_changes(self):
184181
)
185182
cs.detect_discovery_changes()
186183
print("test")
187-
result = pd.read_csv(os.path.join(TEMP_DIR, "allapis.dataframe"))
184+
result = pd.read_csv(TEMP_DIR / "allapis.dataframe")
188185

189186
# bigquery was added
190187
# 28 key changes in total.

scripts/updatediscoveryartifacts.py

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

15+
16+
import pathlib
17+
import shutil
1518
import subprocess
1619
import tempfile
17-
import shutil
18-
import os
1920

2021
import describe
2122
import changesummary
2223

23-
SCRIPTS_DIR = os.path.dirname(os.path.realpath(__file__))
24-
DISCOVERY_DOC_DIR = os.path.join(SCRIPTS_DIR, '../googleapiclient/discovery_cache/documents')
25-
REFERENCE_DOC_DIR = os.path.join(SCRIPTS_DIR, '../docs/dyn')
26-
TEMP_DIR = os.path.join(SCRIPTS_DIR, 'temp')
24+
25+
SCRIPTS_DIR = pathlib.Path(__file__).parent.resolve()
26+
DISCOVERY_DOC_DIR = SCRIPTS_DIR / ".." / "googleapiclient" / "discovery_cache" / "documents"
27+
REFERENCE_DOC_DIR = SCRIPTS_DIR / ".." / "docs" / "dyn"
28+
TEMP_DIR = SCRIPTS_DIR / "temp"
2729

2830
# Clear discovery documents and reference documents directory
2931
shutil.rmtree(DISCOVERY_DOC_DIR, ignore_errors=True)
@@ -49,22 +51,22 @@
4951
'origin/master',
5052
'--name-only',
5153
'--',
52-
(os.path.join(DISCOVERY_DOC_DIR, '*.json')),
53-
(os.path.join(REFERENCE_DOC_DIR, '*.html')),
54-
(os.path.join(REFERENCE_DOC_DIR, '*.md')),
54+
DISCOVERY_DOC_DIR / '*.json',
55+
REFERENCE_DOC_DIR / '*.html',
56+
REFERENCE_DOC_DIR / '*.md',
5557
],
5658
universal_newlines=True)
5759

5860
# Create lists of the changed files
59-
all_changed_files = [os.path.basename(file_name) for file_name in git_diff_output.split('\n')]
61+
all_changed_files = [pathlib.Path(file_name).name for file_name in git_diff_output.split('\n')]
6062
json_changed_files = [file for file in all_changed_files if file.endswith(".json")]
6163

6264
# Create temporary directory
63-
os.mkdir(TEMP_DIR)
65+
pathlib.Path(TEMP_DIR).mkdir()
6466

6567
# Analyze the changes in discovery artifacts using the changesummary module
6668
changesummary.ChangeSummary(DISCOVERY_DOC_DIR, current_discovery_doc_dir, TEMP_DIR, json_changed_files).detect_discovery_changes()
6769

6870
# Write a list of the files changed to a file called `changed files` which will be used in the `createcommits.sh` script.
69-
with open(os.path.join(TEMP_DIR, "changed_files"), "w") as f:
71+
with open(TEMP_DIR / "changed_files", "w") as f:
7072
f.writelines('\n'.join(all_changed_files))

0 commit comments

Comments
 (0)