We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Hy Ignores PYTHONDONTWRITEBYTECODE
When `PYTHONDONTWRITEBYTECODE` is set in the environment (for example using `export PYTHONDONTWRITEBYTECODE=1`) Hy should not generate `.pyc`.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `hy/importer.py`
Content:
```
1 # Copyright 2017 the authors.
2 # This file is part of Hy, which is free software licensed under the Expat
3 # license. See the LICENSE.
4 
5 from hy.compiler import hy_compile, HyTypeError
6 from hy.models import HyObject, replace_hy_obj
7 from hy.lex import tokenize, LexException
8 from hy.errors import HyIOError
9 
10 from io import open
11 import re
12 import marshal
13 import struct
14 import imp
15 import sys
16 import ast
17 import os
18 import __future__
19 
20 from hy._compat import PY3, PY34, MAGIC, builtins, long_type, wr_long
21 from hy._compat import string_types
22 
23 
24 def ast_compile(ast, filename, mode):
25     """Compile AST.
26     Like Python's compile, but with some special flags."""
27     flags = (__future__.CO_FUTURE_DIVISION |
28              __future__.CO_FUTURE_PRINT_FUNCTION)
29     return compile(ast, filename, mode, flags)
30 
31 
32 def import_buffer_to_hst(buf):
33     """Import content from buf and return a Hy AST."""
34     return tokenize(buf + "\n")
35 
36 
37 def import_file_to_hst(fpath):
38     """Import content from fpath and return a Hy AST."""
39     try:
40         with open(fpath, 'r', encoding='utf-8') as f:
41             return import_buffer_to_hst(f.read())
42     except IOError as e:
43         raise HyIOError(e.errno, e.strerror, e.filename)
44 
45 
46 def import_buffer_to_ast(buf, module_name):
47     """ Import content from buf and return a Python AST."""
48     return hy_compile(import_buffer_to_hst(buf), module_name)
49 
50 
51 def import_file_to_ast(fpath, module_name):
52     """Import content from fpath and return a Python AST."""
53     return hy_compile(import_file_to_hst(fpath), module_name)
54 
55 
56 def import_file_to_module(module_name, fpath, loader=None):
57     """Import Hy source from fpath and put it into a Python module.
58 
59     If there's an up-to-date byte-compiled version of this module, load that
60     instead. Otherwise, byte-compile the module once we're done loading it, if
61     we can.
62 
63     Return the module."""
64 
65     module = None
66 
67     bytecode_path = get_bytecode_path(fpath)
68     try:
69         source_mtime = int(os.stat(fpath).st_mtime)
70         with open(bytecode_path, 'rb') as bc_f:
71             # The first 4 bytes are the magic number for the version of Python
72             # that compiled this bytecode.
73             bytecode_magic = bc_f.read(4)
74             # The next 4 bytes, interpreted as a little-endian 32-bit integer,
75             # are the mtime of the corresponding source file.
76             bytecode_mtime, = struct.unpack('<i', bc_f.read(4))
77     except (IOError, OSError):
78         pass
79     else:
80         if bytecode_magic == MAGIC and bytecode_mtime >= source_mtime:
81             # It's a cache hit. Load the byte-compiled version.
82             if PY3:
83                 # As of Python 3.6, imp.load_compiled still exists, but it's
84                 # deprecated. So let's use SourcelessFileLoader instead.
85                 from importlib.machinery import SourcelessFileLoader
86                 module = (SourcelessFileLoader(module_name, bytecode_path).
87                           load_module(module_name))
88             else:
89                 module = imp.load_compiled(module_name, bytecode_path)
90 
91     if not module:
92         # It's a cache miss, so load from source.
93         sys.modules[module_name] = None
94         try:
95             _ast = import_file_to_ast(fpath, module_name)
96             module = imp.new_module(module_name)
97             module.__file__ = fpath
98             code = ast_compile(_ast, fpath, "exec")
99             try:
100                 write_code_as_pyc(fpath, code)
101             except (IOError, OSError):
102                 # We failed to save the bytecode, probably because of a
103                 # permissions issue. The user only asked to import the
104                 # file, so don't bug them about it.
105                 pass
106             eval(code, module.__dict__)
107         except (HyTypeError, LexException) as e:
108             if e.source is None:
109                 with open(fpath, 'rt') as fp:
110                     e.source = fp.read()
111                 e.filename = fpath
112             raise
113         except Exception:
114             sys.modules.pop(module_name, None)
115             raise
116         sys.modules[module_name] = module
117         module.__name__ = module_name
118 
119     module.__file__ = fpath
120     if loader:
121         module.__loader__ = loader
122     if is_package(module_name):
123         module.__path__ = []
124         module.__package__ = module_name
125     else:
126         module.__package__ = module_name.rpartition('.')[0]
127 
128     return module
129 
130 
131 def import_buffer_to_module(module_name, buf):
132     try:
133         _ast = import_buffer_to_ast(buf, module_name)
134         mod = imp.new_module(module_name)
135         eval(ast_compile(_ast, "", "exec"), mod.__dict__)
136     except (HyTypeError, LexException) as e:
137         if e.source is None:
138             e.source = buf
139             e.filename = '<stdin>'
140         raise
141     return mod
142 
143 
144 def hy_eval(hytree, namespace, module_name, ast_callback=None):
145     foo = HyObject()
146     foo.start_line = 0
147     foo.end_line = 0
148     foo.start_column = 0
149     foo.end_column = 0
150     replace_hy_obj(hytree, foo)
151 
152     if not isinstance(module_name, string_types):
153         raise HyTypeError(foo, "Module name must be a string")
154 
155     _ast, expr = hy_compile(hytree, module_name, get_expr=True)
156 
157     # Spoof the positions in the generated ast...
158     for node in ast.walk(_ast):
159         node.lineno = 1
160         node.col_offset = 1
161 
162     for node in ast.walk(expr):
163         node.lineno = 1
164         node.col_offset = 1
165 
166     if ast_callback:
167         ast_callback(_ast, expr)
168 
169     if not isinstance(namespace, dict):
170         raise HyTypeError(foo, "Globals must be a dictionary")
171 
172     # Two-step eval: eval() the body of the exec call
173     eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)
174 
175     # Then eval the expression context and return that
176     return eval(ast_compile(expr, "<eval>", "eval"), namespace)
177 
178 
179 def write_hy_as_pyc(fname):
180     _ast = import_file_to_ast(fname,
181                               os.path.basename(os.path.splitext(fname)[0]))
182     code = ast_compile(_ast, fname, "exec")
183     write_code_as_pyc(fname, code)
184 
185 
186 def write_code_as_pyc(fname, code):
187     st = os.stat(fname)
188     timestamp = long_type(st.st_mtime)
189 
190     cfile = get_bytecode_path(fname)
191     try:
192         os.makedirs(os.path.dirname(cfile))
193     except (IOError, OSError):
194         pass
195 
196     with builtins.open(cfile, 'wb') as fc:
197         fc.write(MAGIC)
198         wr_long(fc, timestamp)
199         if PY3:
200             wr_long(fc, st.st_size)
201         marshal.dump(code, fc)
202 
203 
204 class MetaLoader(object):
205     def __init__(self, path):
206         self.path = path
207 
208     def load_module(self, fullname):
209         if fullname in sys.modules:
210             return sys.modules[fullname]
211 
212         if not self.path:
213             return
214 
215         return import_file_to_module(fullname, self.path, self)
216 
217 
218 class MetaImporter(object):
219     def find_on_path(self, fullname):
220         fls = ["%s/__init__.hy", "%s.hy"]
221         dirpath = "/".join(fullname.split("."))
222 
223         for pth in sys.path:
224             pth = os.path.abspath(pth)
225             for fp in fls:
226                 composed_path = fp % ("%s/%s" % (pth, dirpath))
227                 if os.path.exists(composed_path):
228                     return composed_path
229 
230     def find_module(self, fullname, path=None):
231         path = self.find_on_path(fullname)
232         if path:
233             return MetaLoader(path)
234 
235 
236 sys.meta_path.insert(0, MetaImporter())
237 sys.path.insert(0, "")
238 
239 
240 def is_package(module_name):
241     mpath = os.path.join(*module_name.split("."))
242     for path in map(os.path.abspath, sys.path):
243         if os.path.exists(os.path.join(path, mpath, "__init__.hy")):
244             return True
245     return False
246 
247 
248 def get_bytecode_path(source_path):
249     if PY34:
250         import importlib.util
251         return importlib.util.cache_from_source(source_path)
252     elif hasattr(imp, "cache_from_source"):
253         return imp.cache_from_source(source_path)
254     else:
255         # If source_path has a file extension, replace it with ".pyc".
256         # Otherwise, just append ".pyc".
257         d, f = os.path.split(source_path)
258         return os.path.join(d, re.sub(r"(?:\.[^.]+)?\Z", ".pyc", f))
259
```
--- 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/hy/importer.py b/hy/importer.py
--- a/hy/importer.py
+++ b/hy/importer.py
@@ -96,13 +96,14 @@
             module = imp.new_module(module_name)
             module.__file__ = fpath
             code = ast_compile(_ast, fpath, "exec")
