Use context managers to open files

Inspired by d50a6ddc1b.
This commit is contained in:
Luflosi 2019-08-01 13:21:26 -05:00
parent 68f3b6fbeb
commit 5f855ce547
No known key found for this signature in database
GPG Key ID: 14140F703B7D8362
17 changed files with 161 additions and 139 deletions

View File

@ -107,7 +107,8 @@ features of the graphics protocol:
sys.stdout.flush() sys.stdout.flush()
cmd.clear() cmd.clear()
write_chunked({'a': 'T', 'f': 100}, open(sys.argv[-1], 'rb').read()) with open(sys.argv[-1], 'rb') as f:
write_chunked({'a': 'T', 'f': 100}, f.read())
Save this script as :file:`png.py`, then you can use it to display any PNG Save this script as :file:`png.py`, then you can use it to display any PNG

View File

@ -229,7 +229,8 @@ def script_launch():
def update_intaller_wrapper(): def update_intaller_wrapper():
# To run: python3 -c "import runpy; runpy.run_path('installer.py', run_name='update_wrapper')" installer.sh # To run: python3 -c "import runpy; runpy.run_path('installer.py', run_name='update_wrapper')" installer.sh
src = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
src = f.read().decode('utf-8')
wrapper = sys.argv[-1] wrapper = sys.argv[-1]
with open(wrapper, 'r+b') as f: with open(wrapper, 'r+b') as f:
raw = f.read().decode('utf-8') raw = f.read().decode('utf-8')

View File

@ -29,10 +29,12 @@ def get_data(fname, folder='UCD'):
bn = os.path.basename(url) bn = os.path.basename(url)
local = os.path.join('/tmp', bn) local = os.path.join('/tmp', bn)
if os.path.exists(local): if os.path.exists(local):
data = open(local, 'rb').read() with open(local, 'rb') as f:
data = f.read()
else: else:
data = urlopen(url).read() data = urlopen(url).read()
open(local, 'wb').write(data) with open(local, 'wb') as f:
f.write(data)
for line in data.decode('utf-8').splitlines(): for line in data.decode('utf-8').splitlines():
line = line.strip() line = line.strip()
if line and not line.startswith('#'): if line and not line.startswith('#'):
@ -166,21 +168,20 @@ def write_case(spec, p):
@contextmanager @contextmanager
def create_header(path, include_data_types=True): def create_header(path, include_data_types=True):
f = open(path, 'w') with open(path, 'w') as f:
p = partial(print, file=f) p = partial(print, file=f)
p('// unicode data, built from the unicode standard on:', date.today()) p('// unicode data, built from the unicode standard on:', date.today())
p('// see gen-wcwidth.py') p('// see gen-wcwidth.py')
if path.endswith('.h'): if path.endswith('.h'):
p('#pragma once') p('#pragma once')
if include_data_types: if include_data_types:
p('#include "data-types.h"\n') p('#include "data-types.h"\n')
p('START_ALLOW_CASE_RANGE') p('START_ALLOW_CASE_RANGE')
p() p()
yield p yield p
p() p()
if include_data_types: if include_data_types:
p('END_ALLOW_CASE_RANGE') p('END_ALLOW_CASE_RANGE')
f.close()
def gen_emoji(): def gen_emoji():
@ -282,7 +283,9 @@ def gen_ucd():
p('combining_type mark_for_codepoint(char_type c) {') p('combining_type mark_for_codepoint(char_type c) {')
rmap = codepoint_to_mark_map(p, mark_map) rmap = codepoint_to_mark_map(p, mark_map)
p('}\n') p('}\n')
expected = int(re.search(r'^#define VS15 (\d+)', open('kitty/unicode-data.h').read(), re.M).group(1)) with open('kitty/unicode-data.h') as f:
unicode_data = f.read()
expected = int(re.search(r'^#define VS15 (\d+)', unicode_data, re.M).group(1))
if rmap[0xfe0e] != expected: if rmap[0xfe0e] != expected:
raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format( raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format(
rmap[0xfe0e], rmap[0xfe0f] rmap[0xfe0e], rmap[0xfe0f]

View File

@ -38,7 +38,8 @@ def init_env(env, pkg_config, at_least_version, test_compile, module='x11'):
) )
else: else:
ans.ldpaths.extend('-lrt -lm -ldl'.split()) ans.ldpaths.extend('-lrt -lm -ldl'.split())
sinfo = json.load(open(os.path.join(base, 'source-info.json'))) with open(os.path.join(base, 'source-info.json')) as f:
sinfo = json.load(f)
module_sources = list(sinfo[module]['sources']) module_sources = list(sinfo[module]['sources'])
if module in ('x11', 'wayland'): if module in ('x11', 'wayland'):
remove = 'linux_joystick.c' if is_bsd else 'null_joystick.c' remove = 'linux_joystick.c' if is_bsd else 'null_joystick.c'
@ -157,7 +158,8 @@ class Function:
def generate_wrappers(glfw_header): def generate_wrappers(glfw_header):
src = open(glfw_header).read() with open(glfw_header) as f:
src = f.read()
functions = [] functions = []
first = None first = None
for m in re.finditer(r'^GLFWAPI\s+(.+[)]);\s*$', src, flags=re.MULTILINE): for m in re.finditer(r'^GLFWAPI\s+(.+[)]);\s*$', src, flags=re.MULTILINE):

