We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Incorrect OSError raised when redirecting to NUL on Windows
Reproducible for both Python 3.6 and 3.7. I did not test against older versions.

Tested on the Click 6.x series. Windows 10, Build 17134.

Steps to reproduce:

```python
# t.py
import click

@click.command()
def main():
    click.echo('run')

if __name__ == '__main__':
    main()
```

```
> python t.py
run

> python t.py >NUL
Traceback (most recent call last):
  File "t.py", line 10, in <module>
    main()
  File ".venv\lib\site-packages\click\core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File ".venv\lib\site-packages\click\core.py", line 697, in main
    rv = self.invoke(ctx)
  File ".venv\lib\site-packages\click\core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File ".venv\lib\site-packages\click\core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "t.py", line 6, in main
    click.echo('run')
  File ".venv\lib\site-packages\click\utils.py", line 259, in echo
    file.write(message)
  File ".venv\lib\site-packages\click\_winconsole.py", line 180, in write
    return self._text_stream.write(x)
  File ".venv\lib\site-packages\click\_winconsole.py", line 164, in write
    raise OSError(self._get_error_message(GetLastError()))
OSError: Windows error 1
```

I believe the problem is that Click tries to be helpful, and raises an error when there are not bytes written when there should be. This is, however, exactly what is expected to happen when you redirect things to `NUL` on Windows.

