Skip to content

Commit eced731

Browse files
authored
Changes to use f-strings instead of format (#1265)
1 parent 8b22373 commit eced731

6 files changed

Lines changed: 69 additions & 67 deletions

File tree

l2tdevtools/review_helpers/cli.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,9 @@ def RunCommand(self, command):
5959
error = codecs.decode(error, self.preferred_encoding)
6060
exit_code = process.returncode
6161
if exit_code != 0:
62-
logging.error('Running: "{0:s}" failed with error: {1!s}.'.format(
63-
command, error))
62+
logging.error(f'Running: "{command:s}" failed with error: {error!s}.')
6463

6564
except OSError as exception:
66-
logging.error('Running: "{0:s}" failed with error: {1!s}'.format(
67-
command, exception))
65+
logging.error(f'Running: "{command:s}" failed with error: {exception!s}')
6866

6967
return exit_code, output, error

l2tdevtools/review_helpers/github.py

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ def AssignPullRequest(
4040
post_data = json.dumps({"assignees": assignees})
4141

4242
github_url = (
43-
'https://api.github.com/repos/{0:s}/{1:s}/issues/{2:d}/'
44-
'assignees?access_token={3:s}').format(
45-
self._organization, self._project, pull_request_number,
46-
access_token)
43+
f'https://api.github.com/repos/'
44+
f'{self._organization:s}/{self._project:s}/issues/'
45+
f'{pull_request_number:d}/assignees?'
46+
f'access_token={access_token:s}')
4747

4848
try:
4949
self._url_lib_helper.Request(github_url, post_data=post_data)
@@ -78,18 +78,18 @@ def CreatePullRequest(self, access_token, origin, title, body, no_edit=False):
7878

7979
# Note that the maintainer_can_modify is a JSON boolean value.
8080
post_data = (
81-
'{{\n'
82-
' "title": "{0:s}",\n'
83-
' "body": "{1:s}",\n'
84-
' "head": "{2:s}",\n'
85-
' "base": "main",\n'
86-
' "maintainer_can_modify": {3:s}\n'
87-
'}}\n').format(title, body, origin, maintainer_can_modify)
81+
f'{{\n'
82+
f' "title": "{title:s}",\n'
83+
f' "body": "{body:s}",\n'
84+
f' "head": "{origin:s}",\n'
85+
f' "base": "main",\n'
86+
f' "maintainer_can_modify": {maintainer_can_modify:s}\n'
87+
f'}}\n')
8888

8989
github_url = (
90-
'https://api.github.com/repos/{0:s}/{1:s}/pulls?'
91-
'access_token={2:s}').format(
92-
self._organization, self._project, access_token)
90+
f'https://api.github.com/repos/'
91+
f'{self._organization:s}/{self._project:s}/pulls?'
92+
f'access_token={access_token:s}')
9393

9494
response_data = self._url_lib_helper.Request(
9595
github_url, post_data=post_data)
@@ -118,10 +118,10 @@ def CreatePullRequestReview(
118118
post_data = json.dumps({"reviewers": reviewers})
119119

120120
github_url = (
121-
'https://api.github.com/repos/{0:s}/{1:s}/pulls/{2:d}/'
122-
'requested_reviewers?access_token={3:s}').format(
123-
self._organization, self._project, pull_request_number,
124-
access_token)
121+
f'https://api.github.com/repos/'
122+
f'{self._organization:s}/{self._project:s}/pulls/'
123+
f'{pull_request_number:d}/requested_reviewers?'
124+
f'access_token={access_token:s}')
125125

126126
try:
127127
self._url_lib_helper.Request(github_url, post_data=post_data)
@@ -140,7 +140,7 @@ def GetForkGitRepoUrl(self, username):
140140
Returns:
141141
str: git repository URL or None.
142142
"""
143-
return 'https://github.com/{0:s}/{1:s}.git'.format(username, self._project)
143+
return f'https://github.com/{username:s}/{self._project:s}.git'
144144

145145
def GetUsername(self, access_token):
146146
"""Retrieves a GitHub user.
@@ -151,9 +151,7 @@ def GetUsername(self, access_token):
151151
Returns:
152152
str: GitHub user name or None if not available.
153153
"""
154-
github_url = (
155-
'https://api.github.com/user?access_token={0:s}').format(
156-
access_token)
154+
github_url = f'https://api.github.com/user?access_token={access_token:s}'
157155

158156
try:
159157
response_data = self._url_lib_helper.Request(github_url)
@@ -178,13 +176,13 @@ def QueryUser(self, username):
178176
Returns:
179177
dict[str,object]: JSON response or None if not available.
180178
"""
181-
github_url = 'https://api.github.com/users/{0:s}'.format(username)
179+
github_url = f'https://api.github.com/users/{username:s}'
182180

