-
Notifications
You must be signed in to change notification settings - Fork 0
/
save_ascii.py
59 lines (43 loc) · 1.65 KB
/
save_ascii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# encoding:utf-8
"""
DwLoadServer - A DWLOAD server written in Python
================================================
:created: 2014 by Jens Diemer - www.jensdiemer.de
:copyleft: 2014 by the DwLoadServer team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
import logging
from dragonlib.api import Dragon32API
from dwload_server import constants
from dwload_server.utils import hook_handler
from dwload_server.utils.file_tools import backup_rename
log = logging.getLogger(__name__)
@hook_handler.register_post_hook(constants.OP_WRITE)
def save_ascii_post_write_hook(server, filepath, lsn):
"""
Save a BASIC listing in "Dragon DOS Binary Format" in a ASCII file, too.
:param server: DwLoadServer() instance
:param filepath: current filepath of the written chunk
:param lsn: current "Logical Sector Number" (not really needed here)
:return: None
"""
log.critical("Hook info: Filepath %r LSN: %i", filepath, lsn)
# TODO: Optimize this:
with open(filepath, "rb") as f:
content = f.read()
if not content.endswith(b"\x00\x00\x00"):
log.info("File ends not with $00 $00 $00, ok.")
return
log.info("File end found. Parse binary...")
api = Dragon32API()
try:
ascii_listing = api.bin2bas(content)
except Exception as err:
log.error("Can't parse BASIC file: %s", err)
log.info("content: %s", repr(content))
return
bas_filepath = filepath + ".bas"
backup_rename(bas_filepath)
log.info("Create %r...", bas_filepath)
with open(bas_filepath, "w") as f:
f.write(ascii_listing)