View File

@ -249,7 +249,8 @@ class ImageManager:
cmd, standard_b64encode(rgba_path.encode(fsenc))) cmd, standard_b64encode(rgba_path.encode(fsenc)))
else: else:
import zlib import zlib
data = open(rgba_path, 'rb').read() with open(rgba_path, 'rb') as f:
data = f.read()
cmd['S'] = len(data) cmd['S'] = len(data)
data = zlib.compress(data) data = zlib.compress(data)
cmd['o'] = 'z' cmd['o'] = 'z'

View File

@ -30,14 +30,16 @@ if is_macos:
else: else:
def cmdline_of_process(pid): def cmdline_of_process(pid):
return list(filter(None, open('/proc/{}/cmdline'.format(pid), 'rb').read().decode('utf-8').split('\0'))) with open('/proc/{}/cmdline'.format(pid), 'rb') as f:
return list(filter(None, f.read().decode('utf-8').split('\0')))
def cwd_of_process(pid): def cwd_of_process(pid):
ans = '/proc/{}/cwd'.format(pid) ans = '/proc/{}/cwd'.format(pid)
return os.path.realpath(ans) return os.path.realpath(ans)
def _environ_of_process(pid): def _environ_of_process(pid):
return open('/proc/{}/environ'.format(pid), 'rb').read().decode('utf-8') with open('/proc/{}/environ'.format(pid), 'rb') as f:
return f.read().decode('utf-8')
def process_group_map(): def process_group_map():
ans = defaultdict(list) ans = defaultdict(list)
@ -47,7 +49,8 @@ else:
except Exception: except Exception:
continue continue
try: try:
raw = open('/proc/' + x + '/stat', 'rb').read().decode('utf-8') with open('/proc/' + x + '/stat', 'rb') as f:
raw = f.read().decode('utf-8')
except EnvironmentError: except EnvironmentError:
continue continue
try: try:

View File

@ -728,9 +728,11 @@ def create_opts(args, debug_config=False, accumulate_bad_lines=None):
import subprocess import subprocess
print(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip()) print(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip())
if os.path.exists('/etc/issue'): if os.path.exists('/etc/issue'):
print(open('/etc/issue', encoding='utf-8', errors='replace').read().strip()) with open('/etc/issue', encoding='utf-8', errors='replace') as f:
print(f.read().strip())
if os.path.exists('/etc/lsb-release'): if os.path.exists('/etc/lsb-release'):
print(open('/etc/lsb-release', encoding='utf-8', errors='replace').read().strip()) with open('/etc/lsb-release', encoding='utf-8', errors='replace') as f:
print(f.read().strip())
config = tuple(x for x in config if os.path.exists(x)) config = tuple(x for x in config if os.path.exists(x))
if config: if config:
print(green('Loaded config files:'), ', '.join(config)) print(green('Loaded config files:'), ', '.join(config))

View File

@ -157,7 +157,8 @@ def replay(raw):
def main(path): def main(path):
raw = open(path).read() with open(path) as f:
raw = f.read()
replay(raw) replay(raw)
with suppress(EOFError, KeyboardInterrupt): with suppress(EOFError, KeyboardInterrupt):
input() input()