-            try:
-                write_code_as_pyc(fpath, code)
-            except (IOError, OSError):
-                # We failed to save the bytecode, probably because of a
-                # permissions issue. The user only asked to import the
-                # file, so don't bug them about it.
-                pass
+            if not os.environ.get('PYTHONDONTWRITEBYTECODE'):
+                try:
+                    write_code_as_pyc(fpath, code)
+                except (IOError, OSError):
+                    # We failed to save the bytecode, probably because of a
+                    # permissions issue. The user only asked to import the
+                    # file, so don't bug them about it.
+                    pass
             eval(code, module.__dict__)
         except (HyTypeError, LexException) as e:
             if e.source is None:

{"golden_diff": "diff --git a/hy/importer.py b/hy/importer.py\n--- a/hy/importer.py\n+++ b/hy/importer.py\n@@ -96,13 +96,14 @@\n             module = imp.new_module(module_name)\n             module.__file__ = fpath\n             code = ast_compile(_ast, fpath, \"exec\")\n-            try:\n-                write_code_as_pyc(fpath, code)\n-            except (IOError, OSError):\n-                # We failed to save the bytecode, probably because of a\n-                # permissions issue. The user only asked to import the\n-                # file, so don't bug them about it.\n-                pass\n+            if not os.environ.get('PYTHONDONTWRITEBYTECODE'):\n+                try:\n+                    write_code_as_pyc(fpath, code)\n+                except (IOError, OSError):\n+                    # We failed to save the bytecode, probably because of a\n+                    # permissions issue. The user only asked to import the\n+                    # file, so don't bug them about it.\n+                    pass\n             eval(code, module.__dict__)\n         except (HyTypeError, LexException) as e:\n             if e.source is None:\n", "issue": "Hy Ignores PYTHONDONTWRITEBYTECODE\nWhen `PYTHONDONTWRITEBYTECODE` is set in the environment (for example using `export PYTHONDONTWRITEBYTECODE=1`) Hy should not generate `.pyc`.\n", "before_files": [{"content": "# Copyright 2017 the authors.\n# This file is part of Hy, which is free software licensed under the Expat\n# license. See the LICENSE.\n\nfrom hy.compiler import hy_compile, HyTypeError\nfrom hy.models import HyObject, replace_hy_obj\nfrom hy.lex import tokenize, LexException\nfrom hy.errors import HyIOError\n\nfrom io import open\nimport re\nimport marshal\nimport struct\nimport imp\nimport sys\nimport ast\nimport os\nimport __future__\n\nfrom hy._compat import PY3, PY34, MAGIC, builtins, long_type, wr_long\nfrom hy._compat import string_types\n\n\ndef ast_compile(ast, filename, mode):\n    \"\"\"Compile AST.\n    Like Python's compile, but with some special flags.\"\"\"\n    flags = (__future__.CO_FUTURE_DIVISION |\n             __future__.CO_FUTURE_PRINT_FUNCTION)\n    return compile(ast, filename, mode, flags)\n\n\ndef import_buffer_to_hst(buf):\n    \"\"\"Import content from buf and return a Hy AST.\"\"\"\n    return tokenize(buf + \"\\n\")\n\n\ndef import_file_to_hst(fpath):\n    \"\"\"Import content from fpath and return a Hy AST.\"\"\"\n    try:\n        with open(fpath, 'r', encoding='utf-8') as f:\n            return import_buffer_to_hst(f.read())\n    except IOError as e:\n        raise HyIOError(e.errno, e.strerror, e.filename)\n\n\ndef import_buffer_to_ast(buf, module_name):\n    \"\"\" Import content from buf and return a Python AST.\"\"\"\n    return hy_compile(import_buffer_to_hst(buf), module_name)\n\n\ndef import_file_to_ast(fpath, module_name):\n    \"\"\"Import content from fpath and return a Python AST.\"\"\"\n    return hy_compile(import_file_to_hst(fpath), module_name)\n\n\ndef import_file_to_module(module_name, fpath, loader=None):\n    \"\"\"Import Hy source from fpath and put it into a Python module.\n\n    If there's an up-to-date byte-compiled version of this module, load that\n    instead. Otherwise, byte-compile the module once we're done loading it, if\n    we can.\n\n    Return the module.\"\"\"\n\n    module = None\n\n    bytecode_path = get_bytecode_path(fpath)\n    try:\n        source_mtime = int(os.stat(fpath).st_mtime)\n        with open(bytecode_path, 'rb') as bc_f:\n            # The first 4 bytes are the magic number for the version of Python\n            # that compiled this bytecode.\n            bytecode_magic = bc_f.read(4)\n            # The next 4 bytes, interpreted as a little-endian 32-bit integer,\n            # are the mtime of the corresponding source file.\n            bytecode_mtime, = struct.unpack('<i', bc_f.read(4))\n    except (IOError, OSError):\n        pass\n    else:\n        if bytecode_magic == MAGIC and bytecode_mtime >= source_mtime:\n            # It's a cache hit. Load the byte-compiled version.\n            if PY3:\n                # As of Python 3.6, imp.load_compiled still exists, but it's\n                # deprecated. So let's use SourcelessFileLoader instead.\n                from importlib.machinery import SourcelessFileLoader\n                module = (SourcelessFileLoader(module_name, bytecode_path).\n                          load_module(module_name))\n            else:\n                module = imp.load_compiled(module_name, bytecode_path)\n\n    if not module:\n        # It's a cache miss, so load from source.\n        sys.modules[module_name] = None\n        try:\n            _ast = import_file_to_ast(fpath, module_name)\n            module = imp.new_module(module_name)\n            module.__file__ = fpath\n            code = ast_compile(_ast, fpath, \"exec\")\n            try:\n                write_code_as_pyc(fpath, code)\n            except (IOError, OSError):\n                # We failed to save the bytecode, probably because of a\n                # permissions issue. The user only asked to import the\n                # file, so don't bug them about it.\n                pass\n            eval(code, module.__dict__)\n        except (HyTypeError, LexException) as e:\n            if e.source is None:\n                with open(fpath, 'rt') as fp:\n                    e.source = fp.read()\n                e.filename = fpath\n            raise\n        except Exception:\n            sys.modules.pop(module_name, None)\n            raise\n        sys.modules[module_name] = module\n        module.__name__ = module_name\n\n    module.__file__ = fpath\n    if loader:\n        module.__loader__ = loader\n    if is_package(module_name):\n        module.__path__ = []\n        module.__package__ = module_name\n    else:\n        module.__package__ = module_name.rpartition('.')[0]\n\n    return module\n\n\ndef import_buffer_to_module(module_name, buf):\n    try:\n        _ast = import_buffer_to_ast(buf, module_name)\n        mod = imp.new_module(module_name)\n        eval(ast_compile(_ast, \"\", \"exec\"), mod.__dict__)\n    except (HyTypeError, LexException) as e:\n        if e.source is None:\n            e.source = buf\n            e.filename = '<stdin>'\n        raise\n    return mod\n\n\ndef hy_eval(hytree, namespace, module_name, ast_callback=None):\n    foo = HyObject()\n    foo.start_line = 0\n    foo.end_line = 0\n    foo.start_column = 0\n    foo.end_column = 0\n    replace_hy_obj(hytree, foo)\n\n    if not isinstance(module_name, string_types):\n        raise HyTypeError(foo, \"Module name must be a string\")\n\n    _ast, expr = hy_compile(hytree, module_name, get_expr=True)\n\n    # Spoof the positions in the generated ast...\n    for node in ast.walk(_ast):\n        node.lineno = 1\n        node.col_offset = 1\n\n    for node in ast.walk(expr):\n        node.lineno = 1\n        node.col_offset = 1\n\n    if ast_callback:\n        ast_callback(_ast, expr)\n\n    if not isinstance(namespace, dict):\n        raise HyTypeError(foo, \"Globals must be a dictionary\")\n\n    # Two-step eval: eval() the body of the exec call\n    eval(ast_compile(_ast, \"<eval_body>\", \"exec\"), namespace)\n\n    # Then eval the expression context and return that\n    return eval(ast_compile(expr, \"<eval>\", \"eval\"), namespace)\n\n\ndef write_hy_as_pyc(fname):\n    _ast = import_file_to_ast(fname,\n                              os.path.basename(os.path.splitext(fname)[0]))\n    code = ast_compile(_ast, fname, \"exec\")\n    write_code_as_pyc(fname, code)\n\n\ndef write_code_as_pyc(fname, code):\n    st = os.stat(fname)\n    timestamp = long_type(st.st_mtime)\n\n    cfile = get_bytecode_path(fname)\n    try:\n        os.makedirs(os.path.dirname(cfile))\n    except (IOError, OSError):\n        pass\n\n    with builtins.open(cfile, 'wb') as fc:\n        fc.write(MAGIC)\n        wr_long(fc, timestamp)\n        if PY3:\n            wr_long(fc, st.st_size)\n        marshal.dump(code, fc)\n\n\nclass MetaLoader(object):\n    def __init__(self, path):\n        self.path = path\n\n    def load_module(self, fullname):\n        if fullname in sys.modules:\n            return sys.modules[fullname]\n\n        if not self.path:\n            return\n\n        return import_file_to_module(fullname, self.path, self)\n\n\nclass MetaImporter(object):\n    def find_on_path(self, fullname):\n        fls = [\"%s/__init__.hy\", \"%s.hy\"]\n        dirpath = \"/\".join(fullname.split(\".\"))\n\n        for pth in sys.path:\n            pth = os.path.abspath(pth)\n            for fp in fls:\n                composed_path = fp % (\"%s/%s\" % (pth, dirpath))\n                if os.path.exists(composed_path):\n                    return composed_path\n\n    def find_module(self, fullname, path=None):\n        path = self.find_on_path(fullname)\n        if path:\n            return MetaLoader(path)\n\n\nsys.meta_path.insert(0, MetaImporter())\nsys.path.insert(0, \"\")\n\n\ndef is_package(module_name):\n    mpath = os.path.join(*module_name.split(\".\"))\n    for path in map(os.path.abspath, sys.path):\n        if os.path.exists(os.path.join(path, mpath, \"__init__.hy\")):\n            return True\n    return False\n\n\ndef get_bytecode_path(source_path):\n    if PY34:\n        import importlib.util\n        return importlib.util.cache_from_source(source_path)\n    elif hasattr(imp, \"cache_from_source\"):\n        return imp.cache_from_source(source_path)\n    else:\n        # If source_path has a file extension, replace it with \".pyc\".\n        # Otherwise, just append \".pyc\".\n        d, f = os.path.split(source_path)\n        return os.path.join(d, re.sub(r\"(?:\\.[^.]+)?\\Z\", \".pyc\", f))\n", "path": "hy/importer.py"}], "after_files": [{"content": "# Copyright 2017 the authors.\n# This file is part of Hy, which is free software licensed under the Expat\n# license. See the LICENSE.\n\nfrom hy.compiler import hy_compile, HyTypeError\nfrom hy.models import HyObject, replace_hy_obj\nfrom hy.lex import tokenize, LexException\nfrom hy.errors import HyIOError\n\nfrom io import open\nimport re\nimport marshal\nimport struct\nimport imp\nimport sys\nimport ast\nimport os\nimport __future__\n\nfrom hy._compat import PY3, PY34, MAGIC, builtins, long_type, wr_long\nfrom hy._compat import string_types\n\n\ndef ast_compile(ast, filename, mode):\n    \"\"\"Compile AST.\n    Like Python's compile, but with some special flags.\"\"\"\n    flags = (__future__.CO_FUTURE_DIVISION |\n             __future__.CO_FUTURE_PRINT_FUNCTION)\n    return compile(ast, filename, mode, flags)\n\n\ndef import_buffer_to_hst(buf):\n    \"\"\"Import content from buf and return a Hy AST.\"\"\"\n    return tokenize(buf + \"\\n\")\n\n\ndef import_file_to_hst(fpath):\n    \"\"\"Import content from fpath and return a Hy AST.\"\"\"\n    try:\n        with open(fpath, 'r', encoding='utf-8') as f:\n            return import_buffer_to_hst(f.read())\n    except IOError as e:\n        raise HyIOError(e.errno, e.strerror, e.filename)\n\n\ndef import_buffer_to_ast(buf, module_name):\n    \"\"\" Import content from buf and return a Python AST.\"\"\"\n    return hy_compile(import_buffer_to_hst(buf), module_name)\n\n\ndef import_file_to_ast(fpath, module_name):\n    \"\"\"Import content from fpath and return a Python AST.\"\"\"\n    return hy_compile(import_file_to_hst(fpath), module_name)\n\n\ndef import_file_to_module(module_name, fpath, loader=None):\n    \"\"\"Import Hy source from fpath and put it into a Python module.\n\n    If there's an up-to-date byte-compiled version of this module, load that\n    instead. Otherwise, byte-compile the module once we're done loading it, if\n    we can.\n\n    Return the module.\"\"\"\n\n    module = None\n\n    bytecode_path = get_bytecode_path(fpath)\n    try:\n        source_mtime = int(os.stat(fpath).st_mtime)\n        with open(bytecode_path, 'rb') as bc_f:\n            # The first 4 bytes are the magic number for the version of Python\n            # that compiled this bytecode.\n            bytecode_magic = bc_f.read(4)\n            # The next 4 bytes, interpreted as a little-endian 32-bit integer,\n            # are the mtime of the corresponding source file.\n            bytecode_mtime, = struct.unpack('<i', bc_f.read(4))\n    except (IOError, OSError):\n        pass\n    else:\n        if bytecode_magic == MAGIC and bytecode_mtime >= source_mtime:\n            # It's a cache hit. Load the byte-compiled version.\n            if PY3:\n                # As of Python 3.6, imp.load_compiled still exists, but it's\n                # deprecated. So let's use SourcelessFileLoader instead.\n                from importlib.machinery import SourcelessFileLoader\n                module = (SourcelessFileLoader(module_name, bytecode_path).\n                          load_module(module_name))\n            else:\n                module = imp.load_compiled(module_name, bytecode_path)\n\n    if not module:\n        # It's a cache miss, so load from source.\n        sys.modules[module_name] = None\n        try:\n            _ast = import_file_to_ast(fpath, module_name)\n            module = imp.new_module(module_name)\n            module.__file__ = fpath\n            code = ast_compile(_ast, fpath, \"exec\")\n            if not os.environ.get('PYTHONDONTWRITEBYTECODE'):\n                try:\n                    write_code_as_pyc(fpath, code)\n                except (IOError, OSError):\n                    # We failed to save the bytecode, probably because of a\n                    # permissions issue. The user only asked to import the\n                    # file, so don't bug them about it.\n                    pass\n            eval(code, module.__dict__)\n        except (HyTypeError, LexException) as e:\n            if e.source is None:\n                with open(fpath, 'rt') as fp:\n                    e.source = fp.read()\n                e.filename = fpath\n            raise\n        except Exception:\n            sys.modules.pop(module_name, None)\n            raise\n        sys.modules[module_name] = module\n        module.__name__ = module_name\n\n    module.__file__ = fpath\n    if loader:\n        module.__loader__ = loader\n    if is_package(module_name):\n        module.__path__ = []\n        module.__package__ = module_name\n    else:\n        module.__package__ = module_name.rpartition('.')[0]\n\n    return module\n\n\ndef import_buffer_to_module(module_name, buf):\n    try:\n        _ast = import_buffer_to_ast(buf, module_name)\n        mod = imp.new_module(module_name)\n        eval(ast_compile(_ast, \"\", \"exec\"), mod.__dict__)\n    except (HyTypeError, LexException) as e:\n        if e.source is None:\n            e.source = buf\n            e.filename = '<stdin>'\n        raise\n    return mod\n\n\ndef hy_eval(hytree, namespace, module_name, ast_callback=None):\n    foo = HyObject()\n    foo.start_line = 0\n    foo.end_line = 0\n    foo.start_column = 0\n    foo.end_column = 0\n    replace_hy_obj(hytree, foo)\n\n    if not isinstance(module_name, string_types):\n        raise HyTypeError(foo, \"Module name must be a string\")\n\n    _ast, expr = hy_compile(hytree, module_name, get_expr=True)\n\n    # Spoof the positions in the generated ast...\n    for node in ast.walk(_ast):\n        node.lineno = 1\n        node.col_offset = 1\n\n    for node in ast.walk(expr):\n        node.lineno = 1\n        node.col_offset = 1\n\n    if ast_callback:\n        ast_callback(_ast, expr)\n\n    if not isinstance(namespace, dict):\n        raise HyTypeError(foo, \"Globals must be a dictionary\")\n\n    # Two-step eval: eval() the body of the exec call\n    eval(ast_compile(_ast, \"<eval_body>\", \"exec\"), namespace)\n\n    # Then eval the expression context and return that\n    return eval(ast_compile(expr, \"<eval>\", \"eval\"), namespace)\n\n\ndef write_hy_as_pyc(fname):\n    _ast = import_file_to_ast(fname,\n                              os.path.basename(os.path.splitext(fname)[0]))\n    code = ast_compile(_ast, fname, \"exec\")\n    write_code_as_pyc(fname, code)\n\n\ndef write_code_as_pyc(fname, code):\n    st = os.stat(fname)\n    timestamp = long_type(st.st_mtime)\n\n    cfile = get_bytecode_path(fname)\n    try:\n        os.makedirs(os.path.dirname(cfile))\n    except (IOError, OSError):\n        pass\n\n    with builtins.open(cfile, 'wb') as fc:\n        fc.write(MAGIC)\n        wr_long(fc, timestamp)\n        if PY3:\n            wr_long(fc, st.st_size)\n        marshal.dump(code, fc)\n\n\nclass MetaLoader(object):\n    def __init__(self, path):\n        self.path = path\n\n    def load_module(self, fullname):\n        if fullname in sys.modules:\n            return sys.modules[fullname]\n\n        if not self.path:\n            return\n\n        return import_file_to_module(fullname, self.path, self)\n\n\nclass MetaImporter(object):\n    def find_on_path(self, fullname):\n        fls = [\"%s/__init__.hy\", \"%s.hy\"]\n        dirpath = \"/\".join(fullname.split(\".\"))\n\n        for pth in sys.path:\n            pth = os.path.abspath(pth)\n            for fp in fls:\n                composed_path = fp % (\"%s/%s\" % (pth, dirpath))\n                if os.path.exists(composed_path):\n                    return composed_path\n\n    def find_module(self, fullname, path=None):\n        path = self.find_on_path(fullname)\n        if path:\n            return MetaLoader(path)\n\n\nsys.meta_path.insert(0, MetaImporter())\nsys.path.insert(0, \"\")\n\n\ndef is_package(module_name):\n    mpath = os.path.join(*module_name.split(\".\"))\n    for path in map(os.path.abspath, sys.path):\n        if os.path.exists(os.path.join(path, mpath, \"__init__.hy\")):\n            return True\n    return False\n\n\ndef get_bytecode_path(source_path):\n    if PY34:\n        import importlib.util\n        return importlib.util.cache_from_source(source_path)\n    elif hasattr(imp, \"cache_from_source\"):\n        return imp.cache_from_source(source_path)\n    else:\n        # If source_path has a file extension, replace it with \".pyc\".\n        # Otherwise, just append \".pyc\".\n        d, f = os.path.split(source_path)\n        return os.path.join(d, re.sub(r\"(?:\\.[^.]+)?\\Z\", \".pyc\", f))\n", "path": "hy/importer.py"}]}