Curiously, however, Windows seems to act a little differently for stderr. `2>NUL` works as expected.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `click/_winconsole.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # This module is based on the excellent work by Adam Bartoš who
3 # provided a lot of what went into the implementation here in
4 # the discussion to issue1602 in the Python bug tracker.
5 #
6 # There are some general differences in regards to how this works
7 # compared to the original patches as we do not need to patch
8 # the entire interpreter but just work in our little world of
9 # echo and prmopt.
10 
11 import io
12 import os
13 import sys
14 import zlib
15 import time
16 import ctypes
17 import msvcrt
18 from ._compat import _NonClosingTextIOWrapper, text_type, PY2
19 from ctypes import byref, POINTER, c_int, c_char, c_char_p, \
20      c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE
21 try:
22     from ctypes import pythonapi
23     PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
24     PyBuffer_Release = pythonapi.PyBuffer_Release
25 except ImportError:
26     pythonapi = None
27 from ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE
28 
29 
30 c_ssize_p = POINTER(c_ssize_t)
31 
32 kernel32 = windll.kernel32
33 GetStdHandle = kernel32.GetStdHandle
34 ReadConsoleW = kernel32.ReadConsoleW
35 WriteConsoleW = kernel32.WriteConsoleW
36 GetLastError = kernel32.GetLastError
37 GetCommandLineW = WINFUNCTYPE(LPWSTR)(
38     ('GetCommandLineW', windll.kernel32))
39 CommandLineToArgvW = WINFUNCTYPE(
40     POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
41         ('CommandLineToArgvW', windll.shell32))
42 
43 
44 STDIN_HANDLE = GetStdHandle(-10)
45 STDOUT_HANDLE = GetStdHandle(-11)
46 STDERR_HANDLE = GetStdHandle(-12)
47 
48 
49 PyBUF_SIMPLE = 0
50 PyBUF_WRITABLE = 1
51 
52 ERROR_SUCCESS = 0
53 ERROR_NOT_ENOUGH_MEMORY = 8
54 ERROR_OPERATION_ABORTED = 995
55 
56 STDIN_FILENO = 0
57 STDOUT_FILENO = 1
58 STDERR_FILENO = 2
59 
60 EOF = b'\x1a'
61 MAX_BYTES_WRITTEN = 32767
62 
63 
64 class Py_buffer(ctypes.Structure):
65     _fields_ = [
66         ('buf', c_void_p),
67         ('obj', py_object),
68         ('len', c_ssize_t),
69         ('itemsize', c_ssize_t),
70         ('readonly', c_int),
71         ('ndim', c_int),
72         ('format', c_char_p),
73         ('shape', c_ssize_p),
74         ('strides', c_ssize_p),
75         ('suboffsets', c_ssize_p),
76         ('internal', c_void_p)
77     ]
78 
79     if PY2:
80         _fields_.insert(-1, ('smalltable', c_ssize_t * 2))
81 
82 
83 # On PyPy we cannot get buffers so our ability to operate here is
84 # serverly limited.
85 if pythonapi is None:
86     get_buffer = None
87 else:
88     def get_buffer(obj, writable=False):
89         buf = Py_buffer()
90         flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
91         PyObject_GetBuffer(py_object(obj), byref(buf), flags)
92         try:
93             buffer_type = c_char * buf.len
94             return buffer_type.from_address(buf.buf)
95         finally:
96             PyBuffer_Release(byref(buf))
97 
98 
99 class _WindowsConsoleRawIOBase(io.RawIOBase):
100 
101     def __init__(self, handle):
102         self.handle = handle
103 
104     def isatty(self):
105         io.RawIOBase.isatty(self)
106         return True
107 
108 
109 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
110 
111     def readable(self):
112         return True
113 
114     def readinto(self, b):
115         bytes_to_be_read = len(b)
116         if not bytes_to_be_read:
117             return 0
118         elif bytes_to_be_read % 2:
119             raise ValueError('cannot read odd number of bytes from '
120                              'UTF-16-LE encoded console')
121 
122         buffer = get_buffer(b, writable=True)
123         code_units_to_be_read = bytes_to_be_read // 2
124         code_units_read = c_ulong()
125 
126         rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,
127                           byref(code_units_read), None)
128         if GetLastError() == ERROR_OPERATION_ABORTED:
129             # wait for KeyboardInterrupt
130             time.sleep(0.1)
131         if not rv:
132             raise OSError('Windows error: %s' % GetLastError())
133 
134         if buffer[0] == EOF:
135             return 0
136         return 2 * code_units_read.value
137 
138 
139 class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
140 
141     def writable(self):
142         return True
143 
144     @staticmethod
145     def _get_error_message(errno):
146         if errno == ERROR_SUCCESS:
147             return 'ERROR_SUCCESS'
148         elif errno == ERROR_NOT_ENOUGH_MEMORY:
149             return 'ERROR_NOT_ENOUGH_MEMORY'
150         return 'Windows error %s' % errno
151 
152     def write(self, b):
153         bytes_to_be_written = len(b)
154         buf = get_buffer(b)
155         code_units_to_be_written = min(bytes_to_be_written,
156                                        MAX_BYTES_WRITTEN) // 2
157         code_units_written = c_ulong()
158 
159         WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,
160                       byref(code_units_written), None)
161         bytes_written = 2 * code_units_written.value
162 
163         if bytes_written == 0 and bytes_to_be_written > 0:
164             raise OSError(self._get_error_message(GetLastError()))
165         return bytes_written
166 
167 
168 class ConsoleStream(object):
169 
170     def __init__(self, text_stream, byte_stream):
171         self._text_stream = text_stream
172         self.buffer = byte_stream
173 
174     @property
175     def name(self):
176         return self.buffer.name
177 
178     def write(self, x):
179         if isinstance(x, text_type):
180             return self._text_stream.write(x)
181         try:
182             self.flush()
183         except Exception:
184             pass
185         return self.buffer.write(x)
186 
187     def writelines(self, lines):
188         for line in lines:
189             self.write(line)
190 
191     def __getattr__(self, name):
192         return getattr(self._text_stream, name)
193 
194     def isatty(self):
195         return self.buffer.isatty()
196 
197     def __repr__(self):
198         return '<ConsoleStream name=%r encoding=%r>' % (
199             self.name,
200             self.encoding,
201         )
202 
203 
204 class WindowsChunkedWriter(object):
205     """
206     Wraps a stream (such as stdout), acting as a transparent proxy for all
207     attribute access apart from method 'write()' which we wrap to write in
208     limited chunks due to a Windows limitation on binary console streams.
209     """
210     def __init__(self, wrapped):
211         # double-underscore everything to prevent clashes with names of
212         # attributes on the wrapped stream object.
213         self.__wrapped = wrapped
214 
215     def __getattr__(self, name):
216         return getattr(self.__wrapped, name)
217 
218     def write(self, text):
219         total_to_write = len(text)
220         written = 0
221 
222         while written < total_to_write:
223             to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)
224             self.__wrapped.write(text[written:written+to_write])
225             written += to_write
226 
227 
228 _wrapped_std_streams = set()
229 
230 
231 def _wrap_std_stream(name):
232     # Python 2 & Windows 7 and below
233     if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:
234         setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))
235         _wrapped_std_streams.add(name)
236 
237 
238 def _get_text_stdin(buffer_stream):
239     text_stream = _NonClosingTextIOWrapper(
240         io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
241         'utf-16-le', 'strict', line_buffering=True)
242     return ConsoleStream(text_stream, buffer_stream)
243 
244 
245 def _get_text_stdout(buffer_stream):
246     text_stream = _NonClosingTextIOWrapper(
247         io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
248         'utf-16-le', 'strict', line_buffering=True)
249     return ConsoleStream(text_stream, buffer_stream)
250 
251 
252 def _get_text_stderr(buffer_stream):
253     text_stream = _NonClosingTextIOWrapper(
254         io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
255         'utf-16-le', 'strict', line_buffering=True)
256     return ConsoleStream(text_stream, buffer_stream)
257 
258 
259 if PY2:
260     def _hash_py_argv():
261         return zlib.crc32('\x00'.join(sys.argv[1:]))
262 
263     _initial_argv_hash = _hash_py_argv()
264 
265     def _get_windows_argv():
266         argc = c_int(0)
267         argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
268         argv = [argv_unicode[i] for i in range(0, argc.value)]
269 
270         if not hasattr(sys, 'frozen'):
271             argv = argv[1:]
272             while len(argv) > 0:
273                 arg = argv[0]
274                 if not arg.startswith('-') or arg == '-':
275                     break
276                 argv = argv[1:]
277                 if arg.startswith(('-c', '-m')):
278                     break
279 
280         return argv[1:]
281 
282 
283 _stream_factories = {
284     0: _get_text_stdin,
285     1: _get_text_stdout,
286     2: _get_text_stderr,
287 }
288 
289 
290 def _get_windows_console_stream(f, encoding, errors):
291     if get_buffer is not None and \
292        encoding in ('utf-16-le', None) \
293        and errors in ('strict', None) and \
294        hasattr(f, 'isatty') and f.isatty():
295         func = _stream_factories.get(f.fileno())
296         if func is not None:
297             if not PY2:
298                 f = getattr(f, 'buffer', None)
299                 if f is None:
300                     return None
301             else:
302                 # If we are on Python 2 we need to set the stream that we
303                 # deal with to binary mode as otherwise the exercise if a
304                 # bit moot.  The same problems apply as for
305                 # get_binary_stdin and friends from _compat.
306                 msvcrt.setmode(f.fileno(), os.O_BINARY)
307             return func(f)
308
```
--- 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/click/_winconsole.py b/click/_winconsole.py
--- a/click/_winconsole.py
+++ b/click/_winconsole.py
@@ -24,7 +24,7 @@
     PyBuffer_Release = pythonapi.PyBuffer_Release
 except ImportError:
     pythonapi = None
-from ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE
+from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE
 
 
 c_ssize_p = POINTER(c_ssize_t)
@@ -33,6 +33,7 @@
 GetStdHandle = kernel32.GetStdHandle
 ReadConsoleW = kernel32.ReadConsoleW
 WriteConsoleW = kernel32.WriteConsoleW
+GetConsoleMode = kernel32.GetConsoleMode
 GetLastError = kernel32.GetLastError
 GetCommandLineW = WINFUNCTYPE(LPWSTR)(
     ('GetCommandLineW', windll.kernel32))
@@ -287,11 +288,24 @@
 }
 
 
+def _is_console(f):
+    if not hasattr(f, 'fileno'):
+        return False
+
+    try:
+        fileno = f.fileno()
+    except OSError:
+        return False
+
+    handle = msvcrt.get_osfhandle(fileno)
+    return bool(GetConsoleMode(handle, byref(DWORD())))
+
+
 def _get_windows_console_stream(f, encoding, errors):
     if get_buffer is not None and \
        encoding in ('utf-16-le', None) \
        and errors in ('strict', None) and \
-       hasattr(f, 'isatty') and f.isatty():
+       _is_console(f):
         func = _stream_factories.get(f.fileno())
         if func is not None:
             if not PY2:

{"golden_diff": "diff --git a/click/_winconsole.py b/click/_winconsole.py\n--- a/click/_winconsole.py\n+++ b/click/_winconsole.py\n@@ -24,7 +24,7 @@\n     PyBuffer_Release = pythonapi.PyBuffer_Release\n except ImportError:\n     pythonapi = None\n-from ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE\n+from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE\n \n \n c_ssize_p = POINTER(c_ssize_t)\n@@ -33,6 +33,7 @@\n GetStdHandle = kernel32.GetStdHandle\n ReadConsoleW = kernel32.ReadConsoleW\n WriteConsoleW = kernel32.WriteConsoleW\n+GetConsoleMode = kernel32.GetConsoleMode\n GetLastError = kernel32.GetLastError\n GetCommandLineW = WINFUNCTYPE(LPWSTR)(\n     ('GetCommandLineW', windll.kernel32))\n@@ -287,11 +288,24 @@\n }\n \n \n+def _is_console(f):\n+    if not hasattr(f, 'fileno'):\n+        return False\n+\n+    try:\n+        fileno = f.fileno()\n+    except OSError:\n+        return False\n+\n+    handle = msvcrt.get_osfhandle(fileno)\n+    return bool(GetConsoleMode(handle, byref(DWORD())))\n+\n+\n def _get_windows_console_stream(f, encoding, errors):\n     if get_buffer is not None and \\\n        encoding in ('utf-16-le', None) \\\n        and errors in ('strict', None) and \\\n-       hasattr(f, 'isatty') and f.isatty():\n+       _is_console(f):\n         func = _stream_factories.get(f.fileno())\n         if func is not None:\n             if not PY2:\n", "issue": "Incorrect OSError raised when redirecting to NUL on Windows\nReproducible for both Python 3.6 and 3.7. I did not test against older versions.\r\n\r\nTested on the Click 6.x series. Windows 10, Build 17134.\r\n\r\nSteps to reproduce:\r\n\r\n```python\r\n# t.py\r\nimport click\r\n\r\n@click.command()\r\ndef main():\r\n    click.echo('run')\r\n\r\nif __name__ == '__main__':\r\n    main()\r\n```\r\n\r\n```\r\n> python t.py\r\nrun\r\n\r\n> python t.py >NUL\r\nTraceback (most recent call last):\r\n  File \"t.py\", line 10, in <module>\r\n    main()\r\n  File \".venv\\lib\\site-packages\\click\\core.py\", line 722, in __call__\r\n    return self.main(*args, **kwargs)\r\n  File \".venv\\lib\\site-packages\\click\\core.py\", line 697, in main\r\n    rv = self.invoke(ctx)\r\n  File \".venv\\lib\\site-packages\\click\\core.py\", line 895, in invoke\r\n    return ctx.invoke(self.callback, **ctx.params)\r\n  File \".venv\\lib\\site-packages\\click\\core.py\", line 535, in invoke\r\n    return callback(*args, **kwargs)\r\n  File \"t.py\", line 6, in main\r\n    click.echo('run')\r\n  File \".venv\\lib\\site-packages\\click\\utils.py\", line 259, in echo\r\n    file.write(message)\r\n  File \".venv\\lib\\site-packages\\click\\_winconsole.py\", line 180, in write\r\n    return self._text_stream.write(x)\r\n  File \".venv\\lib\\site-packages\\click\\_winconsole.py\", line 164, in write\r\n    raise OSError(self._get_error_message(GetLastError()))\r\nOSError: Windows error 1\r\n```\r\n\r\nI believe the problem is that Click tries to be helpful, and raises an error when there are not bytes written when there should be. This is, however, exactly what is expected to happen when you redirect things to `NUL` on Windows.\r\n\r\nCuriously, however, Windows seems to act a little differently for stderr. `2>NUL` works as expected.\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# This module is based on the excellent work by Adam Barto\u0161 who\n# provided a lot of what went into the implementation here in\n# the discussion to issue1602 in the Python bug tracker.\n#\n# There are some general differences in regards to how this works\n# compared to the original patches as we do not need to patch\n# the entire interpreter but just work in our little world of\n# echo and prmopt.\n\nimport io\nimport os\nimport sys\nimport zlib\nimport time\nimport ctypes\nimport msvcrt\nfrom ._compat import _NonClosingTextIOWrapper, text_type, PY2\nfrom ctypes import byref, POINTER, c_int, c_char, c_char_p, \\\n     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE\ntry:\n    from ctypes import pythonapi\n    PyObject_GetBuffer = pythonapi.PyObject_GetBuffer\n    PyBuffer_Release = pythonapi.PyBuffer_Release\nexcept ImportError:\n    pythonapi = None\nfrom ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE\n\n\nc_ssize_p = POINTER(c_ssize_t)\n\nkernel32 = windll.kernel32\nGetStdHandle = kernel32.GetStdHandle\nReadConsoleW = kernel32.ReadConsoleW\nWriteConsoleW = kernel32.WriteConsoleW\nGetLastError = kernel32.GetLastError\nGetCommandLineW = WINFUNCTYPE(LPWSTR)(\n    ('GetCommandLineW', windll.kernel32))\nCommandLineToArgvW = WINFUNCTYPE(\n    POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(\n        ('CommandLineToArgvW', windll.shell32))\n\n\nSTDIN_HANDLE = GetStdHandle(-10)\nSTDOUT_HANDLE = GetStdHandle(-11)\nSTDERR_HANDLE = GetStdHandle(-12)\n\n\nPyBUF_SIMPLE = 0\nPyBUF_WRITABLE = 1\n\nERROR_SUCCESS = 0\nERROR_NOT_ENOUGH_MEMORY = 8\nERROR_OPERATION_ABORTED = 995\n\nSTDIN_FILENO = 0\nSTDOUT_FILENO = 1\nSTDERR_FILENO = 2\n\nEOF = b'\\x1a'\nMAX_BYTES_WRITTEN = 32767\n\n\nclass Py_buffer(ctypes.Structure):\n    _fields_ = [\n        ('buf', c_void_p),\n        ('obj', py_object),\n        ('len', c_ssize_t),\n        ('itemsize', c_ssize_t),\n        ('readonly', c_int),\n        ('ndim', c_int),\n        ('format', c_char_p),\n        ('shape', c_ssize_p),\n        ('strides', c_ssize_p),\n        ('suboffsets', c_ssize_p),\n        ('internal', c_void_p)\n    ]\n\n    if PY2:\n        _fields_.insert(-1, ('smalltable', c_ssize_t * 2))\n\n\n# On PyPy we cannot get buffers so our ability to operate here is\n# serverly limited.\nif pythonapi is None:\n    get_buffer = None\nelse:\n    def get_buffer(obj, writable=False):\n        buf = Py_buffer()\n        flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE\n        PyObject_GetBuffer(py_object(obj), byref(buf), flags)\n        try:\n            buffer_type = c_char * buf.len\n            return buffer_type.from_address(buf.buf)\n        finally:\n            PyBuffer_Release(byref(buf))\n\n\nclass _WindowsConsoleRawIOBase(io.RawIOBase):\n\n    def __init__(self, handle):\n        self.handle = handle\n\n    def isatty(self):\n        io.RawIOBase.isatty(self)\n        return True\n\n\nclass _WindowsConsoleReader(_WindowsConsoleRawIOBase):\n\n    def readable(self):\n        return True\n\n    def readinto(self, b):\n        bytes_to_be_read = len(b)\n        if not bytes_to_be_read:\n            return 0\n        elif bytes_to_be_read % 2:\n            raise ValueError('cannot read odd number of bytes from '\n                             'UTF-16-LE encoded console')\n\n        buffer = get_buffer(b, writable=True)\n        code_units_to_be_read = bytes_to_be_read // 2\n        code_units_read = c_ulong()\n\n        rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,\n                          byref(code_units_read), None)\n        if GetLastError() == ERROR_OPERATION_ABORTED:\n            # wait for KeyboardInterrupt\n            time.sleep(0.1)\n        if not rv:\n            raise OSError('Windows error: %s' % GetLastError())\n\n        if buffer[0] == EOF:\n            return 0\n        return 2 * code_units_read.value\n\n\nclass _WindowsConsoleWriter(_WindowsConsoleRawIOBase):\n\n    def writable(self):\n        return True\n\n    @staticmethod\n    def _get_error_message(errno):\n        if errno == ERROR_SUCCESS:\n            return 'ERROR_SUCCESS'\n        elif errno == ERROR_NOT_ENOUGH_MEMORY:\n            return 'ERROR_NOT_ENOUGH_MEMORY'\n        return 'Windows error %s' % errno\n\n    def write(self, b):\n        bytes_to_be_written = len(b)\n        buf = get_buffer(b)\n        code_units_to_be_written = min(bytes_to_be_written,\n                                       MAX_BYTES_WRITTEN) // 2\n        code_units_written = c_ulong()\n\n        WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,\n                      byref(code_units_written), None)\n        bytes_written = 2 * code_units_written.value\n\n        if bytes_written == 0 and bytes_to_be_written > 0:\n            raise OSError(self._get_error_message(GetLastError()))\n        return bytes_written\n\n\nclass ConsoleStream(object):\n\n    def __init__(self, text_stream, byte_stream):\n        self._text_stream = text_stream\n        self.buffer = byte_stream\n\n    @property\n    def name(self):\n        return self.buffer.name\n\n    def write(self, x):\n        if isinstance(x, text_type):\n            return self._text_stream.write(x)\n        try:\n            self.flush()\n        except Exception:\n            pass\n        return self.buffer.write(x)\n\n    def writelines(self, lines):\n        for line in lines:\n            self.write(line)\n\n    def __getattr__(self, name):\n        return getattr(self._text_stream, name)\n\n    def isatty(self):\n        return self.buffer.isatty()\n\n    def __repr__(self):\n        return '<ConsoleStream name=%r encoding=%r>' % (\n            self.name,\n            self.encoding,\n        )\n\n\nclass WindowsChunkedWriter(object):\n    \"\"\"\n    Wraps a stream (such as stdout), acting as a transparent proxy for all\n    attribute access apart from method 'write()' which we wrap to write in\n    limited chunks due to a Windows limitation on binary console streams.\n    \"\"\"\n    def __init__(self, wrapped):\n        # double-underscore everything to prevent clashes with names of\n        # attributes on the wrapped stream object.\n        self.__wrapped = wrapped\n\n    def __getattr__(self, name):\n        return getattr(self.__wrapped, name)\n\n    def write(self, text):\n        total_to_write = len(text)\n        written = 0\n\n        while written < total_to_write:\n            to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)\n            self.__wrapped.write(text[written:written+to_write])\n            written += to_write\n\n\n_wrapped_std_streams = set()\n\n\ndef _wrap_std_stream(name):\n    # Python 2 & Windows 7 and below\n    if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:\n        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))\n        _wrapped_std_streams.add(name)\n\n\ndef _get_text_stdin(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stdout(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stderr(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\nif PY2:\n    def _hash_py_argv():\n        return zlib.crc32('\\x00'.join(sys.argv[1:]))\n\n    _initial_argv_hash = _hash_py_argv()\n\n    def _get_windows_argv():\n        argc = c_int(0)\n        argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\n        argv = [argv_unicode[i] for i in range(0, argc.value)]\n\n        if not hasattr(sys, 'frozen'):\n            argv = argv[1:]\n            while len(argv) > 0:\n                arg = argv[0]\n                if not arg.startswith('-') or arg == '-':\n                    break\n                argv = argv[1:]\n                if arg.startswith(('-c', '-m')):\n                    break\n\n        return argv[1:]\n\n\n_stream_factories = {\n    0: _get_text_stdin,\n    1: _get_text_stdout,\n    2: _get_text_stderr,\n}\n\n\ndef _get_windows_console_stream(f, encoding, errors):\n    if get_buffer is not None and \\\n       encoding in ('utf-16-le', None) \\\n       and errors in ('strict', None) and \\\n       hasattr(f, 'isatty') and f.isatty():\n        func = _stream_factories.get(f.fileno())\n        if func is not None:\n            if not PY2:\n                f = getattr(f, 'buffer', None)\n                if f is None:\n                    return None\n            else:\n                # If we are on Python 2 we need to set the stream that we\n                # deal with to binary mode as otherwise the exercise if a\n                # bit moot.  The same problems apply as for\n                # get_binary_stdin and friends from _compat.\n                msvcrt.setmode(f.fileno(), os.O_BINARY)\n            return func(f)\n", "path": "click/_winconsole.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# This module is based on the excellent work by Adam Barto\u0161 who\n# provided a lot of what went into the implementation here in\n# the discussion to issue1602 in the Python bug tracker.\n#\n# There are some general differences in regards to how this works\n# compared to the original patches as we do not need to patch\n# the entire interpreter but just work in our little world of\n# echo and prmopt.\n\nimport io\nimport os\nimport sys\nimport zlib\nimport time\nimport ctypes\nimport msvcrt\nfrom ._compat import _NonClosingTextIOWrapper, text_type, PY2\nfrom ctypes import byref, POINTER, c_int, c_char, c_char_p, \\\n     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE\ntry:\n    from ctypes import pythonapi\n    PyObject_GetBuffer = pythonapi.PyObject_GetBuffer\n    PyBuffer_Release = pythonapi.PyBuffer_Release\nexcept ImportError:\n    pythonapi = None\nfrom ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE\n\n\nc_ssize_p = POINTER(c_ssize_t)\n\nkernel32 = windll.kernel32\nGetStdHandle = kernel32.GetStdHandle\nReadConsoleW = kernel32.ReadConsoleW\nWriteConsoleW = kernel32.WriteConsoleW\nGetConsoleMode = kernel32.GetConsoleMode\nGetLastError = kernel32.GetLastError\nGetCommandLineW = WINFUNCTYPE(LPWSTR)(\n    ('GetCommandLineW', windll.kernel32))\nCommandLineToArgvW = WINFUNCTYPE(\n    POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(\n        ('CommandLineToArgvW', windll.shell32))\n\n\nSTDIN_HANDLE = GetStdHandle(-10)\nSTDOUT_HANDLE = GetStdHandle(-11)\nSTDERR_HANDLE = GetStdHandle(-12)\n\n\nPyBUF_SIMPLE = 0\nPyBUF_WRITABLE = 1\n\nERROR_SUCCESS = 0\nERROR_NOT_ENOUGH_MEMORY = 8\nERROR_OPERATION_ABORTED = 995\n\nSTDIN_FILENO = 0\nSTDOUT_FILENO = 1\nSTDERR_FILENO = 2\n\nEOF = b'\\x1a'\nMAX_BYTES_WRITTEN = 32767\n\n\nclass Py_buffer(ctypes.Structure):\n    _fields_ = [\n        ('buf', c_void_p),\n        ('obj', py_object),\n        ('len', c_ssize_t),\n        ('itemsize', c_ssize_t),\n        ('readonly', c_int),\n        ('ndim', c_int),\n        ('format', c_char_p),\n        ('shape', c_ssize_p),\n        ('strides', c_ssize_p),\n        ('suboffsets', c_ssize_p),\n        ('internal', c_void_p)\n    ]\n\n    if PY2:\n        _fields_.insert(-1, ('smalltable', c_ssize_t * 2))\n\n\n# On PyPy we cannot get buffers so our ability to operate here is\n# serverly limited.\nif pythonapi is None:\n    get_buffer = None\nelse:\n    def get_buffer(obj, writable=False):\n        buf = Py_buffer()\n        flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE\n        PyObject_GetBuffer(py_object(obj), byref(buf), flags)\n        try:\n            buffer_type = c_char * buf.len\n            return buffer_type.from_address(buf.buf)\n        finally:\n            PyBuffer_Release(byref(buf))\n\n\nclass _WindowsConsoleRawIOBase(io.RawIOBase):\n\n    def __init__(self, handle):\n        self.handle = handle\n\n    def isatty(self):\n        io.RawIOBase.isatty(self)\n        return True\n\n\nclass _WindowsConsoleReader(_WindowsConsoleRawIOBase):\n\n    def readable(self):\n        return True\n\n    def readinto(self, b):\n        bytes_to_be_read = len(b)\n        if not bytes_to_be_read:\n            return 0\n        elif bytes_to_be_read % 2:\n            raise ValueError('cannot read odd number of bytes from '\n                             'UTF-16-LE encoded console')\n\n        buffer = get_buffer(b, writable=True)\n        code_units_to_be_read = bytes_to_be_read // 2\n        code_units_read = c_ulong()\n\n        rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,\n                          byref(code_units_read), None)\n        if GetLastError() == ERROR_OPERATION_ABORTED:\n            # wait for KeyboardInterrupt\n            time.sleep(0.1)\n        if not rv:\n            raise OSError('Windows error: %s' % GetLastError())\n\n        if buffer[0] == EOF:\n            return 0\n        return 2 * code_units_read.value\n\n\nclass _WindowsConsoleWriter(_WindowsConsoleRawIOBase):\n\n    def writable(self):\n        return True\n\n    @staticmethod\n    def _get_error_message(errno):\n        if errno == ERROR_SUCCESS:\n            return 'ERROR_SUCCESS'\n        elif errno == ERROR_NOT_ENOUGH_MEMORY:\n            return 'ERROR_NOT_ENOUGH_MEMORY'\n        return 'Windows error %s' % errno\n\n    def write(self, b):\n        bytes_to_be_written = len(b)\n        buf = get_buffer(b)\n        code_units_to_be_written = min(bytes_to_be_written,\n                                       MAX_BYTES_WRITTEN) // 2\n        code_units_written = c_ulong()\n\n        WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,\n                      byref(code_units_written), None)\n        bytes_written = 2 * code_units_written.value\n\n        if bytes_written == 0 and bytes_to_be_written > 0:\n            raise OSError(self._get_error_message(GetLastError()))\n        return bytes_written\n\n\nclass ConsoleStream(object):\n\n    def __init__(self, text_stream, byte_stream):\n        self._text_stream = text_stream\n        self.buffer = byte_stream\n\n    @property\n    def name(self):\n        return self.buffer.name\n\n    def write(self, x):\n        if isinstance(x, text_type):\n            return self._text_stream.write(x)\n        try:\n            self.flush()\n        except Exception:\n            pass\n        return self.buffer.write(x)\n\n    def writelines(self, lines):\n        for line in lines:\n            self.write(line)\n\n    def __getattr__(self, name):\n        return getattr(self._text_stream, name)\n\n    def isatty(self):\n        return self.buffer.isatty()\n\n    def __repr__(self):\n        return '<ConsoleStream name=%r encoding=%r>' % (\n            self.name,\n            self.encoding,\n        )\n\n\nclass WindowsChunkedWriter(object):\n    \"\"\"\n    Wraps a stream (such as stdout), acting as a transparent proxy for all\n    attribute access apart from method 'write()' which we wrap to write in\n    limited chunks due to a Windows limitation on binary console streams.\n    \"\"\"\n    def __init__(self, wrapped):\n        # double-underscore everything to prevent clashes with names of\n        # attributes on the wrapped stream object.\n        self.__wrapped = wrapped\n\n    def __getattr__(self, name):\n        return getattr(self.__wrapped, name)\n\n    def write(self, text):\n        total_to_write = len(text)\n        written = 0\n\n        while written < total_to_write:\n            to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)\n            self.__wrapped.write(text[written:written+to_write])\n            written += to_write\n\n\n_wrapped_std_streams = set()\n\n\ndef _wrap_std_stream(name):\n    # Python 2 & Windows 7 and below\n    if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:\n        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))\n        _wrapped_std_streams.add(name)\n\n\ndef _get_text_stdin(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stdout(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stderr(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\nif PY2:\n    def _hash_py_argv():\n        return zlib.crc32('\\x00'.join(sys.argv[1:]))\n\n    _initial_argv_hash = _hash_py_argv()\n\n    def _get_windows_argv():\n        argc = c_int(0)\n        argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\n        argv = [argv_unicode[i] for i in range(0, argc.value)]\n\n        if not hasattr(sys, 'frozen'):\n            argv = argv[1:]\n            while len(argv) > 0:\n                arg = argv[0]\n                if not arg.startswith('-') or arg == '-':\n                    break\n                argv = argv[1:]\n                if arg.startswith(('-c', '-m')):\n                    break\n\n        return argv[1:]\n\n\n_stream_factories = {\n    0: _get_text_stdin,\n    1: _get_text_stdout,\n    2: _get_text_stderr,\n}\n\n\ndef _is_console(f):\n    if not hasattr(f, 'fileno'):\n        return False\n\n    try:\n        fileno = f.fileno()\n    except OSError:\n        return False\n\n    handle = msvcrt.get_osfhandle(fileno)\n    return bool(GetConsoleMode(handle, byref(DWORD())))\n\n\ndef _get_windows_console_stream(f, encoding, errors):\n    if get_buffer is not None and \\\n       encoding in ('utf-16-le', None) \\\n       and errors in ('strict', None) and \\\n       _is_console(f):\n        func = _stream_factories.get(f.fileno())\n        if func is not None:\n            if not PY2:\n                f = getattr(f, 'buffer', None)\n                if f is None:\n                    return None\n            else:\n                # If we are on Python 2 we need to set the stream that we\n                # deal with to binary mode as otherwise the exercise if a\n                # bit moot.  The same problems apply as for\n                # get_binary_stdin and friends from _compat.\n                msvcrt.setmode(f.fileno(), os.O_BINARY)\n            return func(f)\n", "path": "click/_winconsole.py"}]}