183181
try:
184182
response_data = self._url_lib_helper.Request(github_url)
185183

186184
except errors.ConnectivityError as exception:
187-
logging.warning('{0!s}'.format(exception))
185+
logging.warning(f'{exception!s}')
188186
return None
189187

190188
if isinstance(response_data, bytes):

l2tdevtools/review_helpers/pylint.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,24 +55,24 @@ def CheckFiles(self, filenames, rcfile):
5555
print('Running linter on changed files.')
5656
failed_filenames = []
5757
for filename in filenames:
58-
print('Checking: {0:s}'.format(filename))
58+
print(f'Checking: {filename:s}')
5959

60-
command = 'pylint --rcfile="{0:s}" {1:s}'.format(rcfile, filename)
60+
command = f'pylint --rcfile="{rcfile:s}" {filename:s}'
6161
# For now disable pylint 2.1.1 and later specific checks.
6262
if version_tuple >= (2, 1, 1):
6363
additional_checks = [
6464
'assignment-from-none', 'chained-comparison',
6565
'useless-object-inheritance']
66-
command = '{0:s} --disable={1:s}'.format(
67-
command, ','.join(additional_checks))
66+
disable_checks = ','.join(additional_checks)
67+
command = f'{command:s} --disable={disable_checks:s}'
6868

6969
exit_code = subprocess.call(command, shell=True)
7070
if exit_code != 0:
7171
failed_filenames.append(filename)
7272

7373
if failed_filenames:
74-
print('\nFiles with linter errors:\n{0:s}\n'.format(
75-
'\n'.join(failed_filenames)))
74+
filenames_string = '\n'.join(failed_filenames)
75+
print(f'\nFiles with linter errors:\n{filenames_string:s}\n')
7676
return False
7777

7878
return True

l2tdevtools/review_helpers/review.py

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515
class ReviewHelper:
1616
"""Helper for conducting code reviews."""
1717

18+
_SUPPORTED_PROJECTS_PATTERN = '|'.join(
19+
project.ProjectHelper.SUPPORTED_PROJECTS)
1820
_PROJECT_NAME_PREFIX_REGEX = re.compile(
19-
r'\[({0:s})\] '.format(
20-
'|'.join(project.ProjectHelper.SUPPORTED_PROJECTS)))
21+
rf'\[({_SUPPORTED_PROJECTS_PATTERN})\] ')
2122

2223
_CODE_INSPECTION_COMMANDS = frozenset([
2324
'create-pr', 'create_pr', 'lint', 'lint-test', 'lint_test'])
@@ -66,32 +67,32 @@ def CheckLocalGitState(self):
6667
if self._command in (
6768
'close', 'create-pr', 'create_pr', 'lint', 'lint-test', 'lint_test'):
6869
if not self._git_helper.CheckHasProjectUpstream():
69-
print('{0:s} aborted - missing project upstream.'.format(
70-
self._command.title()))
71-
print('Run: git remote add upstream {0:s}'.format(self._git_repo_url))
70+
command_title = self._command.title()
71+
print(f'{command_title:s} aborted - missing project upstream.')
72+
print(f'Run: git remote add upstream {self._git_repo_url:s}')
7273
return False
7374

7475
if self._command not in (
7576
'lint', 'lint-test', 'lint_test', 'test', 'update-version',
7677
'update_version'):
7778
if self._git_helper.CheckHasUncommittedChanges():
78-
print('{0:s} aborted - detected uncommitted changes.'.format(
79-
self._command.title()))
79+
command_title = self._command.title()
80+
print(f'{command_title:s} aborted - detected uncommitted changes.')
8081
print('Run: git commit')
8182
return False
8283

8384
if self._github_organization in ('ForensicArtifacts', 'log2timeline'):
8485
self._active_branch = self._git_helper.GetActiveBranch()
8586
if self._command in ('create-pr', 'create_pr'):
8687
if self._active_branch == 'main':
87-
print('{0:s} aborted - active branch is main.'.format(
88-
self._command.title()))
88+
command_title = self._command.title()
89+
print(f'{command_title:s} aborted - active branch is main.')
8990
return False
9091

9192
elif self._command == 'close':
9293
if self._feature_branch == 'main':
93-
print('{0:s} aborted - feature branch cannot be main.'.format(
94-
self._command.title()))
94+
command_title = self._command.title()
95+
print(f'{command_title:s} aborted - feature branch cannot be main.')
9596
return False
9697

