We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Make work on Chrome

Make work on Chrome


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `tools/buildpkg.py`
Content:
```
1 #!/usr/bin/env python3
2 
3 """
4 Builds a Pyodide package.
5 """
6 
7 import argparse
8 import hashlib
9 import os
10 import shutil
11 import subprocess
12 
13 
14 import common
15 
16 
17 ROOTDIR = os.path.abspath(os.path.dirname(__file__))
18 
19 
20 def check_checksum(path, pkg):
21     """
22     Checks that a tarball matches the checksum in the package metadata.
23     """
24     if 'md5' not in pkg['source']:
25         return
26     checksum = pkg['source']['md5']
27     CHUNK_SIZE = 1 << 16
28     h = hashlib.md5()
29     with open(path, 'rb') as fd:
30         while True:
31             chunk = fd.read(CHUNK_SIZE)
32             h.update(chunk)
33             if len(chunk) < CHUNK_SIZE:
34                 break
35     if h.hexdigest() != checksum:
36         raise ValueError("Invalid checksum")
37 
38 
39 def download_and_extract(buildpath, packagedir, pkg, args):
40     tarballpath = os.path.join(
41         buildpath, os.path.basename(pkg['source']['url']))
42     if not os.path.isfile(tarballpath):
43         subprocess.run([
44             'wget', '-q', '-O', tarballpath, pkg['source']['url']
45         ], check=True)
46         check_checksum(tarballpath, pkg)
47     srcpath = os.path.join(buildpath, packagedir)
48     if not os.path.isdir(srcpath):
49         shutil.unpack_archive(tarballpath, buildpath)
50     return srcpath
51 
52 
53 def patch(path, srcpath, pkg, args):
54     if os.path.isfile(os.path.join(srcpath, '.patched')):
55         return
56 
57     # Apply all of the patches
58     orig_dir = os.getcwd()
59     pkgdir = os.path.abspath(os.path.dirname(path))
60     os.chdir(srcpath)
61     try:
62         for patch in pkg['source'].get('patches', []):
63             subprocess.run([
64                 'patch', '-p1', '--binary', '-i', os.path.join(pkgdir, patch)
65             ], check=True)
66     finally:
67         os.chdir(orig_dir)
68 
69     # Add any extra files
70     for src, dst in pkg['source'].get('extras', []):
71         shutil.copyfile(os.path.join(pkgdir, src), os.path.join(srcpath, dst))
72 
73     with open(os.path.join(srcpath, '.patched'), 'wb') as fd:
74         fd.write(b'\n')
75 
76 
77 def get_libdir(srcpath, args):
78     # Get the name of the build/lib.XXX directory that distutils wrote its
79     # output to
80     slug = subprocess.check_output([
81         os.path.join(args.host, 'bin', 'python3'),
82         '-c',
83         'import sysconfig, sys; '
84         'print("{}-{}.{}".format('
85         'sysconfig.get_platform(), '
86         'sys.version_info[0], '
87         'sys.version_info[1]))']).decode('ascii').strip()
88     purelib = os.path.join(srcpath, 'build', 'lib')
89     if os.path.isdir(purelib):
90         libdir = purelib
91     else:
92         libdir = os.path.join(srcpath, 'build', 'lib.' + slug)
93     return libdir
94 
95 
96 def compile(path, srcpath, pkg, args):
97     if os.path.isfile(os.path.join(srcpath, '.built')):
98         return
99 
100     orig_dir = os.getcwd()
101     os.chdir(srcpath)
102     try:
103         subprocess.run([
104             os.path.join(args.host, 'bin', 'python3'),
105             os.path.join(ROOTDIR, 'pywasmcross'),
106             '--cflags',
107             args.cflags + ' ' +
108             pkg.get('build', {}).get('cflags', ''),
109             '--ldflags',
110             args.ldflags + ' ' +
111             pkg.get('build', {}).get('ldflags', ''),
112             '--host', args.host,
113             '--target', args.target], check=True)
114     finally:
115         os.chdir(orig_dir)
116 
117     post = pkg.get('build', {}).get('post')
118     if post is not None:
119         libdir = get_libdir(srcpath, args)
120         pkgdir = os.path.abspath(os.path.dirname(path))
121         env = {
122             'BUILD': libdir,
123             'PKGDIR': pkgdir
124         }
125         subprocess.run([
126             'bash', '-c', post], env=env, check=True)
127 
128     with open(os.path.join(srcpath, '.built'), 'wb') as fd:
129         fd.write(b'\n')
130 
131 
132 def package_files(buildpath, srcpath, pkg, args):
133     if os.path.isfile(os.path.join(buildpath, '.packaged')):
134         return
135 
136     name = pkg['package']['name']
137     libdir = get_libdir(srcpath, args)
138     subprocess.run([
139         'python2',
140         os.path.join(os.environ['EMSCRIPTEN'], 'tools', 'file_packager.py'),
141         os.path.join(buildpath, name + '.data'),
142         '--preload',
143         '{}@/lib/python3.6/site-packages'.format(libdir),
144         '--js-output={}'.format(os.path.join(buildpath, name + '.js')),
145         '--export-name=pyodide',
146         '--exclude', '*.wasm.pre',
147         '--exclude', '__pycache__'], check=True)
148     subprocess.run([
149         'uglifyjs',
150         os.path.join(buildpath, name + '.js'),
151         '-o',
152         os.path.join(buildpath, name + '.js')], check=True)
153 
154     with open(os.path.join(buildpath, '.packaged'), 'wb') as fd:
155         fd.write(b'\n')
156 
157 
158 def build_package(path, args):
159     pkg = common.parse_package(path)
160     packagedir = pkg['package']['name'] + '-' + pkg['package']['version']
161     dirpath = os.path.dirname(path)
162     orig_path = os.getcwd()
163     os.chdir(dirpath)
164     try:
165         buildpath = os.path.join(dirpath, 'build')
166         if not os.path.exists(buildpath):
167             os.makedirs(buildpath)
168         srcpath = download_and_extract(buildpath, packagedir, pkg, args)
169         patch(path, srcpath, pkg, args)
170         compile(path, srcpath, pkg, args)
171         package_files(buildpath, srcpath, pkg, args)
172     finally:
173         os.chdir(orig_path)
174 
175 
176 def parse_args():
177     parser = argparse.ArgumentParser('Build a pyodide package.')
178     parser.add_argument(
179         'package', type=str, nargs=1,
180         help="Path to meta.yaml package description")
181     parser.add_argument(
182         '--cflags', type=str, nargs='?', default=common.DEFAULTCFLAGS,
183         help='Extra compiling flags')
184     parser.add_argument(
185         '--ldflags', type=str, nargs='?', default=common.DEFAULTLDFLAGS,
186         help='Extra linking flags')
187     parser.add_argument(
188         '--host', type=str, nargs='?', default=common.HOSTPYTHON,
189         help='The path to the host Python installation')
190     parser.add_argument(
191         '--target', type=str, nargs='?', default=common.TARGETPYTHON,
192         help='The path to the target Python installation')
193     return parser.parse_args()
194 
195 
196 def main(args):
197     path = os.path.abspath(args.package[0])
198     build_package(path, args)
199 
200 
201 if __name__ == '__main__':
202     args = parse_args()
203     main(args)
204
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/tools/buildpkg.py b/tools/buildpkg.py
--- a/tools/buildpkg.py
+++ b/tools/buildpkg.py
@@ -144,7 +144,8 @@
         '--js-output={}'.format(os.path.join(buildpath, name + '.js')),
         '--export-name=pyodide',
         '--exclude', '*.wasm.pre',
-        '--exclude', '__pycache__'], check=True)
+        '--exclude', '__pycache__',
+        '--use-preload-plugins'], check=True)
     subprocess.run([
         'uglifyjs',
         os.path.join(buildpath, name + '.js'),

{"golden_diff": "diff --git a/tools/buildpkg.py b/tools/buildpkg.py\n--- a/tools/buildpkg.py\n+++ b/tools/buildpkg.py\n@@ -144,7 +144,8 @@\n         '--js-output={}'.format(os.path.join(buildpath, name + '.js')),\n         '--export-name=pyodide',\n         '--exclude', '*.wasm.pre',\n-        '--exclude', '__pycache__'], check=True)\n+        '--exclude', '__pycache__',\n+        '--use-preload-plugins'], check=True)\n     subprocess.run([\n         'uglifyjs',\n         os.path.join(buildpath, name + '.js'),\n", "issue": "Make work on Chrome\n\nMake work on Chrome\n\n", "before_files": [{"content": "#!/usr/bin/env python3\n\n\"\"\"\nBuilds a Pyodide package.\n\"\"\"\n\nimport argparse\nimport hashlib\nimport os\nimport shutil\nimport subprocess\n\n\nimport common\n\n\nROOTDIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef check_checksum(path, pkg):\n    \"\"\"\n    Checks that a tarball matches the checksum in the package metadata.\n    \"\"\"\n    if 'md5' not in pkg['source']:\n        return\n    checksum = pkg['source']['md5']\n    CHUNK_SIZE = 1 << 16\n    h = hashlib.md5()\n    with open(path, 'rb') as fd:\n        while True:\n            chunk = fd.read(CHUNK_SIZE)\n            h.update(chunk)\n            if len(chunk) < CHUNK_SIZE:\n                break\n    if h.hexdigest() != checksum:\n        raise ValueError(\"Invalid checksum\")\n\n\ndef download_and_extract(buildpath, packagedir, pkg, args):\n    tarballpath = os.path.join(\n        buildpath, os.path.basename(pkg['source']['url']))\n    if not os.path.isfile(tarballpath):\n        subprocess.run([\n            'wget', '-q', '-O', tarballpath, pkg['source']['url']\n        ], check=True)\n        check_checksum(tarballpath, pkg)\n    srcpath = os.path.join(buildpath, packagedir)\n    if not os.path.isdir(srcpath):\n        shutil.unpack_archive(tarballpath, buildpath)\n    return srcpath\n\n\ndef patch(path, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(srcpath, '.patched')):\n        return\n\n    # Apply all of the patches\n    orig_dir = os.getcwd()\n    pkgdir = os.path.abspath(os.path.dirname(path))\n    os.chdir(srcpath)\n    try:\n        for patch in pkg['source'].get('patches', []):\n            subprocess.run([\n                'patch', '-p1', '--binary', '-i', os.path.join(pkgdir, patch)\n            ], check=True)\n    finally:\n        os.chdir(orig_dir)\n\n    # Add any extra files\n    for src, dst in pkg['source'].get('extras', []):\n        shutil.copyfile(os.path.join(pkgdir, src), os.path.join(srcpath, dst))\n\n    with open(os.path.join(srcpath, '.patched'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef get_libdir(srcpath, args):\n    # Get the name of the build/lib.XXX directory that distutils wrote its\n    # output to\n    slug = subprocess.check_output([\n        os.path.join(args.host, 'bin', 'python3'),\n        '-c',\n        'import sysconfig, sys; '\n        'print(\"{}-{}.{}\".format('\n        'sysconfig.get_platform(), '\n        'sys.version_info[0], '\n        'sys.version_info[1]))']).decode('ascii').strip()\n    purelib = os.path.join(srcpath, 'build', 'lib')\n    if os.path.isdir(purelib):\n        libdir = purelib\n    else:\n        libdir = os.path.join(srcpath, 'build', 'lib.' + slug)\n    return libdir\n\n\ndef compile(path, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(srcpath, '.built')):\n        return\n\n    orig_dir = os.getcwd()\n    os.chdir(srcpath)\n    try:\n        subprocess.run([\n            os.path.join(args.host, 'bin', 'python3'),\n            os.path.join(ROOTDIR, 'pywasmcross'),\n            '--cflags',\n            args.cflags + ' ' +\n            pkg.get('build', {}).get('cflags', ''),\n            '--ldflags',\n            args.ldflags + ' ' +\n            pkg.get('build', {}).get('ldflags', ''),\n            '--host', args.host,\n            '--target', args.target], check=True)\n    finally:\n        os.chdir(orig_dir)\n\n    post = pkg.get('build', {}).get('post')\n    if post is not None:\n        libdir = get_libdir(srcpath, args)\n        pkgdir = os.path.abspath(os.path.dirname(path))\n        env = {\n            'BUILD': libdir,\n            'PKGDIR': pkgdir\n        }\n        subprocess.run([\n            'bash', '-c', post], env=env, check=True)\n\n    with open(os.path.join(srcpath, '.built'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef package_files(buildpath, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(buildpath, '.packaged')):\n        return\n\n    name = pkg['package']['name']\n    libdir = get_libdir(srcpath, args)\n    subprocess.run([\n        'python2',\n        os.path.join(os.environ['EMSCRIPTEN'], 'tools', 'file_packager.py'),\n        os.path.join(buildpath, name + '.data'),\n        '--preload',\n        '{}@/lib/python3.6/site-packages'.format(libdir),\n        '--js-output={}'.format(os.path.join(buildpath, name + '.js')),\n        '--export-name=pyodide',\n        '--exclude', '*.wasm.pre',\n        '--exclude', '__pycache__'], check=True)\n    subprocess.run([\n        'uglifyjs',\n        os.path.join(buildpath, name + '.js'),\n        '-o',\n        os.path.join(buildpath, name + '.js')], check=True)\n\n    with open(os.path.join(buildpath, '.packaged'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef build_package(path, args):\n    pkg = common.parse_package(path)\n    packagedir = pkg['package']['name'] + '-' + pkg['package']['version']\n    dirpath = os.path.dirname(path)\n    orig_path = os.getcwd()\n    os.chdir(dirpath)\n    try:\n        buildpath = os.path.join(dirpath, 'build')\n        if not os.path.exists(buildpath):\n            os.makedirs(buildpath)\n        srcpath = download_and_extract(buildpath, packagedir, pkg, args)\n        patch(path, srcpath, pkg, args)\n        compile(path, srcpath, pkg, args)\n        package_files(buildpath, srcpath, pkg, args)\n    finally:\n        os.chdir(orig_path)\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser('Build a pyodide package.')\n    parser.add_argument(\n        'package', type=str, nargs=1,\n        help=\"Path to meta.yaml package description\")\n    parser.add_argument(\n        '--cflags', type=str, nargs='?', default=common.DEFAULTCFLAGS,\n        help='Extra compiling flags')\n    parser.add_argument(\n        '--ldflags', type=str, nargs='?', default=common.DEFAULTLDFLAGS,\n        help='Extra linking flags')\n    parser.add_argument(\n        '--host', type=str, nargs='?', default=common.HOSTPYTHON,\n        help='The path to the host Python installation')\n    parser.add_argument(\n        '--target', type=str, nargs='?', default=common.TARGETPYTHON,\n        help='The path to the target Python installation')\n    return parser.parse_args()\n\n\ndef main(args):\n    path = os.path.abspath(args.package[0])\n    build_package(path, args)\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "tools/buildpkg.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n\n\"\"\"\nBuilds a Pyodide package.\n\"\"\"\n\nimport argparse\nimport hashlib\nimport os\nimport shutil\nimport subprocess\n\n\nimport common\n\n\nROOTDIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef check_checksum(path, pkg):\n    \"\"\"\n    Checks that a tarball matches the checksum in the package metadata.\n    \"\"\"\n    if 'md5' not in pkg['source']:\n        return\n    checksum = pkg['source']['md5']\n    CHUNK_SIZE = 1 << 16\n    h = hashlib.md5()\n    with open(path, 'rb') as fd:\n        while True:\n            chunk = fd.read(CHUNK_SIZE)\n            h.update(chunk)\n            if len(chunk) < CHUNK_SIZE:\n                break\n    if h.hexdigest() != checksum:\n        raise ValueError(\"Invalid checksum\")\n\n\ndef download_and_extract(buildpath, packagedir, pkg, args):\n    tarballpath = os.path.join(\n        buildpath, os.path.basename(pkg['source']['url']))\n    if not os.path.isfile(tarballpath):\n        subprocess.run([\n            'wget', '-q', '-O', tarballpath, pkg['source']['url']\n        ], check=True)\n        check_checksum(tarballpath, pkg)\n    srcpath = os.path.join(buildpath, packagedir)\n    if not os.path.isdir(srcpath):\n        shutil.unpack_archive(tarballpath, buildpath)\n    return srcpath\n\n\ndef patch(path, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(srcpath, '.patched')):\n        return\n\n    # Apply all of the patches\n    orig_dir = os.getcwd()\n    pkgdir = os.path.abspath(os.path.dirname(path))\n    os.chdir(srcpath)\n    try:\n        for patch in pkg['source'].get('patches', []):\n            subprocess.run([\n                'patch', '-p1', '--binary', '-i', os.path.join(pkgdir, patch)\n            ], check=True)\n    finally:\n        os.chdir(orig_dir)\n\n    # Add any extra files\n    for src, dst in pkg['source'].get('extras', []):\n        shutil.copyfile(os.path.join(pkgdir, src), os.path.join(srcpath, dst))\n\n    with open(os.path.join(srcpath, '.patched'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef get_libdir(srcpath, args):\n    # Get the name of the build/lib.XXX directory that distutils wrote its\n    # output to\n    slug = subprocess.check_output([\n        os.path.join(args.host, 'bin', 'python3'),\n        '-c',\n        'import sysconfig, sys; '\n        'print(\"{}-{}.{}\".format('\n        'sysconfig.get_platform(), '\n        'sys.version_info[0], '\n        'sys.version_info[1]))']).decode('ascii').strip()\n    purelib = os.path.join(srcpath, 'build', 'lib')\n    if os.path.isdir(purelib):\n        libdir = purelib\n    else:\n        libdir = os.path.join(srcpath, 'build', 'lib.' + slug)\n    return libdir\n\n\ndef compile(path, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(srcpath, '.built')):\n        return\n\n    orig_dir = os.getcwd()\n    os.chdir(srcpath)\n    try:\n        subprocess.run([\n            os.path.join(args.host, 'bin', 'python3'),\n            os.path.join(ROOTDIR, 'pywasmcross'),\n            '--cflags',\n            args.cflags + ' ' +\n            pkg.get('build', {}).get('cflags', ''),\n            '--ldflags',\n            args.ldflags + ' ' +\n            pkg.get('build', {}).get('ldflags', ''),\n            '--host', args.host,\n            '--target', args.target], check=True)\n    finally:\n        os.chdir(orig_dir)\n\n    post = pkg.get('build', {}).get('post')\n    if post is not None:\n        libdir = get_libdir(srcpath, args)\n        pkgdir = os.path.abspath(os.path.dirname(path))\n        env = {\n            'BUILD': libdir,\n            'PKGDIR': pkgdir\n        }\n        subprocess.run([\n            'bash', '-c', post], env=env, check=True)\n\n    with open(os.path.join(srcpath, '.built'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef package_files(buildpath, srcpath, pkg, args):\n    if os.path.isfile(os.path.join(buildpath, '.packaged')):\n        return\n\n    name = pkg['package']['name']\n    libdir = get_libdir(srcpath, args)\n    subprocess.run([\n        'python2',\n        os.path.join(os.environ['EMSCRIPTEN'], 'tools', 'file_packager.py'),\n        os.path.join(buildpath, name + '.data'),\n        '--preload',\n        '{}@/lib/python3.6/site-packages'.format(libdir),\n        '--js-output={}'.format(os.path.join(buildpath, name + '.js')),\n        '--export-name=pyodide',\n        '--exclude', '*.wasm.pre',\n        '--exclude', '__pycache__',\n        '--use-preload-plugins'], check=True)\n    subprocess.run([\n        'uglifyjs',\n        os.path.join(buildpath, name + '.js'),\n        '-o',\n        os.path.join(buildpath, name + '.js')], check=True)\n\n    with open(os.path.join(buildpath, '.packaged'), 'wb') as fd:\n        fd.write(b'\\n')\n\n\ndef build_package(path, args):\n    pkg = common.parse_package(path)\n    packagedir = pkg['package']['name'] + '-' + pkg['package']['version']\n    dirpath = os.path.dirname(path)\n    orig_path = os.getcwd()\n    os.chdir(dirpath)\n    try:\n        buildpath = os.path.join(dirpath, 'build')\n        if not os.path.exists(buildpath):\n            os.makedirs(buildpath)\n        srcpath = download_and_extract(buildpath, packagedir, pkg, args)\n        patch(path, srcpath, pkg, args)\n        compile(path, srcpath, pkg, args)\n        package_files(buildpath, srcpath, pkg, args)\n    finally:\n        os.chdir(orig_path)\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser('Build a pyodide package.')\n    parser.add_argument(\n        'package', type=str, nargs=1,\n        help=\"Path to meta.yaml package description\")\n    parser.add_argument(\n        '--cflags', type=str, nargs='?', default=common.DEFAULTCFLAGS,\n        help='Extra compiling flags')\n    parser.add_argument(\n        '--ldflags', type=str, nargs='?', default=common.DEFAULTLDFLAGS,\n        help='Extra linking flags')\n    parser.add_argument(\n        '--host', type=str, nargs='?', default=common.HOSTPYTHON,\n        help='The path to the host Python installation')\n    parser.add_argument(\n        '--target', type=str, nargs='?', default=common.TARGETPYTHON,\n        help='The path to the target Python installation')\n    return parser.parse_args()\n\n\ndef main(args):\n    path = os.path.abspath(args.package[0])\n    build_package(path, args)\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "tools/buildpkg.py"}]}