-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
misc improvements #562
Merged
Merged
misc improvements #562
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
01fb8b3
misc improvements
cmkohnen 6356708
misc improvements
cmkohnen 54f0d32
implement file-like-wrapper
cmkohnen 444a2c3
improve wrapper
cmkohnen 3799d46
safen config migration
cmkohnen f3ffc8b
use context manager for file handling
cmkohnen 8580a5c
slighty improve columns parsing
cmkohnen b69c1a6
mimic builtin's open()
cmkohnen 598fbd5
use wrapper for writing as well
cmkohnen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,48 +1,125 @@ | ||
# SPDX-License-Identifier: GPL-3.0-or-later | ||
import io | ||
import json | ||
from xml.dom import minidom | ||
|
||
from gi.repository import GLib | ||
from gi.repository import GLib, Gio | ||
|
||
|
||
class FileLikeWrapper(io.BufferedIOBase): | ||
def __init__(self, read_stream=None, write_stream=None): | ||
self._read_stream, self._write_stream = read_stream, write_stream | ||
|
||
@classmethod | ||
def new_for_io_stream(cls, io_stream: Gio.IOStream): | ||
return cls( | ||
read_stream=io_stream.get_input_stream(), | ||
write_stream=io_stream.get_output_stream(), | ||
) | ||
|
||
@property | ||
def closed(self) -> bool: | ||
return self._read_stream is None and self._write_stream is None | ||
|
||
def close(self) -> None: | ||
if self._read_stream is not None: | ||
self._read_stream.close() | ||
self._read_stream = None | ||
if self._write_stream is not None: | ||
self._write_stream.close() | ||
self._write_stream = None | ||
|
||
def writable(self) -> bool: | ||
return self._write_stream is not None | ||
|
||
def write(self, b) -> int: | ||
if self._write_stream is None: | ||
raise OSError() | ||
elif b is None or b == b"": | ||
return 0 | ||
return self._write_stream.write_bytes(GLib.Bytes(b)) | ||
|
||
def readable(self) -> bool: | ||
return self._read_stream is not None | ||
|
||
def read(self, size=-1): | ||
if self._read_stream is None: | ||
raise OSError() | ||
elif size == 0: | ||
return b"" | ||
elif size > 0: | ||
return self._read_stream.read_bytes(size, None).get_data() | ||
buffer = io.BytesIO() | ||
while True: | ||
chunk = self._read_stream.read_bytes(4096, None) | ||
if chunk.get_size() == 0: | ||
break | ||
buffer.write(chunk.get_data()) | ||
return buffer.getvalue() | ||
|
||
read1 = read | ||
|
||
|
||
def open_wrapped(file: Gio.File, mode: str = "rt", encoding: str = "utf-8"): | ||
read = "r" in mode | ||
append = "a" in mode | ||
replace = "w" in mode | ||
|
||
def _create_stream(): | ||
if file.query_exists(None): | ||
file.delete(None) | ||
return file.create(0, None) | ||
|
||
def _io_stream(): | ||
return FileLikeWrapper.new_for_io_stream(file.open_readwrite(None)) | ||
|
||
if "x" in mode: | ||
if file.query_exists(): | ||
return OSError() | ||
stream = _create_stream() | ||
stream.close() | ||
if read and append: | ||
obj = _io_stream() | ||
elif read and replace: | ||
stream = _create_stream() | ||
stream.close() | ||
obj = _io_stream() | ||
elif read: | ||
obj = FileLikeWrapper(read_stream=file.read(None)) | ||
elif replace: | ||
obj = FileLikeWrapper(write_stream=_create_stream()) | ||
elif append: | ||
obj = FileLikeWrapper(write_stream=file.append(None)) | ||
|
||
if "b" not in mode: | ||
obj = io.TextIOWrapper(obj, encoding=encoding) | ||
return obj | ||
|
||
|
||
def save_item(file, item_): | ||
delimiter = "\t" | ||
fmt = delimiter.join(["%.12e"] * 2) | ||
stream = get_write_stream(file) | ||
xlabel, ylabel = item_.get_xlabel(), item_.get_ylabel() | ||
if xlabel != "" and ylabel != "": | ||
write_string(stream, xlabel + delimiter + ylabel + "\n") | ||
for values in zip(item_.xdata, item_.ydata): | ||
write_string(stream, fmt % values + "\n") | ||
stream.close() | ||
with open_wrapped(file, "wt") as wrapper: | ||
if xlabel != "" and ylabel != "": | ||
wrapper.write(xlabel + delimiter + ylabel + "\n") | ||
for values in zip(item_.xdata, item_.ydata): | ||
wrapper.write(fmt % values + "\n") | ||
|
||
|
||
def parse_json(file): | ||
return json.loads(file.load_bytes(None)[0].get_data()) | ||
with open_wrapped(file, "rb") as wrapper: | ||
return json.load(wrapper) | ||
|
||
|
||
def write_json(file, json_object, pretty_print=True): | ||
stream = get_write_stream(file) | ||
write_string(stream, json.dumps( | ||
json_object, indent=4 if pretty_print else None, sort_keys=True, | ||
)) | ||
stream.close() | ||
with open_wrapped(file, "wt") as wrapper: | ||
json.dump( | ||
json_object, wrapper, | ||
indent=4 if pretty_print else None, sort_keys=True, | ||
) | ||
|
||
|
||
def parse_xml(file): | ||
return minidom.parseString(read_file(file)) | ||
|
||
|
||
def get_write_stream(file): | ||
if file.query_exists(None): | ||
file.delete(None) | ||
return file.create(0, None) | ||
|
||
|
||
def write_string(stream, line, encoding="utf-8"): | ||
stream.write_bytes(GLib.Bytes(line.encode(encoding)), None) | ||
|
||
|
||
def read_file(file, encoding="utf-8"): | ||
content = file.load_bytes(None)[0].get_data() | ||
return content if encoding is None else content.decode(encoding) | ||
with open_wrapped(file, "rb") as wrapper: | ||
return minidom.parse(wrapper) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've actually been working a lot with custom constructors at work, where I've been using class methods for the exact same purpose. Seems the better way to me, yes. Also coincidentally reminds me on what I've been working on at work.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The main reason, was that classmethods can be inherited. Say we introduce
DataItemButWithInternalHistory
which doesn't need its own new method, since it has no new properties to render. using the staticmethod we would only get aDataItem
whereas a classmethod will indeed get the correct type.