View File

@ -177,12 +177,11 @@ def load_config(Options, defaults, parse_config, merge_configs, *paths, override
if not path: if not path:
continue continue
try: try:
f = open(path, encoding='utf-8', errors='replace') with open(path, encoding='utf-8', errors='replace') as f:
vals = parse_config(f)
except FileNotFoundError: except FileNotFoundError:
continue continue
with f: ans = merge_configs(ans, vals)
vals = parse_config(f)
ans = merge_configs(ans, vals)
if overrides is not None: if overrides is not None:
vals = parse_config(overrides) vals = parse_config(overrides)
ans = merge_configs(ans, vals) ans = merge_configs(ans, vals)

View File

@ -293,99 +293,99 @@ def generate_key_table():
# To run this, use: python3 . +runpy "from kitty.keys import *; generate_key_table()" # To run this, use: python3 . +runpy "from kitty.keys import *; generate_key_table()"
import os import os
from functools import partial from functools import partial
f = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') as f:
w = partial(print, file=f) w = partial(print, file=f)
w('// auto-generated from keys.py, do not edit!') w('// auto-generated from keys.py, do not edit!')
w('#pragma once') w('#pragma once')
w('#include <stddef.h>') w('#include <stddef.h>')
w('#include <stdint.h>') w('#include <stdint.h>')
w('#include <stdbool.h>') w('#include <stdbool.h>')
w('#include <limits.h>') w('#include <limits.h>')
number_of_keys = defines.GLFW_KEY_LAST + 1 number_of_keys = defines.GLFW_KEY_LAST + 1
w('// map glfw key numbers to 7-bit numbers for compact data storage') w('// map glfw key numbers to 7-bit numbers for compact data storage')
w('static const uint8_t key_map[%d] = {' % number_of_keys) w('static const uint8_t key_map[%d] = {' % number_of_keys)
key_count = 0 key_count = 0
def key_name(k): def key_name(k):
return k[len('GLFW_KEY_'):] return k[len('GLFW_KEY_'):]
keys = {v: k for k, v in vars(defines).items() if k.startswith('GLFW_KEY_') and k not in {'GLFW_KEY_LAST', 'GLFW_KEY_UNKNOWN'}} keys = {v: k for k, v in vars(defines).items() if k.startswith('GLFW_KEY_') and k not in {'GLFW_KEY_LAST', 'GLFW_KEY_UNKNOWN'}}
key_rmap = [] key_rmap = []
for i in range(number_of_keys): for i in range(number_of_keys):
k = keys.get(i) k = keys.get(i)
if k is None: if k is None:
w('UINT8_MAX,') w('UINT8_MAX,')
else:
w('%d, /* %s */' % (key_count, key_name(k)))
key_rmap.append(i)
key_count += 1
if key_count > 128:
raise OverflowError('Too many keys')
w('};\n')
w('static inline const char* key_name(int key) { switch(key) {')
for i in range(number_of_keys):
k = keys.get(i)
if k is not None:
w('case %d: return "%s";' % (i, key_name(k)))
w('default: return NULL; }}\n')
w('typedef enum { NORMAL, APPLICATION, EXTENDED } KeyboardMode;\n')
w('static inline const char*\nkey_lookup(uint8_t key, KeyboardMode mode, uint8_t mods, uint8_t action) {')
i = 1
def ind(*a):
w((' ' * i)[:-1], *a)
ind('switch(mode) {')
mmap = [(False, False), (True, False), (False, True)]
for (smkx, extended), mode in zip(mmap, 'NORMAL APPLICATION EXTENDED'.split()):
i += 1
ind('case {}:'.format(mode))
i += 1
ind('switch(action & 3) { case 3: return NULL;')
for action in (defines.GLFW_RELEASE, defines.GLFW_PRESS, defines.GLFW_REPEAT):
i += 1
ind('case {}: // {}'.format(action, 'RELEASE PRESS REPEAT'.split()[action]))
i += 1
if action != defines.GLFW_RELEASE or mode == 'EXTENDED':
ind('switch (mods & 0xf) {')
i += 1
for mods in range(16):
key_bytes = {}
for key in range(key_count):
glfw_key = key_rmap[key]
data = key_to_bytes(glfw_key, smkx, extended, mods, action)
if data:
key_bytes[key] = data, glfw_key
i += 1
ind('case 0x{:x}:'.format(mods))
i += 1
if key_bytes:
ind('switch(key & 0x7f) { default: return NULL;')
i += 1
for key, (data, glfw_key) in key_bytes.items():
ind('case {}: // {}'.format(key, key_name(keys[glfw_key])))
i += 1
items = bytearray(data)
items.insert(0, len(items))
ind('return "{}";'.format(''.join('\\x{:02x}'.format(x) for x in items)))
i -= 1
i -= 1
ind('} // end switch(key)')
else:
ind('return NULL;')
i -= 2
i -= 1
ind('} // end switch(mods)')
ind('break;\n')
i -= 1
else: else:
ind('return NULL;\n') w('%d, /* %s */' % (key_count, key_name(k)))
key_rmap.append(i)
key_count += 1
if key_count > 128:
raise OverflowError('Too many keys')
w('};\n')
w('static inline const char* key_name(int key) { switch(key) {')
for i in range(number_of_keys):
k = keys.get(i)
if k is not None:
w('case %d: return "%s";' % (i, key_name(k)))
w('default: return NULL; }}\n')
w('typedef enum { NORMAL, APPLICATION, EXTENDED } KeyboardMode;\n')
w('static inline const char*\nkey_lookup(uint8_t key, KeyboardMode mode, uint8_t mods, uint8_t action) {')
i = 1
def ind(*a):
w((' ' * i)[:-1], *a)
ind('switch(mode) {')
mmap = [(False, False), (True, False), (False, True)]
for (smkx, extended), mode in zip(mmap, 'NORMAL APPLICATION EXTENDED'.split()):
i += 1
ind('case {}:'.format(mode))
i += 1
ind('switch(action & 3) { case 3: return NULL;')
for action in (defines.GLFW_RELEASE, defines.GLFW_PRESS, defines.GLFW_REPEAT):
i += 1
ind('case {}: // {}'.format(action, 'RELEASE PRESS REPEAT'.split()[action]))
i += 1
if action != defines.GLFW_RELEASE or mode == 'EXTENDED':
ind('switch (mods & 0xf) {')
i += 1
for mods in range(16):
key_bytes = {}
for key in range(key_count):
glfw_key = key_rmap[key]
data = key_to_bytes(glfw_key, smkx, extended, mods, action)
if data:
key_bytes[key] = data, glfw_key
i += 1
ind('case 0x{:x}:'.format(mods))
i += 1
if key_bytes:
ind('switch(key & 0x7f) { default: return NULL;')
i += 1
for key, (data, glfw_key) in key_bytes.items():
ind('case {}: // {}'.format(key, key_name(keys[glfw_key])))
i += 1
items = bytearray(data)
items.insert(0, len(items))
ind('return "{}";'.format(''.join('\\x{:02x}'.format(x) for x in items)))
i -= 1
i -= 1
ind('} // end switch(key)')
else:
ind('return NULL;')
i -= 2
i -= 1
ind('} // end switch(mods)')
ind('break;\n')
i -= 1
else:
ind('return NULL;\n')
i -= 1
i -= 1 i -= 1
ind('}} // end switch(action) in mode {}'.format(mode))
ind('break;\n\n')
i -= 1 i -= 1
ind('}} // end switch(action) in mode {}'.format(mode))
ind('break;\n\n')
i -= 1 i -= 1
i -= 1 ind('}')
ind('}') ind('return NULL;')
ind('return NULL;') i -= 1
i -= 1 w('}')
w('}')

17
kitty/rgb.py generated
View File

@ -835,14 +835,15 @@ if __name__ == '__main__':
import sys import sys
import pprint import pprint
data = {} data = {}
for line in open(sys.argv[-1]): with open(sys.argv[-1]) as f:
line = line.strip() for line in f:
if not line or line.startswith('!'): line = line.strip()
continue if not line or line.startswith('!'):
parts = line.split() continue
r, g, b = map(int, parts[:3]) parts = line.split()
name = ' '.join(parts[3:]).lower() r, g, b = map(int, parts[:3])
data[name] = data[name.replace(' ', '')] = r, g, b name = ' '.join(parts[3:]).lower()
data[name] = data[name.replace(' ', '')] = r, g, b
data = pprint.pformat(data).replace('{', '{\n ').replace('(', 'Color(') data = pprint.pformat(data).replace('{', '{\n ').replace('(', 'Color(')
with open(__file__, 'r+') as src: with open(__file__, 'r+') as src:
raw = src.read() raw = src.read()

View File

@ -23,8 +23,10 @@ BASE = os.path.dirname(os.path.abspath(__file__))
def load_shaders(name): def load_shaders(name):
from .fast_data_types import GLSL_VERSION from .fast_data_types import GLSL_VERSION
vert = open(os.path.join(BASE, '{}_vertex.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) with open(os.path.join(BASE, '{}_vertex.glsl'.format(name))) as f:
frag = open(os.path.join(BASE, '{}_fragment.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) vert = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1)
with open(os.path.join(BASE, '{}_fragment.glsl'.format(name))) as f:
frag = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1)
return vert, frag return vert, frag

View File

@ -56,7 +56,8 @@ def main():
raise SystemExit('Must specify a PNG file to display') raise SystemExit('Must specify a PNG file to display')
clear_screen() clear_screen()
display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20) display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20)
display(open(os.path.join(base, '../logo/kitty.rgba'), 'rb').read(), 256, 256, 0, 5, -9) with open(os.path.join(base, '../logo/kitty.rgba'), 'rb') as f:
display(f.read(), 256, 256, 0, 5, -9)
display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3) display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3)
move_cursor(5, 8) move_cursor(5, 8)
print('kitty is \033[3m\033[32mawesome\033[m!') print('kitty is \033[3m\033[32mawesome\033[m!')