9798
if self._active_branch != 'main':
@@ -107,14 +108,15 @@ def Close(self):
107108
bool: True if the close was successful.
108109
"""
109110
if not self._git_helper.CheckHasBranch(self._feature_branch):
110-
print('No such feature branch: {0:s}'.format(self._feature_branch))
111+
print(f'No such feature branch: {self._feature_branch:s}')
111112
else:
112113
self._git_helper.RemoveFeatureBranch(self._feature_branch)
113114

114115
if not self._git_helper.SynchronizeWithUpstream():
115-
print((
116-
'{0:s} aborted - unable to synchronize with '
117-
'upstream/main.').format(self._command.title()))
116+
command_title = self._command.title()
117+
print(
118+
f'{command_title:s} aborted - unable to synchronize with '
119+
f'upstream/main.')
118120

119121
return True
120122

@@ -130,8 +132,8 @@ def InitializeHelpers(self):
130132

131133
self._project_name = self._project_helper.project_name
132134
if not self._project_name:
133-
print('{0:s} aborted - unable to determine project name.'.format(
134-
self._command.title()))
135+
command_title = self._command.title()
136+
print(f'{command_title:s} aborted - unable to determine project name.')
135137
return False
136138

137139
project_definition = self._project_helper.ReadDefinitionFile()
@@ -144,12 +146,15 @@ def InitializeHelpers(self):
144146
self._github_organization, _, _ = self._github_organization.partition('/')
145147

146148
if not self._github_organization:
147-
print('{0:s} aborted - unable to determine GitHub organization.'.format(
148-
self._command.title()))
149+
command_title = self._command.title()
150+
print(
151+
f'{command_title:s} aborted - unable to determine GitHub '
152+
f'organization.')
149153
return False
150154

151-
self._git_repo_url = 'https://github.com/{0:s}/{1:s}.git'.format(
152-
self._github_organization, self._project_name)
155+
self._git_repo_url = (
156+
f'https://github.com/'
157+
f'{self._github_organization:s}/{self._project_name:s}.git')
153158

154159
self._git_helper = git.GitHelper(self._git_repo_url)
155160

@@ -172,8 +177,11 @@ def Lint(self):
172177

173178
pylint_helper = pylint.PylintHelper()
174179
if not pylint_helper.CheckUpToDateVersion():
175-
print('{0:s} aborted - pylint version {1:s} or later required.'.format(
176-
self._command.title(), pylint.PylintHelper.MINIMUM_VERSION))
180+
command_title = self._command.title()
181+
min_version = pylint.PylintHelper.MINIMUM_VERSION
182+
print(
183+
f'{command_title:s} aborted - pylint version {min_version:s} '
184+
f'or later required.')
177185
return False
178186

179187
if self._all_files:
@@ -186,8 +194,8 @@ def Lint(self):
186194

187195
pylint_configuration = pylint_helper.GetRCFile(self._project_path)
188196
if not pylint_helper.CheckFiles(changed_python_files, pylint_configuration):
189-
print('{0:s} aborted - unable to pass linter.'.format(
190-
self._command.title()))
197+
command_title = self._command.title()
198+
print(f'{command_title:s} aborted - unable to pass linter.')
191199

192200
return False
193201

@@ -208,11 +216,11 @@ def Test(self):
208216

209217
# TODO: determine why this alters the behavior of argparse.
210218
# Currently affects this script being used in plaso.
211-
command = '{0:s} run_tests.py'.format(sys.executable)
219+
command = f'{sys.executable:s} run_tests.py'
212220
exit_code = subprocess.call(command, shell=True)
213221
if exit_code != 0:
214-
print('{0:s} aborted - unable to pass review.'.format(
215-
self._command.title()))
222+
command_title = self._command.title()
223+
print(f'{command_title:s} aborted - unable to pass review.')
216224

217225
return False
218226

l2tdevtools/review_helpers/url_lib.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,10 @@ def Request(self, url, post_data=None):
3939

4040
except urllib_error.HTTPError as exception:
4141
raise errors.ConnectivityError(
42-
'Failed requesting URL {0:s} with error: {1!s}'.format(
43-
url, exception))
42+
f'Failed requesting URL {url:s} with error: {exception!s}')
4443

4544
if response_code not in (200, 201):
4645
raise errors.ConnectivityError(
47-
'Failed requesting URL {0:s} with status code: {1:d}'.format(
48-
url, response_code))
46+
f'Failed requesting URL {url:s} with status code: {response_code:d}')
4947

5048
return page_content

l2tdevtools/source_helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def __init__(self, project_name, project_definition):
6666
def Clean(self):
6767
"""Removes a previous version of the source directory."""
6868
if os.path.exists(self.project_name):
69-
logging.info('Removing: {0:s}'.format(self.project_name))
69+
logging.info(f'Removing: {self.project_name:s}')
7070
shutil.rmtree(self.project_name)
7171

7272
def Create(self):

0 commit comments

Comments
 (0)