Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

python: Use universal_newlines to get str from subprocess.

Anders Kaseorgaaa7b766d820
diff --git a/scripts/lib/node_cache.py b/scripts/lib/node_cache.py
index 8a568b19ff2..a6015f2e264 100644
--- a/scripts/lib/node_cache.py
+++ b/scripts/lib/node_cache.py
@@ -2,9 +2,10 @@ import hashlib
import json
import os
import shutil
+import subprocess
from typing import List, Optional
-from scripts.lib.zulip_tools import run, subprocess_text_output
+from scripts.lib.zulip_tools import run
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ZULIP_SRV_PATH = "/srv"
@@ -30,14 +31,16 @@ def generate_sha1sum_node_modules(
PACKAGE_JSON_FILE_PATH = os.path.join(setup_dir, 'package.json')
YARN_LOCK_FILE_PATH = os.path.join(setup_dir, 'yarn.lock')
sha1sum = hashlib.sha1()
- sha1sum.update(subprocess_text_output(['cat', PACKAGE_JSON_FILE_PATH]).encode('utf8'))
+ with open(PACKAGE_JSON_FILE_PATH, "rb") as fb:
+ sha1sum.update(fb.read().strip())
if os.path.exists(YARN_LOCK_FILE_PATH):
# For backwards compatibility, we can't assume yarn.lock exists
- sha1sum.update(subprocess_text_output(['cat', YARN_LOCK_FILE_PATH]).encode('utf8'))
+ with open(YARN_LOCK_FILE_PATH, "rb") as fb:
+ sha1sum.update(fb.read().strip())
with open(YARN_PACKAGE_JSON) as f:
yarn_version = json.load(f)['version']
sha1sum.update(yarn_version.encode("utf8"))
- sha1sum.update(subprocess_text_output(['node', '--version']).encode('utf8'))
+ sha1sum.update(subprocess.check_output(['node', '--version']).strip())
yarn_args = get_yarn_args(production=production)
sha1sum.update(''.join(sorted(yarn_args)).encode('utf8'))
return sha1sum.hexdigest()
diff --git a/scripts/lib/upgrade-zulip-stage-2 b/scripts/lib/upgrade-zulip-stage-2
index 3c660d3410d..a8d682edf21 100755
--- a/scripts/lib/upgrade-zulip-stage-2
+++ b/scripts/lib/upgrade-zulip-stage-2
@@ -232,7 +232,7 @@ migrations_needed = False
if not args.skip_migrations:
logging.info("Checking for needed migrations")
migrations_output = subprocess.check_output(["./manage.py", "showmigrations"],
- preexec_fn=su_to_zulip).decode("utf-8")
+ preexec_fn=su_to_zulip, universal_newlines=True)
need_create_large_indexes = False
for ln in migrations_output.split("\n"):
line_str = ln.strip()
diff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.py
index 45d5ba2b313..287160ce2dc 100755
--- a/scripts/lib/zulip_tools.py
+++ b/scripts/lib/zulip_tools.py
@@ -106,9 +106,6 @@ def is_invalid_upgrade(current_version: str, new_version: str) -> bool:
return True
return False
-def subprocess_text_output(args: Sequence[str]) -> str:
- return subprocess.check_output(args, universal_newlines=True).strip()
-
def get_zulip_pwent() -> pwd.struct_passwd:
deploy_root_uid = os.stat(get_deploy_root()).st_uid
if deploy_root_uid != 0:
diff --git a/scripts/setup/restore-backup b/scripts/setup/restore-backup
index 1f1f8ed1345..680540f7d04 100755
--- a/scripts/setup/restore-backup
+++ b/scripts/setup/restore-backup
@@ -123,7 +123,7 @@ def restore_backup(tarball_file: IO[bytes]) -> None:
rabbitmq_host = subprocess.check_output(
[os.path.join(settings.DEPLOY_ROOT,
"scripts", "get-django-setting"),
- "RABBITMQ_HOST"]).strip().decode("utf-8")
+ "RABBITMQ_HOST"], universal_newlines=True).strip()
if rabbitmq_host in ["127.0.0.1", "::1", "localhost", "localhost6"]:
run([os.path.join(settings.DEPLOY_ROOT,
"scripts", "setup", "configure-rabbitmq")])
diff --git a/tools/i18n/process-mobile-i18n b/tools/i18n/process-mobile-i18n
index 1ce108879eb..55334461148 100755
--- a/tools/i18n/process-mobile-i18n
+++ b/tools/i18n/process-mobile-i18n
@@ -10,8 +10,8 @@ def get_json_filename(locale: str) -> str:
return f"locale/{locale}/mobile.json"
def get_locales() -> List[str]:
- output = check_output(['git', 'ls-files', 'locale'])
- tracked_files = output.decode().split()
+ output = check_output(['git', 'ls-files', 'locale'], universal_newlines=True)
+ tracked_files = output.split()
regex = re.compile(r'locale/(\w+)/LC_MESSAGES/django.po')
locales = ['en']
for tracked_file in tracked_files:
diff --git a/tools/review b/tools/review
index a8891681e89..2d564e7dc7e 100755
--- a/tools/review
+++ b/tools/review
@@ -15,7 +15,7 @@ def run(command: List[str]) -> None:
subprocess.check_call(command)
def check_output(command: List[str]) -> str:
- return subprocess.check_output(command).decode('ascii')
+ return subprocess.check_output(command, universal_newlines=True)
def get_git_branch() -> str:
command = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']
diff --git a/tools/update-zuliprc-api-field b/tools/update-zuliprc-api-field
index b46029c62f4..2c82756d69f 100755
--- a/tools/update-zuliprc-api-field
+++ b/tools/update-zuliprc-api-field
@@ -57,7 +57,7 @@ for zuliprc_path in zuliprc_paths_list:
arguments = ['./manage.py', 'print_initial_password', email]
# We redirect 'stderr' to 'stdout' to avoid 'Connection to 127.0.0.1 closed'
# appearing after this script finishes.
- output = subprocess.check_output(arguments, stderr=subprocess.STDOUT).decode('UTF-8')
+ output = subprocess.check_output(arguments, stderr=subprocess.STDOUT, universal_newlines=True)
new_key = output.split()[6]
if new_key != key:
diff --git a/zerver/lib/mdiff.py b/zerver/lib/mdiff.py
index 6297ac8f543..fc81479562e 100755
--- a/zerver/lib/mdiff.py
+++ b/zerver/lib/mdiff.py
@@ -15,5 +15,5 @@ def diff_strings(output: str, expected_output: str) -> str:
raise DiffException(msg)
command = ['node', mdiff_path, output, expected_output]
- diff = subprocess.check_output(command).decode('utf-8')
+ diff = subprocess.check_output(command, universal_newlines=True)
return diff
diff --git a/zerver/logging_handlers.py b/zerver/logging_handlers.py
index 273a568e6dc..9cac485774e 100644
--- a/zerver/logging_handlers.py
+++ b/zerver/logging_handlers.py
@@ -25,7 +25,8 @@ def try_git_describe() -> Optional[str]:
['git', 'describe', '--tags', '--match=[0-9]*', '--always', '--dirty', '--long'],
stderr=subprocess.PIPE,
cwd=os.path.join(os.path.dirname(__file__), '..'),
- ).strip().decode('utf-8')
+ universal_newlines=True,
+ ).strip()
except (FileNotFoundError, subprocess.CalledProcessError): # nocoverage
return None
diff --git a/zerver/management/commands/compilemessages.py b/zerver/management/commands/compilemessages.py
index f12fc0be25f..74db445540c 100644
--- a/zerver/management/commands/compilemessages.py
+++ b/zerver/management/commands/compilemessages.py
@@ -72,8 +72,8 @@ class Command(compilemessages.Command):
raise Exception(f"Unknown language {locale}")
def get_locales(self) -> List[str]:
- output = check_output(['git', 'ls-files', 'locale'])
- tracked_files = output.decode().split()
+ output = check_output(['git', 'ls-files', 'locale'], universal_newlines=True)
+ tracked_files = output.split()
regex = re.compile(r'locale/(\w+)/LC_MESSAGES/django.po')
locales = ['en']
for tracked_file in tracked_files:
diff --git a/zerver/openapi/test_curl_examples.py b/zerver/openapi/test_curl_examples.py
index 2c704d7575c..3ef703b492e 100644
--- a/zerver/openapi/test_curl_examples.py
+++ b/zerver/openapi/test_curl_examples.py
@@ -63,7 +63,7 @@ def test_generated_curl_examples_for_success(client: Client) -> None:
try:
# We split this across two lines so if curl fails and
# returns non-JSON output, we'll still print it.
- response_json = subprocess.check_output(generated_curl_command).decode('utf-8')
+ response_json = subprocess.check_output(generated_curl_command, universal_newlines=True)
response = json.loads(response_json)
assert(response["result"] == "success")
except (AssertionError, Exception):
diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.py
index 974480d87ec..95ed80197e3 100644
--- a/zerver/tests/test_email_mirror.py
+++ b/zerver/tests/test_email_mirror.py
@@ -1126,12 +1126,12 @@ class TestScriptMTA(ZulipTestCase):
mail_template = self.fixture_data('simple.txt', type='email')
mail = mail_template.format(stream_to_address=stream_to_address, sender=sender)
- read_pipe, write_pipe = os.pipe()
- os.write(write_pipe, mail.encode())
- os.close(write_pipe)
- subprocess.check_call(
+ subprocess.run(
[script, '-r', stream_to_address, '-s', settings.SHARED_SECRET, '-t'],
- stdin=read_pipe)
+ input=mail,
+ check=True,
+ universal_newlines=True,
+ )
def test_error_no_recipient(self) -> None:
script = os.path.join(os.path.dirname(__file__),
@@ -1142,21 +1142,17 @@ class TestScriptMTA(ZulipTestCase):
stream_to_address = encode_email_address(stream)
mail_template = self.fixture_data('simple.txt', type='email')
mail = mail_template.format(stream_to_address=stream_to_address, sender=sender)
- read_pipe, write_pipe = os.pipe()
- os.write(write_pipe, mail.encode())
- os.close(write_pipe)
- success_call = True
- try:
- subprocess.check_output([script, '-s', settings.SHARED_SECRET, '-t'],
- stdin=read_pipe)
- except subprocess.CalledProcessError as e:
- self.assertEqual(
- e.output,
- b'5.1.1 Bad destination mailbox address: No missed message email address.\n',
- )
- self.assertEqual(e.returncode, 67)
- success_call = False
- self.assertFalse(success_call)
+ p = subprocess.run(
+ [script, '-s', settings.SHARED_SECRET, '-t'],
+ input=mail,
+ stdout=subprocess.PIPE,
+ universal_newlines=True,
+ )
+ self.assertEqual(
+ p.stdout,
+ '5.1.1 Bad destination mailbox address: No missed message email address.\n',
+ )
+ self.assertEqual(p.returncode, 67)
class TestEmailMirrorTornadoView(ZulipTestCase):