View File

@ -23,7 +23,8 @@ os.chdir(os.path.dirname(os.path.abspath(__file__)))
build_path = os.path.abspath('../build-kitty') build_path = os.path.abspath('../build-kitty')
docs_dir = os.path.abspath('docs') docs_dir = os.path.abspath('docs')
publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty')) publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty'))
raw = open('kitty/constants.py').read() with open('kitty/constants.py') as f:
raw = f.read()
nv = re.search( nv = re.search(
r'^version\s+=\s+\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE) r'^version\s+=\s+\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE)
version = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3)) version = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3))

View File

@ -315,7 +315,8 @@ def get_vcs_rev_defines():
with open('.git/refs/heads/master') as f: with open('.git/refs/heads/master') as f:
rev = f.read() rev = f.read()
except NotADirectoryError: except NotADirectoryError:
gitloc = open('.git').read() with open('.git') as f:
gitloc = f.read()
with open(os.path.join(gitloc, 'refs/heads/master')) as f: with open(os.path.join(gitloc, 'refs/heads/master')) as f:
rev = f.read() rev = f.read()
@ -343,7 +344,8 @@ def newer(dest, *sources):
def dependecies_for(src, obj, all_headers): def dependecies_for(src, obj, all_headers):
dep_file = obj.rpartition('.')[0] + '.d' dep_file = obj.rpartition('.')[0] + '.d'
try: try:
deps = open(dep_file).read() with open(dep_file) as f:
deps = f.read()
except FileNotFoundError: except FileNotFoundError:
yield src yield src
yield from iter(all_headers) yield from iter(all_headers)

View File

@ -46,7 +46,8 @@ def run(what):
raise SystemExit(ret.returncode) raise SystemExit(ret.returncode)
script = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
script = f.read().decode('utf-8')
script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1)
os.chdir(os.path.expanduser('~/work/build-kitty')) os.chdir(os.path.expanduser('~/work/build-kitty'))
with tempfile.NamedTemporaryFile(prefix='install-dmg-', suffix='.py') as f: with tempfile.NamedTemporaryFile(prefix='install-dmg-', suffix='.py') as f:

View File

@ -44,7 +44,8 @@ def run(what):
raise SystemExit(ret.returncode) raise SystemExit(ret.returncode)
script = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
script = f.read().decode('utf-8')
script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1)
os.chdir(os.path.expanduser('~/work/build-kitty')) os.chdir(os.path.expanduser('~/work/build-kitty'))
with tempfile.NamedTemporaryFile(prefix='install-tarball-', suffix='.py') as f: with tempfile.NamedTemporaryFile(prefix='install-tarball-', suffix='.py') as f: